Repository navigation
fix(merge): serialize away authority with synchronous merges - #4285
Merged
Merged
Conversation
bin/fm-pr-merge.sh read the away-posture record for merge authority (the per-task merge grant and the yolo/away-grant decision) and handed the merge to the forge afterwards. An archive at the captain's return or a grant revoked by a replacement record could land in between, so a merge could proceed on away authority that no longer held. The away record now carries a cross-subsystem lock, built on the existing bounded lock primitive rather than a new lock format: the record-mutating subcommands hold it across their mutation, and the merge holds it across both its authority read and the forge command. Because a queued or auto merge returns before the pull request lands, and would therefore outlive the lock, an away merge is now refused whenever it could land asynchronously: a requested --auto, a base branch whose merge-queue state does not prove an immediate merge, and GitLab's asynchronous flags and configuration. What remains permitted while away is the synchronous merge that lands inside the lock. This closes the common away-record/merge race against a live lock owner. It does not make the merge atomic in every case, and two narrow races are accepted and documented at their sites rather than hidden, both confused-agent-grade in the sense bin/fm-lease-lib.sh already uses: - A merge-queue rule change or a PR base change in the window between the queue-free preflight and the forge call can still enqueue the merge, which can then land after its grant lapses. - Killing the lock-owning shell while its gh or glab child is still running lets stale-owner recovery reclaim the lock and the record be archived or replaced, after which the orphaned child can complete the merge on lapsed authority. Closing either one needs landing verification or an ownership handoff, which is deliberately out of scope here. No existing gate is relaxed. The lock is taken after the live green-at-head verify and the captain-hold check, the in-lock authority read is unchanged, and a lock that cannot be taken refuses the merge rather than proceeding unlocked. The away grant stays a structured field; no prose is parsed.
…e the required baseRefName. Both previously failing test suites now pass: fm-captain-hold-lifecycle.test.sh and fm-pr-check-security.test.sh. git diff --check also passes
auss
pushed a commit
to auss/firstmate
that referenced
this pull request
Sep 12, 2026
…guid#4285) * fix(merge): serialize the away-authority check with a synchronous merge bin/fm-pr-merge.sh read the away-posture record for merge authority (the per-task merge grant and the yolo/away-grant decision) and handed the merge to the forge afterwards. An archive at the captain's return or a grant revoked by a replacement record could land in between, so a merge could proceed on away authority that no longer held. The away record now carries a cross-subsystem lock, built on the existing bounded lock primitive rather than a new lock format: the record-mutating subcommands hold it across their mutation, and the merge holds it across both its authority read and the forge command. Because a queued or auto merge returns before the pull request lands, and would therefore outlive the lock, an away merge is now refused whenever it could land asynchronously: a requested --auto, a base branch whose merge-queue state does not prove an immediate merge, and GitLab's asynchronous flags and configuration. What remains permitted while away is the synchronous merge that lands inside the lock. This closes the common away-record/merge race against a live lock owner. It does not make the merge atomic in every case, and two narrow races are accepted and documented at their sites rather than hidden, both confused-agent-grade in the sense bin/fm-lease-lib.sh already uses: - A merge-queue rule change or a PR base change in the window between the queue-free preflight and the forge call can still enqueue the merge, which can then land after its grant lapses. - Killing the lock-owning shell while its gh or glab child is still running lets stale-owner recovery reclaim the lock and the record be archived or replaced, after which the orphaned child can complete the merge on lapsed authority. Closing either one needs landing verification or an ownership handoff, which is deliberately out of scope here. No existing gate is relaxed. The lock is taken after the live green-at-head verify and the captain-hold check, the in-lock authority read is unchanged, and a lock that cannot be taken refuses the merge rather than proceeding unlocked. The away grant stays a structured field; no prose is parsed. * no-mistakes(review): Fix GitHub rollup fixture base branch * no-mistakes(document): Document atomic away-authority merge locking * no-mistakes(ci): Updated two executable GitHub API fixtures to include the required baseRefName. Both previously failing test suites now pass: fm-captain-hold-lifecycle.test.sh and fm-pr-check-security.test.sh. git diff --check also passes
auss
added a commit
to auss/firstmate
that referenced
this pull request
Sep 13, 2026
* fix(backlog): bound per-item backlog row reads so a wedged backend cannot blind a session start (kunchenguid#4027) * fix(bin): bound each backlog row read so one wedged backend cannot blind a session start bin/fm-bootstrap.sh's reconcile and close-replay sweeps read the backlog backend once per item through fm_backlog_row_show, and that read was unbounded. A single wedged `tasks-axi show` therefore consumed the whole FM_SESSION_START_TIMEOUT and truncated the digest before the wake queue, supervision instructions, fleet state, and context sections ever printed, leaving the fleet unsupervised with no live watcher. The harm was a blind startup, not a slow one. Bound the read with the existing shared timeout primitive (bin/fm-timeout-lib.sh), so a wedged backend degrades to a loud partial reconcile: the sweep's existing BACKLOG_RECONCILE diagnostic names the item it could not read and the loop continues to the next one. The first bound hit also latches FM_BACKLOG_ROW_SHOW_WEDGED, so a sweep over many items pays one bound rather than one per item and still names every item it skipped, which is what keeps the digest whole on a home carrying a large fleet. The bound holds regardless of any particular tasks-axi install, so it does not depend on the 0.2.5 `show` hang being resolved separately. * fix(bin): set the wedged-backend latch where it survives, and prove it The latch added with the read bound was inert. fm_backlog_row_show runs inside a command substitution in both of its status-capturing callers, so the subshell read the inherited value correctly but its write died with the subshell. Every item still paid a full bound and reported `exceeded`, never `skipped`, which left the large-fleet case the latch existed to cover completely uncovered. Move the write to the two callers that capture the read's status and own the surviving shell, and leave fm_backlog_row_show reading the latch only. Correct the comments that claimed an ownership the function never had. The test that was supposed to cover this asserted only that the second read finished under a generous ceiling, which is true whether or not the latch works. Assert instead that a latched read is strictly faster than one bound and that it reports its own item as skipped, so an inert latch fails the test. * test: cover every item the wedged-backend latch skips The latch assertion exercised a single skipped item, so "every skipped item is still named" was inferred rather than tested. Probe three items instead and assert each skipped one names itself and costs less than a bound. Verified as a real guard by removing both latch writes: the suite then fails on the first skipped item instead of passing. * no-mistakes(review): distinguish backlog read-bound hits from absent rows * no-mistakes(review): preserve read-bound status through the captain verify gates * no-mistakes(review): Preserve backlog read-bound hits through resolve_entry and reconcile instead of spending them as absent rows * no-mistakes(review): Preserve backlog read-bound 124 through migrated-prefix scan and remaining task_show call sites * no-mistakes(document): Document bounded backlog row reads and FM_BACKLOG_ROW_TIMEOUT_SECS * no-mistakes(ci): Fixed all four failing CI checks with one root-cause fix plus one test-heredity fix. (1) bin/fm-captain-hold.sh: task_show carries the row in TASK_SHOW_OUTPUT and emits no stdout, but four call sites still used the stale command-substitution convention show=$(task_show ...), leaving show empty: task_show_or_fail (every captain hold failed with 'did not retain its hold-set stamp' - broke fm-captain-hold-lifecycle in parallel 1 and fm-bearings-board in serial 3), resolve_migrated_entry (migrated-prefix resolution could never match), reconcile-requests (existing rows were refused as absent), and command_open --identity (printed a constant '#0' identity, so fm-watch-triage's re-held captain call inherited the previous call's silence in serial 1). This is also the Greptile P1. Fixed by invoking task_show in the current shell and reading show=$TASK_SHOW_OUTPUT, the convention the other eight call sites already use; read-bound hits still stop loudly by name. (2) tests/fm-backlog-read-bound.test.sh (serial 4, unclassified family): the new e2e half implicitly relied on the author's process tree containing a harness process so fm-lock.sh would grant the fleet lock; on CI runners the lock is refused, the reconcile sweep is skipped, and the final BACKLOG_RECONCILE assertion fails. Reproduced by simulating a CI ancestry via a ps shim, fixed by pinning the lock evidence with the established fake-ps harness fixture pattern from tests/fm-session-start.test.sh. Verified: shellcheck clean; parallel-1, serial-3, and serial-4 lanes fully green locally (failed=0); serial-1 lane green except fm-gemini-harness, which fails only under local Node v26 (comm=node-MainThread); CI's default Node 22 reports comm=node, the branch that test passes on, so it is not a CI failure * no-mistakes(document): Verified bounded backlog read docs accurate across branch * fix(merge): serialize away authority with synchronous merges (kunchenguid#4285) * fix(merge): serialize the away-authority check with a synchronous merge bin/fm-pr-merge.sh read the away-posture record for merge authority (the per-task merge grant and the yolo/away-grant decision) and handed the merge to the forge afterwards. An archive at the captain's return or a grant revoked by a replacement record could land in between, so a merge could proceed on away authority that no longer held. The away record now carries a cross-subsystem lock, built on the existing bounded lock primitive rather than a new lock format: the record-mutating subcommands hold it across their mutation, and the merge holds it across both its authority read and the forge command. Because a queued or auto merge returns before the pull request lands, and would therefore outlive the lock, an away merge is now refused whenever it could land asynchronously: a requested --auto, a base branch whose merge-queue state does not prove an immediate merge, and GitLab's asynchronous flags and configuration. What remains permitted while away is the synchronous merge that lands inside the lock. This closes the common away-record/merge race against a live lock owner. It does not make the merge atomic in every case, and two narrow races are accepted and documented at their sites rather than hidden, both confused-agent-grade in the sense bin/fm-lease-lib.sh already uses: - A merge-queue rule change or a PR base change in the window between the queue-free preflight and the forge call can still enqueue the merge, which can then land after its grant lapses. - Killing the lock-owning shell while its gh or glab child is still running lets stale-owner recovery reclaim the lock and the record be archived or replaced, after which the orphaned child can complete the merge on lapsed authority. Closing either one needs landing verification or an ownership handoff, which is deliberately out of scope here. No existing gate is relaxed. The lock is taken after the live green-at-head verify and the captain-hold check, the in-lock authority read is unchanged, and a lock that cannot be taken refuses the merge rather than proceeding unlocked. The away grant stays a structured field; no prose is parsed. * no-mistakes(review): Fix GitHub rollup fixture base branch * no-mistakes(document): Document atomic away-authority merge locking * no-mistakes(ci): Updated two executable GitHub API fixtures to include the required baseRefName. Both previously failing test suites now pass: fm-captain-hold-lifecycle.test.sh and fm-pr-check-security.test.sh. git diff --check also passes * fix(bin): pin away-mode heartbeat cadence against backoff decay During the away posture the watcher's heartbeat schedule still backed off per consecutive no-change heartbeat up to the 2h cap, although the away branch hands every scheduled heartbeat to the daemon precisely so an expired external wait surfaces within one base cadence. Overnight 2026-09-10/11 that decayed fleet scans to 2h blind spots (8 heartbeats in 7.5h) while the AGY task sat on an expired 20:55 UTC recheck. While .afk stands, pin the interval to the base HEARTBEAT and hold the durable streak at zero before wake() adds its one, so a decayed schedule cannot survive the return either. * feat(bin): gate manual compaction with a one-shot pre-compact stow ask The captain asked for compact hooks: stow before compaction, start after it. Neither Claude Code nor Codex delivers a PreCompact hook's output to the model, and shell cannot perform /stow's semantic memory curation, so the pre-compact half is a gate that asks once: a manual compaction blocks one attempt with a visible /stow instruction (Claude exit 2, Codex continue:false) and the retry always passes, with a stale window so a crashed ask never silences later ones. Auto compaction is never blocked because blocking an error-recovery auto-compact fails the in-flight request on Claude Code. The post-compact half needs no new registration: both harnesses discard PostCompact hook stdout, so the model-visible restart stays the tracked SessionStart hook (Claude source=compact; codex exec rehydrates a compacted thread as a resume the nudge path already owns). Codex 0.154 probing is recorded in docs/verification/supervision.md: exec dispatches no PreCompact/PostCompact around /compact, and project-hook trust stays interactive-only, so the gate activates wherever a codex surface actually dispatches it. Portable coverage extends tests/fm-sessionstart-nudge.test.sh; the live guard drives a real gated /compact in the TUI probe and adds a codex exec post-compaction reopen probe. The claude live refresh is recorded as pending an account window. * no-mistakes(review): Register durable post-compact startup hooks * fix(bin): land away heartbeat exits at streak zero The away branch wrote 0 to state/.heartbeat-streak but the shared wake() boundary in bin/fm-push-transition-lib.sh immediately incremented it to 1 on every heartbeat exit, so the first post-return watcher computed its interval from streak 1 and delayed the first post-return heartbeat to twice the base cadence, the exact decay the pin promised to prevent. Seed -1 instead so wake()'s increment lands on 0, and sanitize the main-loop interval read so a -1 left behind by a crashed exit reads as 0 rather than feeding a negative shift count. The regression now asserts the zero end state. * feat(bin): perform stow from the pre-compact hook The captain rejected the advisory containment: the preCompact hook must itself do stow, and a postCompact registration must exist. Redesign bin/fm-precompact-stow.sh from a one-shot ask into a runner that performs the work: every compaction, manual or auto, launches a detached headless agent that resumes the compacting session where the payload carries a session id and executes the stow skill's required startup-memory pass and knowledge sweep, then the compaction proceeds immediately. The hook never blocks, prints, or asks, so the unarmable-marker wedge class is gone outright: marker writes are guarded, a state directory that rejects writes loses bookkeeping only, a failed or unavailable agent records no cooldown and retries on the next compaction, a live pass is not stacked onto, and a completed pass inside FM_PRECOMPACT_STOW_SECS satisfies the window. Register the precompact-stow operational-input kind so the headless prompt stays marked as firstmate input rather than captain words, and rewrite the portable gate coverage for the new contract. * test(sessionstart): link the post-compact starter into the live lab The live lab copied the tracked PostCompact registrations into its harness configs but never linked bin/fm-postcompact-start.sh, so a Claude version that dispatches PostCompact would exec a missing script (127) instead of exercising the registration, and a codex surface would silently skip at its executable check - defeating the guard's recorded purpose of surfacing any version that starts dispatching the events. Link the real starter plus the operational-input and timeout libraries the pre-compact runner's detached child sources, wire a stub headless stow agent through FM_PRECOMPACT_STOW_AGENT into both the TUI and exec compaction probes, and rewrite those probes for the runner contract: a dispatched PreCompact must launch the marked stub pass and still compact immediately, with no blocking and no retry step. * test(sessionstart): track claude 2.1.269 trust default and codex compact phrasing The live guard's claude legs assumed the fresh-folder trust dialog defaults to the trusting option, but 2.1.269 defaults to 'No, exit', so the guard's bare Enter quit the lab session and the session-open hook never fired; move the dialog cursor onto the short trusting option line before confirming. codex-cli 0.154.0 now reports a completed exec /compact as 'Compacted.' where the 2026-09-11 evidence recorded 'Context compacted.', so accept both phrasings, and drop the pi lab's now-redundant copy of fm-operational-input.sh that the shared link already provides. docs/verification/supervision.md records the refreshed evidence: claude 2.1.269 performs the detached stow pass on a dispatched PreCompact and compacts immediately, the linked PostCompact starter drives the recorder's compact source, and every harness leg passed on 2026-09-12. * chore: re-arm the validation gate after preserved-head recovery The recovered pipeline head was content-identical to the head already recorded in the no-mistakes gate, so a new run's gate push had no ref work to do and the runner closed its pipe before git could report cleanly; advance the branch by one explicit commit so the gate fast-forwards again. No code change. * no-mistakes(review): bound stale precompact run markers by mtime; document compact hooks * chore: re-arm the validation gate after preserved-head recovery The recovered pipeline head was content-identical to the head already recorded in the no-mistakes gate, so a new run's gate push had no ref work to do and the runner closed its pipe before git could report cleanly; advance the branch by one explicit commit so the gate fast-forwards again. No code change. * no-mistakes(review): Guard PostCompact drain against committing undelivered one-shot presentations * chore: re-arm the validation gate after the attestation-failure recovery The previous run updated the no-mistakes gate to its final head but failed while writing the pipeline attestation against the closed inherited pull request, so a fresh run's gate push would have no ref work to do and trips the runner's up-to-date pipe defect; advance the branch by one explicit commit so the gate fast-forwards again. No code change. * no-mistakes(review): guard startup-replay against undelivered PostCompact stdout * test: cover compact hooks in grok guard inventory and drop unused local * no-mistakes(ci): Lint: fixed ShellCheck SC2034 in tests/fm-sessionstart-nudge.test.sh wait_for_stub_calls - the loop ran 'for i in 1 2 ... 20' without referencing i. Replaced with the repo's house-style count-only loop 'local _; for _ in $(seq 1 20)' (identical 20x0.2s polling). Reproduced the exact SC2034 on the pre-fix file with the pinned ShellCheck 0.11.0, then verified the fixed file passes shellcheck --norc --external-sources and bin/fm-lint.sh with full extended analysis (exit 0), and the full test file passes (36 ok, exit 0). PR must be raised via no-mistakes: attestation failure, not code - it reports the pipeline's test and document steps as skipped and resolves when the outer no-mistakes pipeline completes those phases and pushes; same finding was declined in an earlier round, so no code change made for it --------- Co-authored-by: Jon Roosevelt <[email protected]> Co-authored-by: Kun Chen <[email protected]>
Intent
Close the away-record/merge TOCTOU with an atomic cross-subsystem lock.
This is a hardening follow-up to the already-merged merge-safety build (firstmate PR #4199, "live-head merge gates and away task grants"). That build established two things this work builds on: a GitHub merge is refused unless the pull request is open, not a draft, mergeable, conflict-free, and every unwaived check is green at the exact live head, which is then bound with --match-head-commit; and while the away-posture record state/.afk-contract exists, a task's merge proceeds only if its meta yolo=on or its task id appears in that record's structured merge-grant list, with the grant lapsing when the record is archived at the captain's return.
The residual race: bin/fm-pr-merge.sh reads the away record (the per-task merge-grant check and the yolo/away-grant merge-authority decision) and THEN performs the merge, but the away record can change between that read and the merge - the record archives on captain return, or a grant is revoked - a TOCTOU window where a merge could proceed on stale away-authority. Close it so the authority check and the merge are atomic.
What Changed
Risk Assessment
Testing
The two live away-contract lock-contention scenarios passed. The remaining merge scenarios were covered only by executable tests using controlled GitHub/GitLab executables rather than live external repositories, so they do not establish live results.
Evidence: Live archive contention transcript
Source: Live archive contention transcript
Evidence: Live grant-revocation contention transcript
Source: Live grant-revocation contention transcript
Evidence: Targeted away-contract test transcript
Source: Targeted away-contract test transcript
Evidence: Targeted PR-merge test transcript
Source: Targeted PR-merge test transcript
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
🔧 **Rebase** - 1 issue found → auto-fixed ✅
bin/fm-pr-merge.sh- merge conflict rebasing onto origin/main🔧 Fix applied.
✅ Re-checked - no issues remain.
🔧 **Review** - 1 issue found → auto-fixed ✅
tests/fm-pr-merge.test.sh:111-github_verify_mergeablenow requires a non-emptybaseRefName, butwrite_github_rollup_jsonomits that field. All ten check-rollup scenarios therefore fail at the pre-merge state read instead of exercising their assertions; positive cases cannot merge. Add"baseRefName":"main"to this executable fixture, matching the other GitHub fixtures.🔧 Fix applied.
✅ Re-checked - no issues remain.
bash tests/fm-afk-contract.test.shbash tests/fm-pr-merge.test.shLive isolatedfm-afk-contract.sh archiveattempt while its cross-subsystem lock was held, followed by archive after releaseLive isolatedfm-afk-contract.sh confirmgrant-replacement attempt while its lock was held, followed by replacement after releasegit status --shortto verify testing left the worktree clean✅ **Document** - passed
✅ No issues found.
✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.