Skip to content

feat(bin): sync upstream herdr backend fixes, session-start digest, and stow skill - #4

Merged
korallis merged 11 commits into
mainfrom
fm/firstmate-upstream-sync
Jul 3, 2026
Merged

korallis merged 11 commits into
mainfrom
fm/firstmate-upstream-sync

Conversation

@korallis

@korallis korallis commented Jul 3, 2026 •

Copy link
Copy Markdown
Owner

Intent

Sync this fork (korallis/firstmate) with its upstream template (kunchenguid/firstmate), which had diverged by 8 commits: Herdr backend fixes (default-tab pruning safety, workspace reuse instead of leaking one per spawn, idle crew state corroboration, per-home secondmate workspaces, workspace label rename, smoke-test cleanup safety), a new unified session-start digest feature (bin/fm-session-start.sh composing lock+bootstrap+wake-drain into one report), and a new /stow skill for capturing operational memory before context resets. This fork's own 3 unique commits (README rebuild, a gitignore fix, a scout-report-verification feature) are unaffected - this is a routine merge to pull upstream improvements in, not a change to fork-specific behavior. Verified via merge-tree that origin/main and upstream/main merge cleanly with zero conflicts at the base commit; in practice one conflict appeared in README.md because both sides had independently touched the same 'How It Works' section (this fork's README was rebuilt into a 'why/what's-different/how-to' structure in a commit that landed after the merge-tree check ran, while upstream made small wording/factual updates to the old prose in that same section for its new features). I resolved it by keeping this fork's restructured README (heading-only 'How it works' / 'The lifecycle of a request', since the detailed mechanics already live in docs/architecture.md which merged cleanly and already has the correct, up-to-date wording), while folding upstream's two real behavior-level facts into the fork's condensed prose: the herdr backend's per-home workspace switching (primary uses 'firstmate', each secondmate uses '2ndmate-') into the Install section's herdr sentence, and the upstream-inserted /stow row in the Built-in skills table (which merged in without conflict). No other files conflicted; AGENTS.md, bin/fm-bootstrap.sh, bin/fm-spawn.sh, and all other overlapping files auto-merged cleanly. I intentionally did not touch, comment on, or modify the existing open upstream-contribution PR kunchenguid#216 (korallis:main -> kunchenguid/main) - that's a separate, human-owned concern. Verified with the full local test suite (all 34 tests/*.test.sh files pass) before starting this pipeline run.

What Changed

  • Merged upstream template updates: Herdr backend fixes (safe default-tab pruning, workspace reuse instead of leaking one per spawn, per-home secondmate workspaces with renamed labels, idle crew-state corroboration, and safer smoke-test cleanup), plus a follow-up fix routing fm_backend_target_exists's herdr check through fm_backend_herdr_cli so it honors the requested herdr session reliably.
  • Added bin/fm-session-start.sh, a unified session-start digest that composes the session lock, bootstrap diagnostics, and wake-queue drain into a single ordered report, with matching updates to bin/fm-bootstrap.sh, bin/fm-guard.sh, bin/fm-spawn.sh, and bin/fm-crew-state.sh.
  • Added the /stow skill for capturing operational memory before context resets, and expanded docs (AGENTS.md, CONTRIBUTING.md, README.md, docs/architecture.md, docs/configuration.md, docs/herdr-backend.md, docs/scripts.md) and test coverage across the herdr backend, session-start, and tangle-guard paths.

Risk Assessment

✅ Low: This is a routine fast-forward-clean merge of already-tested, well-documented upstream commits (herdr backend fixes, session-start digest, /stow skill) plus one small fork-authored fix; the only issue found in round 1 (an unrouted HERDR_SESSION call bypassing the --session CLI flag workaround) has been correctly applied, no other call sites were missed, and the sole merge conflict (README.md) was resolved correctly with no lost content or stray markers.

Testing

The pre-supplied baseline test command (all tests/*.test.sh) already passed before I started; I re-ran the full 34-file suite myself after adding a new unit test that specifically targets the last commit's fix (bin/fm-backend.sh's herdr branch of fm_backend_target_exists now routing through fm_backend_herdr_cli's --session flag instead of a bare HERDR_SESSION call), and proved that test is a real regression guard by reverting the fix in place, watching the new test fail with the exact missing-flag diagnostic, then restoring the fix and confirming all 34 test files (including the new test) pass. I also spot-checked that the README/docs merge-conflict resolution described in the user intent actually landed the claimed content. No functional or test failures found; only change to the working tree is the new regression test in tests/fm-backend.test.sh.

Evidence: Full 34-file test suite run (post-fix, with new regression test included)
== tests/fm-afk-inject-e2e.test.sh OK (3 ok) ==
== tests/fm-backend-autodetect-smoke.test.sh OK (4 ok) ==
== tests/fm-backend-herdr-prune-safety-e2e.test.sh OK (6 ok) ==
== tests/fm-backend-herdr-smoke.test.sh OK (15 ok) ==
== tests/fm-backend-herdr-workspace-per-home-e2e.test.sh OK (10 ok) ==
== tests/fm-backend-herdr.test.sh OK (43 ok) ==
== tests/fm-backend-tmux-smoke.test.sh OK (7 ok) ==
== tests/fm-backend.test.sh OK (18 ok) ==
== tests/fm-bootstrap.test.sh OK (4 ok) ==
== tests/fm-composer-ghost.test.sh OK (9 ok) ==
== tests/fm-crew-state.test.sh OK (25 ok) ==
== tests/fm-daemon.test.sh OK (43 ok) ==
== tests/fm-fleet-sync.test.sh OK (12 ok) ==
== tests/fm-gotmp.test.sh OK (4 ok) ==
== tests/fm-grok-harness.test.sh OK (3 ok) ==
== tests/fm-pr-merge.test.sh OK (10 ok) ==
== tests/fm-secondmate-harness.test.sh OK (24 ok) ==
== tests/fm-secondmate-lifecycle-e2e.test.sh OK (6 ok) ==
== tests/fm-secondmate-safety.test.sh OK (49 ok) ==
== tests/fm-secondmate-sync.test.sh OK (11 ok) ==
== tests/fm-send-popup-settle.test.sh OK (7 ok) ==
== tests/fm-send-secondmate-marker.test.sh OK (5 ok) ==
== tests/fm-send-settle.test.sh OK (4 ok) ==
== tests/fm-session-start.test.sh OK (11 ok) ==
== tests/fm-spawn-batch.test.sh OK (3 ok) ==
== tests/fm-spawn-dispatch-profile.test.sh OK (15 ok) ==
== tests/fm-tangle-guard.test.sh OK (5 ok) ==
== tests/fm-teardown.test.sh OK (19 ok) ==
== tests/fm-update.test.sh OK (9 ok) ==
== tests/fm-wake-daemon-lifecycle-e2e.test.sh OK (2 ok) ==
== tests/fm-wake-queue.test.sh OK (8 ok) ==
== tests/fm-watch-triage.test.sh OK (20 ok) ==
== tests/fm-watcher-lock.test.sh OK (20 ok) ==
== tests/fm-x-mode.test.sh OK (63 ok) ==
RC=0
Evidence: Before/after proof that the new test catches the c89bd43 herdr --session-flag regression
Demonstration that the new test tests/fm-backend.test.sh::test_target_exists_herdr_routes_through_cli_session_flag
actually catches the bug fixed in commit c89bd43 (fm_backend_target_exists herdr case not passing --session flag).

1) Against target commit c89bd43 (fixed code, calls fm_backend_herdr_cli):
   $ bash tests/fm-backend.test.sh
   ok - fm_backend_target_exists: herdr case routes through fm_backend_herdr_cli's --session flag and reports live/dead panes correctly

2) Against the pre-fix code (bare `HERDR_SESSION="$session" herdr pane get "$pane"`, reverted in-place for this check only, then restored):
   $ bash tests/fm-backend.test.sh
   not ok - fm_backend_target_exists's herdr case did not append a trailing --session <name> flag
     (must route through fm_backend_herdr_cli, not a bare HERDR_SESSION call)
     (missing: 'panegetp-live--sessionsess-a')
   --- output ---
   HERDR_SESSION=sess-apanegetp-live

This confirms the fix in bin/fm-backend.sh (routing fm_backend_target_exists's herdr branch through
fm_backend_herdr_cli, which appends a trailing `--session <name>` flag) is both real and now covered by a
regression test - closing a gap where no existing test distinguished the old (buggy, env-var-only) call
from the new (fixed, --session-flag) call for this specific call site. This mirrors the documented,
previously-production-incident-causing bug described in bin/backends/herdr.sh and tests/herdr-test-safety.sh:
HERDR_SESSION alone is not reliably honored by the installed herdr 0.7.1 client once another herdr server is
already bound on the machine.

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 1 issue found → auto-fixed ✅
  • ⚠️ bin/fm-backend.sh:325 - fm_backend_target_exists()'s herdr branch calls HERDR_SESSION=&#34;$session&#34; herdr pane get &#34;$pane&#34; directly instead of routing through fm_backend_herdr_cli (bin/backends/herdr.sh:97), which sets both the env var AND a trailing --session &lt;name&gt; CLI flag. Every other herdr call site in the codebase was switched to fm_backend_herdr_cli specifically because herdr 0.7.1 does not reliably honor HERDR_SESSION alone once any other herdr server is already running on the machine - queries silently fall back to whichever server IS running instead of the requested one (documented at bin/backends/herdr.sh:82-96). This function was added in the same commit family (feat(bin): add unified session start digest kunchenguid/firstmate#201, session-start digest) that relies on this fix elsewhere, but missed applying it here.

🔧 Fix: fix(backends): route fm_backend_target_exists herdr check through fm_backend_herdr_cli
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • command -v tmux >/dev/null || { echo "tmux is required for e2e tests" >&2; exit 1; }; tmux -V; rc=0; for t in tests/*.test.sh; do echo "== $t =="; bash "$t" || rc=1; done; exit "$rc"
  • bash tests/fm-backend.test.sh (18 assertions, including a new test_target_exists_herdr_routes_through_cli_session_flag)
  • Full suite: for t in tests/*.test.sh; do bash &#34;$t&#34;; done — all 34 files pass (RC=0)
  • Manual regression proof: reverted bin/fm-backend.sh's fm_backend_target_exists herdr branch to the pre-fix bare HERDR_SESSION=... herdr pane get call, reran tests/fm-backend.test.sh, confirmed the new test fails with the expected missing --session flag, then restored the fixed code and reconfirmed it passes
  • grep verification that README.md and docs/architecture.md contain the two upstream facts the merge commit message claims were folded into the restructured README ('How it works' section, /stow skill table row, per-home herdr workspace label sentence)
  • ls tests/*.test.sh | wc -l confirms 34 test files, matching the stated pre-pipeline test count
  • git status --short confirms the working tree is clean apart from the intentionally added test
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

Summary by CodeRabbit

  • New Features

    • Added a new /stow command to capture durable session knowledge, route it to the right place, and surface whether the session is safe to reset.
    • Added a new session-start digest that summarises context, fleet state, and next steps in one place.
    • Improved herdr support so workspaces can be scoped per home, including secondmate launches.
  • Bug Fixes

    • Made busy-state detection more reliable across backends.
    • Safer handling for read-only and detect-only modes, reducing accidental changes during recovery or checks.
  • Documentation

    • Updated setup and workflow docs to reflect the new session, workspace, and X-mode behaviour.

kunchenguid and others added 11 commits July 2, 2026 14:16
* feat(stow): add operational-memory learnings convention and /stow skill

Add data/learnings.md as the fleet-local operational-learnings home,
a knowledge-routing table in AGENTS.md, and a user-invocable /stow
skill that sweeps a session for uncaptured durable knowledge and
files it to the right disk home before a reset.

* no-mistakes(review): Fix stow backlog note command

* no-mistakes(document): Document stow memory routing
…nguid#199)

* fix(tests): stop real-herdr smoke tests from ever killing the default session

Both fm-backend-herdr-smoke.test.sh and fm-backend-autodetect-smoke.test.sh
tore down their isolated throwaway HERDR_SESSION via a bare/inline-prefixed
`herdr server stop`, which is unscoped and resolves ambiently. On this herdr
client, that ambient resolution silently falls back to whatever server is
already running instead of the requested session - it killed the captain's
live default herdr server twice in production (2026-07-02), once from each
smoke test's cleanup trap.

Add tests/herdr-test-safety.sh with herdr_safe_stop_and_delete: it uses the
explicit-by-name `herdr session stop/delete <name>` form (never the ambient
`server stop`) and, before that, a read-only hard guard
(herdr_refuse_if_default) that re-queries `herdr session list --json` and
refuses outright if the target is literally "default", not found, or flagged
default:true. Fails closed on any ambiguity. Verified empirically against a
real isolated session: refuses on default/nonexistent/empty names without
ever calling stop, and correctly tears down a genuine isolated session while
leaving the default session's workspace state byte-identical before and
after.

* no-mistakes(review): guard herdr delete with fresh check

* no-mistakes(document): Document herdr smoke cleanup safety
…uid#200)

* feat(bin): give each secondmate its own labeled herdr workspace

Give each secondmate its own labeled herdr workspace, and land crewmates
spawned from a secondmate home in that secondmate's own space, instead of
every firstmate home (primary and all secondmates) sharing one "firstmate"
workspace.

bin/backends/herdr.sh: replace the constant FM_BACKEND_HERDR_WORKSPACE_LABEL
with fm_backend_herdr_workspace_label(), resolved fresh from FM_HOME on every
call. The primary (no .fm-secondmate-home marker) still resolves to
"firstmate" - byte-identical to every pre-existing task's recorded label, no
forced migration. A secondmate home resolves to "firstmate-<secondmate-id>".
Every workspace-scoped path (find/ensure, tab create + duplicate check,
list-live recovery, pane-for-tab) uses this same resolution, so recovery and
duplicate checks stay scoped to each home's own space. Workspace and tab
create now pass --no-focus unconditionally (verified: neither focuses by
default once a workspace exists; --no-focus is defense in depth against the
one bootstrap edge case where the very first workspace in a session auto-
focuses).

Also fixes a session-targeting bug found while verifying this empirically:
HERDR_SESSION (env var, exported or inline-prefixed) is not reliably honored
by herdr 0.7.1 CLI subcommands once another herdr server is already running -
it silently falls back to whatever server IS running. fm_backend_herdr_cli
wraps every herdr invocation with both HERDR_SESSION and a trailing
--session <name> flag (verified to route correctly in every case tried),
fixing this for the whole adapter, not just the new label-scoped calls.

bin/fm-spawn.sh: a --secondmate spawn is launched BY the primary's own
process, whose FM_HOME still names the primary at that point. The herdr case
arm now shadows FM_HOME to the secondmate's own home (PROJ_ABS) for just the
two calls that resolve/create the workspace and tab, restored automatically
afterward (bash's temporary-assignment-before-a-command form works for shell
functions too). A crewmate/scout spawned FROM a secondmate's own fm-spawn.sh
process needs no such glue - its own FM_HOME already names it.

Tests: extended tests/fm-backend-herdr.test.sh (per-home label resolution,
--no-focus, --session flag, workspace-find/list-live scoping) and
tests/fm-backend-herdr-smoke.test.sh (a secondmate-shaped home's workspace
label, list-live scoping, restart stability in the multi-workspace shape).
Added tests/fm-backend-herdr-workspace-per-home-e2e.test.sh: the mandatory
isolated E2E, driving real bin/fm-spawn.sh/fm-teardown.sh - a primary-shaped
home into "firstmate", a --secondmate spawn into its own labeled space, a
crewmate spawned FROM that secondmate-shaped home landing in the same space
(this exact path had never run before), teardown closing only the right tab,
and list-live recovery seeing only each home's own tabs. All ten assertions
passed on the real binary; the default herdr session's own workspace state
was confirmed byte-identical before and after every real-herdr test run in
this change.

docs/herdr-backend.md: rewrote "Task container shape" for the workspace-per-
home design (label derivation, the --secondmate FM_HOME-shadow wrinkle, focus
behavior, label-collision/adopt-don't-duplicate semantics, no-forced-
migration), added "Session targeting: the --session flag, not HERDR_SESSION
alone", extended "ID stability" to the multi-workspace shape, and documented
the new E2E test.

* no-mistakes(review): Clarify herdr focus docs

* no-mistakes(review): Captain, clarify herdr server session docs

* no-mistakes(document): Document herdr per-home spaces
)

* Rename herdr secondmate workspace prefix to 2ndmate-

The primary home keeps the firstmate label; secondmate homes now
resolve to 2ndmate-<id> so the herdr spaces sidebar is unambiguous.
Tests and docs updated; pre-rename workspaces can be aligned with
herdr workspace rename.

* no-mistakes(review): Clarify herdr workspace migration behavior

* no-mistakes(document): Herdr docs label alignment
* feat(bin): collapse session start into one command

Add bin/fm-session-start.sh, composing fm-lock.sh, fm-bootstrap.sh, and
fm-wake-drain.sh into one ordered digest (lock, bootstrap diagnostics,
wake queue, context files, fleet state) instead of six-plus separate
turns. Lock now runs before bootstrap's mutating sweeps, closing a race
where a second concurrent session could mutate shared state before
discovering the lock was held. A lock refusal prints a loud read-only
banner, skips every mutating step via a new opt-in
FM_BOOTSTRAP_DETECT_ONLY flag on fm-bootstrap.sh, and still completes
the read-only-safe digest.

Add fm_backend_target_exists to fm-backend.sh as a shared, read-only,
never-side-effecting per-task endpoint-liveness primitive for both the
tmux and herdr backends.

Rewrite AGENTS.md sections 3 and 5 around the single command and add
tests/fm-session-start.test.sh.

* no-mistakes(review): Harden session-start read-only guidance

* no-mistakes(review): Suppress read-only tangle repair guidance

* no-mistakes(review): Include orphan status logs

* no-mistakes(review): Captain: make session-start test executable

* no-mistakes(review): Captain: clarify status tail guidance

* no-mistakes(document): Sync session-start docs

* no-mistakes(lint): Shell lint clean

* fix(tests): avoid shellcheck boolean chain
* fix(bin): corroborate herdr idle agent_status with the pane's own text

crew_pane_is_busy trusted a bare `idle` verdict from herdr's agent.get
outright, skipping the tail-regex corroboration unknown already gets.
agent.get reports generation state only (working while the model streams
a turn), so it reads idle for a crew blocked on its own long foreground
no-mistakes run - even though the pane still shows the busy banner the
whole time. Combined with the no-mistakes CLI's 10-run attribution cap,
this made a genuinely working herdr crew read as not provably working,
triggering an immediate stale wake instead of absorb-then-escalate.

* no-mistakes(document): Align herdr busy-state docs
… one per spawn (kunchenguid#202)

* fix(backends): reuse the herdr firstmate workspace instead of leaking one per spawn

Every herdr-backed crewmate left an orphaned `firstmate`-labelled workspace
behind, one per task, because `fm_backend_herdr_workspace_find` never matched
the existing workspace: its jq filter used `--arg label ... $label`, and
`label` is a reserved keyword in jq (label/break), so the filter was a compile
error. The error was swallowed by `2>/dev/null`, the find returned empty on
every call, and `workspace_ensure` took the create path each spawn, minting a
fresh workspace. The same collision silently disabled the create-task
duplicate-label check and the bare-selector tab lookup.

Rename the jq variable to `$want` in all three affected filters so reuse,
duplicate detection, and bare-selector lookup work. With reuse restored the
single `firstmate` workspace is persistent (like tmux's session) and teardown
correctly leaves it in place, closing only the task's pane/tab.

Also prune the default tab (label "1") herdr auto-creates inside a freshly
created workspace, best-effort, so the workspace holds only real task tabs.

Add stateful-fake-CLI tests that replay repeated spawn/teardown cycles and
assert one reused workspace, zero orphans, the default tab pruned, and
`workspace create` invoked exactly once. Verified against the real herdr binary
too: the pre-fix code failed the smoke idempotency check (minted wE then wF in
an isolated session); the fix passes it.

Document the workspace lifecycle, the jq-keyword pitfall, the default-tab
prune, and the project-labelled-workspace anomaly (not adapter-created) in
docs/herdr-backend.md.

* docs(herdr): trim workspace-lifecycle addition to current-state facts

The docs/herdr-backend.md convention documents current behavior, not
history - narrative belongs in the PR/commit message. Tightened the
workspace-leak and default-tab-prune write-up down to the operative
facts (the jq reserved-keyword guard, when pruning is safe, and the
persistence caveat), and corrected the CLI-facts table rows to match
the corrected prune timing.

* fix(backends): defer herdr default-tab prune until a real task tab exists

Closing a workspace's LAST tab deletes the whole workspace on real
herdr (verified). Pruning the auto-created default tab right after
workspace create closed the workspace's only tab at that point,
destroying the just-created workspace on every single spawn instead of
reusing it - the fake-CLI unit tests didn't model this real-herdr
behavior, so they passed while the real-herdr smoke test failed with
"container_ensure is not idempotent".

Move the prune into fm_backend_herdr_create_task, right after the
first real task tab is added to a freshly created workspace, when
closing the default tab alongside it is safe. Update the fake-CLI unit
test to match the corrected timing.

Also fix a smoke-test-only bug this surfaced: the test's second
create_task call reused a $CONTAINER captured before the first task
was killed, rather than re-running container_ensure like real
fm-spawn.sh always does immediately before every create_task call - so
once the workspace (correctly) disappeared after its last tab closed,
the stale reference no longer named a live workspace.

* test(backends): guard against jq --arg names colliding with jq keywords

Regression guard for the workspace-leak bug this PR fixes: a jq
--arg/--argjson variable named after a jq reserved keyword (e.g.
label) is a compile error on jq <= 1.6, and this adapter's
2>/dev/null silently turns that into an empty result instead of a
visible failure. Greps bin/ for the pattern so a future violation
fails loudly here instead of silently misbehaving on an older jq.

* docs(herdr): fix per-home staleness and drop contributor-specific example

The workspace-lifecycle write-up hardcoded "the firstmate workspace"
as if the label were always the fixed constant, stale against the
per-home labeling documented earlier in this file (primary: firstmate,
secondmate: 2ndmate-<id>). Rephrased per-home throughout, and pointed
the "workspace this adapter did not derive" case at the existing
Label-derivation section instead of a separate anomaly writeup.

Dropped the "Anomaly: a workspace labelled with a project name"
section - the python-teslemetry-stream example was a contributor's own
environment, not current adapter fact, and it repeated a now-incorrect
FM_BACKEND_HERDR_WORKSPACE_LABEL constant claim. Replaced with one
generic sentence already covered by the corrected wording above.

Also fixed the jq-reserved-keyword guard test's file reference, which
named tests/fm-backend.test.sh when the test actually lives in
tests/fm-backend-herdr.test.sh.

---------

Co-authored-by: kunchenguid <kun@kunchenguid.com>
* fix(backends): make the herdr default-tab prune provably safe

The default-tab prune could close a pane holding a LIVE agent: an
ADOPTED workspace (found pre-existing by label match) was pruned using
the same tab-count/label heuristic as a freshly created one, and herdr
derives a workspace's displayed label from its cwd basename when no
explicit --label is given. A captain launching herdr directly inside a
directory named "firstmate" produces a workspace that looks identical,
by label alone, to firstmate's own container - so the very next spawn
adopted the captain's own live workspace and closed their live pane
27ms after creating its task tab (2026-07-02 incident).

The fix is structural: fm_backend_herdr_workspace_ensure now captures
the seeded default tab's id straight from its own `workspace create`
response, only when it just created the workspace. That id threads
through fm_backend_herdr_container_ensure to fm_backend_herdr_create_task,
which is the only function allowed to prune it - an adopted workspace's
caller always passes an empty seeded-tab-id, so create_task never
re-derives "prunable" from a tab's label or count. Defense in depth:
the prune also refuses a tab whose pane reports a working agent.

Covered by new unit tests (adopted-never-prunes, created-prunes-exactly,
the exact label-collision incident shape) and a new isolated real-herdr
E2E test that reproduces the incident against the pre-fix code and shows
it fixed, plus the normal happy path.

* no-mistakes(document): Sync herdr prune docs

* no-mistakes: apply CI fixes
@coderabbitai

coderabbitai Bot commented Jul 3, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds bin/fm-session-start.sh as a single composite session digest command, reworks the herdr backend into a per-FM_HOME workspace model with seeded-default-tab pruning safety, adds read-only/detect-only modes to fm-guard.sh/fm-bootstrap.sh, adjusts crew-state busy corroboration, adds a /stow skill, updates docs, and adds extensive tests.

Changes

Session-start digest, herdr workspace-per-home, and supporting docs/tests

Layer / File(s) Summary
Session-start digest entrypoint
bin/fm-session-start.sh, tests/fm-session-start.test.sh
New composite script orchestrates lock/bootstrap/wake-drain, prints CONTEXT, FLEET STATE, and NEXT STEP digest sections, with full integration test coverage.
Read-only/detect-only guard and bootstrap modes
bin/fm-guard.sh, bin/fm-bootstrap.sh, tests/fm-tangle-guard.test.sh
Adds FM_GUARD_READ_ONLY and FM_BOOTSTRAP_DETECT_ONLY toggles suppressing mutating actions while retaining diagnostic banners; tests verify both modes.
Crew-state busy corroboration
bin/fm-crew-state.sh, bin/fm-backend.sh, tests/fm-crew-state.test.sh
Removes the early idle short-circuit so busy detection always corroborates against captured pane text; comment contract updated accordingly.
Herdr backend workspace-per-home rework
bin/backends/herdr.sh
Derives workspace labels from FM_HOME/.fm-secondmate-home, adds scoped fm_backend_herdr_cli() with --session, and introduces seeded-default-tab pruning safety logic across container/task lifecycle functions.
Spawn wiring and target-exists probe
bin/fm-spawn.sh, bin/fm-backend.sh, tests/fm-backend.test.sh
Passes seeded-tab id through spawn to create_task, overrides FM_HOME for secondmate spawns, and adds fm_backend_target_exists for read-only liveness checks.
Herdr unit/E2E test coverage
tests/fm-backend-herdr*.test.sh, tests/fm-backend-autodetect-smoke.test.sh, tests/herdr-test-safety.sh
Adds a stateful herdr fake, workspace-label/CLI-routing/pruning unit tests, new smoke/E2E scripts, and a shared guarded teardown safety helper.
Documentation and skills updates
AGENTS.md, .agents/skills/*, README.md, CONTRIBUTING.md, docs/*
Updates session-start/recovery/knowledge-routing guidance, adds /stow skill, and revises architecture/configuration/herdr-backend/scripts docs to match new behaviours.

Estimated code review effort: 4 (Complex) | ~75 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Operator
  participant SessionStart as fm-session-start.sh
  participant Lock as fm-lock.sh
  participant Bootstrap as fm-bootstrap.sh
  participant WakeDrain as fm-wake-drain.sh
  participant Guard as fm-guard.sh
  Operator->>SessionStart: run session start
  SessionStart->>Lock: acquire fleet lock
  Lock-->>SessionStart: granted or refused
  alt lock granted
    SessionStart->>Bootstrap: run normal bootstrap
    SessionStart->>WakeDrain: drain wake queue
  else lock refused
    SessionStart->>Bootstrap: run with FM_BOOTSTRAP_DETECT_ONLY=1
    SessionStart->>Guard: run with FM_GUARD_READ_ONLY=1
  end
  SessionStart-->>Operator: print CONTEXT, FLEET STATE, NEXT STEP digest
Loading
sequenceDiagram
  participant Spawn as fm-spawn.sh
  participant Adapter as herdr.sh
  participant CLI as fm_backend_herdr_cli
  participant Herdr as herdr server
  Spawn->>Adapter: fm_backend_herdr_container_ensure(FM_HOME)
  Adapter->>CLI: workspace create/find --session
  CLI->>Herdr: herdr workspace ...
  Herdr-->>Adapter: workspace_id + seeded_default_tab_id
  Adapter-->>Spawn: session:workspace_id\tseeded_tab_id
  Spawn->>Adapter: fm_backend_herdr_create_task(seeded_tab_id)
  Adapter->>CLI: tab create --no-focus
  alt seeded_tab_id non-empty
    Adapter->>CLI: pane close (prune seeded default tab)
  end
Loading

Poem

A rabbit hopped through session logs so long,
Found each home its own workspace, right or wrong,
Pruned the seeded tab with careful paw,
Read-only guards now follow every law,
Thump thump! Ship it — the digest sings its song. 🐇📜

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly reflects the main changes: Herdr backend fixes, the session-start digest, and the new /stow skill.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fm/firstmate-upstream-sync

Comment @coderabbitai help to get the list of available commands.

@korallis
korallis merged commit a4f2b4d into main Jul 3, 2026
1 check was pending

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
docs/herdr-backend.md (1)

209-222: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Make --session the explicit contract here.

HERDR_SESSION is still described as the normal selector, but the safety notes below say the env var alone is not reliable. Tighten this so the wrapper's --session flag is the actual contract and HERDR_SESSION is only an implementation detail; otherwise manual CLI use can drift back to the unsafe path the cleanup bug exposed.

As per the provided line-range notes, this section is documenting the Herdr session-targeting wrapper contract. source_other

Suggested rewording
- `HERDR_SESSION=<name>` is the adapter's normal way to select a named herdr session for NON-destructive operations: start, workspace, tab, pane, capture, send, and busy-state calls all still use it (via fm_backend_herdr_cli, below).
+ `fm_backend_herdr_cli` always appends `--session <name>` for non-destructive calls; `HERDR_SESSION=<name>` is only an implementation detail used by the wrapper, not the targeting mechanism itself.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/herdr-backend.md` around lines 209 - 222, Clarify the Herdr
session-targeting contract so `--session` is the explicit, required selector and
`HERDR_SESSION` is only an internal/compatibility detail. Update the wording in
this section to make `fm_backend_herdr_cli` the source of truth, state that all
adapter calls are scoped via the trailing `--session <name>`, and avoid
describing the env var as the normal external control path. Keep the
destructive-cleanup guidance aligned with `herdr_safe_stop_and_delete`,
`herdr_refuse_if_default`, and `herdr session stop/delete` as the only safe
named-session forms.
tests/fm-session-start.test.sh (1)

79-81: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Unclear/dead line in make_fake_toolchain.

printf '%s\n' manual > "${fakebin%/*}/home-placeholder" 2>/dev/null || true doesn't correspond to any fixture consumed elsewhere in this file and its failure is silently swallowed. This looks like a stray debug artifact left in the fixture.

🧹 Proposed cleanup
   chmod +x "$fakebin/no-mistakes"
-  printf '%s\n' manual > "${fakebin%/*}/home-placeholder" 2>/dev/null || true
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/fm-session-start.test.sh` around lines 79 - 81, The
`make_fake_toolchain` fixture contains a stray unused debug artifact: the
`printf '%s\n' manual > "${fakebin%/*}/home-placeholder" 2>/dev/null || true`
line is not consumed anywhere and its failure is hidden. Remove that line from
`make_fake_toolchain` and keep the fixture focused on the toolchain files
actually used by the `fm-session-start` test.
bin/fm-bootstrap.sh (1)

408-412: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Truthy-value parsing differs from FM_GUARD_READ_ONLY.

FM_BOOTSTRAP_DETECT_ONLY only matches the literal 1 ([ "${FM_BOOTSTRAP_DETECT_ONLY:-0}" = 1 ]), whereas bin/fm-guard.sh's sibling FM_GUARD_READ_ONLY flag normalises 1|true|TRUE|yes|YES. Not a functional bug today (only ever set to 1 by fm-session-start.sh), but the two flags implement the same "read-only/detect-only" concept inconsistently, which is a minor foot-gun for future callers.

Also applies to: 425-429

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@bin/fm-bootstrap.sh` around lines 408 - 412, FM_BOOTSTRAP_DETECT_ONLY is
parsed more narrowly than the matching read-only flag logic used elsewhere, so
align the truthy-value handling in the fm-bootstrap.sh branch that checks
FM_BOOTSTRAP_DETECT_ONLY with the normalization used by FM_GUARD_READ_ONLY in
fm-guard.sh. Update the detect-only condition and the related echo paths in the
bootstrap flow so they accept the same truthy forms consistently, using the
existing feature-flag handling as the reference point.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/fm-backend-herdr.test.sh`:
- Around line 925-933: The jq reserved-keyword guard in
test_no_jq_reserved_keyword_arg_names() uses a GNU-only word boundary in the
grep pattern, so on BSD/macOS it can miss matches; update the grep ERE to use a
portable POSIX end-of-token boundary such as whitespace-or-end-of-line, while
keeping the reserved keyword list and the test_no_jq_reserved_keyword_arg_names
symbol intact.

---

Nitpick comments:
In `@bin/fm-bootstrap.sh`:
- Around line 408-412: FM_BOOTSTRAP_DETECT_ONLY is parsed more narrowly than the
matching read-only flag logic used elsewhere, so align the truthy-value handling
in the fm-bootstrap.sh branch that checks FM_BOOTSTRAP_DETECT_ONLY with the
normalization used by FM_GUARD_READ_ONLY in fm-guard.sh. Update the detect-only
condition and the related echo paths in the bootstrap flow so they accept the
same truthy forms consistently, using the existing feature-flag handling as the
reference point.

In `@docs/herdr-backend.md`:
- Around line 209-222: Clarify the Herdr session-targeting contract so
`--session` is the explicit, required selector and `HERDR_SESSION` is only an
internal/compatibility detail. Update the wording in this section to make
`fm_backend_herdr_cli` the source of truth, state that all adapter calls are
scoped via the trailing `--session <name>`, and avoid describing the env var as
the normal external control path. Keep the destructive-cleanup guidance aligned
with `herdr_safe_stop_and_delete`, `herdr_refuse_if_default`, and `herdr session
stop/delete` as the only safe named-session forms.

In `@tests/fm-session-start.test.sh`:
- Around line 79-81: The `make_fake_toolchain` fixture contains a stray unused
debug artifact: the `printf '%s\n' manual > "${fakebin%/*}/home-placeholder"
2>/dev/null || true` line is not consumed anywhere and its failure is hidden.
Remove that line from `make_fake_toolchain` and keep the fixture focused on the
toolchain files actually used by the `fm-session-start` test.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a30b847f-990f-4704-b033-c9c239916234

📥 Commits

Reviewing files that changed from the base of the PR and between 7c60be5 and b95002c.

📒 Files selected for processing (28)
  • .agents/skills/fmx-respond/SKILL.md
  • .agents/skills/harness-adapters/SKILL.md
  • .agents/skills/stow/SKILL.md
  • AGENTS.md
  • CONTRIBUTING.md
  • README.md
  • bin/backends/herdr.sh
  • bin/fm-backend.sh
  • bin/fm-bootstrap.sh
  • bin/fm-brief.sh
  • bin/fm-crew-state.sh
  • bin/fm-guard.sh
  • bin/fm-session-start.sh
  • bin/fm-spawn.sh
  • docs/architecture.md
  • docs/configuration.md
  • docs/herdr-backend.md
  • docs/scripts.md
  • tests/fm-backend-autodetect-smoke.test.sh
  • tests/fm-backend-herdr-prune-safety-e2e.test.sh
  • tests/fm-backend-herdr-smoke.test.sh
  • tests/fm-backend-herdr-workspace-per-home-e2e.test.sh
  • tests/fm-backend-herdr.test.sh
  • tests/fm-backend.test.sh
  • tests/fm-crew-state.test.sh
  • tests/fm-session-start.test.sh
  • tests/fm-tangle-guard.test.sh
  • tests/herdr-test-safety.sh

Comment on lines +925 to +933
test_no_jq_reserved_keyword_arg_names() {
local reserved='and|as|catch|def|elif|else|end|foreach|if|import|include|label|module|or|reduce|then|try'
local hits
hits=$(grep -rnE -- "--arg(json)?[[:space:]]+($reserved)\b" "$ROOT/bin" 2>/dev/null)
if [ -n "$hits" ]; then
fail "a jq --arg/--argjson variable is named after a jq reserved keyword (compile error on jq <= 1.6, silently swallowed by 2>/dev/null):"$'\n'"$hits"
fi
pass "no bin/ jq filter names a --arg/--argjson variable after a jq reserved keyword"
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

Does BSD/macOS grep support \b word boundary in extended regular expressions (grep -E)?

💡 Result:

No, BSD/macOS grep does not support the \b word boundary escape sequence in extended regular expressions (grep -E) [1][2][3]. The \b, <, and > syntax is a common extension found in GNU grep, but it is not standard in the BSD grep implementation used by macOS and other BSD-based systems [1][2][4]. Instead, BSD grep provides its own non-portable, system-specific syntax for word boundaries [2]: - [[:<:]] matches the null string at the beginning of a word [2][3]. - [[:>:]] matches the null string at the end of a word [2][3]. These bracket expressions are defined in the re_format(7) manual page as extensions for word matching [2]. If you require portable word boundary support (like \b) across different systems, you should avoid these BSD-specific extensions and consider using an alternative tool like perl or awk, which often have more consistent regex engine support across platforms [2][4].

Citations:


🏁 Script executed:

sed -n '925,933p' tests/fm-backend-herdr.test.sh

printf '%s\n' '--arg label' '--arg ifname' '--arg labelX' | grep -nE -- '--arg(json)?[[:space:]]+(and|as|catch|def|elif|else|end|foreach|if|import|include|label|module|or|reduce|then|try)\b' || true

printf '%s\n' '--arg label' '--arg ifname' '--arg labelX' | grep -nE -- '--arg(json)?[[:space:]]+(and|as|catch|def|elif|else|end|foreach|if|import|include|label|module|or|reduce|then|try)([[:space:]]|$)' || true

Repository: korallis/firstmate

Length of output: 710


Use a portable end-of-word match here. \b is a GNU grep extension and can be ignored by BSD/macOS grep -E, which makes this guard miss reserved names on those systems. Replace it with a POSIX ERE boundary such as ([[:space:]]|$).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/fm-backend-herdr.test.sh` around lines 925 - 933, The jq
reserved-keyword guard in test_no_jq_reserved_keyword_arg_names() uses a
GNU-only word boundary in the grep pattern, so on BSD/macOS it can miss matches;
update the grep ERE to use a portable POSIX end-of-token boundary such as
whitespace-or-end-of-line, while keeping the reserved keyword list and the
test_no_jq_reserved_keyword_arg_names symbol intact.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants