Skip to content

fix(bin): recover Claude auto-arm from hung claims - #3156

Merged
kunchenguid merged 4 commits into
mainfrom
fm/fm-watcher-flap-autoarm-fix-r3
Aug 27, 2026
Merged

kunchenguid merged 4 commits into
mainfrom
fm/fm-watcher-flap-autoarm-fix-r3

Conversation

@kunchenguid

Copy link
Copy Markdown
Owner

Intent

Find and fix the fundamental cause of the Claude Stop-hook watcher flap in Firstmate: a hung auto-arm hook (bin/fm-claude-stop-autoarm.sh) held the single-flight lock state/.claude-autoarm.lock with its epoch ledger frozen at outcome=arming, and because the reclaim only fired on a terminal outcome or dead owner, every later Stop firing read the live hung owner as legitimate contention and exited 0, silently disabling all future auto-arms while the watcher lapsed between manual arms (the 2026-08-26 watcher flap). This branch is a CAPTAIN-AUTHORIZED CLEAN REBUILD from current main of the captain's accepted generation-based optimistic auto-arm redesign, superseding branch fm/fm-watcher-flap-autoarm-fix-r2 and PR #3150 (preserved read-only; firstmate closes the old PR after this one is green). The accepted design, all details deliberate and settled - none of the following are open questions: each auto-arm claim takes a monotonic generation (the epoch ledger state/.claude-autoarm-epoch's own sequence; the two-line entry - classic epoch record plus the claimant's MANDATORY pid-identity on line 2, read from the ledger alone and never substituted from any lock - IS the claim); no mutex is held across any blocking step (arming or output; the owner lock survives only as a micro-mutex around individual ledger writes with dead-holder self-reclaim); every firing defers to a live OPEN claim (outcome arming, owner alive, recorded identity successfully recomputes AND matches, not stuck - stuck means ledger entry AND watcher beacon state/.last-watcher-beat both older than FM_GUARD_GRACE default 300s; an identityless entry is never open); a finished, dead, identity-mismatched, identityless, or stuck claim is superseded by simply taking the next generation with NO revocation of a steady-state predecessor; a superseded owner goes COMPLETELY silent (cleanup only) - ownership is re-verified before every arm invocation, episode reset, failure-notice, alarm, budget, ledger write, and continuation; the irrevocable commit point of a translation is the EXIT STATUS (the harness delivers the collected stderr banner only on exit 2 and discards it on exit 0), so the owned terminal ledger write is the atomic commit - the winning generation exits 2 unconditionally after it with NO post-write ownership flip, a refused generation exits 0 silently even after printing, and the once-per-episode failure notice commits in the same owned critical section as the winning failed write; the guard (bin/fm-turnend-guard.sh --claude) reads the same predicates for recovery ownership and re-checks for a live open claim under its held locks before committing the attended fail-open alarm, with its ledger reads anchored to line 1. Deliberate accepted decisions: NO predecessor revocation and NO cross-output mutex in steady state; the upgrade-window-only legacy shim (fm_autoarm_claim_abandoned/fm_autoarm_release_abandoned, recognizing pre-generation lock-holding claims by their role file) retires a live identity-VERIFIED proven-stuck old-build owner via TERM before removing its lock - a successfully queued TERM suffices when the owner is stopped (delivery precedes any further user code on continue), an unverified or identityless pid is NEVER signalled, and missing identity evidence never blocks a proven-abandoned reclaim (it only disables the TERM and the mtime-preserving identity graft into the ledger); the stuck threshold reuses FM_GUARD_GRACE rather than adding a knob; TWO bounded residuals are documented accepted intent, each costing at most one extra exit-2 continuation turn absorbed by the durable idempotent wake queue: an owner that dies between its owned terminal write and its own process exit, and a hung old-build owner that resumes during the one legacy upgrade window; a claim misread as stuck in a pathological race (e.g. a beacon read right at system wake) costs at most one extra arm that the watcher singleton dedupes while the superseded owner still goes silent. Behavioral regression coverage is required and present for all three edge classes through the real hook and guard (open-claim deferral with no lock held; stuck-claim supersession and re-arm; an end-to-end genuinely-hung-owner run where a concurrent firing defers promptly mid-arm, a later firing supersedes, and the superseded owner exits silently without a second translation), plus the identityless/reused-pid loopholes, the superseded-owner arm-invocation boundary, and the legacy TERM, SIGSTOP-with-queued-TERM, and signal-free identityless reclaim paths; the legacy lock-shape tests are retained as upgrade-shim coverage. Changed bash stays macOS bash-3.2 compatible and shellcheck-clean; docs updated in their single-owner locations (docs/turnend-guard.md, docs/watcher-continuity.md).

What Changed

  • Replace lock-held auto-arm ownership with monotonic ledger generations, PID identity validation, stuck-claim supersession, and ownership checks that silence superseded hooks.
  • Align the Claude turn-end guard and failure commits with the open-claim predicate while preserving safe legacy lock reclamation.
  • Expand regression coverage and documentation for concurrent deferral, hung-owner recovery, identity edge cases, and legacy upgrade behavior.

Risk Assessment

✅ Low: The generation-based recovery and follow-up fixes preserve the required ownership, lock ordering, refusal, and silent-supersession invariants with no substantiated remaining defect.

Testing

Reproduced the original hung-owner flap on the base commit, then verified the target through both focused behavior suites and an end-to-end hook transcript showing lock-free deferral, generation supersession and re-arm, exactly-once marker recovery, and silent superseded-owner cleanup; the worktree remained clean.

Evidence: Baseline hung-owner watcher-flap reproduction

Source: Baseline hung-owner watcher-flap reproduction

not ok - the superseding generation must translate its own close: expected exit 2, got 0
baseline test exit=1 (nonzero reproduces the watcher-flap behavior)
Evidence: Focused end-to-end auto-arm behavior and persisted ledger evidence

Source: Focused end-to-end auto-arm behavior and persisted ledger evidence


=== OPEN CLAIM: concurrent firing defers without a lock ===
ok - auto-arm: a live open generation claim defers concurrent firings with no lock held
persisted ledger: epoch=464 owner_pid=60569 outcome=arming updated_at=1
arm invocations by competing firing: 0
owner mutex present after firing: no

=== STUCK CLAIM: later firing supersedes and re-arms ===
ok - auto-arm: a hung generation owner with no watcher beat is superseded so re-arming self-heals
persisted successor ledger: epoch=465 owner_pid=61438 outcome=rewake updated_at=1787802872
successful successor arm invocations:        1
owner mutex present after completion: no

=== FAILURE MARKER REFUSAL: no delivery until marker can commit ===
ok - auto-arm: marker-write refusal defers delivery until one successor commits the notice
final persisted ledger: epoch=3 owner_pid=64004 outcome=failed-suppressed updated_at=1787802874
notice marker exists after restored-path successor: yes
bounded arm attempts across three firings:        6

=== REAL HUNG OWNER: one successor translation, old owner silent ===
ok - auto-arm: a superseded owner goes silent - one supersession episode, one translation, no held mutex
winning persisted ledger: epoch=2 owner_pid=65761 outcome=rewake updated_at=1787802883
total arms (hung owner + successor):        2
superseded owner output bytes:        0
owner mutex present after both finish: no
Evidence: Claude Stop auto-arm regression transcript

Source: Claude Stop auto-arm regression transcript

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: marker-write refusal defers delivery until one successor commits the 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: owner-mutex contention preserves successor episode state
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: an abandoned owner claim is reclaimed so a lapsed cycle re-arms
ok - auto-arm: a legacy owner still arming is never reclaimed while its watcher keeps beating
ok - auto-arm: a fresh legacy arming claim is never reclaimed while its startup window is still open
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: a stuck live legacy owner is retired via TERM and its lock reclaimed
ok - auto-arm: a SIGSTOPped legacy owner is reclaimed with TERM pending and dies on continue
ok - auto-arm: a live open generation claim defers concurrent firings with no lock held
ok - auto-arm: a hung generation owner with no watcher beat is superseded so re-arming self-heals
ok - auto-arm: an identityless arming ledger never defers the gate (reused-pid loophole closed)
ok - auto-arm: a superseded owner never re-invokes the arm and leaves its successor's claim untouched
ok - auto-arm: a superseded owner goes silent - one supersession episode, one translation, no held mutex
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
Evidence: Turn-end guard regression transcript

Source: Turn-end guard regression transcript

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: 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: a hung owner frozen at arming with no watcher beat no longer allows a blind stop
ok - fm-turnend-guard --claude: a live open generation claim owns recovery with no lock held
ok - fm-turnend-guard --claude: a stuck generation claim no longer allows a blind stop
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: secondmate home re-blocks unclaimed and allows auto-arm-claimed stops

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 1 issue found → auto-fixed (2) ✅
  • 🚨 bin/fm-wake-lib.sh:1198 - Intent requires that “the once-per-episode failure notice commits in the same owned critical section as the winning failed write,” but marker creation explicitly ignores failure (: > "$marker" ... || true) and still returns success. If the marker cannot be created (for example, it is a dangling symlink), the hook commits outcome=failed, delivers exit 2 and the notice, yet leaves no marker; the next firing can deliver the notice again. Treat marker-write failure as a refused commit so that generation exits 0 and a successor retries.

🔧 Fix: Refuse auto-arm commits when notice marker creation fails
1 error still open:

  • 🚨 bin/fm-claude-stop-autoarm.sh:266 - This contradicts the required invariant that a superseded owner “goes COMPLETELY silent (cleanup only).” The ownership check and fm_failure_episode_reset are not atomic. Concrete path: an old long-running claim observes a beacon at age 299s and passes line 262; after the beacon crosses the 300s grace, a successor supersedes it, fails, and commits its notice/alarm/budget state; the old process then resumes at line 266 and deletes that successor state, allowing the episode notice to repeat. The comment that a fresh beacon makes supersession impossible is only momentarily true. Perform the generation check and reset while holding the owner micro-mutex, acquiring the budget lock second, so a successor cannot publish between verification and mutation.

🔧 Fix: Make episode reset atomic with generation ownership
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • git diff --stat 524994c8b483513eababb4e791b8b06b3b4ec974..HEAD and targeted implementation/test diff inspection
  • Baseline hung-owner regression against commit 524994c8b483513eababb4e791b8b06b3b4ec974 using the executable hook test harness
  • bash tests/fm-claude-stop-autoarm.test.sh
  • bash tests/fm-turnend-guard.test.sh
  • Focused executable-hook scenarios for open-claim deferral, stuck-claim supersession, failure-marker refusal/retry, and a genuinely hung superseded owner
  • git status --short and transient-artifact checks after testing
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

On a Claude primary, a Stop-hook auto-arm process that hung mid-arm held
the single-flight owner lock with its epoch ledger frozen at
outcome=arming, and the abandonment proof read any live lock holder in
arming as legitimately deciding forever. Every later Stop firing exited
0 at the lock, the turn-end guard kept deferring to the hung owner as
recovery under way, and the watcher was never auto-re-armed again for
the rest of the session - supervision survived only on manual arms and
lapsed between them (the 2026-08-26 watcher flap).

Corrections layered onto the lock-held-across-arm shape each reopened
the same concurrency class one level down, so this replaces the claim
machinery wholesale with a generation-based optimistic design:

- The epoch ledger's monotonic sequence IS the claim generation; the
  two-line entry (classic epoch record plus the claimant's MANDATORY
  pid-identity) is the claim. Every firing defers to a live OPEN claim:
  outcome arming, owner alive, identity recomputes and matches, and not
  stuck (entry and watcher beacon both older than the guard grace).
- A finished, dead, identity-mismatched, identityless, or stuck claim
  is superseded by simply taking the next generation - no signalling or
  revocation of a steady-state predecessor.
- No mutex is held across arming or output; the owner lock survives
  only as a micro-mutex around individual ledger writes. A superseded
  owner goes completely silent: ownership is re-verified before every
  arm invocation, episode-state mutation, ledger write, and
  continuation.
- The irrevocable commit point of a translation is the exit status
  (the harness delivers the collected stderr only on exit 2), so the
  owned terminal ledger write is the atomic commit: the winning
  generation exits 2 unconditionally after it, a refused one exits 0
  silently even after printing, and the once-per-episode failure notice
  commits in the same owned critical section as the winning failed
  write. Two bounded residuals are documented accepted intent: an owner
  dying between its owned write and its own exit, and a hung old-build
  owner resuming during the one legacy upgrade window.
- The pre-generation lock-holding claim shape keeps defer-or-reclaim
  behavior through a legacy shim: a live identity-verified stuck owner
  is retired via TERM (with a queued TERM sufficient when the owner is
  stopped) before its lock is removed, an unverified or identityless
  pid is never signalled but never blocks a proven-abandoned reclaim,
  and the lock's identity evidence is grafted into the ledger
  (mtime-preserving) so pid-reuse protection survives the lock.
- The guard reads the same predicates for recovery ownership and its
  terminal fail-open (which re-checks for a live open claim under the
  held locks before committing the attended alarm), with ledger reads
  anchored to line 1 so the identity line can never confuse them.

Behavioral regression coverage exercises all three edge classes through
the real hook and guard - a live open claim defers with no lock held, a
stuck claim is superseded and the home re-arms, and an end-to-end run
with a genuinely hung owner shows a concurrent firing deferring
promptly mid-arm, a later firing superseding the stuck owner, and the
superseded owner exiting silently without a second translation - plus
the identityless/reused-pid loopholes, the superseded-owner arm
boundary, and the legacy TERM, SIGSTOP, and signal-free reclaim paths.
@greptile-apps

greptile-apps Bot commented Aug 27, 2026

Copy link
Copy Markdown

Confidence Score: 5/5

The PR appears safe to merge with no concrete changed-code defect identified.

Generation ownership is revalidated at shared-state commit boundaries, the guard serializes its terminal decision against claim publication, and legacy process signaling requires a matching live PID identity.

Reviews (1): Last reviewed commit: "no-mistakes(document): Update auto-arm g..." | Re-trigger Greptile