Skip to content

fix: add turn-end supervision guard - #249

Merged
kunchenguid merged 5 commits into
mainfrom
fm/fm-turnend-guard-g4
Jul 4, 2026
Merged

kunchenguid merged 5 commits into
mainfrom
fm/fm-turnend-guard-g4

Conversation

@kunchenguid

Copy link
Copy Markdown
Owner

Intent

Build a turn-end supervision guard for the PRIMARY firstmate session so a turn that ends blind (fleet work in flight but no live watcher) raises an immediate alarm instead of waiting for the next fleet-touching command. Motivated by a 2026-07-04 incident where the primary ended a turn without re-arming the watcher and a parked pipeline gate sat unnoticed for ~9 hours, since fm-guard.sh is pull-based (only warns when some other supervision script runs).

Design deliberately chosen after empirical investigation (verified live against a real claude -p session, not just docs):

  • Added bin/fm-turnend-guard.sh, a Claude Code Stop hook. Exiting the hook with status 2 and a reason on stderr reliably forces Claude Code to continue the turn and act on the reason (verified empirically with a scratch smoke test: a hook that demanded a specific word in the reply caused the model's next message to comply before the turn was allowed to end).
  • Loop-guard uses Claude Code's own stop_hook_active stdin field (true when the current stop is itself a forced continuation) rather than any custom counter file, so it never blocks more than once per turn - deliberately chosen over a manual state-file approach to avoid ever wedging an un-endable session.
  • The block reason must say exactly: 'tasks in flight, no live watcher - run bin/fm-watch-arm.sh as a background task before ending the turn' (a hard requirement), wrapped in a bordered banner matching fm-guard.sh's existing alarm style.
  • Factored the shared 'in-flight work exists but no watcher has a fresh beacon' predicate out of fm-guard.sh into a new bin/fm-supervision-lib.sh, sourced by both fm-guard.sh (refactored, no behavior change - confirmed via the existing fm-tangle-guard.test.sh still passing) and the new hook script, so the two can never drift on what 'unhealthy' means.
  • Scoping is deliberately precise and was the hardest design part: the hook ships in a TRACKED .claude/settings.json (chosen over an untracked/local file specifically so every user of this repo gets it automatically after a normal clone and session start, with no manual per-user setup) - which means it is also checked out into every crewmate/scout task worktree of firstmate-on-itself and every secondmate home. The hook must therefore be inert everywhere except the true primary checkout. After investigating how secondmate homes are actually provisioned (bin/fm-home-seed.sh: some via treehouse-leased linked worktrees, others via plain 'git clone' with an independent .git dir), a single structural git-dir/git-common-dir check alone is NOT sufficient to exclude all secondmates - so the design deliberately checks the .fm-secondmate-home marker file FIRST (written at seed time regardless of acquisition method) before the git-dir/common-dir structural check (which handles ordinary crewmate/scout worktrees, always genuine linked git worktrees per fm-spawn.sh's own isolation guarantee), plus a cheap AGENTS.md/bin//state/ sanity check. This intentionally mirrors the existing worktree-tangle guard's caution (bin/fm-brief.sh) that git-dir/common-dir alone is not authoritative proof of isolation.
  • Fails open (never blocks) if jq is missing or stdin is unreadable/empty, matching the existing bin/fm-x-poll.sh convention for a missing-jq dependency, deliberately prioritizing 'never blocking work' over always catching the unhealthy case.
  • This backstop is deliberately claude-only for now (matching how the primary runs today); other harnesses still rely on the pre-existing pull-based fm-guard.sh alone. This is called out explicivamente as a known gap/future work in both AGENTS.md and the harness-adapters skill, not silently left unstated.

Also added docs/turnend-guard.md recording the verified empirical Stop-hook findings (exact JSON schema fields, the exit-code-2 block mechanism, the stop_hook_active loop-guard, and that a project-level .claude/settings.json does not take effect when launched from a subdirectory of the project - verified live), added a harness-adapters skill note, an AGENTS.md section 8 note, docs/scripts.md and README.md doc-index entries, and a new tests/fm-turnend-guard.test.sh (14 cases) covering the predicate lib directly and the hook script's scoping/loop-guard/fail-open behavior end to end. Confirmed no regressions: shellcheck clean and the full existing 41-file test suite passes unchanged.

What Changed

  • Added a Claude Stop-hook turn-end guard that blocks primary firstmate turns when work is in flight without a live watcher, with fail-open handling for missing hook input or dependencies.
  • Refactored shared supervision-health checks into reusable shell libraries so fm-guard.sh, watcher arming, and the new turn-end guard use consistent state and watcher predicates.
  • Documented the turn-end guard behavior, Claude-only scope, and harness limitations, and added focused shell tests covering primary scoping, secondmate/worktree no-ops, loop-guard behavior, and live-watcher detection, captain.

Risk Assessment

⚠️ Medium: Captain, the change is operationally sensitive because it adds a Claude Stop hook and refactors watcher liveness helpers, but I did not find a substantiated merge-blocking issue in the current diff.

Testing

The provided full-suite baseline was already green; I then ran the focused turn-end guard, tangle guard, and watcher lock suites, plus a manual end-to-end Stop-hook transcript showing the configured hook blocks with exit 2 and the exact required reason when in-flight work has no live watcher, allows the loop-guard retry, allows a real live watcher, and stays inert in a secondmate home.

Evidence: Manual turn-end guard transcript
Manual end-to-end evidence for bin/fm-turnend-guard.sh
repo=/Users/kunchen/.no-mistakes/worktrees/016d88035d58/01KWQ6E50HEJGKADE8WARXP26Z
configured_stop_hook_command=bin/fm-turnend-guard.sh
required_reason=tasks in flight, no live watcher - run bin/fm-watch-arm.sh as a background task before ending the turn

## primary: in-flight task + fresh leftover beacon + no live watcher lock blocks the turn
$ printf '{"stop_hook_active":false}' | FM_ROOT_OVERRIDE=/var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KWQ6E50HEJGKADE8WARXP26Z/turnend-guard-manual-work/plain-primary bash bin/fm-turnend-guard.sh
exit=2
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
●  TURN WOULD END BLIND - SUPERVISION IS OFF
●  1 task(s) in flight, but no live watcher holds this home lock (last beat: 0s ago).
●  tasks in flight, no live watcher - run bin/fm-watch-arm.sh as a background task before ending the turn
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

## primary: stop_hook_active=true allows the forced-continuation retry
$ printf '{"stop_hook_active":true}' | FM_ROOT_OVERRIDE=/var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KWQ6E50HEJGKADE8WARXP26Z/turnend-guard-manual-work/plain-primary bash bin/fm-turnend-guard.sh
exit=0
<no output>

## primary: actual fm-watch.sh process makes the hook allow the stop
started_watcher_pid=54258
recorded_lock_pid=54258
beacon_present=yes

## primary: in-flight task + live watcher lock + fresh beacon is silent
$ printf '{"stop_hook_active":false}' | FM_ROOT_OVERRIDE=/var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KWQ6E50HEJGKADE8WARXP26Z/turnend-guard-manual-work/plain-primary bash bin/fm-turnend-guard.sh
exit=0
<no output>
watcher_log_path=/var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KWQ6E50HEJGKADE8WARXP26Z/turnend-guard-watcher.log

## secondmate clone-shaped home: tracked hook is inert even when unhealthy
$ printf '{"stop_hook_active":false}' | FM_ROOT_OVERRIDE=/var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KWQ6E50HEJGKADE8WARXP26Z/turnend-guard-manual-work/plain-secondmate-home bash bin/fm-turnend-guard.sh
exit=0
<no output>

transcript_path=/var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KWQ6E50HEJGKADE8WARXP26Z/turnend-guard-manual-transcript.txt

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 1 issue found → auto-fixed (3) ✅
  • ⚠️ bin/fm-turnend-guard.sh:66 - The hook hard-codes $FM_ROOT/state instead of the established FM_HOME / FM_STATE_OVERRIDE state resolution used by the rest of firstmate. In a supported primary session with FM_HOME set, it can miss the real in-flight tasks or block on stale repo-root state; compute STATE the same way as fm-guard.sh and run the predicate against that.

🔧 Fix: Respect active home in turnend guard
1 error still open:

  • 🚨 bin/fm-turnend-guard.sh:68 - The Stop hook reuses the grace-based fm_supervision_unhealthy predicate, so a watcher that just fired and exited still looks healthy for up to FM_GUARD_GRACE seconds because .last-watcher-beat is fresh. That lets the exact failure mode through: after handling a wake, ending the turn without re-arming the watcher will usually happen inside the 300s grace window, so the hook exits 0 and the fleet can go blind until some later fleet command. The hook needs an end-of-turn predicate that verifies a live watcher/arm is actually present, or otherwise treats a missing watcher lock/process as unhealthy even when the last beacon is recent.

🔧 Fix: Require live watcher for turn-end guard
1 warning still open:

  • ⚠️ tests/fm-turnend-guard.test.sh:342 - date +%s%N is GNU-specific. On macOS/BSD date, %N is left literal, so elapsed_ms=$(( (end - start) / 1000000 )) can abort the new test under set -u instead of running the suite on a supported local platform. Use a portable seconds-based check or an existing portable timing helper.

🔧 Fix: Captain: portable turn-end timing
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • command -v tmux >/dev/null || { echo "tmux is required for e2e tests" >&2; exit 1; }; tmux -V; rc=0; for t in tests/*.test.sh; do echo "== $t =="; bash "$t" || rc=1; done; exit "$rc"
  • Baseline already ran successfully before this validation: command -v tmux &gt;/dev/null || { echo &#34;tmux is required for e2e tests&#34; &gt;&amp;2; exit 1; }; tmux -V; rc=0; for t in tests/*.test.sh; do echo &#34;== $t ==&#34;; bash &#34;$t&#34; || rc=1; done; exit &#34;$rc&#34;
  • bash tests/fm-turnend-guard.test.sh
  • bash tests/fm-tangle-guard.test.sh
  • bash tests/fm-watcher-lock.test.sh
  • Manual Stop-hook evidence: created primary-shaped and secondmate-shaped fixtures in the evidence directory, invoked FM_ROOT_OVERRIDE=&lt;fixture&gt; bash bin/fm-turnend-guard.sh with Claude Stop payloads, and started bin/fm-watch.sh once to verify the live-watcher allow path; captured transcript at /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KWQ6E50HEJGKADE8WARXP26Z/turnend-guard-manual-transcript.txt
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

fm-guard.sh is pull-based: it only warns when some other supervision
script happens to run, so a primary session that ends a turn without
re-arming the watcher and then runs no further fleet-touching command
can sit blind for hours (the 2026-07-04 incident this fixes).

Add bin/fm-turnend-guard.sh, a Claude Code Stop hook registered in the
tracked .claude/settings.json, that fires on every primary turn end and
blocks (exit 2, verified empirically to force continuation) when work
is in flight with no fresh watcher beacon. It never blocks more than
once per turn, using Claude Code's own stop_hook_active loop-guard
field, and scopes itself to the actual primary checkout only (inert in
crewmate/scout worktrees and secondmate homes).

Factor the shared "in-flight but no live watcher" predicate out of
fm-guard.sh into bin/fm-supervision-lib.sh so the pull-based banner and
the push-based hook can never drift on what "unhealthy" means.

Document the verified Stop-hook mechanism and scoping in
docs/turnend-guard.md, add a harness-adapters note, and cover the
predicate and hook with tests/fm-turnend-guard.test.sh.
@kunchenguid
kunchenguid force-pushed the fm/fm-turnend-guard-g4 branch from b8bee3c to f71393e Compare July 4, 2026 19:29
@kunchenguid
kunchenguid merged commit 1b68a69 into main Jul 4, 2026
4 checks passed
@kunchenguid
kunchenguid deleted the fm/fm-turnend-guard-g4 branch July 4, 2026 19:38
leo1oel added a commit to leo1oel/nemo that referenced this pull request Jul 5, 2026
…kunchenguid#256) (#26)

Port upstream kunchenguid#249 with the kunchenguid#256 path-anchoring fix. fm-guard.sh is
pull-based - it warns only when another supervision script happens to
run - so a primary session that ends a turn without re-arming the
watcher can sit blind for hours. bin/fm-turnend-guard.sh is push-based:
a Claude Code Stop hook (tracked .claude/settings.json, anchored via
$CLAUDE_PROJECT_DIR since hooks run from the session cwd) that blocks
the turn end (exit 2, at most once per turn via stop_hook_active) when
tasks are in flight with no fresh watcher beacon. Fork adaptations:
python3 instead of jq for the payload (fail-open), and an afk branch
that judges the sub-supervisor daemon pid instead of the beacon, since
the daemon owns the watcher while state/.afk exists. Scoped to the
primary checkout; secondmate homes and linked worktrees no-op.
mielyemitchell added a commit to mielyemitchell/firstmate that referenced this pull request Jul 6, 2026