Skip to content

fix(bin): restore downtime on supervision-host hand-back when the successor already closed - #6355

Merged
kunchenguid merged 6 commits into
kunchenguid:mainfrom
tiago-peixoto:fm/upstream-6294-host-successor-handback
Oct 2, 2026
Merged

kunchenguid merged 6 commits into
kunchenguid:mainfrom
tiago-peixoto:fm/upstream-6294-host-successor-handback

Conversation

@tiago-peixoto

@tiago-peixoto tiago-peixoto commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Intent

Fixes #6294.
Fixes #5943.

Fix the supervision-host successor-watcher loss described in #6294 and #5943, both labeled ready-for-pr by the maintainer (contract class: restore), with no open PR.

Observed in real use on a Claude primary (a local secondmate home) four times in one day: the supervision host chained watcher cycles about 33 seconds apart, the last cycle closed on an actionable signal with no successor, no Stop-hook feedback reached the idle session, its watcher beacon froze, and wakes sat unhandled until a manual steer. The host also printed "the handling handoff to the successor watcher could not be confirmed; this wake is yours", yet nothing woke the session.

The maintainer's triage on main at 549e07f (which includes #6255, the polling-churn reduction) found it still present: exit_to_main -> retire_successor relies on a watcher exit to republish downtime, so when the handling successor already closed, the stop is a no-op and the recovery marker can remain pending:handling; attended pass-through restores downtime after detach_successor but the post-handled branch-outcome exit_to_main path has no mirror step; autoarm_commit rewake accepts only pending:downtime / announced:downtime, and a refusal deletes the banner and exits 0 silently. For #5943: after a handled attended turn with captain rows the host either exits to main with a branch-outcome line or parks on ARM_PID=$SUCCESSOR_PID with no live-successor check, so a successor that already closed mid engine turn is orphaned and no arm owner remains.

Expected: a branch-outcome hand-back or an actionable wake always reaches the primary (a Stop-hook rewake), or a live watcher/host keeps owning supervision; the home is never left with no watcher, no host and a queued wake.

What Changed

  • bin/fm-supervision-host.sh: when a successor generation was recorded, exit_to_main now republishes downtime on the .watcher-down recovery marker itself after retiring the successor. Previously it relied on the watcher's exit to do that, so a successor that had already closed left the marker stuck at pending:handling. If the publish fails, the hand-back logs downtime-unrestored, adds a supervision-host: watcher downtime could not be restored for the main hand-back line and exits nonzero. SUCCESSOR_WATCHER and SUCCESSOR_GENERATION are now initialised at startup so an early hand-back works under set -u.
  • bin/fm-claude-stop-autoarm.sh: in host mode, when an actionable rewake is refused, the marker is still pending:handling and no watcher is healthy, the Stop hook now commits the auto-arm failure notice (failed once per episode, failed-suppressed after that) and exits 2, so the wake reaches the primary. Before, it deleted the banner and exited 0 silently. Every other refused rewake still exits silently.
  • Docs and tests: docs/supervision-host.md (Failure direction) and docs/watcher-continuity.md now describe the downtime restore and the lost-hand-back notice. New tests cover a successor that closes before exit_to_main, one that closes mid engine turn, a failed downtime restore, one notice per failure episode, and a benign refusal that opens no failure episode.

Risk Assessment

✅ Low: The change is small. exit_to_main now explicitly republishes downtime whenever a successor generation was recorded, and returns 1 with a note if that fails. The Stop-hook fallback fires only when the recovery marker still reads pending:handling, no watcher is healthy, and this hook is still the owner. It reuses the once-per-episode notice handling. Successor globals are initialised so the script survives set -u. The new tests drive the real host and hook and assert behaviour: the benign refusal, the notify-once episode, and a successor that closes before or during the engine turn.

Testing

I ran the whole autoarm test file plus the three new host hand-back tests, the latch test and three neighbouring hand-back tests, all under nice. Everything passes on this branch. On base 8690c41 the new mid-engine-turn, restore-failure and lost-hand-back tests fail with the reported symptom (hook exit 0, no rewake). These tests run the real host, Stop hook, watcher, drain and lease scripts in throwaway homes, but the engine and harness are stubs, so they are integration evidence, not live. I also launched a real Claude primary in a disposable lab home. From the gate worktree the Stop hook does nothing by design, because it only acts in a plain checkout. Running from a plain clone hit Claude's workspace-trust prompt, and accepting it would edit user-level Claude config, so I tore the lab down. No scenario was driven live, so all are untested and the verdict is inconclusive. There is no UI surface, so no screenshots.

  • Live validation: ⚠️ inconclusive - 0 of 7 scenarios driven live against the product
Scenario Result Live Evidence
Successor watcher closes mid engine turn, then the host hands its branch outcome to main: the Stop hook rewakes main (exit 2, outcome=rewake) and the marker is left at pending/announced downtime ⏸️ untested no The prior payload did not establish a live result. Only the stubbed-engine integration test test_claude_stop_hook_restores_handoff_when_successor_closed_mid_engine_turn was run: it passes on this bran…
Successor closes before exit_to_main: the branch-outcome hand-back still rewakes main ⏸️ untested no The prior payload did not establish a live result. Only the stubbed-engine integration test test_claude_stop_hook_restores_handoff_when_successor_closed_before_exit_to_main was run, and it passes.
Adversarial: downtime restore fails during the lost hand-back: main gets a delivered 'auto-arm FAILED' notice (exit 2, outcome=failed) instead of a silent exit 0 ⏸️ untested no The prior payload did not establish a live result. Only the integration test test_claude_stop_hook_notifies_when_closed_successor_downtime_restore_fails was run, with a mktemp-shim fault and a stubbed…
Lost hand-back repeated: the failure notice is delivered once per episode, then failed-suppressed, and every repeat still exits 2 ⏸️ untested no The prior payload did not establish a live result. Only test_host_lost_handback_notifies_once_per_episode was run, with a fixture host script. It passes on this branch and fails on base.
Adversarial: a rewake refused because main already acknowledged the wake stays silent (exit 0) and opens no failure episode ⏸️ untested no The prior payload did not establish a live result. Only test_host_benign_rewake_refusal_opens_no_failure_episode was run, with a fixture host script, and it passes.
Regression guard: the engine-error latch trips, probes and recovers as on base ⏸️ untested no The prior payload did not establish a live result. Only the stubbed-engine integration test test_latch_trips_after_two_engine_errors_then_probes_and_recovers was run, and it passes.
Real Claude primary in a lab home: the Stop hook starts the supervision host, and the host's hand-back rewakes the idle session ⏸️ untested no Started a real claude primary per the runbook in a marked lab home with the supervision-host opt-in. The session lock was acquired, but the Stop hook does nothing in the gate worktree by design: fm_pr…
Evidence: Targeted host tests on this branch (all ok)

Source: Targeted host tests on this branch (all ok)

ok - host+hook: a successor closed before exit_to_main does not suppress the branch-outcome rewake
ok - host+hook: a successor that closes during a held engine turn does not suppress the branch-outcome rewake
ok - host+hook: a refused hand-back becomes a delivered failure notice
ok - host: two engine errors latch the session, main keeps every away wake in the cooldown, a failed probe doubles it up to its cap, and a report recovers it silently
ok - host+hook: an attended main-only pass-through rewakes main and keeps its successor watcher
ok - host: a captain return during an engine turn hands that turn's outcomes to main
ok - host: an engine turn that records no outcome hands its durable wake to main
Evidence: Autoarm test file on this branch (all ok)

Source: Autoarm test file on this branch (all ok)

ok - auto-arm: inert in a linked child worktree even when in-flight
ok - auto-arm: inert with no session lock
ok - auto-arm: a demonstrably dead recorded session owner is reclaimed through fm-lock.sh before arming
ok - auto-arm: inert without arm, rewake, or lock replacement when another live harness owns the home
ok - auto-arm: inert while AFK owns supervision
ok - auto-arm: stale-owner recovery leaves the AFK and supervision-need gates unchanged
ok - auto-arm: resolves the outermost pid of a nested contiguous claude ancestry (bg-spare chain)
ok - auto-arm: inert with nothing in flight and no X-mode need
ok - auto-arm: actionable close translates to exactly one exit-2 rewake with reason
ok - auto-arm: actionable close survives a healthy successor without duplicate delivery
ok - auto-arm: an attached cycle's end starts a handling successor named after the closed arm before the rewake
ok - auto-arm: an unconfirmed handling successor is reported in the rewake instead of blocking it
ok - auto-arm: bounded failure verification emits one automatic-mechanism alarm
ok - auto-arm: consecutive failures keep Stop-owned retry without repeating notice
ok - auto-arm: marker-write refusal defers delivery until one successor commits the notice
ok - auto-arm: unverified clean close exhausts retries and fails closed
ok - auto-arm: post-alarm actionable outcomes cannot continue or reset failure state
ok - auto-arm: benign cycle end with a live watcher and fresh beacon stays silent across the next cycle
ok - auto-arm: budget contention preserves the episode and forces a reset retry
ok - auto-arm: owner-mutex contention preserves successor episode state
ok - auto-arm: X-mode poll need arms the cycle even with no tasks in flight
ok - auto-arm: a registered custom check arms the cycle even with no tasks in flight
ok - auto-arm: concurrent firings admit one owner and one rewake translation
ok - auto-arm: TERM mid-arm commits a durable failure and exits 2 for rewake
ok - auto-arm: an abandoned owner claim is reclaimed so a lapsed cycle re-arms
ok - auto-arm: an abandoned-claim reclaim reaps a dead steal mutex without nesting
ok - auto-arm: a legacy owner still arming is never reclaimed while its watcher keeps beating
ok - auto-arm: a fresh legacy arming claim is never reclaimed while its startup window is still open
ok - auto-arm: a live claim the ledger does not name is never reclaimed
ok - auto-arm: a claim whose pid was reused is reclaimed even while its ledger entry still reads arming
ok - auto-arm: a reused-pid claim is reclaimed even with no ledger entry to prove it
ok - auto-arm: an identity-matched owner still arming is never reclaimed
ok - auto-arm: the guard's terminal-check claim is never reclaimed
ok - auto-arm: a stuck live legacy owner is retired via TERM and its lock reclaimed
ok - auto-arm: a SIGSTOPped legacy owner is reclaimed with TERM pending and dies on continue
ok - auto-arm: a live open generation claim defers concurrent firings with no lock held
ok - auto-arm: a hung generation owner with no watcher beat is superseded so re-arming self-heals
ok - auto-arm: an identityless arming ledger never defers the gate (reused-pid loophole closed)
ok - auto-arm: a superseded owner never re-invokes the arm and leaves its successor's claim untouched
ok - auto-arm: a superseded owner goes silent - one supersession episode, one translation, no held mutex
ok - auto-arm: need vanishing mid-cycle closes without a rewake
ok - auto-arm: mid-cycle AFK hands triage to the daemon with no rewake
ok - auto-arm: active in a marked secondmate home
ok - auto-arm: a long FM_POLL with FM_GUARD_GRACE unset reaches fm-watch-arm.sh with the derived grace
ok - auto-arm: config/supervision-host-off keeps the hook on the arm exactly as before
ok - auto-arm: a Claude home without config/supervision-host runs the host by default
ok - auto-arm: an opted-in home runs the host bound to its generation, and a host line rewakes like a wake
ok - auto-arm: a wake the host hands back under the away record says it is automatic supervision, not a return
ok - auto-arm: a wake the host hands back beside a quiet record carries no away note
ok - auto-arm: without the host the rewake banner is unchanged, eight wake lines at most
ok - auto-arm: a host handback delivers every host line, while its wake lines keep their cap
ok - auto-arm: a host that stood down closes silently without a retry
ok - auto-arm: a host rewake refused on an acknowledged marker opens no failure episode
ok - auto-arm: a lost host hand-back notifies once per failure episode
ok - auto-arm: a host that died without a close is retried, then reported as a failure
ok - auto-arm: --help, -h, and an unknown argument arm nothing; the Stop path still arms
ok - fm-lock: shared session-lock lib preserves the status path
ok - auto-arm: stands down only on a pi-code-delivered transcript_path (/.pi/)
Evidence: New host tests against base 8690c41 bin (reproduces silent exit 0)

Source: New host tests against base 8690c411 bin (reproduces silent exit 0)

ok - host+hook: a successor closed before exit_to_main does not suppress the branch-outcome rewake
not ok - the Stop hook must rewake main after the successor closed: expected exit 2, got 0

real	0m17.127s
user	0m7.130s
sys	0m16.701s
not ok - the Stop hook must notify main when neither hand-back nor downtime restoration commits: expected exit 2, got 0
Evidence: New autoarm tests against base 8690c41 bin

Source: New autoarm tests against base 8690c411 bin

ok - auto-arm: a host rewake refused on an acknowledged marker opens no failure episode not ok - a lost hand-back must reach main: expected exit 2, got 0

ok - auto-arm: a host rewake refused on an acknowledged marker opens no failure episode
not ok - a lost hand-back must reach main: expected exit 2, got 0
- Outcome: ⚠️ 1 warning across 1 run (8m45s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

⚠️ **Test** - 1 warning
  • ⚠️ live validation verdict: inconclusive (0 of 7 scenarios were driven live against the product); untested: Successor watcher closes mid engine turn, then the host hands its branch outcome to main: the Stop hook rewakes main (exit 2, outcome=rewake) and the marker is left at pending/announced downtime, Successor closes before exit_to_main: the branch-outcome hand-back still rewakes main, Adversarial: downtime restore fails during the lost hand-back: main gets a delivered 'auto-arm FAILED' notice (exit 2, outcome=failed) instead of a silent exit 0, Lost hand-back repeated: the failure notice is delivered once per episode, then failed-suppressed, and every repeat still exits 2, Adversarial: a rewake refused because main already acknowledged the wake stays silent (exit 0) and opens no failure episode, Regression guard: the engine-error latch trips, probes and recovers as on base, Real Claude primary in a lab home: the Stop hook starts the supervision host, and the host's hand-back rewakes the idle session
  • Live validation: ⚠️ inconclusive - 0 of 7 scenarios driven live against the product
Scenario Result Live Evidence
Successor watcher closes mid engine turn, then the host hands its branch outcome to main: the Stop hook rewakes main (exit 2, outcome=rewake) and the marker is left at pending/announced downtime ⏸️ untested no The prior payload did not establish a live result. Only the stubbed-engine integration test test_claude_stop_hook_restores_handoff_when_successor_closed_mid_engine_turn was run: it passes on this bran…
Successor closes before exit_to_main: the branch-outcome hand-back still rewakes main ⏸️ untested no The prior payload did not establish a live result. Only the stubbed-engine integration test test_claude_stop_hook_restores_handoff_when_successor_closed_before_exit_to_main was run, and it passes.
Adversarial: downtime restore fails during the lost hand-back: main gets a delivered 'auto-arm FAILED' notice (exit 2, outcome=failed) instead of a silent exit 0 ⏸️ untested no The prior payload did not establish a live result. Only the integration test test_claude_stop_hook_notifies_when_closed_successor_downtime_restore_fails was run, with a mktemp-shim fault and a stubbed…
Lost hand-back repeated: the failure notice is delivered once per episode, then failed-suppressed, and every repeat still exits 2 ⏸️ untested no The prior payload did not establish a live result. Only test_host_lost_handback_notifies_once_per_episode was run, with a fixture host script. It passes on this branch and fails on base.
Adversarial: a rewake refused because main already acknowledged the wake stays silent (exit 0) and opens no failure episode ⏸️ untested no The prior payload did not establish a live result. Only test_host_benign_rewake_refusal_opens_no_failure_episode was run, with a fixture host script, and it passes.
Regression guard: the engine-error latch trips, probes and recovers as on base ⏸️ untested no The prior payload did not establish a live result. Only the stubbed-engine integration test test_latch_trips_after_two_engine_errors_then_probes_and_recovers was run, and it passes.
Real Claude primary in a lab home: the Stop hook starts the supervision host, and the host's hand-back rewakes the idle session ⏸️ untested no Started a real claude primary per the runbook in a marked lab home with the supervision-host opt-in. The session lock was acquired, but the Stop hook does nothing in the gate worktree by design: fm_pr…
  • nice -n 10 bash tests/fm-claude-stop-autoarm.test.sh (whole file, as the recorded decision allows): all pass, including test_host_benign_rewake_refusal_opens_no_failure_episode and test_host_lost_handback_notifies_once_per_episode
  • nice -n 10 on a copy of tests/fm-supervision-host.test.sh that runs only these functions: test_claude_stop_hook_restores_handoff_when_successor_closed_before_exit_to_main, test_claude_stop_hook_restores_handoff_when_successor_closed_mid_engine_turn, test_claude_stop_hook_notifies_when_closed_successor_downtime_restore_fails, test_latch_trips_after_two_engine_errors_then_probes_and_recovers, test_claude_stop_hook_delivers_a_main_only_pass_through, test_return_during_an_engine_turn_hands_its_outcomes_to_main, test_away_turn_without_a_report_hands_the_wake_to_main: all pass
  • Regression reproduction: git archive 8690c411 into a scratch dir, copied in the new test files, ran the new host and autoarm tests against the base bin/ code. mid_engine_turn, downtime_restore_fails and lost_handback fail with 'expected exit 2, got 0'; benign_refusal passes there too (its behaviour is preserved, as intended)
  • Tried a live lab Claude primary per the runbook (fm-lab-home.sh create, supervision-host opt-in, claude on the private fm-lab tmux socket). Lab torn down.
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@greptile-apps

greptile-apps Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 5/5

[High risk] Modifies supervision host hand-back and auto-arm failure handling.

The PR appears safe to merge; no outstanding finding or new actionable issue was identified.

Reviews (2) · Last reviewed commit: "no-mistakes(ci): I fixed the Greptile fi..."

Comment thread bin/fm-claude-stop-autoarm.sh Resolved
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: whole thread read (body + attestation; linked #6294/#5943 ready-for-pr; Greptile P1). Diff reviewed vs main 8690c4117a298ee870f0f72f571c72b846b4c5fb.

Verdict: waiting-author · contract-class: restore · Firstmate flag: no · closes #6294/#5943: yes (body Fixes both; matches described successor-closed hand-back loss)

Tip vs main (own inspection):

  • Main exit_to_main retires successor then exits 0 without republishing downtime when the successor already closed — Stop rewake refuses on pending:handling / announced:handling with no healthy watcher (issues' silent gap).
  • Tip republishes downtime on hand-back (nonzero if restore fails) and adds a host-mode Stop fallback that commits failure + exit 2 when marker is pending:handling:* and no watcher is live. Unconfigured path is the broken default continuity path — restore (not a new observer/wake/Bearings surface).

VISION.md per-rule:

  • One captain, one interface: aligns — lost hand-back becomes a delivered failure/rewake, not silent drop.
  • Authority explicit: aligns — no new autonomy grant.
  • Scripts vs agents: aligns — host/autoarm mechanics stay in scripts.
  • A restart is a non-event: aligns — restores durable hand-back when successor already exited.
  • Delegation with a spine: aligns.
  • Fleet outlives any vendor: aligns (Claude Stop path continuity).
  • Scope: aligns.

Attestation: MATCH 565863f70ddd. CI/NM: SUCCESS (CI 36952854233; NM 36952854240). Greptile: FAILURE P1 — announced:handling not covered by the new fallback (bin/fm-claude-stop-autoarm.sh); #5943's field marker was announced:handling. Please include announced:handling:* in that check + a regression, then re-push. Mergeable: MERGEABLE/UNSTABLE. No auto-merge. Workflow approvals this pass: none.

…d: when the supervision host hands back an actionable wake, its rewake is refused, and no watcher is healthy, the hand-back still has to reach main as a delivered notice. That must be true whether the recovery marker is `pending:handling` or `announced:handling`. Only one place applies this check: the lost hand-back fallback in `bin/fm-claude-stop-autoarm.sh`. **Fix:** that check now accepts both `pending:handling:*` and `announced:handling:*` tokens (a one-line change). Nothing else in the fallback changed: - Refusals on any other marker, such as an already acknowledged one, still exit 0 silently and open no failure episode. - The notice is still sent once per episode, and repeats are recorded as `failed-suppressed`. **Tests:** - `tests/fm-claude-stop-autoarm.test.sh`: the lost hand-back test now runs as a shared helper with two variants, one writing a `pending:handling` marker and a new one writing `announced:handling` (`test_host_lost_announced_handback_notifies_once_per_episode`). - `tests/fm-supervision-host.test.sh`: the end-to-end test where downtime restoration fails is now a shared helper too, with a new `announced` variant (`test_claude_stop_hook_notifies_when_closed_announced_successor_downtime_restore_fails`). It moves the handling episode to `announced` before the host hands back. Without the fix the hook would exit 0 here; the test requires exit 2, `outcome=failed` and a delivered failure notice. **Verification (all under nice -n 10):** - The full `tests/fm-claude-stop-autoarm.test.sh` suite passed (rc=0), including both lost hand-back variants and the benign-refusal test. - In `tests/fm-supervision-host.test.sh` I ran only the four hand-back test functions, all passing (rc=0). The suite can't run single functions, so I used a temporary copy with a trimmed test list and deleted it afterwards; `git status` shows only the 3 intended files changed. - shellcheck is clean on all three changed files. I did not run `bin/fm-lint.sh`. - I did not run the new tests against the unfixed code; the claim that they fail without the fix comes from reading the old check
@tiago-peixoto

Copy link
Copy Markdown
Contributor Author

Addressed: the lost hand-back fallback in bin/fm-claude-stop-autoarm.sh now accepts announced:handling:* as well as pending:handling:*, with regressions test_host_lost_announced_handback_notifies_once_per_episode and test_claude_stop_hook_notifies_when_closed_announced_successor_downtime_restore_fails. Head c6c6e856 is mergeable with all checks passing.

@kunchenguid
kunchenguid merged commit 241d461 into kunchenguid:main Oct 2, 2026
20 checks passed
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: this is merged. Thank you @tiago-peixoto — really appreciate you taking the time on this.

d-ploutarchos added a commit to OK-LG/firstmate that referenced this pull request Oct 2, 2026
* test: preserve Pi calm transcript captures with Pi 1.0 (kunchenguid#6338)

* test(calm): pin Pi's regular TUI mode where pane assertions read scrollback

Pi 1.0.0 defaults its TUI to a fullscreen alternate-screen mode whose
scrollable transcript is application-owned, so rows that leave the viewport
never enter terminal scrollback and tmux capture-pane -S can no longer see
them. The Pi Calm e2e launches now pass --tui-mode regular wherever the flag
exists so the transcript assertions keep reading real scrollback on both the
Pi 1.0.0 line and earlier Pi lines, which have no such flag and render
regular-only anyway.

* no-mistakes(document): Correct Pi TUI documentation and scrollback rationale

* fix(bin): preserve hold reasons and reject invalid completion inventories (kunchenguid#6331)

* fix(bin): encode captain-hold reasons and reject self-inventory in complete

hold now stores a reason with parentheses, line breaks, or percent signs
through a reversible percent encoding that every reader decodes, instead of
refusing it. hold --origin records the origin on the held task, and complete
refuses the origin as its own inventory entry and an entry held for a
different origin; holds with no recorded origin are accepted and flagged.

* fix(review): Decode marked hold reasons consistently across readers

* fix(review): Remove unnecessary lifecycle test dispatch

* fix(review): Correct hold origin identity and inventory recovery

* fix(review): Record origins before placing backend holds

* fix(document): Clarify captain-hold validation and reason reader documentation

* fix(ci): Fixed both findings: failed backend holds restore the previous origin, and invalid base64/UTF-8 reasons remain verbatim. Added regressions and documented valid-literal ambiguity. Both failures were reproduced before fixes. Verification: 54 lifecycle tests and 9 wrapper tests passed; 7 Beads-specific cases skipped because tasks-axi is markdown-only. Focused lint and diff checks passed. No pipeline or publication actions performed

* fix: reclaim orphaned watcher arms on the next park (kunchenguid#6335)

* fix(bin): take over the watcher cycle a main-only pass-through leaves

An attended main-only pass-through leaves a successor watcher cycle
running through main's handling turn. The session's next park attached
to that cycle instead of owning it, so the successor's arm, orphaned by
its host's exit, kept owning the watcher while the new park's arm polled
it twice a second until the next close or the park boundary, hours later
in a quiet second mate. A second-mate restart hit this every time, since
its persist request is a main-only close.

The host now records the successor it leaves for main, and the next
host's first cycle runs bin/fm-watch-arm.sh --take-over on it: when that
arm still owns the healthy watcher, the new arm stops it, reports a
reason the cycle delivered first, and otherwise owns a fresh cycle. The
stop's own downtime publication is undone over an acknowledged episode
when no wake was appended in between, so the handover wakes nobody.

* no-mistakes(review): Keep left-arm record until the orphaned arm is gone

* no-mistakes(review): Relinquish successor arm only after durably recording it

* no-mistakes(review): Relinquish successor only after its record reads back

* no-mistakes(document): Clarify successor takeover guarantees and authoritative documentation

* no-mistakes(ci): Fixed ci-1: acknowledgement restore now requires the exact taken-over arm/watcher ledger row with signal=TERM, awaited within a short bound. Otherwise takeover proceeds without erasing downtime. Added a self-exit regression confirmed failing before the fix and passing afterward; ordinary takeover tests and the full watcher-arm suite pass. Updated Generation reuse documentation. Syntax, diff checks, and ShellCheck pass with existing SC1091/SC2034 warnings excluded. ci-2 remains unchanged

* no-mistakes(document): Clarify watcher take-over recovery and restart limits

* fix(bin): restore downtime on supervision-host hand-back when the successor already closed (kunchenguid#6355)

* fix(bin): restore supervision host hand-back continuity

* no-mistakes(review): Scope host hand-back failure fallback to lost pending:handling

* no-mistakes(review): Remove stray scratch test copy tests/.tmp-rest.test.sh

* no-mistakes(test): Initialise successor globals so early hand-back survives set -u

* no-mistakes(document): Document host hand-back downtime failure and Claude lost-handback notice

* no-mistakes(ci): I fixed the Greptile finding. The rule that must hold: when the supervision host hands back an actionable wake, its rewake is refused, and no watcher is healthy, the hand-back still has to reach main as a delivered notice. That must be true whether the recovery marker is `pending:handling` or `announced:handling`. Only one place applies this check: the lost hand-back fallback in `bin/fm-claude-stop-autoarm.sh`. **Fix:** that check now accepts both `pending:handling:*` and `announced:handling:*` tokens (a one-line change). Nothing else in the fallback changed: - Refusals on any other marker, such as an already acknowledged one, still exit 0 silently and open no failure episode. - The notice is still sent once per episode, and repeats are recorded as `failed-suppressed`. **Tests:** - `tests/fm-claude-stop-autoarm.test.sh`: the lost hand-back test now runs as a shared helper with two variants, one writing a `pending:handling` marker and a new one writing `announced:handling` (`test_host_lost_announced_handback_notifies_once_per_episode`). - `tests/fm-supervision-host.test.sh`: the end-to-end test where downtime restoration fails is now a shared helper too, with a new `announced` variant (`test_claude_stop_hook_notifies_when_closed_announced_successor_downtime_restore_fails`). It moves the handling episode to `announced` before the host hands back. Without the fix the hook would exit 0 here; the test requires exit 2, `outcome=failed` and a delivered failure notice. **Verification (all under nice -n 10):** - The full `tests/fm-claude-stop-autoarm.test.sh` suite passed (rc=0), including both lost hand-back variants and the benign-refusal test. - In `tests/fm-supervision-host.test.sh` I ran only the four hand-back test functions, all passing (rc=0). The suite can't run single functions, so I used a temporary copy with a trimmed test list and deleted it afterwards; `git status` shows only the 3 intended files changed. - shellcheck is clean on all three changed files. I did not run `bin/fm-lint.sh`. - I did not run the new tests against the unfixed code; the claim that they fail without the fix comes from reading the old check

---------

Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: Mickaël Rémond <[email protected]>
Co-authored-by: Tiago <[email protected]>
yehezkieled added a commit to yehezkieled/firstmate that referenced this pull request Oct 5, 2026
* fix: reclaim orphaned watcher arms on the next park (kunchenguid#6335)

* fix(bin): take over the watcher cycle a main-only pass-through leaves

An attended main-only pass-through leaves a successor watcher cycle
running through main's handling turn. The session's next park attached
to that cycle instead of owning it, so the successor's arm, orphaned by
its host's exit, kept owning the watcher while the new park's arm polled
it twice a second until the next close or the park boundary, hours later
in a quiet second mate. A second-mate restart hit this every time, since
its persist request is a main-only close.

The host now records the successor it leaves for main, and the next
host's first cycle runs bin/fm-watch-arm.sh --take-over on it: when that
arm still owns the healthy watcher, the new arm stops it, reports a
reason the cycle delivered first, and otherwise owns a fresh cycle. The
stop's own downtime publication is undone over an acknowledged episode
when no wake was appended in between, so the handover wakes nobody.

* no-mistakes(review): Keep left-arm record until the orphaned arm is gone

* no-mistakes(review): Relinquish successor arm only after durably recording it

* no-mistakes(review): Relinquish successor only after its record reads back

* no-mistakes(document): Clarify successor takeover guarantees and authoritative documentation

* no-mistakes(ci): Fixed ci-1: acknowledgement restore now requires the exact taken-over arm/watcher ledger row with signal=TERM, awaited within a short bound. Otherwise takeover proceeds without erasing downtime. Added a self-exit regression confirmed failing before the fix and passing afterward; ordinary takeover tests and the full watcher-arm suite pass. Updated Generation reuse documentation. Syntax, diff checks, and ShellCheck pass with existing SC1091/SC2034 warnings excluded. ci-2 remains unchanged

* no-mistakes(document): Clarify watcher take-over recovery and restart limits

* fix(bin): restore downtime on supervision-host hand-back when the successor already closed (kunchenguid#6355)

* fix(bin): restore supervision host hand-back continuity

* no-mistakes(review): Scope host hand-back failure fallback to lost pending:handling

* no-mistakes(review): Remove stray scratch test copy tests/.tmp-rest.test.sh

* no-mistakes(test): Initialise successor globals so early hand-back survives set -u

* no-mistakes(document): Document host hand-back downtime failure and Claude lost-handback notice

* no-mistakes(ci): I fixed the Greptile finding. The rule that must hold: when the supervision host hands back an actionable wake, its rewake is refused, and no watcher is healthy, the hand-back still has to reach main as a delivered notice. That must be true whether the recovery marker is `pending:handling` or `announced:handling`. Only one place applies this check: the lost hand-back fallback in `bin/fm-claude-stop-autoarm.sh`. **Fix:** that check now accepts both `pending:handling:*` and `announced:handling:*` tokens (a one-line change). Nothing else in the fallback changed: - Refusals on any other marker, such as an already acknowledged one, still exit 0 silently and open no failure episode. - The notice is still sent once per episode, and repeats are recorded as `failed-suppressed`. **Tests:** - `tests/fm-claude-stop-autoarm.test.sh`: the lost hand-back test now runs as a shared helper with two variants, one writing a `pending:handling` marker and a new one writing `announced:handling` (`test_host_lost_announced_handback_notifies_once_per_episode`). - `tests/fm-supervision-host.test.sh`: the end-to-end test where downtime restoration fails is now a shared helper too, with a new `announced` variant (`test_claude_stop_hook_notifies_when_closed_announced_successor_downtime_restore_fails`). It moves the handling episode to `announced` before the host hands back. Without the fix the hook would exit 0 here; the test requires exit 2, `outcome=failed` and a delivered failure notice. **Verification (all under nice -n 10):** - The full `tests/fm-claude-stop-autoarm.test.sh` suite passed (rc=0), including both lost hand-back variants and the benign-refusal test. - In `tests/fm-supervision-host.test.sh` I ran only the four hand-back test functions, all passing (rc=0). The suite can't run single functions, so I used a temporary copy with a trimmed test list and deleted it afterwards; `git status` shows only the 3 intended files changed. - shellcheck is clean on all three changed files. I did not run `bin/fm-lint.sh`. - I did not run the new tests against the unfixed code; the claim that they fail without the fix comes from reading the old check

* fix: reduce remote-job polling process churn (kunchenguid#6363)

* perf: cut remote-job idle process creation in the three hot loops

Post-update host measurement still attributes most idle churn to three
per-sample loops: result-consumer state reads and date calls, the delta
reader's capture/hash pass on every poll, and the lane preemption scan's
per-field pipelines. This drops each to its minimum without touching the
contracts around them.

* fm_remote_job_read_state gains an optional result-variable form backed
  by fm_remote_job_read_line, a builtin-only bounded record read (regular
  non-symlink file, byte bound, one newline-terminated line, tolerated
  unterminated tail, no carriage returns). fm_remote_job_wait samples
  state and the SECONDS clock with no per-sample children; one date call
  converts the epoch deadline once.
* fm-remote-delta-read stats the log each poll and re-runs the bounded
  capture and hashing only when size, mtime, ctime, inode, or device
  change. The snapshot's own stat writes the comparison key, so a log
  that moves between the gate and the capture is never read as stable.
* worker_preempting_waiter_exists reads state, home, and the staged argv
  head with builtins only. The now-unused worker_job_command goes away.

The bounded reads use -d '' -n, which behaves identically on the macOS
stock bash 3.2 and current bash; -N does not exist on 3.2. Tests cover
the malformed-record corpus, delta identity gating, fork-free lane
scanning through counting PATH shims, and same-home versus cross-home
preemption. No signal traps or sleep contracts change.

* no-mistakes(review): Restore subsecond delta keys and byte-bounded builtin record reads

* no-mistakes(document): Clarify delta snapshot caching and coarse-timestamp fallback

* no-mistakes(lint): Scope UTF-8 regression locales to individual function calls

* no-mistakes(ci): Fixed both lint failures by applying the documented production-library analysis boundary at the two affected test imports. Runtime behavior is unchanged; the library remains independently linted. Canonical full-analysis lint passed for the library and both suites, as did bash syntax checks and git diff --check

* fix(bin): recognize titled Claude top rules and preserve grey slash commands (kunchenguid#5963)

* fix(composer): read a titled Claude top rule as the composer's edge

A named Claude Code session draws its title into the composer's top rule.
The strict separator predicate rejected that row, so the closing rule read
as a lower unmatched separator and an idle, empty composer classified
unknown on every cursorless backend, refusing fm-send, exit, and relaunch.

Spare a bare agent-glyph row sandwiched between a width-proven titled rule
and the screen's only unmatched separator directly below it. The strict
separator predicate, dead-shell rule, and blank-row posture are unchanged.

Fixes kunchenguid#5601
Fixes kunchenguid#5558

* no-mistakes(test): Keep Claude's grey slash command in Herdr payload proof

* no-mistakes(test): Make missing-herdr version check hermetic to installed herdr

* fix: prevent Pi trust prompts in seeded secondmate homes (kunchenguid#6387)

* fix: pre-approve Pi trust for seeded secondmate homes

Unattended first launches of Firstmate-seeded Pi secondmate homes stalled on
"Trust project folder?" until Enter. Probe --approve like --tui-mode and pass
it only for --secondmate when help advertises it (.fm-secondmate-home signal),
leaving ordinary workers and older Pi unchanged.

* no-mistakes(document): Consolidate Pi seeded-home trust documentation ownership

* no-mistakes(ci): Fixed Lint 1’s unused polling counter. Diagnosed Behavior portable serial 4 as a pre-existing delta-reader test clock race; replaced timing-dependent rewrite and deletion with deterministic executable-boundary synchronization. ShellCheck, Bash syntax checks, and git diff --check passed. Delta-reader tests passed three consecutive runs; all three live Pi trust cases passed. Production behavior unchanged

* fix(bin): retry ShellCheck roots that hit the memory ceiling without --external-sources (kunchenguid#6443)

* fix(lint): retry memory-bound roots without external sources

* no-mistakes(review): Make fallback tests portable and correct source-following telemetry

* no-mistakes(review): Remove committed parity fixtures and use disposable test roots

* no-mistakes(document): Document ShellCheck memory fallback and telemetry

* no-mistakes(review): Cover bounded and unbounded fallback RSS behavior

* no-mistakes(document): Correct stale lint fallback documentation

* no-mistakes(document): Correct stale lint test documentation

* no-mistakes(ci): The memory fallback (the retry without --external-sources) now gets only the time left in its root's original deadline, so it can no longer outlast the CI job. Invariant: one root's first attempt plus its fallback must fit inside a single FM_LINT_ROOT_SECONDS deadline, plus the cleanup grace. Only one site started a new deadline: the fallback call in fm_lint_run_root. The deadline is the only budget involved, because the memory limit already applies to each process separately. Changes in bin/fm-lint.sh: - fm_lint_exec_root now takes a <seconds> argument instead of always reading FM_LINT_INTERNAL_ROOT_SECS. - The first attempt passes the full deadline. - The fallback passes floor((start + deadline - now) / 1000) seconds. - When bounds are enforced and less than 1 second is left, no retry starts. fm_exec_timed rejects 0 seconds, so the retry cannot run with no time. The root keeps reason=memory, and the shard output says "no time left in its Ns deadline to retry without it". - Unbounded local runs have no deadline and behave as before. - The header comment now describes the shared deadline. Changes in tests/fm-lint.test.sh: a new test, test_memory_fallback_spends_only_the_remaining_root_deadline, runs only on hosts that can enforce bounds. It uses a 6 s deadline and 1 s grace. - Case 1: the first attempt runs 3 s and then fails with memory status 251. The test asserts one fallback ran, reported reason=timeout, and the root's recorded duration is under 7000 ms. - Case 2: the first attempt runs 5.2 s. The test asserts no fallback starts, the skip is explained, and the sidecar records memory with source-following 1. Verification: - Full `nice -n 10 bash tests/fm-lint.test.sh` passed, including the new test, in about 5 minutes. - Case 1 run against the HEAD script: the root took 9168 ms, so the under-7000 ms check fails before the fix. - `bin/fm-lint.sh bin/fm-lint.sh tests/fm-lint.test.sh` reported no findings. - The CI workflow is unchanged, so the Test step still runs only tests/fm-lint.test.sh with nice -n 10 and the 12 GiB ShellCheck limit

* fix(pi): restore watcher continuity across successor gaps and make extension log opt-in (kunchenguid#5489)

* Fix Pi watcher successor-gap confirmations and add extension log

Accept an already-acknowledged handling confirmation as a no-op when the
generation matches, confirm the restoration's own recovery token with a
superseded (not rejected) outcome on generation mismatch, retire an arm on
confirm failure only when the failed token names that exact pid, and record
restore attempts, readiness timeouts, and confirm results in the bounded
state/.watch-extension.log. Regression tests: already-acked no-op plus
mismatch/dead-pid/lock-mismatch rejections and the manual-restart churn
contract in fm-watch-arm.test.sh, and a mid-restore marker advance with no
rejection appendix in fm-pi-watch-extension.test.sh.

* Treat a dead arm child as an empty slot so repair and retry recover

startArm and scheduleRetry answered unchanged while holding a ChildProcess
whose OS process was already gone but whose close had not fired, so neither
the repair tool nor the retry timer started anything until that close fired.
Gate slot occupancy on a liveness check (exit/signal codes plus pid probe)
and start a fresh arm instead, with a regression test driving the repair
tool against a dead-but-unclosed child.

* no-mistakes(document): Document new Pi extension log knob

* no-mistakes(review): Fix confirm-failure retire token match, add distinct-pid test

* no-mistakes(document): Clarify retire guard needs pid and generation

* Make the Pi extension diagnostic log opt-in and default-off

Only a positive FM_WATCH_EXTENSION_LOG_KEEP_LINES enables
state/.watch-extension.log. Unset, empty, non-numeric, zero, and
negative values disable logging entirely, so the default run writes
nothing and never creates the file. The shared positiveInteger
fallback semantics stay untouched for the retry and timeout knobs.
docs/configuration.md owns the knob contract and
docs/watcher-continuity.md points at it. Tests: the superseded-delivery
case runs opted in, and a new case proves unset, zero, and non-numeric
values create no log file while delivery still succeeds.

* no-mistakes(document): Qualify extension-log coverage bullet as opt-in

* no-mistakes(ci): The two reported checks (CI run 36372002913, Require no-mistakes run 36372069208) show conclusion action_required with 0 jobs and no logs because this is a fork PR (RibatTRW/firstmate) and GitHub is holding the workflow runs awaiting maintainer approval; that gate is external to the code and needs a maintainer to approve the runs. While verifying the change locally I found a real defect the approved CI run would hit: the PR's new test test_handling_delivered_rejects_a_superseded_generation failed deterministically. Invariant violated: reopen-announced (a non-successor/manual arm start) mints a fresh recovery generation only when the durable wake queue holds unrecovered work; an announced episode with an empty queue must be left untouched so idle arm starts never churn generations (the [ -s queue ] guard from kunchenguid#4819, relied on by bin/fm-watch.sh:2413 and covered by the append-reopens and announcement-bound sibling tests). The test called reopen with an empty queue and expected churn, so the fix establishes the queued-work precondition (append one wake, re-announce, re-read the generation) before asserting the reopen mints and the old confirmation mismatches. Test-only change, 14 lines in tests/fm-watch-arm.test.sh. Verified: fm-watch-arm.test.sh 25/25 ok on two consecutive runs, fm-pi-watch-extension.test.sh 55/55 ok, and shellcheck reports only one pre-existing warning outside the edited region

* no-mistakes(document): Restore blank line in watcher-continuity docs

* Route superseded Pi deliveries like confirmed ones and cover the retire guard

A superseded handling confirmation now falls through to the normal delivery
path, so an accepting supervision branch owns the wake instead of main.
Scope the watcher-continuity token-pinned confirmation and narrowed retire
rule to Pi, since omp and OpenCode still confirm against the current
successor. Add tests that fail when the retire guard, the scheduled-retry
gate, or the deferred-close gate is reverted, relabel the churned-generation
characterization test, and use a reaped pid for the dead-pid rejection.

* fix(pi): hide duplicate assistant finals from hidden processing retries (kunchenguid#5863)

* fix(pi): silence unacknowledged processing retry replies

Suppress autonomous processing prose before persistence and during streaming while retaining tool calls, signed reasoning, and retryable outcomes. Restore ordinary output after acknowledgement or a user message.

Fixes kunchenguid#4954

* no-mistakes(review): Silence only processing retries, keep first presentation visible

* fix(pi): preserve differing processing retry replies

* test(pi): accept Pi 1.0.1's renamed HTML export renderer lookup (kunchenguid#6530)

Pi 1.0.1's createToolHtmlRenderer reads getToolRenderers and ignores
getToolDefinition. Calm /export still includes stock grep HTML; the
fixture has to pass the lookup key the installed Pi actually reads.

* fix(bin): tolerate transient quota read failures (