Repository navigation
fix(bin): prevent watcher recovery acknowledgement livelock - #2212
Merged
Merged
Conversation
A watcher cycle that opened and closed while the model handled its drained wakes minted a fresh recovery generation, which invalidated the exact acknowledgement the drain had just printed. That acknowledgement then consumed nothing, so the marker stayed pending and every later arm spent its whole cycle re-announcing the same recovery instead of supervising - a livelock the home could not leave on its own. A downtime publication now reuses the generation of an outstanding handling episode, so a close during the handling window cannot orphan the printed acknowledgement. The acknowledgement itself separates its two facts: queue-row consumption is bound to the monotonic --ack-through sequence and always happens, while only retiring the episode is bound to --recovery-generation. A generation that moved on is a non-fatal result that names its own remedy instead of a refusal that consumes nothing.
…acknowledgements safely
abhi-sama
added a commit
to abhi-sama/firstmate
that referenced
this pull request
Aug 12, 2026
…y livelock fix) (#9) * docs: add project vision (kunchenguid#1997) * docs: add firstmate vision * no-mistakes(test): Classify VISION.md as public product documentation * no-mistakes(document): Restore approved one-file vision diff * no-mistakes: apply CI fixes * fix(spawn): force regular Pi TUI for crews (kunchenguid#2005) * fix(spawn): force regular Pi TUI for crews * no-mistakes(document): Documented Pi regular TUI launch mode * fix(cmux): classify borderless Claude composers (kunchenguid#2029) * fix(cmux): classify borderless Claude composer * no-mistakes(review): Normalize cmux NBSP prompts across locales * no-mistakes(document): Document cmux borderless Claude composer classification * docs(stow): generalize read-before-write in the public stow skill (kunchenguid#2091) The public installer-facing stow skill scoped its classify-then-replace discipline to TODO/BACKLOG items only, so findings routed to a memory file had no stated rule against a blind append or a wholesale overwrite. Step 6 now classifies every finding against the destination's current contents as new, duplicate, superseding, or obsolete, and states the considered replacement each classification implies. The outcomes follow the tiered-memory contract already in the file: an obsolete entry is refreshed, archived, or replaced in a way that preserves its fact, a duplicate folds into the entry that already carries it, and a superseded body worth keeping leaves through step 7's existing exits rather than a second recovery mechanism. * fix: resurface durable supervision work after re-arm (kunchenguid#2065) * fix(watcher): resurface durable work after downtime * no-mistakes(review): Make watcher rearm recovery durable and cursor-safe * no-mistakes(review): Persist safe recovery markers across migration lock recovery * no-mistakes(review): Retain stale lock when recovery marker publication fails * no-mistakes(review): Preserve delivery-gap recovery and quarantine malformed markers * no-mistakes(review): Serialize recovery consumption and report acknowledgment failures * no-mistakes(review): Centralize recovery publication before clearing watcher evidence * no-mistakes(review): Guarantee recovery evidence across queue and lock handoffs * no-mistakes(review): Publish recovery evidence before durable wake commits * no-mistakes(review): Replace recovery marker Perl dependency with Node * no-mistakes(review): Keep interrupted wakes durable until handling acknowledgment * no-mistakes(review): Add post-handling durable wake acknowledgements * no-mistakes(review): Enforce post-handling acknowledgement across recovery and AFK return * no-mistakes(review): Bind wake acknowledgements to recovery generations * no-mistakes(review): Align wake regressions with generation-bound acknowledgements * no-mistakes(document): Document durable re-arm recovery semantics * no-mistakes(lint): Resolve ShellCheck warnings in recovery and watcher tests * no-mistakes: apply CI fixes * test(watcher): assert post-handling wake replay * no-mistakes(review): Prevent successor loops and adopt legacy wake generations * no-mistakes(review): Rearm durable wakes without recursive successor recovery * no-mistakes(review): Align recovery tests with handling marker state * no-mistakes(review): Delay handling transition until successor launch is established * no-mistakes(review): Confirm wake handling only after successful prompt delivery * no-mistakes(review): Acknowledge AFK wakes only after evidence publication * no-mistakes(review): Prevent AFK wake loss before post-handling acknowledgement * no-mistakes(document): Document durable wake acknowledgement semantics * no-mistakes(lint): Suppress false positive for recovery action output * no-mistakes: apply CI fixes * no-mistakes: apply CI fixes * ci: measure Herdr automation on Windows runners (kunchenguid#2100) * ci: add Windows Herdr automation spike * ci: run Windows spike on its pull request * fix: wait for Windows Herdr command output * fix: run ANSI probe in pane shell * ci: keep Windows Herdr spike manually triggered * docs: clarify Windows Herdr spike verdict * feat(ahoy): guide captains through open decisions (kunchenguid#2099) * Add guided ahoy decision flow * no-mistakes(document): Document guided Ahoy decision flow * fix(stow): enforce startup-memory budget decisions (kunchenguid#2110) * Harden stow memory budget policy * Refine internal stow offload policy * no-mistakes(review): Enforce shared-budget decisions and autonomous offload * fix(spawn): refresh pooled worktrees from origin before launch (kunchenguid#2116) * fix(spawn): refresh pooled worktree base * no-mistakes(document): Document spawn base-freshness invariant * no-mistakes: apply CI fixes * fix(composer): unify safe classification across backends (kunchenguid#2102) * refactor(composer): one shape owner behind thin capture adapters, whole matrix fixed Consolidate every composer shape - bordered boxes (all families, geometry, titled bottom borders), bare agent-glyph rows and their wrap regions, opencode's left bar, and pi's identity-gated separator pair - into fm_composer_classify_screen in bin/fm-composer-lib.sh. Adapters now contribute only a capture and a declarative capability descriptor (styled/cursor/identity/rows); capability differences change how confidently a shape is judged, never what the shapes are, so a new harness shape is teachable in exactly one place. Correctness fixes landed as part of the consolidation (audit data/fm-composer-consolidation-audit-s1): - locale-safe Unicode-space normalization in the shared owner (closes the fleet-wide half of kunchenguid#1988; cmux's local byte-exact NBSP case deleted; naming converges with PR kunchenguid#1995's normalization primitive) - muse's bare glyph joins the shared set, unbreaking muse on herdr/cmux/orca - orca learns the borderless bare shape, drops its backward-paged composer window, and can no longer classify a stale startup banner as the composer - tmux tolerates a titled bottom border, unbreaking grok steering - the left-bar shape makes opencode readable on every backend - zellij gets a real classifier through dump-screen --ansi, replacing the content-diff submit heuristic that could confirm an undelivered message and close a --resolve-key decision (the fleet's only false positive) - fm-spawn's kimi launch-readiness regex (the fourth shape copy) now routes through the shared classifier The strict blank-row posture applies fleet-wide (captain decision blank-row-injection-posture): no positive container proof = unknown = defer, replacing tmux's permissive blank-cursor-row rule. Away-mode injection was re-validated end to end on real tmux (defer on partial input and unproven rows, clean delivery with swallowed-Enter retry into proven-empty composers). The tmux submit core gains a baseline-idle turn-started conversion so pi steering stays confirmed while its working screen hides the composer; busy conversion without that baseline remains forbidden. Plain-capture backends now degrade a glyph row carrying trailing text to unknown instead of a false pending, per the approved capability rule. Portable regressions pin the full byte-capture matrix from the audit under a UTF-8 locale and LC_ALL=C, the strict-vs-permissive divergence, and deliberate signal separation; the opt-in live guard (tests/fm-composer-matrix-live-e2e.test.sh) verified every installed harness against the real classifier, recorded in docs/verification/runtime-backends.md. * no-mistakes(review): Fix Pi glyph ambiguity and complete profile matrix * no-mistakes(review): Preserve bare verdict when Pi identity probe is absent * no-mistakes(review): Harden composer structure and titled-border geometry * no-mistakes(review): Require proven idle baseline and strict Zellij guard * no-mistakes(review): Reject box bottom borders as composer input rows * no-mistakes(review): Prove Zellij probe typing before classifier retries * no-mistakes(review): Preserve Pi identity uncertainty and scan full left-bar drafts * no-mistakes(review): Verify Zellij text lands before submitting * no-mistakes(review): Scope Zellij typing verification to selected composer content * no-mistakes(review): Verify Zellij pastes through composer-scoped content deltas * no-mistakes(review): Prove wrapped bare Zellij pastes through composer extraction * no-mistakes(review): Invalidate stale cursorless composers below dead shell prompts * no-mistakes(review): Handle shell prompt placeholders in composer extraction * no-mistakes(review): Classify cursorless bare continuation regions safely * no-mistakes(review): Reject stale cursorless containers below live activity * no-mistakes(review): Preserve prompt glyphs in wrapped Zellij pastes * no-mistakes(review): Reject live shell rows during composer extraction * no-mistakes(review): Preserve wrapped glyph continuations through submit retries * no-mistakes(review): Scope idle placeholders to proven positions * no-mistakes(review): Restore boxed placeholders and live prompt reanchoring * no-mistakes(review): Fix Zellij placeholder and wrapped glyph paste proof * no-mistakes(document): Align composer architecture documentation * no-mistakes(lint): Fix ShellCheck warnings in composer refactor * no-mistakes: apply CI fixes * docs(verification): record the trusted-checkout live matrix rerun The pipeline's isolated gate worktree is untrusted, so claude, grok, and muse stopped at first-launch trust dialogs there (the guard refuses to confirm them by design). This rerun from the trusted checkout at the final validated head verified all six installed harnesses, the strict blank-row deferral, and the hardened zellij false-positive probe live. * no-mistakes(document): Align composer verification evidence * no-mistakes: apply CI fixes * no-mistakes(review): Restore proven box bottom-cursor classification * no-mistakes(review): Preserve styled placeholder-like drafts as pending * no-mistakes(document): Align composer safety and Zellij delivery documentation * no-mistakes: apply CI fixes * docs(verification): refresh the live matrix with the final-head trusted rerun The post-validation rerun from the trusted checkout verified all six installed harnesses at the branch's final head, including Claude 2.1.227 (auto-updated since the audit's captures) and Grok, which the untrusted gate worktree could not verify past their first-launch trust dialogs. * fix(spawn): gate Pi TUI mode by CLI capability (kunchenguid#2117) * fix(spawn): gate Pi regular TUI flag by capability * no-mistakes(review): Document conditional Pi TUI capability detection * no-mistakes(review): Pin Pi probing and launch to one executable * no-mistakes(review): Preserve literal pinned Pi paths and update documentation * no-mistakes(review): Defer pinned Pi path insertion until final substitution * no-mistakes(document): Document version-safe Pi launch probing * no-mistakes: apply CI fixes * no-mistakes: apply CI fixes * docs(vision): elevate experience, pain narrative, and distro virtues (kunchenguid#2147) * docs(vision): elevate experience, pain narrative, and distro virtues Fold the captain's public vision framing into VISION.md: peace of mind as a primary goal, multi-session context-switch pain as the problem one interface solves, clone-and-run setup ease, self-evolution including community, and explicit harness/backend orthogonality. Reconcile experience-as-garnish into experience-as-purpose and update aligns/resists accordingly. * docs(vision): state the experience goal positively Drop the negative "not a smart workflow / useful tool / impressive technology" pretext. Lead straight into the positive experience north star. * feat(bin): reconcile inactive terminal crew outcomes (kunchenguid#2167) * fix: reconcile inactive terminal outcomes * fix: stream secondmate summary inputs * no-mistakes(review): Fix reconciliation locking and request delivery retries * no-mistakes(review): Prevent retries after unknown request delivery * no-mistakes(document): Clarify inactive reconciliation cadence and receipts * no-mistakes(lint): Quote terminal status arguments in reconciliation tests * refactor: simplify inactive outcome reconciliation * no-mistakes(review): Bound inactive reconciliation scans with durable progress * no-mistakes(review): Bound reconciliation and deduplicate recovery notices * no-mistakes(document): Document inactive outcome reconciliation contracts * no-mistakes(review): Reject relative local secondmate parent routes * no-mistakes(review): Key terminal receipts by spawn incarnation * no-mistakes(review): Stabilize legacy receipts and lock reconciliation snapshots * no-mistakes(review): Fail closed on invalid secondmate identity markers * no-mistakes(document): Document durable inactive-outcome reconciliation * no-mistakes: apply CI fixes * no-mistakes: apply CI fixes * no-mistakes: apply CI fixes * ci: raise Herdr test timeout (kunchenguid#2191) * fix: refresh stale Pi instructions after compaction (kunchenguid#2163) * fix(session-start): refresh drifted instructions on stale rebuilds * test(session-start): prove Pi instruction refresh end to end * no-mistakes(review): Fix stale instruction refresh and baseline integrity * no-mistakes(review): Preserve true-start baselines across Pi continuations * no-mistakes(review): Correct Pi continuation classification and live expectation * no-mistakes(review): Correct Pi continuation coverage documentation * no-mistakes(review): Fix read-only refresh and exact Pi session restores * no-mistakes(review): Classify Pi create-if-missing sessions correctly * no-mistakes(review): Classify named Pi sessions using immutable headers * no-mistakes(review): Correct Codex interactive coverage diagnostic * no-mistakes(document): Document immutable Pi compaction instruction refresh * no-mistakes(document): Correct Pi refresh documentation and validation claims * feat: add deterministic condition-to-action watcher (kunchenguid#2200) * feat(bin): add deterministic condition->action watch adapter on the process-event channel Register a (condition, action) pair once with bin/fm-procevent-when.sh and the existing process-to-event runner polls the condition tokenlessly, fires the action at most once on a stable true, and wakes firstmate exactly once with the captured outcome - instead of burning an agent turn per re-check. The pair is stored privately under state/when/ and hash-bound by a trust record the same way fm-check-register.sh binds a custom check, so a mutated spec is refused without executing anything. A durable exclusive fired marker claimed before the action makes restarts and re-polls unable to double-fire; every failure path (mutated spec, condition error past budget, expired deadline, failed action, uncaptured earlier fire) ends in a terminal captured outcome that wakes firstmate rather than a silent retry. Eligibility stays a firstmate judgment: only exact, safe, reversible actions may be bound, and judgment- needing or destructive actions keep the wake-and-decide flow. * no-mistakes(review): Harden when watcher concurrency, deadlines, timeouts, and output * no-mistakes(test): Bind watcher actions to registered executable bytes * no-mistakes(document): Correct condition-action watcher documentation * no-mistakes(document): Clarify outcome wake re-announcement * no-mistakes: apply CI fixes * fix(bin): honor a decision key stated after the verb colon (kunchenguid#2202) The open-decisions fold only recognized a [key=<slug>] token between the verb and the colon (needs-decision [key=x]: note). The common worker shape with the colon first (needs-decision: [key=x] note) silently folded its stated key into the shared "default" bucket, so two open decisions could collapse into one record and fm-send --resolve-key <x> refused to close the decision it plainly named. A complete token at the head of the note is now an equivalent stated-key position for every keyed verb, shared by the whole-file and incremental folds through the one _fm_decision_key owner. The documented before-colon position wins when both are present, a token deeper in the note stays prose, a bare keyless line still folds to "default", and a stated-but-malformed slug is rejected rather than rewritten to "default". A consumed note-head token is stripped from the note so both positions yield identical records, and the incremental fold version is bumped so persisted cursors folded under the old interpretation are rebuilt from the authoritative log. Fixes kunchenguid#2109 * fix(bin): prevent watcher recovery acknowledgement livelock (kunchenguid#2212) * fix(bin): keep a recovery acknowledgement valid across republication A watcher cycle that opened and closed while the model handled its drained wakes minted a fresh recovery generation, which invalidated the exact acknowledgement the drain had just printed. That acknowledgement then consumed nothing, so the marker stayed pending and every later arm spent its whole cycle re-announcing the same recovery instead of supervising - a livelock the home could not leave on its own. A downtime publication now reuses the generation of an outstanding handling episode, so a close during the handling window cannot orphan the printed acknowledgement. The acknowledgement itself separates its two facts: queue-row consumption is bound to the monotonic --ack-through sequence and always happens, while only retiring the episode is bound to --recovery-generation. A generation that moved on is a non-fatal result that names its own remedy instead of a refusal that consumes nothing. * no-mistakes(review): Preserve recovery generations and consume stale acknowledgements safely * no-mistakes(document): Document sequence-bound recovery acknowledgements * feat(fmx-respond): consume Relay conversation chains (kunchenguid#2206) * feat(fmx-respond): consume in_reply_to_chain conversation context The relay's poll payload can carry in_reply_to_chain, an oldest-first transcript of the surrounding conversation, but the mention-handling procedure only ever read the immediate in_reply_to parent, so referents like "this" in a standalone mention stayed unresolvable even when context was delivered. Teach fmx-respond to read the chain when present (optional and backward-compatible: often absent today, kind label not required), resolve referents against the whole transcript, and extend the untrusted-content framing to every chain entry including the upcoming kind=history entries. Document the field's wire shape in docs/configuration.md as the firstmate-side owner. * no-mistakes(document): Document Relay chain context ownership --------- Co-authored-by: Kun Chen <[email protected]> Co-authored-by: Roelof Blom <[email protected]>
Intent
Fix the watcher supervision livelock this task's own scout investigation diagnosed (data/fm-watcher-postcompaction-death-s1/report.md): on a Claude primary, after a context compaction the primary-session watcher died within seconds of every arm and the home could not recover on its own. Root cause: the rearm-resurface recovery episode is retired only by a nonce-bound acknowledgement, ANY concurrent republication of state/.watcher-down mints a fresh nonce and invalidates the acknowledgement the drain just printed, and that failed acknowledgement consumed NOTHING - leaving exactly the pending:downtime state that forces the next armed watcher to spend its whole cycle on 'check: rearm-resurface' and exit after one poll.
The captain reviewed the report and explicitly chose SCOPE B, which is exactly three changes: (1) PRIMARY - a downtime publication in bin/fm-wake-lib.sh reuses the generation of an outstanding pending:handling episode instead of minting a new nonce, so a watcher close during the handling window cannot orphan the printed acknowledgement; (2) COMPANION - bin/fm-wake-drain.sh separates the two facts an acknowledgement carries, so queue-row consumption bound to the monotonic --ack-through sequence always happens under any marker state while only retiring the episode stays bound to --recovery-generation, and a moved generation degrades to a NON-FATAL result instead of the old exit-1 that consumed nothing; (3) DIAGNOSTIC - the acknowledgement failure messages now name the remedy (re-drain, then use the new WAKE_ACK_REQUIRED command) so a session self-heals on the first failure.
The captain explicitly EXCLUDED two things the report also raised, so their absence is deliberate and must not be flagged as an omission: do NOT add a queue-non-empty condition to the pending:downtime branch of the arm-check state machine (the empty-queue resurface re-presents the cursor-folded OPEN DECISIONS set and is documented as intentional in docs/watcher-continuity.md), and do NOT give Claude the Pi/OpenCode --handling-delivered successor handoff (a real architectural change to the Stop-hook contract, not the smallest fix).
Accepted trade-off the captain chose knowingly: because a preserved generation lets the acknowledgement match, an empty-queue downtime episode can now be retired without its own dedicated recovery turn. Correctness is preserved because the acknowledgement still retires the marker only when the remaining queue is empty, and any wake appended after the drain carries a higher sequence, keeps the queue non-empty, and keeps the episode pending and re-presented.
Deliberate test changes: tests/fm-watch-arm.test.sh gains two new real-process cases reproducing report section 5d (a watcher close inside the handling window must leave the printed acknowledgement valid) and the drain-side self-healing moved-generation path. tests/fm-wake-queue.test.sh's test_stale_recovery_generation_is_rejected PINNED THE OLD CONTRACT (it asserted that a publication during handling must advance the generation, and that a stale acknowledgement must exit non-zero), so it was deliberately rewritten into test_stale_recovery_generation_cannot_touch_a_newer_episode, which keeps the real safety properties (a stale acknowledgement may neither retire the newer episode nor consume rows above its sequence) while pinning the new behaviour; its sibling ack-failure case was updated for the reworded diagnostic. Both rewritten and both new cases were verified to FAIL on pre-fix bin/ and pass after, and the new cases ran 5/5 stable.
This machinery is harness-agnostic shell shared by every harness, and the fix is pure state-machine logic, so portable tests/ regressions are sufficient and no live-harness guard is warranted. bin/fm-lint.sh and bin/fm-doc-audience-check.sh are clean; docs/watcher-continuity.md owns this contract and was patched there rather than restated elsewhere.
Known and unrelated: tests/fm-watch-arm.test.sh's pre-existing test_rearm_resurfaces_durable_queue_and_remote_open_decision case can hang (measured 1 in 5 runs on pristine origin/main, same rate on this branch). Its cause is a separate pre-existing defect - a watcher signalled while holding the recovery-marker lock unwinds via trap 'exit 1' without releasing it, then watcher_cleanup waits on that same lock forever - and it is being reported to the captain as follow-up work rather than fixed here.
What Changed
Risk Assessment
✅ Low: The durable generation-preservation and non-fatal stale-acknowledgement paths now satisfy the stated invariants with behavioral regression coverage and no material source risks found.
Testing
Inspected the clean targeted diff, ran the two new real-process watcher regressions and the focused wake-queue regression suite, then demonstrated the complete acknowledgement workflow through production interfaces: handling-window republication preserved the generation, sequence-bounded acknowledgement retained newer rows, a genuinely stale generation exited successfully with the re-drain remedy, and the newer episode remained pending. All checks succeeded; no worktree artifacts remained.
Evidence: End-to-end recovery contract demonstration
Evidence: Focused real-process watcher regression transcript
Evidence: Wake-queue behavioral regression transcript
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
🔧 **Review** - 2 issues found → auto-fixed ✅
bin/fm-wake-lib.sh:443- The required durable fix says any publication during the handling window must preserve the printed acknowledgement, but this hunk preserves the generation only forpending:handling:*. A first concurrent append/close rewrites it topending:downtime:G; a second publication then mints G2 and invalidates the acknowledgement for G. Preserve the generation for the entire outstanding pending episode, includingpending:downtime:*.bin/fm-wake-drain.sh:183- The required companion behavior says a moved generation must be non-fatal and queue consumption must still happen, but generation is snapshotted at line 178 and acknowledged under a separate marker-lock acquisition here. If the generation moves between those operations,fm_recovery_marker_ackreturns stale and this branch exits 1 before replacing the queue—the original consume-nothing failure. Distinguish a stale-generation return from an actual marker-write failure and continue queue consumption for the former.🔧 Fix: Preserve recovery generations and consume stale acknowledgements safely
✅ Re-checked - no issues remain.
✅ **Test** - passed
✅ No issues found.
git status --shortandgit diff 614fae60879372978a4480e22ec4d41eef083b3c..297fb7855f6e13dcebd2d28bc5d35a9d2e7439b4Focused real-process cases:test_handling_window_close_keeps_the_acknowledgement_validandtest_moved_generation_acknowledgement_is_self_healing./tests/fm-wake-queue.test.shManual production-interface recovery demo usingfm_wake_appendandbin/fm-wake-drain.sh, recording marker generations, queue state, acknowledgement results, and recovery diagnostics✅ **Document** - passed
✅ No issues found.
✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.