Skip to content

fix(bin): stop the Claude turn-end guard raising a false blind-turn alarm while the Stop auto-arm is still starting - #49

Merged
alandomio merged 2 commits into
mainfrom
fm/fm-stop-guard-race
Sep 29, 2026
Merged

alandomio merged 2 commits into
mainfrom
fm/fm-stop-guard-race

Conversation

@alandomio

@alandomio alandomio commented Sep 29, 2026 •

Copy link
Copy Markdown
Owner

Intent

Fix a race in firstmate's Claude primary turn-end supervision. Under the Claude harness, after almost every handled wake the Stop-hook guard (bin/fm-turnend-guard.sh --claude, registered in .claude/settings.json alongside bin/fm-claude-stop-autoarm.sh) printed a false 'TURN WOULD END BLIND - SUPERVISION IS OFF ... Stop-owned auto-arm did not claim this home either' alarm although the auto-arm was already arming the watcher (epoch outcome=arming, fresh watcher). Root cause reproduced and confirmed: Claude starts both Stop hooks concurrently; the auto-arm's pre-claim work (harness ancestry resolution, a chain of ps forks, seconds under load) outlasts the guard's ~800ms claim window, so the claim lands after the guard blocks. Required: reproduce the race with a test harness starting the two hooks concurrently, fix so the guard recognizes an auto-arm that is starting for this home (bounded wait / early announcement per docs/turnend-guard.md and docs/watcher-continuity.md), while preserving the guard's real safety (still block when no recovery is actually under way), add colocated regression tests, update owning docs. Decisions made: the auto-arm publishes a per-pid marker state/.claude-autoarm-starting. right after its scope check and removes it once its autoarm claim role is published (or on any earlier exit); the guard waits past the claim window while a live-pid marker younger than FM_CLAUDE_AUTOARM_START_WAIT seconds (default 15) exists, sampling the marker before the ownership check; dead/expired markers and an auto-arm that stands down still end in the normal block. Also investigated the guard's '16 task(s) in flight' count: it counts every state/*.meta, including finished-but-not-torn-down tasks; that is stale records reconciled separately, not a count bug, so deliberately left unchanged. Docs updated: docs/turnend-guard.md, docs/watcher-continuity.md, AGENTS.md state list.

What Changed

  • bin/fm-claude-stop-autoarm.sh now writes a per-pid marker, state/.claude-autoarm-starting.<pid>, right after its scope check. It removes the marker once it has published its autoarm claim role, and also on any earlier exit.
  • bin/fm-turnend-guard.sh --claude checks for that marker before its ownership check. If the marker's pid is alive and the marker is younger than FM_CLAUDE_AUTOARM_START_WAIT seconds (default 15), the guard keeps waiting past its usual claim window. The normal "TURN WOULD END BLIND" block still fires when the marker's pid is dead, the marker has expired, or the auto-arm stands down.
  • Added regression tests to tests/fm-turnend-guard.test.sh and tests/fm-claude-stop-autoarm.test.sh. Updated docs/turnend-guard.md, docs/watcher-continuity.md and the state list in AGENTS.md to cover the new marker.

Risk Assessment

✅ Low: This is a small, bounded fix. The marker is sampled before the ownership check, which avoids the race with role publication. The extra wait is capped by the marker's age and a live pid. Every exit path in the auto-arm cleans up the marker, and the new tests exercise real behavior.

Testing

I ran the guard and auto-arm test files at HEAD and both pass, including the new tests that start the two hooks concurrently. I then put the pre-fix bin scripts back and reran the guard tests. The slow-starting auto-arm test fails there with the false-alarm block (exit 2), so the tests do reproduce the race. The worktree was restored and is clean.

Evidence: Guard tests at HEAD (fix)

Source: Guard tests at HEAD (fix)

ok - fm_supervision_unhealthy: false with no state/*.meta at all
ok - fm_supervision_unhealthy: true with in-flight task and no beacon ever
ok - fm_supervision_unhealthy: true with in-flight task and a beacon far outside the grace window
ok - fm_supervision_unhealthy: false with in-flight task and a fresh beacon
ok - fm_supervision_status: FM_SUP_QUEUE_PENDING tracks state/.wake-queue
ok - fm_supervision_needed: X-mode relay poll needs supervision
ok - fm_supervision_unhealthy: source-only home needs supervision
ok - fm-turnend-guard: silent no-op with nothing in flight
ok - fm-turnend-guard: the opt-in Jev turn-end record leaves the verdict unchanged
ok - fm-turnend-guard: blocks when a fresh beacon has no live watcher lock
ok - fm-turnend-guard: non-Claude path blocks a source-only home
ok - fm-turnend-guard: blocks on a dead watcher lock even when the beacon is fresh
ok - fm-turnend-guard: silent no-op with a live watcher lock and fresh beacon
ok - fm-turnend-guard: healthy non-Claude harness paths ignore Claude episode contention
ok - fm-turnend-guard: blocks on a live watcher lock with an ancient beacon
ok - fm-turnend-guard: blocks with the exact required reason in the primary when unhealthy
ok - fm-turnend-guard: blocks from active FM_HOME state, not only repo-root state
ok - fm-turnend-guard: X-mode repair reason sources the cadence config
ok - fm-turnend-guard: X-mode-only supervision remains guarded in default mode
ok - fm-turnend-guard: ignores stale repo-root state when FM_HOME is set
ok - fm-turnend-guard: uses FM_STATE_OVERRIDE ahead of FM_HOME/state
ok - fm-turnend-guard: stop_hook_active=true always allows the stop (never blocks twice in one turn)
ok - fm-turnend-guard: blocks a blind turn end in a secondmate's own home (.fm-secondmate-home no longer excludes it)
ok - fm-turnend-guard: idle-by-default - silent in a secondmate home with nothing in flight
ok - fm-turnend-guard: stop_hook_active=true allows the stop in a secondmate home (never blocks twice in one turn)
ok - fm-turnend-guard: secondmate deferred-death recovery - silent while watched, forces re-arm once the watcher exits
ok - fm-turnend-guard: inert in a secondmate's own child worktree (linked git worktree) even when unhealthy
ok - fm-turnend-guard: blocks a blind turn end in a treehouse-leased LINKED secondmate home (marker force-include)
ok - fm-turnend-guard: an invalid (empty) marker cannot spoof inclusion; linked worktree stays exempt
ok - fm-turnend-guard: a non-ASCII marker cannot spoof inclusion; linked worktree stays exempt
ok - fm-turnend-guard: inert in a crewmate/scout task worktree (linked git worktree) even when unhealthy
ok - fm-turnend-guard: fails open (never blocks) when jq is missing
ok - fm-turnend-guard: silent no-op on empty stdin
ok - fm-turnend-guard: runs well under the generous timing margin (0s)
ok - fm-turnend-guard-grok: forces one explicitly marked same-session resume when the shared predicate blocks
ok - fm-turnend-guard-grok: legacy environment loop guard prevents a nested resume loop
ok - fm-turnend-guard-grok: native false delegates blocking feedback with zero resume processes
ok - fm-turnend-guard-grok: native true remains bounded and starts no resume process
ok - fm-turnend-guard-grok: both spellings are typed and camelCase has deterministic precedence
ok - fm-turnend-guard-grok: malformed, invalidly typed, and missing-prerequisite payloads start neither path
ok - fm-turnend-guard-grok: missing jq and no-supervision-needed stops stay silent and bounded
ok - tracked .claude/settings.json entries: 5 inert under grok, the documented subagent exception still armed, all live under Claude
ok - .codex/hooks.json: Stop hook uses hook process root when payload cwd is outside
ok - .codex/hooks.json: Stop hook ignores nested git root guard scripts
ok - .opencode primary plugin: guard path is anchored to worktree, not directory
ok - .pi primary extension: no-tool and multi-tool runs each inject exactly one guard follow-up
ok - .pi primary extension: delivery failure resets the logical-run latch
ok - fm-turnend-guard --claude: re-blocks a loop-guarded stop while unhealthy and unclaimed (incident regression)
ok - fm-turnend-guard --claude: X-mode-only homes re-block when auto-arm recovery is absent
ok - fm-turnend-guard --claude: a live arming epoch advances once and repeated observation is idempotent
ok - fm-turnend-guard --claude: repeated failed-to-arming races make bounded monotonic progress
ok - fm-turnend-guard --claude: terminal owner boundary excludes a concurrent start without deadlock
ok - fm-turnend-guard --claude: fresh rewake epoch prevents a duplicate continuation for the same event
ok - fm-turnend-guard --claude: an abandoned auto-arm claim no longer allows a blind stop (incident regression)
ok - fm-turnend-guard --claude: a claim whose pid was reused stops counting as recovery even while its entry reads arming
ok - fm-turnend-guard --claude: the terminal path clears an abandoned claim instead of stepping aside silently
ok - fm-turnend-guard --claude: fresh failed epochs preserve and advance monotonic fail-open progression
ok - fm-turnend-guard --claude: integrated fresh failures reach one bounded fail-open, stop continuation, and reset on recovery
ok - fm-turnend-guard --claude: reset contention preserves all episode state until retry
ok - fm-turnend-guard --claude: concurrent auto-arm and guard resets are idempotent and deadlock-free
ok - fm-turnend-guard --claude: stale rewake epoch does not allow a blind stop
ok - fm-turnend-guard --claude: budget exhaustion alone cannot permit a blind stop
ok - fm-turnend-guard --claude: verified fail-open is loud, bounded, attended, and non-repeating
ok - fm-turnend-guard --claude: fail-open requires both exhausted retries and consumed notice
ok - fm-turnend-guard --claude: away ownership excludes the Stop-autoarm fail-open
ok - fm-turnend-guard --claude: positive watcher recovery resets failure episode state
ok - fm-turnend-guard --claude: bounded claim wait avoids a token-consuming forced continuation
ok - fm-turnend-guard --claude: a slow-starting auto-arm is recognised, no false blind-turn alarm (race regression)
ok - fm-turnend-guard --claude: an auto-arm that starts and stands down does not mask a blind turn
ok - fm-turnend-guard --claude: dead or expired starting markers are not recovery proof
ok - fm-turnend-guard --claude: the starting-auto-arm wait is bounded and then blocks
ok - fm-turnend-guard --claude: secondmate home re-blocks unclaimed and allows auto-arm-claimed stops
exit=0
Evidence: Guard tests on pre-fix scripts (race reproduced)

Source: Guard tests on pre-fix scripts (race reproduced)

not ok - --claude must not raise a blind-turn alarm while a slow auto-arm is still starting: expected exit 0, got 2

ok - fm_supervision_unhealthy: false with no state/*.meta at all
ok - fm_supervision_unhealthy: true with in-flight task and no beacon ever
ok - fm_supervision_unhealthy: true with in-flight task and a beacon far outside the grace window
ok - fm_supervision_unhealthy: false with in-flight task and a fresh beacon
ok - fm_supervision_status: FM_SUP_QUEUE_PENDING tracks state/.wake-queue
ok - fm_supervision_needed: X-mode relay poll needs supervision
ok - fm_supervision_unhealthy: source-only home needs supervision
ok - fm-turnend-guard: silent no-op with nothing in flight
ok - fm-turnend-guard: the opt-in Jev turn-end record leaves the verdict unchanged
ok - fm-turnend-guard: blocks when a fresh beacon has no live watcher lock
ok - fm-turnend-guard: non-Claude path blocks a source-only home
ok - fm-turnend-guard: blocks on a dead watcher lock even when the beacon is fresh
ok - fm-turnend-guard: silent no-op with a live watcher lock and fresh beacon
ok - fm-turnend-guard: healthy non-Claude harness paths ignore Claude episode contention
ok - fm-turnend-guard: blocks on a live watcher lock with an ancient beacon
ok - fm-turnend-guard: blocks with the exact required reason in the primary when unhealthy
ok - fm-turnend-guard: blocks from active FM_HOME state, not only repo-root state
ok - fm-turnend-guard: X-mode repair reason sources the cadence config
ok - fm-turnend-guard: X-mode-only supervision remains guarded in default mode
ok - fm-turnend-guard: ignores stale repo-root state when FM_HOME is set
ok - fm-turnend-guard: uses FM_STATE_OVERRIDE ahead of FM_HOME/state
ok - fm-turnend-guard: stop_hook_active=true always allows the stop (never blocks twice in one turn)
ok - fm-turnend-guard: blocks a blind turn end in a secondmate's own home (.fm-secondmate-home no longer excludes it)
ok - fm-turnend-guard: idle-by-default - silent in a secondmate home with nothing in flight
ok - fm-turnend-guard: stop_hook_active=true allows the stop in a secondmate home (never blocks twice in one turn)
ok - fm-turnend-guard: secondmate deferred-death recovery - silent while watched, forces re-arm once the watcher exits
ok - fm-turnend-guard: inert in a secondmate's own child worktree (linked git worktree) even when unhealthy
ok - fm-turnend-guard: blocks a blind turn end in a treehouse-leased LINKED secondmate home (marker force-include)
ok - fm-turnend-guard: an invalid (empty) marker cannot spoof inclusion; linked worktree stays exempt
ok - fm-turnend-guard: a non-ASCII marker cannot spoof inclusion; linked worktree stays exempt
ok - fm-turnend-guard: inert in a crewmate/scout task worktree (linked git worktree) even when unhealthy
ok - fm-turnend-guard: fails open (never blocks) when jq is missing
ok - fm-turnend-guard: silent no-op on empty stdin
ok - fm-turnend-guard: runs well under the generous timing margin (0s)
ok - fm-turnend-guard-grok: forces one explicitly marked same-session resume when the shared predicate blocks
ok - fm-turnend-guard-grok: legacy environment loop guard prevents a nested resume loop
ok - fm-turnend-guard-grok: native false delegates blocking feedback with zero resume processes
ok - fm-turnend-guard-grok: native true remains bounded and starts no resume process
ok - fm-turnend-guard-grok: both spellings are typed and camelCase has deterministic precedence
ok - fm-turnend-guard-grok: malformed, invalidly typed, and missing-prerequisite payloads start neither path
ok - fm-turnend-guard-grok: missing jq and no-supervision-needed stops stay silent and bounded
ok - tracked .claude/settings.json entries: 5 inert under grok, the documented subagent exception still armed, all live under Claude
ok - .codex/hooks.json: Stop hook uses hook process root when payload cwd is outside
ok - .codex/hooks.json: Stop hook ignores nested git root guard scripts
ok - .opencode primary plugin: guard path is anchored to worktree, not directory
ok - .pi primary extension: no-tool and multi-tool runs each inject exactly one guard follow-up
ok - .pi primary extension: delivery failure resets the logical-run latch
ok - fm-turnend-guard --claude: re-blocks a loop-guarded stop while unhealthy and unclaimed (incident regression)
ok - fm-turnend-guard --claude: X-mode-only homes re-block when auto-arm recovery is absent
ok - fm-turnend-guard --claude: a live arming epoch advances once and repeated observation is idempotent
ok - fm-turnend-guard --claude: repeated failed-to-arming races make bounded monotonic progress
ok - fm-turnend-guard --claude: terminal owner boundary excludes a concurrent start without deadlock
ok - fm-turnend-guard --claude: fresh rewake epoch prevents a duplicate continuation for the same event
ok - fm-turnend-guard --claude: an abandoned auto-arm claim no longer allows a blind stop (incident regression)
ok - fm-turnend-guard --claude: a claim whose pid was reused stops counting as recovery even while its entry reads arming
ok - fm-turnend-guard --claude: the terminal path clears an abandoned claim instead of stepping aside silently
ok - fm-turnend-guard --claude: fresh failed epochs preserve and advance monotonic fail-open progression
ok - fm-turnend-guard --claude: integrated fresh failures reach one bounded fail-open, stop continuation, and reset on recovery
ok - fm-turnend-guard --claude: reset contention preserves all episode state until retry
ok - fm-turnend-guard --claude: concurrent auto-arm and guard resets are idempotent and deadlock-free
ok - fm-turnend-guard --claude: stale rewake epoch does not allow a blind stop
ok - fm-turnend-guard --claude: budget exhaustion alone cannot permit a blind stop
ok - fm-turnend-guard --claude: verified fail-open is loud, bounded, attended, and non-repeating
ok - fm-turnend-guard --claude: fail-open requires both exhausted retries and consumed notice
ok - fm-turnend-guard --claude: away ownership excludes the Stop-autoarm fail-open
ok - fm-turnend-guard --claude: positive watcher recovery resets failure episode state
ok - fm-turnend-guard --claude: bounded claim wait avoids a token-consuming forced continuation
not ok - --claude must not raise a blind-turn alarm while a slow auto-arm is still starting: expected exit 0, got 2
exit=1
Evidence: Auto-arm tests at HEAD

Source: Auto-arm tests at HEAD

ok - auto-arm: inert in a linked child worktree even when in-flight
ok - auto-arm: inert with no session lock
ok - auto-arm: a demonstrably dead recorded session owner is reclaimed through fm-lock.sh before arming
ok - auto-arm: inert without arm, rewake, or lock replacement when another live harness owns the home
ok - auto-arm: inert while AFK owns supervision
ok - auto-arm: stale-owner recovery leaves the AFK and supervision-need gates unchanged
ok - auto-arm: resolves the outermost pid of a nested contiguous claude ancestry (bg-spare chain)
ok - auto-arm: inert with nothing in flight and no X-mode need
ok - auto-arm: actionable close translates to exactly one exit-2 rewake with reason
ok - auto-arm: actionable close survives a healthy successor without duplicate delivery
ok - auto-arm: bounded failure verification emits one automatic-mechanism alarm
ok - auto-arm: consecutive failures keep Stop-owned retry without repeating notice
ok - auto-arm: unverified clean close exhausts retries and fails closed
ok - auto-arm: post-alarm actionable outcomes cannot continue or reset failure state
ok - auto-arm: benign cycle end with a live watcher and fresh beacon stays silent across the next cycle
ok - auto-arm: budget contention preserves the episode and forces a reset retry
ok - auto-arm: X-mode poll need arms the cycle even with no tasks in flight
ok - auto-arm: concurrent firings admit one owner and one rewake translation
ok - auto-arm: announces starting before the slow pre-claim work and retracts it at the claim
ok - auto-arm: an abandoned owner claim is reclaimed so a lapsed cycle re-arms
ok - auto-arm: an owner still arming is never reclaimed, however long the cycle runs
ok - auto-arm: a live claim the ledger does not name is never reclaimed
ok - auto-arm: a claim whose pid was reused is reclaimed even while its ledger entry still reads arming
ok - auto-arm: a reused-pid claim is reclaimed even with no ledger entry to prove it
ok - auto-arm: an identity-matched owner still arming is never reclaimed
ok - auto-arm: the guard's terminal-check claim is never reclaimed
ok - auto-arm: need vanishing mid-cycle closes without a rewake
ok - auto-arm: mid-cycle AFK hands triage to the daemon with no rewake
ok - auto-arm: active in a marked secondmate home
ok - fm-lock: shared session-lock lib preserves the status path
exit=0

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

✅ **Test** - passed

✅ No issues found.

  • bash tests/fm-turnend-guard.test.sh at HEAD: all pass, including the 4 new race tests (slow start recognised, auto-arm stands down still blocks, dead or expired markers ignored, bounded wait then blocks)
  • bash tests/fm-claude-stop-autoarm.test.sh at HEAD: all pass (checks the per-pid starting marker)
  • Checked the regression: git checkout 1685d63 -- bin/fm-turnend-guard.sh bin/fm-claude-stop-autoarm.sh and reran tests/fm-turnend-guard.test.sh. The slow-start test fails with exit 2, the false blind-turn block. Restored the bin files to HEAD afterwards.
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

Alan Domio and others added 2 commits September 29, 2026 09:22
…larm while the Stop auto-arm is still starting

The guard's 800ms claim window raced the auto-arm's pre-claim work (harness
ancestry resolution is a chain of ps forks, seconds under load), so recovery
already under way read as absent. The auto-arm now announces itself with a
per-pid starting marker before that work and retracts it once its claim role is
published; the guard waits, bounded by the marker's age, for a live announced
auto-arm before blocking.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…sh. The failure came from the PR's own new test, not from the guard fix itself. After the change, all 72 tests in tests/fm-turnend-guard.test.sh pass locally. I have not re-run CI. **What failed:** CI (portable serial shard 4) failed on `--claude must still block when the starting auto-arm stood down without claiming: expected exit 2, got 0`. **Why:** That test puts a second fake Claude session in the home lock by running `other-claude -c 'sleep 60'`. For a one-command script like that, bash replaces itself with `sleep`. So the lock pid then shows up as `sleep 60` instead of a Claude-named process. The auto-arm's check (`fm_harness_pid_alive`) treats that as a stale lock owner, takes over the lock and claims the home, so the guard correctly allows the stop (exit 0). The test only blocked when the auto-arm checked the lock before bash made that switch. That is a timing race: it passed locally, but on the loaded CI runner it went the other way and waited out the full 15s start window. **Fix:** The fake session now runs `'sleep 60; :'` instead. The trailing `:` stops bash from replacing itself with `sleep`, so the lock pid stays a live Claude-named process. The auto-arm now deterministically stands down, and the test checks what it was meant to: the guard still blocks. No production code changed
@alandomio
alandomio merged commit a62f82d into main Sep 29, 2026
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant