Repository navigation
fix(bin): mirror remote secondmate status streams - #1846
Merged
Merged
Conversation
A remote secondmate's reply channel required corr=<16hex> on every line and failed the entire delta when one line lacked it, so the cursor could never advance past that line and the channel wedged permanently. The charter tells a secondmate to report its own progress phases and to raise new decisions with no correlation token, because correlation only answers a marked parent request. Those lines were therefore unrepresentable on the remote channel, while a local secondmate writes them straight into the parent's status file. Treat the channel as what it is: a mirror of the mate's status stream. A remote mate now presents the same status and decision model as a local one, so a newly raised needs-decision reaches the parent's open-decision fold identically, and correlation goes back to being a per-line property that settles a pending request rather than a gate on the stream. Only what crossing a machine boundary genuinely adds stays behind: cursor continuity, confined document fetch and rewrite, at-most-once append, and control-byte normalization that rewrites bytes without ever dropping a line. Line framing and size bounding already belong to fm-remote-delta-read.sh. A document the remote reader refuses is named in one escalation instead of stalling the stream, while an unavailable transport still leaves the delta for the existing retry.
Every line entering the parent status stream - a mirrored line, the continuity escalation, and the undelivered-document escalation - now goes through one at-most-once append, so the idempotence a replayed generation depends on is stated once instead of copied at three call sites.
kunchenguid
force-pushed
the
fm/fm-remote-reply-uncorrelated-wedge-r1
branch
from
August 7, 2026 00:40
8a8ebf8 to
1ffacb6
Compare
kunchenguid
added a commit
that referenced
this pull request
Aug 7, 2026
Integrates PR #1846's remote status-stream mirroring, which deleted this adapter's line validator: gating the stream made a remote mate's uncorrelated progress lines unrepresentable, and rejecting one line failed a whole delta and wedged the channel. The reserved-key guard this branch had put inside that validator was therefore in the wrong place twice over. It was batch-fatal, and it protected only the remote path while a local mate appends into the very same status stream unchecked. Both writers meet at the open-decision fold, so the rule now lives there: a key like `pending-reply-<id>` names a decision one library raises and is the only writer that ever closes it, and the fold lets a reserved key be opened or closed only by a line whose note speaks that namespace's own vocabulary. Any other line naming the key folds as ordinary status, so it can neither take the key over and block the owner's close forever, nor clear the owner's decision. The rule is generic, so the fold needs no knowledge of any particular owner, and being consumer-side it can never fail a delta or wedge a stream. Also converts the serialized pending-reply lifecycle off subshell function bodies. Sourcing the wake library inside a subshell assigned its globals there, which read as a lost subshell write at every later use in every script that sources this library and failed the repo's own lint gate; main lints clean, so that was this branch's regression rather than a pre-existing one. The globals are declared local and the lock is released explicitly instead, leaving the per-correlation serialization unchanged with its concurrency regressions passing.
kaku-san
added a commit
to kaku-san/firstmate
that referenced
this pull request
Aug 7, 2026
Intent
Fix a remote-secondmate transport bug in firstmate: the remote reply adapter (bin/fm-procevent-remote-reply.sh) fail-closed and wedged the reply channel when a remote secondmate wrote UN-CORRELATED status lines, and a remote secondmate had no first-class way to raise a NEW needs-decision to the parent.
OBSERVED BUG (captain, 2026-08-06): the adapter could not ingest axi-a1 reply seq 5 with 'delta contains an invalid or uncorrelated status line'. The remote mate had written a NEW needs-decision it was raising plus a 'working [key=...]' progress line; neither carries a corr= token, so line_valid rejected the WHOLE delta. Two real problems: (1) an un-correlated line WEDGES the channel because the cursor cannot advance past it, so ingest fails repeatedly and the channel is stuck; (2) a remote secondmate has NO clean path to raise a NEW needs-decision to the parent through the reply channel.
CAPTAIN DESIGN PRINCIPLE (supersedes any 'tolerate/route un-correlated lines' framing): remote vs local secondmates must differ ONLY at the transport layer. Do NOT bespoke-patch the correlated-reply channel. Instead make a REMOTE secondmate present the SAME status/decision model as a LOCAL one - the full status stream including un-correlated progress AND newly raised needs-decisions - just carried over SSH, so raising a decision, folding open-decisions, and reconciling status all work identically local vs remote. Ask WHY local mates do not have this bug (their status stream is written straight into the parent's state/.status and read/folded directly) and adopt that architecture over the transport.
WHAT WAS IMPLEMENTED: the channel is now a status-stream MIRROR rather than a correlated-reply channel. Correlation is restored to what it is locally - a per-line property that fm-pending-reply-lib.sh consumes to settle a pending request - and is no longer a gate on the stream, so no single line can stop ingest or freeze the cursor. The verb allowlist and per-line byte cap were removed as semantic gates with no local analogue; line framing and size bounding already belong to bin/fm-remote-delta-read.sh, which delivers only whole lines and raises a continuity break on an over-long one. What remains is only what crossing a machine boundary genuinely adds: cursor continuity and identity, data/*.md pointers fetched through the path-confined remote reader and rewritten to local copies, at-most-once append, and control-byte normalization that rewrites C0/DEL bytes to '?' while passing tab, printable ASCII and all high bytes (UTF-8) through untouched - it never drops a line. A document the remote reader permanently refuses is named in one keyed escalation and the mate's line is mirrored with its own pointer intact, rather than stalling the stream; an SSH exit 255 stays 'transport unavailable/unknown' and still leaves the delta for the runner's existing retry, per fm-on.sh's documented contract. A later refactor gave the parent status stream ONE at-most-once append owner (append_status_once) used by the mirrored line, the continuity escalation, and the document escalation - the captain asked for this to stay clean and well-factored because follow-on work builds on it.
DELIBERATE: the secondmate charter (bin/fm-brief.sh) was NOT changed. It already tells a mate to report progress phases and raise decisions without a corr token, and only marked from-firstmate requests require correlation. The charter was already correct; the transport was wrong. That no-change is evidence the architecture is right, not an omission.
DIAGNOSIS DELIVERED: reproduced the wedge end to end against the real ingest boundary (three consecutive ingests of a staged delta all failed identically with the cursor never created and the parent status file never written). Pinned the exact mechanism: cmd_ingest's per-line line_valid call dies before write_cursor, so the cursor never advances and every retry replays the same rejection; cmd_handle_locked then returns nonzero, so the generation is never acknowledged and the source is never re-armed. Read-only durable-record finding on the live axi-a1 mate (no SSH, no mutation of the live host or channel): its channel IS currently wedged AND dark - cursor frozen at offset 2088, the seq-5 delta (offsets 2088-4364, three lines including TWO newly raised needs-decisions) never reached state/axi-a1.status (2088 bytes, unchanged since 12:47), no .5.ingested receipt exists although a .5.handled marker does, and no remote-reply-axi-a1 source registration remains, so nothing newer can arrive either. Recovering the live axi-a1 channel is explicitly NOT part of this change and stays with the main firstmate.
SCOPE - EXPLICITLY NARROWED BY THE CAPTAIN: a scope expansion to fold in remote STATE reconciliation (fm-crew-state.sh misreporting 'worktree gone' because it stats the remote worktree path locally, fm-peek.sh failing 'can't find session: remote' because fm_backend_of_meta returns tmux for a remote meta, false pending-reply-missed alarms, and the duplicated inline remote handling in fm-bootstrap.sh and fm-fleet-snapshot.sh) was diagnosed and proposed, and the captain then APPROVED A SPLIT: this change is JUST the reply-channel unwedge. The state-reads reconciliation is a separate follow-on the captain is filing and must NOT be done here. Do not add remote placement resolution, backend dispatch changes, or crew-state/peek changes to this change.
COORDINATION: PR #1831 edits this same adapter (runner auto-ingest, pending-reply resolution, library-owned escalation-format matching) and is not in this branch's base (main). Do not undo it. Its added pending-reply-* decision-key rejection sits inside line_valid, the function this change removes, and on main that rejection is itself whole-delta-fatal; how to reconcile it was raised to the captain as an open decision and deliberately NOT decided in this change.
ACCEPTANCE CRITERIA: a reply delta with an un-correlated needs-decision and/or 'working [key=...]' line ingests without wedging and the cursor advances; correlated replies still resolve their pending-reply records exactly as before; a remote secondmate can raise a NEW needs-decision that surfaces to the parent's decision/hold path through the shared fold; the whole-delta-rejection-on-one-bad-line wedge is gone while validation stays fail-closed where correlation is genuinely required, with no silent security or identity regression (cursor/prefix continuity, confined document fetch, and exact-corr pending-reply resolution are all unchanged); regression and E2E tests added; bin/fm-lint.sh clean.
Firstmate repo conventions apply: one sentence per line in tracked Markdown, plain dash never an em dash, no agent co-author, shellcheck-clean bin scripts via bin/fm-lint.sh, tests colocated in tests/ extending the existing runner, and tests must exercise behavior through an executable interface rather than asserting implementation source text. Delivery is mode=no-mistakes with yolo OFF: the captain merges, no self-merge.
What Changed
Risk Assessment
🚨 High: A reachable infrastructure failure can still cause permanent document loss and cursor advancement, contradicting the required permanent-refusal-only commit invariant.
Testing
The focused remote-reply E2E passed and produced a reviewer-visible transcript showing the remote status stream reaches the parent, newly raised decisions fold open, correlated replies resolve pending records, and the cursor advances without wedging; no baseline results were supplied, and lint was not run because this phase expressly forbids static analysis.
Evidence: Remote reply E2E transcript
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
bin/fm-procevent-remote-reply.sh:334- The required invariant says “the whole-delta-rejection-on-one-bad-line wedge is gone,” but accepting every nonempty line exposes the result parser’s whole-fileresult_fieldscan: a payload line beginningstatus=,path=,reason=, or another protocol field makes that field ambiguous, so ingest fails before advancing the cursor and retries wedge on the same delta. Parse metadata only from the header before the blank payload boundary.bin/fm-procevent-remote-reply.sh:333- The required normalization “rewrites C0/DEL bytes to '?'”, but Bashreadstores the payload inlinebeforemirror_lineruns and cannot preserve NUL bytes, so NUL is discarded instead of rewritten. Normalize the staged payload bytewise before reading it into shell variables.bin/fm-procevent-remote-reply.sh:345- Every non-255fetch_documentfailure is treated as a permanent remote refusal, but the function also returns 1 for localmkdir, confinement,mktemp,chmod, andmvfailures. A transient local storage failure therefore appends an undelivered escalation and commits the cursor, permanently abandoning the document. Return distinct statuses and advance only for an actual permanent remote-reader refusal; local failures must leave the delta retryable.🔧 Fix: Keep local document transfer failures retryable
2 errors still open:
bin/fm-procevent-remote-reply.sh:334- The required “whole-delta-rejection-on-one-bad-line wedge is gone” invariant remains false: arbitrary mirrored payload may contain a line beginningschema=,status=,path=, or another protocol field, whileresult_fieldscans the whole result rather than only the header. The field becomes ambiguous before cursor advancement, so every retry wedges on the same delta. Parse metadata only before the blank payload boundary.bin/fm-procevent-remote-reply.sh:336- The required normalization says every C0/DEL byte becomes?, butreadplaces payload bytes in a Bash variable andmirror_lineuses command substitution; Bash cannot preserve NUL, and thetrrange also excludes NUL. A NUL is therefore dropped or can make whole-file header parsing treat the result as binary instead of being rewritten. Normalize the staged payload bytewise before header-safe line processing.🔧 Fix: Isolate reply headers and normalize payload bytes
1 error still open:
bin/fm-procevent-remote-reply.sh:341- The required mirror contract says it “reproduces its stream line for line” and “never drops a line,” but this branch explicitly skips every complete blank payload line. The remote delta reader can deliver blank newline-terminated lines, and the cursor then advances past them, permanently diverging from the local status stream. Mirror the blank line through the shared append owner instead of continuing.🔧 Fix: Correct remote reply mirror contract wording
2 issues (1 error, 1 warning) still open:
bin/fm-procevent-remote-reply.sh:255-fm-on.shcan return non-255 failures before the remote reader runs, including remote entrypoint or worker failures with status 64/70. This code treats all of them as permanent document refusals, then mirrors the unresolved pointer and commits the cursor, so a temporary infrastructure failure permanently abandons the document. Preserve provenance at the remote-command boundary and commit only when the reader itself definitively refused the document; keep dispatch and infrastructure failures retryable.docs/scripts.md:65- The script catalog still describes this adapter as relaying "correlated remote-secondmate reply deltas", contradicting the changed status-stream mirror contract where correlation is never an ingest gate. Update the catalog entry to describe the remote status stream.🔧 Fix: Update remote reply script catalog description
1 error still open:
bin/fm-procevent-remote-reply.sh:255-fm-on.shcan fail before the remote file reader runs, including local route validation and remote entrypoint or worker failures. This code treats every non-255 failure as a permanent document refusal, then mirrors the unresolved pointer and commits the cursor, permanently abandoning a document after transient infrastructure failure. Preserve failure provenance at the remote-command boundary and commit only when the reader itself definitively refused the document; keep dispatch and infrastructure failures retryable.✅ **Test** - passed
✅ No issues found.
bash tests/fm-remote-reply.test.sh- exercised fake-SSH process-event capture, uncorrelated progress and new-decision mirroring, shared decision folding, exact-correlation pending-reply settlement, cursor advancement, replay idempotency, control-byte normalization, document delivery recovery, and continuity failure handling✅ **Document** - passed
✅ No issues found.
✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.
Known and deferred
These are deliberate captain decisions, not oversights.
Document-fetch provenance is deferred to
fm-remote-doc-fetch-provenance-r1.fm-on.shreturns ssh's status unchanged, so 255 alone means unavailable transport.This change treats a remaining non-255 remote-command failure as a permanent reader refusal, mirrors the mate's line with its own pointer intact, names the gap in one keyed escalation, and lets the stream continue.
That classification is too coarse in one direction:
bin/fm-remote-file.shsignals its own definitive refusals throughdiewith exit 1, the same statusfm-on.shuses for route-validation failure, so exit 1 cannot currently distinguish "the reader refused" from "the reader never ran".A transient dispatch failure can therefore cost one document copy rather than being retried.
Making that provenance definitive requires exit-code changes in
bin/fm-remote-file.shorbin/fm-on.sh, which are shared remote transport also used by backlog handoff, so the captain scoped it out of this change rather than widen it.This is still a strict improvement over the previous behavior, which failed the whole delta on any fetch failure and wedged the channel permanently.
Local storage failures and unavailable transport both remain retryable here.
Remote state reconciliation is a separate follow-on.
The same root cause reaches the parent's state reads:
remoteis a real placement that onlybin/fm-send.shunderstands, sofm_backend_of_metaresolves a remote secondmate's metadata to tmux and other readers treatwindow=remote:<id>as a local session.bin/fm-crew-state.shstats the remote worktree path locally and reports it torn down,bin/fm-peek.shdispatches tmux and fails to find sessionremote, andbin/fm-bootstrap.shandbin/fm-fleet-snapshot.sheach carry their own inline remote handling.That work is filed separately and is deliberately absent here.
PR #1831 reconciliation is unresolved by design.
That PR edits this same adapter and is not in this branch's base.
Its
pending-reply-*decision-key rejection sits insideline_valid, the function this change removes, and on main that rejection is itself whole-delta-fatal.Because a local secondmate can write the same line straight into the parent status file, the guard likely belongs in the shared consumer rather than in this transport.
That was raised to the captain as an open decision and is not decided here; no code from #1831 was modified.