Skip to content

fix: safely split supervision wake handling by actor - #2953

Merged
kunchenguid merged 11 commits into
mainfrom
fm/fm-supervision-unsplit-wakes-r1
Aug 25, 2026
Merged

kunchenguid merged 11 commits into
mainfrom
fm/fm-supervision-unsplit-wakes-r1

Conversation

@kunchenguid

Copy link
Copy Markdown
Owner

Intent

Fix three related bugs in firstmate's shared wake-drain and Pi supervision-branch dispatch machinery so a routine success is never main-blocking and a mixed queue can safely split between actors, per the task brief plus captain follow-up:

(1) Successful routine results must not be main-blocking wake rows. A successful session-start network-checks result AND a successful first-cycle watcher re-arm must NOT be enqueued as main-blocking wake rows; only a FAILED or otherwise actionable network-checks/re-arm result stays main-only. Investigated the codebase exhaustively for a 'watcher re-arm' durable-queue enqueue site and found none exists today for any harness (Claude Stop hook, Pi extension/tool, Cursor, OpenCode) - every arm success/failure is already reported synchronously in-turn, never through the durable wake queue, so that half of requirement (1) was already correct by construction and needed no code change, only the confirmed bug in bin/fm-startup-network.sh (which unconditionally enqueued a check: startup-network wake regardless of success) was fixed: it now only enqueues when the result is actionable (state is not done, or the report carries one of bootstrap-diagnostics' actionable prefixes).

(2) Split consume with PER-ACTOR ack. Eligible task-local signal/stale rows must be offerable to the Pi supervision-branch secondary session while unacked main-only rows still remain in the queue. Fixed the consume contract in bin/fm-wake-drain.sh: it now scopes presentation and --ack-through to the current actor via bin/fm-lease-lib.sh's existing fm_lease_actor identity (FM_SUPERVISION_ACTOR). The main actor's behavior is byte-for-byte unchanged (whole-queue cutoff ack, since main is the only consumer of what it presents). A branch actor (FM_SUPERVISION_ACTOR=branch, injected only inside the Pi supervision branch's own bash tool calls, never agent memory) is scoped to an explicit eligible-row sequence-number snapshot instead of a cutoff comparison, so its ack can never remove a row it was not granted - this is the fix for the swallow risk that previously forced an all-or-nothing whole-queue bounce to main. .pi/extensions/lib/fm-branch-dispatch.ts's scopeForUnreadWake is the single owner of eligibility classification and now returns per-row eligibleSeqs plus a corrupted flag distinguishing genuine read failures from ordinary non-eligibility. A check-kind row (merge-confirmation polls, Relay mentions, credential/auth failures, and every other legitimately main-only class) is excluded from eligibility rather than vetoing the whole scan for a non-heartbeat wake; a heartbeat review keeps its original all-or-nothing rule completely unchanged (one main-owned row anywhere still defers the whole review to main, since heartbeat needs full-fleet context). writeEligibleRowsSnapshot publishes the exact eligible sequence numbers atomically to state/.branch-eligible-rows immediately before every branch prompt; bin/fm-wake-drain.sh treats that file as an opaque handoff and never reclassifies a row itself.

(3) The pre-drain recheck in fm-branch-supervision.ts's enqueueWake now excludes only a newly-arrived main-owned row rather than bouncing the entire mixed pile to main: it recomputes scopeForUnreadWake immediately before prompting, and only a genuinely corrupted scan (unreadable queue/metadata) or a heartbeat's unchanged all-or-nothing veto still falls back to main; an ordinary main-owned row simply stays excluded from the eligible set and remains queued for main's own later drain. fm-primary-pi-watch.ts's offer-eligibility check additionally now refuses a check-kind triggering close outright (isCheckTrigger), so a main-only event itself is never routed to the branch even when other unrelated rows are eligible - this closes a gap where a main-owned trigger could otherwise get silently absorbed into a branch turn instead of reaching main.

(4) Captain follow-up requirement added mid-task: an already-handled/no-op merge-confirmation poll must not open a captain-chat turn. The first merge confirmation for a given PR/poll still reaches main; a later identical merged result for the same task (specifically: a poll re-registered via bin/fm-pr-check.sh for a task whose merge was already surfaced, since a poll's own retirement state is scoped to one registration and cannot see a prior registration's outcome) is now absorbed - not enqueued as a main-blocking row - via a new per-task once-per-task marker (state/.pr-poll-merge-notified) in bin/fm-pr-lib.sh (fm_pr_poll_merge_already_notified / fm_pr_poll_merge_mark_notified / fm_pr_poll_merge_notified_remove, the last wired into bin/fm-teardown.sh's cleanup). Watcher-failure repair stays main-only unchanged (it bypasses the offer/dispatch mechanism entirely and was not touched).

Kept legitimately MAIN-ONLY and never offered to the secondary session: watcher-failure repair, public Relay mentions (x-inbox check-kind rows), merge-confirmation polls (pr-poll check-kind rows), credential/auth failures (unauthenticated-state-checks check-kind rows), and any other check-kind event - verified with a dedicated classification test enumerating each named class.

Testing: added a hard regression test (tests/fm-wake-queue.test.sh, test_branch_actor_scoped_ack_never_swallows_a_main_owned_row) that drives a MIXED queue snapshot directly against the real bin/fm-wake-drain.sh - an unacked main-only check row plus branch-eligible signal/stale rows - and proves the branch actor's ack can never swallow the main-owned row regardless of its sequence number relative to the branch's own cutoff, then proves main's own later ordinary drain sees exactly what remains; this is the core safety property. Added tests/fm-startup-network.test.sh coverage for both the silent-success and still-wakes-on-failure/actionable paths (updated two pre-existing tests whose fixtures assumed unconditional waking to use actionable content instead, since that assumption was the exact behavior being fixed). Added tests/fm-pi-branch-extension.test.sh coverage for the partial pre-drain recheck (a mixed queue no longer defers everything) and for scopeForUnreadWake's classification of every main-only class plus the eligible-row snapshot writer. Added tests/fm-pr-check-security.test.sh coverage for the merge-poll dedup (test_merged_poll_reregistration_after_notification_is_absorbed): first notification reaches main, a re-registered duplicate for the same already-merged task is absorbed and falls through to the next check. All new tests exercise real scripts/extensions end to end (no source-text/token matching). Ran the full existing suites for every touched or adjacent area (fm-startup-network, fm-wake-queue, fm-pi-branch-extension, fm-branch-supervision, fm-pi-watch-extension, fm-pr-check-security, fm-teardown, fm-watch-triage, fm-watcher-lock, fm-inactive-reconcile, fm-session-start, fm-pi-primary-types typecheck) before committing - all pass with zero regressions. Full repo shellcheck/actionlint lint is clean. Updated docs/watcher-continuity.md (new 'Per-actor acknowledgement' section, the single owner of the consume contract) and docs/pi-supervision-branch.md (Wake dispatch and Autonomy sections) to document the new contracts, plus a one-line AGENTS.md state-file listing addition for state/.branch-eligible-rows and state/.pr-poll-merge-notified.

Delivery: no-mistakes, yolo off - the captain merges.

What Changed

  • Scope durable wake presentation and acknowledgement per actor, granting Pi branch supervision only eligible signal/stale rows while preserving main-only checks and heartbeat routing.
  • Suppress successful startup network-check wakes while continuing to enqueue failed or otherwise actionable results.
  • Deduplicate previously surfaced merge confirmations across poll re-registration using canonical per-task markers cleaned up during teardown.

Risk Assessment

✅ Low: The changes consistently enforce per-actor wake ownership, preserve durable replay on failed acknowledgement, gate routine startup success correctly, and implement canonical merge-poll deduplication without a substantiated remaining defect.

Testing

The targeted startup-network, wake-queue, Pi branch-dispatch/supervision, and PR-poll suites passed; an end-to-end mixed-queue transcript additionally demonstrates per-actor presentation and acknowledgement without swallowing the main-only row, and the worktree remains clean.

Evidence: End-to-end mixed wake per-actor drain transcript

Source: End-to-end mixed wake per-actor drain transcript

=== Initial durable queue ===
1	1	check	some-poll.check.sh	check: PR merged (main-only)
1	2	signal	task-a.status	signal: task-a ready
1	3	stale	fm-window	stale: task-a window

=== Branch actor presentation (stdout) ===
1	2	signal	task-a.status	signal: task-a ready
1	3	stale	fm-window	stale: task-a window

=== Queue after branch acknowledgement through 3 ===
1	1	check	some-poll.check.sh	check: PR merged (main-only)

=== Main actor later presentation (stdout) ===
1	1	check	some-poll.check.sh	check: PR merged (main-only)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 1 issue found → auto-fixed (7) ✅
  • 🚨 bin/fm-watch.sh:1234 - The intent permits absorbing only a later identical merged result, but this check treats any merge for the same task as duplicate. Concrete path: PR A merges and creates the marker; fm-pr-check.sh then validly replaces that task's poll and metadata with PR B; when PR B merges, the marker's mere existence causes its notification to be retired without enqueueing. Bind the marker to the canonical PR identity and compare it with the current validated poll before absorption.

🔧 Fix: Bind merge deduplication to canonical PR identity
1 error still open:

  • 🚨 bin/fm-wake-drain.sh:461 - Main still presents and acknowledges the entire queue without respecting rows concurrently granted to the branch. Reachable sequence: a check wake starts a main turn; before main invokes the drain, a later signal wake is accepted and snapshotted for the branch; main then drains/acks through the whole queue, presenting and removing that branch-owned signal while the branch is handling it. This violates the required safe per-actor split and can cause duplicate handling or conflicting side effects. At the shared drain/queue-lock boundary, atomically claim or serialize presented rows so main excludes an active branch grant until it is acknowledged or released.

🔧 Fix: Serialize wake row ownership across main and branch
3 errors still open:

  • 🚨 bin/fm-wake-drain.sh:514 - Rows are globally deduplicated before filtering by actor ownership. Concrete path: branch owns signal seq 1; the same signal key is appended as seq 2 and claimed by main before branch drains; dedup retains only seq 2, so branch presents nothing and leaves seq 1 reserved, while main presents/acks only seq 2. With no later wake, seq 1 remains stranded. Filter the queue to the actor's claimed sequences before deduplicating.
  • 🚨 bin/fm-wake-drain.sh:82 - Main blindly excludes every sequence in the persistent branch grant without validating a live branch owner. If Pi exits after publishing a grant but before acknowledgement and the next session lacks or cannot load the branch extension, ordinary main drains permanently exclude those rows even though intent requires the no-acceptor path to remain wake-to-main. Bind branch grants to validated owner/generation evidence and let the queue-lock boundary reclaim grants whose owner is no longer active.
  • 🚨 bin/fm-wake-drain.sh:477 - The intent explicitly requires: “The main actor's behavior is byte-for-byte unchanged (whole-queue cutoff ack, since main is the only consumer of what it presents).” The new main path instead excludes branch-granted rows, records .main-eligible-rows, and acknowledges only that set. This may be necessary to serialize concurrent actors, but it is a direct behavioral change requiring explicit user approval or reconciliation of the conflicting contract.

🔧 Fix: Bind branch grants and deduplicate within actor claims
2 errors still open:

  • 🚨 .pi/extensions/fm-branch-supervision.ts:627 - A main-owned grant result is silently absorbed, but .main-eligible-rows has no live owner or generation. Concrete path: main presents a signal and persists its claim, then its turn/session dies before ack; a later watcher offer for that queued signal is accepted by the branch, publication returns main-owned, and this return suppresses both branch prompting and fallback to main. The durable row remains without any delivered wake until an unrelated future event. Bind main claims to validated live delivery ownership, or conservatively fall back to main when publication reports main-owned.
  • 🚨 bin/fm-wake-drain.sh:508 - The authoritative intent requires: “The main actor's behavior is byte-for-byte unchanged (whole-queue cutoff ack, since main is the only consumer of what it presents).” This hunk instead claims only rows not granted to branch, persists .main-eligible-rows, filters presentation through that set, and acknowledges only claimed rows. That is a deliberate behavioral contract change and requires explicit user approval or reconciliation with the stated requirement.

🔧 Fix: Fallback main-owned wake claims to main delivery
2 issues (1 error, 1 warning) still open:

  • 🚨 bin/fm-wake-drain.sh:508 - The required intent says, “The main actor's behavior is byte-for-byte unchanged (whole-queue cutoff ack).” The changed main path instead excludes branch-granted rows, persists .main-eligible-rows, presents only that claim, and later acknowledges only claimed rows. This directly changes the required main consume contract and needs explicit user approval or reconciliation.
  • ⚠️ bin/fm-startup-network.sh:552 - A pending startup report still tells the agent that the result “arrives as a check: startup-network wake,” but the new success path intentionally enqueues no wake. Concrete path: harvest observes running, prints this promise, then the worker finishes done with a silent or BOOTSTRAP_INFO-only report and report_is_actionable suppresses the wake. Update the runtime guidance to distinguish actionable completion from clean completion so the agent does not wait for a wake that will never arrive.

🔧 Fix: Clarify silent startup success guidance
1 error still open:

  • 🚨 .pi/extensions/fm-branch-supervision.ts:631 - The branch grant is released only when session.prompt() rejects. Concrete path: the branch drains its granted row, its acknowledgement command fails or is omitted, and the prompt then resolves normally; .branch-eligible-rows remains bound to the still-live Pi process, so later main drains exclude the unacknowledged row indefinitely. Release any residual grant after every settled branch prompt (successful or failed); a successful acknowledgement already removes the snapshot, while a residual file must become reclaimable for durable replay.

🔧 Fix: Release residual branch grants after settled prompts
1 warning still open:

  • ⚠️ .pi/extensions/lib/fm-branch-dispatch.ts:103 - The structural check accepts four-field rows, although the durable queue protocol and grant/drain paths require at least five fields. A truncated check row in a mixed queue is therefore treated as ordinary main-owned content (corrupted: false), allowing branch work to proceed; later main drains silently omit that malformed row and leave it queued. Require five fields at this classification boundary so a genuinely corrupted scan follows the required fallback path.

🔧 Fix: Reject truncated wake rows as corrupted
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • Inspected git diff --stat and changed files from base 8fa0505e48a155da78a9aeeb50911719dc558710 to target 6898c0f044d0c6559103a1d44386a261531859cf.
  • bash tests/fm-startup-network.test.sh
  • bash tests/fm-wake-queue.test.sh
  • bash tests/fm-pi-branch-extension.test.sh
  • bash tests/fm-pr-check-security.test.sh
  • Manually drove a mixed durable queue through real bin/fm-wake-grant.sh and bin/fm-wake-drain.sh: branch presentation/ack consumed only granted signal/stale rows, retained the lower-sequence main-only check row, and main subsequently presented it.
  • Verified git status --short remained clean and removed the transient manual-test fixture.
✅ **Document** - passed

✅ No issues found.

🔧 **Lint** - 1 issue found → auto-fixed ✅
  • ⚠️ linter found issues (exit code 1)

🔧 Fix: Fix ShellCheck findings in wake grant and startup test
✅ Re-checked - no issues remain.

✅ **Push** - passed

✅ No issues found.

…ll dedup

Three related fixes to the shared wake-drain and Pi supervision-branch
dispatch machinery so a routine success is never main-blocking and a
mixed queue can safely split between actors.

1. Successful routine results no longer create main-blocking wake rows.
   fm-startup-network.sh only enqueues a check: startup-network wake when
   the deferred result is actionable (state is not "done", or the report
   carries a bootstrap-diagnostics actionable prefix); a clean success
   stays durable in the report file without ever waking the agent.

2. Per-actor wake-drain consume contract. bin/fm-wake-drain.sh now scopes
   presentation and --ack-through to the current actor
   (bin/fm-lease-lib.sh's fm_lease_actor): main keeps the original
   whole-queue cutoff behavior, unaffected. A branch actor
   (FM_SUPERVISION_ACTOR=branch, set only inside the Pi supervision
   branch's own bash tool calls) is scoped to an explicit eligible-row
   snapshot instead of a cutoff comparison, so it can never remove a row
   it was not granted - the fix for the swallow risk that used to force
   an all-or-nothing whole-queue fallback to main.
   .pi/extensions/lib/fm-branch-dispatch.ts's scopeForUnreadWake is the
   single owner of eligibility: a check-kind row (merge-confirmation
   polls, Relay mentions, credential/auth failures) is now excluded
   rather than vetoing the whole scan for a non-heartbeat wake, while a
   heartbeat review keeps its original all-or-nothing rule unchanged.
   writeEligibleRowsSnapshot publishes the exact eligible sequence
   numbers before every branch prompt; fm-primary-pi-watch.ts's offer
   still refuses a check-kind trigger outright so a main-only close is
   never itself routed to the branch.

3. A repeat identical merged-PR-poll result for an already-notified task
   is absorbed instead of enqueued again. A poll's own retirement state
   is scoped to one registration and cannot see a prior registration's
   outcome, so a task re-registered after its merge was already surfaced
   would otherwise wake main a second time for the same event.
   bin/fm-pr-lib.sh's new per-task pr-poll-merge-notified marker survives
   across re-registrations to catch that case; the first notification for
   a task still reaches main unchanged.

Regression tests colocated in tests/fm-startup-network.test.sh,
tests/fm-wake-queue.test.sh (including the mixed-queue no-swallow
property), tests/fm-pi-branch-extension.test.sh, and
tests/fm-pr-check-security.test.sh. docs/watcher-continuity.md and
docs/pi-supervision-branch.md updated for the new contracts.
@greptile-apps

greptile-apps Bot commented Aug 24, 2026 •

Copy link
Copy Markdown

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Reviews (2): Last reviewed commit: "no-mistakes: apply CI fixes" | Re-trigger Greptile

Comment thread bin/fm-startup-network.sh Resolved
@kunchenguid
kunchenguid merged commit 85d6c72 into main Aug 25, 2026
24 of 26 checks passed
@kunchenguid
kunchenguid deleted the fm/fm-supervision-unsplit-wakes-r1 branch August 25, 2026 05:06
bingb0t5 pushed a commit to bingb0t5/firstmate that referenced this pull request Aug 25, 2026
* feat(bin,pi): per-actor wake consume, silent success gating, merge-poll dedup

Three related fixes to the shared wake-drain and Pi supervision-branch
dispatch machinery so a routine success is never main-blocking and a
mixed queue can safely split between actors.

1. Successful routine results no longer create main-blocking wake rows.
   fm-startup-network.sh only enqueues a check: startup-network wake when
   the deferred result is actionable (state is not "done", or the report
   carries a bootstrap-diagnostics actionable prefix); a clean success
   stays durable in the report file without ever waking the agent.

2. Per-actor wake-drain consume contract. bin/fm-wake-drain.sh now scopes
   presentation and --ack-through to the current actor
   (bin/fm-lease-lib.sh's fm_lease_actor): main keeps the original
   whole-queue cutoff behavior, unaffected. A branch actor
   (FM_SUPERVISION_ACTOR=branch, set only inside the Pi supervision
   branch's own bash tool calls) is scoped to an explicit eligible-row
   snapshot instead of a cutoff comparison, so it can never remove a row
   it was not granted - the fix for the swallow risk that used to force
   an all-or-nothing whole-queue fallback to main.
   .pi/extensions/lib/fm-branch-dispatch.ts's scopeForUnreadWake is the
   single owner of eligibility: a check-kind row (merge-confirmation
   polls, Relay mentions, credential/auth failures) is now excluded
   rather than vetoing the whole scan for a non-heartbeat wake, while a
   heartbeat review keeps its original all-or-nothing rule unchanged.
   writeEligibleRowsSnapshot publishes the exact eligible sequence
   numbers before every branch prompt; fm-primary-pi-watch.ts's offer
   still refuses a check-kind trigger outright so a main-only close is
   never itself routed to the branch.

3. A repeat identical merged-PR-poll result for an already-notified task
   is absorbed instead of enqueued again. A poll's own retirement state
   is scoped to one registration and cannot see a prior registration's
   outcome, so a task re-registered after its merge was already surfaced
   would otherwise wake main a second time for the same event.
   bin/fm-pr-lib.sh's new per-task pr-poll-merge-notified marker survives
   across re-registrations to catch that case; the first notification for
   a task still reaches main unchanged.

Regression tests colocated in tests/fm-startup-network.test.sh,
tests/fm-wake-queue.test.sh (including the mixed-queue no-swallow
property), tests/fm-pi-branch-extension.test.sh, and
tests/fm-pr-check-security.test.sh. docs/watcher-continuity.md and
docs/pi-supervision-branch.md updated for the new contracts.

* no-mistakes(review): Bind merge deduplication to canonical PR identity

* no-mistakes(review): Serialize wake row ownership across main and branch

* no-mistakes(review): Bind branch grants and deduplicate within actor claims

* no-mistakes(review): Fallback main-owned wake claims to main delivery

* no-mistakes(review): Clarify silent startup success guidance

* no-mistakes(review): Release residual branch grants after settled prompts

* no-mistakes(review): Reject truncated wake rows as corrupted

* no-mistakes(document): Document per-actor routing and silent startup success

* no-mistakes(lint): Fix ShellCheck findings in wake grant and startup test

* no-mistakes: apply CI fixes
Vinosaamaa added a commit to Vinosaamaa/firstmate that referenced this pull request Aug 25, 2026