Skip to content

chore: update pull request - #3150

Closed
kunchenguid wants to merge 11 commits into
mainfrom
fm/fm-watcher-flap-autoarm-fix-r2
Closed

kunchenguid wants to merge 11 commits into
mainfrom
fm/fm-watcher-flap-autoarm-fix-r2

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. After review rounds showed that every correction layered onto the lock-held-across-arm shape reopened the same concurrency class one level down (an ownership re-check racing a resuming watcher; a reclaim mutex held across the blocking banner write recreating an unreclaimable live owner; terminal publication allowing a reclaimed owner and its replacement to translate one close twice), the captain explicitly decided to REPLACE the lock-based held-mutex approach wholesale with a generation-based optimistic design - this is the accepted design, not an open question: each auto-arm claim takes a monotonic generation (the epoch ledger's own sequence; the two-line ledger entry with the claimant's pid-identity on line 2 IS the claim), no mutex is held across any blocking step (arming or output; state/.claude-autoarm.lock survives only as a micro-mutex around individual ledger writes), every firing defers to a live OPEN claim (outcome arming, owner alive, identity matched, not stuck - stuck means ledger entry AND watcher beacon state/.last-watcher-beat both older than the guard grace FM_GUARD_GRACE default 300s), a finished, dead, identity-mismatched, or stuck claim is superseded by simply taking the next generation with no revocation of the predecessor, and the owner re-verifies it still holds the newest generation immediately before each ledger write and each emit, going completely silent when superseded - so a newer generation cleanly supersedes a stuck or older one, structurally eliminating all three edge classes at once while preserving the single-flight guarantee (exactly one open claim arms; one supersession episode produces exactly one translation), the identity/ownership safety, and the never-block-the-Stop-decision contract. The guard (bin/fm-turnend-guard.sh --claude) reads the same predicates for recovery ownership and its terminal fail-open, with its ledger reads anchored to line 1 so the identity line cannot confuse them. Deliberate accepted decisions: the pre-generation lock-holding claim shape keeps defer-or-reclaim behavior through a retained legacy shim (fm_autoarm_claim_abandoned/fm_autoarm_release_abandoned, now with the reclaimed lock's identity evidence grafted into the ledger under the steal mutex, preserving the ledger's mtime, so pid-reuse protection survives lock removal) - required so an upgrade mid-session can neither double-arm nor deadlock behind a hung legacy hook; the stuck threshold reuses FM_GUARD_GRACE rather than adding a knob; a claim misread as stuck in a pathological race (e.g. right at system wake) costs at most one extra arm that the watcher singleton dedupes while the superseded owner still goes silent instead of double-firing; and the residual micro-mutex holds are bounded to a few non-blocking file operations with dead-holder self-reclaim. Behavioral regression tests are required to cover ALL THREE edge classes through the real hook and guard, including an end-to-end run where a genuinely hung live owner is superseded and then goes silent without a second translation; the legacy lock-shape tests are retained as upgrade-shim coverage. Changed bash must stay macOS bash-3.2 compatible and shellcheck-clean; docs updated in their single-owner locations (docs/turnend-guard.md, docs/watcher-continuity.md). Note: this branch supersedes fm/fm-watcher-flap-autoarm-fix-r1, whose cancelled run's lock-based fix commits were deliberately invalidated by the captain and kept out of this rebuilt history.

What Changed

Final changed paths and statuses:

M	bin/fm-claude-stop-autoarm.sh
M	bin/fm-turnend-guard.sh
M	bin/fm-wake-lib.sh
M	docs/configuration.md
M	docs/supervision-protocols/claude.md
M	docs/turnend-guard.md
M	docs/watcher-continuity.md
M	tests/fm-claude-stop-autoarm.test.sh
M	tests/fm-turnend-guard.test.sh

Risk Assessment

✅ Low: The generation-based ownership, terminal-write commit model, identity checks, and legacy reclamation paths are internally consistent with the stated intent, with no remaining source-verifiable merge blocker found.

Testing

Both focused behavioral suites passed, including generation ownership, legacy reclaim, identity safety, guard recovery, and terminal-write commit cases. An end-to-end transcript additionally demonstrates that a genuinely hung owner is superseded with exactly one user-visible translation while the predecessor resumes silently.

Evidence: Hung live owner supersession and single-translation transcript

Source: Hung live owner supersession and single-translation transcript

=== Concurrent Stop while owner A is live/open ===
exit=0 output_bytes=0 arm_count=1
=== Stop after owner A and watcher beacon become stuck ===
exit=2
firstmate watcher wake - one supervision event needs a handling turn now.
stale: fixture-win actionable
Run bin/fm-wake-drain.sh first, handle the wake, then run its exact WAKE_ACK_REQUIRED --ack-through command. Until that post-handling acknowledgement, interruption leaves the wake durable for idempotent re-handling. This Stop hook owns watcher continuity: when the handling turn ends, the next needed cycle arms automatically - do NOT run bin/fm-watch-arm.sh after an ordinary wake.
=== Original owner A resumes after supersession ===
exit=0 delivered_output_bytes=0
=== Final persisted claim ===
epoch=2 owner_pid=24184 outcome=rewake updated_at=1787796589
Wed Aug 26 19:09:42 2026     bash /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T//fm-claude-stop-autoarm.COgbla/evidence-supersession/bin/fm-claude-stop-autoarm.sh
arm_count=2 micro_mutex_present=no

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 3 issues found → auto-fixed (8) ✅
  • 🚨 bin/fm-claude-stop-autoarm.sh:274 - The terminal outcome is published before the emit. Once rewake/failed is written, the claim is no longer OPEN, so another Stop firing can take the next generation before lines 278–302 emit; the predecessor never calls fm_autoarm_still_owner again and can then double-translate. This contradicts the required invariant that the owner “re-verifies it still holds the newest generation immediately before each ledger write and each emit, going completely silent when superseded.” Move this into a generation-aware handoff boundary that does not make the claim supersedable before the emit and cannot let a blocked writer resume after supersession; another detached pre-emit check alone retains the race.
  • 🚨 bin/fm-turnend-guard.sh:335 - terminal_fail_open checks for an OPEN claim only before acquiring the ledger micro-mutex. A claimant can publish outcome=arming after line 318 but before the guard acquires OWNER_LOCK; the guard then takes terminal-check, never rechecks the claim, creates FAILURE_ALARM, and emits the attended fail-open while recovery is active. This contradicts the requirement that the guard use the same recovery predicates for terminal fail-open. Recheck fm_autoarm_claim_open after acquiring OWNER_LOCK and before committing the alarm, where a claimant cannot race the decision.
  • 🚨 bin/fm-wake-lib.sh:1138 - New claims do not guarantee the required two-line identity-bearing ledger: fm_pid_identity failure is ignored and line 2 is omitted. Additionally, fm_autoarm_claim_open at line 1101 treats a recorded identity as acceptable when recomputation fails rather than proving it matches. Thus an unrelated reused live PID can be accepted as an OPEN owner until the stuck threshold. This contradicts the required “two-line ledger entry with the claimant's pid-identity on line 2 IS the claim” and preserved identity safety; either fail the claim when identity cannot be recorded or obtain an explicitly approved fallback contract, and require successful equality when an identity is present.

🔧 Fix: Fix auto-arm ownership handoff and identity validation
3 errors still open:

  • 🚨 bin/fm-claude-stop-autoarm.sh:189 - The required “one supersession episode produces exactly one translation” invariant remains breakable during the blocking emit. If the ledger and beacon are already past grace when owner A reaches this path, line 188 succeeds, printf blocks, and firing B can classify A as stuck, claim N+1, and translate. A then resumes and completes its own banner and exit 2 without another ownership check. The new test only supersedes A while it is still inside the arm, not while output is blocked. Use an atomic durable translation handoff that prevents a successor from translating after A commits to emit, without holding the micro-mutex across output.
  • 🚨 bin/fm-claude-stop-autoarm.sh:260 - The bare exit-2 paths still publish a terminal outcome before emitting the continuation. For example, when a healthy watcher is found but failure reset fails, autoarm_finalize failed-suppressed makes the claim immediately supersedable; another firing can take N+1 before line 266 while the predecessor still exits 2. The same sequence exists at lines 308–313. This contradicts the required owner re-verification before every bare exit-2 continuation and can produce two translations. Keep the claim non-supersedable through the exit-2 handoff or introduce a durable translation token that successors honor.
  • 🚨 bin/fm-wake-lib.sh:1228 - The legacy upgrade shim cannot guarantee the required “upgrade mid-session can neither double-arm nor deadlock” behavior. A live identity-matched legacy owner whose arming entry and beacon exceed grace is declared abandoned and its held lock is removed at line 1278. A new generation can then arm and translate, but the old pre-generation process has no generation check: if it resumes, it writes another ledger outcome and emits too. Reclaiming a live legacy process therefore needs a supported revocation/termination boundary with confirmed retirement, or it must continue deferring; merely grafting identity into the ledger cannot silence old code.

🔧 Fix: Retire legacy owners before generation reclaim
2 errors still open:

  • 🚨 bin/fm-claude-stop-autoarm.sh:253 - A superseded owner can still reset the current failure episode. Concrete path: generation A hangs past grace; B supersedes it, records a failure notice/alarm state; A resumes, observes B's healthy watcher, and calls fm_failure_episode_reset before checking generation ownership. It deletes B's notice, alarm, and budget, then only discovers supersession during autoarm_finalize. This contradicts the required “superseded owner goes completely silent (cleanup only)” invariant. Make failure reset generation-owned at the shared OWNER_LOCK→BUDGET_LOCK boundary before mutating episode state.
  • 🚨 bin/fm-claude-stop-autoarm.sh:190 - The failure-notice side effect is outside the generation handoff. autoarm_emit_finalize swallows a refused terminal write, then line 305 creates FAILURE_NOTICE even if the owner was superseded during its blocking emit. If the successor completed an actionable cycle, the stale predecessor can leave a notice with a rewake ledger; the next real failure suppresses its only banner and may advance toward attended fail-open without the promised notice. Even without blocked output, publishing failed before creating the marker lets a paused owner and immediate successor both emit the once-per-episode notice. Keep the claim open through marker publication, and do not mutate the marker when the owned terminal write is refused.

🔧 Fix: Gate failure episode state by generation ownership
1 error still open:

  • 🚨 bin/fm-claude-stop-autoarm.sh:189 - The required “one supersession episode produces exactly one translation” and “superseded owner goes completely silent” invariants remain breakable after output completes. autoarm_emit_finalize ignores a refused terminal write and returns success; similarly, the failure-notice path ignores fm_autoarm_failure_notice_finalize at line 317. Concrete path: A prints its banner and publishes a terminal outcome (or pauses before finalization), B immediately claims N+1 and exits 2, then A resumes and also exits 2 at line 296 or 319. This is outside the accepted case of an owner blocked inside its emit syscall. Propagate finalization refusal and perform the same final lockless ownership check immediately before both exit-2 translations.

🔧 Fix: Gate translations on successful owned terminal writes
1 error still open:

  • 🚨 bin/fm-wake-lib.sh:1106 - fm_autoarm_claim_open skips identity verification when line 2 is absent. A fresh one-line outcome=arming ledger naming an unrelated live/reused PID therefore returns open, causing the hook to exit 0 and the guard to allow a blind stop. This contradicts the required predicate “owner alive, identity matched” and the requirement that the two-line entry “IS the claim.” Require identity for generation claims; route identityless lock-holding legacy claims through the role-based legacy shim instead.

🔧 Fix: Require identity evidence for open generation claims
1 error still open:

  • 🚨 bin/fm-wake-lib.sh:1417 - The required legacy upgrade shim can deadlock behind an identityless live legacy owner. For a stale outcome=arming or terminal ledger whose matching role-bearing lock has a live PID but no pid-identity (a supported pre-generation shape), fm_autoarm_claim_abandoned proves abandonment, but this branch makes fm_autoarm_release_abandoned refuse removal forever. Every subsequent hook therefore exits 0 without re-arming. This contradicts the requirement that the retained legacy shim ensure an upgrade can “neither double-arm nor deadlock behind a hung legacy hook.” Reclaim the already-proven legacy lock without requiring identity evidence; retain identity only for safe signaling/grafting. The former identityless terminal-reclaim test was changed to add identity, masking this path.

🔧 Fix: Reclaim identityless abandoned legacy claims safely
1 error still open:

  • 🚨 bin/fm-claude-stop-autoarm.sh:310 - The required “one last-resort notice per failure episode” can still be consumed without delivery. Concrete path: owner A prints the failure banner and fm_autoarm_failure_notice_finalize commits both outcome=failed and the notice marker; owner B then supersedes A, fails, sees the committed marker, writes failed-suppressed, and exits 2 without a banner; A's final ownership check fails and it exits 0, so Claude discards A's stderr. The episode now has a committed notice marker but no delivered notice. This contradicts the intent that the exhausted failure “emits one last-resort notice.” Make notice consumption conditional on the generation whose exit-2 translation actually wins, at the earliest shared terminal-claim boundary.

🔧 Fix: Commit translations with successful owned terminal writes
1 error still open:

  • 🚨 bin/fm-wake-lib.sh:1413 - The required legacy shim can still “deadlock behind a hung legacy hook.” A proven-abandoned, identity-matched legacy owner stopped with SIGSTOP remains alive with the same identity after TERM is queued; after the bounded wait this branch refuses reclamation and leaves its lock. Every later Stop firing repeats the same failure and never re-arms. Adjust the shared legacy-release boundary so a successfully signalled, verified owner cannot retain the lock indefinitely—for example, safely reclaim once TERM is pending rather than requiring observed process exit.

🔧 Fix: Reclaim signalled stopped legacy owners safely
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • bash tests/fm-claude-stop-autoarm.test.sh
  • bash tests/fm-turnend-guard.test.sh
  • Manual end-to-end hung-owner scenario using the real Stop hook: concurrent open claim deferred, stale live owner was superseded, successor delivered one rewake, and resumed predecessor exited silently without overwriting the ledger.
✅ **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).

Successive corrections inside the lock-based shape each reopened the
same class one level down: an ownership re-check raced a resuming
watcher, holding the reclaim mutex across the banner write recreated an
unreclaimable live owner, and terminal publication let a reclaimed
owner and its replacement translate one close twice. So this replaces
the held-lock claim wholesale with a generation-based optimistic
design:

- The epoch ledger's monotonic sequence IS the claim generation; the
  entry itself (plus a second line recording the claimant's
  pid-identity) is the claim. Every firing defers to a live OPEN claim:
  outcome arming, owner alive, identity matched, and not stuck (entry
  and watcher beacon both older than the guard grace).
- A finished, dead, identity-mismatched, or stuck claim is superseded
  by simply taking the next generation - no unlock, signal, or
  revocation of the predecessor.
- No mutex is held across arming or output. The owner lock survives
  only as a micro-mutex around individual ledger writes, and the owner
  re-verifies it still holds the newest generation before every ledger
  write and every emit, going silent when superseded - so a hung
  predecessor can neither block re-arming forever nor double-translate
  one close, and single-flight, identity safety, and the
  never-block-the-Stop-decision contract are preserved.
- The lock-holding claim shape from pre-generation builds keeps
  defer-or-reclaim behavior through a legacy shim (with the reclaimed
  lock's identity evidence grafted into the ledger so pid-reuse
  protection survives the lock's removal), so an upgrade mid-session
  cannot double-arm or deadlock.

The guard's ownership, terminal fail-open, and budget paths read the
same predicates; its ledger reads are anchored to line 1 so the
identity line can never confuse them.

Regression coverage exercises all three edge classes through the real
hook and guard: a live open generation claim defers with no lock held,
a stuck claim is superseded and the home re-arms (hook exit-2 and guard
block), 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. The legacy lock-shape suite is retained
as the upgrade shim's coverage.
@greptile-apps

greptile-apps Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

Confidence Score: 4/5

The PR should not merge until failure-notice output and its durable terminal commit can no longer be separated by interruption or supersession.

The revised protocol still prints the once-per-episode failure notice before recording the failed outcome that makes its pending marker durable, so a process stopping in that window allows a later generation to repeat the notice and makes the guard treat the delivered episode as unnotified.

Files Needing Attention: bin/fm-claude-stop-autoarm.sh, bin/fm-wake-lib.sh

Reviews (2): Last reviewed commit: "no-mistakes: apply CI fixes" | Re-trigger Greptile

Comment on lines +304 to +305
printf '%s\n' "$MESSAGE" >&2
if ! fm_autoarm_failure_notice_finalize "$STATE" "$MY_GEN"; then

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Notice commit remains nonatomic

When the auto-arm owner prints the failure notice and then exits, is killed, or is superseded before fm_autoarm_failure_notice_finalize publishes outcome=failed, the pending marker is not treated as delivered. The next claimant can remove the marker and emit the same notice again, while the guard treats the episode as unnotified.

@kunchenguid

Copy link
Copy Markdown
Owner Author

Superseded by the captain-authorized clean rebuild in PR #3156 (green). Closing this contaminated branch's PR; branch preserved read-only for audit, not deleted.

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