Repository navigation
feat: add deterministic condition-to-action watcher - #2200
Merged
Merged
Conversation
…rocess-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.
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
Build a new firstmate primitive: a condition->action watcher, so firstmate can set up 'do X as soon as Y is true' once and have it run almost tokenlessly, instead of the captain or firstmate repeatedly polling 'are we ready yet?'. When the condition trips, a DETERMINISTIC action fires without waking firstmate, and firstmate is woken exactly once at the end with the captured outcome. Required by the captain: build ON the existing watcher/check infrastructure rather than inventing a parallel system - after inventorying the custom check.sh registration/trust binding, the watcher poll loop, procevent, fm-check-register, and fm-pr-check merge-poll arming, the chosen integration is a new 'when' adapter on the existing process-to-event channel (bin/fm-procevent-when.sh), because procevent already owns durable capture, restart-on-death, wake publication, and adapter-owned terminal retirement, and needs zero changes to fm-watch.sh; the check.sh channel was deliberately rejected for the action half because FM_CHECK_TIMEOUT=30s would kill a long action mid-run. Hard design boundary from firstmate's VISION: scripts own exact mechanics, agents own judgment - the primitive is ONLY for cases where BOTH condition AND action are genuinely exact/deterministic; the existing check-fires-then-wake-firstmate-and-decide flow stays available and unchanged for judgment-needing actions, and the eligibility judgment is deliberately documented as firstmate's pre-arm decision (in the process-event-sources skill) because scripts cannot classify an argv as destructive; the primitive must NEVER be used for destructive, irreversible, or security-sensitive actions. Mandatory fail-safe semantics, all implemented and tested: fail safe (action error, ambiguous/flaky condition past an error budget, expired deadline, and mutated spec all wake firstmate with a terminal captured outcome rather than silently proceeding or retrying); robust condition (fires only on a configurable count of consecutive true polls, condition exit 0=true 1=clean-false other=error, so a flapping one-shot true never fires); idempotent single-fire (a durable O_EXCL fired marker is claimed BEFORE the action so a restart or re-poll reports 'ambiguous' instead of double-firing); the action's bytes are trust-bound at registration the same way fm-check-register.sh binds a custom check (spec + sha256 trust record under state/when/, refused without execution on mismatch); the end-of-run wake carries the action's captured outcome (status, exit code, bounded output) via the procevent durable result. The motivating acceptance scenario is 'run no-mistakes update --beta once no validation runs are active' but the primitive is general (any exact condition + any registered deterministic action), not hardcoded to no-mistakes. This changes firstmate's shared tracked material, so the firstmate-coding-guidelines were followed: mechanics live in the script header + --help, the operating contract in docs/configuration.md's procevent section (single owner), arming/handling/eligibility in the process-event-sources skill, only one-line pointers in AGENTS.md (state layout line + section 13 trigger extension), one-sentence-per-line Markdown, plain dashes, shellcheck-clean bin script via bin/fm-lint.sh, and behavioral tests in tests/fm-procevent-when.test.sh that exercise the public adapter + generic runner interface with real processes (never asserting implementation-source bytes): 8 scenarios covering arm/refuse-duplicate/retire, exactly-once fire with outcome wake on the durable queue, flapping condition never firing, action failure captured, condition error budget, expired deadline, crash-restart ambiguity instead of double-fire, and mutated-spec trust refusal. No harness-dependent checks are involved, so no live-harness dual test is needed. Docs rows added to docs/scripts.md and the FM_WHEN_OUTPUT_TAIL_BYTES env var documented in docs/configuration.md.
What Changed
whenadapter that polls for consecutive true conditions and runs a registered action at most once.Risk Assessment
🚨 High: Two mandatory trust-binding fail-safe guarantees remain concretely bypassable and require explicit resolution before merge.
Testing
After inspecting the change, the focused behavioral suite passed, including action-byte mutation refusal; a manual end-to-end CLI run also demonstrated one action invocation, one durable wake, captured successful output, and terminal retirement.
Evidence: End-to-end condition-to-action watcher transcript
Evidence: Durably captured watcher outcome
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
bin/fm-procevent-when.sh:187- Intent requires “the action's bytes [to be] trust-bound at registration,” but the trust hash covers only the serialized argv/spec. Replacing the executable or script at the unchanged action path after arming leaves the spec hash valid, and line 382 executes the replacement. Confirm the intended trust boundary and bind/validate the action artifact at registration and immediately before invocation if executable bytes are required.bin/fm-procevent-when.sh:297- The Perl timeout fallback kills only the direct child PID. A condition or action wrapper that spawns a descendant can time out while that descendant continues running, so an action-failed outcome may be captured before the action's effects finish. Use the existing bin/fm-timeout-lib.sh shared boundary, which isolates and terminates the whole process group.bin/fm-procevent-when.sh:355- The deadline is checked only before starting a condition poll. A poll begun just before expiry can complete true after the deadline and immediately break toward the action, violating the required fail-safe expired-deadline behavior. Recheck the deadline after each poll and immediately before claiming the fired marker.bin/fm-procevent-when.sh:156- Duplicate refusal is a check-then-publish sequence with no shared lock. Two concurrent arms for the same name can both pass the absence check, overwrite each other's spec/trust/registration, and both report success instead of refusing one registration. Serialize the adapter's absence check through completed process-event registration at one per-source boundary.bin/fm-procevent-when.sh:348- Condition and action output is written without a size limit to the temporary run file; FM_WHEN_OUTPUT_TAIL_BYTES is applied only after the command exits. A verbose command can therefore consume arbitrary disk space during its timeout. Capture through a rolling bounded tail and validate the configured byte limit before execution.🔧 Fix: Harden when watcher concurrency, deadlines, timeouts, and output
2 errors still open:
bin/fm-procevent-when.sh:191- Required intent says “the action's bytes are trust-bound at registration,” but the hash covers only the spec containing argv. Replacing the executable or script at the same action path after arming leaves the hash valid, and line 401 executes the replacement. Bind the authorized action artifact's hash at registration and validate it immediately before invocation, or confirm a different intended trust boundary.bin/fm-procevent-when.sh:327- Required intent says a “mutated spec” must wake with a terminal outcome rather than proceed, but the spec is validated only once when the long-running process starts. After the first false poll, mutating the on-disk spec and then making the condition true still executes the previously loaded action. Revalidate the trust binding before each poll and immediately before claiming the fired marker.🔧 **Test** - 1 issue found → auto-fixed ✅
bin/fm-procevent-when.sh:191- Registration hashes only the serialized spec and action argv, not the action executable's bytes. End-to-end verification armed a watch, replaced the action script after registration, and observed the mutated script execute with a durablestatus: firedoutcome. This violates the required check-style byte trust binding. Persist an action-byte hash at registration and revalidate it immediately before claiming and executing the action, with a focused mutation regression test.git status --shortand target/base diff inspectionbash tests/fm-procevent-when.test.shManual public-interface check: armwhen-byte-bind, mutate the registered action executable, runbin/fm-procevent.sh reconcile, then inspect the durable result, action side effect, and wake queuebin/fm-procevent.sh sweep-hometo stop and clean the manual runner🔧 Fix: Bind watcher actions to registered executable bytes
✅ Re-checked - no issues remain.
Inspected the target diff and confirmed the worktree remained clean after testing.bash tests/fm-procevent-when.test.shEnd-to-end CLI check: armedbeta-update, started it withbin/fm-procevent.sh reconcile, made the condition true, and inspected the durable result, wake queue, invocation log, and terminal source retirement.🔧 **Document** - 1 issue found → auto-fixed ✅
docs/configuration.md:494- The required exactly-once end wake is not guaranteed: unacknowledged process-event results may be republished and delivered again.🔧 Fix: Clarify outcome wake re-announcement
✅ Re-checked - no issues remain.
✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.