Repository navigation
feat(bin): reconcile inactive terminal crew outcomes - #2167
Merged
Merged
Conversation
jokim1
pushed a commit
to jokim1/firstmate-fork
that referenced
this pull request
Aug 12, 2026
* 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
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
Ship the minimal inactive terminal-outcome reconciliation core. On the existing watcher poll loop and locked session start, deterministically reconcile only long-inactive, non-captain-held, direct ordinary crewmates through fm-crew-state.sh. For terminal done or failed outcomes, retain a durable receipt and emit one actionable wake without calling GitHub, a forge, a PR API, gh, gh-axi, curl, or any PR poll. A secondmate reconciles only its own direct children and records an idempotent parent report through the established route. A main home surfaces only its own direct terminal workers. Preserve bounded cadence independently of heartbeat backoff, atomic receipt and cadence-marker handling, restart idempotency, and the healthy idle-secondmate wedge exemption. Do not inspect secondmate summaries, request cross-home reports, or add summary cursors, pagination, identity logic, or other cross-home reconciliation machinery. This simplified branch supersedes the abandoned #2140 approach and should open a new PR for captain review.
What Changed
doneorfailed, excluding captain-held work and secondmates.Risk Assessment
✅ Low: The reconciliation is bounded, local-only, fail-closed on invalid routing identity, and the reviewed durable receipt and locking paths satisfy the stated intent without a substantiated remaining defect.
Testing
After baseline inspection, targeted reconciliation, wake-queue, and parent-route tests passed; executable end-to-end fixtures demonstrated one durable captain wake transitioning from pending to presented, idempotent secondmate parent reporting, no cross-home surfacing, and no gh, gh-axi, or curl invocation. The worktree remained clean.
Evidence: Main-home terminal reconciliation, durable wake presentation, acknowledgement, and forge trap evidence
Evidence: Secondmate direct-child parent routing and restart-idempotency evidence
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
🔧 **Review** - 1 issue found → auto-fixed (4) ✅
bin/fm-inactive-reconcile.sh:294- A local secondmate report trusts FM_SECONDMATE_PARENT_HOME and marks the receipt reported after writing there, but fm_secondmate_parent_record_parse currently accepts relative parent_home values despite its absolute-path contract. A malformed record such as parent_home=foo therefore writes to a cwd-relative false parent and permanently records successful delivery. Enforce the absolute local-home invariant at the shared parent-record parser before using the route.🔧 Fix: Reject relative local secondmate parent routes
2 errors still open:
bin/fm-inactive-reconcile.sh:381- The required routing says a secondmate must report through its parent route while a main home surfaces only its own workers, buthome_secondmate_id || truetreats a present malformed or symlinked.fm-secondmate-homeexactly like an absent marker. That secondmate home then queues local main-home presentation wakes and never records the required parent report. Distinguish an absent marker from an invalid marker and fail closed for the latter.bin/fm-inactive-reconcile.sh:324- Receipts are keyed only by task ID, state, PR, and last status. Teardown deletes the task's meta/status files but leaves terminal-outcome receipts, so a supported reuse of the same ID that reaches the same common terminal state and text (for examplefailed: terminalwith no PR) matches the prior.presented/.reportedreceipt at line 155 and emits no wake or parent report. Include an immutable per-spawn incarnation established at the spawn metadata boundary in the fingerprint so each concrete terminal outcome remains independently idempotent.🔧 Fix: Key terminal receipts by spawn incarnation
3 errors still open:
bin/fm-inactive-reconcile.sh:399- The required criterion says, “A secondmate reconciles only its own direct children and records an idempotent parent report through the established route,” buthome_secondmate_id || truetreats a present malformed or symlinked.fm-secondmate-homeas if the marker were absent. That home then creates main-home presentation wakes instead of parent reports. Distinguish absence from invalid presence and fail closed for an invalid marker.bin/fm-inactive-reconcile.sh:273- For pre-upgrade metadata withoutspawn_gen, the receipt incarnation hashes inode and modification/change times. Supported metadata updates such asfm-pr-check.shor X follow-up rewrites replace the file, so the same already-presented terminal worker receives a new fingerprint and duplicate wake/report after the next inactivity interval. Derive the legacy identity from an immutable per-spawn metadata value such as the existingtasktmp, rather than mutable file identity.bin/fm-inactive-reconcile.sh:341- Reconciliation reads activity/current state and then readsspawn_genwithout taking the task's shared metadata lock. A concurrent supported relaunch can replace metadata betweenfm-crew-state.shreturning the old worker's terminal state andmeta_incarnationreading the replacement's generation, creating a false terminal receipt for the active replacement. Hold the task'sfm_meta_lock_pathacross the eligibility, authoritative state read, and fingerprint snapshot so relaunch/teardown cannot change ownership mid-decision.🔧 Fix: Stabilize legacy receipts and lock reconciliation snapshots
1 error still open:
bin/fm-inactive-reconcile.sh:408- The required criterion says, “A secondmate reconciles only its own direct children and records an idempotent parent report through the established route,” butself=$(home_secondmate_id || true)treats a present malformed or symlinked.fm-secondmate-homeas an absent marker. The secondmate home then queues main-home captain presentation wakes instead of reporting through its parent route. Distinguish marker absence from invalid presence and fail closed for the latter.🔧 Fix: Fail closed on invalid secondmate identity markers
✅ Re-checked - no issues remain.
✅ **Test** - passed
✅ No issues found.
Inspected the base-to-target diff and confirmed a clean worktree baseline; rangit diff --check 76355e20b4f44d968ca43c14e1bb21c100ac90d7..790b5650aec81345ca9393251a3bcd7aafc705b4.bash tests/fm-inactive-reconcile.test.shbash tests/fm-wake-queue.test.shbash tests/fm-remote-secondmate-parent-binding.test.shManually executedfm-inactive-reconcile.sh scan --startup, repeated it, presented the wake withfm-wake-drain.sh, and acknowledged it; inspected the durable queue and terminal receipt states.Manually scanned a main home and secondmate home to verify direct-child routing, parent-report persistence, restart idempotency, and secondmate exclusion.✅ **Document** - passed
✅ No issues found.
✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.