Skip to content

fix(bin): correct declared-pause liveness triage - #2598

Closed
tiago-peixoto wants to merge 18 commits into
kunchenguid:mainfrom
tiago-peixoto:fm/firstmate-declared-pause-not-absorbed-r2
Closed

tiago-peixoto wants to merge 18 commits into
kunchenguid:mainfrom
tiago-peixoto:fm/firstmate-declared-pause-not-absorbed-r2

Conversation

@tiago-peixoto

@tiago-peixoto tiago-peixoto commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Intent

Fix an inverted safety check in bin/fm-watch.sh: healthy workers parked on a declared wait are woken every cycle, while dead ones get the quiet long cadence. It is exactly backwards, and it has been costing a full supervision turn per false alarm since at least 2026-08-12 (six spurious stale wakes across four correctly parked tasks in roughly forty minutes).

The diagnosis was handed over already done, to VERIFY rather than repeat. pause_state_class reads the status log correctly - crew_absorb_class returns paused for a worker with a declared paused: line - and that verdict is then thrown away by two liveness short-circuits that both return none: one when .paused-<key> exists and the recheck marker is fresh, and one unconditionally, in each case for a non-secondmate window whose agent is not dead. The dispatcher routes none to surface_nonterminal_stale, which emits the bare unannotated stale: <win> and then writes .paused-<key>, .paused-rechecked-<key> and .paused-resurfaced-<key>. Consequence: handle_paused_stale, the absorber holding the long PAUSE_RESURFACE_SECS cadence, was reachable for a non-secondmate worker ONLY when its agent was dead. Secondmates escaped entirely because both short-circuits were gated on window_kind != secondmate. This was verified against the code before changing it, and traced to its origin: PR #743 added the inversion in a review-fix commit titled "Gate pause suppression on confirmed agent death".

Intended behaviour, as specified: liveness decides whether a declared pause is TRUSTWORTHY, not what the class is. A live agent on a declared pause is the normal healthy case and belongs in handle_paused_stale, absorbed on the long cadence. A dead agent on a declared pause is the anomaly - the pause can no longer be true, because nothing is left to end it - and deserves the immediate surface. The existing re-surface throttle is kept so a genuinely long wait still gets rechecked periodically; the goal is to stop the per-cycle churn, not to make firstmate blind to a wait that has gone stale.

An explicitly assigned open question was what unknown should mean, since fm_backend_agent_alive can return it and textually it took the same != dead branch as a live agent. DECISION MADE DELIBERATELY: unknown keeps the declaration trusted, same as alive. fm_backend_agent_alive folds an unreadable read, an ambiguous foreground process, and an unverified backend into unknown, so it is a gap in measurement rather than evidence the worker is gone; fm_backend_agent_state reserves confident verdicts for alive and dead/missing for that same reason. Reading unknown as death would permanently strip pause absorption from every worker on a backend that cannot answer, which is the same bug in a narrower form, while trusting it costs at most one bounded recheck per PAUSE_RESURFACE_SECS window because that recheck remains the backstop. This decision is justified in the commit message, as required.

This change DELIBERATELY overturns part of PR #743's tested guarantee, and that is intended, not an oversight. A dead agent's declared pause now surfaces as a plain stale wake instead of the annotated "awaiting external ... confirm the wait still holds" recheck, because that annotation told firstmate a wait was still live for a worker that had already exited. The flood #743 actually fixed is preserved and still asserted: exactly one wake across six unchanged polls, since the per-hash stale suppressor and the pause markers take over the moment the first surface lands. Two of #743's assertions (bare -eq 0 and the "awaiting external" grep for the dead-agent cases) were rewritten because they encoded the inversion, and the pre-existing alive-decision-gate sub-case, which asserted that a live parked worker must surface immediately, was replaced by the correct contract. This matches the fix shape recorded independently in the fleet backlog entry for this task, which asks for exactly this live/dead split including the immediate bare surface for a dead agent.

Test approach was specified and followed: the regression was written FIRST and proven RED against the prior HEAD, and it can fail in both directions. All four liveness verdicts - alive, dead, unreadable, ambiguous - are driven through the real tmux liveness classifier via the existing fake-tmux fixture (pane commands grok, zsh, node and empty resolve to alive, dead, ambiguous and unreadable respectively), and both unknown sources are exercised so neither one alone carries the verdict. Assertions are on the classification's observable effects rather than on wake wording, as required: the pause is fresh under a high re-surface threshold, so the bounded cadence cannot wake at all, which makes a queued stale wake mean "declaration rejected" and no wake mean "absorbed". Existing fixtures whose scenarios describe a LIVE parked worker but used zsh as the pane command (a dead-agent read, which only passed before because dead was the absorbing path) were switched to an agent command so they model what they claim; that is a fixture correction, not a weakened assertion. A queued_stale_wakes test helper was added because an absorbed cycle never creates the wake-queue file, so a raw awk over it errored instead of counting zero.

Scope was constrained to bin/fm-watch.sh and its tests, with an explicit instruction not to redesign the watcher, add a config knob, introduce a new state file, or build a wrapper. The fix is the inversion of two conditions, extracted into one named predicate (pause_declaration_is_trustworthy) so the duplicated liveness read has a single owner; the now-dead class = none && agent dead -> paused promotion collapsed into the trusted path. No config knob, no new state file, no wrapper, no redesign. Two owners outside bin/fm-watch.sh were updated because they stated the now-inverted policy in prose: docs/architecture.md's watcher paragraph, and a comment in bin/fm-classify-lib.sh which restated the watcher's liveness policy - that restatement was removed rather than corrected, so the policy keeps one owner (the firstmate repo's one-owner rule for contracts).

The tmux liveness classifier itself is unchanged, so its existing portable regression (tests/fm-tmux-agent-liveness.test.sh) and its opt-in live guard (tests/fm-harness-liveness-drift-live-e2e.test.sh) still own its per-harness evidence; no verification record needed refreshing.

The fleet backlog entry for this task was deliberately NOT edited: the shipped behaviour matches the fix shape its body records, and that file is private fleet state outside this repository's tracked surface.

Constraints observed while editing: this is the firstmate repo's own shared tracked material, so the repo's coding guidelines were loaded first and applied - one sentence per physical line in tracked Markdown, plain dashes rather than em dashes, no agent co-author on the commit, shellcheck-clean bin scripts via bin/fm-lint.sh, and tests colocated in tests/ extending the existing suite rather than a new runner. bin/fm-lint.sh and bin/fm-doc-audience-check.sh both pass, and all fifteen suites selected by bin/fm-test-run.sh --changed are green.

RE-SCAFFOLD, 2026-08-18, captain ruling. An earlier validation of this same change parked at the rebase gate because the branch was based on the personal fork's main, which carries 35 commits absent from official upstream; rebasing would have bundled that unrelated fork divergence (65 files) into the upstream pull request. The base was a briefing error, not a defect in the change. The captain ruled: re-scaffold from upstream/main. That earlier run was aborted through the supported abort command and confirmed cancelled, and this branch was rebuilt at upstream/main (d843712) carrying exactly the original commit's content and nothing else; the original commit is preserved on a keep ref. bin/fm-watch.sh and bin/fm-classify-lib.sh are byte-identical to the already-validated original, because those two files were identical between upstream and fork main. The conflicting test hunk was resolved to this change's own content, and the fork-only test-harness edits it sat next to (a raised wait budget, an extra queue assertion, a bounded reap helper, a heartbeat polling loop) were deliberately NOT carried across, so this pull request contains only this fix.

Every piece of evidence was re-established on the new base rather than assumed to carry over: all four liveness verdicts were re-proven RED against upstream/main's watcher, failing in both directions, and the full triage suite passes on the new base.

One deliberate test-timing decision: the two multi-round loops in the exited-pause case wait 3s per absorbing round rather than the 1.5s used elsewhere in that suite. Each absorbing round must stay alive long enough to finish the poll that writes its markers; measured on this base, 15 ticks failed 5/5 in isolation while 30 passed 5/5, and the two new tests then passed 13/13 across repeated runs. That value was chosen from measurement on this base, not copied from the fork.

Known pre-existing failure that is NOT part of this change and must not be attributed to it: tests/fm-wake-queue.test.sh fails on stock macOS Bash 3.2 with "a subshell reclaimed its parent's live hold", both with and without this change, verified by running it on a clean upstream/main checkout. Stock macOS Bash has no BASHPID, so ${BASHPID:-$$} falls back to $$, which a subshell inherits unchanged, and fm_lock_try_acquire's holder check therefore misfires; the personal fork already carries a BASH_SUBSHELL guard for it. It is deliberately excluded here because importing that fix would bundle fork divergence into this upstream pull request, which is exactly what the re-scaffold was ordered to prevent. It does not affect this repository's CI: the Linux jobs run a Bash with BASHPID, and the required stock-macOS job runs only a parse sweep plus the fleet-snapshot and Bearings suites, which were verified locally under /bin/bash 3.2.57 at their exact expected counts of 15 and 41, with all three changed files parsing cleanly under that shell.

FOLLOW-UP FIX, 2026-08-19, captain ruling. Fork integration review found a real defect in this change and the captain ruled it must be fixed here, on this pull request, because this is the live review artifact. The dead-agent guarantee only held for a pane that sat perfectly still. When a pane's content differs from the previous poll the hash counter resets, so the two-consecutive-hash stale path is never reached and the changing-hash dispatcher decides alone, and that dispatcher still collapsed working and none into a single clear_pause_tracking catch-all. A confidently dead agent therefore had its pause and stale markers erased every poll with no wake queued, and a dead agent's idle shell is exactly the pane most likely to churn - a clock, a timestamped prompt, a spinner the exited agent left behind - so its hash never repeats and firstmate was never told the worker was gone.

This was a regression introduced by this change rather than a pre-existing gap: before it, that path returned paused for a dead agent, so a churning dead pane still re-surfaced once per PAUSE_RESURFACE_SECS. It went from bounded-but-eventually-surfaced to permanently silent, which is strictly worse than the behaviour being replaced.

The fix brings the third dispatcher into line with the two that review already corrected, rather than inventing a new rule: clearing is reserved for working, where an authoritative run supersedes the declaration and the pane returns to ordinary wedge tracking, and none routes to surface_nonterminal_stale. That target is what keeps the flood bound intact, because it records the surfaced marker, so the next poll returns paused and a churning dead pane still costs exactly one wake rather than one per poll.

The regression was proven RED first and fails for its stated reason rather than by timing: "dead churning declared pause was cleared instead of surfacing", while its live half already passed, so the test discriminates. It drives a pane whose captured content differs on every read through the real tmux liveness classifier, asserts that live and churning stays absorbed across repeated polls, then that the same window with a confirmed-dead agent surfaces exactly once and stays quiet across three further churning polls. The once-only flood bound, the dead-agent guarantee, the unknown-is-trusted semantics, and the authoritative-working reclassification all remain asserted by their existing tests and green, the full watcher triage suite passes with 53 tests, and bin/fm-lint.sh is now fully clean including pinned actionlint workflow lint.

TRIAGE REORDER STAGE, 2026-08-19, captain ruling. Review found that the dead-agent guarantee was still bypassable by two short-circuits that both exist verbatim in official upstream: the capture-failure skip, which can leave a dead worker holding a declared wait silent indefinitely because nothing revisits a window whose terminal window is gone, and the busy_now guard, which delays the same reconciliation behind wedge timing because the busy classifier does not probe process state. The captain ruled to take the finding's own remedy and accept the triage reordering, explicitly relaxing this task's standing no-redesign constraint for that one concrete reorder and nothing wider, and he required the absolute dead-agent wording to stay while the code is made true to it rather than the statement being weakened.

The current head carries the first half of that reorder. Three review findings against it remain open and must be closed: the preflight covers only a confidently dead agent, so a declared pause whose agent reads alive or unknown still falls through the capture-failure skip and can go silent indefinitely with its bounded cadence never running; the surfaced early return skips authoritative run-step reconciliation, so an active run starting later while the append-only status still reads paused is never reconciled; and the commit history must state that both bypasses are pre-existing upstream defects rather than regressions from this branch, and must explain what the reordering changes about triage order.

That last requirement must be satisfied by the message of a NEW commit. An earlier attempt at this stage failed because the required explanation was added by amending an already-recorded pipeline commit, which the gate correctly refused as an out-of-band rewrite that would have lost the reviewed change. Nothing may amend, reset, or replace an existing commit on this branch.

The reorder's own new regression does not yet pass, so completing it is part of this stage rather than a separate concern. Acceptance is unchanged and every existing guarantee must stay green and be re-run rather than assumed: the once-only flood bound, the dead-agent guarantee on every path including a missing terminal window and a stale busy record, the unknown-is-trusted classification with its bounded-recheck caching, the authoritative-working reclassification, and the changing-hash live-to-dead regression. A failed capture must never be read as death; only a confident dead or missing liveness verdict may invalidate a declaration, and a live or unknown agent must stay absorbed on every newly reachable path so healthy parked workers are not turned back into per-cycle wakes.

TEST COST TAKEBACK, 2026-08-19. CI on the previous head executed once a maintainer released the fork-approval gate, and it carried real information: one shard failed and a second was cancelled. Both were diagnosed separately rather than assumed related. The failure, "concurrent watcher never saw complete poll" in tests/fm-pr-check-security.test.sh, was caused by this change and legitimately so: that fixture never provided a tmux fake, so capture failed and the window was silently DROPPED under the old loop, and totality now records a verdict and surfaces it, so the watcher exits before completing its poll. The test encoded the old broken behaviour as its expectation. It was fixed by giving the fixture the tmux fake it never had so capture succeeds, leaving its merged assertion untouched; the totality guarantee was NOT weakened to make an old test pass. The cancelled shard was independent of that failure - the shard matrix sets fail-fast: false, proven directly because a sibling shard kept running after the failure and passed - and was a timeout at 15m19s against a 15-minute limit, caused by this branch's added tests growing that shard's runtime.

That growth was split into inherent cost and accidental waste before anything was changed. The waste was the fixed-budget liveness wait, which burns its whole budget to prove a negative; the live phase of the churning-pane test now waits for the pane's recorded hash to advance, returning as soon as a poll completes and asserting strictly more than before. The same conversion was attempted on that test's dead-agent phase and reverted, because a dead already-surfaced pause absorbs cheaply and writes no artifact by design, so there is nothing to observe completing and a bounded liveness wait is the honest instrument; the reason is recorded in the test. The established result is a per-test reduction from 32s to 18s in-suite. A suite-level saving is deliberately NOT claimed: across two runs with only that test changed the suite moved 299s to 315s, so run-to-run spread exceeded the saving and a single pair of measurements cannot establish a delta in either direction. The shard limit was deliberately not raised and the shard partition deliberately not rebalanced, because shard 3 was already at 13m02s before this branch existed, making that imbalance a separate concern rather than this change's defect.

What Changed

  • Trust declared pauses for live or unknown agents, while surfacing confidently dead agents once per continuous death episode.
  • Reconcile active run steps and pause liveness before capture, busy-pane, and changing-hash paths so every watcher pane receives an authoritative triage verdict.
  • Add regression coverage for pause liveness and update the watcher architecture and configuration documentation.

Risk Assessment

✅ Low: Captain, the source fixes remain intact and the new forward-only empty-tree commit satisfies every required history explanation without rewriting prior commits or changing behavior.

Testing

Baseline commit/diff inspection confirmed the tested tree matches the assigned target; four focused suites passed, and end-to-end watcher evidence demonstrated trusted live/unknown pauses, one immediate notification for confirmed death, and no repeated notification, with both logs saved and no transient worktree files remaining.

Evidence: Targeted automated tests

All four targeted suites passed with zero failures.

FM_TEST_BEGIN 2026-08-20T12:19:58Z tests/fm-watch-triage.test.sh family=watcher-wake-lock expected_gate_skip=none
ok - declared pauses reconcile before capture and busy bypasses without flooding or hiding active runs
ok - every capture failure records a surfaced or authoritative absorbed verdict across ordinary, secondmate, and AFK entry modes
ok - signal_reason_is_actionable: benign absorbed, captain verbs and coalesced batches surfaced
ok - stale_is_terminal: terminal status surfaces, non-terminal and no-status are benign
ok - scan_captain_relevant_statuses lists only captain-relevant statuses
ok - classifier primitives: keyed decisions and activity phases, captain relevance, window-to-task, and overrides
ok - crew_is_provably_working: only working+run-step/pane is provable; idle/finished/parked/failed/unknown surface
ok - status_is_paused: only the leading paused verb matches, and paused is not captain-relevant
ok - crew_absorb_class: working/paused/none from one read; crew_is_paused and crew_is_provably_working agree
ok - signal_crew_provably_working: benign only when every referenced crew is provably working
ok - a secondmate's status signal is never absorbed as provably working; crewmates are unaffected
ok - a no-verb signal whose crew is provably working is absorbed (no exit, no queue, suppressor advanced, beacon present)
ok - a bare turn-end whose crew is provably working (busy pane) is absorbed
ok - a bare turn-end whose crew is not provably working is surfaced (the swallowed-finish fix)
ok - a no-verb working: note whose crew is idle with no running pipeline is surfaced
ok - a secondmate's status note surfaces even while its own agent is busy
ok - a self-announced close never wakes its own home, and the next real note still does
ok - captain-relevant signal is surfaced (queue + exit) and marked surfaced
ok - a stale pane sitting on a terminal status is surfaced (queue + exit)
ok - a stale terminal-looking status is overridden and absorbed while a run is actively working, then wedge-escalated
ok - provably-working non-terminal stale is absorbed on first sight, then wedge-escalated past the threshold
ok - consecutive wedge escalations on the same pane accumulate and demand deep inspection at the threshold
ok - a pane becoming active again resets the consecutive wedge-escalation counter
ok - a busy worker below the turn-age bound remains working with no escalation
ok - a busy worker with a stable pane hash still escalates once its completed-turn age reaches the bound
ok - a busy worker whose pane hash changes every poll still escalates once its completed-turn age reaches the bound
ok - touching a busy worker's completed-turn marker resets the age and prevents an old-age escalation
ok - repeated busy turn-age escalations reuse the existing escalation counter and demand deep inspection at the threshold
ok - the production default busy-turn-age bound is 3600s (5min under does not wedge, 66min over does)
ok - a busy pane under a declared pause is rechecked on the long cadence, and lifting the pause restores the wedge escalation
ok - a not-provably-working non-terminal stale is surfaced immediately (never left to wait out the timer)
ok - a declared pause is absorbed on first sight, then re-surfaced as a recheck past the threshold, never wedge-escalated
ok - a declared pause is absorbed for a live or unmeasurable agent and surfaced only for a confidently dead one
ok - a declared pause on a churning pane stays absorbed while live and surfaces exactly once once its agent is confirmed dead
ok - unknown liveness stays trusted while current run-step authority is re-derived
ok - each distinct dead-agent episode surfaces exactly once
ok - a scheduled pause recheck cannot throttle a later death, while a surfaced death stays once-only
ok - an exited declared pause or captain hold surfaces exactly once and then stays bounded, while a live parked pane replays nothing
ok - a declared paused secondmate re-surfaces on the bounded normal-mode cadence
ok - a non-paused secondmate retains normal stale suppression
ok - a resumed secondmate clears pause and stale tracking before stale exemption
ok - unchanged stale hashes reclassify when a crew enters or leaves pause
ok - a declared pause is periodically rechecked against authoritative active-run state
ok - a paused status overridden by authoritative working preserves its wedge timer and escalates
ok - matching non-terminal stale suppressors repair missing or corrupt stale-since timers
ok - triage log capping handles wc byte counts with leading spaces
ok - a captured process-event result wakes a healthy watcher proactively, with no manual drain
ok - an unacknowledged process-event result re-drains until handling is acknowledged
ok - complete process-event queue keys map to distinct seen markers
WAKE_ACK_REQUIRED: after handling completes run bin/fm-wake-drain.sh --ack-through 1 --recovery-generation 49481.1787228754.621NRg
ok - queue revalidation, proactive output, and marker commit serialize with drain
/Users/tiago/.no-mistakes/worktrees/bbb16e1f0808/01M0FF3G5T8X68BXR1NKZQ3V2H/bin/fm-push-transition-lib.sh: line 96: echo: write error: Broken pipe
tests/wake-helpers.sh: line 277: 51632 Killed: 9               PATH="$dir/fakebin:$PATH" FM_HOME="$dir" FM_PROCEVENT_CLAIM_ROOT="$dir/claims" FM_CREW_STATE_BIN="$dir/fakebin/fm-crew-state.sh" FM_POLL=0.2 FM_SIGNAL_GRACE=1 FM_CHECK_INTERVAL=999999 FM_HEARTBEAT=999999 "$WATCH" > "$out"
tests/wake-helpers.sh: line 277: 52622 Killed: 9               PATH="$dir/fakebin:$PATH" FM_HOME="$dir" FM_PROCEVENT_CLAIM_ROOT="$dir/claims" FM_CREW_STATE_BIN="$dir/fakebin/fm-crew-state.sh" FM_POLL=0.2 FM_SIGNAL_GRACE=1 FM_CHECK_INTERVAL=999999 FM_HEARTBEAT=999999 "$WATCH" > "$out"
ok - surfacing failures replay until post-handling acknowledgement
ok - marker failure exits through the shared wake owner, releases its lock, and replays later
ok - a heartbeat with no captain-relevant change is absorbed and backs off the cadence
ok - heartbeat backstop fail-safe surfaces a captain-relevant status the per-wake path missed
ok - the liveness beacon stays fresh while the watcher absorbs benign wakes (fm-guard never false-alarms)
ok - with .afk present the watcher reverts to one-shot so the daemon owns triage (no double-triage)
ok - AFK changed paused panes hand off plain stale identities for daemon-owned pause triage
FM_TEST_END 2026-08-20T12:26:25Z tests/fm-watch-triage.test.sh exit=0 duration_ms=386393 gate_skip=false
FM_TEST_BEGIN 2026-08-20T12:26:25Z tests/fm-watch-arm.test.sh family=watcher-wake-lock expected_gate_skip=none
ok - watch-arm: an attached arm reports the wake its cycle delivered instead of a false failure
ok - watch-arm: a delivered wake consumed by the handling turn still closes the attached arm cleanly
ok - watch-arm: a cycle that delivered no wake of its own still fails loudly
/Users/tiago/.no-mistakes/worktrees/bbb16e1f0808/01M0FF3G5T8X68BXR1NKZQ3V2H/bin/fm-watch-arm.sh: line 566: 92611 Killed: 9               "$WATCH" > "$child_out"
WAKE_ACK_REQUIRED: after handling completes run bin/fm-wake-drain.sh --ack-through 2 --recovery-generation 93222.1787228818.0SeRln
ok - watch-arm: re-arm surfaces every queued wake and an open remote decision after downtime
watcher: recovery state could not be persisted; retaining stale lock evidence
ok - watch-arm: marker publication failure retains stale-lock recovery evidence
WAKE_ACK_REQUIRED: after handling completes run bin/fm-wake-drain.sh --ack-through 2 --recovery-generation 99889.1787228828.9xzx0Q
WAKE_ACK_REQUIRED: after handling completes run bin/fm-wake-drain.sh --ack-through 3 --recovery-generation 2882.1787228830.tboPbL
ok - watch-arm: a wake queued after handling drain is recovered once at successor arm
ok - watch-arm: interrupted handling leaves its wake durable for successor re-drain
WAKE_ACK_REQUIRED: after handling completes run bin/fm-wake-drain.sh --ack-through 0 --recovery-generation 9513.1787228839.jFltxB
ok - watch-arm: malformed recovery state is quarantined without a successor loop
WAKE_ACK_REQUIRED: after handling completes run bin/fm-wake-drain.sh --ack-through 1 --recovery-generation 13312.1787228841.7Sj0Qv
ok - watch-arm: publication after recovery handoff is surfaced
ok - watch-arm: restart publishes recovery before clearing a reused-pid watcher lock
WAKE_ACK_REQUIRED: after handling completes run bin/fm-wake-drain.sh --ack-through 7 --recovery-generation 15074.1787228845.I572pO
ok - watch-arm: markerless legacy queues are adopted and recovered
ok - watch-arm: a watcher close during handling keeps the printed acknowledgement valid
ok - watch-arm: a moved recovery generation consumes handled rows and names its remedy
ok - watch-arm: downtime marker publication does not follow symlinks
FM_TEST_END 2026-08-20T12:27:41Z tests/fm-watch-arm.test.sh exit=0 duration_ms=75669 gate_skip=false
FM_TEST_BEGIN 2026-08-20T12:27:41Z tests/fm-pr-check-security.test.sh family=pr-forge expected_gate_skip=none
ok - raw-byte parser accepts canonical URLs and rejects the complete adversarial matrix
ok - GitLab merge requests are followed on any instance and never wake falsely
ok - validated merged polls notify once and retire before the next watcher cycle
ok - merged poll retirement preserves every persistent secondmate lifecycle artifact
ok - queue, receipt, and every fixed-path removal crash point recover without loss or repeated execution
ok - open/red, closed-unmerged, malformed, and forge errors remain armed until an exact merged transition
ok - replacement, nonterminal, tampered, and custom results receive no deletion authority
ok - queue failure and untrusted receipts preserve canonical poll evidence
ok - GitHub and GitLab exact merged results share one retirement path
ok - PR and teardown entrypoints reject invalid arguments before every side effect
ok - valid direct and merge flows record exact metadata and reject multiline head metadata
ok - rejected metacharacter bytes remain inert at generation and watcher time
ok - static poll is silent except for one merged line and remains watcher-bounded
ok - interrupted atomic preparation cleans private temporaries and publishes nothing
ok - concurrent watchers observe only complete private poll publications
ok - post-rename poll validation faults revoke both names and allow a clean retry
ok - migration creates and validates private state before watcher exclusion
ok - migration pauses older watchers and acquires exclusion before its first scan or marker
ok - poll, marker, diagnostic, and quarantine paths refuse symlinks and directories
ok - marker and diagnostic rename errors and signals fail closed and recover durably on retry
ok - post-rename marker, diagnostic, and obligation faults are revoked and reconstructed on retry
ok - quarantine type and mode faults fail closed and recover only when a retry can validate them
ok - canonical and ambiguous failure obligations block every retry until all task artifacts are repaired
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
●  WATCHER DOWN - SUPERVISION IS OFF
●  1 task(s) in flight, but no watcher has a fresh beacon (last beat: never, grace 300s).
●  Trust the emitted supervision protocol for this harness; do not use shell & for watcher repair.
●  This is a supervision warning only; the guarded operation WILL still run.
●  repair missing watcher supervision according to the session-start block for this harness; do not use shell &.
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ok - ambiguous migration recovery accepts an explicitly validated replacement poll
ok - ambiguous repair rejects copied, metadata- or task-mismatched, forged, and partial poll publications
ok - all live, marker, diagnostic, X, custom-check, obligation, and teardown boundaries require single-link files
ok - canonical publication failure remains incomplete until a later clean retry rebuilds the poll
ok - legacy reserved obligations and delimiter-bearing task IDs retry without ambiguity
ok - migration never executes legacy checks, preserves X mode, quarantines ambiguity, and is idempotent
ok - historical X shims migrate only from the exact single-link mode-0755 identity
ok - direct registration refreshes authenticated v1 X shims across marker states
ok - bootstrap runs the non-executing migration at the locked session boundary
ok - bootstrap isolates incomplete poll migration from unrelated recovery sweeps
ok - watcher signals promptly stop custom checks and clean private state
ok - returned custom check descendants are drained on installed and fallback timeout paths
ok - teardown removes safe poll artifacts and refuses quarantine-directory symlinks without traversal
FM_TEST_END 2026-08-20T12:34:57Z tests/fm-pr-check-security.test.sh exit=0 duration_ms=436179 gate_skip=false
FM_TEST_BEGIN 2026-08-20T12:34:57Z tests/fm-tmux-agent-liveness.test.sh family=backend-dispatch expected_gate_skip=none
ok - tmux liveness: a harness-named foreground process classifies alive
ok - tmux liveness: muse's version-suffixed muse-bin-<version> classifies alive
ok - tmux liveness: unrelated muse-containing command names stay ambiguous
ok - tmux liveness: a version-named executable under a harness install path classifies alive
ok - tmux liveness: a version-named executable under a decoy path stays ambiguous
ok - tmux liveness: a process neither name source attributes stays ambiguous rather than inventing an agent
ok - tmux liveness: a launcher whose own identity reads as a bare shell classifies alive from its harness child
ok - tmux liveness: an idle shell pane classifies dead
ok - tmux liveness: a harness-named background process in an idle pane still classifies dead
ok - tmux liveness: an absent window classifies missing rather than inheriting tmux's active-window fallback
ok - cursor composer: an idle Cursor pane reads empty even though the cursor row is blind
ok - cursor composer: real typed text still reads pending, so the injection guard holds
ok - cursor composer: an identical screen stays unknown when the pane is not Cursor
ok - cursor composer: a stale Cursor screen over a dead shell never reads empty
FM_TEST_END 2026-08-20T12:35:01Z tests/fm-tmux-agent-liveness.test.sh exit=0 duration_ms=3810 gate_skip=false
FM_TEST_SUMMARY total=4 failed=0 skipped_gate=0 duration_ms=903180
FM_TEST_SUMMARY_FAMILY family=backend-dispatch count=1 duration_ms=3810 failed=0
FM_TEST_SUMMARY_FAMILY family=pr-forge count=1 duration_ms=436179 failed=0
FM_TEST_SUMMARY_FAMILY family=watcher-wake-lock count=2 duration_ms=462062 failed=0
FM_TEST_SLOWEST rank=1 script=tests/fm-pr-check-security.test.sh duration_ms=436179
FM_TEST_SLOWEST rank=2 script=tests/fm-watch-triage.test.sh duration_ms=386393
FM_TEST_SLOWEST rank=3 script=tests/fm-watch-arm.test.sh duration_ms=75669
FM_TEST_SLOWEST rank=4 script=tests/fm-tmux-agent-liveness.test.sh duration_ms=3810
Evidence: Declared-pause end-to-end evidence

Live, ambiguous, and unreadable agents queued no notification; confirmed death queued one bare stale notification, then none on the repeat poll.

Declared-pause liveness: end-to-end watcher evidence
assigned_target=3e350096dbcc428f9329227f67d81c7090e82b32
tested_head=337440201e2c3674858889d065214cad29879d88
tree_diff_from_assigned_target=none

scenario=live agent
watcher_after_completed_poll=still_waiting
queued_stale_notifications=0
bounded_pause_marker=present

scenario=ambiguous liveness (unknown)
watcher_after_completed_poll=still_waiting
queued_stale_notifications=0
bounded_pause_marker=present

scenario=unreadable liveness (unknown)
watcher_after_completed_poll=still_waiting
queued_stale_notifications=0
bounded_pause_marker=present

scenario=confirmed dead agent
watcher_output=stale: test:fm-confirmed-dead
queued_stale_notifications=1
death_surface_marker=surfaced
reviewer-visible durable notification:
  1787229565	1	stale	test:fm-confirmed-dead	stale: test:fm-confirmed-dead
repeat_poll_watcher=still_waiting
repeat_queued_stale_notifications=0

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 2 issues found → auto-fixed (2) ✅
  • 🚨 bin/fm-watch.sh:1068 - The intent requires authoritative run-step reconciliation before the busy guard and says an active run supersedes the older pause. This preflight calls pause_state_class only for dead liveness; alive/unknown skips it, while a dead+working verdict merely clears markers and falls through. A successfully captured, busy, over-age pane then reaches busy_turn_bound_check, which trusts the stale paused status and restores pause cadence instead of wedge tracking. Derive pause class for every declaration and carry a working verdict through the busy-bound decision.
  • 🚨 bin/fm-watch.sh:1096 - The intent requires “every existing guarantee must stay green,” but the new working capture-failure arm absorbs even when .afk exists. This contradicts the established away-mode contract that every notification is queued for daemon-owned classification and that the watcher skips provably-working reads. Check AFK before capture-failure classification and hand off a plain stale notification rather than absorbing it; update the new afk-working fixture accordingly.

🔧 Fix: Captain, fix active-run and AFK pause triage
1 error still open:

  • 🚨 The accepted follow-up requires “Carry forward the standing commit-message requirements”: a new commit must state that both bypasses are pre-existing upstream defects and explain the triage reordering. Commit 3e35009 has an empty body, so it records neither fact. Preserve history and add a forward commit whose message supplies the required explanation.

🔧 Fix: Add empty forward commit documenting triage rationale
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • bin/fm-test-run.sh tests/fm-watch-triage.test.sh tests/fm-watch-arm.test.sh tests/fm-pr-check-security.test.sh tests/fm-tmux-agent-liveness.test.sh
  • Temporary evidence harness: bash .manual-pause-evidence.sh
  • git diff --quiet 3e350096dbcc428f9329227f67d81c7090e82b32..HEAD
  • Durable queue-row verification with awk -F &#39;\t&#39; ... pause-liveness-e2e.txt
  • git status --porcelain=v1 --untracked-files=all
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@tiago-peixoto
tiago-peixoto force-pushed the fm/firstmate-declared-pause-not-absorbed-r2 branch from 0d9bbd8 to 0992d8f Compare August 19, 2026 19:10
@tiago-peixoto tiago-peixoto changed the title fix(watcher): trust declared pauses until agents are confirmed dead fix(watcher): correct declared-pause liveness triage Aug 19, 2026
@tiago-peixoto
tiago-peixoto force-pushed the fm/firstmate-declared-pause-not-absorbed-r2 branch from 0992d8f to d5da853 Compare August 19, 2026 19:16
A worker parked on a current, accurate `paused:` line was woken on first sight of
every distinct stale hash instead of being absorbed on the long
PAUSE_RESURFACE_SECS cadence. Six such wakes landed across four correctly parked
tasks in roughly forty minutes on 2026-08-12, each costing a full supervision
turn to confirm a wait that was already declared.

pause_state_class read the declaration correctly - crew_absorb_class returns
`paused` for it - and then discarded that verdict in two liveness short-circuits
that returned `none` for any non-secondmate window whose agent was not `dead`.
`none` routes to surface_nonterminal_stale, so handle_paused_stale, the absorber
holding the long cadence, was reachable only once the agent was already dead: the
healthy parked worker got surfaced and the dead one got the quiet cadence.
Secondmates never showed it because both short-circuits skipped them.

Liveness now decides whether the declaration still HOLDS instead of replacing the
class, in one named predicate (pause_declaration_is_trustworthy):

- a live agent is the normal case - it is there to end its own wait - so it is
  absorbed on the bounded cadence;
- a confidently dead agent breaks the declaration, because nothing is left to end
  that wait, so it surfaces once for reconciliation and the per-hash stale
  suppressor plus the pause markers return it to the bounded cadence immediately;
- a secondmate is unchanged: its idle endpoint is healthy by charter.

`unknown` liveness keeps the declaration trusted. fm_backend_agent_alive folds an
unreadable read, an ambiguous foreground process, and an unverified backend into
`unknown`, so it is a gap in measurement rather than evidence the worker is gone -
fm_backend_agent_state reserves confident verdicts for `alive` and `dead`/`missing`
for that same reason. Reading it as death would permanently strip pause absorption
from every worker on a backend that cannot answer, which is the same bug in a
narrower form. Trusting it costs at most one bounded recheck per
PAUSE_RESURFACE_SECS window, since that recheck remains the backstop for a trusted
wait that has quietly rotted.

This deliberately changes the dead-agent wake SHAPE that kunchenguid#743 introduced. A dead
agent's declared pause now surfaces as a plain stale wake rather than one
annotated "awaiting external ... confirm the wait still holds", which told
firstmate a wait was still live for a worker that had already exited. The flood
unchanged polls.

Coverage drives all four liveness verdicts - alive, dead, unreadable, ambiguous -
through the real tmux liveness classifier, and asserts the classification rather
than wake wording: the pause is fresh under a high re-surface threshold, so the
bounded cadence cannot wake, which makes a queued stale wake mean "declaration
rejected" and no wake mean "absorbed". All four were proven RED against the prior
code, failing in both directions. The classifier itself is unchanged, so its own
portable regression (tests/fm-tmux-agent-liveness.test.sh) and live guard
(tests/fm-harness-liveness-drift-live-e2e.test.sh) still own its per-harness
evidence.

The two multi-round loops in the exited-pause case wait 3s per absorbing round
rather than the 1.5s used elsewhere in this suite. Each such round has to stay
alive long enough to finish the poll that writes its markers; at 1.5s it reaps
mid-poll and fails on either the wake count or the pause marker, measured 5/5
failures at 15 ticks against 5/5 passes at 30 with FM_POLL=1.
The dead-agent guarantee only held for a pane that sat perfectly still. When a
pane's content differs from the previous poll the hash counter resets, so the
two-consecutive-hash stale path is never reached and the changing-hash dispatcher
decides alone - and that dispatcher still collapsed two opposite verdicts into one
catch-all:

    paused) handle_paused_stale ... ;;
    *)      clear_pause_tracking ... ;;

`none` there means the declaration is CONTRADICTED by a confidently dead agent,
which is the anomaly this classification exists to surface. Routing it to
clear_pause_tracking erased the pause and stale markers and queued nothing. A dead
agent's idle shell is exactly the pane most likely to churn - a clock, a
timestamped prompt, a spinner the exited agent left behind - so its hash never
repeats, this branch ran every poll, the state was cleared every poll, and
firstmate was never told the worker was gone.

That was a regression rather than a pre-existing gap. Before the liveness-trust
change this path returned `paused` for a dead agent, so a churning dead pane still
re-surfaced once per PAUSE_RESURFACE_SECS. It went from bounded-but-eventually
-surfaced to permanently silent.

The two stale dispatchers already route these three verdicts correctly, so this
brings the third into line rather than inventing a rule: clearing belongs to
`working` alone, where an authoritative run supersedes the declaration and the pane
returns to ordinary wedge tracking, while `none` surfaces. Using
surface_nonterminal_stale is what keeps the flood bound intact: it records the
`surfaced` marker, so the next poll returns `paused` and the churning dead pane
still costs exactly one wake rather than one per poll.

The regression covers both halves of the transition and was proven RED first,
failing with "dead churning declared pause was cleared instead of surfacing" while
its live half already passed, so the test discriminates rather than merely failing.
It drives a pane whose captured content differs on every read through the real tmux
liveness classifier: live and churning stays absorbed across repeated polls, then
the same window with a confirmed-dead agent surfaces once and stays quiet across
three further churning polls. The once-only bound, the dead-agent guarantee, the
unknown-is-trusted semantics, and the authoritative-working reclassification are
all still asserted by their existing tests and remain green.
The capture-failure skip and busy-state guard both exist verbatim in official upstream. Their ability to hide a declared pause is therefore a pre-existing watcher defect, not a regression introduced by this branch.\n\nComplete the triage reorder ahead of those short-circuits. A trusted live or unknown declaration now enters the bounded pause handler when capture fails, reusing the last recorded hash; capture failure itself never becomes evidence of death.\n\nReconcile an authoritative active run-step before the surfaced-marker early return. Active work can reclaim the pane and resume ordinary wedge tracking, while the surfaced marker still deduplicates a dead pane to one immediate wake.
This is architecturally the same defect as firstmate's disk-reclaim work ruled on earlier today: a pipeline step can silently drop an item while the guarantee is stated over all items. Two unrelated pieces of firstmate tooling had one flaw.

The capture-failure skip and busy-state guard both exist verbatim in official upstream, so this closes a pre-existing watcher defect rather than a regression introduced by this branch.

Every unique nonempty metadata-backed target now enters pane triage as an ordinary, secondmate, or AFK window. Missing metadata, empty targets, and duplicates are filtered before entry; the only in-loop exits are an explicitly logged secondmate charter absorption, a persisted pause absorption, a queued surface, or a capture-failure verdict recorded as authoritative working, trusted pause, or surfaced cannot-determine. Successful capture still records hash and count state before stale, busy, pause, or timer classification.

The ordering now derives declared-pause liveness and current run-step authority before capture and busy checks can bypass them. A confirmed dead worker surfaces ahead of those guards, a current active run reclaims the pane on every poll, and failed capture is classified instead of skipped.

The legacy .paused-rechecked marker no longer stores liveness trust, surface deduplication, bounded recheck decisions, or run-step authority. Pause mode persists in .paused, the once-only re-surface throttle persists in .paused-resurfaced, and all current decisions are derived during classification.
This is architecturally the same defect as firstmate's disk-reclaim work ruled on earlier today: a pipeline step can silently drop an item while the guarantee is stated over all items. Two unrelated pieces of firstmate tooling had one flaw.

The capture-failure skip and busy-state guard both exist verbatim in official upstream, so this closes a pre-existing watcher defect rather than a regression introduced by this branch.

The triage ordering still assigns every metadata-backed window one verdict before exit: declared-pause liveness and current run-step authority precede capture and busy guards, capture failure is classified instead of skipped, and cannot-determine surfaces. Unknown liveness remains a recorded trusted pause, while current run-step authority is derived on every classification rather than cached.

The restored .paused-rechecked=surfaced token records one past act only: this death was already surfaced. That act cannot be reconstructed from current classification, unlike liveness trust, bounded cadence, or run-step authority; separating it from the shared .paused-resurfaced throttle preserves immediate death detection after scheduled wait rechecks without reintroducing the overloaded marker.
This is architecturally the same defect as firstmate's disk-reclaim work: a pipeline step could silently drop an item under a guarantee stated over all items. Two unrelated pieces of firstmate tooling had the same flaw.

The capture-failure skip and busy-state guard both exist verbatim in official upstream, so the triage reorder closes a pre-existing watcher defect rather than a regression introduced by this branch. The reorder derives current run-step authority before capture and busy short-circuits, then records one verdict for every window instead of letting either guard drop it.

The restored death-surface fact records a past act, not a derivable verdict. A confirmed alive read ends that death episode and clears only that fact; unknown leaves it untouched, so liveness trust, recheck caching, and run-step authority remain derived rather than stored on the marker.
This is architecturally the same defect as firstmate's disk-reclaim work: a pipeline step could silently drop an item under a guarantee stated over all items. Two unrelated pieces of firstmate tooling had the same flaw, and placing the episode reset inside a classifier that not every poll reaches repeated it one level down.

The capture-failure skip and busy-state guard both exist verbatim in official upstream, so the triage reorder closes a pre-existing watcher defect rather than a regression introduced by this branch. The reorder derives current liveness and run-step authority before capture and busy short-circuits, then records one verdict for every window instead of letting either guard drop it.

The death-surface token records a past act, not a derivable verdict. The shared preflight now uses its confident alive verdict to end that death episode immediately on every path; unknown leaves the token untouched, so liveness trust, recheck caching, and run-step authority remain derived rather than stored on the marker.
… budget

The declared-pause tests added by this branch pushed the portable serial shard
that carries them from 10m55s to 15m19s against a 15-minute limit, so CI cancelled
it. This takes back the part of that cost which was buying nothing, and only that
part.

`wait_live` proves a negative: it burns its whole budget to show the watcher is
still alive at the end of it. Every absorbing round therefore paid a fixed 3s even
when the state it was really waiting for had landed in milliseconds. The live
phase of the churning-pane test now waits for the pane's recorded hash to advance
instead, which a churning pane rewrites on every poll. That returns as soon as one
poll completes, and it asserts strictly more than the wait it replaces: that a poll
actually happened, rather than only that the process had not exited.

The dead-agent phase of the same test keeps its bounded liveness wait, and that is
deliberate. A dead, already-surfaced pause absorbs cheaply and writes no new
artifact - that cheapness is the once-only guarantee working - so there is nothing
to observe completing. The same conversion was tried there, failed with "never
completed a poll", and was reverted. The reason is recorded in the test so a later
reader does not re-optimise it into asserting less than it does now.

What is established: that one test drops from 32s to 18s in-suite, a 14s reduction,
with a stronger assertion than before.

What is NOT claimable, and is stated here so nobody infers it from the diff: a
suite-level saving. Across the two measured runs, with only that one test changed,
the suite moved 299s to 315s. Run-to-run spread of roughly 16s exceeds the 14s
saving, so a single pair of measurements cannot establish a suite delta in either
direction, and the nominal increase is noise rather than evidence of a slowdown.
Resolving an effect that small against that noise floor would need several runs per
side.

The shard limit is deliberately not raised and the shard partition is deliberately
not rebalanced here. Shard 3 was already at 13m02s before this branch existed, so
the imbalance is not this change's defect, and correcting it belongs in its own
work rather than bundled into this validation.
The capture-failure skip and busy-state guard both exist verbatim in official upstream, so this branch closes a pre-existing watcher defect rather than a regression it introduced.

Declared-pause liveness reconciliation and authoritative run-step state now run before the capture and busy short-circuits, and no window leaves triage without exactly one recorded verdict.

This is architecturally the same defect as Firstmate's disk-reclaim work: a pipeline step could silently drop an item while the guarantee was stated over all items. The tools are unrelated, but the flaw is shared, so future work can recognize the pattern instead of rediscovering it.

The restored death-surface record stores a past ACT rather than caching a derivable verdict, so it does not reintroduce the overloaded marker removed by the restructure.
@tiago-peixoto

Copy link
Copy Markdown
Contributor Author

Closing this pre-issue implementation so the confirmed behavior and any fresh implementation can proceed from #2713. That issue is now the authoritative discussion surface and is marked ready-for-pr.

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