Skip to content

fix(merge): serialize away authority with synchronous merges - #4285

Merged
kunchenguid merged 4 commits into
mainfrom
fm/fm-mergesafety-away-merge-atomic-lock-r2
Sep 12, 2026
Merged

kunchenguid merged 4 commits into
mainfrom
fm/fm-mergesafety-away-merge-atomic-lock-r2

Conversation

@kunchenguid

@kunchenguid kunchenguid commented Sep 12, 2026 •

Copy link
Copy Markdown
Owner

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

  • Add a bounded cross-subsystem lock that serializes away-record confirmation and archival with merge-authority reads and synchronous forge commands.
  • Refuse GitHub and GitLab asynchronous or queue-dependent merge paths while away, failing closed when immediate execution or lock ownership cannot be proven.
  • Add regression coverage and documentation for lock contention, away-mode merge restrictions, and accepted residual race limits.

Risk Assessment

⚠️ Medium: The change correctly serializes supported away-record mutations with synchronous forge submission, but it remains concurrency-sensitive and retains the explicitly accepted queue-preflight and orphaned-child races.

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.

  • Live validation: ⚠️ inconclusive - 2 of 6 scenarios driven live against the product
Scenario Result Live Evidence
Captain return cannot archive the away record while merge authority is locked ✅ pass live Live archive contention transcript: archive exited 1, named the live lock holder, retained task-x1's grant, and succeeded after release.
Grant revocation cannot replace the away record while merge authority is locked ✅ pass live Live grant-revocation contention transcript: confirm exited 1 while locked, task-x1 remained granted, and task-other replaced it only after release.
A synchronous away-authorized merge keeps archive or revocation outside the authority-read-to-forge window ⏸️ untested no The prior payload established this only through mocked GitHub/GitLab executables, not the live product. A live external repository with merge credentials and controlled concurrent archive or revocatio…
A revocation that wins before the final authority read prevents the merge ⏸️ untested no The prior payload established this only through an executable test, not the live product. A live external repository with merge credentials and authority to coordinate revocation before the final read…
A merge refuses rather than proceeding when the away-record lock is unavailable ⏸️ untested no The prior payload established this only through an executable test, not the live product. A live merge target with valid forge credentials and authority to hold the away-record lock during the merge a…
Away posture permits immediate merges but rejects GitHub queue/auto and GitLab asynchronous paths ⏸️ untested no The prior payload established this only with controlled GitHub/GitLab executables, not live forge services. Live GitHub and GitLab repositories with merge credentials and the relevant queue, auto-merg…
Evidence: Live archive contention transcript

Source: Live archive contention transcript

SCENARIO: an operator returns while the away-authority lock is held
lock-holder-pid=40102
contended-archive-exit=1
contended-archive-output=fm-afk-contract: the away-posture record is locked by live process 40102 (an in-flight merge, or another change to this record); nothing was changed
live-grants-after-refusal=task-x1
archive-after-release=/var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T//fm-afk-live.4E6Y0A/state/afk-contracts/1789201362.afk-contract
final-state=archived-after-lock-release
Evidence: Live grant-revocation contention transcript

Source: Live grant-revocation contention transcript

SCENARIO: an operator revokes a grant while the away-authority lock is held
lock-holder-pid=60064
contended-confirm-exit=1
contended-confirm-output=fm-afk-contract: the away-posture record is locked by live process 60064 (an in-flight merge, or another change to this record); nothing was changed
live-grants-after-refusal=task-x1
fm-afk-contract: replaced the earlier away posture; its record is archived at /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T//fm-afk-live.cFEG1B/state/afk-contracts/1789201375-superseded-1789201377.afk-contract
live-grants-after-release=task-other
final-state=grant-replaced-after-lock-release
Evidence: Targeted away-contract test transcript

Source: Targeted away-contract test transcript

COMMAND: bash tests/fm-afk-contract.test.sh
ok - structural refusals name their missing part
ok - an omitted stop uses the no-stop marker and confirms
ok - the never-set flags listed concepts and their inflections without refusing, and never fires on unrelated names
ok - clause fields are recorded verbatim, and no static parser judges the wording
ok - clause fields preserve repeated spaces, tabs, newlines, and backslashes
ok - clause ids are input ordinals across accepted and refused clauses
ok - the read-back renders the words verbatim beside the accepted and refused lists
ok - words preserve their final newline shape in storage and read-back
ok - propose then confirm writes the record, announces hold-for-return only, and every read subcommand reflects it
ok - confirmation requires a read-back, and refresh leaves the standing record untouched
ok - a replacement archives the old mandate and keeps the session start
ok - a failed replacement keeps the standing posture live
ok - a failed final replacement publication rolls back its superseded archive
ok - validation and archive refuse incomplete clause rows by name
ok - validation and archive refuse blank decoded clause fields
ok - validation and archive refuse blank stop and refused text
ok - validation and archive refuse damaged words blocks
ok - archive keys the record by its entry time, empties the posture, and is idempotent
ok - malformed inputs and foreign record versions are refused rather than guessed
ok - merge grants round-trip through propose, confirm, read-back, and grants
ok - empty grants write the scalar form, and invalid or duplicate ids are usage errors
ok - a pre-field v1 record reads as empty grants rather than skipping the field
ok - malformed and duplicate merge-grant fields fail record validation
ok - archive removes live grants so archived copies are not consulted
ok - confirm and archive refuse while the record is locked, and proceed once it clears
Evidence: Targeted PR-merge test transcript

Source: Targeted PR-merge test transcript

COMMAND: bash tests/fm-pr-merge.test.sh
ok - fm-pr-merge reports exact queue retry flags after a zero-exit false success
ok - fm-pr-merge omits merge-queue retry guidance for a closed GitHub PR
ok - fm-pr-merge aggregates agreeing merge-queue rules
ok - fm-pr-merge reports ambiguity for conflicting merge-queue rules
ok - fm-pr-merge records pr= and pr_head= for a verified GitHub merge
ok - fm-pr-merge records pr= before the forge call can land the merge
ok - fm-pr-merge propagates a real merge failure without silently succeeding
ok - fm-pr-merge refuses a GitHub merge call that leaves the PR open and unqueued
ok - fm-pr-merge keeps PR bookkeeping when it cannot read a successful merge call's outcome
ok - fm-pr-merge refuses with the forge's own output quoted apart from its verdict
ok - fm-pr-merge quotes the forge output when it cannot read the outcome either
ok - fm-pr-merge does not echo back queue flags the caller already used
ok - fm-pr-merge still names retry flags when the caller used a different method
ok - fm-pr-merge names the queue requirement even when its method is unrecognised
ok - fm-pr-merge distinguishes unreadable branch rules from a base with no merge queue
ok - fm-pr-merge says nothing about a merge queue when the base branch has no queue rule
ok - fm-pr-merge accepts only a proved merge from the gh-axi fallback
ok - fm-pr-merge explains an armed auto-merge that landed nothing on a queue-less base
ok - fm-pr-merge never reports auto-merge as armed when the merge command failed
ok - fm-pr-merge claims no acceptance for a failed merge command carrying queue flags
ok - fm-pr-merge falls back to the gh-axi view when gh's read fails
ok - fm-pr-merge names a landed state hiding behind a failed GitHub merge command
ok - fm-pr-merge refuses a GitHub merge when gh is missing, before recording
ok - fm-pr-merge refuses a GitHub merge when gh is missing rather than merging blind
ok - fm-pr-merge verifies a genuinely merged GitHub pull request
ok - fm-pr-merge refuses to claim a merge when poll recording fails
ok - fm-pr-merge accepts and accurately reports a GitHub merge-queue entry
ok - fm-pr-merge explains how to retry with the required GitHub merge queue method
ok - fm-pr-merge refuses branch deletion unless --attended-override is passed
ok - fm-pr-merge refuses before merging when task meta is missing
ok - fm-pr-merge refuses malformed PR URLs before calling gh-axi
ok - fm-pr-merge refuses unsafe PR URL segments before recording state
ok - fm-pr-merge refuses repo override args before recording state
ok - fm-pr-merge refuses a bundled short-option repo override and refuses -d unless attended
ok - fm-pr-merge does not add default --squash when the caller passes an explicit merge method
ok - fm-pr-merge respects --method=<value> as an explicit merge method
ok - fm-pr-merge parses a GitHub PR URL into gh-axi number and --repo arguments
ok - fm-pr-merge refuses a caller --sha on GitHub because the head comes from the live read
ok - fm-pr-merge merges a GitLab merge request through glab instead of refusing it
ok - fm-pr-merge takes the GitLab instance from the URL rather than assuming one
ok - fm-pr-merge imposes no merge method on GitLab, leaving the project's own one
ok - fm-pr-merge refuses GitLab source-branch deletion unless --attended-override is passed
ok - fm-pr-merge propagates a real glab merge failure without silently succeeding
ok - fm-pr-merge refuses on each GitLab pre-merge condition independently
ok - fm-pr-merge reports every failing GitLab condition, not only the first
ok - fm-pr-merge reports a stale recorded head and verifies the live one
ok - fm-pr-merge refuses an unreadable GitLab merge request state rather than merging blind
ok - fm-pr-merge refuses a GitLab head commit it cannot validate
ok - fm-pr-merge refuses before recording anything when glab or jq is absent
ok - fm-pr-merge refuses a GitLab head override before recording state
ok - a merge a secondmate home performs itself is reported upward exactly once
ok - a locally routed secondmate home reports the landed PR into its parent's own channel
ok - a landed GitLab merge request is reported upward on the same channel
ok - a queued GitLab merge stays silent and leaves confirmation to the armed poll
ok - a refused or failed merge reports no outcome
ok - a GitLab merge refused before the forge call reports no outcome
ok - a merge a main home performs itself leaves one durable wake naming the PR
ok - a queued GitHub merge stays silent and leaves confirmation to the armed poll
ok - distinct merged PRs for one task retain distinct captain-facing wakes
ok - an uncommitted marker retry preserves at least one durable outcome
ok - a secondmate home that cannot report upward says so instead of merging in silence
ok - fm-pr-merge proceeds when the home carries no backlog at all
ok - fm-pr-merge refuses when the backlog exists but cannot be read
ok - fm-pr-merge refuses when its configured backend cannot be read
ok - fm-pr-merge refuses when its user backend configuration cannot be read
ok - fm-pr-merge refuses when its user backend configuration directory cannot be traversed
ok - fm-pr-merge proceeds once when its user configuration directory and backlog are genuinely absent
ok - fm-pr-merge honors a backend override over an unreadable user configuration
ok - fm-pr-merge refuses red GitHub checks and waives only a named --allow-red check
ok - fm-pr-merge merges when a failed check run was replaced by a passing re-run
ok - fm-pr-merge never lets a check run supersede a legacy status context
ok - fm-pr-merge still refuses when a check's current run failed after an earlier pass
ok - fm-pr-merge uses start order when the old success finishes last
ok - fm-pr-merge supersedes an old cancellation that finishes last
ok - fm-pr-merge keeps a check red while its re-run is still in flight
ok - fm-pr-merge never lets one check's pass clear another check's failure
ok - fm-pr-merge clears a failure only on a proven later pass of the same check
ok - fm-pr-merge keeps --allow-red scoped to its named check beside a superseded failure
ok - fm-pr-merge rechecks away presence before an attended red merge
ok - fm-pr-merge accepts exactly one separately named red-check waiver
ok - away merges require yolo or a grant, and --attended-override does not skip that
ok - away posture permits immediate merges but refuses every asynchronous path
ok - a grant does not bypass red checks, and a recorded pr= must match the URL
ok - an unreadable away-posture record refuses the merge instead of skipping the grant
ok - no away-record archive or grant revocation lands between the authority read and the merge
ok - a grant revoked before the merge's own authority read refuses the merge
ok - a merge that cannot lock the away record refuses instead of merging unlocked
ok - fm-pr-merge refuses --allow-red on GitLab
- Outcome: ⚠️ 1 warning across 1 run (4m26s)

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_mergeable now requires a non-empty baseRefName, but write_github_rollup_json omits 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 &#34;baseRefName&#34;:&#34;main&#34; to this executable fixture, matching the other GitHub fixtures.

🔧 Fix applied.
✅ Re-checked - no issues remain.

⚠️ **Test** - 1 warning
  • ⚠️ live validation verdict: inconclusive (2 of 6 scenarios were driven live against the product); untested: A synchronous away-authorized merge keeps archive or revocation outside the authority-read-to-forge window, A revocation that wins before the final authority read prevents the merge, A merge refuses rather than proceeding when the away-record lock is unavailable, Away posture permits immediate merges but rejects GitHub queue/auto and GitLab asynchronous paths
  • Live validation: ⚠️ inconclusive - 2 of 6 scenarios driven live against the product
Scenario Result Live Evidence
Captain return cannot archive the away record while merge authority is locked ✅ pass live Live archive contention transcript: archive exited 1, named the live lock holder, retained task-x1's grant, and succeeded after release.
Grant revocation cannot replace the away record while merge authority is locked ✅ pass live Live grant-revocation contention transcript: confirm exited 1 while locked, task-x1 remained granted, and task-other replaced it only after release.
A synchronous away-authorized merge keeps archive or revocation outside the authority-read-to-forge window ⏸️ untested no The prior payload established this only through mocked GitHub/GitLab executables, not the live product. A live external repository with merge credentials and controlled concurrent archive or revocatio…
A revocation that wins before the final authority read prevents the merge ⏸️ untested no The prior payload established this only through an executable test, not the live product. A live external repository with merge credentials and authority to coordinate revocation before the final read…
A merge refuses rather than proceeding when the away-record lock is unavailable ⏸️ untested no The prior payload established this only through an executable test, not the live product. A live merge target with valid forge credentials and authority to hold the away-record lock during the merge a…
Away posture permits immediate merges but rejects GitHub queue/auto and GitLab asynchronous paths ⏸️ untested no The prior payload established this only with controlled GitHub/GitLab executables, not live forge services. Live GitHub and GitLab repositories with merge credentials and the relevant queue, auto-merg…
  • bash tests/fm-afk-contract.test.sh
  • bash tests/fm-pr-merge.test.sh
  • Live isolated fm-afk-contract.sh archive attempt while its cross-subsystem lock was held, followed by archive after release
  • Live isolated fm-afk-contract.sh confirm grant-replacement attempt while its lock was held, followed by replacement after release
  • git status --short to verify testing left the worktree clean
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

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
@kunchenguid
kunchenguid merged commit 76d4405 into main Sep 12, 2026
14 checks passed
@kunchenguid
kunchenguid deleted the fm/fm-mergesafety-away-merge-atomic-lock-r2 branch September 12, 2026 18:54
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]>
msylergy added a commit to sylergydigital/firstmate that referenced this pull request Sep 14, 2026