Skip to content

fix: preserve merge polls across task metadata updates - #3452

Closed
ktapa wants to merge 8 commits into
kunchenguid:mainfrom
ktapa:fm/fm-relaunch-breaks-pr-poll
Closed

ktapa wants to merge 8 commits into
kunchenguid:mainfrom
ktapa:fm/fm-relaunch-breaks-pr-poll

Conversation

@ktapa

@ktapa ktapa commented Sep 1, 2026

Copy link
Copy Markdown

Intent

Fix a silent failure in firstmate's own tooling: relaunching a task disarms its merge poll.

THE DEFECT (reproduced and isolated 2026-08-31). bin/fm-control.sh <id> relaunch appends control_relaunch_tx= to the END of state/<id>.meta. When that task already has a PR recorded, the new key lands AFTER the pr= line. fm_pr_metadata_identity_parse in bin/fm-pr-lib.sh tolerates only pr_head= and the x_* keys after pr=; any other key sets post_pr_invalid=1 and the parse returns 1. That propagates through fm_pr_poll_artifacts_valid -> fm_pr_poll_snapshot_capture -> bin/fm-watch.sh, which then classifies the task's merge poll as an unregistered check and emits check: rejected unauthenticated state checks: state/<id>.check.sh on every check interval WITHOUT ever executing the poll.

CONSEQUENCE. Merge detection is silently OFF for any task relaunched after its PR was recorded, and firstmate is woken repeatedly by a rejection instead. Both symptoms read as noise.

EVIDENCE. Observed on task focal-year-quarter. Its meta ended pr= / pr_head= / control_relaunch_tx=. Every other binding validated cleanly - 0600 modes, single links, template byte-match against bin/fm-pr-poll.sh, data hash, registration hashes, device:inode identities - and bisecting the gates in fm_pr_poll_artifacts_valid isolated the failure to fm_pr_metadata_identity_parse alone. Re-running bin/fm-pr-check.sh re-appended pr=/pr_head= last and the poll validated again. That was a workaround applied to that task, not the fix.

THE DECISION REQUIRED. Read the header of bin/fm-pr-lib.sh and understand WHY the trailing-key rule exists before touching it. It is a tamper-evidence boundary; do not simply delete or weaken the check because it is in the way. Choose deliberately between: (A) make every meta writer keep pr=/pr_head= last - fragile, each future writer must remember; (B) relax the parser to ignore unknown keys after pr= - simplest, but forfeits whatever the strict ordering was buying, and only acceptable if ordering can be shown never to have been load-bearing; (C) keep the strict parse and have relaunch, and any other writer, rewrite meta so the PR identity block stays terminal. State the choice and the reasoning in the PR. If the evidence points somewhere none of these cover, say so and follow the evidence.

CHOICE MADE: OPTION C, with one owner rather than four writers remembering. Option B was refused: the ordering rule is the only structural check the record carries, because unlike the sidecar and the poll source, a task record must stay mutable across a relaunch and so cannot be bound by hash. Option A is what already failed - four writers forgot, and the parse's existing x_* exception shows the same invariant being retrofitted one key at a time; a blast radius of four argues against per-writer discipline, not for it. So the strict parse is kept byte-for-byte and the discipline moves into a single helper the writers call: bin/fm-pr-lib.sh (which owns the contract) gains fm_pr_meta_terminal_restage, which moves the identity block back to the end of a staged record and changes nothing else.

REQUIRED SCOPE, all three satisfied. (1) Audit every writer of state/<id>.meta in bin/ for the same pattern - fm-control.sh was the one PROVEN to append after pr=; establish whether it is alone rather than assuming it. The writer set was established as closed by enumerating every path that can make a file become state/<id>.meta: direct redirection, mv/cp, and fm_backlog_atomic_transition publish. Four writers broke the invariant and now call the helper: bin/fm-spawn.sh writing control_relaunch_tx= on a relaunch (the proven case, reached through bin/fm-control.sh <id> relaunch); bin/fm-spawn.sh appending traceparent= when recording a carrier; bin/fm-captain-hold.sh appending decisions_reviewed=/decision_keys= when attesting a reviewed inventory, whose raw in-place append became a staged rewrite renamed under the meta lock the command already holds, preserving the record's mode; and bin/fm-promote.sh writing kind=/mode=/yolo= last. The remainder are accounted for rather than assumed: bin/fm-pr-check.sh builds the block last by construction, bin/fm-x-lib.sh appends only x_* keys which the parse already tolerates in any position, and bin/fm-spawn.sh's remote secondmate record carries no PR. (2) Regression coverage is mandatory: a relaunch on a task with a recorded PR must leave the merge poll validating, and the test must fail without the fix. Regressions cover a relaunch, a relaunch that records a carrier, a promotion, and a completion attestation, each asserting an armed merge poll stays recognisable by the watcher's own snapshot capture, plus a direct test that the restage only moves lines. (3) Do not change the merge-poll security model as a side effect; if the fix touches what the poll trusts, say so explicitly and justify it.

TRUST BOUNDARY, stated explicitly per (3) and corrected during review. An initial claim that nothing about what the merge poll trusts changes was over-strong and was corrected. The task-record writers now validate the record as it exists on disk before contributing any metadata, and terminal restaging validates that source again before moving lines. A record is refused when any key after pr= is neither pr_head= nor a tolerated x_* key; refusal leaves the anomalous record unnormalised and emits a visible error naming the offending key or keys at relaunch, trace recording, promotion, and completion attestation. The poll still does not authenticate every mutable task-record field or bind the complete record by hash. Its strict parser remains the structural boundary for trailing metadata, while the existing sidecar, poll-source hashes, identity bindings, and check registration remain unchanged.

A later correction narrowed over-broad x_* wording: terminal validation accepts after pr= only pr_head plus x_request, x_request_ts, x_followups, x_platform, and x_reply_max_chars, exactly matching the unchanged parser. Any other x_-prefixed key is refused, left unnormalised, and named in the visible error before a writer contributes metadata. bin/fm-x-lib.sh writes exactly those five relay keys, so it remains outside the invalid-suffix writer set and needs no change. A known and deliberately unexpanded coupling is recorded: the validator and parser still encode the five-name list separately, so drift could silently reopen this defect; a later change could give both functions one shared predicate or add behavioral equivalence coverage for the five accepted names and an unknown control, but a source-grep comparison would violate the repository test contract.

OUT OF SCOPE, accepted constraints. Do not refactor the wider PR-poll or watcher machinery. Do not change teardown, spawn, or the check-registration model.

ACCEPTANCE. A task that has a PR recorded and is then relaunched still has a valid merge poll; the rejection wake no longer fires for that case; the tamper-evidence property the original check provided is either preserved or its removal is explicitly argued and accepted in the PR.

REPOSITORY CONSTRAINTS. This is firstmate's shared tracked material under bin/, governed by the firstmate-coding-guidelines skill: one sentence per line, plain dash, shellcheck-clean bin scripts, colocated tests, no agent co-author, and the one-owner rule for contracts.

HISTORY CONSTRAINT accepted during this work: do not rewrite history. Carry corrections in later commits and in the PR body, never by rewriting an ancestor. This is why the trust-boundary and x_* corrections above appear as follow-up commits rather than amendments.

What Changed

  • Add a shared PR metadata helper that preserves the terminal PR identity block while retaining strict validation of post-PR keys.
  • Update relaunch, trace recording, promotion, and completion-attestation writers to restage valid metadata and visibly refuse anomalous suffixes without modifying the record.
  • Add regression coverage proving these metadata updates keep armed merge polls recognizable and that restaging only reorders existing lines.

Risk Assessment

✅ Low: The change is well-bounded, preserves the strict parser boundary, validates live metadata before all four writer paths, and the latest restaging fix correctly preserves pre-PR pr_head lines without introducing a substantiated reachable defect.

Testing

Focused behavioral suites exercised relaunch, trace recording, promotion, completion attestation, terminal restaging, parser enforcement, and watcher snapshot recognition; they demonstrated that armed merge polls remain recognized, invalid suffixes are visibly named and preserved, and the pre-PR pr_head regression is fixed, with all checks passing and CLI transcripts captured.

Evidence: Relaunch, trace-recording, and promotion behavioral transcript

Source: Relaunch, trace-recording, and promotion behavioral transcript

ok - fm-control relaunch: a same-harness relaunch replaces the agent in the same endpoint and worktree
ok - fm-control relaunch: durable task metadata survives replacement launch publication
ok - fm-control relaunch: an armed merge poll survives replacing the agent
ok - fm-control relaunch: a pre-PR head stays outside the merge-poll identity block
ok - fm-control relaunch: a pre-existing invalid PR suffix is named and preserved
ok - fm-control relaunch: its own pre-existing suffix key is named and preserved
ok - fm-control relaunch: recording a carrier keeps an armed merge poll recognised
ok - fm-spawn trace recording: its own pre-existing suffix key is named and preserved
ok - fm-promote: promoting a task that already recorded a PR keeps its merge poll recognised
ok - fm-promote: its own pre-existing suffix key is named and preserved
ok - fm-control relaunch: delivery and concurrent task metadata publication serialize
ok - fm-control relaunch: disabling tracing clears metadata and pane context
ok - fm-control relaunch: the progress note lands in the instructions the replacement reads
ok - fm-control relaunch: a ship task refuses without the progress note its replacement needs
ok - fm-control relaunch: switching harness is one ordinary relaunch, and the old wiring goes with the old agent
ok - fm-control relaunch: a harness switch resets model and effort unless they are named too
ok - fm-control relaunch: a prefixed recorded harness can switch adapters transactionally
ok - fm-control relaunch: a prefixed command requires an explicit replacement harness
ok - fm-control relaunch: a same-harness relaunch keeps the profile axes it was running with
ok - fm-control relaunch: explicit model and effort win over the recorded ones
ok - fm-control relaunch: refuses to relaunch onto an adapter with no verified mechanics
ok - fm-control relaunch: the retired incarnation's global turn-end token is revoked
ok - fm-control relaunch: wiring cleanup failure refuses replacement arming
ok - fm-control-lib: one owner resolves each harness's turn-end registry entry, and refuses a malformed token
ok - fm-control relaunch: a secondmate relaunch re-resolves its durable configured harness pin
ok - fm-control relaunch: invalid configured effort is ignored before stop
ok - fm-control relaunch: an adapter unverified for this task kind refuses before the agent is stopped
ok - fm-control relaunch: explicit secondmate harness resets unnamed profile axes
ok - fm-control relaunch: a ship task keeps its recorded harness instead of re-reading crew config
ok - fm-spawn --relaunch: with no explicit harness it reuses the task's recorded one, never the crew default
ok - fm-spawn --relaunch: wiring armed under a prefixed harness name is still retired
ok - fm-spawn --relaunch: switching away from muse retires its session binding
ok - fm-spawn --relaunch: switching away from cursor retires its session binding
ok - fm-control relaunch: an unaccountable local copy refuses before the agent is touched
ok - fm-control relaunch: a worker with nothing to work from is never launched
ok - fm-control relaunch: a refusal before the agent is stopped leaves the durable record untouched
ok - fm-control relaunch: checkpoint inspection failures refuse before stopping
ok - fm-control relaunch: a launch failure after the stop keeps the prior record and reports the real state
ok - fm-control relaunch: unpublished rollback keeps concurrent durable metadata
ok - fm-control relaunch: post-publication failure keeps the new durable record
ok - fm-control relaunch: partial stop reconciles actual agent state
ok - fm-control relaunch: failed journal replacement preserves durable phase
ok - fm-spawn relaunch: prepublication abort removes replacement state
ok - fm-control relaunch: the checkpoint records the exact unlanded work it preserved
ok - fm-control relaunch: a secondmate's child work is accounted for and its charter is left alone
ok - fm-control relaunch: a secondmate home that is not this secondmate's is refused
ok - fm-control relaunch: unreadable and untraversable child state fails checkpoint
ok - fm-control relaunch: two control actions on one task serialize instead of interleaving
ok - fm-spawn relaunch: direct entry participates in lifecycle serialization
ok - fm-promote: promotion participates in lifecycle serialization
ok - fm-spawn --relaunch: refuses to launch a second agent into a live endpoint
ok - fm-spawn --relaunch: symlinked records refuse before inspection
ok - fm-spawn --relaunch: keeps its early meta lock continuous
ok - fm-spawn --relaunch: pending closes refuse before replacement begins
ok - fm-spawn --relaunch: every identity axis comes from the record, and a contradicting flag refuses
ok - fm-spawn --relaunch: an unrecorded task is refused
ok - fm-spawn --relaunch: refuses to start a replacement outside the copy holding the work
ok - relaunch re-reads the backlog item instead of blindly re-running the transition
ok - relaunch heals an item that drifted out of In flight while the task stayed live
Evidence: Completion-attestation behavioral transcript

Source: Completion-attestation behavioral transcript

ok - report-only unresolved captain call is reproduced and completion refuses before loss
ok - the completion gate attests captain-held inventory and transfers open status decisions
ok - answer records the captain's words, closes idempotently, and releases routed work
ok - release frees held work with the captain's words recorded and the body preserved
ok - a deferred captain call leaves the live Captain's Call until its date and stays answerable
ok - an out-of-band close is recordable with the captain's word and nothing else
ok - ended visual review follows the same captain-hold completion owner
ok - recording a reviewed inventory keeps an armed merge poll recognised
ok - completion attestation names and preserves its own pre-existing suffix key
ok - resolved findings and decision-like prose do not create captain-held tasks
ok - terminal single-owner stale status decisions do not block empty inventory
ok - main-home and secondmate-home captain calls remain correctly routed
ok - a bound channel's captured answers close their captain-held tasks at answer time
ok - a channel source with no decision binding closes nothing
ok - legacy identities, metadata, bindings, and the shim keep working
ok - the chat channel feeds the same keyed-answer intake a captured review does
ok - completion and verification validate origins before constructing paths
ok - a status resolution over a still-open captain-held task is signalled, not closed
ok - a captain call with no routed work, a verified transfer, an open decision, and an answered call all stay silent
Evidence: PR identity restaging and watcher-security transcript

Source: PR identity restaging and watcher-security transcript

ok - raw-byte parser accepts canonical URLs and rejects the complete adversarial matrix
ok - GitLab merge requests are followed on any instance and never wake falsely
ok - validated merged polls notify once and retire before the next watcher cycle
ok - a repeat identical merged poll for an already-notified task is absorbed, never queued as a main-blocking row
ok - a failed upward merge report keeps its poll armed for repair and retry
ok - staged self-merge and poll interleavings are never silent
ok - a merge detected by the poll is reported upward from a secondmate home exactly once
ok - a different merged PR for the same task gets its own first notification
ok - merged poll retirement preserves every persistent secondmate lifecycle artifact
ok - queue, receipt, and every fixed-path removal crash point recover without loss or repeated execution
ok - open/red, closed-unmerged, malformed, and forge errors remain armed until an exact merged transition
ok - replacement, nonterminal, tampered, and custom results receive no deletion authority
ok - queue failure and untrusted receipts preserve canonical poll evidence
ok - GitHub and GitLab exact merged results share one retirement path
ok - task-record restage moves the PR identity block to the end and changes nothing else
ok - PR and teardown entrypoints reject invalid arguments before every side effect
ok - valid direct and merge flows record exact metadata and reject multiline head metadata
ok - rejected metacharacter bytes remain inert at generation and watcher time
ok - static poll is silent except for one merged line and remains watcher-bounded
ok - interrupted atomic preparation cleans private temporaries and publishes nothing
ok - concurrent watchers observe only complete private poll publications
ok - poll publication paths refuse symlinks and directories
ok - live poll and custom-check artifacts require private single-link files
ok - post-rename poll validation faults revoke both names and allow a clean retry
ok - bootstrap does not rewrite unauthenticated checks or emit retired migration diagnostics
ok - watcher signals promptly stop custom checks and clean private state
ok - returned custom check descendants are drained on installed and fallback timeout paths
ok - teardown removes safe poll artifacts and refuses directory-shaped check files without traversal

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 1 issue found → auto-fixed ✅
  • 🚨 bin/fm-pr-lib.sh:340 - Restaging moves every pr_head= line after pr=, including one that originally preceded it and was therefore ignored by the unchanged parser. Concrete path: pr_head=not-a-sha followed by a valid pr= produces a valid armed-poll snapshot; relaunch validation accepts it, then restaging moves the invalid head after pr=, where parsing rejects it and the writer disarms the poll. Only treat pr_head= encountered after the first pr= as part of the terminal identity block, preserving earlier lines in place, and add a behavioral regression for this sequence.

🔧 Fix: Preserve pre-PR heads during metadata restaging
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • Inspected git diff a5f3cbeeb71768bca2ac54c6926d314b6d27b836..2f7f4ba3ae1accb7d137a246f1e9af5b08b91d01 to map changed behavior to focused tests.
  • bash tests/fm-control-relaunch.test.sh 2>&1 | tee ~/.no-mistakes/evidence/01M1EKFNQB0VQE30YVB5A9RKD3/fm-control-relaunch-transcript.txt
  • bash tests/fm-captain-hold-lifecycle.test.sh 2>&1 | tee ~/.no-mistakes/evidence/01M1EKFNQB0VQE30YVB5A9RKD3/fm-captain-hold-lifecycle-transcript.txt
  • bash tests/fm-pr-check-security.test.sh 2>&1 | tee ~/.no-mistakes/evidence/01M1EKFNQB0VQE30YVB5A9RKD3/fm-pr-check-security-transcript.txt
  • Verified git status --short was empty after testing.
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

ktapa added 8 commits August 31, 2026 23:59
A task record's PR identity block - its single `pr=` line and any
`pr_head=` line - must stay terminal: fm_pr_metadata_identity_parse
refuses every other key that follows it, which is what makes an append
to a record whose merge poll is already armed evident rather than
silent.

Four writers broke that invariant by appending their own key last, so a
task that had recorded a PR lost merge detection entirely: the poll
stopped validating, fm-watch.sh reclassified it as an unregistered
check, and every check interval woke firstmate with a rejection instead
of polling for the merge. Both symptoms read as noise.

OPTION C, with one owner rather than four writers remembering.

Option B - relaxing the parse to ignore unknown keys after `pr=` - is
refused. The ordering rule is the only structural check the record
carries: unlike the sidecar and the poll source, a record must stay
mutable across a relaunch and so cannot be bound by hash. Option A -
asking each writer to keep the block last - is what already failed;
four writers forgot, and the parse's existing `x_*` exception shows the
same invariant being retrofitted one key at a time. A blast radius of
four argues against per-writer discipline, not for it. So the strict
parse is kept byte-for-byte and the discipline moves into a single
helper the writers call.

bin/fm-pr-lib.sh, which owns the contract, gains
fm_pr_meta_terminal_restage: it moves the identity block back to the end
of a staged record and changes nothing else. Each writer calls it before
publishing:

  - bin/fm-spawn.sh writes `control_relaunch_tx=` after carrying the
    previous record forward on a relaunch (the proven case, reached
    through `bin/fm-control.sh <id> relaunch`)
  - bin/fm-spawn.sh appends `traceparent=` when recording a carrier
  - bin/fm-captain-hold.sh appended `decisions_reviewed=` and
    `decision_keys=` when attesting a reviewed inventory; that raw
    in-place append is now a staged rewrite renamed under the meta lock
    the command already holds, preserving the record's mode
  - bin/fm-promote.sh writes `kind=`/`mode=`/`yolo=` last

The writer set is closed, established by enumerating every path that can
make a file become `state/<id>.meta`: direct redirection, mv/cp, and
`fm_backlog_atomic_transition publish`. The remainder are accounted for
rather than assumed: bin/fm-pr-check.sh builds the block last by
construction; bin/fm-x-lib.sh appends only `x_*` keys, which the parse
already tolerates in any position; and bin/fm-spawn.sh's remote
secondmate record carries no PR.

Nothing about what the merge poll trusts changes: the parse, the sidecar
and poll-source hash and identity bindings, and the check registration
model are all untouched.

Regressions fail without the fix: a relaunch, a relaunch that records a
carrier, a promotion, and a completion attestation each leave an armed
merge poll recognisable by the watcher's own snapshot capture, plus a
direct test that the restage only moves lines.
The earlier claim that nothing about what the merge poll trusts changes was over-strong. The task-record writers now validate the record as it exists on disk before contributing any metadata, and terminal restaging validates that source again before moving lines.

A record is refused when any key after pr= is neither pr_head= nor a tolerated x_* key. Refusal leaves the anomalous record unnormalised and emits a visible error naming the offending key or keys at relaunch, trace recording, promotion, and completion attestation.

The poll still does not authenticate every mutable task-record field or bind the complete record by hash. Its strict parser remains the structural boundary for trailing metadata, while the existing sidecar, poll-source hashes, identity bindings, and check registration remain unchanged.
The earlier x_* wording was over-broad. Terminal validation now accepts after pr= only pr_head plus x_request, x_request_ts, x_followups, x_platform, and x_reply_max_chars, exactly matching the unchanged parser. Any other x_-prefixed key is refused, left unnormalised, and named in the visible error before a writer contributes metadata.

bin/fm-x-lib.sh writes exactly those five relay keys, so it remains outside the invalid-suffix writer set and needs no change.

The validator and parser still encode the five-name list separately, so drift could silently reopen this defect. A later change could give both functions one shared predicate, or add behavioral equivalence coverage for the five accepted names and an unknown control; a source-grep comparison would violate the repository test contract. This coupling is recorded but intentionally not expanded in this fix.
@greptile-apps

greptile-apps Bot commented Sep 1, 2026

Copy link
Copy Markdown

Confidence Score: 5/5

The PR appears safe to merge with no actionable defects identified in the changed metadata-restaging paths.

The shared helper preserves the strict trailing-metadata boundary, the updated writers serialize and stage their changes, and focused regressions cover the previously failing merge-poll scenarios.

Reviews (1): Last reviewed commit: "no-mistakes(document): Clarify terminal ..." | Re-trigger Greptile

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: first-time fork CI approved after a full-thread + full-diff review (no .github/workflows writes). Runs 33516468905 (CI) and 33516468919 (Require no-mistakes).

Inspected HEAD b9036696fbb0876a8126937304e47c51d328b08a vs main a5f3cbeeb71768bca2ac54c6926d314b6d27b836: bin/fm-pr-lib.sh (fm_pr_meta_terminal_validate / fm_pr_meta_terminal_restage), bin/fm-spawn.sh (relaunch + traceparent), bin/fm-promote.sh, bin/fm-captain-hold.sh (staged complete), docs, and the three regression suites. Attestation MATCH. MERGEABLE/UNSTABLE. workflow-zero. Greptile SUCCESS. Security clean (ktapa not blocked; strengthens refusal of anomalous post-pr= suffixes; does not weaken the strict parser).

Contract-class: restore. Unconfigured fleet already promised that an armed merge poll stays recognizable after relaunch / metadata updates; main writers were appending after pr= and the unchanged parser correctly refused those records, so merge detection went silent and the watcher woke on rejection noise. Option C keeps the byte-for-byte parser and moves writer discipline into one owner helper — restoring the promised poll durability without inventing a new default path. No auto-merge until CI + no-mistakes are green.

VISION.md per-rule

  • One captain, one interface — aligns. Stops false rejection wakes and restores merge-outcome visibility after relaunch.
  • Authority is explicit and never inferred — aligns. No new autonomy; anomalous suffixes are named and left unnormalized rather than quietly rewritten into validity.
  • Scripts own the mechanics, agents own the judgment — aligns. Deterministic restage/validate in fm-pr-lib.sh; writers call it.
  • A restart is a non-event — aligns. Core of the fix: relaunch must not disarm merge detection.
  • Delegation with a spine — aligns. Behavioral regressions pin watcher snapshot recognition and refusal preservation.
  • The fleet outlives any vendor — aligns. Task-record / poll contract, not forge UI pixels.
  • Scope — aligns. Command-layer meta contract; no workshop growth.

This wait is on CI (blocking no-mistakes), not the author or the captain.

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