Skip to content

feat(pi): add persistent multi-brain supervision branch - #13

Merged
verbagem merged 9 commits into
mainfrom
fm/firstmate-multibrain-green-recovery-6351
Aug 27, 2026
Merged

verbagem merged 9 commits into
mainfrom
fm/firstmate-multibrain-green-recovery-6351

Conversation

@verbagem

Copy link
Copy Markdown
Owner

Intent

Recover the fully built multi-brain Pi supervision feature from PR #9 (#9, branch fm/firstmate-pi-multibrain-fork-reconcile-5834) into a clean, current, no-mistakes-certified replacement PR against verbagem/firstmate:main. PR #9 was opened outside no-mistakes (expected provenance-check failure) and had one real CI failure: 'Behavior portable serial 4' was cancelled by GitHub Actions at the 15-minute job timeout on both its CI attempts, mid-script in an unrelated pre-existing test, not inside any hang. Root cause: the multi-brain feature's new tests roughly doubled the portable-serial lane's real total weight (measured 2,187,781ms across 120 scripts vs. the 1,143,762ms baseline the 4-shard/15-minute-timeout design was sized around, per docs/fm-test-portable-shards.md) without a matching shard-count increase, silently compressing the documented ~3x hang-tripwire margin to under 2x. Fix applied: raised PORTABLE_SERIAL_SHARDS 4->8 in bin/fm-test-run.sh, matched .github/workflows/ci.yml's matrix, corrected docs/fm-test-portable-shards.md's shard table and Timeouts section with real current numbers; verified via bin/fm-test-run.sh --check-coverage (serial_shards=8) and the same bin-packing algorithm CI runs (each of 8 shards balances to ~273s, restoring >3x margin under the unchanged 900s cap). Two additional correctness defects were found during review of the reconciled branch's outcome-delivery code (.pi/extensions/fm-branch-supervision.ts) and fixed with regression tests in tests/fm-pi-branch-extension.test.sh: (1) an outcome-cursor defect where the durable outcome store's single monotonic read cursor could silently bury an undelivered lower-sequence outcome when a later outcome was delivered and its cursor advanced past it - fixed by having mergeIntoMain redeliver every still-unread lower-seq row (in order) before advancing the cursor, preserving ordering and at-least-once delivery without a parallel store; (2) misleading merge-failure reporting where a note that sent successfully but then lost lock ownership before the cursor-advance step was reported to the calling agent as 'merge refused', which could prompt a false duplicate re-report - fixed by having mergeIntoMain return delivered/cursorAdvanced separately so only a truly-undelivered note is ever reported as refused. The task required reconstructing PR #9's exact 6-commit range (feat: add persistent Pi supervision branch kunchenguid#2858; style: distinguish routine and captain supervision merge notes by icon kunchenguid#2934; docs: add the approved multi-brain architecture poster kunchenguid#2938; feat(pi): default branch supervision and route heartbeats kunchenguid#2939; fix(pi-watch): restore confirm-before-send handling delivery, prereq of kunchenguid#2858; fix: bound recovery announcements and preserve supervision kunchenguid#2733) from the remote PR branch onto CURRENT verbagem/main (which had advanced 4 commits past PR #9's stale 3d8426c base) rather than PR #9's own base, explicitly excluding unrelated Kun Chen/kunchenguid upstream drift, and preserving every fork-specific change already on current main. This produced 3 real merge conflicts (tests/fm-pi-watch-extension.test.sh, .pi/extensions/fm-primary-pi-watch.ts, docs/watcher-continuity.md), each a genuine case of both current main and PR #9 independently adding different new tests/functions/paragraphs at the same anchor point; resolved by keeping BOTH sides' additions in full rather than picking one, verified by every downstream test exercising that code passing (fm-pi-watch-extension.test.sh 36/36, fm-pi-branch-extension.test.sh 15/15 incl. the 2 new tests, fm-branch-supervision.test.sh 14/14, strict Pi/pi-signed extension typecheck). kunchenguid/firstmate was read-only evidence throughout (fetched, never pushed to, never modified). The old worker's endpoint and its preserved active validation run/local copy at a separate worktree were left completely untouched per instruction - this is a fresh worktree and fresh branch. Do not merge this PR; leave PR #9 open for firstmate to retire after this replacement lands. The replacement PR body must link PR #9 as preserved/superseded evidence, explain the real CI root cause and both correctness fixes, and include complete final-head validation evidence - this commit message on b5d1675 already carries that full content and should be reused/adapted for the PR body. Disclosed, not silently omitted: fm-watch-arm.test.sh's one pre-existing failure and fm-pr-check-security.test.sh's local-machine-only timing flakiness both reproduce identically on an unmodified origin/main baseline in an isolated worktree - confirmed pre-existing, out of scope, not asserted as fixed.

What Changed

  • Adds persistent multi-brain Pi supervision branch support: a new .pi/extensions/fm-branch-supervision.ts extension plus lib/fm-branch-dispatch.ts, bin/fm-branch-prompt.sh, bin/fm-branch-outcome.sh, and a lease layer (bin/fm-lease.sh, bin/fm-lease-lib.sh); branch supervision becomes the default and heartbeats route through it, routine vs. captain merge notes are distinguished by icon, and fm-primary-pi-watch.ts, the watch/wake/send/spawn/teardown scripts, and the OpenCode watch-arm plugin are wired to the new path. Recovery announcements are now bounded so a recovery loop cannot preserve-then-spam supervision.
  • Fixes two outcome-delivery defects in fm-branch-supervision.ts: the durable outcome store's single monotonic read cursor could bury an undelivered lower-sequence outcome once a later one advanced the cursor — mergeIntoMain now redelivers every still-unread lower-seq row in order before advancing, and leaves the cursor unadvanced when redelivery is unproven; and it now returns delivered/cursorAdvanced separately so a note that sent but then lost lock ownership is no longer misreported to the calling agent as "merge refused".
  • Raises PORTABLE_SERIAL_SHARDS 4 → 8 in bin/fm-test-run.sh and matches the tests-portable-serial matrix in .github/workflows/ci.yml, because the new suites roughly doubled the lane's measured serial weight and had compressed the 15-minute job timeout's intended ~3x hang-tripwire margin to under 2x; docs/fm-test-portable-shards.md shard table and Timeouts section were corrected with the current measurements. New/expanded coverage lands in tests/fm-pi-branch-extension.test.sh, fm-branch-supervision.test.sh, fm-watch-recovery-loop.test.sh, fm-pi-branch-live-e2e.test.sh, and fm-pi-watch-extension.test.sh, alongside new docs (docs/pi-supervision-branch.md, architecture poster, configuration/scripts/supervision-protocol updates).

Risk Assessment

⚠️ Medium: Large new subsystem (5115 insertions: persistent branch session, durable outcome store, lease guards, recovery state machine) but every source-verifiable acceptance criterion checks out - both claimed correctness fixes are present and hold against the concrete failing sequences, the CI shard math reproduces byte-exactly, the conflict resolutions preserved both sides, and the new tests are behavioral regressions rather than source-content assertions.

Testing

I validated the intent's three claims directly rather than by suite pass counts. For the CI root cause I re-ran the runner's own bin-packing partitioner at both shard counts and summed each shard against the unchanged 900s job cap: the 4-shard config balances to 547s per shard (1.65x margin, matching the intent's "under 2x" compression) and the 8-shard config to ~273.4s (3.29x) — so the artifact demonstrates the hang-tripwire margin restored to over 3x, not a reproduced job cancellation, and it independently reproduces the doc's 2187781 ms total and its per-shard table exactly. I also confirmed the 8 shards partition the 120-script serial lane completely and disjointly, that ci.yml's matrix resolves to exactly those 8 lanes, and that a stale 4-shard lane is refused loudly. For the two correctness fixes I produced fail-before/pass-after across two separate parent states (reverting only the extension file, tests held at HEAD) and, more usefully, a transcript of what the captain's main session actually receives: before the fix a single note is delivered while the undelivered lower-sequence row's unread count silently drops to zero, after the fix both notes arrive in sequence order. The conflict resolution's "kept both sides" claim is backed by a superset check showing no test, function, or doc heading from current main was dropped (32 → 38 tests in the pi-watch suite), with that suite plus fm-branch-supervision and fm-pi-branch-extension all green. The disclosed fm-watch-arm failure did not reproduce at HEAD or on a clean fbcd994 baseline, so it is not caused by this change; fm-pr-check-security ran past a 10-minute local budget and is flagged as the one unverified disclosure. The worktree is clean — all revert experiments were restored and transient files removed.

Evidence: Portable-serial shard margin: 4 shards (1.65x) vs 8 shards (3.29x) against the 900s CI cap

Source: Portable-serial shard margin: 4 shards (1.65x) vs 8 shards (3.29x) against the 900s CI cap

== BEFORE: PORTABLE_SERIAL_SHARDS=4 (the config PR #9's CI ran) == shard scripts weight_ms weight_s margin 1/4 28 546952 547.0 1.65x 2/4 32 546943 546.9 1.65x 3/4 30 546950 547.0 1.65x 4/4 30 546936 546.9 1.65x == AFTER: PORTABLE_SERIAL_SHARDS=8 (this change) == 1/8 7 273925 273.9 3.29x 2/8 13 273422 273.4 3.29x 3/8 17 273405 273.4 3.29x 4/8 17 273413 273.4 3.29x 5/8 14 273396 273.4 3.29x 6/8 16 273406 273.4 3.29x 7/8 19 273413 273.4 3.29x 8/8 17 273401 273.4 3.29x

GitHub Actions job timeout for the portable-serial lane: 900s (900000 ms)
Weights are the runner's own measured per-script balance hints (bin/fm-test-run.sh).

== BEFORE: PORTABLE_SERIAL_SHARDS=4 (the config PR #9's CI ran) ==
shard     scripts    weight_ms   weight_s      margin
1/4            28       546952      547.0       1.65x
2/4            32       546943      546.9       1.65x
3/4            30       546950      547.0       1.65x
4/4            30       546936      546.9       1.65x

== AFTER: PORTABLE_SERIAL_SHARDS=8 (this change) ==
shard     scripts    weight_ms   weight_s      margin
1/8             7       273925      273.9       3.29x
2/8            13       273422      273.4       3.29x
3/8            17       273405      273.4       3.29x
4/8            17       273413      273.4       3.29x
5/8            14       273396      273.4       3.29x
6/8            16       273406      273.4       3.29x
7/8            19       273413      273.4       3.29x
8/8            17       273401      273.4       3.29x
Evidence: Merge notes actually delivered to the captain's main session, before vs after the outcome-cursor fix

Source: Merge notes actually delivered to the captain's main session, before vs after the outcome-cursor fix

BEFORE the fix (extension at 24aa62f): unread rows before the merge: 1 notes actually delivered into the main session: 1 [1] ⛵ task-fresh: opened PR #12, checks green still-unread rows after the merge: 0 <- the earlier row was buried, never delivered AFTER the fix (HEAD 31fb75f): unread rows before the merge: 1 notes actually delivered into the main session: 2 [1] ⛵ task-stale: rebased onto main, checks green [2] ⛵ task-fresh: opened PR #12, checks green still-unread rows after the merge: 0

### What the main (captain) session actually receives from the supervision branch
#
# Routine outcomes render as a dim note prefixed with the sailboat glyph.
# Captain-verdict outcomes are delivered as a turn-triggering follow-up with
# display:false (no glyph) - that is the behavior 3497541 established inside
# the recovered range, not something the fix commits changed. Verified by
# archaeology: MERGE_NOTE_ANCHOR is present at ce8c2ad and ff1ff49 and gone from
# 3497541 onward, so the single-glyph outcome predates b5d1675 and 31fb75f.
# Reviewers reading ce8c2ad's title ("distinguish ... by icon") should expect
# one glyph plus a turn-triggering follow-up, not two glyphs.


==================================================================
BEFORE the fix (extension at 24aa62f) - routine outcome
==================================================================
durable store before the next merge:
  {"seq":1,"epoch":1787693290,"task":"task-stale","wake":"","verdict":"routine","summary":"rebased onto main, checks green","silent":false}
unread rows: 1

notes actually delivered into the main session: 1
  [1] ⛵ task-fresh: opened PR #12, checks green

fm_branch_report told the branch agent:
  isError=false  "recorded seq 2 and merged [routine] into main"
still-unread rows after the merge: 0

==================================================================
AFTER the fix (HEAD 31fb75f) - routine outcome
==================================================================
durable store before the next merge:
  {"seq":1,"epoch":1787693291,"task":"task-stale","wake":"","verdict":"routine","summary":"rebased onto main, checks green","silent":false}
unread rows: 1

notes actually delivered into the main session: 2
  [1] ⛵ task-stale: rebased onto main, checks green
  [2] ⛵ task-fresh: opened PR #12, checks green

fm_branch_report told the branch agent:
  isError=false  "recorded seq 2 and merged [routine] into main"
still-unread rows after the merge: 0

==================================================================
AFTER the fix (HEAD) - captain-verdict outcome
==================================================================
durable store before the next merge:
  {"seq":1,"epoch":1787693292,"task":"task-stale","wake":"","verdict":"routine","summary":"rebased onto main, checks green","silent":false}
unread rows: 1

notes actually delivered into the main session: 2
  [1] ⛵ task-stale: rebased onto main, checks green
  [2] task-fresh: needs your call: force-push to a shared branch

fm_branch_report told the branch agent:
  isError=false  "recorded seq 2 and merged [captain] into main"
still-unread rows after the merge: 0
Evidence: Fail-before / pass-after across both fix commits' parents

Source: Fail-before / pass-after across both fix commits' parents

== BEFORE fix b5d1675 (extension restored from parent 24aa62f) == not ok - an undelivered lower-sequence outcome must be redelivered, not buried == BEFORE fix 31fb75f (extension restored from parent b5d1675) == ok - an earlier undelivered outcome is redelivered ahead of a later merged outcome ok - a delivered outcome whose read-cursor advance fails is reported as delivered, not refused not ok - a failed unread enumeration must leave the cursor untouched == AT HEAD (31fb75f) == 16/16 ok

### Fail-before / pass-after for the three outcome-delivery regressions
(only .pi/extensions/fm-branch-supervision.ts is reverted; the tests stay at HEAD)

== BEFORE fix b5d1675 (extension restored from its parent 24aa62f) ==
ok - branch owns accepted wakes with a stable prefix contract and verdict-driven merge delivery
not ok - an undelivered lower-sequence outcome must be redelivered, not buried: file:///Users/temp/.no-mistakes/worktrees/acee6d463bcf/01M0XBJJXHVQBP2YJKQT6RKESV/[eval1]:24
exit=1

== BEFORE fix 31fb75f (extension restored from its parent b5d1675) ==
ok - branch owns accepted wakes with a stable prefix contract and verdict-driven merge delivery
ok - an earlier undelivered outcome is redelivered ahead of a later merged outcome instead of buried
ok - a delivered outcome whose read-cursor advance fails is reported as delivered, not refused
not ok - a failed unread enumeration must leave the cursor untouched: file:///Users/temp/.no-mistakes/worktrees/acee6d463bcf/01M0XBJJXHVQBP2YJKQT6RKESV/[eval1]:28
exit=1

== AT HEAD (31fb75f) ==
ok - branch owns accepted wakes with a stable prefix contract and verdict-driven merge delivery
ok - an earlier undelivered outcome is redelivered ahead of a later merged outcome instead of buried
ok - a delivered outcome whose read-cursor advance fails is reported as delivered, not refused
ok - a merge whose stale-row enumeration fails delivers its note but never advances the cursor
ok - branch prompt_cache_key is stable per home across sessions and distinct between homes
ok - branch default-on eligibility (task-scoped, heartbeat, afk) binds and a broken branch falls back to main
ok - pre-drain eligibility re-check defers a newly main-owned row
ok - pre-drain eligibility re-check no-ops an already-drained wake
ok - dialog mirror filters tool and operational traffic, lands before wakes, and keeps a durable cursor
ok - branch session persists across process restarts through the recorded pointer
ok - replacement activation cleans old branch leases and retries failed cleanup
ok - branch activates on a cold start once the lock is acquired, never before
ok - queued wakes and mirrors stop mutating branch state after lock ownership is lost
ok - stale reports, shells, mirrors, cursors, leases, and prompts perform no side effects
ok - a Pi session that does not own the lock accepts nothing and mutates no branch state
ok - an extension rebind re-mirrors undelivered dialog instead of dropping it
exit=0

worktree clean after revert experiments:
  (empty above == clean)
Evidence: Isolated merge-refusal regression (test run alone)

Source: Isolated merge-refusal regression (test run alone)

### Isolated: the misleading 'merge refused' regression (test 3 alone)
The full-suite run above stops at the first failure, so this runs test 3 by itself.

== BEFORE fix b5d1675 (extension from parent 24aa62f) ==
not ok - a delivered note with a failed cursor advance must not be reported as refused: file:///Users/temp/.no-mistakes/worktrees/acee6d463bcf/01M0XBJJXHVQBP2YJKQT6RKESV/[eval1]:27

== AT HEAD ==
ok - a delivered outcome whose read-cursor advance fails is reported as delivered, not refused
Evidence: CI shard partition: complete, disjoint, matrix-consistent

Source: CI shard partition: complete, disjoint, matrix-consistent

ci.yml jobs.tests-portable-serial: matrix.shard=[1,2,3,4,5,6,7,8] timeout-minutes=15 full portable-serial lane scripts: 120 union over the CI matrix shards: 120 duplicates: 0 dropped by sharding: none RESULT: complete and disjoint - no test is dropped or run twice fm-test-run: lane 'portable-serial-1of4' asks for 4 portable serial shards but this runner is configured for 8 FM_TEST_COVERAGE ok total=156 parallel=24 serial=120 serial_shards=8 herdr=12

ci.yml jobs.tests-portable-serial: matrix.shard=[1, 2, 3, 4, 5, 6, 7, 8] timeout-minutes=15
every CI matrix shard id resolved to a lane the runner accepts: 8 lanes
full portable-serial lane scripts: 120
union over the CI matrix shards:   120  duplicates: 0
dropped by sharding: none
not in the lane:     none
RESULT: complete and disjoint - no test is dropped or run twice

-- runner refuses a CI matrix built for the old shard count --
fm-test-run: lane 'portable-serial-1of4' asks for 4 portable serial shards but this runner is configured for 8 (see --list-lanes)

-- coverage guard --
FM_TEST_COVERAGE ok total=156 parallel=24 serial=120 serial_shards=8 herdr=12
Evidence: Conflict resolution kept both sides (no test/function/heading lost)

Source: Conflict resolution kept both sides (no test/function/heading lost)

tests/fm-pi-watch-extension.test.sh - test function names base(fbcd994)=32 head=38 lost=0 .pi/extensions/fm-primary-pi-watch.ts - top-level functions base(fbcd994)=13 head=13 lost=0 docs/watcher-continuity.md - section headings base(fbcd994)=7 head=7 lost=0

### Conflict resolution kept BOTH sides: nothing that existed on current main was dropped
(comparing the base commit fbcd994 = current verbagem/main, against HEAD 31fb75f)

tests/fm-pi-watch-extension.test.sh - test function names
  base(fbcd994)=32  head=38  lost=0
.pi/extensions/fm-primary-pi-watch.ts - top-level functions
  base(fbcd994)=13  head=13  lost=0
docs/watcher-continuity.md - section headings
  base(fbcd994)=7  head=7  lost=0

-- lines removed from the three conflicted files across the whole range --
90	7	.pi/extensions/fm-primary-pi-watch.ts
8	1	docs/watcher-continuity.md
536	27	tests/fm-pi-watch-extension.test.sh

-- what those removals actually are --
  -          const restoration = await restoreAfterActionableClose(owner, predecessor);
  -          if (generationIsLive(owner)) owner.restoring = false;
  -          if (!generationIsLive(owner)) return;
  -          const message = restoration.failure ? `${classification.message}\n\n${restoration.failure}` : classification.message;
  -          await sendWake(owner, message, restoration.recovery);
  -        })().catch(() => {
  -        });
  -Every watcher close and every durable queue append publishes downtime, so a downtime republication of any pending episode reuses its generation instead of minting a new one.
  -      ? readFileSync(process.env.FM_ARM_LOG, "utf8").trim().split("\n").length
  -if (rows.length !== 2) throw new Error(`expected one successor arm, got ${rows.length}: ${rows.join(" | ")}`);
  -if (!/predecessor=[0-9]+/.test(rows[1])) throw new Error(`successor did not receive predecessor identity: ${rows[1]}`);
  -if (stableRows.length !== 2) throw new Error(`delivery was confirmed before the prompt succeeded: ${stableRows.join(" | ")}`);
  -releaseDelivery();
  -for (let i = 0; i < 100; i += 1) {
  -  if (readFileSync(process.env.FM_ARM_LOG, "utf8").includes("confirmed generation=fixture-generation")) break;
  -  await new Promise((resolve) => setTimeout(resolve, 10));
  -const confirmedRows = readFileSync(process.env.FM_ARM_LOG, "utf8").trim().split("\n");
  -if (confirmedRows.filter((row) => row.startsWith("confirmed ")).length !== 1) {
  -  throw new Error(`successful prompt delivery was not confirmed exactly once: ${confirmedRows.join(" | ")}`);
  -    return child && child !== previousChild && pidAlive(child);
  -  }, `${reason} replacement child`);
  -  return child !== sameInstanceChild && pidAlive(child);
  -}, "same-instance replacement child");
  -  expect_code 0 "$status" "Pi session transitions must rearm through an explicit generation owner"
  -        ? readFileSync(process.env.FM_ARM_LOG, "utf8").trim().split("\n").length
  -if (rows.length !== 2) throw new Error(`expected one successor arm, got ${rows.length}: ${rows.join(" | ")}`);
  -if (!/predecessor=[0-9]+/.test(rows[1])) throw new Error(`successor did not receive predecessor identity: ${rows[1]}`);
  -if (stableRows.length !== 2) throw new Error(`delivery was confirmed before the prompt succeeded: ${stableRows.join(" | ")}`);
  -releasePrompt();
  -for (let i = 0; i < 100; i += 1) {
  -  if (readFileSync(process.env.FM_ARM_LOG, "utf8").includes("confirmed generation=fixture-generation")) break;
  -  await new Promise((resolve) => setTimeout(resolve, 10));
  -const confirmedRows = readFileSync(process.env.FM_ARM_LOG, "utf8").trim().split("\n");
  -if (confirmedRows.filter((row) => row.startsWith("confirmed ")).length !== 1) {
  -  throw new Error(`successful prompt delivery was not confirmed exactly once: ${confirmedRows.join(" | ")}`);
- Evidence: [Multi-brain architecture poster rendered at its native 1200x860 viewBox](https://github.com/verbagem/firstmate/blob/ec8efdb4a387588c2a974b601ead3ad6a9f6c2ba/.no-mistakes/evidence/fm/firstmate-multibrain-green-recovery-6351/pi-supervision-branch-poster.png)
Evidence: Disclosed pre-existing failures vs an unmodified fbcd994 baseline

Source: Disclosed pre-existing failures vs an unmodified fbcd994 baseline

tests/fm-watch-arm.test.sh @ HEAD (31fb75f) exit=0 ok=14 not-ok=0 tests/fm-watch-arm.test.sh @ fbcd994 baseline exit=0 ok=14 not-ok=0 tests/fm-pr-check-security.test.sh @ HEAD exceeded a 10-minute local budget; not re-run on baseline

### Disclosed pre-existing failures - HEAD vs an unmodified fbcd994 baseline checkout
(baseline = `git archive fbcd994` extracted to a clean temp dir, nothing from this change)

tests/fm-watch-arm.test.sh @ HEAD (31fb75f)
  exit=0  ok=14  not-ok=0
tests/fm-watch-arm.test.sh @ fbcd994 baseline
  exit=0  ok=14  not-ok=0
  -> The failure the author disclosed as pre-existing did not reproduce on this
     machine at either revision. Either way this change does not cause it: the
     suite is green at HEAD, including the 33 lines this change adds to it and
     the reworked .opencode/plugins/fm-primary-watch-arm.js it exercises.

tests/fm-pr-check-security.test.sh @ HEAD
  exceeded a 10-minute local wall-clock budget and was stopped, so it was not
  re-run on the baseline. tests/fm-pr-check-security.test.sh itself is unchanged
  by this range (absent from the diffstat), and docs/fm-test-portable-shards.md
  records it as the single longest portable-serial script at 199573 ms. The
  author disclosed it as local-machine-only timing flakiness; remote CI owns it.
Evidence: tests/fm-branch-supervision.test.sh full log (14/14)

Source: tests/fm-branch-supervision.test.sh full log (14/14)

ok - branch prompt is byte-stable across homes, cwd, timezone, and time, above the cache floor
ok - outcome store is append-only and refuses sequence reuse after a torn tail
ok - startup replay skips silent outcomes and preserves visible and legacy rows
ok - lease exclusivity, same-actor refresh, release, staleness, and sweep hold
ok - fm-control and fm-teardown refuse the other actor's live lease and pass through otherwise
ok - PR merge, local landing, and new-task spawn refuse the branch actor and spare main
ok - a non-Pi home ignores stale Pi leases even when the recycled pid owns its lock
ok - lease liveness requires an exact valid session-lock pid
ok - concurrent stale-lease claims serialize so exactly one actor succeeds
ok - guard stale cleanup cannot race with or delete a newer lease claim
ok - lease guard excludes a concurrent actor for the complete mutation
ok - a claim naming the other actor fails loudly instead of silently impersonating it
ok - release commands authorize the caller and bulk release drops only that actor's leases
ok - the branch cannot force a teardown or bypass fm-control for a relaunch
Evidence: tests/fm-pi-watch-extension.test.sh full log (38/38)

Source: tests/fm-pi-watch-extension.test.sh full log (38/38)

ok - Pi extension reports external healthy watcher output
ok - Pi custom tool exposes repair-only metadata and returns automatic-continuation guidance
ok - Pi redundant tool call returns ownership guidance and spawns no second child
ok - Pi scheduled retry remains extension-owned after another tool call
ok - Pi actionable close starts one successor before wake delivery settles
ok - Pi empty rearm-resurface cycles stay silent while a successor remains owned
ok - Pi real signal, stale, check, heartbeat, queued recovery, open-decision, and unread-note reasons still deliver once
ok - Pi dispatcher branch offer owns accepted wakes and falls back to main
ok - Pi dispatcher flags a fleet-wide heartbeat offer as branch-eligible
ok - heartbeat with a main-owned queue row stays on main
ok - heartbeat restoration failure stays on main
ok - watcher-failure repair stays with main even with a live, accepting branch listener
ok - Pi refused handling handshake is classified and not swallowed
ok - Pi hung successor falls back to one typed actionable wake
ok - Pi unretired successor falls back without an overlapping retry
ok - Pi late unretired closes resume classified supervision
ok - Pi clean empty close triggers a bounded continuity retry
ok - Pi established clean closes stop at the configured retry limit
ok - Pi close handler verifies session-lock ownership before successor launch
ok - Pi watcher arm distinguishes all session lock ownership states
ok - Pi session transitions use a generation owner across /new /resume /fork, stale callbacks, and quit
ok - Pi process-exit cleanup listener remains singular across session replacement
ok - Pi process-exit cleanup stops the attached arm child
ok - OpenCode plugins have an explicit ESM boundary even under a typeless parent package
ok - OpenCode watcher plugin uses the effective FM_HOME state
ok - OpenCode watcher plugin sources the effective config
ok - OpenCode watcher plugin requires session lock ownership
ok - OpenCode watcher coordinator respects primary scope
ok - OpenCode watcher plugin starts one successor before wake prompt delivery settles
ok - OpenCode pre-ready actionable close preserves its successor
ok - OpenCode hung successor falls back to one typed actionable wake
ok - OpenCode unretired successor falls back without an overlapping retry
ok - OpenCode late unretired closes resume classified supervision
ok - OpenCode clean empty close triggers a bounded continuity retry
ok - OpenCode established clean closes stop at the configured retry limit
ok - OpenCode close handler verifies session-lock ownership before successor launch
ok - OpenCode watcher plugin coordinates with the turn-end guard
ok - OpenCode healthy arm output does not suppress the turn-end guard
- Outcome: ⚠️ 1 warning across 1 run (25m22s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

⚠️ **Review** - 2 infos
  • ⚠️ .pi/extensions/fm-branch-supervision.ts:399 - mergeIntoMain discards deliverStaleUnreadBelow's return value and advances the read cursor unconditionally, so the buried-outcome defect the commit claims to durably fix is still reachable. deliverStaleUnreadBelow returns 0 without delivering anything on two early exits (line 345: if (!unread.ok || !unread.stdout) return 0;) and silently skips any row it cannot JSON.parse or whose seq is not an integer (lines 350-356). mergeIntoMain ignores all of that and runs mark-read --through numericSeq at line 403 whenever seq is numeric, violating the invariant its own comment states at line 341 ("the cursor is only ever advanced over rows this call actually delivered"). Concrete failing sequence: seq 5 is durably appended but never delivered (a prior merge lost lock ownership after append, per the commit's own scenario); the branch then reports a new outcome, appended as seq 6; the unread invocation fails (spawnSync error, unreadable/missing state dir, or a non-zero exit from fm-branch-outcome.sh under set -eu) so runOutcomeScript returns ok:false; deliverStaleUnreadBelow returns 0 having delivered nothing; mergeIntoMain delivers only seq 6 and then advances the cursor to 6 — seq 5 is now marked read and will never be redelivered by a later merge or by startup-replay. Note also that the !unread.stdout branch cannot mean "nothing to redeliver" in practice: the row at numericSeq was just appended and sits above the cursor, so a healthy unread always emits at least that line — empty stdout likewise means enumeration is broken. Earliest supported boundary: have deliverStaleUnreadBelow signal enumeration failure (or incomplete redelivery) back to mergeIntoMain and return {delivered: true, cursorAdvanced: false} instead of calling mark-read. No call-site change is needed — the fm_branch_report handler at lines 466-476 already reports that state correctly as delivered-but-will-resurface.

🔧 Fix: keep outcome cursor unadvanced when redelivery unproven
2 infos still open:

  • ℹ️ bin/fm-test-run.sh:428 - The restored ~3x hang-tripwire margin is computed from weight hints, and the two heaviest new portable-serial suites carry none. Only tests/fm-watch-recovery-loop.test.sh got a measured hint (80000). tests/fm-pi-branch-extension.test.sh (1321 lines, ~18 node-driver tests) and tests/fm-branch-supervision.test.sh (548 lines) fall back to PORTABLE_SERIAL_DEFAULT_WEIGHT_MS=20000, and tests/fm-pi-branch-live-e2e.test.sh does too (its sibling fm-pi-primary-live-e2e is hinted at 19ms). I reproduced the documented partition exactly (shards 273925/273422/273405/273413/273396/273406/273413/273401 ms, total 2187781 ms, 120 scripts), so the arithmetic in docs/fm-test-portable-shards.md is correct - but the inputs for the newest scripts are estimates, which is the same class of under-estimation that compressed the margin in the first place. Doubling the shard count halves real per-shard load regardless of hint error, so this is a balance risk rather than a total-weight risk. Refresh the hints from the next fm-test-timing-portable-serial artifact per the procedure the doc already states.
  • ℹ️ .pi/extensions/fm-branch-supervision.ts:347 - deliverStaleUnreadBelow's new return shape carries maxDelivered, but the only caller (mergeIntoMain, line 404) reads just stale.ok - the cursor is advanced with String(numericSeq), never with maxDelivered. The field is therefore inert. It was explicitly requested in the fix instruction and documents the walk's progress for a future partial-advance policy, so leaving it is fine; noting it only so a later reader does not assume it feeds the cursor decision.
⚠️ **Test** - 1 warning
  • ⚠️ tests/fm-pr-check-security.test.sh - tests/fm-pr-check-security.test.sh exceeded a 10-minute local wall-clock budget and was stopped, so I could not compare it against the fbcd994 baseline. The test file itself is unchanged by this range and docs/fm-test-portable-shards.md records it as the longest portable-serial script (199573 ms), which is consistent with the author's disclosure of local-machine-only timing flakiness. Remote CI owns confirmation of this lane.
  • bash tests/fm-pi-branch-extension.test.sh — 16/16 at HEAD, including the three outcome-delivery regressions
  • Fail-before/pass-after: git checkout 24aa62f -- .pi/extensions/fm-branch-supervision.ts (tests-at-HEAD) → redelivery test fails; git checkout b5d1675 -- … → cursor-enumeration test fails; HEAD → all pass
  • Isolated run of test_cursor_advance_failure_is_not_reported_as_refusal at 24aa62f (fails) vs HEAD (passes)
  • Node driver over the test's real extension fixture capturing sentToMain note contents for a stale-then-fresh routine merge and a captain-verdict merge, before vs after the fix
  • bin/fm-test-run.sh --list --lane portable-serial-{1..8}of8 weight-summed against the 900s cap, vs the same runner with PORTABLE_SERIAL_SHARDS=4 over portable-serial-{1..4}of4
  • Semantic parse of .github/workflows/ci.yml jobs.tests-portable-serial (matrix.shard, timeout-minutes) plus set-equality of the 8 shards' union against --list --lane portable-serial (120 scripts, 0 duplicates, 0 drops)
  • bin/fm-test-run.sh --list --lane portable-serial-1of4 → runner refuses a matrix built for the old shard count
  • bin/fm-test-run.sh --check-coverage → serial_shards=8
  • Cross-checked docs/fm-test-portable-shards.md's shard table, imbalance, total weight, and Timeouts section against the computed ground truth
  • bash tests/fm-branch-supervision.test.sh — 14/14
  • bash tests/fm-pi-watch-extension.test.sh — 38/38 (conflict-resolution proof)
  • Superset check of the three conflicted files: test-function names, top-level functions, and doc headings at fbcd994 vs 31fb75f (0 lost)
  • bash tests/fm-watch-arm.test.sh at HEAD and on a clean git archive fbcd994 baseline checkout — 14/14 both
  • Rendered docs/pi-supervision-branch-poster.svg to PNG via headless Chrome at its 1200x860 viewBox
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

kunchenguid and others added 9 commits August 25, 2026 12:10
* wip: forked supervision on Pi (checkpoint before docs)

* fix(pi-branch): harden mirror delivery, fallback encoding, and session replacement

Peek-then-shift mirror flush so a failed append retries instead of dropping;
durable mirror cursor commits only after delivery into the branch;
the main fallback wake is operational-encoded like every watcher injection;
session_shutdown quiesces the generation and session_start re-arms, so /new
and /resume no longer kill the branch permanently. Registers the extension in
the strict typecheck, adds the dispatch handshake test, the branch extension
suite, the bash-level regression suite, the session-start replay test, and
the opt-in real-SDK live guard.

* test(fixtures): carry the branch-dispatch lib and lease lib into isolated fixtures

The watcher extension now imports lib/fm-branch-dispatch.ts and fm-teardown
sources fm-lease-lib.sh, so every fixture that copies or symlinks those
files in isolation gains the new sibling.

* no-mistakes(review): Prevent shutdown wake loss and serialize lease claims

* no-mistakes(review): Durably hand off wakes and retain portable leases

* no-mistakes(review): Require durable reports and clear disposed branch leases

* no-mistakes(review): Enforce per-wake outcomes and quiescent lease cleanup

* no-mistakes(review): Require wake acknowledgements and tighten branch lifecycle boundaries

* no-mistakes(review): Require complete acknowledgements and replay cleanup failures

* no-mistakes(review): Bind supervision to lock ownership and durable delivery

* no-mistakes(review): Activate branch lazily after session lock acquisition

* no-mistakes(review): Preserve undelivered mirror context across extension rebinds

* no-mistakes(review): Acknowledge startup replay only after main delivery

* no-mistakes(review): Isolate replay metadata from untrusted digest content

* no-mistakes(review): Reject duplicate reports for active wake sequences

* no-mistakes(review): Retain failed fallbacks and deduplicate outcome replay

* no-mistakes(review): Deduplicate durable outcomes and cache delivery receipts

* no-mistakes(review): Anchor wake sequence matching to outcome fields

* no-mistakes(document): Clarify Pi supervision durability contracts

* no-mistakes(lint): Fix ShellCheck issues in branch supervision scripts

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* refactor(pi-branch): collapse to confused-agent-grade guards per captain decision

Captain decision A: the lease/actor guards target the CONFUSED-AGENT threat
model bin/fm-gate-refuse-lib.sh already documents; adversarial-grade
separation is impossible in the shared-process design and is filed as
separate follow-up work. Rip out the machinery that chased it: the
generation fence and shell-provenance markers, the wrapper-tagged ancestry
walks, guard auto-claim with per-script release traps, the pending-wake
files and ack-receipt correlation (the durable wake queue already
re-presents anything unacknowledged), the delivery-receipt store with
contiguous cursor advancement, the session-start replay-metadata channel,
and the branch tool quiescence counters.

Keep the behaviors the board requires, each on its simplest implementation:
lazy per-action session-lock ownership (cold start activates after the lock
lands; a secondary session stays inert), mirror durability across extension
rebinds via the durable cursor, replay-exactly-once from the one read
cursor, the awaited operational-encoded fallback, per-generation stray-lease
cleanup, session-lock-bound lease liveness (a recycled pid or a non-Pi home
never honors a leftover lease), the loud accidental-override guards
(readonly actor prelude, cross-actor claim refusal), and the role-partition
refinements (no forced teardown, no direct relaunch for the branch).
Default-on-for-Pi is unchanged.

* no-mistakes(review): Enforce lock ownership and serialize lease mutations

* no-mistakes(review): Synchronize guard cleanup and bind leases to lock owner

* no-mistakes(review): Report outcomes before acknowledging durable wakes

* no-mistakes(review): Restrict leases to Pi and instruct main claims

* no-mistakes(review): Reject malformed lease locks and torn outcome tails

* no-mistakes(review): Validate complete outcome tails before appending

* no-mistakes(review): Guard branch side effects across session replacements

* no-mistakes(document): Update Pi supervision durability and lease documentation

* no-mistakes(lint): Suppress intentional nested-shell expansion warning

* no-mistakes: apply CI fixes

* fix(pi-branch): authorize lease releases by caller

* fix(lint): break redundant source-analysis path in fm-lease-lib.sh

fm-lease-lib.sh's lazy fallback source of fm-wake-lib.sh gave ShellCheck's
--external-sources traversal a second path into an already 1540-line file
that fm-send.sh and fm-teardown.sh also source directly, blowing up the
recursive analysis past CI's lint timeout. Mark it a source=/dev/null
analysis boundary, matching the existing fm-task-inbox-lib.sh convention.

Also restores bin/fm-lint.sh and tests/fm-lint.test.sh to the shared
serial-lint definition (dropping an unrelated parallel-sharding change
that was itself hanging and masked this root cause).

* no-mistakes(document): Correct lease caller-authorization documentation

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

(cherry picked from commit 7b88520)
… icon (kunchenguid#2934)

* style(pi): restyle supervision merge notes with a sailboat and matching pad

Secondary-session notes were flush against the TUI edge and fully tinted.
Use the sailboat prefix, Pi's default outputPad, boat-only color, and dim remainder so they sit like real messages.

* style(pi): distinguish routine and captain merge notes by icon only

Visible notes now lead with a sailboat or anchor, then only the dim outcome.
Drop the branch-merged wording and verdict brackets so the icon is the only kind signal.

(cherry picked from commit 52ff62e)
…id#2938)

The markdown contract stays the owner; the still is only the visual of the idea.

(cherry picked from commit d55e00a)
kunchenguid#2858)

Cherry-picking 7b88520/8fa0505 alone silently dropped their prerequisite
content: confirmHandlingDelivery()/WithRetry() and the owner.restoring
re-entrancy guard were introduced by 3f03533 (fix: bound recovery
announcements and preserve supervision, kunchenguid#2733), which landed on
kunchenguid/firstmate main before 7b88520 and was therefore absent from
each later commit's own diff. tsc caught the missing confirmHandlingDelivery
reference; manually reconstructed to match origin/main's current file
(now byte-identical for .pi/extensions/fm-primary-pi-watch.ts).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016KZ15GDC21fsLKVtsXnkLJ
…id#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

(cherry picked from commit 3f03533)
Corrections found during PR #9's recovery onto current main:

- Fix the real CI failure. The multi-brain feature roughly doubled the
  portable-serial lane's total weight (2.19M ms vs the 1.14M ms baseline
  the sharding was designed around) without a matching shard-count
  increase, silently compressing the CI job timeout's intended ~3x
  hang-tripwire margin to under 2x. "Behavior portable serial 4" was
  cancelled at almost exactly the 15-minute job boundary on both PR #9
  CI attempts, mid-script, not inside any single hanging test - a margin
  failure, not a hang. Raise PORTABLE_SERIAL_SHARDS 4 -> 8, restoring
  each shard to ~273s (comfortably >3x under the unchanged 900s cap);
  docs/fm-test-portable-shards.md and the CI workflow comment carry the
  corrected numbers.

- Fix the outcome-cursor defect. bin/fm-branch-outcome.sh's read cursor
  is one monotonic sequence number, not a per-row acknowledgement, so a
  bare "mark-read --through N" could silently bury a lower-seq row still
  unread (a prior merge that lost lock ownership after appending but
  before sending, or after sending but before the cursor advanced).
  mergeIntoMain now redelivers every such stale row, in order, before
  delivering its own outcome and only then advances the cursor past
  everything it actually delivered.

- Fix misleading merge-failure reporting. A merge that sent its note but
  then lost lock ownership before the cursor advance used to report
  "merge refused" to the calling agent - false, since the note had
  already reached main - which could prompt a duplicate re-report.
  mergeIntoMain now returns delivered/cursorAdvanced separately so the
  fm_branch_report tool only ever reports true refusal when nothing was
  sent.

Regression coverage: two new tests in tests/fm-pi-branch-extension.test.sh
(stale-unread redelivery, cursor-advance-failure reporting).

Preserves PR #9's 6 cherry-picked commits (persistent Pi supervision
branch, its follow-up fixes, docs, and tests) reconstructed onto current
verbagem/main rather than the stale 3d8426c base, with the tests/fm-pi-
watch-extension.test.sh and .pi/extensions/fm-primary-pi-watch.ts merge
conflicts resolved by keeping both sides' independently-added tests and
functions rather than picking one.

Verified: strict Pi extension typecheck, fm-pi-branch-extension.test.sh
(15/15 incl. new), fm-branch-supervision.test.sh (14/14),
fm-pi-watch-extension.test.sh (36/36), fm-test-run.test.sh (portable
shard coverage/partition), fm-shared-captain-inheritance.test.sh,
fm-calm-pi-extension.test.sh, fm-watcher-lock.test.sh,
fm-session-start.test.sh, fm-spawn-*.test.sh, fm-send-*.test.sh,
fm-control-relaunch.test.sh, fm-wake-queue.test.sh, shellcheck + actionlint.

Superseded: #9
@verbagem
verbagem merged commit 66d6024 into main Aug 27, 2026
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants