Skip to content

fix: bound recovery announcements and preserve supervision - #2733

Merged
kunchenguid merged 3 commits into
mainfrom
fm/pi-rearm-loop-fix-r1
Aug 21, 2026
Merged

kunchenguid merged 3 commits into
mainfrom
fm/pi-rearm-loop-fix-r1

Conversation

@kunchenguid

Copy link
Copy Markdown
Owner

Intent

Fix the Pi/OpenCode primary recovery-loop bug and its silent supervision gap in firstmate shared tracked supervision-core material (bin/, Pi extensions, OpenCode plugins, tests, docs).

The bug: an unacknowledged recovery episode is re-announced from the durable downtime marker by every supervision cycle, unbounded (about 52 seconds), because the only transition that stops it is an out-of-band, unretried, failure-swallowed handling-delivery RPC the Pi/OpenCode extension makes after scheduling the follow-up. While it loops the fleet is effectively unsupervised (a real crew event was ignored about 54 seconds then dropped). Authoritative diagnosis is the completed scout report for GitHub issue 2615.

Implement recommendations 1 + 2 + 3 from that report (captain-decided cadence: announce an unacknowledged recovery at most ONCE per generation per home, NO bounded repeats):

  1. Idempotent per-generation recovery announcement at the supervision-core layer. Record the announcement in the durable marker itself so the arm-check returns recover for a not-yet-announced generation and wait for an already-announced one. A genuinely new down stretch mints a new generation. This alone terminates the loop and is harness-independent (fixes Pi and OpenCode at once). Preserve the watcher-continuity guarantee: a still-open decision or buried note still reappears after a NEW down stretch (new generation). Keep the marker's one owner in the wake library.

  2. Fix the handshake at the adapter layer for Pi AND OpenCode together (same defect): confirm the handling handoff BEFORE scheduling the follow-up, or retry it against the current generation and successor; NEVER swallow its failure - classify it, retire the rejected successor bounded, surface exactly one typed message; guard the actionable close branch with the in-flight restoring flag the same way the failure branch already is, so overlapping restoration chains cannot both deliver.

  3. Remove the blind wait (the about-55-second pre-loop wait that converts a lost handshake into a supervision outage): the successor should enter its poll loop immediately and evaluate the handoff state per iteration, so a pending handoff never stops signal/stale/check scanning. If any wait must remain, it must NOT refresh the liveness beacon and then go blind.

Regression tests REQUIRED: T1 (an unacknowledged recovery loop is bounded to at most one announcement per generation, and the successor stays alive and supervising) and T2 (a resurfacing successor must NOT go blind - it must surface and enqueue a real crew event within a poll interval or two). Both must fail on the old base and pass after the fix. These are harness-dependent checks (T1 loads the real Pi extension) - follow firstmate-coding-guidelines Harness-dependent checks (portable regression plus env-gated live guard where applicable). Colocate in tests/.

Constraints: Reconcile GitHub issue 2615 in the PR. Do NOT resurrect PR 2708 as the primary fix - it silences the noise but leaves the churn plus supervision gap and can swallow decision-only or unread-note recovery; note briefly in the PR why its approach is not adopted as the primary fix. Do NOT regress the Claude / Cursor / tmux primary paths (they do not loop). Verify affected primary harnesses and runtime backends per firstmate-coding-guidelines compatibility rule.

Delivery: yolo OFF - the captain owns the merge. Escalate ANY ask-user finding; do not answer it in the pipeline. Avoid unattended yes. Note in the PR that homes pick this up after merge plus a firstmate self-update, and that landing timing is coordinated with the main firstmate. Do NOT merge. Do NOT post publicly.

What Changed

  • Persist announcement state in durable recovery markers so each generation resurfaces at most once while new down stretches can mint a fresh generation.
  • Make Pi and OpenCode confirm handling handoff before follow-up delivery, retry and surface typed failures, prevent overlapping restoration, and start successor polling immediately.
  • Add regression coverage for bounded recovery announcements and uninterrupted crew-event supervision, with updated continuity and verification documentation.

Risk Assessment

🚨 High: The durable once-per-generation fix remains bypassable on supported non-adapter supervision paths and can preserve the recovery loop the change is intended to eliminate.

Testing

Inspected the recovery-core and Pi/OpenCode adapter changes, exercised focused watcher, arm, and adapter regressions, then captured an end-to-end transcript showing one recovery announcement, a live successor marker, and a real crew event surfaced and durably queued without a blind wait; all checks succeeded.

Evidence: Pi recovery-loop and no-blind-wait end-to-end evidence

Source: Pi recovery-loop and no-blind-wait end-to-end evidence

T2_WATCH_OUTPUT=signal: /var/folders/0k/bf8mwt2n5qddzk24r20gfk0c0000gn/T//fm-watch-recovery-loop.vNA8ut/recovery-gap-successor/state/crew.status 
T2_QUEUE_ROW=1787294442	2	signal	crew.status	signal: /var/folders/0k/bf8mwt2n5qddzk24r20gfk0c0000gn/T//fm-watch-recovery-loop.vNA8ut/recovery-gap-successor/state/crew.status
ok - a resurfacing handling successor stays alive and supervises instead of going blind
T1_MESSAGES=1
T1_LOCK_PID=31408
T1_MARKER=announced:downtime:seed.1.aaa
ok - unacknowledged recovery is announced at most once per generation and the successor stays alive

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

⚠️ **Review** - 1 error
  • 🚨 .pi/extensions/fm-primary-pi-watch.ts:305 - The required handshake behavior says to “retire the rejected successor bounded,” but a failed confirmation retires the arm only when its watcher PID is already dead; a live successor that rejected both confirmations is retained. The same inversion exists in .opencode/plugins/fm-primary-watch-arm.js:233. Retire the rejected arm with the bounded retirement path and restore supervision with a lock-verified replacement before surfacing the single typed failure.
  • 🚨 tests/fm-watch-recovery-loop.test.sh:191 - Required T2 says the crew event must surface “within a poll interval or two,” but with FM_POLL=1 this loop permits 24 half-second waits (about 12 poll intervals). A 10-second supervision outage would therefore pass. Bound the observation window to the required one-or-two-poll cadence with only a small scheduling allowance.
  • 🚨 tests/fm-watch-recovery-loop.test.sh:64 - The intent explicitly classifies T1 as harness-dependent and requires the coding-guidelines portable-regression plus env-gated-live-guard pattern. This adds only a Node fixture around the extension; no live-harness-optin Pi/OpenCode guard or corresponding refreshable verification evidence was added. Add or extend an env-gated real-harness guard covering installed affected harnesses.

🔧 Fix: Tighten recovery event timing regression
1 error still open:

  • 🚨 bin/fm-watch.sh:777 - The required invariant says “A genuinely new down stretch mints a new generation” and forbids regressing Claude/Cursor/tmux into loops, but every non-handling watcher start now reopens any announced marker. Concrete path: a Claude/Cursor/tmux recovery watcher emits check: rearm-resurface, exits via release-lock-existing, and leaves announced:downtime; the next ordinary arm calls fm_recovery_marker_reopen_announced, mints a generation, and emits the same recovery again. Repeated arms therefore remain an unbounded recovery loop, merely with a new generation each time. Mint the generation at the shared transition that proves an actual new down stretch (such as unexpected watcher cleanup), not unconditionally at watcher startup.
✅ **Test** - passed

✅ No issues found.

  • bash tests/fm-watch-recovery-loop.test.sh
  • bash tests/fm-watch-arm.test.sh
  • bash tests/fm-pi-watch-extension.test.sh
  • FM_TEST_EVIDENCE=1 bash tests/fm-watch-recovery-loop.test.sh | tee /Users/kunchen/.no-mistakes/evidence/01M0HCM7HEMMKB612GAJJRMW66/recovery-loop-e2e.txt
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

… supervising

A lost Pi/OpenCode handling handshake re-announced the same recovery
generation on every cycle and spent the successor's first ~55s blind, so
a real crew event could be ignored and then dropped. Record the
announcement in the durable marker, confirm the handshake before the
follow-up without swallowing failure, and enter the poll loop immediately.
@kunchenguid
kunchenguid merged commit 3f03533 into main Aug 21, 2026
13 checks passed
@kunchenguid
kunchenguid deleted the fm/pi-rearm-loop-fix-r1 branch August 21, 2026 08:00
quinnbot-ai added a commit to quinnbot-ai/firstmate that referenced this pull request Aug 21, 2026
…nt (#167)

* fix(bearings): restore decision options and add close controls (kunchenguid#2707)

* fix(bearings): always show decision options and a close/drop control

Freeform-only Captain's Call cards hid the option buttons the board was designed around, and there was no way to drop a stale hold without inventing an answer. Require selectable options, keep freeform as a supplement, and route the reserved __drop__ answer through decline so the hold leaves Captain's Call.

* no-mistakes(review): Fix drop closure and decision-only option validation

* no-mistakes(review): Preserve answerability for non-decision cards

* no-mistakes(document): Clarify decision drop documentation

* ci: require no-mistakes pipeline step attestation (kunchenguid#2710)

Signature-only PRs can hide skipped review, test, or document steps. Fail unless no-mistakes >= 1.46.0 attests those three steps completed.

* feat: collapse decisions into tasks held for the captain (kunchenguid#2728)

* feat(captain-hold): collapse the decisions concept into tasks held for the captain

A decision is no longer a separate type: it is an ordinary backlog task held
for the captain, identified by its task id. bin/fm-captain-hold.sh owns the
surviving behaviors - guarded hold creation, the recorded-answer close
(answer/answers with a release mode for captain-gated work), the source
bindings, and the investigation completion gate - and bin/fm-decision-hold.sh
becomes a one-release compatibility shim over it.

The fleet snapshot now parses hold-until and computes captain_actionable as
queued + captain-held + unblocked + due, independent of row kind, plus a
presentation-only deferred_marker for prose-deferred rows. Bearings renders
every due captain-held task in Captain's Call, date-deferred holds as dated
Charted Next gates, suppresses prose-deferred rows from default views with an
omitted disclosure, and excludes from Recently Landed anything that closed
while still held for the captain.

Legacy compatibility: pre-collapse <origin>-decision-<key> rows are already
plain task ids and keep working; short keys in recorded metadata, concrete
origin bindings, chat --resolve-key fallbacks, and old resolution records all
resolve in place.

* no-mistakes(review): Fix captain answer replay and body preservation

* no-mistakes(review): Fix captain hold idempotency and legacy replay

* no-mistakes(review): Validate card close modes and compatibility routing

* no-mistakes(review): Enforce release replay mode matching

* no-mistakes(review): Prevent duplicate decision cards and released replay mismatches

* no-mistakes(review): Preserve answer columns and legacy resolve replays

* no-mistakes(document): Document strict replay and legacy compatibility

* no-mistakes(lint): Quote done literals to satisfy ShellCheck

* no-mistakes: apply CI fixes

* fix(rebase): keep collapsed captain hold board semantics

* fix: bound recovery announcements and preserve supervision (kunchenguid#2733)

* fix(watch): announce recovery once per generation and keep successors supervising

A lost Pi/OpenCode handling handshake re-announced the same recovery
generation on every cycle and spent the successor's first ~55s blind, so
a real crew event could be ignored and then dropped. Record the
announcement in the durable marker, confirm the handshake before the
follow-up without swallowing failure, and enter the poll loop immediately.

* no-mistakes(review): Tighten recovery event timing regression

* no-mistakes(document): Document recovery-loop supervision guarantees

* fix(bin): surface captain-call record divergence (kunchenguid#2744)

* fix(bin): signal a captain call resolved in the log but still held

A captain call has two records and closing one has never closed the
other: a `resolved [key=...]` line closes the status-log fold, while the
backlog task held for the captain closes only through
`fm-captain-hold.sh answer`. Answering on the status side alone left no
trace of the disagreement - the fold went quiet, the durable record kept
saying the captain owed an answer, and nothing warned. The defect was
never the separation; it was the silence.

Add `fm-captain-hold.sh diverged`, a read-only report of that
contradiction, and print it from `fm-wake-drain.sh` as a bounded RECORD
DIVERGENCE section beside OPEN DECISIONS on every drain. It flags one
condition: a task still open and still carrying the captain-hold
annotations whose key was closed on the status side by the resolve verb,
under the collapsed identity or the legacy derived one.

It closes nothing, ever. A captain call closed wrongly leaves review
entirely, which is worse than the noise, so both reconciliation
directions stay human-owned and the printed hint names both - a
resolution is not proof the captain ruled, since a call can dissolve on a
false premise or turn out to have been a question of fact.

Three states are deliberately not divergence: a `captain-held` close is
the verified transfer `complete` writes, a still-open keyed decision
belongs to the OPEN DECISIONS fold, and a captain call with no routed
work item is legitimate rather than incomplete, so routed work is no part
of the test.

`fm-classify-lib.sh` gains `status_key_closing_verb`, which reports how
the status side currently reads one key by replaying the existing
`_fm_decision_fold_line` rule rather than re-deriving it, so the two
closing verbs stay distinguishable in one place. The per-wake cost is one
`tasks-axi list`, one key scan per status log, and the precise per-key
fold only for a key that already names a still-open task; the call is
hard-bounded so a slow backlog tool can never delay wake presentation.

* fix(document): Correct divergence lifecycle documentation

* fix(document): Neutralize divergence lifecycle prose

* fix(bin): re-arm after an abandoned auto-arm claim and defer a wedge escalation while a worktree is written (kunchenguid#2524)

* fix(watch): re-arm supervision after an abandoned auto-arm claim

A Claude auto-arm cycle that armed, delivered one rewake, and exited left
its single-flight lock behind. Both Stop-event participants then deferred
to that lock forever, because its recorded pid was still live: the
turn-end guard read it as recovery under way and allowed the stop, and the
next Stop firing treated it as another owner and declined to arm. On
2026-08-14 a home with two tasks in flight lost supervision for about 40
minutes with no watcher process and no watcher lock, its beacon frozen at
the one delivery, and both crewmates' finished reports sat in the durable
queue until an operator drained it by hand.

Abandonment is now proven from the epoch ledger instead of inferred from
pid liveness. A lock whose holder pid matches the ledger's own owner_pid
while the recorded outcome is anything other than arming has already
finished its decision, so that claim is reclaimed under the lock's steal
mutex, stops counting as recovery ownership in the guard, and is cleared
by the guard's terminal check rather than deferred to. A failed clear
re-blocks instead of allowing a blind stop, and an arming entry stays in
flight however old it is, because its owner foregrounds the arm for the
whole watcher cycle.

Issue kunchenguid#2251's PR kunchenguid#2263 does not cover this failure. It is closed and
unmerged, lives entirely in bin/fm-watch-arm.sh, and retires the stalled
watcher and matching stale watcher lock of an arm that is currently
running. Here no arm and no watcher were running and no watcher lock
existed, so it has nothing to retire and the home stays blind.

tests/fm-claude-stop-autoarm.test.sh covers the reclaim, the still-arming
and unnamed-owner cases that must keep the gate closed, and the failed
clear. tests/fm-turnend-guard.test.sh covers the guard side of the same
boundary. Both fail without this change.

* fix(watch): defer a wedge escalation while the task worktree is written

The wedge detector had two inputs, rendered pane quietness and the run
step, and neither can see a crew that is writing source, then tests, then
documentation behind a static pane. On 2026-08-14 one crewmate produced
eight consecutive possible-wedge escalations in a single afternoon, three
of them demanding deep inspection, while it was demonstrably working and
then committed. Every one of them cost a supervision turn to disprove by
hand.

Add write activity inside the crew's own recorded worktree as a third
liveness input. crew_worktree_written_since compares the worktree against
the caller's existing idle-window timer file, so -newer needs no clock
arithmetic, no temp file, and no portable mtime write. The probe runs only
inside the branch that was about to escalate, which bounds it to one
pruned, depth-bounded walk per window per FM_STALE_ESCALATE_SECS and
leaves the per-poll stale sweep exactly as cheap as before.

Positive evidence defers rather than cancels. The idle timer restarts so
the next window probes again, the escalation counter is neither advanced
nor reset so a later genuine wedge keeps the demand-deep-inspection
history it earned, and a .writing-since marker ages the whole deferral
chain so the pane still re-surfaces once per FM_PAUSE_RESURFACE_SECS,
through the same throttle shape a declared pause already uses, labeled as
a recheck rather than a wedge. This can only reduce false positives: every
absence of evidence, including no recorded worktree, a torn-down worktree,
a missing anchor, and a failed walk, falls through to the unchanged
escalation schedule, so a crew that writes nothing still escalates on the
existing timetable.

What the signal cannot see, by design or by construction:

- CPU burn with no writes, such as a long compaction, is invisible. That
  case keeps the old behavior exactly.
- A commit-only phase writes only .git, which is pruned first so that
  firstmate's own read-only git commands against the worktree can never
  make the probe self-fulfilling.
- Writes under the pruned generated trees, or deeper than
  FM_WORKTREE_WRITE_MAXDEPTH, do not count.
- The probe cannot attribute a write to the crew, so a background build or
  another process touching the tree looks the same. The hourly re-surface
  is what bounds that, and a churny file cannot buy silence.
- The away-mode daemon's own escalation path is deliberately untouched.

tests/fm-watch-triage.test.sh covers the classifier including the .git
prune, both halves of the live case on one fixture (quiet plus writing
defers, quiet plus silent still escalates and counts), and the bounded
re-surface. All three fail without this change.

* no-mistakes(review): prove autoarm claims by identity; skip mate-home write probe

* no-mistakes(document): document away-mode wedge boundary and probe filesystem limit

* no-mistakes(document): qualify turn-end recovery condition for abandoned auto-arm claims

* fix(watch): keep a write deferral scoped to its own idle window

Two consistency gaps in the worktree write probe, both found while reviewing
the wedge-deferral change on this branch.

A write deferral is a bounded chain: its .writing-since marker ages the whole
chain so a churning worktree still re-surfaces once per resurface window. That
is only sound while the chain belongs to the current quiet stretch, so every
path that restarts the idle-window timer has to drop it too. Two did not: the
corrupt-timer repair in wedge_timer_check, and both first-sight branches for a
captain-relevant status. A chain left over from an earlier quiet stretch made
the first deferral of the new window re-surface immediately instead of after a
full fresh window.

FM_WORKTREE_WRITE_PRUNE is a skip list, so clearing it reads as "skip nothing"
and is the obvious way to widen the probe to the whole depth-bounded tree.
Instead an empty list reported no evidence at all, quietly costing the wedge
detector its third liveness input on a home that meant to widen the walk. An
empty list now widens the walk, and the header says so.

Neither change alters when a stall that writes nothing escalates.

Regressions in tests/fm-watch-triage.test.sh cover all three paths and each
one fails on the pre-fix code.

* no-mistakes(review): honor an empty write-prune, bound the probe, share window_key

* no-mistakes(document): align probe knob count and guard regression-coverage ownership

* no-mistakes(lint): silence deliberate single-quote SC2016 in write-prune env test

* fix(bin): land local-only dirt that is already the target tip's content

fm-merge-local.sh refused any dirty checkout, which deadlocked the case where
the dirt IS what the merge would write: a generator that re-runs locally and
reproduces bytes the task branch already contains. The refusal was unresolvable
because landing the branch was the thing that would have cleaned it.

Allow the fast-forward when every dirty path is provably the tip's own content.
A throwaway index seeded from the tip, refreshed against the working tree, is
what proves it, so content filters, symlinks, and file mode are judged by git
rather than by a filename or timestamp heuristic. Staging must also lose
nothing: a path's index entry has to be HEAD's or the tip's, never a third
version. Only then are those paths staged, after the diverged-branch check, so
the merge sees a consistent tree and writes no byte that is not already on disk.

Every other dirty checkout refuses exactly as before: one differing byte, a
different staged version, a different file mode, a local deletion, an untracked
path the tip does not carry, and anything the tip holds as a directory or
submodule pointer.

tests/fm-merge-local.test.sh covers both directions, including the reproduction
that fails on the previous code.

---------

Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: Mickaël Rémond <[email protected]>
Co-authored-by: Inthuson <[email protected]>
Co-authored-by: QuinnBot <[email protected]>
withally added a commit to withally/firstmate that referenced this pull request Aug 22, 2026