Skip to content

fix(bin): keep watcher supervision continuous across child cycles - #693

Merged
kunchenguid merged 19 commits into
mainfrom
fm/fm-watcher-continuity-fix
Jul 19, 2026
Merged

kunchenguid merged 19 commits into
mainfrom
fm/fm-watcher-continuity-fix

Conversation

@kunchenguid

Copy link
Copy Markdown
Owner

Intent

Fix watcher supervision continuity so Pi and OpenCode adapters re-arm event-driven after actionable child closes with single-flight, session-lock verification, bounded backoff, independent wake delivery, loud unexplained clean exits, and a bounded arm-owned cycle ledger; add only the tightly scoped Claude in-flight/no-live-watcher fleet-command gate while preserving drain/arm access and leaving the existing turn-end guard unchanged; preserve the 300-second grace and watcher-only beacon ownership; validate credentialed real E2Es for Claude, Codex, OpenCode, Pi via shared openai-codex auth, and Grok with sanitized evidence; create a green PR but do not merge it because captain review is the merge gate.

What Changed

  • Keep watcher arms alive across verified successor cycles, emit typed failures for unexplained clean exits, and record bounded per-cycle lifecycle diagnostics.
  • Have Pi and OpenCode re-arm watcher successors with lock checks, single-flight bounded retries, and restoration-failure wake fallbacks after child closes.
  • Add Claude's narrow continuity gate, allowing wake-drain and arm recovery while blocking other fleet scripts only when in-flight work lacks a live watcher.

Risk Assessment

⚠️ Medium: The implementation is source-clean on review, but it changes a broad, timing-sensitive supervision path across multiple adapters.

Testing

The supplied full-suite baseline was green; I reran the Pi/OpenCode lifecycle suite in isolation and twice concurrently, exercised lock/peer-attach/ledger and Claude gate regressions, and completed isolated credentialed Claude, Codex, OpenCode, Pi, and Grok E2Es with sanitized CLI-transcript evidence. No graphical UI applies to these terminal adapters, so the reviewer-visible evidence is captured terminal output.

Evidence: Pi credentialed TUI continuity transcript
ok - Pi 0.80.10 live E2E used shared Codex auth, auto-started one successor before turn end, and cleaned up
Evidence: OpenCode credentialed TUI continuity transcript
ok - OpenCode 1.17.18 live E2E auto-started one successor before prompt handling without a model re-arm
Evidence: Claude credentialed continuity-gate transcript
ok - Claude 2.1.214 (Claude Code) live E2E refused only the post-completion fleet command with exact re-arm guidance
Evidence: Codex credentialed checkpoint transcript
ok - codex-cli 0.144.5 live E2E preserved the one-second foreground checkpoint path
Evidence: Grok credentialed continuity transcript
ok - grok 0.2.103 (89c3d36fb6f1) [stable] live E2E preserved tracked background completion and shared ledger classification
Evidence: Pi/OpenCode extension suite under concurrent load
ok - Pi primary watcher extension is tracked, self-hashing, and self-locating
ok - Pi secondmate launch wiring includes both tracked primary extensions
ok - Pi extension reports external healthy watcher output
ok - Pi custom tool returns text content and structured details
ok - Pi actionable close starts one successor before wake delivery settles
ok - Pi hung successor falls back to one typed actionable wake
ok - Pi unretired successor falls back without an overlapping retry
ok - Pi late unretired closes resume classified supervision
ok - Pi clean empty close triggers a bounded continuity retry
ok - Pi established clean closes stop at the configured retry limit
ok - Pi close handler verifies session-lock ownership before successor launch
ok - Pi watcher arm distinguishes all session lock ownership states
ok - Pi process-exit cleanup listener has a bounded lifecycle
ok - Pi process-exit cleanup stops the attached arm child
ok - OpenCode primary watcher plugin has the verified TUI wake wiring
ok - OpenCode plugins have an explicit ESM boundary even under a typeless parent package
ok - OpenCode watcher plugin uses the effective FM_HOME state
ok - OpenCode watcher plugin sources the effective config
ok - OpenCode watcher plugin requires session lock ownership
ok - OpenCode watcher coordinator respects primary scope
ok - OpenCode watcher plugin starts one successor before wake prompt delivery settles
ok - OpenCode pre-ready actionable close preserves its successor
ok - OpenCode hung successor falls back to one typed actionable wake
ok - OpenCode unretired successor falls back without an overlapping retry
ok - OpenCode late unretired closes resume classified supervision
ok - OpenCode clean empty close triggers a bounded continuity retry
ok - OpenCode established clean closes stop at the configured retry limit
ok - OpenCode close handler verifies session-lock ownership before successor launch
ok - OpenCode watcher plugin coordinates with the turn-end guard
ok - OpenCode healthy arm output does not suppress the turn-end guard
Evidence: Watcher lock, peer-attach, and lifecycle-ledger evidence
ok - simultaneous watcher starts leave exactly one live process
ok - fm_pid_identity is locale-invariant across LC_ALL/LC_TIME
ok - killed watcher stale lock is reclaimed
ok - live watcher lock with stale heartbeat is actionable
ok - guard banner leads when down with pending wakes (re-arm-after-drain) and stays silent when fresh
ok - concurrent fm_lock_try_acquire yields exactly one winner
ok - dead-pid stale lock is reclaimed by a single acquirer
ok - concurrent stale-lock steal yields exactly one winner
ok - live steal mutex is not reclaimed
ok - live-held lock is not stolen
ok - empty mid-acquire lock keeps a minimum grace
ok - late original claimant cannot claim a recreated lock
ok - paused mid-acquire claimant backs off to active stealer
ok - watch restart refuses to signal a reused pid
ok - watch restart attaches to a verified healthy peer and later surfaces a successor gap
ok - watcher self-evicts when the lock pid no longer names it
ok - arm turns clean self-eviction without a successor into a typed failure
ok - arm attaches to a live fresh watcher and fails loudly when that cycle has no successor
ok - attached arm signals record a classified lifecycle entry
ok - arm starts+confirms a fresh watcher on a clean lock and self-heals a dead-pid lock (never healthy off a dead pid)
ok - arm cleans child watcher and temp output on HUP
ok - arm propagates an immediate watcher wake before confirmation
ok - arm attaches to a peer watcher after child stands down and surfaces a missing successor
watcher: lock held by live pid 84446 but heartbeat is stale for 837652020s (>300s); inspect or stop that watcher before re-arming.
ok - arm reports FAILED and exits non-zero when no fresh watcher can be confirmed
ok - cycle-exit ledger links a verified successor and remains size-capped
ok - SIGSTOP distinguishes live PID from stale beacon and termination records the exit class
- Outcome: 🔧 1 issue found → auto-fixed (2) ✅ across 3 runs (1h47m25s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 3 issues found → auto-fixed (5) ✅
  • 🚨 .opencode/plugins/fm-primary-watch-arm.js:169 - A cycle that emits started/attached and then immediately exits unexpectedly resets retryFailures before its close handler schedules the retry. Every retry is therefore attempt 1, so the configured retry limit is never reached and this can respawn arm children indefinitely at the base delay. Reset the counter only after a cycle has completed successfully, not when readiness is first observed.
  • 🚨 .pi/extensions/fm-primary-pi-watch.ts:219 - As in OpenCode, observing a ready line resets retryFailures before an unexpected close. A watcher that starts and then repeatedly exits will bypass retryLimit forever, producing an unbounded Pi restart loop instead of surfacing the promised restoration failure.
  • ⚠️ bin/fm-watch-arm.sh:341 - The attach path begins tracking an observed cycle and immediately enters attach_and_wait, but signal traps are installed only later in the child-start path. TERM/HUP/INT therefore terminates an attached arm without a lifecycle record or signal classification, contradicting the ledger's per-observed-cycle diagnostics. Install the signal handling before this branch or add an attach-specific trap.

🔧 Fix: Bound watcher retries and log attached signals
2 errors still open:

  • 🚨 .pi/extensions/fm-primary-pi-watch.ts:256 - The required criterion says “independent wake delivery,” but the actionable-close path waits for successorReady before calling sendWake. If the replacement arm hangs before emitting started or attached, that promise never settles and the actionable wake is never delivered. Decide whether delivery should be dispatched immediately after startArm is invoked (while the successor continues establishing) rather than gated on readiness.
  • 🚨 .opencode/plugins/fm-primary-watch-arm.js:272 - The required criterion says “independent wake delivery,” but OpenCode waits for ensureArm to resolve before it calls promptAsync. A successor that does not become ready delays the actionable wake for the arm-ready timeout, coupling delivery to restoration rather than merely starting the successor first. Decide whether to dispatch the wake after initiating the successor and handle restoration failures separately.

🔧 Fix: Add bounded successor-recovery wake fallbacks
2 errors still open:

  • 🚨 .pi/extensions/fm-primary-pi-watch.ts:180 - The captain-required fallback must “remain single-flight,” but timeout abandonment clears the tracked child and sends TERM without waiting for that arm to exit. The next retry can launch while the timed-out arm is still alive or ignoring TERM, leaving concurrent arm processes and allowing the old process to publish a watcher later. Bound termination as well: only retry after close confirmation, or stop retrying and deliver the typed fallback if the old arm cannot be retired.
  • 🚨 .opencode/plugins/fm-primary-watch-arm.js:221 - The captain-required fallback must “remain single-flight,” but this clears child immediately after TERM without awaiting the prior arm’s close. A retry can therefore overlap an unresponsive predecessor arm, defeating single-flight and leaving a late old arm able to interfere with the new cycle. Wait for bounded retirement before retrying, then fall back to the typed wake if retirement does not complete.

🔧 Fix: Prevent overlapping successor-arm retries
2 errors still open:

  • 🚨 .pi/extensions/fm-primary-pi-watch.ts:312 - The required event-driven re-arm path is lost after a retirement timeout. The arm remains tracked until it eventually closes, but it is permanently marked abandoned, so this handler discards that later close - including an actionable wake - rather than delivering it or resuming recovery. The fallback prompt covers the original wake only; decide how a late unretired arm should be supervised after fallback, while still avoiding overlap.
  • 🚨 .opencode/plugins/fm-primary-watch-arm.js:325 - After a timed-out arm fails retirement, its later close event is permanently ignored because it remains in abandonedChildren. If that arm eventually establishes and exits with an actionable reason, the queue receives a wake but OpenCode never delivers it or starts the next cycle. The fallback only reports the earlier wake; decide how late closes should re-enter supervised handling without violating single-flight.

🔧 Fix: Resume supervision after late arm closes
1 error still open:

  • 🚨 .opencode/plugins/fm-primary-watch-arm.js:247 - When a successor closes with an actionable reason before becoming ready, its close handler synchronously starts a new restoration successor and resolves this restoration's readiness waiter. On resume, mutable child now refers to that new successor, so this call sends TERM to it rather than the already-closed arm. Track the arm associated with each readiness attempt and retire that specific child to preserve continuous single-flight recovery.

🔧 Fix: Bind OpenCode recovery to attempted arm
✅ Re-checked - no issues remain.

🔧 **Test** - 1 issue found → auto-fixed (2) ✅
  • 🚨 tests failed with exit code 1
  • 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"

🔧 Fix: Synchronize peer beacon regression fixture
2 warnings still open:

  • ⚠️ tests/fm-pi-watch-extension.test.sh:444 - fm-pi-watch-extension.test.sh failed once in its late-close fixture at a 20 ms readiness/retirement boundary while other focused tests were still active. The identical isolated scenario and a complete clean rerun passed, indicating a load-sensitive test flake rather than a persistent adapter failure. Consider synchronizing or widening this fixture before relying on it as a deterministic gate.
  • ⚠️ No open PR exists for fm/fm-watcher-continuity-fix (gh-axi pr list --state open --head fm/fm-watcher-continuity-fix returned zero results), so the required green-PR acceptance criterion cannot be demonstrated. Creating a PR is an external state change outside this testing-only request.
  • 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"
  • Baseline already completed: 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-watcher-lock.test.sh
  • bash tests/fm-continuity-pretool-check.test.sh
  • bash tests/fm-pi-watch-extension.test.sh - clean rerun after isolated late-close reproduction
  • FM_CLAUDE_LIVE_E2E=1 bash tests/fm-claude-continuity-live-e2e.test.sh
  • FM_CODEX_LIVE_E2E=1 bash tests/fm-codex-continuity-live-e2e.test.sh
  • FM_OPENCODE_LIVE_E2E=1 bash tests/fm-opencode-primary-live-e2e.test.sh
  • FM_PI_LIVE_E2E=1 bash tests/fm-pi-primary-live-e2e.test.sh
  • FM_GROK_LIVE_E2E=1 bash tests/fm-grok-continuity-live-e2e.test.sh
  • git status --short and transient-live-lab scan

🔧 Fix: Synchronize Pi and OpenCode late-close lifecycle fixtures
✅ Re-checked - no issues remain.

  • 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"
  • Baseline already completed successfully: 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-pi-watch-extension.test.sh in clean isolation
  • Two concurrent bash tests/fm-pi-watch-extension.test.sh runs
  • bash tests/fm-watcher-lock.test.sh
  • bash tests/fm-continuity-pretool-check.test.sh
  • FM_CLAUDE_LIVE_E2E=1 bash tests/fm-claude-continuity-live-e2e.test.sh
  • FM_CODEX_LIVE_E2E=1 bash tests/fm-codex-continuity-live-e2e.test.sh
  • FM_OPENCODE_LIVE_E2E=1 bash tests/fm-opencode-primary-live-e2e.test.sh
  • FM_PI_LIVE_E2E=1 bash tests/fm-pi-primary-live-e2e.test.sh
  • FM_GROK_LIVE_E2E=1 bash tests/fm-grok-continuity-live-e2e.test.sh
  • Verified no live-E2E temporary directories or worktree changes remained after cleanup.
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@kunchenguid
kunchenguid merged commit 3729081 into main Jul 19, 2026
5 checks passed
@kunchenguid
kunchenguid deleted the fm/fm-watcher-continuity-fix branch July 19, 2026 00:36
quinnbot-ai pushed a commit to quinnbot-ai/firstmate that referenced this pull request Jul 19, 2026
…nchenguid#693)

* fix: make watcher supervision continuous

* no-mistakes(review): Bound watcher retries and log attached signals

* no-mistakes(review): Add bounded successor-recovery wake fallbacks

* no-mistakes(review): Prevent overlapping successor-arm retries

* no-mistakes(review): Resume supervision after late arm closes

* no-mistakes(review): Bind OpenCode recovery to attempted arm

* no-mistakes(test): Synchronize peer beacon regression fixture

* no-mistakes(test): Synchronize Pi and OpenCode late-close lifecycle fixtures

* no-mistakes(document): Captain: document watcher successor protocol behavior

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes
LoneExile added a commit to LoneExile/firstmate that referenced this pull request Jul 19, 2026
…guid#693)

Port upstream kunchenguid#693's successor-before-wake continuity to the omp watcher
adapter. After an actionable child close the extension now starts and
verifies ONE singleton successor arm BEFORE delivering the wake (Option B),
with single-flight, bounded exponential retry, session-lock recheck at
launch, and a typed continuity-restoration failure so the model is never
left blind. This removes the model-memory re-arm step.

The mechanism lives entirely in .omp/extensions/fm-primary-omp-watch.ts and
reads the arm layer's existing `watcher: started|attached` readiness lines,
so bin/fm-watch-arm.sh - and its CONFIRM_MAX slow-start guard from 862f9a3 -
is untouched (a wholesale arm-layer port would have dropped CONFIRM_MAX and
reintroduced the re-arm storm). Mirrors the Pi kunchenguid#693 adapter with the omp
adaptations: pi.zod schema, Promise.withResolvers (repo TS lint), typed
ChildProcess, FM_OMP_ARM_READY_TIMEOUT_MS, OMP wording.

tests/fm-omp-watch-extension.test.sh: 7 node-harness cases driving the real
close handler (successor-before-wake + single-flight, hung-successor typed
fallback, unretired-successor no-overlap, empty-close bounded retry,
session-lock recheck, process-exit cleanup); proven non-vacuous against the
pre-continuity adapter. Strict-typechecked clean (no-any, no-unused).

The arm-layer diagnostic cycle-exits ledger (also in kunchenguid#693) is intentionally
deferred: the design doc calls it "diagnostic evidence, not a supervision
dependency", and a faithful port requires reconciling upstream's
attach/healthy semantic change against our fork - a dedicated task, not a
tail-of-session change to the safety-critical arm loop.

Also update the opt-in fm-omp-primary-live-e2e.test.sh: with continuity the
successor is auto-armed before the wake, so a post-wake fm_watch_arm_omp
reports an existing child rather than starting a fresh "child 2".
LoneExile added a commit to LoneExile/firstmate that referenced this pull request Jul 19, 2026
…unchenguid#693)

Port kunchenguid#693's arm-layer cycle-exits ledger to bin/fm-watch-arm.sh as a
purely-additive, best-effort diagnostic: one tab-separated record per observed
watcher cycle appended to state/.watch-cycle-exits.log (arm/watcher pids, start
and end timestamps, exit code + signal, classified reason, beacon age, lock
identity before/after close, successor disposition), size-capped via
FM_WATCH_CYCLE_LOG_MAX_BYTES / FM_WATCH_CYCLE_LOG_KEEP_LINES and linked to a
predecessor arm via FM_WATCH_PREDECESSOR_ARM_PID (which the omp adapter already
passes). Every write is bounded and best-effort (a capped lock-acquire spin,
2>/dev/null, || true) so an observability failure can never stall or alter a
cycle: it leaves control flow, exit codes, the CONFIRM_MAX slow-start guard
(862f9a3), and the attach/healthy semantics unchanged.

Kept OUR arm layer as the base rather than adopting upstream's owned_child_finished
refactor - that was built on the pre-fork base and dropped CONFIRM_MAX, which
would reintroduce the re-arm storm.

The "another watcher won the singleton" branch now classifies our child's actual
exit (clean stand-down vs. crash) so the ledger never labels a crashed child as a
voluntary stand-down.

tests/fm-watcher-lock.test.sh: two non-vacuous cases - a started + actionable
cycle logs origin=started / reason=actionable-check, and a never-confirmed cycle
fails closed with the unchanged "no live watcher with a fresh beacon" line AND a
reason=confirmation-timeout ledger row. Proven non-vacuous (neutralizing the
ledger write fails them).

NOT included: kunchenguid#693's typed "cycle ended without an actionable reason" and
"watcher cycle exited <rc>" FAILED reasons. Those are a genuine behavior change
(a confirmed watcher exiting rc=0-empty would flip exit 0 -> 1, and our
never-confirmed path already fails closed with a different message) that belongs
in the separate attach/healthy semantic reconciliation, deferred in the teacher
BACKLOG.
quinnbot-ai added a commit to quinnbot-ai/firstmate that referenced this pull request Jul 19, 2026
* fix(bin): keep watcher supervision continuous across child cycles (kunchenguid#693)

* fix: make watcher supervision continuous

* no-mistakes(review): Bound watcher retries and log attached signals

* no-mistakes(review): Add bounded successor-recovery wake fallbacks

* no-mistakes(review): Prevent overlapping successor-arm retries

* no-mistakes(review): Resume supervision after late arm closes

* no-mistakes(review): Bind OpenCode recovery to attempted arm

* no-mistakes(test): Synchronize peer beacon regression fixture

* no-mistakes(test): Synchronize Pi and OpenCode late-close lifecycle fixtures

* no-mistakes(document): Captain: document watcher successor protocol behavior

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* fix: fetch current PR head for review diffs (kunchenguid#722)

* fix: always fetch PR head for review diffs

Prefer a freshly fetched refs/pull/<n>/head over a reachable recorded
pr_head= so reviewers never hold a merge over a "missing" fix that already
landed on the remote PR. Recorded SHA is offline fallback only; local branch
is last resort with a warning. Store the tip under refs/fm-review/ so a later
base-branch fetch cannot clobber the compare tip via FETCH_HEAD.

* no-mistakes(test): Isolate session-start nudge tests from gate state

* no-mistakes(document): Correct review-diff documentation

* Pin crew worktree git identities

* no-mistakes(review): Captain: retry shared Git config initialization

* no-mistakes(review): Normalize worktree config boolean handling

* no-mistakes(test): Captain, isolate review diffs from external renderers

* no-mistakes(lint): Silence unused retry loop variable

* no-mistakes(lint): Remove unused ShellCheck local

* test: align secondmate charter assertion

---------

Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: QuinnBot <[email protected]>
quinnbot-ai added a commit to quinnbot-ai/firstmate that referenced this pull request Jul 19, 2026
* fix(bin): keep watcher supervision continuous across child cycles (kunchenguid#693)

* fix: make watcher supervision continuous

* no-mistakes(review): Bound watcher retries and log attached signals

* no-mistakes(review): Add bounded successor-recovery wake fallbacks

* no-mistakes(review): Prevent overlapping successor-arm retries

* no-mistakes(review): Resume supervision after late arm closes

* no-mistakes(review): Bind OpenCode recovery to attempted arm

* no-mistakes(test): Synchronize peer beacon regression fixture

* no-mistakes(test): Synchronize Pi and OpenCode late-close lifecycle fixtures

* no-mistakes(document): Captain: document watcher successor protocol behavior

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* fix: fetch current PR head for review diffs (kunchenguid#722)

* fix: always fetch PR head for review diffs

Prefer a freshly fetched refs/pull/<n>/head over a reachable recorded
pr_head= so reviewers never hold a merge over a "missing" fix that already
landed on the remote PR. Recorded SHA is offline fallback only; local branch
is last resort with a warning. Store the tip under refs/fm-review/ so a later
base-branch fetch cannot clobber the compare tip via FETCH_HEAD.

* no-mistakes(test): Isolate session-start nudge tests from gate state

* no-mistakes(document): Correct review-diff documentation

* Escalate busy crews with no progress

* no-mistakes(review): Captain: escalate AFK busy-progress wedges

* no-mistakes(review): Scope pane progress parsing to current footer

* no-mistakes(review): Captain: Harden busy-progress watcher safeguards

* no-mistakes(review): Captain: clear teardown busy-progress state

* no-mistakes(review): Harden busy-progress marker recovery

* fix: cache watcher busy state

* test: bound watcher cache cleanup

* no-mistakes(test): Captain: stabilize tmux smoke and review diffs

* no-mistakes(test): Captain: fix Herdr UTF-8 prompt classification

* no-mistakes(test): Captain: fix transient Herdr worktree detection

* no-mistakes(test): Fix checkpoint cleanup and spawn isolation

* no-mistakes(document): Document busy-progress watcher escalation

* test(brief): restore portable charter assertion

---------

Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: QuinnBot <[email protected]>
LoneExile added a commit to LoneExile/firstmate that referenced this pull request Jul 19, 2026
…henguid#693 sliver)

The started path confirmed a watcher healthy (HEALTHY_PID = child), waited it,
then exited with the child's rc - so a confirmed cycle that ended rc=0 with no
wake was a silent exit 0: the 'clean empty success' kunchenguid#693's arm contract forbids.

Now, after wait: keep today's behavior only when rc=0 AND a wake; otherwise emit
the typed reason ('cycle ended without an actionable reason' for rc=0,
'watcher cycle exited <rc> without an actionable reason' otherwise), log it
(reason=empty-no-wake), and exit non-zero so the harness notify fires loud.

Scoped to the confirmed-started branch only. The never-confirmed child-death
block and confirmation-timeout tail keep their load-bearing 'no live watcher
with a fresh beacon' reason (test_arm_fails_loud_when_no_fresh_watcher_confirmable
still passes) - the exact conflation kunchenguid#693 warns against.

Non-vacuous: test_arm_fails_loud_on_empty_confirmed_cycle (confirmed-then-empty
fake) fails on old code with 'arm returned zero on an empty confirmed cycle';
the never-confirmed sibling stays ok.
LoneExile added a commit to LoneExile/firstmate that referenced this pull request Jul 19, 2026
Self-review of 7ffb38e: the empty-cycle guard gated the wake-propagating path on
'rc=0 AND a wake', so a confirmed watcher that printed a real wake but then exited
NON-ZERO fell into the FAILED-empty branch - swallowing the wake and mislabeling
it 'without an actionable reason' when there was one. kunchenguid#693 reason #2 is 'exited
<rc> WITHOUT a wake'; the discriminator is wake presence, not rc.

Gate the normal path on watch_output_has_wake alone: any exit code with a wake
propagates the wake + rc unchanged (pre-7ffb38e behavior); the typed FAILED-empty
path is reached only with NO wake (rc=0 -> 'cycle ended...', exit 1; rc!=0 ->
'watcher cycle exited <rc>...', exit rc).

Tests: test_arm_propagates_wake_on_nonzero_confirmed_cycle (fix guard - fails on
the old rc=0 gate with 'arm SWALLOWED a real wake') and
test_arm_fails_loud_on_nonzero_empty_confirmed_cycle (reason #2 coverage). Full
suite green modulo the known fm-pr-check-security flake.
quinnbot-ai added a commit to quinnbot-ai/firstmate that referenced this pull request Jul 19, 2026
* fix(bin): keep watcher supervision continuous across child cycles (kunchenguid#693)

* fix: make watcher supervision continuous

* no-mistakes(review): Bound watcher retries and log attached signals

* no-mistakes(review): Add bounded successor-recovery wake fallbacks

* no-mistakes(review): Prevent overlapping successor-arm retries

* no-mistakes(review): Resume supervision after late arm closes

* no-mistakes(review): Bind OpenCode recovery to attempted arm

* no-mistakes(test): Synchronize peer beacon regression fixture

* no-mistakes(test): Synchronize Pi and OpenCode late-close lifecycle fixtures

* no-mistakes(document): Captain: document watcher successor protocol behavior

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* fix: fetch current PR head for review diffs (kunchenguid#722)

* fix: always fetch PR head for review diffs

Prefer a freshly fetched refs/pull/<n>/head over a reachable recorded
pr_head= so reviewers never hold a merge over a "missing" fix that already
landed on the remote PR. Recorded SHA is offline fallback only; local branch
is last resort with a warning. Store the tip under refs/fm-review/ so a later
base-branch fetch cannot clobber the compare tip via FETCH_HEAD.

* no-mistakes(test): Isolate session-start nudge tests from gate state

* no-mistakes(document): Correct review-diff documentation

* fix: hold treehouse worktrees until teardown

* no-mistakes(review): rollback treehouse leases on spawn failures

* no-mistakes(review): recover stranded treehouse lease handoffs

* no-mistakes(review): Harden treehouse lease recovery

* fix: serialize treehouse lease handoffs

* fix: harden treehouse lease cleanup

* no-mistakes(review): Tombstone returned treehouse lease handoffs

* fix: harden treehouse teardown handoffs

* fix: ignore transient lease handoffs

* no-mistakes(test): Fix lease-aware test fixtures

* no-mistakes(test): Fix locale-safe composer and watcher races

* no-mistakes(test): Close AFK launcher signal race

* no-mistakes(document): Document durable treehouse task leases

* fix: preserve Orca abort cleanup through activation

* fix: retain fork charter portability updates

* test: model leased treehouse allocations in identity fixture

* fix: close failed spawn endpoint before lease return

* fix: retain committed lease on activation failure

* fix: retain recovery metadata after lease commit

* test: match durable lease handoff format

* test: retain committed lease after endpoint closure

* test: model absent endpoint in spawn abort fixture

* test: initialize fixture repositories on main

* fix: preserve durable returned lease tombstones

* fix: make leased spawn setup failures deterministic

* test: forward task temp failure injection

* ci: trace tangle guard hang

* test: make lease setup failure injection deterministic

* ci: allow bounded watcher lifecycle tests to finish

---------

Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: QuinnBot <[email protected]>
quinnbot-ai added a commit to quinnbot-ai/firstmate that referenced this pull request Jul 21, 2026
…d guard (#16)

* fix(bin): keep watcher supervision continuous across child cycles (kunchenguid#693)

* fix: make watcher supervision continuous

* no-mistakes(review): Bound watcher retries and log attached signals

* no-mistakes(review): Add bounded successor-recovery wake fallbacks

* no-mistakes(review): Prevent overlapping successor-arm retries

* no-mistakes(review): Resume supervision after late arm closes

* no-mistakes(review): Bind OpenCode recovery to attempted arm

* no-mistakes(test): Synchronize peer beacon regression fixture

* no-mistakes(test): Synchronize Pi and OpenCode late-close lifecycle fixtures

* no-mistakes(document): Captain: document watcher successor protocol behavior

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* fix: fetch current PR head for review diffs (kunchenguid#722)

* fix: always fetch PR head for review diffs

Prefer a freshly fetched refs/pull/<n>/head over a reachable recorded
pr_head= so reviewers never hold a merge over a "missing" fix that already
landed on the remote PR. Recorded SHA is offline fallback only; local branch
is last resort with a warning. Store the tip under refs/fm-review/ so a later
base-branch fetch cannot clobber the compare tip via FETCH_HEAD.

* no-mistakes(test): Isolate session-start nudge tests from gate state

* no-mistakes(document): Correct review-diff documentation

* docs: resolve five contract contradictions across AGENTS.md, README, and skills (kunchenguid#736)

* docs: resolve five contract contradictions

* no-mistakes(test): align owner-pointer assertions with reworded docs; skip absent shellcheck

* docs(harness): correct Grok exit guidance (kunchenguid#742)

* docs(harness): reverify grok exit command

* no-mistakes(test): Correct Grok exit resume attribution

* fix(watcher): bound stale wakes for parked crew (kunchenguid#743)

* fix(watcher): bound stale wakes for exited paused crew

* no-mistakes(review): Gate pause suppression on confirmed agent death

* no-mistakes(test): Fixed stale pause cadence

* no-mistakes(document): Document dead-agent hold cadence

* fix: harden watcher arm relay leases

* no-mistakes(review): Harden relay leases and cleanup identity

* no-mistakes(review): Harden tmux ownership and review remote selection

* no-mistakes(review): Harden watcher relay and tmux recovery safety

* fix(supervision): distinguish ordinary wakes from recovery (kunchenguid#744)

* fix(supervision): distinguish ordinary wakes from repair

* no-mistakes(review): Make passive guard follow-ups recovery-only

* no-mistakes(document): Clarify recovery-only turn-end guard documentation

* fix(x-mode): dedupe pending mention wakes (kunchenguid#745)

* fix(x-mode): dedupe pending mention wakes

* no-mistakes(review): fix x-poll claim error deduplication

* no-mistakes(review): separate claim diagnostics from relay recovery

* no-mistakes(document): Document X-mode once-only mention wakes

* no-mistakes(test): Fix strict target-validation test fixtures

* no-mistakes(document): Document relay lease hardening

* no-mistakes(lint): Fix relay lease lint warnings

* fix: reject symlinked Codex roots before spawn metadata

* fix: reject symlinked Codex root before metadata

* no-mistakes(review): Harden relay leases and normalize PR remotes

* feat(wake): enrich drained signals with bounded status context (kunchenguid#747)

* feat(wake): enrich drained signal context

* no-mistakes(review): Bound wake enrichment reads

* no-mistakes(document): Document wake-drain annotations

* docs(wake): explain at-least-once drain boundary

* no-mistakes(review): Prevent symlink races in wake annotations

* no-mistakes(review): Exercise wake symlink race regression

* test: document intentional AFK marker subprocesses

* fix(wake): isolate annotation marker state

* no-mistakes(test): Fix malformed tangle guard test fixtures

* no-mistakes(document): Document watcher and daemon lease lifecycle

* fix: preserve pre-metadata spawn refusal

* no-mistakes(test): Preserve failed lease metadata and attached arm lifecycle logs

* no-mistakes(review): Fix shared PR review fetch ref

* no-mistakes(review): Harden daemon lease ownership handoff

* no-mistakes(review): Harden stale daemon lease recovery and arm tick validation

* no-mistakes(review): Fence stale AFK lease recovery

* no-mistakes(review): Fence watcher identity lease publication

* no-mistakes(review): Guard reclaimed AFK launcher locks

* no-mistakes(review): Harden relay and launcher lease races

* no-mistakes(document): Document daemon lease recovery grace

* no-mistakes(lint): Isolate lease test helper shells

* fix: harden watcher arm relay leases

* no-mistakes(review): Harden relay leases and cleanup identity

* no-mistakes(review): Harden tmux ownership and review remote selection

* no-mistakes(review): Harden watcher relay and tmux recovery safety

* no-mistakes(test): Fix strict target-validation test fixtures

* no-mistakes(document): Document relay lease hardening

* no-mistakes(lint): Fix relay lease lint warnings

* fix: reject symlinked Codex roots before spawn metadata

* fix: reject symlinked Codex root before metadata

* no-mistakes(review): Harden relay leases and normalize PR remotes

* no-mistakes(test): Fix malformed tangle guard test fixtures

* no-mistakes(document): Document watcher and daemon lease lifecycle

* fix: preserve pre-metadata spawn refusal

* no-mistakes(test): Preserve failed lease metadata and attached arm lifecycle logs

* no-mistakes(review): Fix shared PR review fetch ref

* no-mistakes(review): Harden daemon lease ownership handoff

* no-mistakes(review): Harden stale daemon lease recovery and arm tick validation

* no-mistakes(review): Fence stale AFK lease recovery

* no-mistakes(review): Fence watcher identity lease publication

* docs: retain wake drain annotations

* fix: preserve spawn refusal metadata boundary

* fix: retain prepublication spawn rollback

* test: model stable tmux endpoint cleanup

* fix: retain prelaunch endpoint recovery state

* feat(herdr): add optional presentation spaces (kunchenguid#784)

* feat(herdr): add optional presentation spaces

* no-mistakes(review): Harden Herdr projection creation and spawn serialization

* no-mistakes(review): Captain, disarm Herdr cleanup before launch submission

* no-mistakes(test): Correct stale Orca metadata failure fixture

* no-mistakes(document): Document Herdr presentation projection accurately

* fix: preserve watcher lease handoffs

* fix(spawn): isolated CODEX_HOME for crewmate codex spawns (#3)

* fix: isolate Codex crewmate MCP config

* no-mistakes(review): Harden Codex home cleanup failures

* no-mistakes(review): Harden isolated Codex crewmate launches

* fix: scope Codex trust to worktree

* no-mistakes(review): Harden Codex crewmate launch isolation

* no-mistakes(review): Record failed Codex endpoint cleanup

* no-mistakes(review): Harden case-insensitive Codex launch isolation

* no-mistakes(review): Harden Codex raw launch isolation

* no-mistakes(review): Harden Codex spawn isolation

* no-mistakes(review): Harden Codex launch isolation cleanup

* no-mistakes(review): Harden Codex wrappers and Orca cleanup metadata

* no-mistakes(review): Harden Codex isolation and cleanup

* no-mistakes(review): Captain: Harden Codex spawn isolation

* no-mistakes(review): Harden Codex launch isolation

* no-mistakes(review): Captain: Harden Codex launch isolation

* no-mistakes(review): Captain: harden Codex activation and backend cleanup

* no-mistakes(review): Harden Codex launch isolation

* no-mistakes(review): Captain: preserve raw custom shell launches

* no-mistakes(review): Harden Codex isolation and Zellij cleanup

* no-mistakes(review): Confirm strict Zellij cleanup closures

* no-mistakes(review): Harden Codex activation result isolation

* no-mistakes(review): Harden Codex launch isolation

* fix: harden failed spawn teardown

* fix: harden Codex launch cleanup

* no-mistakes(review): Harden indirect Codex launch isolation

* no-mistakes(review): Harden Codex activation and builtin dispatch

* no-mistakes(review): Harden Orca cleanup and raw launch parsing

* no-mistakes(review): Confirm Orca terminal absence before cleanup

* no-mistakes(test): Disable external review diff drivers

* no-mistakes(test): Fix spawn isolation test fixture

* no-mistakes(review): Respect explicit CODEX_HOME overrides

* no-mistakes(document): Document Codex crewmate isolation

* no-mistakes(lint): Fix ShellCheck lint diagnostics

---------

Co-authored-by: QuinnBot <[email protected]>

* fix: isolate review diffs and Herdr prompt parsing (#2)

* fix(watcher): preserve coalesced pause tracking

* no-mistakes(review): Preserve immediate gone-worker wake detection

* no-mistakes(review): Preserve pause-only signal handoffs

* no-mistakes(test): Fix C-locale Herdr composer detection

* no-mistakes(document): Document coalesced pause recovery

---------

Co-authored-by: nickespo7-del <[email protected]>

* feat: surface operations inbox events in session start and watcher wakes (#4)

* feat: surface operations inbox events

* no-mistakes(review): Harden ops inbox polling

* no-mistakes(review): Bound operations inbox polling

* no-mistakes(review): Harden operations inbox polling

* no-mistakes(review): Harden operations inbox polling

* no-mistakes(review): Captain: bound ops inbox marker traversal

* no-mistakes(review): Bound escaped operations inbox command capture

* no-mistakes(document): Document operations-inbox controls

* test: align ops inbox digest baseline

* fix: keep watcher dependencies fork-local

* fix: keep ops inbox signal output clean

---------

Co-authored-by: QuinnBot <[email protected]>

* fix(watcher): preserve coalesced pause handoffs

* fix(spawn): restore isolated Codex homes

* fix(spawn): resolve isolated CODEX_HOME to a real path for macOS (#6)

* fix(spawn): resolve isolated CODEX_HOME to a real path for macOS

* test(spawn): assert real-path CODEX_HOME activation contract

* style: apply formatter pass to fm-codex-home.py

---------

Co-authored-by: QuinnBot <[email protected]>

* Fix teardown landed-work safeguards (#7)

* Fix teardown landed-work safeguards

* no-mistakes(review): Harden teardown landing safeguards

* no-mistakes(review): Harden teardown cleanup safety

* no-mistakes(review): Captain: harden Orca spawn cleanup

* no-mistakes(review): Captain: harden cleanup safety

* no-mistakes(review): Fix cmux cross-window task discovery

* no-mistakes(review): Harden teardown ownership and legacy cleanup

* no-mistakes(test): Fix teardown lock and endpoint cleanup

* no-mistakes(test): Fix Herdr composer detection under C locale

* no-mistakes(document): Document teardown containment safeguards

---------

Co-authored-by: QuinnBot <[email protected]>

* test: cover legacy teardown task temp paths (#8)

Co-authored-by: QuinnBot <[email protected]>

* fix: absorb declared pauses at parked gates (#9)

* fix: absorb declared pauses at parked gates

* no-mistakes(document): Document parked-gate pause handling

---------

Co-authored-by: QuinnBot <[email protected]>

* fix(spawn): pin worktree-local git identity with Epstein boundary (#14)

* fix(bin): keep watcher supervision continuous across child cycles (kunchenguid#693)

* fix: make watcher supervision continuous

* no-mistakes(review): Bound watcher retries and log attached signals

* no-mistakes(review): Add bounded successor-recovery wake fallbacks

* no-mistakes(review): Prevent overlapping successor-arm retries

* no-mistakes(review): Resume supervision after late arm closes

* no-mistakes(review): Bind OpenCode recovery to attempted arm

* no-mistakes(test): Synchronize peer beacon regression fixture

* no-mistakes(test): Synchronize Pi and OpenCode late-close lifecycle fixtures

* no-mistakes(document): Captain: document watcher successor protocol behavior

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* fix: fetch current PR head for review diffs (kunchenguid#722)

* fix: always fetch PR head for review diffs

Prefer a freshly fetched refs/pull/<n>/head over a reachable recorded
pr_head= so reviewers never hold a merge over a "missing" fix that already
landed on the remote PR. Recorded SHA is offline fallback only; local branch
is last resort with a warning. Store the tip under refs/fm-review/ so a later
base-branch fetch cannot clobber the compare tip via FETCH_HEAD.

* no-mistakes(test): Isolate session-start nudge tests from gate state

* no-mistakes(document): Correct review-diff documentation

* Pin crew worktree git identities

* no-mistakes(review): Captain: retry shared Git config initialization

* no-mistakes(review): Normalize worktree config boolean handling

* no-mistakes(test): Captain, isolate review diffs from external renderers

* no-mistakes(lint): Silence unused retry loop variable

* no-mistakes(lint): Remove unused ShellCheck local

* test: align secondmate charter assertion

---------

Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: QuinnBot <[email protected]>

* feat(watch): escalate busy-looking zero-progress crews (#12)

* fix(bin): keep watcher supervision continuous across child cycles (kunchenguid#693)

* fix: make watcher supervision continuous

* no-mistakes(review): Bound watcher retries and log attached signals

* no-mistakes(review): Add bounded successor-recovery wake fallbacks

* no-mistakes(review): Prevent overlapping successor-arm retries

* no-mistakes(review): Resume supervision after late arm closes

* no-mistakes(review): Bind OpenCode recovery to attempted arm

* no-mistakes(test): Synchronize peer beacon regression fixture

* no-mistakes(test): Synchronize Pi and OpenCode late-close lifecycle fixtures

* no-mistakes(document): Captain: document watcher successor protocol behavior

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* fix: fetch current PR head for review diffs (kunchenguid#722)

* fix: always fetch PR head for review diffs

Prefer a freshly fetched refs/pull/<n>/head over a reachable recorded
pr_head= so reviewers never hold a merge over a "missing" fix that already
landed on the remote PR. Recorded SHA is offline fallback only; local branch
is last resort with a warning. Store the tip under refs/fm-review/ so a later
base-branch fetch cannot clobber the compare tip via FETCH_HEAD.

* no-mistakes(test): Isolate session-start nudge tests from gate state

* no-mistakes(document): Correct review-diff documentation

* Escalate busy crews with no progress

* no-mistakes(review): Captain: escalate AFK busy-progress wedges

* no-mistakes(review): Scope pane progress parsing to current footer

* no-mistakes(review): Captain: Harden busy-progress watcher safeguards

* no-mistakes(review): Captain: clear teardown busy-progress state

* no-mistakes(review): Harden busy-progress marker recovery

* fix: cache watcher busy state

* test: bound watcher cache cleanup

* no-mistakes(test): Captain: stabilize tmux smoke and review diffs

* no-mistakes(test): Captain: fix Herdr UTF-8 prompt classification

* no-mistakes(test): Captain: fix transient Herdr worktree detection

* no-mistakes(test): Fix checkpoint cleanup and spawn isolation

* no-mistakes(document): Document busy-progress watcher escalation

* test(brief): restore portable charter assertion

---------

Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: QuinnBot <[email protected]>

* fix(spawn): durable worktree leases prevent held-slot reallocation (#13)

* fix(bin): keep watcher supervision continuous across child cycles (kunchenguid#693)

* fix: make watcher supervision continuous

* no-mistakes(review): Bound watcher retries and log attached signals

* no-mistakes(review): Add bounded successor-recovery wake fallbacks

* no-mistakes(review): Prevent overlapping successor-arm retries

* no-mistakes(review): Resume supervision after late arm closes

* no-mistakes(review): Bind OpenCode recovery to attempted arm

* no-mistakes(test): Synchronize peer beacon regression fixture

* no-mistakes(test): Synchronize Pi and OpenCode late-close lifecycle fixtures

* no-mistakes(document): Captain: document watcher successor protocol behavior

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* fix: fetch current PR head for review diffs (kunchenguid#722)

* fix: always fetch PR head for review diffs

Prefer a freshly fetched refs/pull/<n>/head over a reachable recorded
pr_head= so reviewers never hold a merge over a "missing" fix that already
landed on the remote PR. Recorded SHA is offline fallback only; local branch
is last resort with a warning. Store the tip under refs/fm-review/ so a later
base-branch fetch cannot clobber the compare tip via FETCH_HEAD.

* no-mistakes(test): Isolate session-start nudge tests from gate state

* no-mistakes(document): Correct review-diff documentation

* fix: hold treehouse worktrees until teardown

* no-mistakes(review): rollback treehouse leases on spawn failures

* no-mistakes(review): recover stranded treehouse lease handoffs

* no-mistakes(review): Harden treehouse lease recovery

* fix: serialize treehouse lease handoffs

* fix: harden treehouse lease cleanup

* no-mistakes(review): Tombstone returned treehouse lease handoffs

* fix: harden treehouse teardown handoffs

* fix: ignore transient lease handoffs

* no-mistakes(test): Fix lease-aware test fixtures

* no-mistakes(test): Fix locale-safe composer and watcher races

* no-mistakes(test): Close AFK launcher signal race

* no-mistakes(document): Document durable treehouse task leases

* fix: preserve Orca abort cleanup through activation

* fix: retain fork charter portability updates

* test: model leased treehouse allocations in identity fixture

* fix: close failed spawn endpoint before lease return

* fix: retain committed lease on activation failure

* fix: retain recovery metadata after lease commit

* test: match durable lease handoff format

* test: retain committed lease after endpoint closure

* test: model absent endpoint in spawn abort fixture

* test: initialize fixture repositories on main

* fix: preserve durable returned lease tombstones

* fix: make leased spawn setup failures deterministic

* test: forward task temp failure injection

* ci: trace tangle guard hang

* test: make lease setup failure injection deterministic

* ci: allow bounded watcher lifecycle tests to finish

---------

Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: QuinnBot <[email protected]>

* fix(spawn): tolerate transient cwd reads and clean up refused spawns (#15)

* fix(bin): keep watcher supervision continuous across child cycles (kunchenguid#693)

* fix: make watcher supervision continuous

* no-mistakes(review): Bound watcher retries and log attached signals

* no-mistakes(review): Add bounded successor-recovery wake fallbacks

* no-mistakes(review): Prevent overlapping successor-arm retries

* no-mistakes(review): Resume supervision after late arm closes

* no-mistakes(review): Bind OpenCode recovery to attempted arm

* no-mistakes(test): Synchronize peer beacon regression fixture

* no-mistakes(test): Synchronize Pi and OpenCode late-close lifecycle fixtures

* no-mistakes(document): Captain: document watcher successor protocol behavior

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* docs: resolve five contract contradictions across AGENTS.md, README, and skills (kunchenguid#736)

* docs: resolve five contract contradictions

* no-mistakes(test): align owner-pointer assertions with reworded docs; skip absent shellcheck

* docs(harness): correct Grok exit guidance (kunchenguid#742)

* docs(harness): reverify grok exit command

* no-mistakes(test): Correct Grok exit resume attribution

* fix(spawn): tolerate transient worktree cwd

* no-mistakes(review): Guard leased worktree CWD resolution

* no-mistakes(test): Captain: synchronize secondmate charter role assertion

* no-mistakes(test): Stabilize Herdr heartbeat test waits

* no-mistakes(document): Document spawn isolation safeguards

* test: include lease helper in teardown fixture

---------

Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: Israel Wilson <[email protected]>
Co-authored-by: QuinnBot <[email protected]>

* Fix fail-closed fm-send delivery verification (#17)

* fix(bin): keep watcher supervision continuous across child cycles (kunchenguid#693)

* fix: make watcher supervision continuous

* no-mistakes(review): Bound watcher retries and log attached signals

* no-mistakes(review): Add bounded successor-recovery wake fallbacks

* no-mistakes(review): Prevent overlapping successor-arm retries

* no-mistakes(review): Resume supervision after late arm closes

* no-mistakes(review): Bind OpenCode recovery to attempted arm

* no-mistakes(test): Synchronize peer beacon regression fixture

* no-mistakes(test): Synchronize Pi and OpenCode late-close lifecycle fixtures

* no-mistakes(document): Captain: document watcher successor protocol behavior

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* fix: durable pause recognition across watcher restarts (#1)

* fix: prevent no-mistakes gate agents from driving the fleet (kunchenguid#518)

* feat: contain no-mistakes gate agents from driving the fleet

Add bin/fm-gate-refuse-lib.sh, sourced at the top of fm-spawn/fm-send/
fm-teardown before any fleet mutation. It fails closed when NO_MISTAKES_GATE
is set, and via an unspoofable git-common-dir backstop when invoked from a
no-mistakes gate worktree (.no-mistakes/repos/*.git) even with the marker
unset. A normal firstmate session has neither signal and is unaffected.

Set disable_project_settings: true in the tracked .no-mistakes.yaml so the
installed pipeline neutralizes gate agents' project instructions for this repo
(trusted-only, honored from the default branch).

firstmate's own suite runs from a gate worktree during validation, so the
shared test helpers set FM_GATE_REFUSE_BYPASS=1 to exempt it; the dedicated
tests/fm-gate-refuse.test.sh strips it to verify real refusal.

* no-mistakes(review): Captain, refuse empty no-mistakes gate markers

* no-mistakes(document): Document no-mistakes gate authority boundary

* fix: guard secondmate primary sessions from blind turn ends (kunchenguid#505)

* fix: guard secondmate own-home turn ends

Remove the .fm-secondmate-home early-exit in fm-turnend-guard.sh so the
'no turn ends blind' backstop fires in a secondmate's own primary session,
matching the cd-guard's scope: the own home is guarded, child crew/scout
worktrees stay exempt via the retained git-dir/git-common-dir test. This
was pure scoping from the guard's primary-only origin and guarded against
no secondmate-specific hazard.

Add secondmate regression tests (blind-turn block, idle-by-default,
stop_hook_active loop guard, deferred-death recovery loop, child-worktree
exemption) and record the autonomous background-notify re-invoke
measurement (Claude Code 2.1.207, 11s) in docs/turnend-guard.md.

* no-mistakes(document): Correct secondmate guard documentation, captain

* fix: force-include marked secondmate homes in turn-end guard

The prior remove-only form (just deleting the .fm-secondmate-home check)
left the DEFAULT secondmate topology unguarded: a treehouse-leased home is
a linked git worktree (git-dir != git-common-dir), which the retained
git-dir exemption still skipped, so its own primary session could still end
a turn blind. Invert the marker: a genuinely-marked home is force-included
as a guarded primary (treehouse-leased linked OR git-cloned plain), and the
git-dir exemption applies only to UNMARKED child worktrees. Marker
validation (regular non-symlink file, non-empty id-token content) blocks a
stray or empty marker from spoofing inclusion.

Add real linked-worktree regression tests: a treehouse-leased LINKED
secondmate home is guarded, a stray/empty marker stays exempt, and the
unmarked child worktree stays exempt - the topology the plain git-init
fixtures masked. Predicates, in-flight gate, and loop guard untouched.

* fix: force ASCII collation in secondmate marker validation

Add a function-scoped local LC_ALL=C in fm_root_is_secondmate_home so the
[A-Za-z0-9._-] id allowlist matches under C collation, not the ambient
locale - a locale-crafted non-ASCII marker id can no longer slip through
the range match and spoof force-inclusion of a linked child worktree.
Add a regression test proving a non-ASCII marker id is rejected and the
linked worktree stays exempt.

* no-mistakes(test): fix backend baseline gate-refusal dependency

* no-mistakes(document): Correct secondmate turn-end guard documentation

* fix: make bootstrap diagnostics backend-aware (kunchenguid#519)

* fix: make bootstrap required-tool detection backend-aware

Bootstrap demanded tmux and treehouse for every backend except orca, so a
herdr/zellij/cmux home with tmux absent was wrongly told MISSING: tmux.

Required tools now follow the resolved backend via the single-owner
fm_backend_required_tools helper (bin/fm-backend.sh): each backend's own
session-provider CLI, jq for the JSON-emitting adapters (herdr/zellij/cmux),
and treehouse for session-provider-only backends (orca owns its worktree).
The treehouse lease-support check is gated to backends that use treehouse.

Adds install hints for herdr/zellij/cmux, regression tests for the full
backend dependency matrix (herdr-without-tmux repro plus each boundary),
and updates the authoritative Toolchain docs.

* no-mistakes(review): Captain, prevent executing Herdr install guidance

* no-mistakes(review): Captain, harden backend-aware bootstrap diagnostics

* no-mistakes(review): Captain, separate manual dependency remediation

* no-mistakes(review): Captain, align bootstrap diagnostic consumers

* no-mistakes(document): Align backend adapter dependency comments

* fix: preserve follow-up platform context after inbox cleanup (kunchenguid#520)

* fix: recover X/Discord follow-up platform after inbox cleanup

A milestone follow-up posted directly by request_id after the inbox was
drained - and with no task link, because one persistent secondmate's single
x_request slot collides across concurrent requests - resolved platform only
from the local inbox, so a >280 Discord reply silently defaulted to the X
280-char budget and threaded as (1/2).

- fm-x-poll records a durable per-request reply context
  (state/x-context/<rid>.json) at stash time, keyed by request_id so
  concurrent requests never overwrite each other; it survives inbox cleanup
  and restart.
- fm-x-reply resolves platform/budget through registry -> inbox -> relay
  (the relay lookup confined to a live follow-up), recovering the original
  platform independent of task-link availability.
- Fail-safe: a follow-up whose platform/budget cannot be authoritatively
  resolved and that would split is refused (exit 8) and held for retry,
  never wrongly split; fm-x-followup keeps the link on that exit.
- fm-x-dismiss clears the durable context for a dismissed mention.

Refactors reply-context extraction into a single owner and adds regression
coverage for all four cases.

* no-mistakes(review): Captain, fail closed on incomplete follow-up context

* no-mistakes(review): Captain, bound X context registry retention

* no-mistakes(review): Captain, align context retention with answer binding

* no-mistakes(document): Align X follow-up context documentation

* no-mistakes(document): Align durable X follow-up documentation

* fix: preserve secondmate routing markers in terminal sends (kunchenguid#533)

* fix: preserve secondmate routing markers

* no-mistakes(review): Captain, preserve trailing newlines in marked secondmate sends

* no-mistakes(test): Captain, tolerate bootstrap timeout elapsed drift

* no-mistakes(document): Refresh Herdr marker documentation

* fix: align Grok effort handling with 0.2.99 (kunchenguid#527)

* fix: align grok effort docs and spawn with 0.2.99 ceiling

grok 0.2.99 accepts only low|medium|high for --reasoning-effort and
rejects both xhigh and max. Omit unsupported values on spawn, flag them
in crew-dispatch validation, and update harness-adapters.

* no-mistakes(test): Captain: refresh gotmp teardown fixture dependencies

* no-mistakes(document): Clarify Grok effort documentation ownership

* fix: preserve declared pauses across watcher restarts

* no-mistakes(review): Preserve unknown-state stale wake safety

* no-mistakes(test): Stabilize PR review diffs

---------

Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: Korallis <[email protected]>
Co-authored-by: nickespo7-del <[email protected]>

* fix(herdr): distinguish submitted codex redraws

* no-mistakes(review): Harden Herdr submit and nested inbox detection

* no-mistakes(review): Harden Herdr confirmation and Codex activation

* no-mistakes(review): Track all operations inbox events

* no-mistakes(review): Captain: harden activation and bound inbox polling

* no-mistakes(review): Captain: harden activation, cleanup, and inbox markers

* no-mistakes(review): Harden activation and bound inbox scans

* no-mistakes(review): Prevent capped inbox runners resetting deadlines

* no-mistakes(review): Harden submit verification and cleanup recovery

* no-mistakes(test): Preserve pause recheck grace

* no-mistakes(document): Document operations-inbox scan bounds

* no-mistakes(lint): Remove unused Herdr scan variable

* test(orca): align abort cleanup fixture

* no-mistakes(review): Fix Codex home cleanup identity arguments

* no-mistakes(review): Harden failed-spawn cleanup safety

* no-mistakes(review): Harden cleanup safety, captain

* no-mistakes(review): Fail closed unknown Herdr preflight

* no-mistakes(test): Fix teardown patch equivalence and OpenCode lock race

* no-mistakes(test): Captain: align teardown tests with lock preflight

* no-mistakes(document): Document submit and failed-spawn safeguards

* fix(teardown): honor checkout default branch

* no-mistakes(review): Harden teardown and inbox fingerprinting

* no-mistakes(review): Bound ops inbox fingerprint scans

* no-mistakes(review): Harden spawn cleanup and inbox overflow detection

* no-mistakes(review): Stabilize overflowed inbox fingerprints

* no-mistakes(review): Harden leased spawn cleanup and watcher reaping

* no-mistakes(review): Captain: harden treehouse lease cleanup validation

* no-mistakes(review): Guard treehouse leases against active worktree collisions

* no-mistakes(test): Update spawn test fakes for verified treehouse leases

* no-mistakes(document): Document strict spawn isolation and watcher timeout reaping

* test(orca): preserve fixture default branch

* no-mistakes(review): Captain: fail closed on unconfirmed submits

* no-mistakes(review): Require confirmed Orca terminal absence before teardown

* no-mistakes(review): Preserve Orca resources without terminal confirmation

* no-mistakes(review): Captain: Preserve leases pending endpoint confirmation

* no-mistakes(review): Preserve confirmed Orca terminal absence

* no-mistakes(review): Honor confirmed Orca terminal absence

* no-mistakes(review): Harden fm-send and Orca cleanup

* no-mistakes(review): Harden backend agent liveness and Orca recovery

* no-mistakes(review): Fail closed without native backend liveness

* no-mistakes(review): Captain: harden explicit target liveness

* no-mistakes(test): Fix fm-send test liveness fixtures

* no-mistakes(test): Preserve endpoints on failed worktree cleanup

* no-mistakes(test): Return lease before failed Codex activation cleanup

* no-mistakes(document): Document fail-closed steering and teardown safety

* no-mistakes(review): Fail closed on unverified Python liveness

* fix(orca): retain abort cleanup state

* fix(orca): preserve abort cleanup safety

* test(send): model a live tmux agent

* test(codex): keep activation fixture alive

* fix(teardown): check locks before safety approval

---------

Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: Korallis <[email protected]>
Co-authored-by: nickespo7-del <[email protected]>
Co-authored-by: QuinnBot <[email protected]>

* fix(watch): sync fork with upstream through 4ab61fa, fix pause-liveness merge regression (#18)

* fix(bin): keep watcher supervision continuous across child cycles (kunchenguid#693)

* fix: make watcher supervision continuous

* no-mistakes(review): Bound watcher retries and log attached signals

* no-mistakes(review): Add bounded successor-recovery wake fallbacks

* no-mistakes(review): Prevent overlapping successor-arm retries

* no-mistakes(review): Resume supervision after late arm closes

* no-mistakes(review): Bind OpenCode recovery to attempted arm

* no-mistakes(test): Synchronize peer beacon regression fixture

* no-mistakes(test): Synchronize Pi and OpenCode late-close lifecycle fixtures

* no-mistakes(document): Captain: document watcher successor protocol behavior

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* fix: fetch current PR head for review diffs (kunchenguid#722)

* fix: always fetch PR head for review diffs

Prefer a freshly fetched refs/pull/<n>/head over a reachable recorded
pr_head= so reviewers never hold a merge over a "missing" fix that already
landed on the remote PR. Recorded SHA is offline fallback only; local branch
is last resort with a warning. Store the tip under refs/fm-review/ so a later
base-branch fetch cannot clobber the compare tip via FETCH_HEAD.

* no-mistakes(test): Isolate session-start nudge tests from gate state

* no-mistakes(document): Correct review-diff documentation

* docs: resolve five contract contradictions across AGENTS.md, README, and skills (kunchenguid#736)

* docs: resolve five contract contradictions

* no-mistakes(test): align owner-pointer assertions with reworded docs; skip absent shellcheck

* docs(harness): correct Grok exit guidance (kunchenguid#742)

* docs(harness): reverify grok exit command

* no-mistakes(test): Correct Grok exit resume attribution

* fix(watcher): bound stale wakes for parked crew (kunchenguid#743)

* fix(watcher): bound stale wakes for exited paused crew

* no-mistakes(review): Gate pause suppression on confirmed agent death

* no-mistakes(test): Fixed stale pause cadence

* no-mistakes(document): Document dead-agent hold cadence

* fix(supervision): distinguish ordinary wakes from recovery (kunchenguid#744)

* fix(supervision): distinguish ordinary wakes from repair

* no-mistakes(review): Make passive guard follow-ups recovery-only

* no-mistakes(document): Clarify recovery-only turn-end guard documentation

* fix(x-mode): dedupe pending mention wakes (kunchenguid#745)

* fix(x-mode): dedupe pending mention wakes

* no-mistakes(review): fix x-poll claim error deduplication

* no-mistakes(review): separate claim diagnostics from relay recovery

* no-mistakes(document): Document X-mode once-only mention wakes

* feat(wake): enrich drained signals with bounded status context (kunchenguid#747)

* feat(wake): enrich drained signal context

* no-mistakes(review): Bound wake enrichment reads

* no-mistakes(document): Document wake-drain annotations

* docs(wake): explain at-least-once drain boundary

* no-mistakes(review): Prevent symlink races in wake annotations

* no-mistakes(review): Exercise wake symlink race regression

* test: document intentional AFK marker subprocesses

* fix(wake): isolate annotation marker state

* fix(watch): resolve fork/upstream pause-liveness merge conflict; add divergence runbook

The fork/upstream sync merge (67c79e2) combined pause_state_class's parked-gate
override (fork-local) with the new exited-agent liveness gate (upstream) in a
way that was syntactically clean but behaviorally wrong: any class=paused
verdict, including a plain authoritative "state: paused" read, was silently
downgraded to none whenever the agent wasn't CONFIRMED dead - even for
"unknown" liveness, which must never license an action on its own. Split
crew_absorb_class into a line-based classifier shared with pause_state_class
so the parked-gate-override case can bypass the liveness gate entirely (an
explicit declaration is authoritative) while a confirmed-live agent at a
plain "paused" read still gets a fresh surface, and unknown liveness keeps
trusting whatever classification already stood. Full fm-watch-triage suite
(56 tests) now passes clean.

Also adds docs/fm-main-divergence/runbook.md: the verified, exercised
command sequence for hard-aligning the primary checkout's local main to
fork/main once this branch merges, plus the audit proving no local-only
content is at risk and a root-cause note on why /updatefirstmate's
base_mode="origin" never pulls fork-only merges.

* no-mistakes(review): Captain: refresh fork tracking refs

* no-mistakes(review): Reclaim orphaned Treehouse handoff writer files

* no-mistakes(review): Recover X-mode wakes

* docs: fail closed on runbook fetches

* no-mistakes(test): Captain: restore second mate charter role

* no-mistakes(document): Document paused wake recovery

---------

Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: Israel Wilson <[email protected]>
Co-authored-by: QuinnBot <[email protected]>

* fix: harden watcher arm relay leases

* no-mistakes(review): Harden relay leases and cleanup identity

* no-mistakes(review): Harden tmux ownership and review remote selection

* no-mistakes(review): Harden watcher relay and tmux recovery safety

* no-mistakes(test): Fix strict target-validation test fixtures

* no-mistakes(document): Document relay lease hardening

* no-mistakes(lint): Fix relay lease lint warnings

* fix: reject symlinked Codex roots before spawn metadata

* fix: reject symlinked Codex root before metadata

* no-mistakes(review): Harden relay leases and normalize PR remotes

* no-mistakes(test): Fix malformed tangle guard test fixtures

* no-mistakes(document): Document watcher and daemon lease lifecycle

* fix: preserve pre-metadata spawn refusal

* no-mistakes(test): Preserve failed lease metadata and attached arm lifecycle logs

* no-mistakes(review): Fix shared PR review fetch ref

* no-mistakes(review): Harden daemon lease ownership handoff

* no-mistakes(review): Harden stale daemon lease recovery and arm tick validation

* no-mistakes(review): Fence stale AFK lease recovery

* no-mistakes(review): Fence watcher identity lease publication

* docs: retain wake drain annotations

* fix: preserve spawn refusal metadata boundary

* fix: retain prepublication spawn rollback

* test: model stable tmux endpoint cleanup

* fix: retain prelaunch endpoint recovery state

* fix: preserve watcher lease handoffs

* no-mistakes(review): Harden tmux ownership and review remote selection

* no-mistakes(test): Fix strict target-validation test fixtures

* no-mistakes(document): Document relay lease hardening

* no-mistakes(test): Fix malformed tangle guard test fixtures

* fix: preserve pre-metadata spawn refusal

* no-mistakes(test): Preserve failed lease metadata and attached arm lifecycle logs

* no-mistakes(review): Harden stale daemon lease recovery and arm tick validation

* no-mistakes(review): Fence stale AFK lease recovery

* no-mistakes(review): Guard reclaimed AFK launcher locks

* no-mistakes(review): Harden relay and launcher lease races

* no-mistakes(document): Document daemon lease recovery grace

* no-mistakes(lint): Isolate lease test helper shells

* no-mistakes(review): Publish lease before watcher binding

* no-mistakes(test): Fix watcher and Herdr teardown regressions

* no-mistakes(test): Fix watcher and Codex activation test fixtures

* no-mistakes(test): Preserve paused recovery across watcher restarts

* no-mistakes(test): Remove duplicate pause-liveness test invocation

* no-mistakes(test): Fix attached arm lifecycle ledger race

* no-mistakes(document): Document lease and Git identity helpers

* no-mistakes(lint): Resolve ShellCheck warnings in lease regression tests

* no-mistakes(review): Reclaim reused watcher locks during normal arm

* no-mistakes(review): Fence watcher lock reclaim race

* fix: fence watcher restart reclaim

* no-mistakes(review): Fence arm lease release by owner PID

* no-mistakes(document): Correct operations inbox and relay lease docs

* no-mistakes(lint): Remove unused treehouse lease assignment

* no-mistakes(lint): Captain: remove unused treehouse lease assignment

* fix(spawn): preserve prepublication refusal boundary

* test(spawn): model stable tmux cleanup identity

* test(spawn): cover stable data-root refusal cleanup

* test(spawn): cover stable abort cleanup paths

* test(spawn): model stable isolation cleanup

* fix(watch): surface attached relay handoff failures

---------

Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: Israel Wilson <[email protected]>
Co-authored-by: QuinnBot <[email protected]>
Co-authored-by: nickespo7-del <[email protected]>
Co-authored-by: Korallis <[email protected]>
vitalNohj added a commit to vitalNohj/firstmate that referenced this pull request Jul 24, 2026
* feat(pi): simplify primary session launch (#386)

* docs(readme): reformat Quick Start and recommend Grok equally with Claude Code

* no-mistakes(review): Captain: align harness launch guidance

* no-mistakes(review): Captain, clarify Pi supervised launch

* no-mistakes(review): Captain, document Pi first-launch bridge

* feat(pi): track primary watcher extension for plain-pi launch

Move Pi's primary watcher bridge from a generated state/ file to a
tracked .pi/extensions/fm-primary-pi-watch.ts, matching how the turn-end
guard extension already works: self-hashing version, project-local
auto-discovery after one-time Pi trust. This drops the state/-generation
step and dual -e requirement from the happy path, so Pi's Quick Start
launch becomes plain 'pi', the same friction class as 'claude' and
'grok --trust'.

- bin/fm-pi-watch-extension.sh is removed; nothing generates the
  extension anymore since it is committed.
- fm-session-start.sh and fm-supervision-instructions.sh resolve the
  watcher extension path from FM_ROOT instead of state/, and the
  session-start diagnostic now points at restarting plain pi after
  trust, with -e as a documented fallback.
- fm-spawn.sh points Pi secondmate launches at the tracked extension
  path in the secondmate home instead of generating a state/ copy.
- README Quick Start Pi block is now just 'pi' plus a trust note.
- Tests, docs, and the harness-adapters skill updated to match.

* fix(pi): drop backticks from session-start diagnostic to satisfy shellcheck SC2016

* feat(supervision): prevent unsafe watcher-arm commands (#387)

* feat(supervision): add PreToolUse seatbelt against watcher-arm anti-patterns

Adds bin/fm-arm-pretool-check.sh, a shared PreToolUse-style checker that
denies a primary shell command backgrounding, piping, or bundling the
watcher arm/checkpoint, or force-killing the watcher process broadly -
the exact shapes that silently took Grok's supervision down. Wires it
into all five verified harnesses (grok, claude, codex, opencode, pi),
each validated empirically against the real harness.

Also fixes a grok 0.2.93 regression discovered during that validation: the
existing turnend-guard Stop hook's bare root variable broke grok's own
variable pre-substitution and silently no-op'd the hook.

* no-mistakes(review): Harden watcher arm validation

* no-mistakes(review): Harden arm guard metacharacter checks

* no-mistakes(review): Harden nested shell arm guard

* fix(lint): rewrite SC2015 guards in fm-arm-pretool-check.sh as if/then

A && B || C is not if-then-else; C can run when A is true. Replace both
occurrences of the quote-state early-continue with an explicit if/then.

* fix(pi): restore primary watcher supervision lifecycle (#397)

* fix Pi primary supervision lifecycle

* no-mistakes(document): Synchronize Pi primary extension documentation

* fix: keep persistent secondmates out of the main backlog (#398)

* fix secondmate backlog guidance

* no-mistakes(review): Require reasons for captain backlog holds

* no-mistakes(test): Document secondmate handoff skill requirement

* fix secondmate teardown reminder

* no-mistakes(document): sync teardown reminder docs to work-items-only backlog contract

* fix(backlog-handoff): move full item blocks including indented bodies (#401)

* fix(backlog-handoff): move full item blocks including indented bodies

fm-backlog-handoff only moved the checklist header line, so multi-line
item bodies were left orphaned in the source backlog and never reached
the secondmate. Move the full block (header plus indented body lines)
atomically, treating body membership by indentation so lines like
## Intent stay with the item, and add regression coverage.

* no-mistakes(review): Captain: preserve EOF handoff terminators

* no-mistakes(review): treat blank lines inside item bodies as movable body

* no-mistakes(document): sync backlog-handoff docs with full-block move behavior

* feat(herdr): make Herdr lab lifecycle safety deterministic for briefs (#402)

* guard Herdr lab lifecycle in briefs

* no-mistakes(review): Fix Herdr lab helper and provisioning safety

* no-mistakes(review): Captain, harden Herdr lab lifecycle safety

* no-mistakes(review): fix Herdr lab test cleanup ordering and brief help range

* no-mistakes(review): reject leading options in Herdr lab run guard

* no-mistakes(review): strip leading non-alnum in Herdr lab name generator

* no-mistakes(document): document Herdr lab helper and --herdr-lab brief flag

* no-mistakes(lint): add shellcheck disable for deliberate SC2016 literals in fm-brief herdr-lab

* no-mistakes: apply CI fixes

* fix(watcher): classify arm-command seatbelt by execution position (#403)

* fix watcher arm command policy

* no-mistakes(review): Harden watcher command policy parsing

* no-mistakes(review): Captain: harden watcher policy parsing

* no-mistakes(review): harden watcher policy for expanded paths, direct-watch, and sound prefilter

* no-mistakes(review): close prefilter and classifier locale/ANSI-C watcher-path decode gaps

* no-mistakes(review): fail closed on loop-wrapped broad watcher kills

* no-mistakes(document): sync docs for watcher-arm command-position policy

* fix: reconcile existing AGENTS.md safely (#405)

* fix(agents-md): inject self-governance section into existing AGENTS.md

fm-ensure-agents-md.sh only appended the canonical "## Maintaining this
file" section on skeleton create or CLAUDE.md promotion, so an existing
AGENTS.md that lacked it exited unchanged and forced hand-copying the
wording during a rollout across existing projects. Call the already-
idempotent ensure_maintenance_section on the existing-AGENTS.md paths and
report whether the file changed; a re-run and an already-complete file stay
byte-identical.

Also fixes #389: refuse a case-variant real memory file (e.g. a lowercase
agents.md) instead of silently emitting a CLAUDE.md symlink whose uppercase
literal target dangles once the tree lands on a case-sensitive filesystem.

Tests extend tests/fm-ensure-agents-md.test.sh; skeleton-create and
CLAUDE.md-promotion regressions still pass. Docs updated to match.

* no-mistakes(review): Captain: preserve CRLF maintenance-section idempotency

* no-mistakes(review): Preserve CRLF during maintenance-section injection

* no-mistakes(review): Captain: harden dangling-symlink regression coverage

* no-mistakes(document): Document agent-memory injection outcomes

* feat: support project-less secondmate homes (#409)

* feat(secondmate): support project-less homes via --no-projects

fm-brief.sh --secondmate and fm-home-seed.sh now accept an explicit
--no-projects signal to scaffold, seed, and register a secondmate home
whose subject is the firstmate repo itself (no clones). The signal is
mutually exclusive with a project list; omitting both still fails loudly
so an accidental omission is never a silent project-less seed. The
registry line renders an empty projects: field, which spawn and the
snapshot already tolerate. Docs updated in the secondmate-provisioning
skill and both script headers.

* no-mistakes(review): Captain: document project-less secondmate flow

* no-mistakes(review): Captain: refuse project-less reseeding of populated homes

* fix(seed): fail closed on unreadable project data

* no-mistakes(review): Captain: reject stale projectful charters

* no-mistakes(review): Captain: fail closed on unsafe project paths

* no-mistakes(review): Captain: validate project-less charter clone sections

* no-mistakes(document): Document project-less secondmate seeding

* fix: delegate backlog handoffs to tasks-axi (#411)

* wip(handoff): record verified delegation design + tasks-axi mv blocker

No production code changed yet. tasks-axi mv (v0.2.1) cannot atomically
move a blocked-by-linked item set across backlogs (deadlocks both orders,
no batch/--force), which fm-secondmate-lifecycle-e2e requires. Parked
pending a tasks-axi connected-set mv enhancement; note captures the
verified design, semantics, test/CI/doc changes, and resume checklist.

* refactor(handoff): delegate the item move to tasks-axi mv

fm-backlog-handoff.sh's two-pass awk was a second parser of the backlog
format and the source of the PR #401 body-orphaning drift. Delete it and
delegate the move to `tasks-axi mv <id>... --to <dest>` (v0.2.2 atomic
multi-id), the single owner of the format: a connected set (blocker plus
dependents) moves together with blocked-by preserved, item blocks stay
byte-exact, and destination section placement holds. The helper keeps only
the fleet-level validation tasks-axi cannot know - secondmate-home
resolution, the seeded-home safety checks, the In-flight refusal, and
idempotent per-key reporting - and is atomic: on any move failure nothing
moves.

Tests: fm-backlog-handoff.test.sh keeps PR #401's regression matrix but now
exercises the delegated path and skips cleanly when tasks-axi is absent; the
two whole-file fixtures move to tasks-axi's canonical whitespace. The
lifecycle-e2e and safety move-cases gain the same skip guard. CI installs
tasks-axi so the delegated path is exercised. Docs state that
config/backlog-backend=manual governs firstmate's own hand-editing, not this
validated helper, which delegates fleet-wide because bootstrap requires
tasks-axi on PATH.

Remove the now-redundant WIP design note.

* no-mistakes(review): Captain: harden atomic backlog handoffs

* no-mistakes(review): Captain: enforce queued-only backlog handoffs

* no-mistakes(review): Captain: harden handoff section parsing

* no-mistakes(document): Document delegated backlog handoffs

* no-mistakes(lint): Silence ShellCheck source diagnostics

* fix: ignore secondmate home marker during sync (#417)

* fix: gitignore the secondmate home marker

bin/fm-home-seed.sh writes an untracked .fm-secondmate-home marker into
every seeded secondmate home. A secondmate home is a worktree of the
firstmate repo, so any plain `git status --porcelain` dirtiness check
counted the untracked marker and the home read as dirty forever:
fleet-sync reported it STUCK and the local fast-forward convergence
sweeps risked leaving it stale on firstmate updates.

Add .fm-secondmate-home to the tracked .gitignore so the marker is
invisible to every dirtiness check uniformly, without weakening
fleet-sync's deliberate untracked-counting for project clones.

Convergence chicken-and-egg: existing homes predate the fix and it only
arrives by fast-forward. The already-present marker-tolerant ff-skip
(ignore_seed_marker=yes, used by the bootstrap sweep, /updatefirstmate,
and spawn pre-launch) advances such a home past the fix commit, after
which .gitignore takes over - no hand intervention.

Tests in tests/fm-secondmate-sync.test.sh cover a freshly seeded home
reading clean, an existing marker-only home converging then reading
clean, and a genuinely dirty home still skipping.

* no-mistakes(review): Captain: document standalone-clone update path

* no-mistakes(document): Document secondmate marker migration

* fix(composer): prevent dead-shell message injection (#416)

* fix(composer): stop reading dead-shell prompts as empty agent composers

Consolidate composer empty/pending/unknown classification into one shared
owner, bin/fm-composer-lib.sh's fm_composer_classify_content, delegated to by
all four backend adapters (tmux via fm-tmux-lib.sh, herdr, orca, cmux). This
replaces four drifting copies of the glyph decision.

Safety fix: a bare shell prompt glyph (> $ % #) on an unstructured row is now
classified unknown (a dead shell, unsafe for injection), not empty. It is only
empty inside a bordered composer box (the harness's own prompt). Agent glyphs
❯ (claude) and › (codex) read empty either way. The away-mode injector
(inject_msg) now requires an affirmatively-empty composer, deferring on pending
or unknown, so an escalation can never be typed into (or executed by) a pane
whose agent exited to its login shell.

Regression coverage: new tests/fm-composer-lib.test.sh pins the shared owner;
per-backend dead-shell tests in fm-daemon (tmux + injector), orca, and the
existing herdr/cmux suites. shellcheck clean; herdr incident regressions stay
green.

* no-mistakes(review): Captain: harden composer safety checks

* no-mistakes(test): Stabilize Herdr prune safety setup

* no-mistakes(document): Document composer injection safety

* no-mistakes(lint): Clean composer safety lint

* no-mistakes: apply CI fixes

* feat(watcher): add paused external-wait supervision (#421)

* feat(watcher): add paused/awaiting-external crew state

A crew (or firstmate steering it) can declare a deliberate wait on a known
external dependency with a paused: <reason> status. Both the always-on watcher
and the away-mode daemon absorb such an idle pane through shared fm-classify-lib.sh
vocabulary instead of tripping the possible-wedge stale escalation, and re-surface
it for a recheck only on a long bounded cadence (FM_PAUSE_RESURFACE_SECS) so a
forgotten pause cannot rot invisibly. fm-crew-state.sh reports state: paused
distinctly. A crew that goes idle without declaring a pause classifies exactly as
before. Docs and brief scaffold state lists updated; tests colocated.

* no-mistakes(review): Captain: fix paused-state transitions

* init

* no-mistakes(review): Captain: fix paused-state supervision transitions

* no-mistakes(review): Captain: fix paused supervision handoffs

* no-mistakes(review): Reconcile paused supervision markers

* no-mistakes(review): Captain: prioritize paused states over captain relevance

* no-mistakes(review): Captain: preserve paused-working wedge timer

* no-mistakes(review): Captain: honor configured pause verb in briefs

* no-mistakes(test): Captain: fix AFK paused watcher handoff

* no-mistakes(document): Document declared external waits

* no-mistakes(lint): Clean paused-state lint

---------

Co-authored-by: fmtest <[email protected]>

* fix: preserve X-mode follow-up platform limits (#425)

* fix(x-mode): make follow-up platform splitting immune to link ordering

A ~470-char Discord follow-up posted as a (1/2)(2/2) thread split at ~280
chars because fm-x-link only learned the platform from the inbox payload,
and the fmx-respond ack path can drain that inbox file before the task is
linked. A link recorded after cleanup silently lost the platform and the
splitter defaulted to the X 280-char budget.

Make platform resolution ordering-proof:

- fm-x-link now resolves the platform AUTHORITATIVELY by request_id via a
  new fmx_request_relay_context helper (POST /connector/request-context)
  when neither the inbox payload nor carry flags carry it. The request_id
  survives the inbox drain, so a post-cleanup link still learns the right
  split budget. Best-effort: no token/curl or a non-2xx relay degrades to
  the loud warning below rather than a silent X default.
- fm-x-link warns loudly when no platform source resolves, so the loss is
  never silent.
- The fmx-respond procedure now orders link-before-inbox-cleanup so the
  fast local path stays correct without a relay round-trip.

Colocated regression tests: a Discord follow-up >280 <2000 posts as ONE
message even when linked after inbox cleanup, and an unresolvable platform
warns loudly instead of splitting silently. docs/configuration.md documents
the request-context lookup.

The relay endpoint is the companion durable change (see done status); until
it ships, the link-before-cleanup reorder keeps the normal path correct.

* no-mistakes(document): Document X-mode platform recovery

* fix(composer): handle ANSI ghost text safely (#429)

* fix(composer): one ANSI-aware ghost owner covers claude dim + grok truecolor

Away-mode injection wedged all night on the primary claude-on-herdr pane:
the herdr composer classifier never stripped generic dim ghost text (only a
narrow codex bold-wrapped byte-pattern check), so claude's rotating
prompt-suggestion ghost - a bare "❯" then SGR-2 dim text, which herdr's ANSI
pane read preserves - read as real pending input and every escalation deferred
(6524 lifetime "pending input (non-empty composer)" defers; wedge 30623s).

Consolidate ghost extraction into one fleet-wide ANSI-aware owner,
fm_composer_strip_ghost (bin/fm-composer-lib.sh), that drops every
de-emphasised run - dim/faint (SGR 2: claude, codex) AND a dark/muted truecolor
foreground (grok's placeholder, luminance below FM_COMPOSER_GHOST_LUMA_MAX,
default 128, dark-theme assumption). Both ANSI-capable backends route through
it: fm_tmux_composer_state (fm_tmux_strip_ghost is now a thin adapter) and
fm_backend_herdr_composer_state. The herdr-only faint byte-pattern check is
removed and fm_backend_herdr_strip_ansi reduced to a thin adapter over the
shared fm_composer_strip_ansi. Bordered detection now reads the plain row so a
dark box border dropped with the ghost does not lose the composer shape.

This also closes the documented grok TRUECOLOR placeholder gap by the same
mechanism (harness-adapters skill note updated).

Empirical evidence (read-only live capture + isolated tmux, no herdr lifecycle)
and the incident write-up are in docs/herdr-backend.md; deterministic
regressions feed the exact captured bytes through the real classifiers
(tests/fm-backend-herdr.test.sh, tests/fm-composer-ghost.test.sh). Two prior
ghost-test fixtures that used a near-black 38;2;1;2;3 as "real" colored text
(never a realistic real-input color) are corrected to a bright 38;2;224;222;244,
preserving the truecolor payload-skip parser intent.

* no-mistakes(review): Preserve dark shell prompt safety

* no-mistakes(review): Harden erased shell prompt classification

* no-mistakes(document): Document shared composer ghost extraction

* no-mistakes(lint): Normalize tmux comment punctuation

* fix(spawn): make tmux window handling robust under non-default config (#134)

* test: isolate session-start suite from ambient harness markers (#432)

* fix(session-start): isolate harness env markers in suite runner

Neutralize CLAUDECODE, PI_CODING_AGENT, and GROK_AGENT in
run_session_start so ambient interactive shells cannot override the
suite's fake ps harness (local-vs-CI split on the pi supervision case).

* no-mistakes(document): Correct Pi marker documentation

* fix(teardown): retry transient index locks during worktree return (#435)

* fix(teardown): retry treehouse return on transient index.lock

Killed crew git ops can leave a short-lived worktree index.lock that
makes treehouse return fail. Retry on that error signature with a
bounded wait (env-overridable), never force-delete a live lock, and
only then fall back to the existing provably-stale cleanup path.

* no-mistakes(review): Harden teardown retry configuration

* no-mistakes(document): Document teardown index-lock retry behavior

* no-mistakes(lint): Fix empty shell variable assignments

* fix: complete brief help and consolidate documentation (#438)

* docs: de-feature the scripts.md and CONTRIBUTING test inventories

Slice 1 of the documentation redundancy cleanup wave (firstmate scope).

docs/scripts.md: every row is now one purpose clause; script headers
are the declared owner of behavior, flags, and contracts. Coverage
stays 61/61 scripts; bytes drop 19,922 -> 7,958.

CONTRIBUTING.md: the 54-row per-test inventory is gone; contributors
discover tests by listing tests/*.test.sh and reading each script's
own header, and gated tests print their own skip gates. The run
commands, symlink assertions, and watcher smoke line are unchanged.
Lines drop 135 -> 84 (18,797 -> 7,831 bytes).

Two facts that existed only as inventory rows moved into their
owners' headers first: fm-brief.sh's paused-vs-blocked scaffold
distinction and fm-session-start.sh's Pi extension-loaded check.

No instruction-surface or behavior change; AGENTS.md untouched.

* no-mistakes(review): Captain, fix brief help and Grok test discovery

* no-mistakes(review): Captain: document Grok lock-holder test coverage

* fix: detect Git and centralize backend configuration (#445)

* docs: consolidate universal backend contracts into configuration.md

Slice 2 of the documentation redundancy cleanup wave (firstmate scope).

docs/configuration.md is now the declared single owner of three
universal contracts, each with an explicit ownership sentence:
- the universal toolchain list (Toolchain), now also carrying the
  per-tool purpose clauses that previously lived only in the tmux guide;
- the task-selector vocabulary (Runtime backend);
- the tasks-axi compatibility definition (Backlog backend).

The five backend guides' prerequisites replace their verbatim
universal-requirements parentheticals (5 full copies) with a pointer
plus only backend-specific items; zellij/cmux selector restatements
and architecture.md's partial copy become pointers or are dropped;
CONTRIBUTING's compatibility sentence becomes a pointer; two
near-verbatim orca-bootstrap restatements (configuration.md Runtime
backend, orca guide) collapse into the Toolchain owner copy.

Backend-specific setup, behavior, target-string shapes, and every
empirical verification record are untouched. AGENTS.md untouched
(slice 3).

* docs: include git and GitHub auth in the toolchain owner list

The review flagged that the new universal-toolchain owner omitted git
and GitHub authentication while every backend guide now defers its
prerequisites here; bootstrap's NEEDS_GH_AUTH check makes them real
universal requirements.

* no-mistakes(review): Detect Git in bootstrap toolchain

* no-mistakes(document): Clarify GitHub CLI and centralize selector documentation

* feat(daemon): add backend-independent wedge alerts (#444)

* feat(daemon): backend-independent active alert for the wedge alarm

When away-mode injection wedges past max-defer, inject_wedge_alarm only
actively signalled via the tmux status-line, which is skipped on non-tmux
backends. A wedged claude-on-herdr primary left only the passive
state/.subsuper-inject-wedged marker (2026-07-10 overnight incident).

Add a config-gated active alert (config/wedge-alarm, local/gitignored;
FM_WEDGE_ALARM_CHANNEL) that reaches the captain even when every pane and
its status-line is unreadable: an OS-level macOS notification (osascript),
a herdr notification, or a captain-supplied command. Default-on (auto) so
the alarm is never silent; each channel best-effort, degrading to the next
and never crashing the daemon loop. The tmux flash and durable marker stay.

The OS notifiers route through a single FM_WEDGE_ALARM_EXEC seam. When the
daemon is sourced (only tests do this; production execs it) the seam
defaults to "discard", and tests/wake-helpers.sh points it at a recorder,
so it is structurally impossible for any test to post a real notification.

Channels verified once manually on macOS 26.5.2 / herdr 0.7.3; see
docs/wedge-alarm.md.

* no-mistakes(review): Bound wedge alarm notifier execution

* no-mistakes(review): Captain: harden wedge alarm notifier safety

* no-mistakes(review): Captain: harden wedge alarm test notifier isolation

* no-mistakes(review): Captain: harden wedge alarm throttling

* no-mistakes(review): Redact wedge alarm directive logs

* no-mistakes(review): Harden wedge alarm notifier safety

* no-mistakes(review): Track notifier process groups through cleanup

* no-mistakes(document): Document wedge-alarm active alert behavior

* docs: centralize firstmate operating contracts (#447)

* docs(agents): extract conditional AGENTS.md material to owned homes

Slice 3 of the documentation redundancy cleanup wave (firstmate scope):
the always-loaded instruction surface drops from 941 lines / 116,733
bytes (~29k tokens per session per fleet member) to 785 / 91,353
(~22.8k tokens), moving only audit-identified conditional and
situational material while preserving every load-bearing invariant at
its trigger point via the inline-stub pattern.

Moves, each to one declared owner plus an inline stub:
- section 3's bootstrap output-line handbook (~44 lines) -> new
  agent-only bootstrap-diagnostics skill, added to the section 13
  trigger index; the detect-consent-install rule and the
  do-not-dispatch gate stay inline as safety-critical.
- section 4's crew-dispatch JSON schema and field semantics ->
  docs/configuration.md 'Crew dispatch profiles' (pointer direction
  flipped); the intake procedure, precedence, backstop, and
  never-select-unverified rules stay inline.
- section 4's quota-balanced algorithm -> bin/fm-dispatch-select.sh
  header (now the declared owner; usage() converted to the dynamic
  header extraction pattern PR #438 established for fm-brief.sh).
- section 7's spawn resolution narrative and example sprawl ->
  bin/fm-spawn.sh header; the isolated-worktree assertion, refusal-is-
  a-blocker rule, and post-spawn duties stay inline.
- section 7's teardown landed-work mechanics -> bin/fm-teardown.sh
  header (section 1's containment pointer retargeted); the fork benign
  case and never-force rule stay inline.
- section 8's watcher classification narrative -> docs/architecture.md
  'Event-driven supervision' (already the owner); every operative rule
  (one live cycle, no turn ends blind, drain first, wake ladder,
  never-pkill, guard responses) stays inline.
- sections 3/4/6/7 secondmate sync, propagation, schema, and handoff
  restatements -> secondmate-provisioning skill, now the declared
  owner including the literal-file inheritance nuance.
- section 14's X-mode cadence mechanism -> docs/configuration.md
  'X mode (.env)', closing issue #363; activation semantics, the
  fmx-respond trigger, and the terminal-wake final-follow-up duty
  stay inline.

CLAUDE.md stays a symlink; no behavior or test change.

* no-mistakes(document): Centralize contract-owner documentation

* fix(cmux): close last workspace during teardown (#449)

* fix(cmux): close the last/selected workspace in a window at teardown

cmux keeps every window at >=1 workspace, so close-workspace on the only
workspace in a window silently no-ops (returns OK, workspace stays), and a
window holding a live session cannot be closed over the control socket.
That left a selected task workspace open at teardown (the last workspace
in a window is always the selected one).

Add fm_backend_cmux_window_of_workspace and have fm_backend_cmux_kill
create a throwaway default sibling in the target's window before closing
when the target is the last workspace there, so the close lands; the
window keeps a fresh default workspace (cmux's own "closed the last tab"
outcome). Non-last teardown closes directly, as before.

Cover both kill branches plus the helper with fake-CLI unit tests, add a
real-cmux window/count detection smoke assertion, and record the
empirical evidence in docs/cmux-backend.md.

* no-mistakes(review): Derive cmux count from membership snapshot

* no-mistakes(document): Document cmux last-workspace teardown behavior

* fix: recover orphaned packed-refs locks during fleet sync (#453)

* fix(fleet-sync): recover from an orphaned packed-refs.lock

A git ref rewrite (fetch --prune, pack-refs, branch -D) killed after
creating .git/packed-refs.lock but before renaming it - e.g. bootstrap's
timed-out fleet-sync kill or teardown's process kills - leaves a lock that
makes the next sync's fetch fail with "Unable to create
'...packed-refs.lock': File exists", leaving the clone unsynced.

On that signature only, fm-fleet-sync.sh now retries the fetch with a
bounded wait (transient locks self-clear), then removes the lock and
retries once more ONLY when it is provably stale: still present, mtime
age past a threshold, and no lsof holder of the lock file or of the clone
worktree itself (a live git keeps that as its cwd even in the window after
it closes the lock and before it exits). A live lock, a missing lsof, any
failed check, or any other fetch failure keeps today's behavior. Every
wait/retry/removal prints to stderr, and a successful recovery also prints
one "recovered:" summary to stdout so a session-start refresh - which
discards fleet-sync stderr and relays only stdout - still surfaces it.

The shared "is this git lock provably abandoned?" proof is extracted into
bin/fm-lock-lib.sh so it has one owner, used by both fm-teardown.sh and
fm-fleet-sync.sh. Constants are env-overridable knobs. tests/fm-gotmp.test.sh
gains the fm-lock-lib.sh symlink teardown now needs in its fake bin/.

* no-mistakes(review): Captain, remove obsolete teardown wake dependency

* no-mistakes(document): Document packed-refs lock recovery architecture

* feat(herdr): escalate blocked panes immediately (#472)

* feat(herdr): immediate blocked-state escalation via native events.subscribe push

Fold herdr's native pane.agent_status_changed stream into the single watcher so
a crew entering blocked wakes its supervisor sub-second (measured 0.129s)
instead of after the ~240s stale-pane wedge timer.

- bin/fm-transition-lib.sh: backend-neutral normalized-transition record shape
  plus the single-owner status->action policy table (blocked=actionable,
  working=absorb+clear-dedupe, idle/done=defer, else=fall back to polling).
- bin/backends/herdr.sh + herdr-eventwait.py: a raw AF_UNIX events.subscribe
  subscriber over one connection for all this home's herdr panes, subscribing to
  ALL statuses, returning the first fresh blocked edge, with a per-pane dedupe
  marker and a reconnect level-reconcile. Version/schema capability gate.
- bin/fm-backend.sh: has-push / events-capable / wait-transition dispatchers so
  the watcher stays backend-agnostic and the shape+policy are reusable.
- bin/fm-watch.sh: splice the bounded event wait in as the watcher's terminal
  wait primitive (replacing the blind sleep POLL for push-capable homes),
  behind a source guard so the splice is unit-testable; secondmate/paused
  exemptions; map pane->window->task and enqueue a stale wake. No second
  watcher process; the single-cycle invariant and every guard/beacon/turn-end
  mechanism are unchanged.
- Polling stays the permanent fail-closed backstop: below-capability, subscribe
  failure, and repeated runtime failures all degrade to sleep.
- Tests: fake-CLI units (fm-transition-lib, wait/apply/dedupe/reconcile/
  fallbacks in fm-backend-herdr, watcher exemptions in fm-supervision-events)
  plus an isolated real-herdr idle->blocked smoke. docs/herdr-backend.md carries
  the dated evidence and retires the old gap note.

* no-mistakes(review): Captain, fix Herdr disconnect handling and dedupe docs

* no-mistakes(review): Captain, commit markers after wake and reuse capability cache

* no-mistakes(review): Captain, clear stale markers and secure Herdr FIFOs

* no-mistakes(review): Captain, subscribe before Herdr reconciliation

* no-mistakes(review): Captain, make Herdr FIFO handling Bash 3.2-safe

* no-mistakes(test): Captain: include lock library in teardown fixture

* no-mistakes(document): Captain: document Herdr immediate blocked escalation

* fix: clarify shellcheck conditionals

* docs(readme): reposition firstmate as an agent distro (#473)

* feat: add deterministic bounded bearings snapshots (#475)

* feat(bearings): deterministic bearings snapshot + durable decision model

Add bin/fm-bearings-snapshot.sh: a bounded TOON-by-default projection over the
canonical fm-fleet-snapshot. Default is local-only (zero network); live open-PR
discovery and checks happen only under --include-prs, which fails soft. Every
dropped surface is marked in omitted[] with the flag that reveals it, and the
prs: line states when checks were not requested, so absence is never silent.

Fix the unresolved-decision masking bug in the canonical layer. fm-classify-lib
gains status_open_decisions, the one authoritative keyed open/resolved fold over
the whole status stream: needs-decision/blocked opens a keyed entry, only an
explicit keyed resolution (or, for run-backed tasks, run-step advancement)
closes it, so a later unrelated done/paused can no longer mask a still-open
captain decision. fm-fleet-snapshot surfaces hints.open_decisions and derives
pending_decision/blocked_event from it; the canonical schema stays complete.

Point the /bearings skill at the one command; add the resolved: writer line to
ship, scout, and secondmate briefs. Register the script and add regression
tests for the output bound, TOON/JSON parity, local-only default, opt-in PR
fetch, partial-failure degradation, decision durability, and report pointers.

* fix(bearings): completed scout report is a pointer, not a pending decision

A completed scout that raised a needs-decision and then finished (done) without
a keyed resolution falsely surfaced as an open/pending decision (the Lavish-103
case). Root cause: the open-decision reconciliation in bin/fm-fleet-snapshot.sh
cleared a stale decision only for a live run-step/pane activity read, so a
terminal task whose current state is read from the status log (a scout or ship
that reached done/failed) never cleared its stale, never-keyed-resolved
needs-decision, and it lingered as pending.

The open-decision set is still derived purely from the keyed fold - never from a
report body or decision-like prose - and reconciled against the crew lifecycle.
Extend that reconciliation so a terminal done/failed state on a single-owner
task (scout or ship), whose deliverable is its report or PR, also clears the set;
a completed scout now surfaces only as a report pointer. Secondmates are excluded
from the terminal clear (persistent, multiplexed stream), which keeps the
unrelated-event masking fix intact. Add regression tests: a completed scout with
decision-like report prose is a pointer not pending (canonical + end-to-end), and
a scout still parked at a decision stays pending so the terminal clear never
over-fires.

* no-mistakes(review): Captain, preserve keyed decisions across shared status parsing

* no-mistakes(review): Captain, close blockers and harden keyed decision parsing

* no-mistakes(review): Captain, bound GitHub enrichment without coreutils timeout

* no-mistakes(review): Captain, bound bearings sections and fail closed

* no-mistakes(review): Captain, disclose capped per-repository PR results

* no-mistakes(document): Refresh bearings documentation and status contracts

* fix(bearings): avoid ambiguous worktree guard

* fix: enforce deterministic ShellCheck parity (#481)

* fix(lint): one shellcheck owner pinned to 0.11.0 for CI/local parity

Firstmate PRs passed local no-mistakes validation but failed CI's
"Lint shell scripts" job on shellcheck findings (SC2015, SC1007, SC2034).
Two divergences caused it:

1. The no-mistakes gate had no commands.lint, so its lint step never ran
   the deterministic shellcheck bin/*.sh bin/backends/*.sh tests/*.sh that
   CI runs. Confirmed from state.sqlite: the lint step_result recorded
   findings:null with no lint agent invocation.
2. CI's shellcheck floated with the runner image while local ran a newer
   build; shellcheck retired SC2015 in 0.11.0, so an older CI shellcheck
   rejected an SC2015 that the newer local one no longer emits.

Establish bin/fm-lint.sh as the single owner of the lint definition: the
file set, the config, and the pinned shellcheck version (0.11.0, printed
via --required-version). Both CI (.github/workflows/ci.yml) and the
no-mistakes gate (.no-mistakes.yaml commands.lint) invoke it; CI installs
the exact version it names and logs the resolved version, and fm-lint.sh
refuses to lint under any other version. This is not a CI relaxation: it
adopts shellcheck 0.11.0's rule set consistently, dropping only the
upstream-retired, false-positive-prone SC2015; default severity and every
still-supported finding stay enforced (no severity downgrade, no excludes).

tests/fm-lint.test.sh asserts both gates invoke the owner, that CI installs
and logs the pinned version, that the owner refuses a non-pinned shellcheck,
and that it rejects a real lint defect the old no-op gate passed.

* no-mistakes(review): Captain, harden deterministic ShellCheck parity

* no-mistakes(review): Captain, neutralize ambient ShellCheck overrides

* feat: guard primary shells from persistent cd commands (#483)

* feat: add cd-guard PreToolUse seatbelt for the primary shell

A stray persistent top-level `cd projects/<clone>` in the primary firstmate
shell relocates the shell, so a later firstmate-owned command (a backlog write,
an fm-* lifecycle call, tasks-axi) runs inside a project clone instead of the
home. The cd-guard denies exactly that command shape before it runs, across all
five verified primary harnesses, mirroring the watcher-arm PreToolUse seatbelt.

- bin/fm-cd-command-policy.mjs: sole block/allow decision owner. Reuses the
  shell classifier exported from bin/fm-arm-command-policy.mjs (no duplicate
  lexer; that file's CLI now runs only when invoked directly).
- bin/fm-cd-pretool-check.sh: transport, strict-superset prefilter, harness
  output rendering, and primary-checkout scoping - fires in a secondmate's own
  primary session, inert in crew/scout child worktrees and non-firstmate repos.
- Wired into claude, codex, grok, opencode, and pi PreToolUse-equivalents;
  per-harness hooks only call the owner.
- Blocks top-level cd/pushd/popd (including cd to an absolute path, X=1 cd,
  and command cd). Allows git -C, subshell / bash -c / env -C / make -C /
  find -execdir, pipeline and background forms, and cd-as-data. Fails open on
  malformed input; agent-mistake threat model.
- tests/fm-cd-pretool-check.test.sh: 43-case x 5-harness-entry-form matrix,
  end-to-end cwd-leak regression, scoping, fail-open, prefilter, and wiring.
- docs/cd-guard.md: full contract plus live validation (claude, codex,
  opencode, pi blocked end-to-end; grok live run blocked by an API balance
  limit, with mechanism parity and deterministic coverage recorded).

* no-mistakes(review): Captain, fix cd-guard classification and prefilter coverage

* no-mistakes(review): Captain, allow path-qualified command wrappers

* no-mistakes(review): Captain, allow non-executing command queries

* no-mistakes(test): Captain, clarify cd-guard safe-path remediation

* docs: clarify cd guard guidance

* no-mistakes(document): Clarify cd-guard safe target guidance

* brief: add no-mistakes shared-daemon rule to ship and scout scaffolds (#267)

Crews must never stop, restart, or update the shared no-mistakes
daemon since one instance serves every firstmate lane/home; a restart
kills other lanes' in-flight pipeline runs and forces expensive
re-runs. Encodes this as a new numbered rule in both the ship-task and
scout-task brief scaffolds.

Co-authored-by: mielyemitchell <[email protected]>

* feat: make bearings concise and accurate (#485)

* feat(bearings): four-section chat contract, accurate secondmate landed, resolved-event state render

/bearings skill (one owner of the chat-response format): mandate the four
always-present chat sections - Captain's Call, Recently Landed, Underway,
Charted Next - each with an explicit empty-state sentence, no At Anchor,
materially shorter than and linking to the report file. Resolves the ambiguous
Check first / Decisions pending split into one strict captain-action section.

fm-crew-state: the log fallback derives current state only from a real
run-state verb, so a trailing decision-closing resolved: event no longer
renders a healthy idle crew (typically a secondmate) as unknown with the
resolution prose as its detail. The keyed-decision contract in
fm-classify-lib.sh is untouched; map_log_state stays the one verb->state owner.

fm-fleet-snapshot: add a bounded, read-only secondmate_landed roll-up of Done
records from registered secondmate homes, reusing the single backlog parser and
the one secondmate-home enumerator (meta home= with data/secondmates.md
fallback); no network, per-home capped.

fm-bearings-snapshot: landed now merges main-home Done with the secondmate
roll-up, bounded by a per-home cap and an overall cap with omitted[] disclosure
(also fixing the previously-silent landed truncation); --all-landed reveals the
full set.

tests: resolved-event state render, secondmate landed aggregation with caps and
omitted[] disclosure, Captain's Call anti-leak, and the four-section contract.

* no-mistakes(review): Captain, ensure bearings reveals all landed work

* no-mistakes(document): Document bearings accuracy contracts

* fix: harden away-mode daemon lifecycle (#490)

* fix: script-owned non-visible away-daemon launch + stale-artifact lifecycle

Away-mode entry left "make the daemon a tracked background terminal" to the
operator; on a pi/herdr primary that meant splitting the captain's active pane,
which visibly shrank it. Add bin/fm-afk-launch.sh, a single owner that launches
the daemon in a non-visible tracked terminal per backend (herdr dedicated
--no-focus workspace, detached tmux session), never a split, pins the captain
pane as FM_SUPERVISOR_TARGET/FM_SUPERVISOR_BACKEND, records the exact terminal
id, and tears it down or reconciles a leaked one by that id. No shell &.
Extract supervisor-pane discovery into bin/fm-supervisor-target-lib.sh, shared
with the daemon (one owner).

Fix the stale subsuper-artifact leak: clear the prior away session's delivery
cache on a fresh entry (fm_afk_clear_stale_artifacts), and stop the daemon
before clearing state/.afk so its shutdown flush runs instead of being a no-op.

Tests: tests/fm-afk-launch.test.sh (per-backend topology invariant in a lab
session, stale clear-on-entry vs refresh, exit ordering). Docs: /afk SKILL.md,
docs/herdr-backend.md (dated herdr evidence), AGENTS.md exit stub, docs/scripts.md.

* no-mistakes(review): Captain, serialize AFK launcher lifecycle safely

* no-mistakes(review): Captain, harden AFK launcher lifecycle races

* no-mistakes(review): Captain, ensure AFK daemon launch readiness

* no-mistakes(review): Captain, unify AFK lifecycle ownership and teardown

* no-mistakes(review): Captain, preserve AFK reconciliation records uniformly

* no-mistakes(review): Captain, harden AFK recovery state durability

* no-mistakes(review): Captain, harden AFK tmux ownership checks

* no-mistakes(review): Captain, simplify AFK lifecycle failure handling

* no-mistakes(review): Captain, require confirmed AFK daemon shutdown

* no-mistakes(review): Captain, confirm AFK exit by process identity

* no-mistakes(document): Align AFK launcher lifecycle documentation

* no-mistakes: apply CI fixes

* fix: prevent no-mistakes gate agents from driving the fleet (#518)

* feat: contain no-mistakes gate agents from driving the fleet

Add bin/fm-gate-refuse-lib.sh, sourced at the top of fm-spawn/fm-send/
fm-teardown before any fleet mutation. It fails closed when NO_MISTAKES_GATE
is set, and via an unspoofable git-common-dir backstop when invoked from a
no-mistakes gate worktree (.no-mistakes/repos/*.git) even with the marker
unset. A normal firstmate session has neither signal and is unaffected.

Set disable_project_settings: true in the tracked .no-mistakes.yaml so the
installed pipeline neutralizes gate agents' project instructions for this repo
(trusted-only, honored from the default branch).

firstmate's own suite runs from a gate worktree during validation, so the
shared test helpers set FM_GATE_REFUSE_BYPASS=1 to exempt it; the dedicated
tests/fm-gate-refuse.test.sh strips it to verify real refusal.

* no-mistakes(review): Captain, refuse empty no-mistakes gate markers

* no-mistakes(document): Document no-mistakes gate authority boundary

* fix: guard secondmate primary sessions from blind turn ends (#505)

* fix: guard secondmate own-home turn ends

Remove the .fm-secondmate-home early-exit in fm-turnend-guard.sh so the
'no turn ends blind' backstop fires in a secondmate's own primary session,
matching the cd-guard's scope: the own home is guarded, child crew/scout
worktrees stay exempt via the retained git-dir/git-common-dir test. This
was pure scoping from the guard's primary-only origin and guarded against
no secondmate-specific hazard.

Add secondmate regression tests (blind-turn block, idle-by-default,
stop_hook_active loop guard, deferred-death recovery loop, child-worktree
exemption) and record the autonomous background-notify re-invoke
measurement (Claude Code 2.1.207, 11s) in docs/turnend-guard.md.

* no-mistakes(document): Correct secondmate guard documentation, captain

* fix: force-include marked secondmate homes in turn-end guard

The prior remove-only form (just deleting the .fm-secondmate-home check)
left the DEFAULT secondmate topology unguarded: a treehouse-leased home is
a linked git worktree (git-dir != git-common-dir), which the retained
git-dir exemption still skipped, so its own primary session could still end
a turn blind. Invert the marker: