Repository navigation
fix(bin): collapse duplicate branch-outcome re-mints into their one recorded event - #6850
ardydedase wants to merge 6 commits into
Conversation
The supervision branch model could call fm_branch_report up to five or six times for one wake handling with identical arguments, minting a duplicate outcome row seconds apart for each re-call: every duplicate captain verdict opened its own captain turn, every duplicate routine row re-rendered a fleet note on the primary. Make the outcome store the idempotence point. fm-branch-outcome append now collapses a re-mint of an event it already recorded into that existing record, under a conjunctive structural identity - task, verdict, wake text, claimed handling token, silence class, summary text, and captured status provenance - against the still-unprocessed portion of the store, with the duplicate window kept only as the residual bound for token-less reports. A collapsed append writes nothing, prints the existing record's seq as its strict stdout contract, notes the collapse on stderr, and never touches read or acknowledged state. The guard fails open. The extension report tool now passes the wake's claimed rows as the handling token, so one handling's re-mint flurry collapses while a newly claimed wake row is a fresh handling that records; a collapsed call prints the truthful collapse message instead of a false recorded line, so a retrying model sees the event already has its one record and settles. The host report wrapper re-prints the collapse note and never queues a second relay wake for the duplicate, and its away path skips the duplicate relay row. Doc owners updated to the final identity semantics; regression tests added in both colocated suites.
…d remints, validate handling, add host tests
|
Speaking as Kun's firstmate (the triage agent for this repo, not Kun personally). Thanks @ardydedase. This is a careful piece of work: the dedup fails open, the stdout contract is kept, and regression tests cover the store, the host, and the extension. CI: this fork's runs were waiting for approval. I reviewed the diff (no workflow, network, or credential surface) and approved runs Triage verdict (my own reading of the tip vs
Status: waiting-ci. Once CI and no-mistakes are green and it's still mergeable, this goes to the captain as a new-default merge-or-leave decision, because it reverses a by-design choice. Nothing is needed from you unless CI comes back red. |
Intent
Fix the supervision branch duplicate-outcome minting bug: one fleet event (one wake, one handling, identical re-calls of the fm_branch_report tool by the branch model up to several times in one prompt) currently mints MULTIPLE identical outcome records seconds apart in state/branch-outcomes.jsonl, each duplicate captain verdict opening its own captain-facing turn and each duplicate routine row re-rendering a fleet note on the primary. Root cause: the model re-issues identical report tool calls; fixes live at the append seam. Acceptance criteria: exactly one outcome record per (task, event identity, verdict class) - a re-mint collapses into the existing record; never suppress unacked records; structural event identity (task, verdict, wake text, claimed handling token, silence class, captured status provenance) with summary text as a narrowing conjunction term, never a sufficient key on its own; the collapse base is the still-unprocessed portion so a fully acknowledged predecessor never swallows its repeat; the duplicate window (default 120s, FM_OUTCOME_DUPLICATE_WINDOW) stays as the residual bound only for token-less reports; the collapsed append keeps its strict stdout contract (existing seq) with the collapse note on stderr; host and extension callers remain truthful about collapses; the guard fails open; regression tests colocated in tests/ (store-level, host-level, extension-level); shellcheck-clean bin scripts; owner docs updated. The fix is in the firstmate repo, branch ardy/fm-branch-outcome-duplicate-bursts.
What Changed
bin/fm-branch-outcome.sh: a re-report whose structural identity (task, verdict, wake text, claimed handling token, silence class, captured status provenance, with summary text as a narrowing AND-term) matches a still-unprocessed record collapses into it, printing the existing seq on stdout with aduplicate:note on stderr; the 120s window (FM_OUTCOME_DUPLICATE_WINDOW) now bounds only token-less reports, acknowledged predecessors never swallow repeats, and the guard fails open to a normal append.bin/fm-branch-report.shpasses the turn's claimed wake rows as the handling token, skips writing a duplicate per-turn receipt or relay wake, and names the collapse (never a fresh record) in stdout; the Pi branch extension (.pi/extensions/fm-branch-supervision.ts) carries the eligible-row claim token intofm_branch_reportappends and tells the model when a duplicate re-mint folded into the existing record.docs/pi-supervision-branch.md,docs/supervision-host.md) for the new dedup contract, and added store-level, host-level, and extension-level regression tests intests/.Risk Assessment
✅ Low: The dedup is bounded to the append seam, fails open on every malformed input, preserves the strict stdout contract with the collapse note on stderr, is covered by behavior-level regression tests at the store, host, and extension levels with aligned owner docs and a clean shellcheck; the only new finding is a narrow concurrency corner whose failure mode is loud and no worse than the pre-fix behavior it replaced.
Testing
Exercised the duplicate-outcome re-mint fix at all three required levels (store, host, extension) plus a live CLI end-to-end run of the reported branch-report burst scenario; every change-targeted test passes at head and fails at base for the right reason, the end-to-end transcript shows exactly one record/receipt/relay per burst with truthful collapse wording, and the only failures encountered (branch-supervision tail test, host live-loop tests, node <22.18 extension loading) all reproduce identically at the base commit and are unrelated to this change.Evidence: End-to-end CLI transcript: three identical fm-branch-report calls in one host turn collapse into one store row, one receipt, one relay wake
Source: End-to-end CLI transcript: three identical fm-branch-report calls in one host turn collapse into one store row, one receipt, one relay wake
$ fm-branch-report.sh --task alpha --verdict routine --summary "worker healthy" (call #1, one host turn) stdout: recorded seq 1 [routine]; the captain has returned, so it is queued for MAIN to relay $ ... (call #2) stdout: duplicate re-mint collapsed into the existing seq 1; its relay wake was already queued, so none is queued twice stderr: duplicate: outcome re-mint for task alpha collapsed into the existing seq 1 $ ... (call #3) stdout: duplicate re-mint collapsed into the existing seq 1; its relay wake was already queued, so none is queued twice --- state after the three-call burst --- store: exactly one row {"seq":1,...,"handling":"4451"} per-turn receipts: exactly one line 't1\t1\troutine\talpha' relay wake count: 1 $ fm-branch-outcome.sh lookup --seqs "1" -> returns the seq 1 row (close-side lookup stays healthy)Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
bin/fm-branch-report.sh:152- A collapsed duplicate report still writes a second receipt line with the same seq, but bin/fm-supervision-host.sh builds lookup requests by joining receipt seqs verbatim (returned_during_turn at line 615-621, awk joins all matching lines -> "3,3"), and fm-branch-outcome.shlookup --seqsrejects duplicate seqs (unique check, exit 2). Concrete path: away turn, captain returns mid-turn, branch model re-issues an identical fm-branch-report call -> first call stores seq 5 and writes receipt (turn,5,...), second call collapses (duplicate: on stderr), writes a second receipt (turn,5,...); at close, returned_during_turn gets TURN_RECEIPT_SEQS="5,5", lookup fails, RETURNED_LOOKUP_FAILED=1, so the handback degrades from relaying the outcome lines to "the recorded outcomes could not be verified...main must review" in both the HANDLE_RC==0 and HANDLE_RC!=0 paths (lines 1154-1170). turn_captain_seqs (line 1024) also prints "store rows 5, 5". Before this change two identical reports minted distinct seqs so receipts never repeated. Fix at the host consumers: dedupe the seq list in returned_during_turn and turn_captain_seqs (the report-script header intentionally keeps the duplicate receipt).bin/fm-branch-outcome.sh:407- The intent states the duplicate window (120s, FM_OUTCOME_DUPLICATE_WINDOW) "stays as the residual bound only for token-less reports", but duplicate_outcome_seq applies.epoch >= $cutoffas a hard conjunct for every candidate, including ones carrying a non-empty handling token. Since one claimed handling token is one fleet event (per the same header contract), a re-mint of that event arriving more than 120s into the same branch prompt (long thinking turns or tool-call interludes are common; the safety of the collapse is otherwise bounded by the processed marker, so the window is redundant here) records a second outcome row for one (task, event identity, verdict class) - exactly the duplicate-minting bug at longer latency. The store-level test never covers a token-carrying re-mint past the window (the '4451' handling collapse happens seconds after the first record). Either drop the window term for candidates with a non-empty handling token (window then bounds only the token-less residual, as the criterion says) or confirm the 120s cap on one handling's re-mints is the deliberate author boundary.bin/fm-branch-outcome.sh:637- append takes --handling as free text (line 637) and writes it escaped into the store (line 682), but the row validator (line 309) requires handling to have no tab/newline and be <= 512 codepoints. json_escape encodes a tab/newline into valid JSON \t/\n escapes that decode back to literal characters, so an append with a tab, newline, or >512-char handling value succeeds and the next last_seq run fails closed - every subsequent read/append/mark of the store fails ("malformed store") until a captain-approved manual repair. The extension (comma-joined numbers) and host (turn_record rows field) currently produce safe tokens, but the append seam is the one shared boundary that must not be able to brick the store. Validate --handling at the append seam the same way the reader does (reject, or normalize per the guard's fail-open policy).bin/fm-branch-report.sh:172- The intent requires "regression tests colocated in tests/ (store-level, host-level, extension-level)", but the change adds only store-level tests (tests/fm-branch-supervision.test.sh appends via bin/fm-branch-outcome.sh directly) and extension-level tests (tests/fm-pi-branch-extension.test.sh drives the real fm_branch_report tool). Nothing exercises the host report surface's new collapse behavior: the duplicate --handling turn token derivation, the stdout/stderr split contract, the second receipt write, and the relay-wake skip (bin/fm-branch-report.sh lines 143-176). That path is exactly where the reachable host degradation (duplicate-receipt lookup failure in finding 1) and the "already queued" truthfulness edge live untested.bin/fm-branch-report.sh:172- The duplicate-collapse relay skip prints "its relay wake was already queued, so none is queued twice", but when the first report's fm_wake_append failed (that path prints "could not be queued" and exits 0, leaving the record stored unrelayed), the collapsed duplicate repeats the false claim instead of retrying the idempotently-keyed supervision-host-return:<seq> wake. The record still reaches main through the drain, so this is a truthfulness edge against the "callers remain truthful about collapses" criterion, not a data-loss path.bin/fm-branch-outcome.sh:412- The.seq > $processedcollapse base makes routine rows at a seq below an acknowledged captain row permanently ineligible to absorb their own re-mints (the processed marker only tracks captain acknowledgements), so a re-mint burst straddling a captain-row acknowledgement can still mint a second routine record for that identity, inside the window and unread or not. Narrow interleaving, failure direction is over-recording rather than suppression, and the window bounds it; noting for the record as a deviation from "exactly one outcome record per (task, event identity, verdict class)" in that corner.🔧 Fix: Skip duplicate receipts, waive window for tokened remints, validate handling, add host tests
1 warning still open:
bin/fm-branch-outcome.sh:32- The header - declared at line 7 to be the one owner of the store's format - still opens the 'Re-mint dedup' contract with "the original row still unprocessed and still within OUTCOME_DUPLICATE_WINDOW_SECONDS (default 120, overridable through FM_OUTCOME_DUPLICATE_WINDOW for tests) - into that existing record", stating the window is a hard condition of every collapse. The fix round changed duplicate_outcome_seq (line 417) to waive that conjunct for token-carrying re-mints, and the same header paragraph was already updated later ("keeps collapsing ... for the whole life of that record's unprocessed span ... The window bounds only the token-less residual"), so the contract now contradicts both the code and itself within one contract block. The user's fix instruction explicitly included 'keep the store header contract aligned with the window semantics change'; this sentence was missed. A consumer or future implementer reading the first condition would treat a post-120s tokened collapse as a store bug. Mechanical fix: qualify the first sentence the way duplicate_outcome_seq's own comment and the window-constant comment already do (e.g. '... still unprocessed and - for a re-mint carrying no handling token - still within OUTCOME_DUPLICATE_WINDOW_SECONDS ...').🔧 Fix: Align store dedup header with tokened-window waiver
2 issues (1 warning, 1 info) still open:
bin/fm-branch-report.sh:188- The intent requires "host and extension callers remain truthful about collapses," and the away-captain-returned path (line 172-173) names its collapse - but the three other exits still print a flat "recorded seq %s ..." for an append that collapsed and stored nothing: the silent path (line 162, "recorded seq N [routine]; silent outcome remains..."), the attended path (lines 165-170), and the away-window path (line 188, "recorded seq N [v]; it waits in the outcome store for MAIN"). Line 188 is the primary host burst context: during a genuine away turn (fm_afk_contract_away_present true) a branch model re-issuing an identical fm-branch-report call collapses in the store and then reads on stdout that it just recorded seq N - the exact opposite of the truthfulness criterion, and inconsistent with the away-returned branch added by the fix round. The store data stays correct (stderr carries the duplicate: note, which the script forwards), and the fix-round host test only exercises the away-returned wording, so this gap is untested. Mirror the away-returned duplicate branch in the silent, attended, and away-window exits (e.g. "duplicate re-mint collapsed into the existing seq N; ..."), leaving the messages of non-duplicate reports untouched so existing tests stay valid.bin/fm-branch-outcome.sh:420- Concrete residual within the author's own identity boundary, for the record: the event identity includes the captured status provenance (.statusEndpoint == $endpoint and .statusIdent == $ident), so a burst where the task's status log grows between two identical token-carrying re-calls (worker appends mid-prompt - exactly what a wake means is in flight) mints a second record for one handling, and for a captain verdict that opens the second captain-facing turn - the original harm. This is deliberate author semantics, not a defect: the intent names "captured status provenance" as part of structural identity and tests/fm-branch-supervision.test.sh ("the status log growing is a new event the same instant") asserts it records. Noted so the acknowledged boundary is explicit; no change requested.🔧 Fix: Name collapse, not record, in all report exits
3 issues (1 warning, 2 infos) still open:
bin/fm-branch-outcome.sh:15- The header - self-declared the one owner of the store's format - documentshandlingas 'comma-separated seqs from the Pi branch's eligible-row snapshot or the supervision host's turn record', but the host's turn record writes rows space-joined (bin/fm-branch-dispatch.mjs:68join(" "), published verbatim into the turn record by bin/fm-supervision-host.sh:905), and fm-branch-report.sh passes that field unchanged as --handling. So host-derived tokens are space-separated ('4451 4452') while Pi-extension tokens are comma-separated ('4451,4452', fm-branch-supervision.ts:1585). Dedup itself is unaffected (each surface is internally consistent, and grants prevent one claimed row being re-claimed across surfaces), but the contract text mis-states the field's grammar for an entire reporting surface; any consumer trusting 'comma-separated' would mis-split host tokens. Mechanical fix: correct the header wording (or unify to one separator).bin/fm-branch-report.sh:148- Before this change a successful store append's stderr passed straight through to the branch shell, so the store's 'warning: outcome N was stored but its display tail copy could not be refreshed' diagnostic (the tail copy is the display source for size-limited readers) was visible. Now stderr is captured to a temp file and only '^duplicate:' lines are replayed, so that warning is silently dropped. The intent's required contract (collapse note on stderr) is preserved; forward the non-duplicate stderr lines as well to restore the diagnostic.bin/fm-branch-outcome.sh:671- Residual corner introduced by the 512-codepoint append refusal (explicitly authorized for caller-supplied tokens): the host and extension both derive the handling token from real turn state (turn_field rows/ eligibleSeqs join) with no upstream bound, and the wake queue is scanned without a claimed-row cap, so a turn claiming roughly 85+ rows (e.g. after long watcher downtime) derives a token over 512 codepoints and every report of that turn is refused with exit 2 - the turn can record nothing and is handed to main. It fails loud (no suppression, no store damage) and requires an unusual queue accumulation, so this is recorded for the record rather than requested as a change; an earliest fix would clip or hash the derived token at the dispatch boundary if that corner ever materializes.🔧 Fix: Fix host token grammar in header, forward store stderr
1 info still open:
bin/fm-branch-report.sh:151- The round-3 skip logic (lines 151-155) checks the receipts file for an existing (turn, seq) line outside any lock, then appends - so two identical fm-branch-report invocations running concurrently in one host turn (parallel Bash tool calls by the branch model; both share FM_BRANCH_REPORT_TURN) whose store appends serialize correctly (first appends seq N, second collapses into N) can each pass the receipts check before either writes, leaving two identicalturn\tNreceipt lines. The store data stays correct, but the host's returned_during_turn then joins the seq asN,Nand lookup --seqs fails itslength == (unique | length)close, degrading the return handoff to the loud "outcomes could not be verified; main must review them" path. Failure direction is loud and strictly narrower than the same interleaving before this change (which minted two store rows), the observed bursts are sequential, and the report script's store append already holds the outcome lock that a full fix would need to span the receipt seam - so noting the residual rather than requesting a cross-file lock redesign.tests/fm-branch-supervision.test.sh:1816- The store-level test file fails at test_away_branch_spawn_requires_queued_dispatchable_work (fm-spawn/backlog gate refuses a queued task it should dispatch). Reproduced identically at base commit b062eb9 in a /tmp extraction of the base tree, so it is pre-existing and unrelated to the duplicate-outcome change; all change-targeted tests in this file pass. Remote CI owns confirming or fixing it.tests/fm-supervision-test-file-aborts-at-first-test- The full tests/fm-supervision-host.test.sh file aborts at its first invoked test (test_claude_stop_hook_restores_handoff_when_successor_closed_before_exit_to_main) in this environment; several surrounding live-loop tests (attended_captain, large_turn, return_during, lookup-failure) fail the same way. Every one was reproduced identically at the base commit, so none is introduced by this change. I ran the change-targeted host tests by isolated invocation instead.tests/fm-pi-branch-extension.test.sh- The extension tests import .pi/extensions/*.ts directly, which requires node with native type-stripping (>==22.18). This machine's default node is v18.20.8 and every test dies with ERR_UNKNOWN_FILE_EXTENSION. Fixed locally by putting node v22.23.1 first on PATH; remote CI should already provide a suitable node, but local runners need this.bash tests/fm-branch-supervision.test.sh - full store-level file: all 4 new dedup tests pass (collapse into one record, separate-events separation incl. window override, token-less-only window, poisoning handling refusal with exit 2 and untouched store); tail failure test_away_branch_spawn_requires_queued_dispatchable_work reproduced identically at base (git archive of b062eb9 run in /tmp/remint-base)targeted host-level invocation of tests/fm-supervision-host.test.sh subset: test_report_collapse_keeps_one_record_receipt_and_relay, test_report_collapse_wording_stays_truthful_in_every_exit, test_report_forwards_non_duplicate_store_diagnostics, test_report_surface_enforces_actor_turn_and_scope, test_report_after_the_return_is_queued_for_main, test_branch_outcomes_collapse_repeated_captain_outcomes_per_task - all pass at headbase-commit comparison of the host subset via /tmp/remint-base extraction: test_report_collapse_keeps_one_record_receipt_and_relay fails at base with 'the report must carry the turn's claimed rows as its handling token', confirming the new tests are genuine regression testsPATH=node-v22.23.1 isolated run of tests/fm-pi-branch-extension.test.sh subset: test_branch_report_refuses_a_task_the_wake_did_not_name and test_branch_report_collapses_a_duplicate_remint_into_the_one_recorded_outcome - both pass at head (one stored row, exactly one captain entry, no unread residue)base-commit comparison of the extension subset: the new test fails at base with 'the duplicate re-mint call did not name its collapse' (two store rows, two captain entries), proving it reproduces the reported failure before the fixmanual end-to-end demo driving bin/fm-branch-report.sh: three identical calls inside one host turn -> one store row, one per-turn receipt line, exactly one supervision-host-return relay wake, 'duplicate re-mint collapsed into the existing seq 1' stdout plus 'duplicate:' stderr note, and fm-branch-outcome.sh lookup --seqs succeeds on the per-turn receipt seqs (transcript saved as evidence)manual guard fail-open checks: FM_OUTCOME_DUPLICATE_WINDOW=abc and chmod-000 .branch-outcomes-processed both fall open to normal appends (new records minted, exit 0)✅ **Document** - passed
✅ No issues found.
✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.