Skip to content

fix(bin): send remote second mate steers over stdin - #7902

Merged
kunchenguid merged 4 commits into
kunchenguid:mainfrom
mehulbhagwani:fm/fm-up-7852
Oct 29, 2026
Merged

kunchenguid merged 4 commits into
kunchenguid:mainfrom
mehulbhagwani:fm/fm-up-7852

Conversation

@mehulbhagwani

@mehulbhagwani mehulbhagwani commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Intent

"Go upstream branch and accept those 6 points" - fix issue #7852 (fm-send to a remote second mate fails for large messages: the body travels as an SSH exec argument), which Kun’s triage labelled ready-for-pr, as a contribution Kun can merge.

What Changed

  • fm-send.sh no longer passes the remote steer body as an SSH exec argument. It now pipes the message through fm-on.sh --stdin to the host-local leg. This applies to the first attempt and to the retry after an exit code of 255. Large messages are no longer limited by the remote argv size (fixes fm-send to a remote second mate fails for large messages: the body travels as an SSH exec argument #7852).
  • fm-remote-secondmate-control.sh adds a send-stdin <id> [fire-and-forget] verb. The verb reads the message from stdin and rejects an empty or whitespace-only body. It then runs the same delivery path as send, which now lives in a shared cmd_send_body. Because the verb name is new, an older remote code root rejects the call with a usage error. It cannot mistake the mode word for the message body.
  • The fake SSH stubs in the remote delivery and second mate restart tests now forward stdin to the real leg and expect send-stdin. A new test sends a steer of about 46 KB while the fake SSH enforces a 32 KB argument limit. It checks that the body crosses the transport on stdin and arrives intact in the remote steering inbox. The fm-send.sh header comment now describes the stdin transport.

Risk Assessment

✅ Low: The change is small. It moves the remote steer body from the SSH exec argv to stdin, using the existing fm-on --stdin channel, which the remote side caps at 1 MiB. A new send-stdin subcommand name makes an older remote reject the call with a usage error instead of storing the wrong body. The body bytes are the same as before (printf '%s' on the parent, read -d '' on the remote), so deduplication still matches, and a test covers the large-message regression.

Testing

I drove the real fm-send -> fm-on -> OpenSSH sshd -> fm-remote-entrypoint -> job worker -> fm-remote-secondmate-control path in a disposable localhost lab. Stock OpenSSH accepts a 46 KB exec argument; the issue's Tailscale SSH did not. So I found where stock sshd rejects the argv form (about 250 KB) and reproduced the failure there. The pre-fix parent at that size gets 'transport lost twice; remote completion unknown': nothing lands remotely and a pending reply is left dangling, exactly as the issue reports. The fixed parent delivers 46 KB, 60 KB and 250 KB bodies with exit 0, and the full body is byte-exact in the remote inbox record. Multiline text with metacharacters and a literal 'fire-and-forget' line also arrives byte-exact. Fire-and-forget records carry their delivery id, and a re-send dedups onto the same record. A pre-fix remote code root rejects send-stdin with 'unknown command', fm-send exits 1, and no record is written. Empty or whitespace-only stdin, an invalid mode, and extra args are all refused. Older parents can still use the legacy argv send. Both changed test files pass. One info note covers teardown noise in the restart test. The lab was torn down. There is no UI surface, so the evidence is CLI transcripts.

  • Live validation: ✅ go - 8 of 8 scenarios driven live against the product
Scenario Result Live Evidence
Reproduce: a pre-fix parent sending a large steer to a remote second mate fails as transport loss and leaves delivery unknown ✅ pass live s1-prefix-fm-send-250kb.txt (base fm-send: ssh 255 twice, 'remote completion unknown', 0 inbox records, pending reply left)
A fixed parent sends a 46 KB steer (the issue's size) to a remote second mate and the full body lands in the remote steering inbox ✅ pass live s2-fixed-fm-send-big46.txt (exit 0, 002.msg contains full body)
A fixed parent sends a 250 KB steer that breaks the argv path and it is delivered, not reported as transport loss ✅ pass live s2-fixed-fm-send-big250.txt (exit 0, 001.msg 250140 bytes, full body present)
A multiline steer with shell metacharacters, unicode and a literal 'fire-and-forget' line arrives byte-exact (body is never confused with the mode argument) ✅ pass live s3-s5-bytes-fireandforget-idempotent.txt (S3)
A --fire-and-forget remote steer still records delivery=fire-and-forget with its delivery id, and a re-send dedups to the same record ✅ pass live s3-s5-bytes-fireandforget-idempotent.txt (S4, S5: record count 4 -> 4)
Adversarial version skew: a fixed parent steering a remote on pre-fix code fails loudly and never writes the mode word as the body ✅ pass live s6-version-skew-old-remote.txt ('unknown command: send-stdin', exit 1, inbox count unchanged, plain and fire-and-forget)
Adversarial: remote send-stdin refuses an empty or whitespace-only body, an invalid mode, and extra arguments ✅ pass live s7-s8-guards-legacy.txt (S7: exits 1/1/2, no records written)
Backward compatibility: an older parent's legacy argv 'send <id> <message>' still delivers to the fixed remote ✅ pass live s7-s8-guards-legacy.txt (S8: exit 0, 005.msg)
Evidence: Probe: stock OpenSSH still accepts a 46 KB argv body (the issue's lower limit came from Tailscale SSH)

Source: Probe: stock OpenSSH still accepts a 46 KB argv body (the issue's lower limit came from Tailscale SSH)

## S1 baseline: pre-fix argv contract (send <id> <message>) with a 46 KB body over a real OpenSSH sshd
$ fm-on.sh rsm fm-remote-secondmate-control.sh send rsm "<46022-byte body>"
notice: doorbell not typed because the agent in fm-remote:p1 has exited; the steer is durably recorded at /private/var/folders/81/55x2dv310px5drcswsjgh8qm0000gn/T/fm-lab-ssh.isWdXG/rhome/state/parent-route/rsm.inbox/001.msg for recovery
exit=0
remote inbox records: 1
Evidence: Pre-fix fm-send: 250 KB remote steer fails as 'transport lost twice', 0 records, dangling pending reply

Source: Pre-fix fm-send: 250 KB remote steer fails as 'transport lost twice', 0 records, dangling pending reply

## S1 pre-fix parent (base 417cec2f bin/fm-send.sh) sends a 250 KB steer to remote secondmate rsm over a real OpenSSH sshd
$ <base-checkout>/bin/fm-send.sh rsm "<250027-byte body>"
fm-gate-refuse: gate agent lifecycle permitted only against lab home /private/var/folders/81/55x2dv310px5drcswsjgh8qm0000gn/T/fm-lab-ssh.isWdXG/parent
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
●  WATCHER DOWN - SUPERVISION IS OFF
●  1 task(s) in flight, but no watcher has a fresh beacon (last beat: never, grace 300s).
●  Trust the emitted supervision protocol for this harness; do not use shell & for watcher repair.
●  This is a supervision warning only; the requested message WILL still be sent.
●  watcher supervision needs Stop-owned automatic recovery; inspect the hook registration and startup status before ending the turn.
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Read from remote host 127.0.0.1: Connection reset by peer
client_loop: send disconnect: Broken pipe
Read from remote host 127.0.0.1: Connection reset by peer
client_loop: send disconnect: Broken pipe
error: steer to remote secondmate rsm is unconfirmed (transport lost twice; remote completion unknown). Only the correlation-reusing resend below is idempotent and lands on the same remote inbox record:
FM_HOME=/private/var/folders/81/55x2dv310px5drcswsjgh8qm0000gn/T/fm-lab-ssh.isWdXG/parent FM_PENDING_REPLY_EXISTING_CORR=0d2cbf48321f2c0c /private/var/folders/81/55x2dv310px5drcswsjgh8qm0000gn/T/fm-lab-ssh.isWdXG/base/bin/fm-send.sh rsm BIG250K-BEGIN\ zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
exit=1 elapsed=13s
remote inbox records after: 0
parent pending-reply records:
0d2cbf48321f2c0c
Evidence: Fixed fm-send: 250 KB steer delivered via stdin, full body in remote record

Source: Fixed fm-send: 250 KB steer delivered via stdin, full body in remote record

## S2 fixed parent (a686f13e bin/fm-send.sh) sends the big250 steer (250026 bytes) to remote secondmate rsm over a real OpenSSH sshd
$ bin/fm-send.sh rsm "<big250 body>"
fm-gate-refuse: gate agent lifecycle permitted only against lab home /private/var/folders/81/55x2dv310px5drcswsjgh8qm0000gn/T/fm-lab-ssh.isWdXG/parent
WARNING: watcher still down (same stale episode; last beat: never, grace 300s) - full banner already printed this episode.
notice: doorbell not typed because the agent in fm-remote:p1 has exited; the steer is durably recorded at /private/var/folders/81/55x2dv310px5drcswsjgh8qm0000gn/T/fm-lab-ssh.isWdXG/rhome/state/parent-route/rsm.inbox/001.msg for recovery
exit=0 elapsed=15s
new remote inbox record: /private/var/folders/81/55x2dv310px5drcswsjgh8qm0000gn/T/fm-lab-ssh.isWdXG/rhome/state/parent-route/rsm.inbox/001.msg (250140 bytes)
full body present in remote record: True
record header lines: ['schema=fm-task-inbox.v1', 'at=2026-10-28T11:46:53Z', 'body-terminator=1', '--']
parent pending-reply records: f21b43b3c334f9a3 
Evidence: Fixed fm-send: 46 KB steer (issue size) delivered via stdin

Source: Fixed fm-send: 46 KB steer (issue size) delivered via stdin

## S2 fixed parent (a686f13e bin/fm-send.sh) sends the big46 steer (46024 bytes) to remote secondmate rsm over a real OpenSSH sshd
$ bin/fm-send.sh rsm "<big46 body>"
fm-gate-refuse: gate agent lifecycle permitted only against lab home /private/var/folders/81/55x2dv310px5drcswsjgh8qm0000gn/T/fm-lab-ssh.isWdXG/parent
WARNING: watcher still down (same stale episode; last beat: never, grace 300s) - full banner already printed this episode.
notice: doorbell not typed because the agent in fm-remote:p1 has exited; the steer is durably recorded at /private/var/folders/81/55x2dv310px5drcswsjgh8qm0000gn/T/fm-lab-ssh.isWdXG/rhome/state/parent-route/rsm.inbox/002.msg for recovery
exit=0 elapsed=5s
new remote inbox record: /private/var/folders/81/55x2dv310px5drcswsjgh8qm0000gn/T/fm-lab-ssh.isWdXG/rhome/state/parent-route/rsm.inbox/002.msg (46138 bytes)
full body present in remote record: True
record header lines: ['schema=fm-task-inbox.v1', 'at=2026-10-28T11:46:58Z', 'body-terminator=1', '--']
parent pending-reply records: 4100d1c5a4f47aeb f21b43b3c334f9a3 
Evidence: Byte-exact multiline body, fire-and-forget record, idempotent re-send

Source: Byte-exact multiline body, fire-and-forget record, idempotent re-send

## S3 multiline steer with shell metacharacters, a literal 'fire-and-forget' line, and a trailing newline
notice: doorbell not typed because the agent in fm-remote:p1 has exited; the steer is durably recorded at /private/var/folders/81/55x2dv310px5drcswsjgh8qm0000gn/T/fm-lab-ssh.isWdXG/rhome/state/parent-route/rsm.inbox/003.msg for recovery
exit=0
record: 003.msg
--- record ---
schema=fm-task-inbox.v1
at=2026-10-28T11:47:18Z
--
[fm-from-firstmate]⁣corr=3e6ce6809eeadf97 line one with $HOME `uname` "quotes" 'single' & | ; * ?
	indented line
unicode: café ✓ 日本
fire-and-forget
-- send rsm
--- end ---
message bytes present verbatim in record: True

## S4 fire-and-forget delivery id rides as the mode argument; body still on stdin
notice: doorbell not typed because the agent in fm-remote:p1 has exited; the steer is durably recorded at /private/var/folders/81/55x2dv310px5drcswsjgh8qm0000gn/T/fm-lab-ssh.isWdXG/rhome/state/parent-route/rsm.inbox/004.msg for recovery
exit=0
record: 004.msg (60164 bytes)
schema=fm-task-inbox.v1
at=2026-10-28T11:47:22Z
body-terminator=1
delivery=fire-and-forget
--
[fm-from-firstmate]⁣delivery=0123456789abcdef fire-and-forget body fffffffffffffffffffffffffffffffffffffffffffffffffff

## S5 idempotent rerun: same fire-and-forget id re-sent lands on the same record
notice: doorbell not typed because the agent in fm-remote:p1 has exited; the steer is durably recorded at /private/var/folders/81/55x2dv310px5drcswsjgh8qm0000gn/T/fm-lab-ssh.isWdXG/rhome/state/parent-route/rsm.inbox/004.msg for recovery
exit=0
inbox record count before=4 after=4
Evidence: Version skew: pre-fix remote rejects send-stdin loudly, no wrong record

Source: Version skew: pre-fix remote rejects send-stdin loudly, no wrong record

## S6 version skew: fixed parent (a686f13e) steers a remote whose code root is pre-fix (417cec2f)
$ bin/fm-send.sh rsm "skew plain ask"
error: unknown command: send-stdin
error: steer not sent to remote secondmate rsm (the remote steering-inbox record could not be written; the remote leg's stderr above has the reason)
exit=1
remote inbox records before=4 after=4
/private/var/folders/81/55x2dv310px5drcswsjgh8qm0000gn/T/fm-lab-ssh.isWdXG/rhome/state/parent-route/rsm.inbox/003.msg

$ bin/fm-send.sh rsm --fire-and-forget fedcba9876543210 "skew reconcile ask"
error: unknown command: send-stdin
error: steer not sent to remote secondmate rsm (the remote steering-inbox record could not be written; the remote leg's stderr above has the reason)
exit=1
remote inbox records before=4 after=4
/private/var/folders/81/55x2dv310px5drcswsjgh8qm0000gn/T/fm-lab-ssh.isWdXG/rhome/state/parent-route/rsm.inbox/003.msg
Evidence: send-stdin guards and legacy argv send compatibility

Source: send-stdin guards and legacy argv send compatibility

## S7 remote send-stdin guards (fixed remote, real sshd transport)
$ printf "  
	" | fm-on.sh --stdin rsm fm-remote-secondmate-control.sh send-stdin rsm
error: remote steer message must be nonempty
exit=1
$ printf "body" | fm-on.sh --stdin rsm fm-remote-secondmate-control.sh send-stdin rsm bogus-mode
error: invalid send delivery mode
exit=1
$ printf "body" | fm-on.sh --stdin rsm fm-remote-secondmate-control.sh send-stdin rsm fire-and-forget extra
exit=2 (usage)
remote inbox records before=4 after=4

## S8 legacy argv 'send <id> <message>' still accepted by the fixed remote (older parents keep working)
notice: doorbell not typed because the agent in fm-remote:p1 has exited; the steer is durably recorded at /private/var/folders/81/55x2dv310px5drcswsjgh8qm0000gn/T/fm-lab-ssh.isWdXG/rhome/state/parent-route/rsm.inbox/005.msg for recovery
exit=0
remote inbox records now=5
- Outcome: ⚠️ 1 info across 1 run (13m10s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

⚠️ **Review** - 1 info
  • ℹ️ bin/fm-remote-secondmate-control.sh:327 - In round 1 the user chose to remove the argument-count check that cmd_send repeated from the dispatcher (review-2). The current change brings back the same kind of duplicate in two places. The new cmd_send wrapper repeats [ &#34;$#&#34; -ge 2 ] &amp;&amp; [ &#34;$#&#34; -le 3 ] || usage, which the dispatcher already runs at line 463. The new cmd_send_stdin (line 333) repeats [ &#34;$#&#34; -ge 1 ] &amp;&amp; [ &#34;$#&#34; -le 2 ] || usage, which the dispatcher already runs at line 464. Each function has only one caller, its dispatcher arm. With the check gone, cmd_send only passes its arguments through. Fix: have the send dispatcher arm call cmd_send_body &#34;$@&#34; directly and delete the cmd_send wrapper. Also drop the count check inside cmd_send_stdin. Behavior does not change.
⚠️ **Test** - 1 info
  • ℹ️ tests/fm-secondmate-restart.test.sh - tests/fm-secondmate-restart.test.sh passes (exit 0, 24 ok), but its teardown prints about 191 'rm: ... Directory not empty' lines. Something still writes into the case's home/state while the temp root is removed, which is a cleanup race. This change did not cause it: the diff only touches the fake-ssh stdin handling in that file. It is still teardown noise, and the global quality bar asks for it to be fixed separately.
  • Live validation: ✅ go - 8 of 8 scenarios driven live against the product
Scenario Result Live Evidence
Reproduce: a pre-fix parent sending a large steer to a remote second mate fails as transport loss and leaves delivery unknown ✅ pass live s1-prefix-fm-send-250kb.txt (base fm-send: ssh 255 twice, 'remote completion unknown', 0 inbox records, pending reply left)
A fixed parent sends a 46 KB steer (the issue's size) to a remote second mate and the full body lands in the remote steering inbox ✅ pass live s2-fixed-fm-send-big46.txt (exit 0, 002.msg contains full body)
A fixed parent sends a 250 KB steer that breaks the argv path and it is delivered, not reported as transport loss ✅ pass live s2-fixed-fm-send-big250.txt (exit 0, 001.msg 250140 bytes, full body present)
A multiline steer with shell metacharacters, unicode and a literal 'fire-and-forget' line arrives byte-exact (body is never confused with the mode argument) ✅ pass live s3-s5-bytes-fireandforget-idempotent.txt (S3)
A --fire-and-forget remote steer still records delivery=fire-and-forget with its delivery id, and a re-send dedups to the same record ✅ pass live s3-s5-bytes-fireandforget-idempotent.txt (S4, S5: record count 4 -> 4)
Adversarial version skew: a fixed parent steering a remote on pre-fix code fails loudly and never writes the mode word as the body ✅ pass live s6-version-skew-old-remote.txt ('unknown command: send-stdin', exit 1, inbox count unchanged, plain and fire-and-forget)
Adversarial: remote send-stdin refuses an empty or whitespace-only body, an invalid mode, and extra arguments ✅ pass live s7-s8-guards-legacy.txt (S7: exits 1/1/2, no records written)
Backward compatibility: an older parent's legacy argv 'send <id> <message>' still delivers to the fixed remote ✅ pass live s7-s8-guards-legacy.txt (S8: exit 0, 005.msg)
  • Built a disposable OpenSSH sshd (/usr/sbin/sshd, OpenSSH 10.3) on 127.0.0.1 with lab host and client keys. The client used a lab ssh_config through FM_SSH_BIN. The real bin/fm-remote-entrypoint.sh was on the remote PATH, and a lab-started fm-remote-job-worker.sh used an isolated FM_REMOTE_JOB_STATE_ROOT.
  • Parent home minted with bin/fm-lab-home.sh create. The remote secondmate home was seeded in the lab. The gate env (NO_MISTAKES_GATE etc.) was unset per the runbook.
  • fm-on.sh rsm fm-remote-secondmate-control.sh send rsm &lt;N-byte body&gt; size probe: 46 KB and 150 KB accepted, 250 KB and 400 KB fail with ssh 255 'Connection reset by peer'
  • Pre-fix parent &lt;base 417cec2f&gt;/bin/fm-send.sh rsm &lt;250 KB body&gt;
  • Fixed parent bin/fm-send.sh rsm &lt;250 KB body&gt; and bin/fm-send.sh rsm &lt;46 KB body&gt;
  • bin/fm-send.sh rsm <multiline body with shell metacharacters, unicode, a literal fire-and-forget line, trailing newline>
  • bin/fm-send.sh rsm --fire-and-forget 0123456789abcdef &lt;60 KB body&gt;, sent twice to check idempotence
  • Version skew: fixed parent bin/fm-send.sh rsm ... (plain and --fire-and-forget) against a remote code root checked out at base 417cec2f, through the same sshd
  • fm-on.sh --stdin rsm fm-remote-secondmate-control.sh send-stdin rsm with whitespace-only stdin, a bogus mode, and too many args
  • Legacy fm-on.sh rsm fm-remote-secondmate-control.sh send rsm &lt;msg&gt; against the fixed remote
  • bash tests/fm-send-remote-delivery.test.sh
  • bash tests/fm-secondmate-restart.test.sh
  • Checked that herdr session fm-remote stayed stopped throughout (the doorbell never reached a live pane). Killed sshd and workers, then removed the lab.
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@greptile-apps

greptile-apps Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; the remaining test gap is non-blocking.

Reviews (2) · Last reviewed commit: "no-mistakes(ci): Two tests failed in CI...." · Reviewed by Greptile

Comment on lines +245 to +248
if expected not in stdin_payload:
raise SystemExit("the large remote steer did not cross the SSH transport on stdin")
if expected not in record:
raise SystemExit("remote inbox record omitted the large steer body")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Extra message text passes unnoticed

The new test only checks whether expected appears inside the transport payload and inbox record. A duplicate message or unwanted trailing text would still pass. The fixture also has no newlines, so it cannot catch lost trailing newlines.

Use a multiline fixture with trailing newlines and compare the complete received body, accounting for the expected marker and correlation token.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

…e other is not. 1. Behavior portable serial 5: `tests/fm-secondmate-reconcile.test.sh` failed with "supervision did not deliver the durable reconcile request later". This PR caused it. The PR now sends a remote steer's body on stdin, using `fm-on.sh --stdin` with the `send-stdin` verb. This test's fake ssh started with `cat > /dev/null`, so it threw the body away before it ran the real `fm-remote-secondmate-control.sh`. `cmd_send_stdin` then read an empty message, died with "remote steer message must be nonempty", and no inbox record was written. Rule that broke: a fake ssh that runs the real remote leg must pass the caller's stdin through, as real ssh does. I checked every fake ssh that runs the real leg. `fm-send-remote-delivery.test.sh` already passes stdin through. `fm-secondmate-sync.test.sh` (`make_remote_leg_ssh_stub`) had the same discard line. The stub in `fm-send-resolve-key.test.sh` never runs the leg, so it is fine. The fix deletes the `cat > /dev/null` line in the reconcile and sync stubs. Calls made without `--stdin` still get /dev/null from fm-on, so nothing else changes. Checks run locally: the reconcile test fails before the fix with the same CI message. After the fix, the reconcile test passes (rc=0) and the sync test passes (rc=0). 2. Behavior portable serial 3: `tests/fm-wake-queue.test.sh` failed in `test_concurrent_append_and_drain` with "wake drain: queue lock could not be acquired safely". This PR did not cause it. The PR does not touch `bin/fm-wake-drain.sh`, the wake tests or the wake helpers. The failure is lock contention: 40 appenders run at the same time as a drain, on a loaded CI runner. Locally the whole test passed (70 ok, rc=0). I made no change for it. It is an existing flake in wake-queue lock acquisition and needs its own fix outside this PR. Open PR kunchenguid#7912 ("preserve wake grants when queue-lock acquisition fails") works in the same area
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thank you @mehulbhagwani. This is a tidy fix for #7852, and finding where stock sshd actually breaks (about 250 KB) to reproduce the bug against real OpenSSH was a nice touch.

What I checked (head 26e2a79e, main 417cec2f): fm-send.sh now pipes the body through the existing fm-on.sh --stdin channel to a new send-stdin verb, on both the first attempt and the 255 retry. The argv carries only the id and the optional fire-and-forget. cmd_send_stdin reads the whole body (read -r -d ''), refuses an empty or whitespace-only body, and hands off to the shared cmd_send_body, so dedup, delivery ids and the doorbell are unchanged. Legacy argv send still works for older parents. A new parent talking to an older remote code root fails loudly with "unknown command" and writes nothing, which is the safe direction. The three fake-ssh stubs now pass stdin through, as real ssh does, and that explains the earlier serial-5 red. tests/fm-send-remote-delivery.test.sh passes locally on this head. No workflow, network or credential changes.

Greptile's P2 is optional. It suggests comparing the complete received body with a multiline fixture that has trailing newlines, instead of a substring match. Your live S3 already shows byte-exact multiline delivery. Adding it to the test would be a nice follow-up if you push again, but it doesn't block anything.

For context, #7610 edits the same fm-on.sh ... send lines in fm-send.sh for a different goal (an explicit sent: confirmation). It's not the same fix, so I'm only noting it for sequencing.

State: the no-mistakes check passes on this head, Greptile is 5/5, and live validation is 8/8. CI run 40696393211 is partly green and still running behind today's Actions backlog. If it finishes green and the PR is still clean, it's ready to merge on a later pass.

contract-class: restore. Remote steer delivery to a second mate is an existing default path, and it broke for large bodies. The same delivery now works at any size up to the existing stdin cap. VISION: aligns rule by rule. One captain: no phantom "transport lost" on long steers. Authority: unchanged. Scripts/agents: transport mechanics stay in scripts. Restart: the durable remote record is unchanged. Delegation: version skew refuses instead of misdelivering. Vendor: plain ssh, no Tailscale-specific behavior. Scope: inside the existing send leg.

Nothing is needed from you right now. This is waiting on CI.

@kunchenguid
kunchenguid merged commit 4415321 into kunchenguid:main Oct 29, 2026
21 checks passed
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: this is merged. Thank you @mehulbhagwani — really appreciate you taking the time on this.

trillium added a commit to trillium/firstmate that referenced this pull request Nov 3, 2026
* feat(bin): opt-in spawn base from the primary checkout for local-only work (#7352)

* feat(bin): add opt-in config/spawn-base-primary-checkout for local landings

A fresh pooled task worktree is reset to origin/<default>. A local-only
project lands work on the primary checkout's default branch through
fm-merge-local.sh and never pushes, so that ref stays frozen at the last
push and every fresh task starts behind work already landed, loading the
project's instruction files from the stale tree. The always-on fix proposed
in #3812 replaced the specified origin-only refresh for every home; this
rework keeps that rule as the default and moves the new base behind an
explicit, default-off presence flag, following the existing config/<flag>
pattern.

With config/spawn-base-primary-checkout present:
- fm-spawn.sh starts a fresh local-only ship, or a scout without
  --base-branch, from the primary checkout's <default> when it strictly
  contains origin's tip. Publishing modes and named base branches keep
  origin's tip, because that work is delivered against origin. A diverged
  primary keeps origin's tip and prints a note counting both sides. The
  commit is read from the local object store, so nothing extra is fetched,
  and the clean-slot refusal still runs first.
- fm-review-diff.sh anchors a remote-backed task without base_branch= on the
  branch it delivers to: publishing modes stay on origin/<default>, while a
  local-only ship or a scout is compared against whichever of the local
  <default> and origin/<default> meets the branch later, so the review shows
  the task's own work instead of every locally landed commit.
- fm-promote.sh tells a scout promoted to a publishing mode to return to
  origin's default branch, because in this home the scout may have started
  from the primary checkout's branch, whose unpushed commits would otherwise
  be published with the work.

fm-dod-lib.sh gains fm_mode_publishes as the one predicate those three
readers share. Without the flag every path is unchanged: the spawn resets
to origin's tip, the review anchors on origin/<default>, and promotion keeps
its wording; the existing tests run unmodified. Treehouse 3 (verified on
3.1.3) already hands a slot out at whichever of the local and remote default
branch is further ahead, so with the flag the refresh keeps that slot where
Treehouse put it for a local landing instead of rewinding it, and a project
without origin is untouched as before.

Supersedes #3812.

* no-mistakes(document): Drop change-relative wording from spawn-base config docs

* no-mistakes(ci): The Greptile Review check failed on two review findings, not on a broken build or test. I fixed both as the user directed, and the tests and lint pass. ci-1 (bin/fm-promote.sh): promotion must name origin's default branch only when spawn could actually have started the scout from the primary checkout. Spawn does that only when the project has an origin remote and is recorded on the task. Before this fix, the opt-in flag alone made promotion to no-mistakes or direct-PR say "copy of origin's default branch...", even on a project with no origin. - The new wording now also requires a recorded project (`[ -n "$PROMOTE_PROJECT" ]`) whose `git remote get-url origin` succeeds. That is the same check bin/fm-review-diff.sh already makes. The empty-project guard is needed because `git -C ""` would run in the current directory. Otherwise the existing "default-branch base" wording stays. - The three places that read the flag now agree: spawn, review-diff and promote. - I updated the header and inline comments in fm-promote.sh, and the promote line in docs/configuration.md, to say this applies only to a project with an origin remote. - Test: `test_promote_names_origin_for_a_publishing_mode_in_an_opted_in_home` in tests/fm-task-delivery.test.sh now records a real `project=` with a registry entry, and covers flag on/off × origin/none × direct-PR/no-mistakes/local-only. Only flag on + origin + a publishing mode gets the new wording. The named-base case is unchanged. - Before the fix, the test fails with "not ok - flag on, remote none, direct-PR: the promotion changed the default-branch wording". With the fix, it passes. ci-2 (tests/fm-spawn-pool-base-freshen.test.sh): with the flag set, both publishing modes must start from origin's tip and print no divergence note. - The opted-in spawn test now covers no-mistakes as well as direct-PR, local-only and scout. - The expectations no longer single out direct-PR. Both publishing modes now expect origin's tip, no "note: pooled worktree", and a review anchored at the slot's start, in the leading, diverged and trailing cases. Verification: - `bash tests/fm-task-delivery.test.sh`: exit 0. - `bash tests/fm-spawn-pool-base-freshen.test.sh`: exit 0. - `bin/fm-lint.sh` on the three changed shell files: exit 0 (ShellCheck 0.11.0, pinned, with extended analysis)

* fix: preserve whitespace when proving patches landed (#7910)

* fix: report unavailable Git containment proofs during teardown (#7915)

* fix(teardown): distinguish unavailable content-landed proof

* no-mistakes(document): Clarify teardown proof failure documentation

* no-mistakes(ci): Captain, CI failed in unchanged watcher recovery code, independent of this PR. The focused failing case passed locally with exit 0. The full suite stalled earlier and was stopped. No tracked changes. Command guard rejected cleanup; scratch remains at .ci-7915/ and tests/.ci-7915-cycle.sh

* chore: untrack CI validation scratch

* feat(bin): prefer a configured provider family in dispatch resolution (#7876)

* feat(dispatch): prefer configured provider family

* no-mistakes(review): drop policy_why field and dead auth fixture from preference tests

* no-mistakes(document): docs: record preferred_provider in schema, diagnostics, verification

* fix: pin local-only merges to the accepted done commit (#7916)

* fix: pin local-only landing to its accepted done head

Persist the accepted local-only commit in task metadata and refuse landing when the branch or the recorded head changes. Merge the full commit ID under the task control and metadata locks.

Closes https://github.com/kunchenguid/firstmate/issues/7782

* no-mistakes(test): Refuse local landing races with atomic ref transactions

* no-mistakes(document): Document pinned local landing and recovery contracts

* no-mistakes(ci): Applied only the verified incremental patch and preserved existing repairs. Complete diff matches the supplied candidate hash. Both focused test files, default lint, and source-aware lint passed with exit 0. Evidence retained at /tmp/up7782-local-repair/ci-phase-fresh-*. No commits, pushes, or pipeline-control actions performed; publication remains with the outer executor

* no-mistakes(ci): Fixed both SC2031 false positives in tests/fm-merge-local.test.sh with narrowly scoped suppressions. Tier 2 lint correction; runtime changes were unnecessary. Default lint, source-aware lint, all 8 focused tests, and git diff --check passed. No commits, pushes, or pipeline-control actions performed

* fix: coalesce repeated extension host errors (#6548) (#7928)

* fix(procevent): coalesce unhandled extension host errors

* no-mistakes(document): Document host-error coalescing and recovery semantics

* fix: preserve wake grants when queue-lock acquisition fails (#7912)

* fix: stop wake grants when lock acquisition fails

* no-mistakes(document): Document wake grant lock acquisition failure behavior

* fix(bin): send remote second mate steers over stdin (#7902)

* fix: send remote steers over stdin

* fix: version remote stdin send protocol

* no-mistakes(document): document stdin transport for remote steer in fm-send header

* no-mistakes(ci): Two tests failed in CI. One is caused by this PR; the other is not. 1. Behavior portable serial 5: `tests/fm-secondmate-reconcile.test.sh` failed with "supervision did not deliver the durable reconcile request later". This PR caused it. The PR now sends a remote steer's body on stdin, using `fm-on.sh --stdin` with the `send-stdin` verb. This test's fake ssh started with `cat > /dev/null`, so it threw the body away before it ran the real `fm-remote-secondmate-control.sh`. `cmd_send_stdin` then read an empty message, died with "remote steer message must be nonempty", and no inbox record was written. Rule that broke: a fake ssh that runs the real remote leg must pass the caller's stdin through, as real ssh does. I checked every fake ssh that runs the real leg. `fm-send-remote-delivery.test.sh` already passes stdin through. `fm-secondmate-sync.test.sh` (`make_remote_leg_ssh_stub`) had the same discard line. The stub in `fm-send-resolve-key.test.sh` never runs the leg, so it is fine. The fix deletes the `cat > /dev/null` line in the reconcile and sync stubs. Calls made without `--stdin` still get /dev/null from fm-on, so nothing else changes. Checks run locally: the reconcile test fails before the fix with the same CI message. After the fix, the reconcile test passes (rc=0) and the sync test passes (rc=0). 2. Behavior portable serial 3: `tests/fm-wake-queue.test.sh` failed in `test_concurrent_append_and_drain` with "wake drain: queue lock could not be acquired safely". This PR did not cause it. The PR does not touch `bin/fm-wake-drain.sh`, the wake tests or the wake helpers. The failure is lock contention: 40 appenders run at the same time as a drain, on a loaded CI runner. Locally the whole test passed (70 ok, rc=0). I made no change for it. It is an existing flake in wake-queue lock acquisition and needs its own fix outside this PR. Open PR #7912 ("preserve wake grants when queue-lock acquisition fails") works in the same area

* fix(bin): stop herdr server_ensure from starting servers an external owner manages (#7357)

* fix(herdr): never start a server an external owner manages or is replacing

fm_backend_herdr_server_ensure started a detached herdr server whenever
status reported the session not running. When a service manager owns the
server, that races a unit restart or a server live-handoff and splits panes
across two servers.

The session directory reported by herdr session list can now carry a
firstmate-server-owner marker (persistent, naming the owner) and a
firstmate-server-replacing marker (for the duration of a restart or handoff).
While either exists and the server is not running, server_ensure never starts
a server: it waits a bounded time (FM_BACKEND_HERDR_EXTERNAL_SERVER_POLLS,
default 30s) for the server to report running, and otherwise fails naming the
owner or the replacement. A running server is still used at once, and a
session with no marker keeps the Firstmate-owned autostart unchanged.

Fixes #7320

* no-mistakes(review): Enforce herdr replacement marker on fast path; fixed wait bound

* no-mistakes(ci): Both CI failures had one cause in this PR, and I fixed it in code; no test assertions changed. `fm_backend_herdr_server_ensure` had started running `herdr session list --json` on every call to find the session directory for the ownership markers. Two existing tests treat that call as a sign of something else: - `tests/fm-control-relaunch.test.sh` failed with "a herdr reclaim touched a session the record does not name: session list --json", because it allows only `--session fmlab` calls and `status --json`. - `tests/fm-backend-herdr-presentation-e2e.test.sh` failed with "opted-out spawn added presentation-ordering capability or socket calls", because there `session list` means presentation ordering ran. Invariant: `server_ensure` must not make Herdr calls beyond its own `status` read, so ordinary spawns and reclaims stay free of `session list` and only touch the session they name. Every caller goes through `server_ensure`, so fixing it there covers all of them. Fix (`bin/backends/herdr.sh`): the session directory now comes from the `status --json` read `server_ensure` already makes. It is the directory containing `.server.socket`. I removed the `fm_backend_herdr_session_dir` helper. On a running server, the only added work is one check for the replacement marker, which is what the user asked for. I checked this against real Herdr 0.9.5: - `status` reports the socket even when the server is stopped, for both the default and named sessions. - The socket's directory is the same `session_dir` that `session list` reports, and it follows `XDG_CONFIG_HOME`. - With `--session`, an inherited `HERDR_SOCKET_PATH` does not change it. - The read creates nothing on disk. If a Herdr version omits the socket, `server_ensure` keeps the old Firstmate-owned behavior, as the docs already said for a missing `session_dir`. Other changes: the marker-test fakes now report the socket under the session directory, and I removed the `session list` stub this PR had added to the shared fake. `docs/herdr-backend.md` and `docs/verification/runtime-backends.md` ("Session directory") now describe and record the `status`-socket measurement. Verification: - `tests/fm-backend-herdr.test.sh` passes: 239 ok, 0 not ok, including all the externally-managed and replacement-marker tests. - `tests/fm-control-relaunch.test.sh` passes; it was the shard 3 failure. - shellcheck shows only existing info-level notes. Not verified locally: the real-Herdr presentation test. Here it stopped earlier, at an unrelated Treehouse timeout ("treehouse get did not enter an isolated worktree within 60s"). After the fix `server_ensure` no longer runs `session list`, which is the call that assertion caught. No lab session was left running, and I removed the test's temp directory

* fix: reset idle backoff for actionable heartbeat wakes (#7903)

* fix: classify actionable heartbeat backstop as a check

* no-mistakes(document): Correct heartbeat routing docs and remove stale test count

* fix: preserve heartbeat routing when resetting actionable backoff

* fix(bin): reclaim a live watch lock whose pid-identity no longer recomputes (#7931)

* fix(bin): reclaim a lock whose recorded pid-identity no longer recomputes

#7886 made fm_lock_holder_alive reject a live pid whose start time no
longer matches the lock's recorded pid-start. A holder that predates that
record still falls back to pid liveness, which leaves issue #7801 open: on
a /proc-less host outside UTC, a watcher started before fm_pid_identity
pinned TZ=UTC0 recorded a local-time pid-identity. After the update that
live holder no longer matches its own identity, so the health predicate
rejects it, yet every new watcher stands down beside it and the home stays
unsupervised.

fm_lock_holder_alive now also requires a recorded pid-identity, when
present, to still recompute for the pid, after the existing start-time
check and with the same missing-evidence fallbacks: no record, a pid
rewritten mid-read, or an unreadable value keeps the pid-liveness answer.
Both records go through one helper, _fm_lock_record_matches. Only
long-lived holders that never exec write a pid-identity (the watcher, the
supervise daemon), so a genuine holder still matches. A watcher replaced
this way stands down unsignalled at its next poll through the existing
self-eviction. The fm_pid_identity comment and docs/turnend-guard.md
claimed the upgrade-window residual is cleared by the post-update restart,
which never reaches a primary home's own watcher; they now say the next
lock claim clears it.

Verification:
- Drove: real bin/fm-watch.sh processes with /proc hidden through
  FM_PROC_ROOT_OVERRIDE and TZ=America/Los_Angeles: a live genuine watcher
  whose lock record was rewritten to its own local-time ps lstart identity
  with no pid-start, as a pre-pin build wrote it, then a fresh watcher;
  plus fm_lock_try_acquire against a live pid with a mismatched, matching,
  and unrecorded pid-identity and no pid-start.
- Observed: on the unchanged library the fresh watcher exits "lock held by
  live pid ... but heartbeat is stale" and fm_lock_try_acquire returns
  held for the mismatch. With this change the fresh watcher takes the
  lock, the legacy holder exits 0 by standing down, the live pid is never
  signalled, and matching or unrecorded identities stay held.
- Re-check: tests/fm-watcher-lock.test.sh cases
  test_watch_replaces_live_holder_with_legacy_local_time_identity and
  test_lock_reclaims_holder_whose_identity_no_longer_recomputes.

* no-mistakes(review): Limit pid-identity lock reclaim to the watch lock

* no-mistakes(document): Correct fm_lock_holder_alive comment on non-watch identity locks

* no-mistakes(ci): I made two small fixes. CI and "Require no-mistakes" never ran: GitHub shows both as `action_required`, waiting for approval to run workflows from a fork, so the code didn't cause those. Greptile failed because it scored the PR 4/5 against a required 5/5, with one P2 comment. 1. **Greptile P2, test children left running (`tests/fm-watcher-lock.test.sh`).** The two new lock tests start a `sleep 300` holder that only gets killed after every assertion passes, and the suite's cleanup only reaps processes whose command line contains the fixture root. Each holder now starts as `(exec -a "$dir/holder" sleep 300)`, so cleanup reaps it if the test fails early. To check, I forced a `fail` right after the child starts: on HEAD the `sleep 300` was still running afterwards, and with the fix it was reaped. Both tests pass normally. 2. **Flaky takeover test (`bin/fm-watch.sh`).** This edit was already uncommitted in the worktree. Twelve isolated runs passed without it, so I first dropped it as out of scope, but the full suite then failed on exactly this race. When a successor takes over a live watcher's lock, it deletes the lock and recreates it while holding `.watch.lock.steal`. If the old watcher checks during that gap, it sees no lock `pid` and exits as "state directory was torn down", not by standing down cleanly as the PR intends. That race only happens once this PR lets a healthy, live watcher's lock be taken. The guard treats a missing `pid` as teardown only when no `.steal` marker exists, with a comment explaining why. With it restored, 15 runs of the takeover test (three at a time, to add load) all passed, and all three PR tests passed in the full suite. **Remaining failures:** with the guard restored, I ran the full suite three times and it failed each time, but always on tests this change doesn't touch: "bounded child cleanup regression" twice and "bounded ledger cycle 2 did not start" once. The host's load average was about 100, and these tests depend on timing; one of them runs before any watcher starts. I didn't confirm they also fail on the base commit. shellcheck reports nothing in the test file beyond info notes about files it didn't follow, and one existing warning in `fm-watch.sh` at line 2598, not from this change. I deleted the leftover temporary runner `tests/.tmp-one.sh`. Nothing is committed or pushed

* fix(bin): re-read the watch lock holder after the steal check

The steal-gap guard read the lock pid, then the steal mutex. A successor
that removed and relinked the lock between those reads let the old
watcher see no pid and then no steal mutex, so it exited as "state
directory was torn down" instead of standing down. Upstream CI hit this
in tests/fm-watcher-lock.test.sh
(test_watch_replaces_live_holder_with_legacy_local_time_identity).

The teardown branch now re-reads the pid after the steal mutex. The
steal mutex is held for the whole remove-and-relink, so a steal that
finished between the first two reads has already relinked the lock by
the third read, and the self-eviction below stands the watcher down.

Verification:
- Drove: the takeover test (real bin/fm-watch.sh processes) 48 times,
  six at a time, with and without this change, plus the whole
  tests/fm-watcher-lock.test.sh file.
- Observed: the interleaving is too narrow to hit locally (48 of 48
  passed either way); the whole file passes with this change. The
  failing CI run shows the old watcher's exit 1 teardown message.
- Re-check: Behavior portable serial 6 on this PR's CI.

* no-mistakes(review): Scope fm_pid_identity residual comment to the watch lock

* no-mistakes(review): Align fm_pid_identity residual comment with autoarm reclaim behaviour

* no-mistakes(document): Note watch-lock identity mismatch skips lock stale grace

* fix(bin): tell a released watch lock from a torn-down state directory

A watcher replaced by a successor still exited 1 as "state directory was
torn down" on upstream CI. The successor that reclaims the lock delivers
its recovery wake and exits, releasing the lock, and on a fast runner
that happens before the old watcher's next poll. The old watcher then
found no lock holder and no steal in progress, which the teardown check
read as a recreated state directory.

The watcher now holds its state directory open (fd 6) from startup, and
a lock with no holder is a teardown only when the directory at that path
is no longer the one it holds; otherwise the lock was released by a
successor and the self-eviction stands the watcher down with exit 0. The
held descriptor keeps the inode from being reused by a recreated
directory. A host that cannot open a directory keeps the old reading.
This replaces the steal-marker check and pid re-read, which only covered
a successor still relinking the lock.

Verification:
- Drove: real bin/fm-watch.sh processes. A new regression,
  test_watch_replaced_holder_stands_down_after_successor_exits, pauses
  the old holder (SIGSTOP, only while it holds no other state lock) until
  the successor has delivered its wake and exited, then resumes it. Also
  a standalone run with the old watcher polling every 5s.
- Observed: on the previous head the old watcher exits 1 "state
  directory was torn down (singleton lock removed)", the CI failure,
  every time; with this change it exits 0 by standing down. Both
  takeover tests passed 20 of 20 runs four at a time on one loaded CPU.
  The teardown tests in tests/fm-watch-arm.test.sh (state directory and
  home removed) still pass.
- Re-check: tests/fm-watcher-lock.test.sh and Behavior portable serial 6.

* no-mistakes(test): Hold the watcher's state directory open before claiming the lock

* no-mistakes(document): Docs already match watch-lock identity reclaim change

---------

Co-authored-by: mangocabs2025 <250559406+mangocabs2025@users.noreply.github.com>

* fix(bin): fall back to perl when timeout is not GNU coreutils (#7911)

* Fix non-GNU timeout fallback

* no-mistakes(review): Assert INT reaches watcher in non-GNU timeout fallback test

* no-mistakes(document): Document GNU-only timeout selection in watch checkpoint

* no-mistakes(ci): Greptile flagged that only the non-GNU-timeout-to-Perl path had an isolated test. I added two isolated tests in tests/fm-watch-checkpoint.test.sh, as you asked. The production code is unchanged. The rule being tested: run_bounded must run GNU `timeout` first, then GNU `gtimeout`, then Perl. Whichever GNU command it runs must receive `--signal=INT --kill-after=<bound>s <seconds> <watcher>`. What changed: - **Shared setup:** a new helper, `make_isolated_checkpoint`, copies the checkpoint into a temporary root. It also builds a PATH that holds only the named host tools, so the stubs decide which timeout is found. The existing Perl-fallback test now uses this helper too. Its assertions are the same. - **Stubs:** a non-GNU stub reports `uutils` for `--version` and exits 137 if it is ever used. A GNU stub reports `GNU coreutils` and writes its own name and arguments to `$FM_HOME/timeout-calls`, then exits 124. - **`test_gnu_timeout_runs_the_watcher_bound`:** GNU `timeout` and GNU `gtimeout` are both on PATH. The test asserts exit 124, the quiet checkpoint line, and exactly one call: `timeout --signal=INT --kill-after=5s 1 <root>/bin/fm-watch.sh`. - **`test_non_gnu_timeout_uses_gnu_gtimeout`:** a non-GNU `timeout` is next to a GNU `gtimeout`. The test asserts the same exact call, made by `gtimeout`. - In both new tests, Perl is not on PATH. So if the code picked Perl by mistake, the run would fail with 127. How I checked it: - The full test file passes: all 14 tests. - I broke the code on purpose twice. When I swapped the order to try `gtimeout` first, the GNU timeout test failed. When the code always picked Perl, the run exited 127 instead of 124. I then put the production file back; `git status` shows only the test file changed. - `shellcheck -x` passes on the test file. This is a change to tests only, so there is nothing a user would see to check by hand

* fix: recover ownerless extension readiness records (#7933)

* fix: recover ownerless extension readiness and announce cleanup refusals

* no-mistakes(review): Reset cleanup failure episodes and classify failure wakes

* no-mistakes(document): Document ownerless readiness recovery and cleanup failure wakes

* no-mistakes(document): Clarify cleanup failure documentation ownership

---------

Co-authored-by: Kun Chen <3233006+kunchenguid@users.noreply.github.com>

* fix(bin): keep failed or non-schema remote reply reads out of captures (#7874)

* Keep malformed remote reply captures from wedging

* no-mistakes(document): Fix garbled remote reply source failure comment

* no-mistakes(document): Document remote reply failure handling

---------

Co-authored-by: Pitch Perfekt Collective <pitchperfekt@Pitchs-Mac-Studio.local>

* feat(bin): add per-project pr=manual registry token for worker-written PR text (#7937)

* feat(bin): per-project pr=manual registry token for hand-written PR text

A no-mistakes ship on a project where an outside maintainer reviews the PR let
the pipeline's pr step rewrite the hand-written title and body on every
validated push. The registry now records pr=manual, resolved by
fm-project-mode.sh --pr and carried by fm-brief.sh --pr, fm-spawn.sh and
fm-promote.sh like forge=. The generated brief skips pr and ci, and the worker
writes and publishes the PR text itself.

* no-mistakes(review): Drop pr_text key; fix manual-PR checks wait and base

* no-mistakes(review): Remove dead PR_TEXT and timeout example

* no-mistakes(document): Fix README pr=manual sentence grammar

* test(bin): restore the displaced placeholder comment and rename the spawn agreement test

The comment for the leftover-placeholder test sat above the new pr=manual tests.
The spawn test said it recorded the PR text, but it only checks that a launch happens.

* fix: refuse teardown when Git hides untracked files (#7909)

* fix(teardown): detect untracked work regardless of Git status config

* test(watcher): avoid blocking FIFO contention handshakes

* no-mistakes(document): Document hidden-untracked teardown safety

---------

Co-authored-by: Kun Chen <3233006+kunchenguid@users.noreply.github.com>

* fix(bin): keep newest run attribution in crew-state (#5954)

* fix: prefer current run over stale overview row

* fix: preserve newest run precedence over stale status

* no-mistakes(document): Document live-run precedence in crew-state attribution

* fix: use ledger order for same-minute run precedence

* test: cover both overview orders for same-minute run attribution

Document and pin newer-first (recorded AXI) and historical-first overview
orders. Same-minute ledger timestamps use row order as the tie-break so an
older live bare status cannot hide a newer completed run.

* no-mistakes(review): Treat failed as overridable terminal overview status

* no-mistakes(review): Fix equal-head live run precedence with identity ordering

* no-mistakes(document): Updated run identity ordering documentation

* no-mistakes(lint): Fix ShellCheck export warning

* no-mistakes(review): Prove same-head ordering or report unknown

* no-mistakes(review): Guard failed selected-run reads and drop dead same-head ordering

* no-mistakes(ci): I fixed both Greptile findings (ci-1, ci-2) in bin/fm-crew-state.sh. The change is in the working tree. I did not commit it, push it, or reply to the Greptile threads, because those steps belong to the outer pipeline. ci-1. Invariant: a live run from bare `axi status` may replace a terminal overview selection only when it is proven newer than every other run on the same branch. Previously the code compared it only against the selected run. Now crew-state reads each other candidate with `axi status --run <id>` and compares the live run against each one: - If another candidate is also live, it reports `unknown`, "competing live runs". This keeps the competing-live-runs check. - If two runs share a head and a ULID timestamp, it reports `unknown`, "same-head run ordering unverified", as before. - It promotes the live run only when it is proven newer than all other candidates. - If the live run is newer than the selected run but not proven newer than some other candidate, it reports `unknown`, "run ordering unverified", and names every run id. This means neither the stale selected run nor the live run can hide a newer failed run. This branch is the one judgement call: without it, the stale "done" row A would still hide C's failure. - In all other cases the overview's selection stands. The lib helper is now a pairwise compare called `fm_nm_run_is_newer_than` (it was `fm_nm_run_is_newer_than_selected`). The selected run's detail from the loop is reused when the read succeeded, as in the round-1 fix. I updated the sentence in docs/architecture.md to match. ci-2. Invariant: the `no-mistakes runs` ledger is read only to order runs with different heads. It is now fetched lazily, at most once, and only when a candidate's head differs from the live run's head. Same-head ULID comparisons never call it. Regression test: `test_live_run_newer_than_selection_does_not_hide_newer_failed_run` covers A (stale completed, listed first), C (newer failed) and B (live, created between them). All three share one head and use ULID ids. It expects `state: unknown`, C's id in the output, and no `state: working`. Before the fix it fails: with the fixed code stashed it printed `state: working ... run: 01M1...` (run B). On the original base 3fbace9f the overview would select A, so the output would be `done`, which also fails the `unknown` check. I did not run that base case. Verification: `bash tests/fm-crew-state.test.sh` passes in full ("all fm-crew-state tests passed", the new test included). `shellcheck` on the three changed shell files reports only the existing info-level SC1091 "not following sourced file" notes. No end-to-end run against a live no-mistakes daemon was possible here. I checked the change with the crew-state test harness and its fake `no-mistakes` CLI

---------

Co-authored-by: mehulbhagwani <mehulbhagwani@users.noreply.github.com>
Co-authored-by: Pitch Perfekt Collective <pitchperfekt@Pitchs-Mac-Studio.local>

* chore(ci): run the full suite on outside pull requests only after the full-ci label

Outside pull requests run only the coverage guard and repo invariants until the full-ci label is added; lint and every test lane wait.

A new Full suite check fails naming the full-ci label until it is added, and fails whenever a lane fails or is cancelled.

The label starts the full suite, and later pushes run it again; main pushes, own branches and write-access authors run everything as before.

Other labels run no job at all: their skipped checks take a 'Not run for label - ' prefix, so they cannot hide an earlier failure or a later pass.

Close main pushes keep only the newest run; CONTRIBUTING.md explains the label, and the full-ci label now exists.

* feat(bin): add opt-in systemone and openai decision providers to dispatch resolution (#7664)

* feat(bin): add opt-in systemone and openai providers to typed dispatch resolution

Extend the FM_DISPATCH_PROVIDER/FM_DISPATCH_MODEL seam with a generic
systemone provider (any System One-compatible host at FM_DISPATCH_BASE_URL,
optional FM_DISPATCH_API_KEY) and an openai provider that maps the Choice
request to OpenAI's Decisions API and its answer back. No provider set keeps
the original off line; the never-send check runs on the endpoint and the final
per-provider body. Live provider captures are recorded as pending.

Refs #7643, builds on #7149.

* docs(verification): record the live OpenAI Decisions capture for dispatch resolution

Add a dated 2026-10-23 section for the openai provider: 25 hand-labeled
synthetic briefs against gpt-6-luna, outcome and latency tables, the usage
and header fields actually returned, a calibration note, and one verbatim
request and response pair. The systemone live check stays pending.

Refs #7643.

* docs(verification): record the live Clef capture for the systemone provider

Replace the pending systemone section with a dated 2026-10-23 run against
Cloudflare Workers AI's @cf/cloudflare/clef, reached through a local
test-only relay because Workers AI serves System One at /ai/run/<model> in
a {result, success} envelope. Adds the outcome and latency tables, a
calibration note compared with the gpt-6-luna run, and one verbatim request
and envelope pair. A direct Workers AI option stays out of scope.

Refs #7643.

* feat(bin): promote agy to a full primary and secondmate harness (#7941)

* feat(agy): promote Antigravity CLI to full primary and secondmate harness

Add tracked .agents/hooks.json, bin/fm-sessionstart-agy.sh, bin/fm-turnend-guard-agy.sh, PreToolUse --agy seatbelt flags, session-lock agy ancestry, autoarm supervision model, and --secondmate agy workspace trust pre-registration and spawn support.

* no-mistakes(review): Fix agy Stop-hook park, hooks.json shape, and live coverage

* no-mistakes(review): Unbound agy Stop park, raise ceiling, prove live deny

* no-mistakes(review): Correct agy verification doc park-bound wording

* no-mistakes(document): Document agy as verified primary and secondmate harness

* no-mistakes(ci): I fixed all three selected findings, and every check I ran passed, including the live agy end-to-end run. **ci-1 (`tests/fm-agy-primary-live-e2e.test.sh`):** The invariant is that the live Stop-hook test passes only if a real watcher starts and its wake reaches a follow-up turn. The old test passed as soon as `.agy-park-owner` existed. I replaced the Stop-hook park block with the one the user specified. It waits until both `.agy-park-owner` and `.last-watcher-beat` exist, wakes the watcher with a `done:` status line, and asserts that the park owner was recorded, the watcher started, and `DONE` appears in the agy output. **ci-2 (agy away daemon):** The invariant is that `/afk` must not launch a separate away daemon on any primary whose home runs the supervision host. The agy Stop-hook guard already runs the host when it is enabled, but `fm_afk_launch_host_primary` left agy out. I added `agy` there, which is the one shared check all three callers use. I also added agy to: - the header comment in `bin/fm-afk-launch.sh`; - the three harness loops and the pass message in `tests/fm-afk-launch.test.sh`; - the primary lists and counts in `docs/supervision-host.md`, the matching lines in its engine-selection section, and a new Antigravity (`agy`) row in its Arm owners table; - the header comment in `bin/fm-supervision-instructions.sh`. **user-1 (`.agents/hooks.json`):** The invariant is that each hook command stays one script under Windows `cmd /c` and exits 0 when `sh` is missing. All 5 commands now use `sh -c "..." || cd .`. This does not change behaviour on Linux or macOS, because the `--agy` hooks report deny or continue as JSON on stdout and exit 0. The file keeps its live-verified `{"firstmate":{...}}` shape, matchers and 28800s Stop timeout. **Verification:** - `tests/fm-agy-primary.test.sh` passes, including running the SessionStart hook command from both `.agents/` and the repo root. - `tests/fm-afk-launch.test.sh` has no failures, and the new agy check passes. Its rex end-to-end cases were skipped because the rex CLI is not installed. - `tests/fm-supervision-instructions.test.sh` has no failures. - `bin/fm-lint.sh` and `bin/fm-doc-audience-check.sh` pass. - `FM_AGY_PRIMARY_LIVE=1 tests/fm-agy-primary-live-e2e.test.sh` printed all four `ok` lines and no failures, including "Stop hook parks on a real watcher and delivers its wake to a follow-up turn". The output went through `tail`, so the exit code shown is `tail`'s, not the test script's

* feat(bin): add shared_quota opt-out from quota-based dispatch ranking (#7894)

* feat(dispatch): add shared_quota home opt-out from quota-based ranking

A home whose Claude and other provider usage draws on one combined AI
budget has no meaningful per-provider quota rows, so spendPriority
ranking and runway gates pick the wrong candidate. An optional
top-level "shared_quota": true in config/crew-dispatch.json now opts
the home out: the typed resolver makes no quota-axi call, applies no
quota floor or runway gate, ranks nothing by spendPriority, and
resolves the matched rule's use profiles in declared order, printing
every candidate line with quota ranking off by home declaration.
Firstmate's quota-array-dispatch intake honors the same declaration.
Without the setting, behavior is unchanged. Non-boolean values are
actionable configuration errors in both the resolver and bootstrap.

* test(dispatch): cover shared-quota bypass of unmet rule and profile floors

The shared_quota opt-out test picked a rule with no quota floor, so the
separate rule-floor and profile-floor bypass paths stayed untested.
Two cases now run against the same fixture: a rule whose model:fable
floor (20%) exceeds the snapshot's 15%, and a profile whose all_models
floor (50%) exceeds codex's 31%, each asserting the declared-order pick
still wins with no quota-axi invocation.

* no-mistakes(review): Narrow shared-quota skill opt-out to quota-only gates

* no-mistakes(review): Document preferred_provider under shared_quota opt-out and test it

* no-mistakes(document): Document shared_quota in schema example and verification inventory

* fix(bin): distinguish recycled reaper PIDs in tombstone cleanup (#7958)

* fix(bin): distinguish recycled reaper PIDs in tombstone cleanup

* no-mistakes(ci): ci-2 fixed in tests/fm-watcher-lock.test.sh (test_lock_tombstone_tracks_reaper_start_time). Invariant: no fixture child may outlive a SIGKILLed runner without a bound. (1) The paused reaper's wait loop now also stops when FM_TEST_SUITE_PID is no longer alive or when SECONDS reaches FM_TEST_STUB_MAX_BLOCK_SECONDS. (2) The one sibling child in the same test, the unrelated `sleep 300`, now sleeps for FM_TEST_STUB_MAX_BLOCK_SECONDS so it uses the same bound. Verification, run serially: bash tests/fm-watcher-lock.test.sh. The new test passed on 4 of 4 runs. Red-before still holds: with the base bin/fm-wake-lib.sh from c9da5523, the test fails with 'not ok - recycled reaper pid kept an abandoned tombstone alive'. Separately, the known stand-down flake ('the replaced watcher did not stand down on its own', watch-legacy-local-time-identity) failed on every run on this host and also fails on base c9da5523 without this change, so the test file still exits 1; left unfixed as instructed. ci-1 (Full suite waiting on the full-ci maintainer label) was ignored per the user's decision

* feat(bin): allow omp as a remote secondmate harness (#7939)

* feat: allow omp as a remote secondmate harness

* test: cover omp on the remote secondmate gates

* fix: retire a remote secondmate whose busy state left with its home

* docs: record omp remote retirement evidence

* review: Refresh pinned remote doctor bootstrap checksum

* fix(bin): name a consumed branch grant instead of a wiring bug (#7969)

* fix(bin): name a consumed branch grant instead of a wiring bug

When a supervision branch's own acknowledgement consumes every granted
row, the drain removes the branch-eligible row snapshot while the owner
record stays live. A repeat drain or acknowledgement in the same turn then
refused with a message implying a broken handoff. Say instead that the
grant was already consumed; the refusal and its exit status are unchanged.

* no-mistakes(document): Document consumed-grant refusal in watcher continuity doc

---------

Co-authored-by: c-c6aw <225476801+c-c6aw@users.noreply.github.com>

* fix: preserve literal ampersands in spawn and supervision paths (#7906)

* feat(bin): read dispatch provider keys from a declared credential source (#5409)

* feat(dispatch): read Typesafe key from Keychain

* no-mistakes(review): Share Keychain key lookup with bootstrap; hard-code service name

* no-mistakes(review): Use one readable-secret Keychain check for bootstrap and resolver

* no-mistakes(document): Point AGENTS key row to owner; record Keychain bootstrap evidence

* feat(dispatch): read provider keys from a declared credential source

bin/fm-dispatch-resolve.sh took the typesafe.ai and OpenRouter keys only
from the environment or $FM_HOME/.env, so a home that keeps its key in the
macOS Keychain needed a wrapper to supply it, and the documented direct
call reported off.

Let the resolver consume an optional, provider-keyed declaration in the
effective config directory, config/dispatch-credential-sources.json. It
names where a key lives and never holds one. macos-keychain is the first
adapter (service, optional account), kept behind a small schema and adapter
registry in bin/fm-credential-source-lib.sh so the shared surface binds to
no one OS or provider.

- Precedence is the environment, then .env, then the declared source, which
  is read only when neither supplied a key and only for the selected
  provider.
- No entry and no key stays off, exactly as before. An unreadable or
  invalid declaration exits 2 with a line that names the problem and never
  a declared value.
- A declared source that this host cannot run, that yields no key, or that
  does not answer within FM_CREDENTIAL_SOURCE_TIMEOUT ends as a structured
  error outcome with nothing sent, so it is not mistaken for an
  unconfigured resolver.
- The key is captured into the same private variable as before and still
  reaches curl only as an fd 3 header. The adapter puts only the service
  and account on argv and discards the tool's stderr.
- --supports-credential-source <source> answers supported or unsupported
  without reading a declaration or running the credential tool, so an
  installer can refuse an unsupported activation before it writes anything.

The resolver tests cover the mapping, effective-home and provider
isolation, precedence, the three failure kinds, and secret containment
with a stubbed security and uname.

Closes #7879

* no-mistakes(review): Gate bootstrap typed checks on declared source; fix timeout

* no-mistakes(review): Document storing the declared Keychain item without access dialog

* no-mistakes(document): Clarify that only a typesafe declaration keeps resolver on

* no-mistakes(document): Merge dispatch key-source precedence into one configuration sentence

---------

Co-authored-by: Kun Chen <kunchenguid@users.noreply.github.com>

* fix: clean up remote reply temporary files and locks on exit (#6489)

* fix(bin): clean remote reply temp paths on every exit

The remote reply adapter left its temporary staging directory and fetch files behind on several exit paths.
The ingest staging directory leaked on the continuity-broken return, whose EXIT trap fired after its local tmp left scope.
The trap cmd_ingest installed also replaced the lifecycle-lock release of the handle subshell.
One EXIT trap now owns every temporary path, each lock subshell runs it before releasing its lock, and the empty hash no longer stages a file.
A test under a private TMPDIR covers the continuity return, a die after staging, a locked handle, and a signal during a document fetch.

* no-mistakes(document): Document remote-reply temporary-file cleanup

* no-mistakes(ci): Fixed ci-1 in tests/fm-remote-reply.test.sh: interrupt the blocked SSH child before waiting, fail if it already exited, and require adapter exit status 143 before checking cleanup. Confirmed the strengthened test rejects an adapter that ignores TERM; the temporary mutation was restored. The full remote-reply suite passed on a serial rerun, and syntax, pinned ShellCheck, and diff checks passed. One earlier run alongside lint timed out waiting for the third reply generation

* fix(bin): clean up the staged source-read output on every exit path

The source leg stages the remote read's output in a temporary file. Track it
with the adapter's other temporary paths so a signal during the read removes
it, and extend the regression test and docs to cover that path.

* chore: ignore Claude Code per-user settings (#6482)

* chore: gitignore Claude Code's per-user local settings file

* no-mistakes(ci): Addressed ci-1 by preserving the staged --no-index correction for both Claude settings assertions in tests/fm-gitignore-config.test.sh, making ignore-rule checks independent of tracking state. Reproduced the original false pass with tracked shared settings and an overly broad .claude/ rule; the corrected test rejects it. Verified normal tracked/untracked settings cases and rejection of a missing local-settings ignore rule. Targeted test runner, pinned ShellCheck, Bash syntax check, and diff checks all passed. No unrelated changes were made

* fix: prefilter inbox history for idempotent remote steering (#7905)

* fix(inbox): prefilter idempotent steering history

* no-mistakes(document): Clarify delivery mode in steering retry contract

* test(inbox): cover acknowledgement before prefilter opens

* feat(bin): add Kiro CLI as a crewmate/scout harness adapter (port of #7956) (#7979)

* feat(bin): add Kiro CLI as a crewmate/scout harness adapter

Port of #7956 onto current main so it gets a fresh CI run.

Adds a `kiro` (Kiro CLI, V2 engine) harness adapter, crewmate/scout only
(--secondmate launches are refused). fm-harness.sh detects it by kiro-cli
ancestry; fm-spawn.sh launches it with a per-task KIRO_HOME under
state/<id>.kiro-home (generated userPromptSubmit and stop hooks plus
chat.disableTrustAllConfirmation); busy, control, send, watch, procevent,
teardown and bootstrap wiring recognise it. Composer ghost-text and busy
footer matching is scoped to FM_COMPOSER_HARNESS=kiro, so other harnesses
read exactly as before. Adds references/harness/kiro.md,
docs/verification/kiro.md, tests/fm-kiro-harness.test.sh and an opt-in
live e2e signals guard.

Conflicts with main were resolved by keeping main's agy promotion and
adding kiro to the crewmate-only lists next to it.

Co-authored-by: kiatng <1106470+kiatng@users.noreply.github.com>
Co-authored-by: Marsjohn-11 <74795701+Marsjohn-11@users.noreply.github.com>

* fix(send): detect kiro on meta-less explicit targets

An explicit session:window send has no task meta, so TARGET_HARNESS stayed
empty and the kiro composer rules never applied. A finished kiro idle
placeholder then read as pending, extra Enters were pressed, and fm-send
exited 3 even though kiro accepted the message.

Resolve kiro from the live pane's foreground process group when meta is
absent, and keep every other explicit-target send on the unknown-harness
path. Move the kiro live e2e version probe to after the live gate so an
opted-out run never starts kiro-cli.

Co-authored-by: Kun Chen <kunchenguid@users.noreply.github.com>

---------

Co-authored-by: kiatng <1106470+kiatng@users.noreply.github.com>
Co-authored-by: Marsjohn-11 <74795701+Marsjohn-11@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Kun Chen <kunchenguid@users.noreply.github.com>

* fix(bin): publish hold origins only after backend success (#6777)

* fix(captain-hold): refuse a previous origin's answer after an incomplete hold move

A hold moved to a new origin wrote its stamp and origin before the backend
hold. A process stopped between those writes, or a refused hold whose rollback
also failed, left the task associated with the new origin while it carried
only the earlier call's answer, and complete and verify accepted that answer.

Verification now treats an open, unheld task that leads with a hold-set stamp
above a recorded answer as a re-hold that never completed, so the answer no
longer satisfies the new origin however the move was interrupted. A refused
hold also restores the body the attempt started from, and the origin lookup
runs before any write, so a clean failure leaves the earlier answer valid.

Closes #6461

* no-mistakes(review): Publish hold origins only after backend success

* no-mistakes(review): Publish verified holds before origin writes

* no-mistakes(document): Clarify hold-origin durability documentation and regression coverage

* no-mistakes(lint): Quote done subcommand to resolve ShellCheck warning

* no-mistakes(document): Clarify recorded-origin provenance guarantees

* feat(backends): add experimental explicit-only hc (herdr-core) runtime backend (#7963)

* feat(backends): add experimental explicit-only hc (herdr-core) runtime backend

herdr-core is the terminal core under Herdr.app and is not Herdr 1.
The adapter follows the tmux shape: one login-shell terminal per task,
Treehouse keeps the worktree, and fm-spawn drives it through the same
send/current-path primitives.

- bin/backends/hc.sh: create, capture, visible capture, send line, typed
  literal through hc keys, named keys, current path, composer state,
  submit, native busy state, recovery agent state from the foreground
  process and its process group, and a close that proves the terminal gone.
  Targets are <session>:<address>; every call pins that HC_SESSION, and an
  empty session never reaches hc. Task and home labels gate input and close.
- bin/fm-backend.sh, bin/fm-spawn.sh: hc arms, explicit-only selection,
  endpoint validation, hc_session/hc_terminal metadata, secondmate refusal.
- tests: fake-CLI suite and a real-hc smoke test on a private core.
- docs: hc-backend.md, configuration, verification record, README links.

* fix(hc): submit the spawn launch line by paste and add the hc liveness live guard

The launch line always carries a + that hc keys cannot type, so fm-spawn
pastes it with hc send and consumes the Enter that follows. The launch
environment floor keeps HC_SESSION, HC_TERMINAL_ID, HC_TERMINAL_SOCKET and
HC_SCOPE. tests/fm-backend-hc-liveness-live-e2e.test.sh launches every
installed harness bare in a private core and requires alive. The
verification record gains the end-to-end spawn, steer, peek and teardown run.

* no-mistakes(review): Allow hc interrupt keys and drop unused hc send_literal

* no-mistakes(document): Sync hc backend inventories and adapter header comment

* no-mistakes(ci): Fixed. When an hc task was torn down, the kill function read the task's expected label from the wrong argument, so it ended up accepting any terminal in the same home and could close another task's worker. - Invariant: every hc close must be gated by the task label that teardown passes as the third argument to fm_backend_kill. - Where it must hold: fm-teardown.sh calls `fm_backend_kill <backend> <target> <zellij_tab_id> fm-<id>` at all its sites (around lines 3482, 3491, 3494, 3876, 3986 and 3995). The dispatcher at bin/fm-backend.sh:1156 passes "$@" through to fm_backend_hc_kill, and that function is the only hc close path. So fixing that one function's arguments covers every teardown site. - Fix in bin/backends/hc.sh:279: the signature is now `<target> [unused] [expected-label]` and it reads `expected=${3:-'*'}`, the same shape tern, rex, cmux and paseo use. The label value matches what hc terminals carry: spawn creates them with firstmate.task=$W where W="fm-$ID" (bin/fm-spawn.sh:4545 and 4955), and teardown passes "fm-$ID". - New test in tests/fm-backend-hc.test.sh, test_kill_refuses_another_tasks_terminal, goes through the public fm_backend_kill path. A terminal labeled fm-other is refused for expected label fm-a1, stays alive and gets no `hc kill`. The terminal labeled fm-a1 is closed and removed. Before the fix the test failed ("expected a refusal"), and after it the whole suite passes. - Checks: `bash tests/fm-backend-hc.test.sh` passes every test and `shellcheck -x` is clean on both files. The live smoke and e2e hc tests call kill without a label, which keeps the existing behavior of accepting any task label from this home. I did not run them because they need a real herdr-core. VERIFIED with the unit tests on the fake hc CLI, not against a real hc core

* fix(hc): keep the live liveness guard from repointing the operator's claude

A real claude started under the guard's scratch XDG_DATA_HOME can self-update into it and repoint ~/.local/bin/claude there, leaving the link dangling once the scratch directory is removed.
Export DISABLE_AUTOUPDATER=1, as bin/fm-live-lab.sh already does for its live harnesses.

* fix(hc): drop an inherited HC_SOCKET so the session pin holds

* no-mistakes(document): Document hc dropping inherited HC_SOCKET for session pin

* no-mistakes(ci): I fixed both Greptile findings. The hc unit suite passes all 12 tests, three runs in a row, and `shellcheck -x` is clean on the 4 touched files. VERIFIED with unit tests (a fake hc CLI plus a real process group). NOT VERIFIED against a real hc core, because the live tests need herdr-core. ci-1, live tests could stop an unrelated core - Invariant: every direct `hc` call a test makes must reach only its private scratch core, so an inherited HC_SOCKET (which wins over HC_SESSION in hc 0.1.14) must never be set. - Where it must hold: the two suites that call `hc` directly (`hc server status` at startup and `hc server stop` in cleanup), `tests/fm-backend-hc-liveness-live-e2e.test.sh` and `tests/fm-backend-hc-smoke.test.sh`. Adapter calls already go through `fm_backend_hc_cli`, which drops HC_SOCKET. - Fix: both suites add HC_SOCKET to the `unset HC_TERMINAL_ID HC_TERMINAL_SOCKET HC_SCOPE` line, before any `hc` call. ci-2, a shell wrapper running a live worker was reported as dead - Invariant: `fm_backend_hc_agent_state` may return `dead` only when neither the foreground process nor anything else in its process group is a harness. - Where it must hold: there is one classification path, `bin/backends/hc.sh` around line 326. Before the fix, the `shell` branch returned `dead` before the process-group check ran. Callers such as the inbox ring and the watcher read this value through `fm_backend_agent_state`, so fixing this one function covers all of them. - Fix: the result is now `alive` when the foreground process is a harness. Otherwise the process group is checked, which can also give `alive`. After that a shell gives `dead` and anything else gives `ambiguous`. An idle shell, whose group holds no harness, is still `dead`, and the existing test_agent_state_classifies_foreground_and_absence still passes (`t2=dead`). - New test `test_agent_state_reads_a_shell_wrappers_group` in `tests/fm-backend-hc.test.sh`. It starts a real `bash` wrapper in its own process group with a child that runs as `claude`, and points the fake hc terminal's foreground at the wrapper. With the old code the test fails ("expected 'dead', got 'alive'"). With the fix it passes. The comment in the code was updated. `docs/hc-backend.md` already describes the process-group read, so it did not need a change. Not run: `fm-backend-hc-smoke.test.sh` and `fm-backend-hc-liveness-live-e2e.test.sh`, because they need a real hc core

* fix: refresh Herdr upstream references and licensing (#8000)

* docs(herdr): record the Apache-2.0 relicense and herdrdev org rename

Herdr relicensed from AGPL-3.0-or-later to Apache-2.0 in 0.8.0 and the
GitHub organization moved ogulcancelik/herdr to herdrdev/herdr. The old
release URLs redirect to the same assets, so the CI installer and the
version-floor guard now fetch via the canonical org with the pinned
version and checksums unchanged; verified end to end by running the
installer against the new URL.

* no-mistakes(document): Clarify Herdr product boundaries and preserve historical evidence

* fix(pi): stop repeated numbered and byte excerpt reads (#7992)

Fixes #7990

* fix(bin): keep the PR merge watch working when a worker with a PR is relaunched (#7996)

* Preserve PR poll authentication on relaunch

* no-mistakes(review): Keep trace and polytoken meta ahead of PR lines

* test: pin lock staleness in malformed presentation lock wake-queue case (#7837)

* fix(tests): pin lock staleness in malformed presentation lock case

A plain-file presentation lock older than FM_LOCK_STALE_AFTER (default 2s) is reclaimed as garbage, so a slow runner could age the malformed-lock fixture into a successful acquire. Pin the staleness window far above the case runtime so the case is deterministic.

* test(wake-queue): correct the malformed presentation lock staleness comment

---------

Co-authored-by: Trillium Smith <5898009+trillium@users.noreply.github.com>

* feat(bin): add configurable self-update source for /updatefirstmate (#5603)

* feat(bin): let /updatefirstmate follow a configured self-update source

An optional local config/self-update-source ("<remote> <branch>") makes
fm-update.sh fast-forward the primary from that one remote branch instead of
origin/<default>, under the same fast-forward-only guards, and makes local
secondmates advance to the primary's resulting commit (a standalone clone
imports it from the primary first). A home can then run its own fixes from a
branch that carries them on top of upstream, while worker spawns, review
diffs, the cleanup landed-work test, lint and default-branch detection keep
using origin, so new contributions still branch from upstream.

Absent, behaviour is unchanged. An unreadable or malformed file, an unknown
remote or an invalid branch name refuses the whole update before anything
moves rather than falling back to origin. A remote secondmate's host follows
its own code root's config, which the docs record as the limit.

* no-mistakes(document): List config/self-update-source in AGENTS.md config inventory

* no-mistakes(document): Mention self-update source in updatefirstmate skill description

* fix: bound watcher auto-arm failures and recover interrupted locks (#8018)

* fix(bin): commit the attended alarm from the exhausted Stop auto-arm

A Claude failure episode could suppress indefinitely without ever raising
the attended alarm. On every Stop cycle the auto-arm opens its generation
claim before the guard's sync-wait decision, so the guard always steps
aside; terminal_fail_open is never reached and no participant knew that
automatic continuation was exhausted. The block budget still climbed
because the guard's step-aside path accounts for the epoch, so Stops kept
rewaking with empty failed-suppressed bodies forever.

The auto-arm is the only participant that knows its own continuation is
exhausted, so it now owns the terminal escalation: once the failure
notice was consumed and the session block budget is over, the terminal
failure path commits .claude-autoarm-failure-alarmed and the
failed-suppressed outcome inside the owner lock (owner then budget, the
same order the guard's writer uses), then emits one loud final rewake
telling the operator to keep the session attended and diagnose the
Stop-hook supervision. A healthy watcher verified inside that hold resets
the episode instead of alarming, and a refused commit stays suppressed
without a false alarm.

Later Stops in the same episode see the alarm, record failed-suppressed,
and exit 0 so no further continuation or alarm is produced. Positive
watcher recovery still clears the notice, the alarm, and the budget.

Every failed-suppressed commit now carries a one-line stderr reason
naming why the operator notice is not repeated and whether the
Stop-owned retry stays alive, replacing the silent empty bodies that
made suppressed Stops indistinguishable from a wedged hook.

Adds an integrated guard/auto-arm regression driving both hooks through
the exhaustion boundary and asserting the single alarm, post-alarm
suppression, and clean recovery; updates existing tests for the reasoned
suppression contract.

* fix(bin): outlast an unpublished lock pid for one freshness window

CI run 40805704864 ("recovery drain after forced arm interruption")
failed because a dying watcher could not publish .watcher-down inside
its bounded cleanup window, so the drain saw no downtime marker to ack.

The blocker was an empty-pid lock artifact: fm_lock_claim and the
bounded-wait handoff published ownerdir/pid with a truncating write,
and a creator killed mid-write (the bounded handoff helper runs under
timeout -k with a process-group KILL) left a resolvable symlink whose
pid file stayed empty forever. fm_lock_try_acquire treats that as a
fresh mid-acquire hold for a full freshness window, cannot steal it,
and a bounded waiter whose bound equals the window gave up before the
evidence expired.

Two changes. First, both pid writes now go through a same-directory
pid.tmp file renamed into place, so a killed write can no longer leave
a live lock with a permanently empty pid; fm_lock_clean_known_files
sweeps leftover tmp files. Second, fm_lock_acquire_wait_max polls one
extra freshness window when the remaining blocker still has no
published pid, so a waiter outlives the residue instead of failing at
its bound; the moment a pid publishes or the artifact goes stale the
ordinary live-holder and steal rules apply unchanged, and published
live holders keep the original bound.

Adds a regression test that links an owner dir with no pid and asserts
the bounded wait outlasts the freshness window to reclaim it, while a
live holder still fails at the nominal bound; verified to fail against
the pre-change implementation.

* no-mistakes(review): Route every suppressed exit through alarm decision

* no-mistakes(document): Clarify exhaustion and lock-wait documentation

* no-mistakes(lint): Quote empty grace deadline assignment for ShellCheck

* no-mistakes(ci): Fixed tests/fm-x-mode.test.sh: atomic lock-pid publication consumed its overly broad injected mv failure. Targeted the counter-record destination and asserted injection occurred. Reproduced failure before fix; full X-mode test script, pinned lint, bash syntax, and diff checks pass afterward. Full suite failure is downstream of this lane failure; no separate fix needed

* no-mistakes(ci): Fixed Full suite’s underlying shard timeout: the PR marker test’s broad mv failure injection blocked atomic lock-PID publication indefinitely. Restricted injection to the marker destination. Reproduced the hang before fixing; targeted regression, all 49 PR-security tests, ShellCheck, bash syntax, and diff checks pass

* no-mistakes(ci): Fixed load-sensitive remote lifecycle test timeout: all three inheritance/launch barrier waits now honor the existing convergence budget instead of failing after 30 seconds. Full suite failure is downstream of this shard. Full lifecycle E2E, Bash syntax, ShellCheck excluding SC1091, and diff checks pass. Production behavior unchanged

* no-mistakes(ci): Fixed remote-reply fixture races, preserved the committing auto-arm’s final rewake on signals, and asserted the live-holder wait bound. Remote-reply and turnend-guard suites and focused lock test pass; signal regression fails before fix and passes after. Full watcher-lock suite fails earlier in an unchanged macOS watcher-replacement test. Full suite CI failure is downstream of the shard failure

* no-mistakes(ci): Fixed teardown race in tests/fm-watch-arm.test.sh: atomically rename state/home/root fixtures away before deleting contents after process exit. Preserved all existing assertions; production code unchanged. Affected suite passed three runs, including two concurrent copies; targeted unpublished-PID lock test and syntax/diff checks passed. Additional full lock suite failed twice at a separate watcher-replacement exit assertion. Standalone ShellCheck reported existing warnings

* fix(bin): cut stat forks in the wake drain by reading identity and size together (#6271)

Local cherry-pick of https://github.com/kunchenguid/firstmate/pull/6271 pending upstream merge.

* fix(bin): keep pr= merge-poll identity last when recording captain-hold completion (#6732)

* fix(bin): keep PR merge polls authenticated across relaunch

A relaunch rewrote the task record with control_relaunch_tx after the
preserved pr= line. fm_pr_metadata_identity_parse rejects any key after
pr= other than pr_head= and x_*, so the watcher stopped authenticating
the armed merge poll and reported it as an unauthenticated state check,
and the merged-PR wake never arrived. Write the transaction id before
the preserved lines, as fm-remote-secondmate-relaunch.sh already does.

* no-mistakes(review): Keep pr= last for traceparent and completion writes

* no-mistakes(document): Note completion record placement ahead of pr= lines

* no-mistakes(ci): Fixed the Greptile P1 finding (ci-1) as the user decided. **Invariant:** a task's `.meta` record holds exactly one `decisions_reviewed`/`decision_keys` pair, and it sits before `pr=`. Then `meta_value` (which reads the last match) returns the current inventory, and `fm_pr_metadata_identity_parse` still sees `pr=` last. The only place that writes this pair is the awk rewrite in `command_complete` (`bin/fm-captain-hold.sh`). The other hits for these keys under `bin/` are only a comment and an error message. `verify` and later `complete` calls read the pair through `meta_value`, so fixing this one writer fixes them too. **Fix:** added one …
trillium added a commit to trillium/firstmate that referenced this pull request Nov 4, 2026
* feat(bin): opt-in spawn base from the primary checkout for local-only work (#7352)

* feat(bin): add opt-in config/spawn-base-primary-checkout for local landings

A fresh pooled task worktree is reset to origin/<default>. A local-only
project lands work on the primary checkout's default branch through
fm-merge-local.sh and never pushes, so that ref stays frozen at the last
push and every fresh task starts behind work already landed, loading the
project's instruction files from the stale tree. The always-on fix proposed
in #3812 replaced the specified origin-only refresh for every home; this
rework keeps that rule as the default and moves the new base behind an
explicit, default-off presence flag, following the existing config/<flag>
pattern.

With config/spawn-base-primary-checkout present:
- fm-spawn.sh starts a fresh local-only ship, or a scout without
  --base-branch, from the primary checkout's <default> when it strictly
  contains origin's tip. Publishing modes and named base branches keep
  origin's tip, because that work is delivered against origin. A diverged
  primary keeps origin's tip and prints a note counting both sides. The
  commit is read from the local object store, so nothing extra is fetched,
  and the clean-slot refusal still runs first.
- fm-review-diff.sh anchors a remote-backed task without base_branch= on the
  branch it delivers to: publishing modes stay on origin/<default>, while a
  local-only ship or a scout is compared against whichever of the local
  <default> and origin/<default> meets the branch later, so the review shows
  the task's own work instead of every locally landed commit.
- fm-promote.sh tells a scout promoted to a publishing mode to return to
  origin's default branch, because in this home the scout may have started
  from the primary checkout's branch, whose unpushed commits would otherwise
  be published with the work.

fm-dod-lib.sh gains fm_mode_publishes as the one predicate those three
readers share. Without the flag every path is unchanged: the spawn resets
to origin's tip, the review anchors on origin/<default>, and promotion keeps
its wording; the existing tests run unmodified. Treehouse 3 (verified on
3.1.3) already hands a slot out at whichever of the local and remote default
branch is further ahead, so with the flag the refresh keeps that slot where
Treehouse put it for a local landing instead of rewinding it, and a project
without origin is untouched as before.

Supersedes #3812.

* no-mistakes(document): Drop change-relative wording from spawn-base config docs

* no-mistakes(ci): The Greptile Review check failed on two review findings, not on a broken build or test. I fixed both as the user directed, and the tests and lint pass. ci-1 (bin/fm-promote.sh): promotion must name origin's default branch only when spawn could actually have started the scout from the primary checkout. Spawn does that only when the project has an origin remote and is recorded on the task. Before this fix, the opt-in flag alone made promotion to no-mistakes or direct-PR say "copy of origin's default branch...", even on a project with no origin. - The new wording now also requires a recorded project (`[ -n "$PROMOTE_PROJECT" ]`) whose `git remote get-url origin` succeeds. That is the same check bin/fm-review-diff.sh already makes. The empty-project guard is needed because `git -C ""` would run in the current directory. Otherwise the existing "default-branch base" wording stays. - The three places that read the flag now agree: spawn, review-diff and promote. - I updated the header and inline comments in fm-promote.sh, and the promote line in docs/configuration.md, to say this applies only to a project with an origin remote. - Test: `test_promote_names_origin_for_a_publishing_mode_in_an_opted_in_home` in tests/fm-task-delivery.test.sh now records a real `project=` with a registry entry, and covers flag on/off × origin/none × direct-PR/no-mistakes/local-only. Only flag on + origin + a publishing mode gets the new wording. The named-base case is unchanged. - Before the fix, the test fails with "not ok - flag on, remote none, direct-PR: the promotion changed the default-branch wording". With the fix, it passes. ci-2 (tests/fm-spawn-pool-base-freshen.test.sh): with the flag set, both publishing modes must start from origin's tip and print no divergence note. - The opted-in spawn test now covers no-mistakes as well as direct-PR, local-only and scout. - The expectations no longer single out direct-PR. Both publishing modes now expect origin's tip, no "note: pooled worktree", and a review anchored at the slot's start, in the leading, diverged and trailing cases. Verification: - `bash tests/fm-task-delivery.test.sh`: exit 0. - `bash tests/fm-spawn-pool-base-freshen.test.sh`: exit 0. - `bin/fm-lint.sh` on the three changed shell files: exit 0 (ShellCheck 0.11.0, pinned, with extended analysis)

* fix: preserve whitespace when proving patches landed (#7910)

* fix: report unavailable Git containment proofs during teardown (#7915)

* fix(teardown): distinguish unavailable content-landed proof

* no-mistakes(document): Clarify teardown proof failure documentation

* no-mistakes(ci): Captain, CI failed in unchanged watcher recovery code, independent of this PR. The focused failing case passed locally with exit 0. The full suite stalled earlier and was stopped. No tracked changes. Command guard rejected cleanup; scratch remains at .ci-7915/ and tests/.ci-7915-cycle.sh

* chore: untrack CI validation scratch

* feat(bin): prefer a configured provider family in dispatch resolution (#7876)

* feat(dispatch): prefer configured provider family

* no-mistakes(review): drop policy_why field and dead auth fixture from preference tests

* no-mistakes(document): docs: record preferred_provider in schema, diagnostics, verification

* fix: pin local-only merges to the accepted done commit (#7916)

* fix: pin local-only landing to its accepted done head

Persist the accepted local-only commit in task metadata and refuse landing when the branch or the recorded head changes. Merge the full commit ID under the task control and metadata locks.

Closes https://github.com/kunchenguid/firstmate/issues/7782

* no-mistakes(test): Refuse local landing races with atomic ref transactions

* no-mistakes(document): Document pinned local landing and recovery contracts

* no-mistakes(ci): Applied only the verified incremental patch and preserved existing repairs. Complete diff matches the supplied candidate hash. Both focused test files, default lint, and source-aware lint passed with exit 0. Evidence retained at /tmp/up7782-local-repair/ci-phase-fresh-*. No commits, pushes, or pipeline-control actions performed; publication remains with the outer executor

* no-mistakes(ci): Fixed both SC2031 false positives in tests/fm-merge-local.test.sh with narrowly scoped suppressions. Tier 2 lint correction; runtime changes were unnecessary. Default lint, source-aware lint, all 8 focused tests, and git diff --check passed. No commits, pushes, or pipeline-control actions performed

* fix: coalesce repeated extension host errors (#6548) (#7928)

* fix(procevent): coalesce unhandled extension host errors

* no-mistakes(document): Document host-error coalescing and recovery semantics

* fix: preserve wake grants when queue-lock acquisition fails (#7912)

* fix: stop wake grants when lock acquisition fails

* no-mistakes(document): Document wake grant lock acquisition failure behavior

* fix(bin): send remote second mate steers over stdin (#7902)

* fix: send remote steers over stdin

* fix: version remote stdin send protocol

* no-mistakes(document): document stdin transport for remote steer in fm-send header

* no-mistakes(ci): Two tests failed in CI. One is caused by this PR; the other is not. 1. Behavior portable serial 5: `tests/fm-secondmate-reconcile.test.sh` failed with "supervision did not deliver the durable reconcile request later". This PR caused it. The PR now sends a remote steer's body on stdin, using `fm-on.sh --stdin` with the `send-stdin` verb. This test's fake ssh started with `cat > /dev/null`, so it threw the body away before it ran the real `fm-remote-secondmate-control.sh`. `cmd_send_stdin` then read an empty message, died with "remote steer message must be nonempty", and no inbox record was written. Rule that broke: a fake ssh that runs the real remote leg must pass the caller's stdin through, as real ssh does. I checked every fake ssh that runs the real leg. `fm-send-remote-delivery.test.sh` already passes stdin through. `fm-secondmate-sync.test.sh` (`make_remote_leg_ssh_stub`) had the same discard line. The stub in `fm-send-resolve-key.test.sh` never runs the leg, so it is fine. The fix deletes the `cat > /dev/null` line in the reconcile and sync stubs. Calls made without `--stdin` still get /dev/null from fm-on, so nothing else changes. Checks run locally: the reconcile test fails before the fix with the same CI message. After the fix, the reconcile test passes (rc=0) and the sync test passes (rc=0). 2. Behavior portable serial 3: `tests/fm-wake-queue.test.sh` failed in `test_concurrent_append_and_drain` with "wake drain: queue lock could not be acquired safely". This PR did not cause it. The PR does not touch `bin/fm-wake-drain.sh`, the wake tests or the wake helpers. The failure is lock contention: 40 appenders run at the same time as a drain, on a loaded CI runner. Locally the whole test passed (70 ok, rc=0). I made no change for it. It is an existing flake in wake-queue lock acquisition and needs its own fix outside this PR. Open PR #7912 ("preserve wake grants when queue-lock acquisition fails") works in the same area

* fix(bin): stop herdr server_ensure from starting servers an external owner manages (#7357)

* fix(herdr): never start a server an external owner manages or is replacing

fm_backend_herdr_server_ensure started a detached herdr server whenever
status reported the session not running. When a service manager owns the
server, that races a unit restart or a server live-handoff and splits panes
across two servers.

The session directory reported by herdr session list can now carry a
firstmate-server-owner marker (persistent, naming the owner) and a
firstmate-server-replacing marker (for the duration of a restart or handoff).
While either exists and the server is not running, server_ensure never starts
a server: it waits a bounded time (FM_BACKEND_HERDR_EXTERNAL_SERVER_POLLS,
default 30s) for the server to report running, and otherwise fails naming the
owner or the replacement. A running server is still used at once, and a
session with no marker keeps the Firstmate-owned autostart unchanged.

Fixes #7320

* no-mistakes(review): Enforce herdr replacement marker on fast path; fixed wait bound

* no-mistakes(ci): Both CI failures had one cause in this PR, and I fixed it in code; no test assertions changed. `fm_backend_herdr_server_ensure` had started running `herdr session list --json` on every call to find the session directory for the ownership markers. Two existing tests treat that call as a sign of something else: - `tests/fm-control-relaunch.test.sh` failed with "a herdr reclaim touched a session the record does not name: session list --json", because it allows only `--session fmlab` calls and `status --json`. - `tests/fm-backend-herdr-presentation-e2e.test.sh` failed with "opted-out spawn added presentation-ordering capability or socket calls", because there `session list` means presentation ordering ran. Invariant: `server_ensure` must not make Herdr calls beyond its own `status` read, so ordinary spawns and reclaims stay free of `session list` and only touch the session they name. Every caller goes through `server_ensure`, so fixing it there covers all of them. Fix (`bin/backends/herdr.sh`): the session directory now comes from the `status --json` read `server_ensure` already makes. It is the directory containing `.server.socket`. I removed the `fm_backend_herdr_session_dir` helper. On a running server, the only added work is one check for the replacement marker, which is what the user asked for. I checked this against real Herdr 0.9.5: - `status` reports the socket even when the server is stopped, for both the default and named sessions. - The socket's directory is the same `session_dir` that `session list` reports, and it follows `XDG_CONFIG_HOME`. - With `--session`, an inherited `HERDR_SOCKET_PATH` does not change it. - The read creates nothing on disk. If a Herdr version omits the socket, `server_ensure` keeps the old Firstmate-owned behavior, as the docs already said for a missing `session_dir`. Other changes: the marker-test fakes now report the socket under the session directory, and I removed the `session list` stub this PR had added to the shared fake. `docs/herdr-backend.md` and `docs/verification/runtime-backends.md` ("Session directory") now describe and record the `status`-socket measurement. Verification: - `tests/fm-backend-herdr.test.sh` passes: 239 ok, 0 not ok, including all the externally-managed and replacement-marker tests. - `tests/fm-control-relaunch.test.sh` passes; it was the shard 3 failure. - shellcheck shows only existing info-level notes. Not verified locally: the real-Herdr presentation test. Here it stopped earlier, at an unrelated Treehouse timeout ("treehouse get did not enter an isolated worktree within 60s"). After the fix `server_ensure` no longer runs `session list`, which is the call that assertion caught. No lab session was left running, and I removed the test's temp directory

* fix: reset idle backoff for actionable heartbeat wakes (#7903)

* fix: classify actionable heartbeat backstop as a check

* no-mistakes(document): Correct heartbeat routing docs and remove stale test count

* fix: preserve heartbeat routing when resetting actionable backoff

* fix(bin): reclaim a live watch lock whose pid-identity no longer recomputes (#7931)

* fix(bin): reclaim a lock whose recorded pid-identity no longer recomputes

#7886 made fm_lock_holder_alive reject a live pid whose start time no
longer matches the lock's recorded pid-start. A holder that predates that
record still falls back to pid liveness, which leaves issue #7801 open: on
a /proc-less host outside UTC, a watcher started before fm_pid_identity
pinned TZ=UTC0 recorded a local-time pid-identity. After the update that
live holder no longer matches its own identity, so the health predicate
rejects it, yet every new watcher stands down beside it and the home stays
unsupervised.

fm_lock_holder_alive now also requires a recorded pid-identity, when
present, to still recompute for the pid, after the existing start-time
check and with the same missing-evidence fallbacks: no record, a pid
rewritten mid-read, or an unreadable value keeps the pid-liveness answer.
Both records go through one helper, _fm_lock_record_matches. Only
long-lived holders that never exec write a pid-identity (the watcher, the
supervise daemon), so a genuine holder still matches. A watcher replaced
this way stands down unsignalled at its next poll through the existing
self-eviction. The fm_pid_identity comment and docs/turnend-guard.md
claimed the upgrade-window residual is cleared by the post-update restart,
which never reaches a primary home's own watcher; they now say the next
lock claim clears it.

Verification:
- Drove: real bin/fm-watch.sh processes with /proc hidden through
  FM_PROC_ROOT_OVERRIDE and TZ=America/Los_Angeles: a live genuine watcher
  whose lock record was rewritten to its own local-time ps lstart identity
  with no pid-start, as a pre-pin build wrote it, then a fresh watcher;
  plus fm_lock_try_acquire against a live pid with a mismatched, matching,
  and unrecorded pid-identity and no pid-start.
- Observed: on the unchanged library the fresh watcher exits "lock held by
  live pid ... but heartbeat is stale" and fm_lock_try_acquire returns
  held for the mismatch. With this change the fresh watcher takes the
  lock, the legacy holder exits 0 by standing down, the live pid is never
  signalled, and matching or unrecorded identities stay held.
- Re-check: tests/fm-watcher-lock.test.sh cases
  test_watch_replaces_live_holder_with_legacy_local_time_identity and
  test_lock_reclaims_holder_whose_identity_no_longer_recomputes.

* no-mistakes(review): Limit pid-identity lock reclaim to the watch lock

* no-mistakes(document): Correct fm_lock_holder_alive comment on non-watch identity locks

* no-mistakes(ci): I made two small fixes. CI and "Require no-mistakes" never ran: GitHub shows both as `action_required`, waiting for approval to run workflows from a fork, so the code didn't cause those. Greptile failed because it scored the PR 4/5 against a required 5/5, with one P2 comment. 1. **Greptile P2, test children left running (`tests/fm-watcher-lock.test.sh`).** The two new lock tests start a `sleep 300` holder that only gets killed after every assertion passes, and the suite's cleanup only reaps processes whose command line contains the fixture root. Each holder now starts as `(exec -a "$dir/holder" sleep 300)`, so cleanup reaps it if the test fails early. To check, I forced a `fail` right after the child starts: on HEAD the `sleep 300` was still running afterwards, and with the fix it was reaped. Both tests pass normally. 2. **Flaky takeover test (`bin/fm-watch.sh`).** This edit was already uncommitted in the worktree. Twelve isolated runs passed without it, so I first dropped it as out of scope, but the full suite then failed on exactly this race. When a successor takes over a live watcher's lock, it deletes the lock and recreates it while holding `.watch.lock.steal`. If the old watcher checks during that gap, it sees no lock `pid` and exits as "state directory was torn down", not by standing down cleanly as the PR intends. That race only happens once this PR lets a healthy, live watcher's lock be taken. The guard treats a missing `pid` as teardown only when no `.steal` marker exists, with a comment explaining why. With it restored, 15 runs of the takeover test (three at a time, to add load) all passed, and all three PR tests passed in the full suite. **Remaining failures:** with the guard restored, I ran the full suite three times and it failed each time, but always on tests this change doesn't touch: "bounded child cleanup regression" twice and "bounded ledger cycle 2 did not start" once. The host's load average was about 100, and these tests depend on timing; one of them runs before any watcher starts. I didn't confirm they also fail on the base commit. shellcheck reports nothing in the test file beyond info notes about files it didn't follow, and one existing warning in `fm-watch.sh` at line 2598, not from this change. I deleted the leftover temporary runner `tests/.tmp-one.sh`. Nothing is committed or pushed

* fix(bin): re-read the watch lock holder after the steal check

The steal-gap guard read the lock pid, then the steal mutex. A successor
that removed and relinked the lock between those reads let the old
watcher see no pid and then no steal mutex, so it exited as "state
directory was torn down" instead of standing down. Upstream CI hit this
in tests/fm-watcher-lock.test.sh
(test_watch_replaces_live_holder_with_legacy_local_time_identity).

The teardown branch now re-reads the pid after the steal mutex. The
steal mutex is held for the whole remove-and-relink, so a steal that
finished between the first two reads has already relinked the lock by
the third read, and the self-eviction below stands the watcher down.

Verification:
- Drove: the takeover test (real bin/fm-watch.sh processes) 48 times,
  six at a time, with and without this change, plus the whole
  tests/fm-watcher-lock.test.sh file.
- Observed: the interleaving is too narrow to hit locally (48 of 48
  passed either way); the whole file passes with this change. The
  failing CI run shows the old watcher's exit 1 teardown message.
- Re-check: Behavior portable serial 6 on this PR's CI.

* no-mistakes(review): Scope fm_pid_identity residual comment to the watch lock

* no-mistakes(review): Align fm_pid_identity residual comment with autoarm reclaim behaviour

* no-mistakes(document): Note watch-lock identity mismatch skips lock stale grace

* fix(bin): tell a released watch lock from a torn-down state directory

A watcher replaced by a successor still exited 1 as "state directory was
torn down" on upstream CI. The successor that reclaims the lock delivers
its recovery wake and exits, releasing the lock, and on a fast runner
that happens before the old watcher's next poll. The old watcher then
found no lock holder and no steal in progress, which the teardown check
read as a recreated state directory.

The watcher now holds its state directory open (fd 6) from startup, and
a lock with no holder is a teardown only when the directory at that path
is no longer the one it holds; otherwise the lock was released by a
successor and the self-eviction stands the watcher down with exit 0. The
held descriptor keeps the inode from being reused by a recreated
directory. A host that cannot open a directory keeps the old reading.
This replaces the steal-marker check and pid re-read, which only covered
a successor still relinking the lock.

Verification:
- Drove: real bin/fm-watch.sh processes. A new regression,
  test_watch_replaced_holder_stands_down_after_successor_exits, pauses
  the old holder (SIGSTOP, only while it holds no other state lock) until
  the successor has delivered its wake and exited, then resumes it. Also
  a standalone run with the old watcher polling every 5s.
- Observed: on the previous head the old watcher exits 1 "state
  directory was torn down (singleton lock removed)", the CI failure,
  every time; with this change it exits 0 by standing down. Both
  takeover tests passed 20 of 20 runs four at a time on one loaded CPU.
  The teardown tests in tests/fm-watch-arm.test.sh (state directory and
  home removed) still pass.
- Re-check: tests/fm-watcher-lock.test.sh and Behavior portable serial 6.

* no-mistakes(test): Hold the watcher's state directory open before claiming the lock

* no-mistakes(document): Docs already match watch-lock identity reclaim change

---------

Co-authored-by: mangocabs2025 <250559406+mangocabs2025@users.noreply.github.com>

* fix(bin): fall back to perl when timeout is not GNU coreutils (#7911)

* Fix non-GNU timeout fallback

* no-mistakes(review): Assert INT reaches watcher in non-GNU timeout fallback test

* no-mistakes(document): Document GNU-only timeout selection in watch checkpoint

* no-mistakes(ci): Greptile flagged that only the non-GNU-timeout-to-Perl path had an isolated test. I added two isolated tests in tests/fm-watch-checkpoint.test.sh, as you asked. The production code is unchanged. The rule being tested: run_bounded must run GNU `timeout` first, then GNU `gtimeout`, then Perl. Whichever GNU command it runs must receive `--signal=INT --kill-after=<bound>s <seconds> <watcher>`. What changed: - **Shared setup:** a new helper, `make_isolated_checkpoint`, copies the checkpoint into a temporary root. It also builds a PATH that holds only the named host tools, so the stubs decide which timeout is found. The existing Perl-fallback test now uses this helper too. Its assertions are the same. - **Stubs:** a non-GNU stub reports `uutils` for `--version` and exits 137 if it is ever used. A GNU stub reports `GNU coreutils` and writes its own name and arguments to `$FM_HOME/timeout-calls`, then exits 124. - **`test_gnu_timeout_runs_the_watcher_bound`:** GNU `timeout` and GNU `gtimeout` are both on PATH. The test asserts exit 124, the quiet checkpoint line, and exactly one call: `timeout --signal=INT --kill-after=5s 1 <root>/bin/fm-watch.sh`. - **`test_non_gnu_timeout_uses_gnu_gtimeout`:** a non-GNU `timeout` is next to a GNU `gtimeout`. The test asserts the same exact call, made by `gtimeout`. - In both new tests, Perl is not on PATH. So if the code picked Perl by mistake, the run would fail with 127. How I checked it: - The full test file passes: all 14 tests. - I broke the code on purpose twice. When I swapped the order to try `gtimeout` first, the GNU timeout test failed. When the code always picked Perl, the run exited 127 instead of 124. I then put the production file back; `git status` shows only the test file changed. - `shellcheck -x` passes on the test file. This is a change to tests only, so there is nothing a user would see to check by hand

* fix: recover ownerless extension readiness records (#7933)

* fix: recover ownerless extension readiness and announce cleanup refusals

* no-mistakes(review): Reset cleanup failure episodes and classify failure wakes

* no-mistakes(document): Document ownerless readiness recovery and cleanup failure wakes

* no-mistakes(document): Clarify cleanup failure documentation ownership

---------

Co-authored-by: Kun Chen <3233006+kunchenguid@users.noreply.github.com>

* fix(bin): keep failed or non-schema remote reply reads out of captures (#7874)

* Keep malformed remote reply captures from wedging

* no-mistakes(document): Fix garbled remote reply source failure comment

* no-mistakes(document): Document remote reply failure handling

---------

Co-authored-by: Pitch Perfekt Collective <pitchperfekt@Pitchs-Mac-Studio.local>

* feat(bin): add per-project pr=manual registry token for worker-written PR text (#7937)

* feat(bin): per-project pr=manual registry token for hand-written PR text

A no-mistakes ship on a project where an outside maintainer reviews the PR let
the pipeline's pr step rewrite the hand-written title and body on every
validated push. The registry now records pr=manual, resolved by
fm-project-mode.sh --pr and carried by fm-brief.sh --pr, fm-spawn.sh and
fm-promote.sh like forge=. The generated brief skips pr and ci, and the worker
writes and publishes the PR text itself.

* no-mistakes(review): Drop pr_text key; fix manual-PR checks wait and base

* no-mistakes(review): Remove dead PR_TEXT and timeout example

* no-mistakes(document): Fix README pr=manual sentence grammar

* test(bin): restore the displaced placeholder comment and rename the spawn agreement test

The comment for the leftover-placeholder test sat above the new pr=manual tests.
The spawn test said it recorded the PR text, but it only checks that a launch happens.

* fix: refuse teardown when Git hides untracked files (#7909)

* fix(teardown): detect untracked work regardless of Git status config

* test(watcher): avoid blocking FIFO contention handshakes

* no-mistakes(document): Document hidden-untracked teardown safety

---------

Co-authored-by: Kun Chen <3233006+kunchenguid@users.noreply.github.com>

* fix(bin): keep newest run attribution in crew-state (#5954)

* fix: prefer current run over stale overview row

* fix: preserve newest run precedence over stale status

* no-mistakes(document): Document live-run precedence in crew-state attribution

* fix: use ledger order for same-minute run precedence

* test: cover both overview orders for same-minute run attribution

Document and pin newer-first (recorded AXI) and historical-first overview
orders. Same-minute ledger timestamps use row order as the tie-break so an
older live bare status cannot hide a newer completed run.

* no-mistakes(review): Treat failed as overridable terminal overview status

* no-mistakes(review): Fix equal-head live run precedence with identity ordering

* no-mistakes(document): Updated run identity ordering documentation

* no-mistakes(lint): Fix ShellCheck export warning

* no-mistakes(review): Prove same-head ordering or report unknown

* no-mistakes(review): Guard failed selected-run reads and drop dead same-head ordering

* no-mistakes(ci): I fixed both Greptile findings (ci-1, ci-2) in bin/fm-crew-state.sh. The change is in the working tree. I did not commit it, push it, or reply to the Greptile threads, because those steps belong to the outer pipeline. ci-1. Invariant: a live run from bare `axi status` may replace a terminal overview selection only when it is proven newer than every other run on the same branch. Previously the code compared it only against the selected run. Now crew-state reads each other candidate with `axi status --run <id>` and compares the live run against each one: - If another candidate is also live, it reports `unknown`, "competing live runs". This keeps the competing-live-runs check. - If two runs share a head and a ULID timestamp, it reports `unknown`, "same-head run ordering unverified", as before. - It promotes the live run only when it is proven newer than all other candidates. - If the live run is newer than the selected run but not proven newer than some other candidate, it reports `unknown`, "run ordering unverified", and names every run id. This means neither the stale selected run nor the live run can hide a newer failed run. This branch is the one judgement call: without it, the stale "done" row A would still hide C's failure. - In all other cases the overview's selection stands. The lib helper is now a pairwise compare called `fm_nm_run_is_newer_than` (it was `fm_nm_run_is_newer_than_selected`). The selected run's detail from the loop is reused when the read succeeded, as in the round-1 fix. I updated the sentence in docs/architecture.md to match. ci-2. Invariant: the `no-mistakes runs` ledger is read only to order runs with different heads. It is now fetched lazily, at most once, and only when a candidate's head differs from the live run's head. Same-head ULID comparisons never call it. Regression test: `test_live_run_newer_than_selection_does_not_hide_newer_failed_run` covers A (stale completed, listed first), C (newer failed) and B (live, created between them). All three share one head and use ULID ids. It expects `state: unknown`, C's id in the output, and no `state: working`. Before the fix it fails: with the fixed code stashed it printed `state: working ... run: 01M1...` (run B). On the original base 3fbace9f the overview would select A, so the output would be `done`, which also fails the `unknown` check. I did not run that base case. Verification: `bash tests/fm-crew-state.test.sh` passes in full ("all fm-crew-state tests passed", the new test included). `shellcheck` on the three changed shell files reports only the existing info-level SC1091 "not following sourced file" notes. No end-to-end run against a live no-mistakes daemon was possible here. I checked the change with the crew-state test harness and its fake `no-mistakes` CLI

---------

Co-authored-by: mehulbhagwani <mehulbhagwani@users.noreply.github.com>
Co-authored-by: Pitch Perfekt Collective <pitchperfekt@Pitchs-Mac-Studio.local>

* chore(ci): run the full suite on outside pull requests only after the full-ci label

Outside pull requests run only the coverage guard and repo invariants until the full-ci label is added; lint and every test lane wait.

A new Full suite check fails naming the full-ci label until it is added, and fails whenever a lane fails or is cancelled.

The label starts the full suite, and later pushes run it again; main pushes, own branches and write-access authors run everything as before.

Other labels run no job at all: their skipped checks take a 'Not run for label - ' prefix, so they cannot hide an earlier failure or a later pass.

Close main pushes keep only the newest run; CONTRIBUTING.md explains the label, and the full-ci label now exists.

* feat(bin): add opt-in systemone and openai decision providers to dispatch resolution (#7664)

* feat(bin): add opt-in systemone and openai providers to typed dispatch resolution

Extend the FM_DISPATCH_PROVIDER/FM_DISPATCH_MODEL seam with a generic
systemone provider (any System One-compatible host at FM_DISPATCH_BASE_URL,
optional FM_DISPATCH_API_KEY) and an openai provider that maps the Choice
request to OpenAI's Decisions API and its answer back. No provider set keeps
the original off line; the never-send check runs on the endpoint and the final
per-provider body. Live provider captures are recorded as pending.

Refs #7643, builds on #7149.

* docs(verification): record the live OpenAI Decisions capture for dispatch resolution

Add a dated 2026-10-23 section for the openai provider: 25 hand-labeled
synthetic briefs against gpt-6-luna, outcome and latency tables, the usage
and header fields actually returned, a calibration note, and one verbatim
request and response pair. The systemone live check stays pending.

Refs #7643.

* docs(verification): record the live Clef capture for the systemone provider

Replace the pending systemone section with a dated 2026-10-23 run against
Cloudflare Workers AI's @cf/cloudflare/clef, reached through a local
test-only relay because Workers AI serves System One at /ai/run/<model> in
a {result, success} envelope. Adds the outcome and latency tables, a
calibration note compared with the gpt-6-luna run, and one verbatim request
and envelope pair. A direct Workers AI option stays out of scope.

Refs #7643.

* feat(bin): promote agy to a full primary and secondmate harness (#7941)

* feat(agy): promote Antigravity CLI to full primary and secondmate harness

Add tracked .agents/hooks.json, bin/fm-sessionstart-agy.sh, bin/fm-turnend-guard-agy.sh, PreToolUse --agy seatbelt flags, session-lock agy ancestry, autoarm supervision model, and --secondmate agy workspace trust pre-registration and spawn support.

* no-mistakes(review): Fix agy Stop-hook park, hooks.json shape, and live coverage

* no-mistakes(review): Unbound agy Stop park, raise ceiling, prove live deny

* no-mistakes(review): Correct agy verification doc park-bound wording

* no-mistakes(document): Document agy as verified primary and secondmate harness

* no-mistakes(ci): I fixed all three selected findings, and every check I ran passed, including the live agy end-to-end run. **ci-1 (`tests/fm-agy-primary-live-e2e.test.sh`):** The invariant is that the live Stop-hook test passes only if a real watcher starts and its wake reaches a follow-up turn. The old test passed as soon as `.agy-park-owner` existed. I replaced the Stop-hook park block with the one the user specified. It waits until both `.agy-park-owner` and `.last-watcher-beat` exist, wakes the watcher with a `done:` status line, and asserts that the park owner was recorded, the watcher started, and `DONE` appears in the agy output. **ci-2 (agy away daemon):** The invariant is that `/afk` must not launch a separate away daemon on any primary whose home runs the supervision host. The agy Stop-hook guard already runs the host when it is enabled, but `fm_afk_launch_host_primary` left agy out. I added `agy` there, which is the one shared check all three callers use. I also added agy to: - the header comment in `bin/fm-afk-launch.sh`; - the three harness loops and the pass message in `tests/fm-afk-launch.test.sh`; - the primary lists and counts in `docs/supervision-host.md`, the matching lines in its engine-selection section, and a new Antigravity (`agy`) row in its Arm owners table; - the header comment in `bin/fm-supervision-instructions.sh`. **user-1 (`.agents/hooks.json`):** The invariant is that each hook command stays one script under Windows `cmd /c` and exits 0 when `sh` is missing. All 5 commands now use `sh -c "..." || cd .`. This does not change behaviour on Linux or macOS, because the `--agy` hooks report deny or continue as JSON on stdout and exit 0. The file keeps its live-verified `{"firstmate":{...}}` shape, matchers and 28800s Stop timeout. **Verification:** - `tests/fm-agy-primary.test.sh` passes, including running the SessionStart hook command from both `.agents/` and the repo root. - `tests/fm-afk-launch.test.sh` has no failures, and the new agy check passes. Its rex end-to-end cases were skipped because the rex CLI is not installed. - `tests/fm-supervision-instructions.test.sh` has no failures. - `bin/fm-lint.sh` and `bin/fm-doc-audience-check.sh` pass. - `FM_AGY_PRIMARY_LIVE=1 tests/fm-agy-primary-live-e2e.test.sh` printed all four `ok` lines and no failures, including "Stop hook parks on a real watcher and delivers its wake to a follow-up turn". The output went through `tail`, so the exit code shown is `tail`'s, not the test script's

* feat(bin): add shared_quota opt-out from quota-based dispatch ranking (#7894)

* feat(dispatch): add shared_quota home opt-out from quota-based ranking

A home whose Claude and other provider usage draws on one combined AI
budget has no meaningful per-provider quota rows, so spendPriority
ranking and runway gates pick the wrong candidate. An optional
top-level "shared_quota": true in config/crew-dispatch.json now opts
the home out: the typed resolver makes no quota-axi call, applies no
quota floor or runway gate, ranks nothing by spendPriority, and
resolves the matched rule's use profiles in declared order, printing
every candidate line with quota ranking off by home declaration.
Firstmate's quota-array-dispatch intake honors the same declaration.
Without the setting, behavior is unchanged. Non-boolean values are
actionable configuration errors in both the resolver and bootstrap.

* test(dispatch): cover shared-quota bypass of unmet rule and profile floors

The shared_quota opt-out test picked a rule with no quota floor, so the
separate rule-floor and profile-floor bypass paths stayed untested.
Two cases now run against the same fixture: a rule whose model:fable
floor (20%) exceeds the snapshot's 15%, and a profile whose all_models
floor (50%) exceeds codex's 31%, each asserting the declared-order pick
still wins with no quota-axi invocation.

* no-mistakes(review): Narrow shared-quota skill opt-out to quota-only gates

* no-mistakes(review): Document preferred_provider under shared_quota opt-out and test it

* no-mistakes(document): Document shared_quota in schema example and verification inventory

* fix(bin): distinguish recycled reaper PIDs in tombstone cleanup (#7958)

* fix(bin): distinguish recycled reaper PIDs in tombstone cleanup

* no-mistakes(ci): ci-2 fixed in tests/fm-watcher-lock.test.sh (test_lock_tombstone_tracks_reaper_start_time). Invariant: no fixture child may outlive a SIGKILLed runner without a bound. (1) The paused reaper's wait loop now also stops when FM_TEST_SUITE_PID is no longer alive or when SECONDS reaches FM_TEST_STUB_MAX_BLOCK_SECONDS. (2) The one sibling child in the same test, the unrelated `sleep 300`, now sleeps for FM_TEST_STUB_MAX_BLOCK_SECONDS so it uses the same bound. Verification, run serially: bash tests/fm-watcher-lock.test.sh. The new test passed on 4 of 4 runs. Red-before still holds: with the base bin/fm-wake-lib.sh from c9da5523, the test fails with 'not ok - recycled reaper pid kept an abandoned tombstone alive'. Separately, the known stand-down flake ('the replaced watcher did not stand down on its own', watch-legacy-local-time-identity) failed on every run on this host and also fails on base c9da5523 without this change, so the test file still exits 1; left unfixed as instructed. ci-1 (Full suite waiting on the full-ci maintainer label) was ignored per the user's decision

* feat(bin): allow omp as a remote secondmate harness (#7939)

* feat: allow omp as a remote secondmate harness

* test: cover omp on the remote secondmate gates

* fix: retire a remote secondmate whose busy state left with its home

* docs: record omp remote retirement evidence

* review: Refresh pinned remote doctor bootstrap checksum

* fix(bin): name a consumed branch grant instead of a wiring bug (#7969)

* fix(bin): name a consumed branch grant instead of a wiring bug

When a supervision branch's own acknowledgement consumes every granted
row, the drain removes the branch-eligible row snapshot while the owner
record stays live. A repeat drain or acknowledgement in the same turn then
refused with a message implying a broken handoff. Say instead that the
grant was already consumed; the refusal and its exit status are unchanged.

* no-mistakes(document): Document consumed-grant refusal in watcher continuity doc

---------

Co-authored-by: c-c6aw <225476801+c-c6aw@users.noreply.github.com>

* fix: preserve literal ampersands in spawn and supervision paths (#7906)

* feat(bin): read dispatch provider keys from a declared credential source (#5409)

* feat(dispatch): read Typesafe key from Keychain

* no-mistakes(review): Share Keychain key lookup with bootstrap; hard-code service name

* no-mistakes(review): Use one readable-secret Keychain check for bootstrap and resolver

* no-mistakes(document): Point AGENTS key row to owner; record Keychain bootstrap evidence

* feat(dispatch): read provider keys from a declared credential source

bin/fm-dispatch-resolve.sh took the typesafe.ai and OpenRouter keys only
from the environment or $FM_HOME/.env, so a home that keeps its key in the
macOS Keychain needed a wrapper to supply it, and the documented direct
call reported off.

Let the resolver consume an optional, provider-keyed declaration in the
effective config directory, config/dispatch-credential-sources.json. It
names where a key lives and never holds one. macos-keychain is the first
adapter (service, optional account), kept behind a small schema and adapter
registry in bin/fm-credential-source-lib.sh so the shared surface binds to
no one OS or provider.

- Precedence is the environment, then .env, then the declared source, which
  is read only when neither supplied a key and only for the selected
  provider.
- No entry and no key stays off, exactly as before. An unreadable or
  invalid declaration exits 2 with a line that names the problem and never
  a declared value.
- A declared source that this host cannot run, that yields no key, or that
  does not answer within FM_CREDENTIAL_SOURCE_TIMEOUT ends as a structured
  error outcome with nothing sent, so it is not mistaken for an
  unconfigured resolver.
- The key is captured into the same private variable as before and still
  reaches curl only as an fd 3 header. The adapter puts only the service
  and account on argv and discards the tool's stderr.
- --supports-credential-source <source> answers supported or unsupported
  without reading a declaration or running the credential tool, so an
  installer can refuse an unsupported activation before it writes anything.

The resolver tests cover the mapping, effective-home and provider
isolation, precedence, the three failure kinds, and secret containment
with a stubbed security and uname.

Closes #7879

* no-mistakes(review): Gate bootstrap typed checks on declared source; fix timeout

* no-mistakes(review): Document storing the declared Keychain item without access dialog

* no-mistakes(document): Clarify that only a typesafe declaration keeps resolver on

* no-mistakes(document): Merge dispatch key-source precedence into one configuration sentence

---------

Co-authored-by: Kun Chen <kunchenguid@users.noreply.github.com>

* fix: clean up remote reply temporary files and locks on exit (#6489)

* fix(bin): clean remote reply temp paths on every exit

The remote reply adapter left its temporary staging directory and fetch files behind on several exit paths.
The ingest staging directory leaked on the continuity-broken return, whose EXIT trap fired after its local tmp left scope.
The trap cmd_ingest installed also replaced the lifecycle-lock release of the handle subshell.
One EXIT trap now owns every temporary path, each lock subshell runs it before releasing its lock, and the empty hash no longer stages a file.
A test under a private TMPDIR covers the continuity return, a die after staging, a locked handle, and a signal during a document fetch.

* no-mistakes(document): Document remote-reply temporary-file cleanup

* no-mistakes(ci): Fixed ci-1 in tests/fm-remote-reply.test.sh: interrupt the blocked SSH child before waiting, fail if it already exited, and require adapter exit status 143 before checking cleanup. Confirmed the strengthened test rejects an adapter that ignores TERM; the temporary mutation was restored. The full remote-reply suite passed on a serial rerun, and syntax, pinned ShellCheck, and diff checks passed. One earlier run alongside lint timed out waiting for the third reply generation

* fix(bin): clean up the staged source-read output on every exit path

The source leg stages the remote read's output in a temporary file. Track it
with the adapter's other temporary paths so a signal during the read removes
it, and extend the regression test and docs to cover that path.

* chore: ignore Claude Code per-user settings (#6482)

* chore: gitignore Claude Code's per-user local settings file

* no-mistakes(ci): Addressed ci-1 by preserving the staged --no-index correction for both Claude settings assertions in tests/fm-gitignore-config.test.sh, making ignore-rule checks independent of tracking state. Reproduced the original false pass with tracked shared settings and an overly broad .claude/ rule; the corrected test rejects it. Verified normal tracked/untracked settings cases and rejection of a missing local-settings ignore rule. Targeted test runner, pinned ShellCheck, Bash syntax check, and diff checks all passed. No unrelated changes were made

* fix: prefilter inbox history for idempotent remote steering (#7905)

* fix(inbox): prefilter idempotent steering history

* no-mistakes(document): Clarify delivery mode in steering retry contract

* test(inbox): cover acknowledgement before prefilter opens

* feat(bin): add Kiro CLI as a crewmate/scout harness adapter (port of #7956) (#7979)

* feat(bin): add Kiro CLI as a crewmate/scout harness adapter

Port of #7956 onto current main so it gets a fresh CI run.

Adds a `kiro` (Kiro CLI, V2 engine) harness adapter, crewmate/scout only
(--secondmate launches are refused). fm-harness.sh detects it by kiro-cli
ancestry; fm-spawn.sh launches it with a per-task KIRO_HOME under
state/<id>.kiro-home (generated userPromptSubmit and stop hooks plus
chat.disableTrustAllConfirmation); busy, control, send, watch, procevent,
teardown and bootstrap wiring recognise it. Composer ghost-text and busy
footer matching is scoped to FM_COMPOSER_HARNESS=kiro, so other harnesses
read exactly as before. Adds references/harness/kiro.md,
docs/verification/kiro.md, tests/fm-kiro-harness.test.sh and an opt-in
live e2e signals guard.

Conflicts with main were resolved by keeping main's agy promotion and
adding kiro to the crewmate-only lists next to it.

Co-authored-by: kiatng <1106470+kiatng@users.noreply.github.com>
Co-authored-by: Marsjohn-11 <74795701+Marsjohn-11@users.noreply.github.com>

* fix(send): detect kiro on meta-less explicit targets

An explicit session:window send has no task meta, so TARGET_HARNESS stayed
empty and the kiro composer rules never applied. A finished kiro idle
placeholder then read as pending, extra Enters were pressed, and fm-send
exited 3 even though kiro accepted the message.

Resolve kiro from the live pane's foreground process group when meta is
absent, and keep every other explicit-target send on the unknown-harness
path. Move the kiro live e2e version probe to after the live gate so an
opted-out run never starts kiro-cli.

Co-authored-by: Kun Chen <kunchenguid@users.noreply.github.com>

---------

Co-authored-by: kiatng <1106470+kiatng@users.noreply.github.com>
Co-authored-by: Marsjohn-11 <74795701+Marsjohn-11@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Kun Chen <kunchenguid@users.noreply.github.com>

* fix(bin): publish hold origins only after backend success (#6777)

* fix(captain-hold): refuse a previous origin's answer after an incomplete hold move

A hold moved to a new origin wrote its stamp and origin before the backend
hold. A process stopped between those writes, or a refused hold whose rollback
also failed, left the task associated with the new origin while it carried
only the earlier call's answer, and complete and verify accepted that answer.

Verification now treats an open, unheld task that leads with a hold-set stamp
above a recorded answer as a re-hold that never completed, so the answer no
longer satisfies the new origin however the move was interrupted. A refused
hold also restores the body the attempt started from, and the origin lookup
runs before any write, so a clean failure leaves the earlier answer valid.

Closes #6461

* no-mistakes(review): Publish hold origins only after backend success

* no-mistakes(review): Publish verified holds before origin writes

* no-mistakes(document): Clarify hold-origin durability documentation and regression coverage

* no-mistakes(lint): Quote done subcommand to resolve ShellCheck warning

* no-mistakes(document): Clarify recorded-origin provenance guarantees

* feat(backends): add experimental explicit-only hc (herdr-core) runtime backend (#7963)

* feat(backends): add experimental explicit-only hc (herdr-core) runtime backend

herdr-core is the terminal core under Herdr.app and is not Herdr 1.
The adapter follows the tmux shape: one login-shell terminal per task,
Treehouse keeps the worktree, and fm-spawn drives it through the same
send/current-path primitives.

- bin/backends/hc.sh: create, capture, visible capture, send line, typed
  literal through hc keys, named keys, current path, composer state,
  submit, native busy state, recovery agent state from the foreground
  process and its process group, and a close that proves the terminal gone.
  Targets are <session>:<address>; every call pins that HC_SESSION, and an
  empty session never reaches hc. Task and home labels gate input and close.
- bin/fm-backend.sh, bin/fm-spawn.sh: hc arms, explicit-only selection,
  endpoint validation, hc_session/hc_terminal metadata, secondmate refusal.
- tests: fake-CLI suite and a real-hc smoke test on a private core.
- docs: hc-backend.md, configuration, verification record, README links.

* fix(hc): submit the spawn launch line by paste and add the hc liveness live guard

The launch line always carries a + that hc keys cannot type, so fm-spawn
pastes it with hc send and consumes the Enter that follows. The launch
environment floor keeps HC_SESSION, HC_TERMINAL_ID, HC_TERMINAL_SOCKET and
HC_SCOPE. tests/fm-backend-hc-liveness-live-e2e.test.sh launches every
installed harness bare in a private core and requires alive. The
verification record gains the end-to-end spawn, steer, peek and teardown run.

* no-mistakes(review): Allow hc interrupt keys and drop unused hc send_literal

* no-mistakes(document): Sync hc backend inventories and adapter header comment

* no-mistakes(ci): Fixed. When an hc task was torn down, the kill function read the task's expected label from the wrong argument, so it ended up accepting any terminal in the same home and could close another task's worker. - Invariant: every hc close must be gated by the task label that teardown passes as the third argument to fm_backend_kill. - Where it must hold: fm-teardown.sh calls `fm_backend_kill <backend> <target> <zellij_tab_id> fm-<id>` at all its sites (around lines 3482, 3491, 3494, 3876, 3986 and 3995). The dispatcher at bin/fm-backend.sh:1156 passes "$@" through to fm_backend_hc_kill, and that function is the only hc close path. So fixing that one function's arguments covers every teardown site. - Fix in bin/backends/hc.sh:279: the signature is now `<target> [unused] [expected-label]` and it reads `expected=${3:-'*'}`, the same shape tern, rex, cmux and paseo use. The label value matches what hc terminals carry: spawn creates them with firstmate.task=$W where W="fm-$ID" (bin/fm-spawn.sh:4545 and 4955), and teardown passes "fm-$ID". - New test in tests/fm-backend-hc.test.sh, test_kill_refuses_another_tasks_terminal, goes through the public fm_backend_kill path. A terminal labeled fm-other is refused for expected label fm-a1, stays alive and gets no `hc kill`. The terminal labeled fm-a1 is closed and removed. Before the fix the test failed ("expected a refusal"), and after it the whole suite passes. - Checks: `bash tests/fm-backend-hc.test.sh` passes every test and `shellcheck -x` is clean on both files. The live smoke and e2e hc tests call kill without a label, which keeps the existing behavior of accepting any task label from this home. I did not run them because they need a real herdr-core. VERIFIED with the unit tests on the fake hc CLI, not against a real hc core

* fix(hc): keep the live liveness guard from repointing the operator's claude

A real claude started under the guard's scratch XDG_DATA_HOME can self-update into it and repoint ~/.local/bin/claude there, leaving the link dangling once the scratch directory is removed.
Export DISABLE_AUTOUPDATER=1, as bin/fm-live-lab.sh already does for its live harnesses.

* fix(hc): drop an inherited HC_SOCKET so the session pin holds

* no-mistakes(document): Document hc dropping inherited HC_SOCKET for session pin

* no-mistakes(ci): I fixed both Greptile findings. The hc unit suite passes all 12 tests, three runs in a row, and `shellcheck -x` is clean on the 4 touched files. VERIFIED with unit tests (a fake hc CLI plus a real process group). NOT VERIFIED against a real hc core, because the live tests need herdr-core. ci-1, live tests could stop an unrelated core - Invariant: every direct `hc` call a test makes must reach only its private scratch core, so an inherited HC_SOCKET (which wins over HC_SESSION in hc 0.1.14) must never be set. - Where it must hold: the two suites that call `hc` directly (`hc server status` at startup and `hc server stop` in cleanup), `tests/fm-backend-hc-liveness-live-e2e.test.sh` and `tests/fm-backend-hc-smoke.test.sh`. Adapter calls already go through `fm_backend_hc_cli`, which drops HC_SOCKET. - Fix: both suites add HC_SOCKET to the `unset HC_TERMINAL_ID HC_TERMINAL_SOCKET HC_SCOPE` line, before any `hc` call. ci-2, a shell wrapper running a live worker was reported as dead - Invariant: `fm_backend_hc_agent_state` may return `dead` only when neither the foreground process nor anything else in its process group is a harness. - Where it must hold: there is one classification path, `bin/backends/hc.sh` around line 326. Before the fix, the `shell` branch returned `dead` before the process-group check ran. Callers such as the inbox ring and the watcher read this value through `fm_backend_agent_state`, so fixing this one function covers all of them. - Fix: the result is now `alive` when the foreground process is a harness. Otherwise the process group is checked, which can also give `alive`. After that a shell gives `dead` and anything else gives `ambiguous`. An idle shell, whose group holds no harness, is still `dead`, and the existing test_agent_state_classifies_foreground_and_absence still passes (`t2=dead`). - New test `test_agent_state_reads_a_shell_wrappers_group` in `tests/fm-backend-hc.test.sh`. It starts a real `bash` wrapper in its own process group with a child that runs as `claude`, and points the fake hc terminal's foreground at the wrapper. With the old code the test fails ("expected 'dead', got 'alive'"). With the fix it passes. The comment in the code was updated. `docs/hc-backend.md` already describes the process-group read, so it did not need a change. Not run: `fm-backend-hc-smoke.test.sh` and `fm-backend-hc-liveness-live-e2e.test.sh`, because they need a real hc core

* fix: refresh Herdr upstream references and licensing (#8000)

* docs(herdr): record the Apache-2.0 relicense and herdrdev org rename

Herdr relicensed from AGPL-3.0-or-later to Apache-2.0 in 0.8.0 and the
GitHub organization moved ogulcancelik/herdr to herdrdev/herdr. The old
release URLs redirect to the same assets, so the CI installer and the
version-floor guard now fetch via the canonical org with the pinned
version and checksums unchanged; verified end to end by running the
installer against the new URL.

* no-mistakes(document): Clarify Herdr product boundaries and preserve historical evidence

* fix(pi): stop repeated numbered and byte excerpt reads (#7992)

Fixes #7990

* fix(bin): keep the PR merge watch working when a worker with a PR is relaunched (#7996)

* Preserve PR poll authentication on relaunch

* no-mistakes(review): Keep trace and polytoken meta ahead of PR lines

* test: pin lock staleness in malformed presentation lock wake-queue case (#7837)

* fix(tests): pin lock staleness in malformed presentation lock case

A plain-file presentation lock older than FM_LOCK_STALE_AFTER (default 2s) is reclaimed as garbage, so a slow runner could age the malformed-lock fixture into a successful acquire. Pin the staleness window far above the case runtime so the case is deterministic.

* test(wake-queue): correct the malformed presentation lock staleness comment

---------

Co-authored-by: Trillium Smith <5898009+trillium@users.noreply.github.com>

* feat(bin): add configurable self-update source for /updatefirstmate (#5603)

* feat(bin): let /updatefirstmate follow a configured self-update source

An optional local config/self-update-source ("<remote> <branch>") makes
fm-update.sh fast-forward the primary from that one remote branch instead of
origin/<default>, under the same fast-forward-only guards, and makes local
secondmates advance to the primary's resulting commit (a standalone clone
imports it from the primary first). A home can then run its own fixes from a
branch that carries them on top of upstream, while worker spawns, review
diffs, the cleanup landed-work test, lint and default-branch detection keep
using origin, so new contributions still branch from upstream.

Absent, behaviour is unchanged. An unreadable or malformed file, an unknown
remote or an invalid branch name refuses the whole update before anything
moves rather than falling back to origin. A remote secondmate's host follows
its own code root's config, which the docs record as the limit.

* no-mistakes(document): List config/self-update-source in AGENTS.md config inventory

* no-mistakes(document): Mention self-update source in updatefirstmate skill description

* fix: bound watcher auto-arm failures and recover interrupted locks (#8018)

* fix(bin): commit the attended alarm from the exhausted Stop auto-arm

A Claude failure episode could suppress indefinitely without ever raising
the attended alarm. On every Stop cycle the auto-arm opens its generation
claim before the guard's sync-wait decision, so the guard always steps
aside; terminal_fail_open is never reached and no participant knew that
automatic continuation was exhausted. The block budget still climbed
because the guard's step-aside path accounts for the epoch, so Stops kept
rewaking with empty failed-suppressed bodies forever.

The auto-arm is the only participant that knows its own continuation is
exhausted, so it now owns the terminal escalation: once the failure
notice was consumed and the session block budget is over, the terminal
failure path commits .claude-autoarm-failure-alarmed and the
failed-suppressed outcome inside the owner lock (owner then budget, the
same order the guard's writer uses), then emits one loud final rewake
telling the operator to keep the session attended and diagnose the
Stop-hook supervision. A healthy watcher verified inside that hold resets
the episode instead of alarming, and a refused commit stays suppressed
without a false alarm.

Later Stops in the same episode see the alarm, record failed-suppressed,
and exit 0 so no further continuation or alarm is produced. Positive
watcher recovery still clears the notice, the alarm, and the budget.

Every failed-suppressed commit now carries a one-line stderr reason
naming why the operator notice is not repeated and whether the
Stop-owned retry stays alive, replacing the silent empty bodies that
made suppressed Stops indistinguishable from a wedged hook.

Adds an integrated guard/auto-arm regression driving both hooks through
the exhaustion boundary and asserting the single alarm, post-alarm
suppression, and clean recovery; updates existing tests for the reasoned
suppression contract.

* fix(bin): outlast an unpublished lock pid for one freshness window

CI run 40805704864 ("recovery drain after forced arm interruption")
failed because a dying watcher could not publish .watcher-down inside
its bounded cleanup window, so the drain saw no downtime marker to ack.

The blocker was an empty-pid lock artifact: fm_lock_claim and the
bounded-wait handoff published ownerdir/pid with a truncating write,
and a creator killed mid-write (the bounded handoff helper runs under
timeout -k with a process-group KILL) left a resolvable symlink whose
pid file stayed empty forever. fm_lock_try_acquire treats that as a
fresh mid-acquire hold for a full freshness window, cannot steal it,
and a bounded waiter whose bound equals the window gave up before the
evidence expired.

Two changes. First, both pid writes now go through a same-directory
pid.tmp file renamed into place, so a killed write can no longer leave
a live lock with a permanently empty pid; fm_lock_clean_known_files
sweeps leftover tmp files. Second, fm_lock_acquire_wait_max polls one
extra freshness window when the remaining blocker still has no
published pid, so a waiter outlives the residue instead of failing at
its bound; the moment a pid publishes or the artifact goes stale the
ordinary live-holder and steal rules apply unchanged, and published
live holders keep the original bound.

Adds a regression test that links an owner dir with no pid and asserts
the bounded wait outlasts the freshness window to reclaim it, while a
live holder still fails at the nominal bound; verified to fail against
the pre-change implementation.

* no-mistakes(review): Route every suppressed exit through alarm decision

* no-mistakes(document): Clarify exhaustion and lock-wait documentation

* no-mistakes(lint): Quote empty grace deadline assignment for ShellCheck

* no-mistakes(ci): Fixed tests/fm-x-mode.test.sh: atomic lock-pid publication consumed its overly broad injected mv failure. Targeted the counter-record destination and asserted injection occurred. Reproduced failure before fix; full X-mode test script, pinned lint, bash syntax, and diff checks pass afterward. Full suite failure is downstream of this lane failure; no separate fix needed

* no-mistakes(ci): Fixed Full suite’s underlying shard timeout: the PR marker test’s broad mv failure injection blocked atomic lock-PID publication indefinitely. Restricted injection to the marker destination. Reproduced the hang before fixing; targeted regression, all 49 PR-security tests, ShellCheck, bash syntax, and diff checks pass

* no-mistakes(ci): Fixed load-sensitive remote lifecycle test timeout: all three inheritance/launch barrier waits now honor the existing convergence budget instead of failing after 30 seconds. Full suite failure is downstream of this shard. Full lifecycle E2E, Bash syntax, ShellCheck excluding SC1091, and diff checks pass. Production behavior unchanged

* no-mistakes(ci): Fixed remote-reply fixture races, preserved the committing auto-arm’s final rewake on signals, and asserted the live-holder wait bound. Remote-reply and turnend-guard suites and focused lock test pass; signal regression fails before fix and passes after. Full watcher-lock suite fails earlier in an unchanged macOS watcher-replacement test. Full suite CI failure is downstream of the shard failure

* no-mistakes(ci): Fixed teardown race in tests/fm-watch-arm.test.sh: atomically rename state/home/root fixtures away before deleting contents after process exit. Preserved all existing assertions; production code unchanged. Affected suite passed three runs, including two concurrent copies; targeted unpublished-PID lock test and syntax/diff checks passed. Additional full lock suite failed twice at a separate watcher-replacement exit assertion. Standalone ShellCheck reported existing warnings

* fix(bin): cut stat forks in the wake drain by reading identity and size together (#6271)

Local cherry-pick of https://github.com/kunchenguid/firstmate/pull/6271 pending upstream merge.

* fix(bin): keep pr= merge-poll identity last when recording captain-hold completion (#6732)

* fix(bin): keep PR merge polls authenticated across relaunch

A relaunch rewrote the task record with control_relaunch_tx after the
preserved pr= line. fm_pr_metadata_identity_parse rejects any key after
pr= other than pr_head= and x_*, so the watcher stopped authenticating
the armed merge poll and reported it as an unauthenticated state check,
and the merged-PR wake never arrived. Write the transaction id before
the preserved lines, as fm-remote-secondmate-relaunch.sh already does.

* no-mistakes(review): Keep pr= last for traceparent and completion writes

* no-mistakes(document): Note completion record placement ahead of pr= lines

* no-mistakes(ci): Fixed the Greptile P1 finding (ci-1) as the user decided. **Invariant:** a task's `.meta` record holds exactly one `decisions_reviewed`/`decision_keys` pair, and it sits before `pr=`. Then `meta_value` (which reads the last match) returns the current inventory, and `fm_pr_metadata_identity_parse` still sees `pr=` last. The only place that writes this pair is the awk rewrite in `command_complete` (`bin/fm-captain-hold.sh`). The other hits for these keys under `bin/` are only a comment and an error message. `verify` and later `complete` calls read the pair through `meta_value`, so fixing this one writer fixes them too. **Fix:** added one …
trillium added a commit to trillium/firstmate that referenced this pull request Nov 4, 2026
* feat(bin): opt-in spawn base from the primary checkout for local-only work (#7352)

* feat(bin): add opt-in config/spawn-base-primary-checkout for local landings

A fresh pooled task worktree is reset to origin/<default>. A local-only
project lands work on the primary checkout's default branch through
fm-merge-local.sh and never pushes, so that ref stays frozen at the last
push and every fresh task starts behind work already landed, loading the
project's instruction files from the stale tree. The always-on fix proposed
in #3812 replaced the specified origin-only refresh for every home; this
rework keeps that rule as the default and moves the new base behind an
explicit, default-off presence flag, following the existing config/<flag>
pattern.

With config/spawn-base-primary-checkout present:
- fm-spawn.sh starts a fresh local-only ship, or a scout without
  --base-branch, from the primary checkout's <default> when it strictly
  contains origin's tip. Publishing modes and named base branches keep
  origin's tip, because that work is delivered against origin. A diverged
  primary keeps origin's tip and prints a note counting both sides. The
  commit is read from the local object store, so nothing extra is fetched,
  and the clean-slot refusal still runs first.
- fm-review-diff.sh anchors a remote-backed task without base_branch= on the
  branch it delivers to: publishing modes stay on origin/<default>, while a
  local-only ship or a scout is compared against whichever of the local
  <default> and origin/<default> meets the branch later, so the review shows
  the task's own work instead of every locally landed commit.
- fm-promote.sh tells a scout promoted to a publishing mode to return to
  origin's default branch, because in this home the scout may have started
  from the primary checkout's branch, whose unpushed commits would otherwise
  be published with the work.

fm-dod-lib.sh gains fm_mode_publishes as the one predicate those three
readers share. Without the flag every path is unchanged: the spawn resets
to origin's tip, the review anchors on origin/<default>, and promotion keeps
its wording; the existing tests run unmodified. Treehouse 3 (verified on
3.1.3) already hands a slot out at whichever of the local and remote default
branch is further ahead, so with the flag the refresh keeps that slot where
Treehouse put it for a local landing instead of rewinding it, and a project
without origin is untouched as before.

Supersedes #3812.

* no-mistakes(document): Drop change-relative wording from spawn-base config docs

* no-mistakes(ci): The Greptile Review check failed on two review findings, not on a broken build or test. I fixed both as the user directed, and the tests and lint pass. ci-1 (bin/fm-promote.sh): promotion must name origin's default branch only when spawn could actually have started the scout from the primary checkout. Spawn does that only when the project has an origin remote and is recorded on the task. Before this fix, the opt-in flag alone made promotion to no-mistakes or direct-PR say "copy of origin's default branch...", even on a project with no origin. - The new wording now also requires a recorded project (`[ -n "$PROMOTE_PROJECT" ]`) whose `git remote get-url origin` succeeds. That is the same check bin/fm-review-diff.sh already makes. The empty-project guard is needed because `git -C ""` would run in the current directory. Otherwise the existing "default-branch base" wording stays. - The three places that read the flag now agree: spawn, review-diff and promote. - I updated the header and inline comments in fm-promote.sh, and the promote line in docs/configuration.md, to say this applies only to a project with an origin remote. - Test: `test_promote_names_origin_for_a_publishing_mode_in_an_opted_in_home` in tests/fm-task-delivery.test.sh now records a real `project=` with a registry entry, and covers flag on/off × origin/none × direct-PR/no-mistakes/local-only. Only flag on + origin + a publishing mode gets the new wording. The named-base case is unchanged. - Before the fix, the test fails with "not ok - flag on, remote none, direct-PR: the promotion changed the default-branch wording". With the fix, it passes. ci-2 (tests/fm-spawn-pool-base-freshen.test.sh): with the flag set, both publishing modes must start from origin's tip and print no divergence note. - The opted-in spawn test now covers no-mistakes as well as direct-PR, local-only and scout. - The expectations no longer single out direct-PR. Both publishing modes now expect origin's tip, no "note: pooled worktree", and a review anchored at the slot's start, in the leading, diverged and trailing cases. Verification: - `bash tests/fm-task-delivery.test.sh`: exit 0. - `bash tests/fm-spawn-pool-base-freshen.test.sh`: exit 0. - `bin/fm-lint.sh` on the three changed shell files: exit 0 (ShellCheck 0.11.0, pinned, with extended analysis)

* fix: preserve whitespace when proving patches landed (#7910)

* fix: report unavailable Git containment proofs during teardown (#7915)

* fix(teardown): distinguish unavailable content-landed proof

* no-mistakes(document): Clarify teardown proof failure documentation

* no-mistakes(ci): Captain, CI failed in unchanged watcher recovery code, independent of this PR. The focused failing case passed locally with exit 0. The full suite stalled earlier and was stopped. No tracked changes. Command guard rejected cleanup; scratch remains at .ci-7915/ and tests/.ci-7915-cycle.sh

* chore: untrack CI validation scratch

* feat(bin): prefer a configured provider family in dispatch resolution (#7876)

* feat(dispatch): prefer configured provider family

* no-mistakes(review): drop policy_why field and dead auth fixture from preference tests

* no-mistakes(document): docs: record preferred_provider in schema, diagnostics, verification

* fix: pin local-only merges to the accepted done commit (#7916)

* fix: pin local-only landing to its accepted done head

Persist the accepted local-only commit in task metadata and refuse landing when the branch or the recorded head changes. Merge the full commit ID under the task control and metadata locks.

Closes https://github.com/kunchenguid/firstmate/issues/7782

* no-mistakes(test): Refuse local landing races with atomic ref transactions

* no-mistakes(document): Document pinned local landing and recovery contracts

* no-mistakes(ci): Applied only the verified incremental patch and preserved existing repairs. Complete diff matches the supplied candidate hash. Both focused test files, default lint, and source-aware lint passed with exit 0. Evidence retained at /tmp/up7782-local-repair/ci-phase-fresh-*. No commits, pushes, or pipeline-control actions performed; publication remains with the outer executor

* no-mistakes(ci): Fixed both SC2031 false positives in tests/fm-merge-local.test.sh with narrowly scoped suppressions. Tier 2 lint correction; runtime changes were unnecessary. Default lint, source-aware lint, all 8 focused tests, and git diff --check passed. No commits, pushes, or pipeline-control actions performed

* fix: coalesce repeated extension host errors (#6548) (#7928)

* fix(procevent): coalesce unhandled extension host errors

* no-mistakes(document): Document host-error coalescing and recovery semantics

* fix: preserve wake grants when queue-lock acquisition fails (#7912)

* fix: stop wake grants when lock acquisition fails

* no-mistakes(document): Document wake grant lock acquisition failure behavior

* fix(bin): send remote second mate steers over stdin (#7902)

* fix: send remote steers over stdin

* fix: version remote stdin send protocol

* no-mistakes(document): document stdin transport for remote steer in fm-send header

* no-mistakes(ci): Two tests failed in CI. One is caused by this PR; the other is not. 1. Behavior portable serial 5: `tests/fm-secondmate-reconcile.test.sh` failed with "supervision did not deliver the durable reconcile request later". This PR caused it. The PR now sends a remote steer's body on stdin, using `fm-on.sh --stdin` with the `send-stdin` verb. This test's fake ssh started with `cat > /dev/null`, so it threw the body away before it ran the real `fm-remote-secondmate-control.sh`. `cmd_send_stdin` then read an empty message, died with "remote steer message must be nonempty", and no inbox record was written. Rule that broke: a fake ssh that runs the real remote leg must pass the caller's stdin through, as real ssh does. I checked every fake ssh that runs the real leg. `fm-send-remote-delivery.test.sh` already passes stdin through. `fm-secondmate-sync.test.sh` (`make_remote_leg_ssh_stub`) had the same discard line. The stub in `fm-send-resolve-key.test.sh` never runs the leg, so it is fine. The fix deletes the `cat > /dev/null` line in the reconcile and sync stubs. Calls made without `--stdin` still get /dev/null from fm-on, so nothing else changes. Checks run locally: the reconcile test fails before the fix with the same CI message. After the fix, the reconcile test passes (rc=0) and the sync test passes (rc=0). 2. Behavior portable serial 3: `tests/fm-wake-queue.test.sh` failed in `test_concurrent_append_and_drain` with "wake drain: queue lock could not be acquired safely". This PR did not cause it. The PR does not touch `bin/fm-wake-drain.sh`, the wake tests or the wake helpers. The failure is lock contention: 40 appenders run at the same time as a drain, on a loaded CI runner. Locally the whole test passed (70 ok, rc=0). I made no change for it. It is an existing flake in wake-queue lock acquisition and needs its own fix outside this PR. Open PR #7912 ("preserve wake grants when queue-lock acquisition fails") works in the same area

* fix(bin): stop herdr server_ensure from starting servers an external owner manages (#7357)

* fix(herdr): never start a server an external owner manages or is replacing

fm_backend_herdr_server_ensure started a detached herdr server whenever
status reported the session not running. When a service manager owns the
server, that races a unit restart or a server live-handoff and splits panes
across two servers.

The session directory reported by herdr session list can now carry a
firstmate-server-owner marker (persistent, naming the owner) and a
firstmate-server-replacing marker (for the duration of a restart or handoff).
While either exists and the server is not running, server_ensure never starts
a server: it waits a bounded time (FM_BACKEND_HERDR_EXTERNAL_SERVER_POLLS,
default 30s) for the server to report running, and otherwise fails naming the
owner or the replacement. A running server is still used at once, and a
session with no marker keeps the Firstmate-owned autostart unchanged.

Fixes #7320

* no-mistakes(review): Enforce herdr replacement marker on fast path; fixed wait bound

* no-mistakes(ci): Both CI failures had one cause in this PR, and I fixed it in code; no test assertions changed. `fm_backend_herdr_server_ensure` had started running `herdr session list --json` on every call to find the session directory for the ownership markers. Two existing tests treat that call as a sign of something else: - `tests/fm-control-relaunch.test.sh` failed with "a herdr reclaim touched a session the record does not name: session list --json", because it allows only `--session fmlab` calls and `status --json`. - `tests/fm-backend-herdr-presentation-e2e.test.sh` failed with "opted-out spawn added presentation-ordering capability or socket calls", because there `session list` means presentation ordering ran. Invariant: `server_ensure` must not make Herdr calls beyond its own `status` read, so ordinary spawns and reclaims stay free of `session list` and only touch the session they name. Every caller goes through `server_ensure`, so fixing it there covers all of them. Fix (`bin/backends/herdr.sh`): the session directory now comes from the `status --json` read `server_ensure` already makes. It is the directory containing `.server.socket`. I removed the `fm_backend_herdr_session_dir` helper. On a running server, the only added work is one check for the replacement marker, which is what the user asked for. I checked this against real Herdr 0.9.5: - `status` reports the socket even when the server is stopped, for both the default and named sessions. - The socket's directory is the same `session_dir` that `session list` reports, and it follows `XDG_CONFIG_HOME`. - With `--session`, an inherited `HERDR_SOCKET_PATH` does not change it. - The read creates nothing on disk. If a Herdr version omits the socket, `server_ensure` keeps the old Firstmate-owned behavior, as the docs already said for a missing `session_dir`. Other changes: the marker-test fakes now report the socket under the session directory, and I removed the `session list` stub this PR had added to the shared fake. `docs/herdr-backend.md` and `docs/verification/runtime-backends.md` ("Session directory") now describe and record the `status`-socket measurement. Verification: - `tests/fm-backend-herdr.test.sh` passes: 239 ok, 0 not ok, including all the externally-managed and replacement-marker tests. - `tests/fm-control-relaunch.test.sh` passes; it was the shard 3 failure. - shellcheck shows only existing info-level notes. Not verified locally: the real-Herdr presentation test. Here it stopped earlier, at an unrelated Treehouse timeout ("treehouse get did not enter an isolated worktree within 60s"). After the fix `server_ensure` no longer runs `session list`, which is the call that assertion caught. No lab session was left running, and I removed the test's temp directory

* fix: reset idle backoff for actionable heartbeat wakes (#7903)

* fix: classify actionable heartbeat backstop as a check

* no-mistakes(document): Correct heartbeat routing docs and remove stale test count

* fix: preserve heartbeat routing when resetting actionable backoff

* fix(bin): reclaim a live watch lock whose pid-identity no longer recomputes (#7931)

* fix(bin): reclaim a lock whose recorded pid-identity no longer recomputes

#7886 made fm_lock_holder_alive reject a live pid whose start time no
longer matches the lock's recorded pid-start. A holder that predates that
record still falls back to pid liveness, which leaves issue #7801 open: on
a /proc-less host outside UTC, a watcher started before fm_pid_identity
pinned TZ=UTC0 recorded a local-time pid-identity. After the update that
live holder no longer matches its own identity, so the health predicate
rejects it, yet every new watcher stands down beside it and the home stays
unsupervised.

fm_lock_holder_alive now also requires a recorded pid-identity, when
present, to still recompute for the pid, after the existing start-time
check and with the same missing-evidence fallbacks: no record, a pid
rewritten mid-read, or an unreadable value keeps the pid-liveness answer.
Both records go through one helper, _fm_lock_record_matches. Only
long-lived holders that never exec write a pid-identity (the watcher, the
supervise daemon), so a genuine holder still matches. A watcher replaced
this way stands down unsignalled at its next poll through the existing
self-eviction. The fm_pid_identity comment and docs/turnend-guard.md
claimed the upgrade-window residual is cleared by the post-update restart,
which never reaches a primary home's own watcher; they now say the next
lock claim clears it.

Verification:
- Drove: real bin/fm-watch.sh processes with /proc hidden through
  FM_PROC_ROOT_OVERRIDE and TZ=America/Los_Angeles: a live genuine watcher
  whose lock record was rewritten to its own local-time ps lstart identity
  with no pid-start, as a pre-pin build wrote it, then a fresh watcher;
  plus fm_lock_try_acquire against a live pid with a mismatched, matching,
  and unrecorded pid-identity and no pid-start.
- Observed: on the unchanged library the fresh watcher exits "lock held by
  live pid ... but heartbeat is stale" and fm_lock_try_acquire returns
  held for the mismatch. With this change the fresh watcher takes the
  lock, the legacy holder exits 0 by standing down, the live pid is never
  signalled, and matching or unrecorded identities stay held.
- Re-check: tests/fm-watcher-lock.test.sh cases
  test_watch_replaces_live_holder_with_legacy_local_time_identity and
  test_lock_reclaims_holder_whose_identity_no_longer_recomputes.

* no-mistakes(review): Limit pid-identity lock reclaim to the watch lock

* no-mistakes(document): Correct fm_lock_holder_alive comment on non-watch identity locks

* no-mistakes(ci): I made two small fixes. CI and "Require no-mistakes" never ran: GitHub shows both as `action_required`, waiting for approval to run workflows from a fork, so the code didn't cause those. Greptile failed because it scored the PR 4/5 against a required 5/5, with one P2 comment. 1. **Greptile P2, test children left running (`tests/fm-watcher-lock.test.sh`).** The two new lock tests start a `sleep 300` holder that only gets killed after every assertion passes, and the suite's cleanup only reaps processes whose command line contains the fixture root. Each holder now starts as `(exec -a "$dir/holder" sleep 300)`, so cleanup reaps it if the test fails early. To check, I forced a `fail` right after the child starts: on HEAD the `sleep 300` was still running afterwards, and with the fix it was reaped. Both tests pass normally. 2. **Flaky takeover test (`bin/fm-watch.sh`).** This edit was already uncommitted in the worktree. Twelve isolated runs passed without it, so I first dropped it as out of scope, but the full suite then failed on exactly this race. When a successor takes over a live watcher's lock, it deletes the lock and recreates it while holding `.watch.lock.steal`. If the old watcher checks during that gap, it sees no lock `pid` and exits as "state directory was torn down", not by standing down cleanly as the PR intends. That race only happens once this PR lets a healthy, live watcher's lock be taken. The guard treats a missing `pid` as teardown only when no `.steal` marker exists, with a comment explaining why. With it restored, 15 runs of the takeover test (three at a time, to add load) all passed, and all three PR tests passed in the full suite. **Remaining failures:** with the guard restored, I ran the full suite three times and it failed each time, but always on tests this change doesn't touch: "bounded child cleanup regression" twice and "bounded ledger cycle 2 did not start" once. The host's load average was about 100, and these tests depend on timing; one of them runs before any watcher starts. I didn't confirm they also fail on the base commit. shellcheck reports nothing in the test file beyond info notes about files it didn't follow, and one existing warning in `fm-watch.sh` at line 2598, not from this change. I deleted the leftover temporary runner `tests/.tmp-one.sh`. Nothing is committed or pushed

* fix(bin): re-read the watch lock holder after the steal check

The steal-gap guard read the lock pid, then the steal mutex. A successor
that removed and relinked the lock between those reads let the old
watcher see no pid and then no steal mutex, so it exited as "state
directory was torn down" instead of standing down. Upstream CI hit this
in tests/fm-watcher-lock.test.sh
(test_watch_replaces_live_holder_with_legacy_local_time_identity).

The teardown branch now re-reads the pid after the steal mutex. The
steal mutex is held for the whole remove-and-relink, so a steal that
finished between the first two reads has already relinked the lock by
the third read, and the self-eviction below stands the watcher down.

Verification:
- Drove: the takeover test (real bin/fm-watch.sh processes) 48 times,
  six at a time, with and without this change, plus the whole
  tests/fm-watcher-lock.test.sh file.
- Observed: the interleaving is too narrow to hit locally (48 of 48
  passed either way); the whole file passes with this change. The
  failing CI run shows the old watcher's exit 1 teardown message.
- Re-check: Behavior portable serial 6 on this PR's CI.

* no-mistakes(review): Scope fm_pid_identity residual comment to the watch lock

* no-mistakes(review): Align fm_pid_identity residual comment with autoarm reclaim behaviour

* no-mistakes(document): Note watch-lock identity mismatch skips lock stale grace

* fix(bin): tell a released watch lock from a torn-down state directory

A watcher replaced by a successor still exited 1 as "state directory was
torn down" on upstream CI. The successor that reclaims the lock delivers
its recovery wake and exits, releasing the lock, and on a fast runner
that happens before the old watcher's next poll. The old watcher then
found no lock holder and no steal in progress, which the teardown check
read as a recreated state directory.

The watcher now holds its state directory open (fd 6) from startup, and
a lock with no holder is a teardown only when the directory at that path
is no longer the one it holds; otherwise the lock was released by a
successor and the self-eviction stands the watcher down with exit 0. The
held descriptor keeps the inode from being reused by a recreated
directory. A host that cannot open a directory keeps the old reading.
This replaces the steal-marker check and pid re-read, which only covered
a successor still relinking the lock.

Verification:
- Drove: real bin/fm-watch.sh processes. A new regression,
  test_watch_replaced_holder_stands_down_after_successor_exits, pauses
  the old holder (SIGSTOP, only while it holds no other state lock) until
  the successor has delivered its wake and exited, then resumes it. Also
  a standalone run with the old watcher polling every 5s.
- Observed: on the previous head the old watcher exits 1 "state
  directory was torn down (singleton lock removed)", the CI failure,
  every time; with this change it exits 0 by standing down. Both
  takeover tests passed 20 of 20 runs four at a time on one loaded CPU.
  The teardown tests in tests/fm-watch-arm.test.sh (state directory and
  home removed) still pass.
- Re-check: tests/fm-watcher-lock.test.sh and Behavior portable serial 6.

* no-mistakes(test): Hold the watcher's state directory open before claiming the lock

* no-mistakes(document): Docs already match watch-lock identity reclaim change

---------

Co-authored-by: mangocabs2025 <250559406+mangocabs2025@users.noreply.github.com>

* fix(bin): fall back to perl when timeout is not GNU coreutils (#7911)

* Fix non-GNU timeout fallback

* no-mistakes(review): Assert INT reaches watcher in non-GNU timeout fallback test

* no-mistakes(document): Document GNU-only timeout selection in watch checkpoint

* no-mistakes(ci): Greptile flagged that only the non-GNU-timeout-to-Perl path had an isolated test. I added two isolated tests in tests/fm-watch-checkpoint.test.sh, as you asked. The production code is unchanged. The rule being tested: run_bounded must run GNU `timeout` first, then GNU `gtimeout`, then Perl. Whichever GNU command it runs must receive `--signal=INT --kill-after=<bound>s <seconds> <watcher>`. What changed: - **Shared setup:** a new helper, `make_isolated_checkpoint`, copies the checkpoint into a temporary root. It also builds a PATH that holds only the named host tools, so the stubs decide which timeout is found. The existing Perl-fallback test now uses this helper too. Its assertions are the same. - **Stubs:** a non-GNU stub reports `uutils` for `--version` and exits 137 if it is ever used. A GNU stub reports `GNU coreutils` and writes its own name and arguments to `$FM_HOME/timeout-calls`, then exits 124. - **`test_gnu_timeout_runs_the_watcher_bound`:** GNU `timeout` and GNU `gtimeout` are both on PATH. The test asserts exit 124, the quiet checkpoint line, and exactly one call: `timeout --signal=INT --kill-after=5s 1 <root>/bin/fm-watch.sh`. - **`test_non_gnu_timeout_uses_gnu_gtimeout`:** a non-GNU `timeout` is next to a GNU `gtimeout`. The test asserts the same exact call, made by `gtimeout`. - In both new tests, Perl is not on PATH. So if the code picked Perl by mistake, the run would fail with 127. How I checked it: - The full test file passes: all 14 tests. - I broke the code on purpose twice. When I swapped the order to try `gtimeout` first, the GNU timeout test failed. When the code always picked Perl, the run exited 127 instead of 124. I then put the production file back; `git status` shows only the test file changed. - `shellcheck -x` passes on the test file. This is a change to tests only, so there is nothing a user would see to check by hand

* fix: recover ownerless extension readiness records (#7933)

* fix: recover ownerless extension readiness and announce cleanup refusals

* no-mistakes(review): Reset cleanup failure episodes and classify failure wakes

* no-mistakes(document): Document ownerless readiness recovery and cleanup failure wakes

* no-mistakes(document): Clarify cleanup failure documentation ownership

---------

Co-authored-by: Kun Chen <3233006+kunchenguid@users.noreply.github.com>

* fix(bin): keep failed or non-schema remote reply reads out of captures (#7874)

* Keep malformed remote reply captures from wedging

* no-mistakes(document): Fix garbled remote reply source failure comment

* no-mistakes(document): Document remote reply failure handling

---------

Co-authored-by: Pitch Perfekt Collective <pitchperfekt@Pitchs-Mac-Studio.local>

* feat(bin): add per-project pr=manual registry token for worker-written PR text (#7937)

* feat(bin): per-project pr=manual registry token for hand-written PR text

A no-mistakes ship on a project where an outside maintainer reviews the PR let
the pipeline's pr step rewrite the hand-written title and body on every
validated push. The registry now records pr=manual, resolved by
fm-project-mode.sh --pr and carried by fm-brief.sh --pr, fm-spawn.sh and
fm-promote.sh like forge=. The generated brief skips pr and ci, and the worker
writes and publishes the PR text itself.

* no-mistakes(review): Drop pr_text key; fix manual-PR checks wait and base

* no-mistakes(review): Remove dead PR_TEXT and timeout example

* no-mistakes(document): Fix README pr=manual sentence grammar

* test(bin): restore the displaced placeholder comment and rename the spawn agreement test

The comment for the leftover-placeholder test sat above the new pr=manual tests.
The spawn test said it recorded the PR text, but it only checks that a launch happens.

* fix: refuse teardown when Git hides untracked files (#7909)

* fix(teardown): detect untracked work regardless of Git status config

* test(watcher): avoid blocking FIFO contention handshakes

* no-mistakes(document): Document hidden-untracked teardown safety

---------

Co-authored-by: Kun Chen <3233006+kunchenguid@users.noreply.github.com>

* fix(bin): keep newest run attribution in crew-state (#5954)

* fix: prefer current run over stale overview row

* fix: preserve newest run precedence over stale status

* no-mistakes(document): Document live-run precedence in crew-state attribution

* fix: use ledger order for same-minute run precedence

* test: cover both overview orders for same-minute run attribution

Document and pin newer-first (recorded AXI) and historical-first overview
orders. Same-minute ledger timestamps use row order as the tie-break so an
older live bare status cannot hide a newer completed run.

* no-mistakes(review): Treat failed as overridable terminal overview status

* no-mistakes(review): Fix equal-head live run precedence with identity ordering

* no-mistakes(document): Updated run identity ordering documentation

* no-mistakes(lint): Fix ShellCheck export warning

* no-mistakes(review): Prove same-head ordering or report unknown

* no-mistakes(review): Guard failed selected-run reads and drop dead same-head ordering

* no-mistakes(ci): I fixed both Greptile findings (ci-1, ci-2) in bin/fm-crew-state.sh. The change is in the working tree. I did not commit it, push it, or reply to the Greptile threads, because those steps belong to the outer pipeline. ci-1. Invariant: a live run from bare `axi status` may replace a terminal overview selection only when it is proven newer than every other run on the same branch. Previously the code compared it only against the selected run. Now crew-state reads each other candidate with `axi status --run <id>` and compares the live run against each one: - If another candidate is also live, it reports `unknown`, "competing live runs". This keeps the competing-live-runs check. - If two runs share a head and a ULID timestamp, it reports `unknown`, "same-head run ordering unverified", as before. - It promotes the live run only when it is proven newer than all other candidates. - If the live run is newer than the selected run but not proven newer than some other candidate, it reports `unknown`, "run ordering unverified", and names every run id. This means neither the stale selected run nor the live run can hide a newer failed run. This branch is the one judgement call: without it, the stale "done" row A would still hide C's failure. - In all other cases the overview's selection stands. The lib helper is now a pairwise compare called `fm_nm_run_is_newer_than` (it was `fm_nm_run_is_newer_than_selected`). The selected run's detail from the loop is reused when the read succeeded, as in the round-1 fix. I updated the sentence in docs/architecture.md to match. ci-2. Invariant: the `no-mistakes runs` ledger is read only to order runs with different heads. It is now fetched lazily, at most once, and only when a candidate's head differs from the live run's head. Same-head ULID comparisons never call it. Regression test: `test_live_run_newer_than_selection_does_not_hide_newer_failed_run` covers A (stale completed, listed first), C (newer failed) and B (live, created between them). All three share one head and use ULID ids. It expects `state: unknown`, C's id in the output, and no `state: working`. Before the fix it fails: with the fixed code stashed it printed `state: working ... run: 01M1...` (run B). On the original base 3fbace9f the overview would select A, so the output would be `done`, which also fails the `unknown` check. I did not run that base case. Verification: `bash tests/fm-crew-state.test.sh` passes in full ("all fm-crew-state tests passed", the new test included). `shellcheck` on the three changed shell files reports only the existing info-level SC1091 "not following sourced file" notes. No end-to-end run against a live no-mistakes daemon was possible here. I checked the change with the crew-state test harness and its fake `no-mistakes` CLI

---------

Co-authored-by: mehulbhagwani <mehulbhagwani@users.noreply.github.com>
Co-authored-by: Pitch Perfekt Collective <pitchperfekt@Pitchs-Mac-Studio.local>

* chore(ci): run the full suite on outside pull requests only after the full-ci label

Outside pull requests run only the coverage guard and repo invariants until the full-ci label is added; lint and every test lane wait.

A new Full suite check fails naming the full-ci label until it is added, and fails whenever a lane fails or is cancelled.

The label starts the full suite, and later pushes run it again; main pushes, own branches and write-access authors run everything as before.

Other labels run no job at all: their skipped checks take a 'Not run for label - ' prefix, so they cannot hide an earlier failure or a later pass.

Close main pushes keep only the newest run; CONTRIBUTING.md explains the label, and the full-ci label now exists.

* feat(bin): add opt-in systemone and openai decision providers to dispatch resolution (#7664)

* feat(bin): add opt-in systemone and openai providers to typed dispatch resolution

Extend the FM_DISPATCH_PROVIDER/FM_DISPATCH_MODEL seam with a generic
systemone provider (any System One-compatible host at FM_DISPATCH_BASE_URL,
optional FM_DISPATCH_API_KEY) and an openai provider that maps the Choice
request to OpenAI's Decisions API and its answer back. No provider set keeps
the original off line; the never-send check runs on the endpoint and the final
per-provider body. Live provider captures are recorded as pending.

Refs #7643, builds on #7149.

* docs(verification): record the live OpenAI Decisions capture for dispatch resolution

Add a dated 2026-10-23 section for the openai provider: 25 hand-labeled
synthetic briefs against gpt-6-luna, outcome and latency tables, the usage
and header fields actually returned, a calibration note, and one verbatim
request and response pair. The systemone live check stays pending.

Refs #7643.

* docs(verification): record the live Clef capture for the systemone provider

Replace the pending systemone section with a dated 2026-10-23 run against
Cloudflare Workers AI's @cf/cloudflare/clef, reached through a local
test-only relay because Workers AI serves System One at /ai/run/<model> in
a {result, success} envelope. Adds the outcome and latency tables, a
calibration note compared with the gpt-6-luna run, and one verbatim request
and envelope pair. A direct Workers AI option stays out of scope.

Refs #7643.

* feat(bin): promote agy to a full primary and secondmate harness (#7941)

* feat(agy): promote Antigravity CLI to full primary and secondmate harness

Add tracked .agents/hooks.json, bin/fm-sessionstart-agy.sh, bin/fm-turnend-guard-agy.sh, PreToolUse --agy seatbelt flags, session-lock agy ancestry, autoarm supervision model, and --secondmate agy workspace trust pre-registration and spawn support.

* no-mistakes(review): Fix agy Stop-hook park, hooks.json shape, and live coverage

* no-mistakes(review): Unbound agy Stop park, raise ceiling, prove live deny

* no-mistakes(review): Correct agy verification doc park-bound wording

* no-mistakes(document): Document agy as verified primary and secondmate harness

* no-mistakes(ci): I fixed all three selected findings, and every check I ran passed, including the live agy end-to-end run. **ci-1 (`tests/fm-agy-primary-live-e2e.test.sh`):** The invariant is that the live Stop-hook test passes only if a real watcher starts and its wake reaches a follow-up turn. The old test passed as soon as `.agy-park-owner` existed. I replaced the Stop-hook park block with the one the user specified. It waits until both `.agy-park-owner` and `.last-watcher-beat` exist, wakes the watcher with a `done:` status line, and asserts that the park owner was recorded, the watcher started, and `DONE` appears in the agy output. **ci-2 (agy away daemon):** The invariant is that `/afk` must not launch a separate away daemon on any primary whose home runs the supervision host. The agy Stop-hook guard already runs the host when it is enabled, but `fm_afk_launch_host_primary` left agy out. I added `agy` there, which is the one shared check all three callers use. I also added agy to: - the header comment in `bin/fm-afk-launch.sh`; - the three harness loops and the pass message in `tests/fm-afk-launch.test.sh`; - the primary lists and counts in `docs/supervision-host.md`, the matching lines in its engine-selection section, and a new Antigravity (`agy`) row in its Arm owners table; - the header comment in `bin/fm-supervision-instructions.sh`. **user-1 (`.agents/hooks.json`):** The invariant is that each hook command stays one script under Windows `cmd /c` and exits 0 when `sh` is missing. All 5 commands now use `sh -c "..." || cd .`. This does not change behaviour on Linux or macOS, because the `--agy` hooks report deny or continue as JSON on stdout and exit 0. The file keeps its live-verified `{"firstmate":{...}}` shape, matchers and 28800s Stop timeout. **Verification:** - `tests/fm-agy-primary.test.sh` passes, including running the SessionStart hook command from both `.agents/` and the repo root. - `tests/fm-afk-launch.test.sh` has no failures, and the new agy check passes. Its rex end-to-end cases were skipped because the rex CLI is not installed. - `tests/fm-supervision-instructions.test.sh` has no failures. - `bin/fm-lint.sh` and `bin/fm-doc-audience-check.sh` pass. - `FM_AGY_PRIMARY_LIVE=1 tests/fm-agy-primary-live-e2e.test.sh` printed all four `ok` lines and no failures, including "Stop hook parks on a real watcher and delivers its wake to a follow-up turn". The output went through `tail`, so the exit code shown is `tail`'s, not the test script's

* feat(bin): add shared_quota opt-out from quota-based dispatch ranking (#7894)

* feat(dispatch): add shared_quota home opt-out from quota-based ranking

A home whose Claude and other provider usage draws on one combined AI
budget has no meaningful per-provider quota rows, so spendPriority
ranking and runway gates pick the wrong candidate. An optional
top-level "shared_quota": true in config/crew-dispatch.json now opts
the home out: the typed resolver makes no quota-axi call, applies no
quota floor or runway gate, ranks nothing by spendPriority, and
resolves the matched rule's use profiles in declared order, printing
every candidate line with quota ranking off by home declaration.
Firstmate's quota-array-dispatch intake honors the same declaration.
Without the setting, behavior is unchanged. Non-boolean values are
actionable configuration errors in both the resolver and bootstrap.

* test(dispatch): cover shared-quota bypass of unmet rule and profile floors

The shared_quota opt-out test picked a rule with no quota floor, so the
separate rule-floor and profile-floor bypass paths stayed untested.
Two cases now run against the same fixture: a rule whose model:fable
floor (20%) exceeds the snapshot's 15%, and a profile whose all_models
floor (50%) exceeds codex's 31%, each asserting the declared-order pick
still wins with no quota-axi invocation.

* no-mistakes(review): Narrow shared-quota skill opt-out to quota-only gates

* no-mistakes(review): Document preferred_provider under shared_quota opt-out and test it

* no-mistakes(document): Document shared_quota in schema example and verification inventory

* fix(bin): distinguish recycled reaper PIDs in tombstone cleanup (#7958)

* fix(bin): distinguish recycled reaper PIDs in tombstone cleanup

* no-mistakes(ci): ci-2 fixed in tests/fm-watcher-lock.test.sh (test_lock_tombstone_tracks_reaper_start_time). Invariant: no fixture child may outlive a SIGKILLed runner without a bound. (1) The paused reaper's wait loop now also stops when FM_TEST_SUITE_PID is no longer alive or when SECONDS reaches FM_TEST_STUB_MAX_BLOCK_SECONDS. (2) The one sibling child in the same test, the unrelated `sleep 300`, now sleeps for FM_TEST_STUB_MAX_BLOCK_SECONDS so it uses the same bound. Verification, run serially: bash tests/fm-watcher-lock.test.sh. The new test passed on 4 of 4 runs. Red-before still holds: with the base bin/fm-wake-lib.sh from c9da5523, the test fails with 'not ok - recycled reaper pid kept an abandoned tombstone alive'. Separately, the known stand-down flake ('the replaced watcher did not stand down on its own', watch-legacy-local-time-identity) failed on every run on this host and also fails on base c9da5523 without this change, so the test file still exits 1; left unfixed as instructed. ci-1 (Full suite waiting on the full-ci maintainer label) was ignored per the user's decision

* feat(bin): allow omp as a remote secondmate harness (#7939)

* feat: allow omp as a remote secondmate harness

* test: cover omp on the remote secondmate gates

* fix: retire a remote secondmate whose busy state left with its home

* docs: record omp remote retirement evidence

* review: Refresh pinned remote doctor bootstrap checksum

* fix(bin): name a consumed branch grant instead of a wiring bug (#7969)

* fix(bin): name a consumed branch grant instead of a wiring bug

When a supervision branch's own acknowledgement consumes every granted
row, the drain removes the branch-eligible row snapshot while the owner
record stays live. A repeat drain or acknowledgement in the same turn then
refused with a message implying a broken handoff. Say instead that the
grant was already consumed; the refusal and its exit status are unchanged.

* no-mistakes(document): Document consumed-grant refusal in watcher continuity doc

---------

Co-authored-by: c-c6aw <225476801+c-c6aw@users.noreply.github.com>

* fix: preserve literal ampersands in spawn and supervision paths (#7906)

* feat(bin): read dispatch provider keys from a declared credential source (#5409)

* feat(dispatch): read Typesafe key from Keychain

* no-mistakes(review): Share Keychain key lookup with bootstrap; hard-code service name

* no-mistakes(review): Use one readable-secret Keychain check for bootstrap and resolver

* no-mistakes(document): Point AGENTS key row to owner; record Keychain bootstrap evidence

* feat(dispatch): read provider keys from a declared credential source

bin/fm-dispatch-resolve.sh took the typesafe.ai and OpenRouter keys only
from the environment or $FM_HOME/.env, so a home that keeps its key in the
macOS Keychain needed a wrapper to supply it, and the documented direct
call reported off.

Let the resolver consume an optional, provider-keyed declaration in the
effective config directory, config/dispatch-credential-sources.json. It
names where a key lives and never holds one. macos-keychain is the first
adapter (service, optional account), kept behind a small schema and adapter
registry in bin/fm-credential-source-lib.sh so the shared surface binds to
no one OS or provider.

- Precedence is the environment, then .env, then the declared source, which
  is read only when neither supplied a key and only for the selected
  provider.
- No entry and no key stays off, exactly as before. An unreadable or
  invalid declaration exits 2 with a line that names the problem and never
  a declared value.
- A declared source that this host cannot run, that yields no key, or that
  does not answer within FM_CREDENTIAL_SOURCE_TIMEOUT ends as a structured
  error outcome with nothing sent, so it is not mistaken for an
  unconfigured resolver.
- The key is captured into the same private variable as before and still
  reaches curl only as an fd 3 header. The adapter puts only the service
  and account on argv and discards the tool's stderr.
- --supports-credential-source <source> answers supported or unsupported
  without reading a declaration or running the credential tool, so an
  installer can refuse an unsupported activation before it writes anything.

The resolver tests cover the mapping, effective-home and provider
isolation, precedence, the three failure kinds, and secret containment
with a stubbed security and uname.

Closes #7879

* no-mistakes(review): Gate bootstrap typed checks on declared source; fix timeout

* no-mistakes(review): Document storing the declared Keychain item without access dialog

* no-mistakes(document): Clarify that only a typesafe declaration keeps resolver on

* no-mistakes(document): Merge dispatch key-source precedence into one configuration sentence

---------

Co-authored-by: Kun Chen <kunchenguid@users.noreply.github.com>

* fix: clean up remote reply temporary files and locks on exit (#6489)

* fix(bin): clean remote reply temp paths on every exit

The remote reply adapter left its temporary staging directory and fetch files behind on several exit paths.
The ingest staging directory leaked on the continuity-broken return, whose EXIT trap fired after its local tmp left scope.
The trap cmd_ingest installed also replaced the lifecycle-lock release of the handle subshell.
One EXIT trap now owns every temporary path, each lock subshell runs it before releasing its lock, and the empty hash no longer stages a file.
A test under a private TMPDIR covers the continuity return, a die after staging, a locked handle, and a signal during a document fetch.

* no-mistakes(document): Document remote-reply temporary-file cleanup

* no-mistakes(ci): Fixed ci-1 in tests/fm-remote-reply.test.sh: interrupt the blocked SSH child before waiting, fail if it already exited, and require adapter exit status 143 before checking cleanup. Confirmed the strengthened test rejects an adapter that ignores TERM; the temporary mutation was restored. The full remote-reply suite passed on a serial rerun, and syntax, pinned ShellCheck, and diff checks passed. One earlier run alongside lint timed out waiting for the third reply generation

* fix(bin): clean up the staged source-read output on every exit path

The source leg stages the remote read's output in a temporary file. Track it
with the adapter's other temporary paths so a signal during the read removes
it, and extend the regression test and docs to cover that path.

* chore: ignore Claude Code per-user settings (#6482)

* chore: gitignore Claude Code's per-user local settings file

* no-mistakes(ci): Addressed ci-1 by preserving the staged --no-index correction for both Claude settings assertions in tests/fm-gitignore-config.test.sh, making ignore-rule checks independent of tracking state. Reproduced the original false pass with tracked shared settings and an overly broad .claude/ rule; the corrected test rejects it. Verified normal tracked/untracked settings cases and rejection of a missing local-settings ignore rule. Targeted test runner, pinned ShellCheck, Bash syntax check, and diff checks all passed. No unrelated changes were made

* fix: prefilter inbox history for idempotent remote steering (#7905)

* fix(inbox): prefilter idempotent steering history

* no-mistakes(document): Clarify delivery mode in steering retry contract

* test(inbox): cover acknowledgement before prefilter opens

* feat(bin): add Kiro CLI as a crewmate/scout harness adapter (port of #7956) (#7979)

* feat(bin): add Kiro CLI as a crewmate/scout harness adapter

Port of #7956 onto current main so it gets a fresh CI run.

Adds a `kiro` (Kiro CLI, V2 engine) harness adapter, crewmate/scout only
(--secondmate launches are refused). fm-harness.sh detects it by kiro-cli
ancestry; fm-spawn.sh launches it with a per-task KIRO_HOME under
state/<id>.kiro-home (generated userPromptSubmit and stop hooks plus
chat.disableTrustAllConfirmation); busy, control, send, watch, procevent,
teardown and bootstrap wiring recognise it. Composer ghost-text and busy
footer matching is scoped to FM_COMPOSER_HARNESS=kiro, so other harnesses
read exactly as before. Adds references/harness/kiro.md,
docs/verification/kiro.md, tests/fm-kiro-harness.test.sh and an opt-in
live e2e signals guard.

Conflicts with main were resolved by keeping main's agy promotion and
adding kiro to the crewmate-only lists next to it.

Co-authored-by: kiatng <1106470+kiatng@users.noreply.github.com>
Co-authored-by: Marsjohn-11 <74795701+Marsjohn-11@users.noreply.github.com>

* fix(send): detect kiro on meta-less explicit targets

An explicit session:window send has no task meta, so TARGET_HARNESS stayed
empty and the kiro composer rules never applied. A finished kiro idle
placeholder then read as pending, extra Enters were pressed, and fm-send
exited 3 even though kiro accepted the message.

Resolve kiro from the live pane's foreground process group when meta is
absent, and keep every other explicit-target send on the unknown-harness
path. Move the kiro live e2e version probe to after the live gate so an
opted-out run never starts kiro-cli.

Co-authored-by: Kun Chen <kunchenguid@users.noreply.github.com>

---------

Co-authored-by: kiatng <1106470+kiatng@users.noreply.github.com>
Co-authored-by: Marsjohn-11 <74795701+Marsjohn-11@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Kun Chen <kunchenguid@users.noreply.github.com>

* fix(bin): publish hold origins only after backend success (#6777)

* fix(captain-hold): refuse a previous origin's answer after an incomplete hold move

A hold moved to a new origin wrote its stamp and origin before the backend
hold. A process stopped between those writes, or a refused hold whose rollback
also failed, left the task associated with the new origin while it carried
only the earlier call's answer, and complete and verify accepted that answer.

Verification now treats an open, unheld task that leads with a hold-set stamp
above a recorded answer as a re-hold that never completed, so the answer no
longer satisfies the new origin however the move was interrupted. A refused
hold also restores the body the attempt started from, and the origin lookup
runs before any write, so a clean failure leaves the earlier answer valid.

Closes #6461

* no-mistakes(review): Publish hold origins only after backend success

* no-mistakes(review): Publish verified holds before origin writes

* no-mistakes(document): Clarify hold-origin durability documentation and regression coverage

* no-mistakes(lint): Quote done subcommand to resolve ShellCheck warning

* no-mistakes(document): Clarify recorded-origin provenance guarantees

* feat(backends): add experimental explicit-only hc (herdr-core) runtime backend (#7963)

* feat(backends): add experimental explicit-only hc (herdr-core) runtime backend

herdr-core is the terminal core under Herdr.app and is not Herdr 1.
The adapter follows the tmux shape: one login-shell terminal per task,
Treehouse keeps the worktree, and fm-spawn drives it through the same
send/current-path primitives.

- bin/backends/hc.sh: create, capture, visible capture, send line, typed
  literal through hc keys, named keys, current path, composer state,
  submit, native busy state, recovery agent state from the foreground
  process and its process group, and a close that proves the terminal gone.
  Targets are <session>:<address>; every call pins that HC_SESSION, and an
  empty session never reaches hc. Task and home labels gate input and close.
- bin/fm-backend.sh, bin/fm-spawn.sh: hc arms, explicit-only selection,
  endpoint validation, hc_session/hc_terminal metadata, secondmate refusal.
- tests: fake-CLI suite and a real-hc smoke test on a private core.
- docs: hc-backend.md, configuration, verification record, README links.

* fix(hc): submit the spawn launch line by paste and add the hc liveness live guard

The launch line always carries a + that hc keys cannot type, so fm-spawn
pastes it with hc send and consumes the Enter that follows. The launch
environment floor keeps HC_SESSION, HC_TERMINAL_ID, HC_TERMINAL_SOCKET and
HC_SCOPE. tests/fm-backend-hc-liveness-live-e2e.test.sh launches every
installed harness bare in a private core and requires alive. The
verification record gains the end-to-end spawn, steer, peek and teardown run.

* no-mistakes(review): Allow hc interrupt keys and drop unused hc send_literal

* no-mistakes(document): Sync hc backend inventories and adapter header comment

* no-mistakes(ci): Fixed. When an hc task was torn down, the kill function read the task's expected label from the wrong argument, so it ended up accepting any terminal in the same home and could close another task's worker. - Invariant: every hc close must be gated by the task label that teardown passes as the third argument to fm_backend_kill. - Where it must hold: fm-teardown.sh calls `fm_backend_kill <backend> <target> <zellij_tab_id> fm-<id>` at all its sites (around lines 3482, 3491, 3494, 3876, 3986 and 3995). The dispatcher at bin/fm-backend.sh:1156 passes "$@" through to fm_backend_hc_kill, and that function is the only hc close path. So fixing that one function's arguments covers every teardown site. - Fix in bin/backends/hc.sh:279: the signature is now `<target> [unused] [expected-label]` and it reads `expected=${3:-'*'}`, the same shape tern, rex, cmux and paseo use. The label value matches what hc terminals carry: spawn creates them with firstmate.task=$W where W="fm-$ID" (bin/fm-spawn.sh:4545 and 4955), and teardown passes "fm-$ID". - New test in tests/fm-backend-hc.test.sh, test_kill_refuses_another_tasks_terminal, goes through the public fm_backend_kill path. A terminal labeled fm-other is refused for expected label fm-a1, stays alive and gets no `hc kill`. The terminal labeled fm-a1 is closed and removed. Before the fix the test failed ("expected a refusal"), and after it the whole suite passes. - Checks: `bash tests/fm-backend-hc.test.sh` passes every test and `shellcheck -x` is clean on both files. The live smoke and e2e hc tests call kill without a label, which keeps the existing behavior of accepting any task label from this home. I did not run them because they need a real herdr-core. VERIFIED with the unit tests on the fake hc CLI, not against a real hc core

* fix(hc): keep the live liveness guard from repointing the operator's claude

A real claude started under the guard's scratch XDG_DATA_HOME can self-update into it and repoint ~/.local/bin/claude there, leaving the link dangling once the scratch directory is removed.
Export DISABLE_AUTOUPDATER=1, as bin/fm-live-lab.sh already does for its live harnesses.

* fix(hc): drop an inherited HC_SOCKET so the session pin holds

* no-mistakes(document): Document hc dropping inherited HC_SOCKET for session pin

* no-mistakes(ci): I fixed both Greptile findings. The hc unit suite passes all 12 tests, three runs in a row, and `shellcheck -x` is clean on the 4 touched files. VERIFIED with unit tests (a fake hc CLI plus a real process group). NOT VERIFIED against a real hc core, because the live tests need herdr-core. ci-1, live tests could stop an unrelated core - Invariant: every direct `hc` call a test makes must reach only its private scratch core, so an inherited HC_SOCKET (which wins over HC_SESSION in hc 0.1.14) must never be set. - Where it must hold: the two suites that call `hc` directly (`hc server status` at startup and `hc server stop` in cleanup), `tests/fm-backend-hc-liveness-live-e2e.test.sh` and `tests/fm-backend-hc-smoke.test.sh`. Adapter calls already go through `fm_backend_hc_cli`, which drops HC_SOCKET. - Fix: both suites add HC_SOCKET to the `unset HC_TERMINAL_ID HC_TERMINAL_SOCKET HC_SCOPE` line, before any `hc` call. ci-2, a shell wrapper running a live worker was reported as dead - Invariant: `fm_backend_hc_agent_state` may return `dead` only when neither the foreground process nor anything else in its process group is a harness. - Where it must hold: there is one classification path, `bin/backends/hc.sh` around line 326. Before the fix, the `shell` branch returned `dead` before the process-group check ran. Callers such as the inbox ring and the watcher read this value through `fm_backend_agent_state`, so fixing this one function covers all of them. - Fix: the result is now `alive` when the foreground process is a harness. Otherwise the process group is checked, which can also give `alive`. After that a shell gives `dead` and anything else gives `ambiguous`. An idle shell, whose group holds no harness, is still `dead`, and the existing test_agent_state_classifies_foreground_and_absence still passes (`t2=dead`). - New test `test_agent_state_reads_a_shell_wrappers_group` in `tests/fm-backend-hc.test.sh`. It starts a real `bash` wrapper in its own process group with a child that runs as `claude`, and points the fake hc terminal's foreground at the wrapper. With the old code the test fails ("expected 'dead', got 'alive'"). With the fix it passes. The comment in the code was updated. `docs/hc-backend.md` already describes the process-group read, so it did not need a change. Not run: `fm-backend-hc-smoke.test.sh` and `fm-backend-hc-liveness-live-e2e.test.sh`, because they need a real hc core

* fix: refresh Herdr upstream references and licensing (#8000)

* docs(herdr): record the Apache-2.0 relicense and herdrdev org rename

Herdr relicensed from AGPL-3.0-or-later to Apache-2.0 in 0.8.0 and the
GitHub organization moved ogulcancelik/herdr to herdrdev/herdr. The old
release URLs redirect to the same assets, so the CI installer and the
version-floor guard now fetch via the canonical org with the pinned
version and checksums unchanged; verified end to end by running the
installer against the new URL.

* no-mistakes(document): Clarify Herdr product boundaries and preserve historical evidence

* fix(pi): stop repeated numbered and byte excerpt reads (#7992)

Fixes #7990

* fix(bin): keep the PR merge watch working when a worker with a PR is relaunched (#7996)

* Preserve PR poll authentication on relaunch

* no-mistakes(review): Keep trace and polytoken meta ahead of PR lines

* test: pin lock staleness in malformed presentation lock wake-queue case (#7837)

* fix(tests): pin lock staleness in malformed presentation lock case

A plain-file presentation lock older than FM_LOCK_STALE_AFTER (default 2s) is reclaimed as garbage, so a slow runner could age the malformed-lock fixture into a successful acquire. Pin the staleness window far above the case runtime so the case is deterministic.

* test(wake-queue): correct the malformed presentation lock staleness comment

---------

Co-authored-by: Trillium Smith <5898009+trillium@users.noreply.github.com>

* feat(bin): add configurable self-update source for /updatefirstmate (#5603)

* feat(bin): let /updatefirstmate follow a configured self-update source

An optional local config/self-update-source ("<remote> <branch>") makes
fm-update.sh fast-forward the primary from that one remote branch instead of
origin/<default>, under the same fast-forward-only guards, and makes local
secondmates advance to the primary's resulting commit (a standalone clone
imports it from the primary first). A home can then run its own fixes from a
branch that carries them on top of upstream, while worker spawns, review
diffs, the cleanup landed-work test, lint and default-branch detection keep
using origin, so new contributions still branch from upstream.

Absent, behaviour is unchanged. An unreadable or malformed file, an unknown
remote or an invalid branch name refuses the whole update before anything
moves rather than falling back to origin. A remote secondmate's host follows
its own code root's config, which the docs record as the limit.

* no-mistakes(document): List config/self-update-source in AGENTS.md config inventory

* no-mistakes(document): Mention self-update source in updatefirstmate skill description

* fix: bound watcher auto-arm failures and recover interrupted locks (#8018)

* fix(bin): commit the attended alarm from the exhausted Stop auto-arm

A Claude failure episode could suppress indefinitely without ever raising
the attended alarm. On every Stop cycle the auto-arm opens its generation
claim before the guard's sync-wait decision, so the guard always steps
aside; terminal_fail_open is never reached and no participant knew that
automatic continuation was exhausted. The block budget still climbed
because the guard's step-aside path accounts for the epoch, so Stops kept
rewaking with empty failed-suppressed bodies forever.

The auto-arm is the only participant that knows its own continuation is
exhausted, so it now owns the terminal escalation: once the failure
notice was consumed and the session block budget is over, the terminal
failure path commits .claude-autoarm-failure-alarmed and the
failed-suppressed outcome inside the owner lock (owner then budget, the
same order the guard's writer uses), then emits one loud final rewake
telling the operator to keep the session attended and diagnose the
Stop-hook supervision. A healthy watcher verified inside that hold resets
the episode instead of alarming, and a refused commit stays suppressed
without a false alarm.

Later Stops in the same episode see the alarm, record failed-suppressed,
and exit 0 so no further continuation or alarm is produced. Positive
watcher recovery still clears the notice, the alarm, and the budget.

Every failed-suppressed commit now carries a one-line stderr reason
naming why the operator notice is not repeated and whether the
Stop-owned retry stays alive, replacing the silent empty bodies that
made suppressed Stops indistinguishable from a wedged hook.

Adds an integrated guard/auto-arm regression driving both hooks through
the exhaustion boundary and asserting the single alarm, post-alarm
suppression, and clean recovery; updates existing tests for the reasoned
suppression contract.

* fix(bin): outlast an unpublished lock pid for one freshness window

CI run 40805704864 ("recovery drain after forced arm interruption")
failed because a dying watcher could not publish .watcher-down inside
its bounded cleanup window, so the drain saw no downtime marker to ack.

The blocker was an empty-pid lock artifact: fm_lock_claim and the
bounded-wait handoff published ownerdir/pid with a truncating write,
and a creator killed mid-write (the bounded handoff helper runs under
timeout -k with a process-group KILL) left a resolvable symlink whose
pid file stayed empty forever. fm_lock_try_acquire treats that as a
fresh mid-acquire hold for a full freshness window, cannot steal it,
and a bounded waiter whose bound equals the window gave up before the
evidence expired.

Two changes. First, both pid writes now go through a same-directory
pid.tmp file renamed into place, so a killed write can no longer leave
a live lock with a permanently empty pid; fm_lock_clean_known_files
sweeps leftover tmp files. Second, fm_lock_acquire_wait_max polls one
extra freshness window when the remaining blocker still has no
published pid, so a waiter outlives the residue instead of failing at
its bound; the moment a pid publishes or the artifact goes stale the
ordinary live-holder and steal rules apply unchanged, and published
live holders keep the original bound.

Adds a regression test that links an owner dir with no pid and asserts
the bounded wait outlasts the freshness window to reclaim it, while a
live holder still fails at the nominal bound; verified to fail against
the pre-change implementation.

* no-mistakes(review): Route every suppressed exit through alarm decision

* no-mistakes(document): Clarify exhaustion and lock-wait documentation

* no-mistakes(lint): Quote empty grace deadline assignment for ShellCheck

* no-mistakes(ci): Fixed tests/fm-x-mode.test.sh: atomic lock-pid publication consumed its overly broad injected mv failure. Targeted the counter-record destination and asserted injection occurred. Reproduced failure before fix; full X-mode test script, pinned lint, bash syntax, and diff checks pass afterward. Full suite failure is downstream of this lane failure; no separate fix needed

* no-mistakes(ci): Fixed Full suite’s underlying shard timeout: the PR marker test’s broad mv failure injection blocked atomic lock-PID publication indefinitely. Restricted injection to the marker destination. Reproduced the hang before fixing; targeted regression, all 49 PR-security tests, ShellCheck, bash syntax, and diff checks pass

* no-mistakes(ci): Fixed load-sensitive remote lifecycle test timeout: all three inheritance/launch barrier waits now honor the existing convergence budget instead of failing after 30 seconds. Full suite failure is downstream of this shard. Full lifecycle E2E, Bash syntax, ShellCheck excluding SC1091, and diff checks pass. Production behavior unchanged

* no-mistakes(ci): Fixed remote-reply fixture races, preserved the committing auto-arm’s final rewake on signals, and asserted the live-holder wait bound. Remote-reply and turnend-guard suites and focused lock test pass; signal regression fails before fix and passes after. Full watcher-lock suite fails earlier in an unchanged macOS watcher-replacement test. Full suite CI failure is downstream of the shard failure

* no-mistakes(ci): Fixed teardown race in tests/fm-watch-arm.test.sh: atomically rename state/home/root fixtures away before deleting contents after process exit. Preserved all existing assertions; production code unchanged. Affected suite passed three runs, including two concurrent copies; targeted unpublished-PID lock test and syntax/diff checks passed. Additional full lock suite failed twice at a separate watcher-replacement exit assertion. Standalone ShellCheck reported existing warnings

* fix(bin): cut stat forks in the wake drain by reading identity and size together (#6271)

Local cherry-pick of https://github.com/kunchenguid/firstmate/pull/6271 pending upstream merge.

* fix(bin): keep pr= merge-poll identity last when recording captain-hold completion (#6732)

* fix(bin): keep PR merge polls authenticated across relaunch

A relaunch rewrote the task record with control_relaunch_tx after the
preserved pr= line. fm_pr_metadata_identity_parse rejects any key after
pr= other than pr_head= and x_*, so the watcher stopped authenticating
the armed merge poll and reported it as an unauthenticated state check,
and the merged-PR wake never arrived. Write the transaction id before
the preserved lines, as fm-remote-secondmate-relaunch.sh already does.

* no-mistakes(review): Keep pr= last for traceparent and completion writes

* no-mistakes(document): Note completion record placement ahead of pr= lines

* no-mistakes(ci): Fixed the Greptile P1 finding (ci-1) as the user decided. **Invariant:** a task's `.meta` record holds exactly one `decisions_reviewed`/`decision_keys` pair, and it sits before `pr=`. Then `meta_value` (which reads the last match) returns the current inventory, and `fm_pr_metadata_identity_parse` still sees `pr=` last. The only place that writes this pair is the awk rewrite in `command_complete` (`bin/fm-captain-hold.sh`). The other hits for these keys under `bin/` are only a comment and an error message. `verify` and later `complete` calls read the pair through `meta_value`, so fixing this one writer fixes them too. **Fix:** added one …
trillium added a commit to trillium/firstmate that referenced this pull request Nov 5, 2026
* feat(bin): opt-in spawn base from the primary checkout for local-only work (#7352)

* feat(bin): add opt-in config/spawn-base-primary-checkout for local landings

A fresh pooled task worktree is reset to origin/<default>. A local-only
project lands work on the primary checkout's default branch through
fm-merge-local.sh and never pushes, so that ref stays frozen at the last
push and every fresh task starts behind work already landed, loading the
project's instruction files from the stale tree. The always-on fix proposed
in #3812 replaced the specified origin-only refresh for every home; this
rework keeps that rule as the default and moves the new base behind an
explicit, default-off presence flag, following the existing config/<flag>
pattern.

With config/spawn-base-primary-checkout present:
- fm-spawn.sh starts a fresh local-only ship, or a scout without
  --base-branch, from the primary checkout's <default> when it strictly
  contains origin's tip. Publishing modes and named base branches keep
  origin's tip, because that work is delivered against origin. A diverged
  primary keeps origin's tip and prints a note counting both sides. The
  commit is read from the local object store, so nothing extra is fetched,
  and the clean-slot refusal still runs first.
- fm-review-diff.sh anchors a remote-backed task without base_branch= on the
  branch it delivers to: publishing modes stay on origin/<default>, while a
  local-only ship or a scout is compared against whichever of the local
  <default> and origin/<default> meets the branch later, so the review shows
  the task's own work instead of every locally landed commit.
- fm-promote.sh tells a scout promoted to a publishing mode to return to
  origin's default branch, because in this home the scout may have started
  from the primary checkout's branch, whose unpushed commits would otherwise
  be published with the work.

fm-dod-lib.sh gains fm_mode_publishes as the one predicate those three
readers share. Without the flag every path is unchanged: the spawn resets
to origin's tip, the review anchors on origin/<default>, and promotion keeps
its wording; the existing tests run unmodified. Treehouse 3 (verified on
3.1.3) already hands a slot out at whichever of the local and remote default
branch is further ahead, so with the flag the refresh keeps that slot where
Treehouse put it for a local landing instead of rewinding it, and a project
without origin is untouched as before.

Supersedes #3812.

* no-mistakes(document): Drop change-relative wording from spawn-base config docs

* no-mistakes(ci): The Greptile Review check failed on two review findings, not on a broken build or test. I fixed both as the user directed, and the tests and lint pass. ci-1 (bin/fm-promote.sh): promotion must name origin's default branch only when spawn could actually have started the scout from the primary checkout. Spawn does that only when the project has an origin remote and is recorded on the task. Before this fix, the opt-in flag alone made promotion to no-mistakes or direct-PR say "copy of origin's default branch...", even on a project with no origin. - The new wording now also requires a recorded project (`[ -n "$PROMOTE_PROJECT" ]`) whose `git remote get-url origin` succeeds. That is the same check bin/fm-review-diff.sh already makes. The empty-project guard is needed because `git -C ""` would run in the current directory. Otherwise the existing "default-branch base" wording stays. - The three places that read the flag now agree: spawn, review-diff and promote. - I updated the header and inline comments in fm-promote.sh, and the promote line in docs/configuration.md, to say this applies only to a project with an origin remote. - Test: `test_promote_names_origin_for_a_publishing_mode_in_an_opted_in_home` in tests/fm-task-delivery.test.sh now records a real `project=` with a registry entry, and covers flag on/off × origin/none × direct-PR/no-mistakes/local-only. Only flag on + origin + a publishing mode gets the new wording. The named-base case is unchanged. - Before the fix, the test fails with "not ok - flag on, remote none, direct-PR: the promotion changed the default-branch wording". With the fix, it passes. ci-2 (tests/fm-spawn-pool-base-freshen.test.sh): with the flag set, both publishing modes must start from origin's tip and print no divergence note. - The opted-in spawn test now covers no-mistakes as well as direct-PR, local-only and scout. - The expectations no longer single out direct-PR. Both publishing modes now expect origin's tip, no "note: pooled worktree", and a review anchored at the slot's start, in the leading, diverged and trailing cases. Verification: - `bash tests/fm-task-delivery.test.sh`: exit 0. - `bash tests/fm-spawn-pool-base-freshen.test.sh`: exit 0. - `bin/fm-lint.sh` on the three changed shell files: exit 0 (ShellCheck 0.11.0, pinned, with extended analysis)

* fix: preserve whitespace when proving patches landed (#7910)

* fix: report unavailable Git containment proofs during teardown (#7915)

* fix(teardown): distinguish unavailable content-landed proof

* no-mistakes(document): Clarify teardown proof failure documentation

* no-mistakes(ci): Captain, CI failed in unchanged watcher recovery code, independent of this PR. The focused failing case passed locally with exit 0. The full suite stalled earlier and was stopped. No tracked changes. Command guard rejected cleanup; scratch remains at .ci-7915/ and tests/.ci-7915-cycle.sh

* chore: untrack CI validation scratch

* feat(bin): prefer a configured provider family in dispatch resolution (#7876)

* feat(dispatch): prefer configured provider family

* no-mistakes(review): drop policy_why field and dead auth fixture from preference tests

* no-mistakes(document): docs: record preferred_provider in schema, diagnostics, verification

* fix: pin local-only merges to the accepted done commit (#7916)

* fix: pin local-only landing to its accepted done head

Persist the accepted local-only commit in task metadata and refuse landing when the branch or the recorded head changes. Merge the full commit ID under the task control and metadata locks.

Closes https://github.com/kunchenguid/firstmate/issues/7782

* no-mistakes(test): Refuse local landing races with atomic ref transactions

* no-mistakes(document): Document pinned local landing and recovery contracts

* no-mistakes(ci): Applied only the verified incremental patch and preserved existing repairs. Complete diff matches the supplied candidate hash. Both focused test files, default lint, and source-aware lint passed with exit 0. Evidence retained at /tmp/up7782-local-repair/ci-phase-fresh-*. No commits, pushes, or pipeline-control actions performed; publication remains with the outer executor

* no-mistakes(ci): Fixed both SC2031 false positives in tests/fm-merge-local.test.sh with narrowly scoped suppressions. Tier 2 lint correction; runtime changes were unnecessary. Default lint, source-aware lint, all 8 focused tests, and git diff --check passed. No commits, pushes, or pipeline-control actions performed

* fix: coalesce repeated extension host errors (#6548) (#7928)

* fix(procevent): coalesce unhandled extension host errors

* no-mistakes(document): Document host-error coalescing and recovery semantics

* fix: preserve wake grants when queue-lock acquisition fails (#7912)

* fix: stop wake grants when lock acquisition fails

* no-mistakes(document): Document wake grant lock acquisition failure behavior

* fix(bin): send remote second mate steers over stdin (#7902)

* fix: send remote steers over stdin

* fix: version remote stdin send protocol

* no-mistakes(document): document stdin transport for remote steer in fm-send header

* no-mistakes(ci): Two tests failed in CI. One is caused by this PR; the other is not. 1. Behavior portable serial 5: `tests/fm-secondmate-reconcile.test.sh` failed with "supervision did not deliver the durable reconcile request later". This PR caused it. The PR now sends a remote steer's body on stdin, using `fm-on.sh --stdin` with the `send-stdin` verb. This test's fake ssh started with `cat > /dev/null`, so it threw the body away before it ran the real `fm-remote-secondmate-control.sh`. `cmd_send_stdin` then read an empty message, died with "remote steer message must be nonempty", and no inbox record was written. Rule that broke: a fake ssh that runs the real remote leg must pass the caller's stdin through, as real ssh does. I checked every fake ssh that runs the real leg. `fm-send-remote-delivery.test.sh` already passes stdin through. `fm-secondmate-sync.test.sh` (`make_remote_leg_ssh_stub`) had the same discard line. The stub in `fm-send-resolve-key.test.sh` never runs the leg, so it is fine. The fix deletes the `cat > /dev/null` line in the reconcile and sync stubs. Calls made without `--stdin` still get /dev/null from fm-on, so nothing else changes. Checks run locally: the reconcile test fails before the fix with the same CI message. After the fix, the reconcile test passes (rc=0) and the sync test passes (rc=0). 2. Behavior portable serial 3: `tests/fm-wake-queue.test.sh` failed in `test_concurrent_append_and_drain` with "wake drain: queue lock could not be acquired safely". This PR did not cause it. The PR does not touch `bin/fm-wake-drain.sh`, the wake tests or the wake helpers. The failure is lock contention: 40 appenders run at the same time as a drain, on a loaded CI runner. Locally the whole test passed (70 ok, rc=0). I made no change for it. It is an existing flake in wake-queue lock acquisition and needs its own fix outside this PR. Open PR #7912 ("preserve wake grants when queue-lock acquisition fails") works in the same area

* fix(bin): stop herdr server_ensure from starting servers an external owner manages (#7357)

* fix(herdr): never start a server an external owner manages or is replacing

fm_backend_herdr_server_ensure started a detached herdr server whenever
status reported the session not running. When a service manager owns the
server, that races a unit restart or a server live-handoff and splits panes
across two servers.

The session directory reported by herdr session list can now carry a
firstmate-server-owner marker (persistent, naming the owner) and a
firstmate-server-replacing marker (for the duration of a restart or handoff).
While either exists and the server is not running, server_ensure never starts
a server: it waits a bounded time (FM_BACKEND_HERDR_EXTERNAL_SERVER_POLLS,
default 30s) for the server to report running, and otherwise fails naming the
owner or the replacement. A running server is still used at once, and a
session with no marker keeps the Firstmate-owned autostart unchanged.

Fixes #7320

* no-mistakes(review): Enforce herdr replacement marker on fast path; fixed wait bound

* no-mistakes(ci): Both CI failures had one cause in this PR, and I fixed it in code; no test assertions changed. `fm_backend_herdr_server_ensure` had started running `herdr session list --json` on every call to find the session directory for the ownership markers. Two existing tests treat that call as a sign of something else: - `tests/fm-control-relaunch.test.sh` failed with "a herdr reclaim touched a session the record does not name: session list --json", because it allows only `--session fmlab` calls and `status --json`. - `tests/fm-backend-herdr-presentation-e2e.test.sh` failed with "opted-out spawn added presentation-ordering capability or socket calls", because there `session list` means presentation ordering ran. Invariant: `server_ensure` must not make Herdr calls beyond its own `status` read, so ordinary spawns and reclaims stay free of `session list` and only touch the session they name. Every caller goes through `server_ensure`, so fixing it there covers all of them. Fix (`bin/backends/herdr.sh`): the session directory now comes from the `status --json` read `server_ensure` already makes. It is the directory containing `.server.socket`. I removed the `fm_backend_herdr_session_dir` helper. On a running server, the only added work is one check for the replacement marker, which is what the user asked for. I checked this against real Herdr 0.9.5: - `status` reports the socket even when the server is stopped, for both the default and named sessions. - The socket's directory is the same `session_dir` that `session list` reports, and it follows `XDG_CONFIG_HOME`. - With `--session`, an inherited `HERDR_SOCKET_PATH` does not change it. - The read creates nothing on disk. If a Herdr version omits the socket, `server_ensure` keeps the old Firstmate-owned behavior, as the docs already said for a missing `session_dir`. Other changes: the marker-test fakes now report the socket under the session directory, and I removed the `session list` stub this PR had added to the shared fake. `docs/herdr-backend.md` and `docs/verification/runtime-backends.md` ("Session directory") now describe and record the `status`-socket measurement. Verification: - `tests/fm-backend-herdr.test.sh` passes: 239 ok, 0 not ok, including all the externally-managed and replacement-marker tests. - `tests/fm-control-relaunch.test.sh` passes; it was the shard 3 failure. - shellcheck shows only existing info-level notes. Not verified locally: the real-Herdr presentation test. Here it stopped earlier, at an unrelated Treehouse timeout ("treehouse get did not enter an isolated worktree within 60s"). After the fix `server_ensure` no longer runs `session list`, which is the call that assertion caught. No lab session was left running, and I removed the test's temp directory

* fix: reset idle backoff for actionable heartbeat wakes (#7903)

* fix: classify actionable heartbeat backstop as a check

* no-mistakes(document): Correct heartbeat routing docs and remove stale test count

* fix: preserve heartbeat routing when resetting actionable backoff

* fix(bin): reclaim a live watch lock whose pid-identity no longer recomputes (#7931)

* fix(bin): reclaim a lock whose recorded pid-identity no longer recomputes

#7886 made fm_lock_holder_alive reject a live pid whose start time no
longer matches the lock's recorded pid-start. A holder that predates that
record still falls back to pid liveness, which leaves issue #7801 open: on
a /proc-less host outside UTC, a watcher started before fm_pid_identity
pinned TZ=UTC0 recorded a local-time pid-identity. After the update that
live holder no longer matches its own identity, so the health predicate
rejects it, yet every new watcher stands down beside it and the home stays
unsupervised.

fm_lock_holder_alive now also requires a recorded pid-identity, when
present, to still recompute for the pid, after the existing start-time
check and with the same missing-evidence fallbacks: no record, a pid
rewritten mid-read, or an unreadable value keeps the pid-liveness answer.
Both records go through one helper, _fm_lock_record_matches. Only
long-lived holders that never exec write a pid-identity (the watcher, the
supervise daemon), so a genuine holder still matches. A watcher replaced
this way stands down unsignalled at its next poll through the existing
self-eviction. The fm_pid_identity comment and docs/turnend-guard.md
claimed the upgrade-window residual is cleared by the post-update restart,
which never reaches a primary home's own watcher; they now say the next
lock claim clears it.

Verification:
- Drove: real bin/fm-watch.sh processes with /proc hidden through
  FM_PROC_ROOT_OVERRIDE and TZ=America/Los_Angeles: a live genuine watcher
  whose lock record was rewritten to its own local-time ps lstart identity
  with no pid-start, as a pre-pin build wrote it, then a fresh watcher;
  plus fm_lock_try_acquire against a live pid with a mismatched, matching,
  and unrecorded pid-identity and no pid-start.
- Observed: on the unchanged library the fresh watcher exits "lock held by
  live pid ... but heartbeat is stale" and fm_lock_try_acquire returns
  held for the mismatch. With this change the fresh watcher takes the
  lock, the legacy holder exits 0 by standing down, the live pid is never
  signalled, and matching or unrecorded identities stay held.
- Re-check: tests/fm-watcher-lock.test.sh cases
  test_watch_replaces_live_holder_with_legacy_local_time_identity and
  test_lock_reclaims_holder_whose_identity_no_longer_recomputes.

* no-mistakes(review): Limit pid-identity lock reclaim to the watch lock

* no-mistakes(document): Correct fm_lock_holder_alive comment on non-watch identity locks

* no-mistakes(ci): I made two small fixes. CI and "Require no-mistakes" never ran: GitHub shows both as `action_required`, waiting for approval to run workflows from a fork, so the code didn't cause those. Greptile failed because it scored the PR 4/5 against a required 5/5, with one P2 comment. 1. **Greptile P2, test children left running (`tests/fm-watcher-lock.test.sh`).** The two new lock tests start a `sleep 300` holder that only gets killed after every assertion passes, and the suite's cleanup only reaps processes whose command line contains the fixture root. Each holder now starts as `(exec -a "$dir/holder" sleep 300)`, so cleanup reaps it if the test fails early. To check, I forced a `fail` right after the child starts: on HEAD the `sleep 300` was still running afterwards, and with the fix it was reaped. Both tests pass normally. 2. **Flaky takeover test (`bin/fm-watch.sh`).** This edit was already uncommitted in the worktree. Twelve isolated runs passed without it, so I first dropped it as out of scope, but the full suite then failed on exactly this race. When a successor takes over a live watcher's lock, it deletes the lock and recreates it while holding `.watch.lock.steal`. If the old watcher checks during that gap, it sees no lock `pid` and exits as "state directory was torn down", not by standing down cleanly as the PR intends. That race only happens once this PR lets a healthy, live watcher's lock be taken. The guard treats a missing `pid` as teardown only when no `.steal` marker exists, with a comment explaining why. With it restored, 15 runs of the takeover test (three at a time, to add load) all passed, and all three PR tests passed in the full suite. **Remaining failures:** with the guard restored, I ran the full suite three times and it failed each time, but always on tests this change doesn't touch: "bounded child cleanup regression" twice and "bounded ledger cycle 2 did not start" once. The host's load average was about 100, and these tests depend on timing; one of them runs before any watcher starts. I didn't confirm they also fail on the base commit. shellcheck reports nothing in the test file beyond info notes about files it didn't follow, and one existing warning in `fm-watch.sh` at line 2598, not from this change. I deleted the leftover temporary runner `tests/.tmp-one.sh`. Nothing is committed or pushed

* fix(bin): re-read the watch lock holder after the steal check

The steal-gap guard read the lock pid, then the steal mutex. A successor
that removed and relinked the lock between those reads let the old
watcher see no pid and then no steal mutex, so it exited as "state
directory was torn down" instead of standing down. Upstream CI hit this
in tests/fm-watcher-lock.test.sh
(test_watch_replaces_live_holder_with_legacy_local_time_identity).

The teardown branch now re-reads the pid after the steal mutex. The
steal mutex is held for the whole remove-and-relink, so a steal that
finished between the first two reads has already relinked the lock by
the third read, and the self-eviction below stands the watcher down.

Verification:
- Drove: the takeover test (real bin/fm-watch.sh processes) 48 times,
  six at a time, with and without this change, plus the whole
  tests/fm-watcher-lock.test.sh file.
- Observed: the interleaving is too narrow to hit locally (48 of 48
  passed either way); the whole file passes with this change. The
  failing CI run shows the old watcher's exit 1 teardown message.
- Re-check: Behavior portable serial 6 on this PR's CI.

* no-mistakes(review): Scope fm_pid_identity residual comment to the watch lock

* no-mistakes(review): Align fm_pid_identity residual comment with autoarm reclaim behaviour

* no-mistakes(document): Note watch-lock identity mismatch skips lock stale grace

* fix(bin): tell a released watch lock from a torn-down state directory

A watcher replaced by a successor still exited 1 as "state directory was
torn down" on upstream CI. The successor that reclaims the lock delivers
its recovery wake and exits, releasing the lock, and on a fast runner
that happens before the old watcher's next poll. The old watcher then
found no lock holder and no steal in progress, which the teardown check
read as a recreated state directory.

The watcher now holds its state directory open (fd 6) from startup, and
a lock with no holder is a teardown only when the directory at that path
is no longer the one it holds; otherwise the lock was released by a
successor and the self-eviction stands the watcher down with exit 0. The
held descriptor keeps the inode from being reused by a recreated
directory. A host that cannot open a directory keeps the old reading.
This replaces the steal-marker check and pid re-read, which only covered
a successor still relinking the lock.

Verification:
- Drove: real bin/fm-watch.sh processes. A new regression,
  test_watch_replaced_holder_stands_down_after_successor_exits, pauses
  the old holder (SIGSTOP, only while it holds no other state lock) until
  the successor has delivered its wake and exited, then resumes it. Also
  a standalone run with the old watcher polling every 5s.
- Observed: on the previous head the old watcher exits 1 "state
  directory was torn down (singleton lock removed)", the CI failure,
  every time; with this change it exits 0 by standing down. Both
  takeover tests passed 20 of 20 runs four at a time on one loaded CPU.
  The teardown tests in tests/fm-watch-arm.test.sh (state directory and
  home removed) still pass.
- Re-check: tests/fm-watcher-lock.test.sh and Behavior portable serial 6.

* no-mistakes(test): Hold the watcher's state directory open before claiming the lock

* no-mistakes(document): Docs already match watch-lock identity reclaim change

---------

Co-authored-by: mangocabs2025 <250559406+mangocabs2025@users.noreply.github.com>

* fix(bin): fall back to perl when timeout is not GNU coreutils (#7911)

* Fix non-GNU timeout fallback

* no-mistakes(review): Assert INT reaches watcher in non-GNU timeout fallback test

* no-mistakes(document): Document GNU-only timeout selection in watch checkpoint

* no-mistakes(ci): Greptile flagged that only the non-GNU-timeout-to-Perl path had an isolated test. I added two isolated tests in tests/fm-watch-checkpoint.test.sh, as you asked. The production code is unchanged. The rule being tested: run_bounded must run GNU `timeout` first, then GNU `gtimeout`, then Perl. Whichever GNU command it runs must receive `--signal=INT --kill-after=<bound>s <seconds> <watcher>`. What changed: - **Shared setup:** a new helper, `make_isolated_checkpoint`, copies the checkpoint into a temporary root. It also builds a PATH that holds only the named host tools, so the stubs decide which timeout is found. The existing Perl-fallback test now uses this helper too. Its assertions are the same. - **Stubs:** a non-GNU stub reports `uutils` for `--version` and exits 137 if it is ever used. A GNU stub reports `GNU coreutils` and writes its own name and arguments to `$FM_HOME/timeout-calls`, then exits 124. - **`test_gnu_timeout_runs_the_watcher_bound`:** GNU `timeout` and GNU `gtimeout` are both on PATH. The test asserts exit 124, the quiet checkpoint line, and exactly one call: `timeout --signal=INT --kill-after=5s 1 <root>/bin/fm-watch.sh`. - **`test_non_gnu_timeout_uses_gnu_gtimeout`:** a non-GNU `timeout` is next to a GNU `gtimeout`. The test asserts the same exact call, made by `gtimeout`. - In both new tests, Perl is not on PATH. So if the code picked Perl by mistake, the run would fail with 127. How I checked it: - The full test file passes: all 14 tests. - I broke the code on purpose twice. When I swapped the order to try `gtimeout` first, the GNU timeout test failed. When the code always picked Perl, the run exited 127 instead of 124. I then put the production file back; `git status` shows only the test file changed. - `shellcheck -x` passes on the test file. This is a change to tests only, so there is nothing a user would see to check by hand

* fix: recover ownerless extension readiness records (#7933)

* fix: recover ownerless extension readiness and announce cleanup refusals

* no-mistakes(review): Reset cleanup failure episodes and classify failure wakes

* no-mistakes(document): Document ownerless readiness recovery and cleanup failure wakes

* no-mistakes(document): Clarify cleanup failure documentation ownership

---------

Co-authored-by: Kun Chen <3233006+kunchenguid@users.noreply.github.com>

* fix(bin): keep failed or non-schema remote reply reads out of captures (#7874)

* Keep malformed remote reply captures from wedging

* no-mistakes(document): Fix garbled remote reply source failure comment

* no-mistakes(document): Document remote reply failure handling

---------

Co-authored-by: Pitch Perfekt Collective <pitchperfekt@Pitchs-Mac-Studio.local>

* feat(bin): add per-project pr=manual registry token for worker-written PR text (#7937)

* feat(bin): per-project pr=manual registry token for hand-written PR text

A no-mistakes ship on a project where an outside maintainer reviews the PR let
the pipeline's pr step rewrite the hand-written title and body on every
validated push. The registry now records pr=manual, resolved by
fm-project-mode.sh --pr and carried by fm-brief.sh --pr, fm-spawn.sh and
fm-promote.sh like forge=. The generated brief skips pr and ci, and the worker
writes and publishes the PR text itself.

* no-mistakes(review): Drop pr_text key; fix manual-PR checks wait and base

* no-mistakes(review): Remove dead PR_TEXT and timeout example

* no-mistakes(document): Fix README pr=manual sentence grammar

* test(bin): restore the displaced placeholder comment and rename the spawn agreement test

The comment for the leftover-placeholder test sat above the new pr=manual tests.
The spawn test said it recorded the PR text, but it only checks that a launch happens.

* fix: refuse teardown when Git hides untracked files (#7909)

* fix(teardown): detect untracked work regardless of Git status config

* test(watcher): avoid blocking FIFO contention handshakes

* no-mistakes(document): Document hidden-untracked teardown safety

---------

Co-authored-by: Kun Chen <3233006+kunchenguid@users.noreply.github.com>

* fix(bin): keep newest run attribution in crew-state (#5954)

* fix: prefer current run over stale overview row

* fix: preserve newest run precedence over stale status

* no-mistakes(document): Document live-run precedence in crew-state attribution

* fix: use ledger order for same-minute run precedence

* test: cover both overview orders for same-minute run attribution

Document and pin newer-first (recorded AXI) and historical-first overview
orders. Same-minute ledger timestamps use row order as the tie-break so an
older live bare status cannot hide a newer completed run.

* no-mistakes(review): Treat failed as overridable terminal overview status

* no-mistakes(review): Fix equal-head live run precedence with identity ordering

* no-mistakes(document): Updated run identity ordering documentation

* no-mistakes(lint): Fix ShellCheck export warning

* no-mistakes(review): Prove same-head ordering or report unknown

* no-mistakes(review): Guard failed selected-run reads and drop dead same-head ordering

* no-mistakes(ci): I fixed both Greptile findings (ci-1, ci-2) in bin/fm-crew-state.sh. The change is in the working tree. I did not commit it, push it, or reply to the Greptile threads, because those steps belong to the outer pipeline. ci-1. Invariant: a live run from bare `axi status` may replace a terminal overview selection only when it is proven newer than every other run on the same branch. Previously the code compared it only against the selected run. Now crew-state reads each other candidate with `axi status --run <id>` and compares the live run against each one: - If another candidate is also live, it reports `unknown`, "competing live runs". This keeps the competing-live-runs check. - If two runs share a head and a ULID timestamp, it reports `unknown`, "same-head run ordering unverified", as before. - It promotes the live run only when it is proven newer than all other candidates. - If the live run is newer than the selected run but not proven newer than some other candidate, it reports `unknown`, "run ordering unverified", and names every run id. This means neither the stale selected run nor the live run can hide a newer failed run. This branch is the one judgement call: without it, the stale "done" row A would still hide C's failure. - In all other cases the overview's selection stands. The lib helper is now a pairwise compare called `fm_nm_run_is_newer_than` (it was `fm_nm_run_is_newer_than_selected`). The selected run's detail from the loop is reused when the read succeeded, as in the round-1 fix. I updated the sentence in docs/architecture.md to match. ci-2. Invariant: the `no-mistakes runs` ledger is read only to order runs with different heads. It is now fetched lazily, at most once, and only when a candidate's head differs from the live run's head. Same-head ULID comparisons never call it. Regression test: `test_live_run_newer_than_selection_does_not_hide_newer_failed_run` covers A (stale completed, listed first), C (newer failed) and B (live, created between them). All three share one head and use ULID ids. It expects `state: unknown`, C's id in the output, and no `state: working`. Before the fix it fails: with the fixed code stashed it printed `state: working ... run: 01M1...` (run B). On the original base 3fbace9f the overview would select A, so the output would be `done`, which also fails the `unknown` check. I did not run that base case. Verification: `bash tests/fm-crew-state.test.sh` passes in full ("all fm-crew-state tests passed", the new test included). `shellcheck` on the three changed shell files reports only the existing info-level SC1091 "not following sourced file" notes. No end-to-end run against a live no-mistakes daemon was possible here. I checked the change with the crew-state test harness and its fake `no-mistakes` CLI

---------

Co-authored-by: mehulbhagwani <mehulbhagwani@users.noreply.github.com>
Co-authored-by: Pitch Perfekt Collective <pitchperfekt@Pitchs-Mac-Studio.local>

* chore(ci): run the full suite on outside pull requests only after the full-ci label

Outside pull requests run only the coverage guard and repo invariants until the full-ci label is added; lint and every test lane wait.

A new Full suite check fails naming the full-ci label until it is added, and fails whenever a lane fails or is cancelled.

The label starts the full suite, and later pushes run it again; main pushes, own branches and write-access authors run everything as before.

Other labels run no job at all: their skipped checks take a 'Not run for label - ' prefix, so they cannot hide an earlier failure or a later pass.

Close main pushes keep only the newest run; CONTRIBUTING.md explains the label, and the full-ci label now exists.

* feat(bin): add opt-in systemone and openai decision providers to dispatch resolution (#7664)

* feat(bin): add opt-in systemone and openai providers to typed dispatch resolution

Extend the FM_DISPATCH_PROVIDER/FM_DISPATCH_MODEL seam with a generic
systemone provider (any System One-compatible host at FM_DISPATCH_BASE_URL,
optional FM_DISPATCH_API_KEY) and an openai provider that maps the Choice
request to OpenAI's Decisions API and its answer back. No provider set keeps
the original off line; the never-send check runs on the endpoint and the final
per-provider body. Live provider captures are recorded as pending.

Refs #7643, builds on #7149.

* docs(verification): record the live OpenAI Decisions capture for dispatch resolution

Add a dated 2026-10-23 section for the openai provider: 25 hand-labeled
synthetic briefs against gpt-6-luna, outcome and latency tables, the usage
and header fields actually returned, a calibration note, and one verbatim
request and response pair. The systemone live check stays pending.

Refs #7643.

* docs(verification): record the live Clef capture for the systemone provider

Replace the pending systemone section with a dated 2026-10-23 run against
Cloudflare Workers AI's @cf/cloudflare/clef, reached through a local
test-only relay because Workers AI serves System One at /ai/run/<model> in
a {result, success} envelope. Adds the outcome and latency tables, a
calibration note compared with the gpt-6-luna run, and one verbatim request
and envelope pair. A direct Workers AI option stays out of scope.

Refs #7643.

* feat(bin): promote agy to a full primary and secondmate harness (#7941)

* feat(agy): promote Antigravity CLI to full primary and secondmate harness

Add tracked .agents/hooks.json, bin/fm-sessionstart-agy.sh, bin/fm-turnend-guard-agy.sh, PreToolUse --agy seatbelt flags, session-lock agy ancestry, autoarm supervision model, and --secondmate agy workspace trust pre-registration and spawn support.

* no-mistakes(review): Fix agy Stop-hook park, hooks.json shape, and live coverage

* no-mistakes(review): Unbound agy Stop park, raise ceiling, prove live deny

* no-mistakes(review): Correct agy verification doc park-bound wording

* no-mistakes(document): Document agy as verified primary and secondmate harness

* no-mistakes(ci): I fixed all three selected findings, and every check I ran passed, including the live agy end-to-end run. **ci-1 (`tests/fm-agy-primary-live-e2e.test.sh`):** The invariant is that the live Stop-hook test passes only if a real watcher starts and its wake reaches a follow-up turn. The old test passed as soon as `.agy-park-owner` existed. I replaced the Stop-hook park block with the one the user specified. It waits until both `.agy-park-owner` and `.last-watcher-beat` exist, wakes the watcher with a `done:` status line, and asserts that the park owner was recorded, the watcher started, and `DONE` appears in the agy output. **ci-2 (agy away daemon):** The invariant is that `/afk` must not launch a separate away daemon on any primary whose home runs the supervision host. The agy Stop-hook guard already runs the host when it is enabled, but `fm_afk_launch_host_primary` left agy out. I added `agy` there, which is the one shared check all three callers use. I also added agy to: - the header comment in `bin/fm-afk-launch.sh`; - the three harness loops and the pass message in `tests/fm-afk-launch.test.sh`; - the primary lists and counts in `docs/supervision-host.md`, the matching lines in its engine-selection section, and a new Antigravity (`agy`) row in its Arm owners table; - the header comment in `bin/fm-supervision-instructions.sh`. **user-1 (`.agents/hooks.json`):** The invariant is that each hook command stays one script under Windows `cmd /c` and exits 0 when `sh` is missing. All 5 commands now use `sh -c "..." || cd .`. This does not change behaviour on Linux or macOS, because the `--agy` hooks report deny or continue as JSON on stdout and exit 0. The file keeps its live-verified `{"firstmate":{...}}` shape, matchers and 28800s Stop timeout. **Verification:** - `tests/fm-agy-primary.test.sh` passes, including running the SessionStart hook command from both `.agents/` and the repo root. - `tests/fm-afk-launch.test.sh` has no failures, and the new agy check passes. Its rex end-to-end cases were skipped because the rex CLI is not installed. - `tests/fm-supervision-instructions.test.sh` has no failures. - `bin/fm-lint.sh` and `bin/fm-doc-audience-check.sh` pass. - `FM_AGY_PRIMARY_LIVE=1 tests/fm-agy-primary-live-e2e.test.sh` printed all four `ok` lines and no failures, including "Stop hook parks on a real watcher and delivers its wake to a follow-up turn". The output went through `tail`, so the exit code shown is `tail`'s, not the test script's

* feat(bin): add shared_quota opt-out from quota-based dispatch ranking (#7894)

* feat(dispatch): add shared_quota home opt-out from quota-based ranking

A home whose Claude and other provider usage draws on one combined AI
budget has no meaningful per-provider quota rows, so spendPriority
ranking and runway gates pick the wrong candidate. An optional
top-level "shared_quota": true in config/crew-dispatch.json now opts
the home out: the typed resolver makes no quota-axi call, applies no
quota floor or runway gate, ranks nothing by spendPriority, and
resolves the matched rule's use profiles in declared order, printing
every candidate line with quota ranking off by home declaration.
Firstmate's quota-array-dispatch intake honors the same declaration.
Without the setting, behavior is unchanged. Non-boolean values are
actionable configuration errors in both the resolver and bootstrap.

* test(dispatch): cover shared-quota bypass of unmet rule and profile floors

The shared_quota opt-out test picked a rule with no quota floor, so the
separate rule-floor and profile-floor bypass paths stayed untested.
Two cases now run against the same fixture: a rule whose model:fable
floor (20%) exceeds the snapshot's 15%, and a profile whose all_models
floor (50%) exceeds codex's 31%, each asserting the declared-order pick
still wins with no quota-axi invocation.

* no-mistakes(review): Narrow shared-quota skill opt-out to quota-only gates

* no-mistakes(review): Document preferred_provider under shared_quota opt-out and test it

* no-mistakes(document): Document shared_quota in schema example and verification inventory

* fix(bin): distinguish recycled reaper PIDs in tombstone cleanup (#7958)

* fix(bin): distinguish recycled reaper PIDs in tombstone cleanup

* no-mistakes(ci): ci-2 fixed in tests/fm-watcher-lock.test.sh (test_lock_tombstone_tracks_reaper_start_time). Invariant: no fixture child may outlive a SIGKILLed runner without a bound. (1) The paused reaper's wait loop now also stops when FM_TEST_SUITE_PID is no longer alive or when SECONDS reaches FM_TEST_STUB_MAX_BLOCK_SECONDS. (2) The one sibling child in the same test, the unrelated `sleep 300`, now sleeps for FM_TEST_STUB_MAX_BLOCK_SECONDS so it uses the same bound. Verification, run serially: bash tests/fm-watcher-lock.test.sh. The new test passed on 4 of 4 runs. Red-before still holds: with the base bin/fm-wake-lib.sh from c9da5523, the test fails with 'not ok - recycled reaper pid kept an abandoned tombstone alive'. Separately, the known stand-down flake ('the replaced watcher did not stand down on its own', watch-legacy-local-time-identity) failed on every run on this host and also fails on base c9da5523 without this change, so the test file still exits 1; left unfixed as instructed. ci-1 (Full suite waiting on the full-ci maintainer label) was ignored per the user's decision

* feat(bin): allow omp as a remote secondmate harness (#7939)

* feat: allow omp as a remote secondmate harness

* test: cover omp on the remote secondmate gates

* fix: retire a remote secondmate whose busy state left with its home

* docs: record omp remote retirement evidence

* review: Refresh pinned remote doctor bootstrap checksum

* fix(bin): name a consumed branch grant instead of a wiring bug (#7969)

* fix(bin): name a consumed branch grant instead of a wiring bug

When a supervision branch's own acknowledgement consumes every granted
row, the drain removes the branch-eligible row snapshot while the owner
record stays live. A repeat drain or acknowledgement in the same turn then
refused with a message implying a broken handoff. Say instead that the
grant was already consumed; the refusal and its exit status are unchanged.

* no-mistakes(document): Document consumed-grant refusal in watcher continuity doc

---------

Co-authored-by: c-c6aw <225476801+c-c6aw@users.noreply.github.com>

* fix: preserve literal ampersands in spawn and supervision paths (#7906)

* feat(bin): read dispatch provider keys from a declared credential source (#5409)

* feat(dispatch): read Typesafe key from Keychain

* no-mistakes(review): Share Keychain key lookup with bootstrap; hard-code service name

* no-mistakes(review): Use one readable-secret Keychain check for bootstrap and resolver

* no-mistakes(document): Point AGENTS key row to owner; record Keychain bootstrap evidence

* feat(dispatch): read provider keys from a declared credential source

bin/fm-dispatch-resolve.sh took the typesafe.ai and OpenRouter keys only
from the environment or $FM_HOME/.env, so a home that keeps its key in the
macOS Keychain needed a wrapper to supply it, and the documented direct
call reported off.

Let the resolver consume an optional, provider-keyed declaration in the
effective config directory, config/dispatch-credential-sources.json. It
names where a key lives and never holds one. macos-keychain is the first
adapter (service, optional account), kept behind a small schema and adapter
registry in bin/fm-credential-source-lib.sh so the shared surface binds to
no one OS or provider.

- Precedence is the environment, then .env, then the declared source, which
  is read only when neither supplied a key and only for the selected
  provider.
- No entry and no key stays off, exactly as before. An unreadable or
  invalid declaration exits 2 with a line that names the problem and never
  a declared value.
- A declared source that this host cannot run, that yields no key, or that
  does not answer within FM_CREDENTIAL_SOURCE_TIMEOUT ends as a structured
  error outcome with nothing sent, so it is not mistaken for an
  unconfigured resolver.
- The key is captured into the same private variable as before and still
  reaches curl only as an fd 3 header. The adapter puts only the service
  and account on argv and discards the tool's stderr.
- --supports-credential-source <source> answers supported or unsupported
  without reading a declaration or running the credential tool, so an
  installer can refuse an unsupported activation before it writes anything.

The resolver tests cover the mapping, effective-home and provider
isolation, precedence, the three failure kinds, and secret containment
with a stubbed security and uname.

Closes #7879

* no-mistakes(review): Gate bootstrap typed checks on declared source; fix timeout

* no-mistakes(review): Document storing the declared Keychain item without access dialog

* no-mistakes(document): Clarify that only a typesafe declaration keeps resolver on

* no-mistakes(document): Merge dispatch key-source precedence into one configuration sentence

---------

Co-authored-by: Kun Chen <kunchenguid@users.noreply.github.com>

* fix: clean up remote reply temporary files and locks on exit (#6489)

* fix(bin): clean remote reply temp paths on every exit

The remote reply adapter left its temporary staging directory and fetch files behind on several exit paths.
The ingest staging directory leaked on the continuity-broken return, whose EXIT trap fired after its local tmp left scope.
The trap cmd_ingest installed also replaced the lifecycle-lock release of the handle subshell.
One EXIT trap now owns every temporary path, each lock subshell runs it before releasing its lock, and the empty hash no longer stages a file.
A test under a private TMPDIR covers the continuity return, a die after staging, a locked handle, and a signal during a document fetch.

* no-mistakes(document): Document remote-reply temporary-file cleanup

* no-mistakes(ci): Fixed ci-1 in tests/fm-remote-reply.test.sh: interrupt the blocked SSH child before waiting, fail if it already exited, and require adapter exit status 143 before checking cleanup. Confirmed the strengthened test rejects an adapter that ignores TERM; the temporary mutation was restored. The full remote-reply suite passed on a serial rerun, and syntax, pinned ShellCheck, and diff checks passed. One earlier run alongside lint timed out waiting for the third reply generation

* fix(bin): clean up the staged source-read output on every exit path

The source leg stages the remote read's output in a temporary file. Track it
with the adapter's other temporary paths so a signal during the read removes
it, and extend the regression test and docs to cover that path.

* chore: ignore Claude Code per-user settings (#6482)

* chore: gitignore Claude Code's per-user local settings file

* no-mistakes(ci): Addressed ci-1 by preserving the staged --no-index correction for both Claude settings assertions in tests/fm-gitignore-config.test.sh, making ignore-rule checks independent of tracking state. Reproduced the original false pass with tracked shared settings and an overly broad .claude/ rule; the corrected test rejects it. Verified normal tracked/untracked settings cases and rejection of a missing local-settings ignore rule. Targeted test runner, pinned ShellCheck, Bash syntax check, and diff checks all passed. No unrelated changes were made

* fix: prefilter inbox history for idempotent remote steering (#7905)

* fix(inbox): prefilter idempotent steering history

* no-mistakes(document): Clarify delivery mode in steering retry contract

* test(inbox): cover acknowledgement before prefilter opens

* feat(bin): add Kiro CLI as a crewmate/scout harness adapter (port of #7956) (#7979)

* feat(bin): add Kiro CLI as a crewmate/scout harness adapter

Port of #7956 onto current main so it gets a fresh CI run.

Adds a `kiro` (Kiro CLI, V2 engine) harness adapter, crewmate/scout only
(--secondmate launches are refused). fm-harness.sh detects it by kiro-cli
ancestry; fm-spawn.sh launches it with a per-task KIRO_HOME under
state/<id>.kiro-home (generated userPromptSubmit and stop hooks plus
chat.disableTrustAllConfirmation); busy, control, send, watch, procevent,
teardown and bootstrap wiring recognise it. Composer ghost-text and busy
footer matching is scoped to FM_COMPOSER_HARNESS=kiro, so other harnesses
read exactly as before. Adds references/harness/kiro.md,
docs/verification/kiro.md, tests/fm-kiro-harness.test.sh and an opt-in
live e2e signals guard.

Conflicts with main were resolved by keeping main's agy promotion and
adding kiro to the crewmate-only lists next to it.

Co-authored-by: kiatng <1106470+kiatng@users.noreply.github.com>
Co-authored-by: Marsjohn-11 <74795701+Marsjohn-11@users.noreply.github.com>

* fix(send): detect kiro on meta-less explicit targets

An explicit session:window send has no task meta, so TARGET_HARNESS stayed
empty and the kiro composer rules never applied. A finished kiro idle
placeholder then read as pending, extra Enters were pressed, and fm-send
exited 3 even though kiro accepted the message.

Resolve kiro from the live pane's foreground process group when meta is
absent, and keep every other explicit-target send on the unknown-harness
path. Move the kiro live e2e version probe to after the live gate so an
opted-out run never starts kiro-cli.

Co-authored-by: Kun Chen <kunchenguid@users.noreply.github.com>

---------

Co-authored-by: kiatng <1106470+kiatng@users.noreply.github.com>
Co-authored-by: Marsjohn-11 <74795701+Marsjohn-11@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Kun Chen <kunchenguid@users.noreply.github.com>

* fix(bin): publish hold origins only after backend success (#6777)

* fix(captain-hold): refuse a previous origin's answer after an incomplete hold move

A hold moved to a new origin wrote its stamp and origin before the backend
hold. A process stopped between those writes, or a refused hold whose rollback
also failed, left the task associated with the new origin while it carried
only the earlier call's answer, and complete and verify accepted that answer.

Verification now treats an open, unheld task that leads with a hold-set stamp
above a recorded answer as a re-hold that never completed, so the answer no
longer satisfies the new origin however the move was interrupted. A refused
hold also restores the body the attempt started from, and the origin lookup
runs before any write, so a clean failure leaves the earlier answer valid.

Closes #6461

* no-mistakes(review): Publish hold origins only after backend success

* no-mistakes(review): Publish verified holds before origin writes

* no-mistakes(document): Clarify hold-origin durability documentation and regression coverage

* no-mistakes(lint): Quote done subcommand to resolve ShellCheck warning

* no-mistakes(document): Clarify recorded-origin provenance guarantees

* feat(backends): add experimental explicit-only hc (herdr-core) runtime backend (#7963)

* feat(backends): add experimental explicit-only hc (herdr-core) runtime backend

herdr-core is the terminal core under Herdr.app and is not Herdr 1.
The adapter follows the tmux shape: one login-shell terminal per task,
Treehouse keeps the worktree, and fm-spawn drives it through the same
send/current-path primitives.

- bin/backends/hc.sh: create, capture, visible capture, send line, typed
  literal through hc keys, named keys, current path, composer state,
  submit, native busy state, recovery agent state from the foreground
  process and its process group, and a close that proves the terminal gone.
  Targets are <session>:<address>; every call pins that HC_SESSION, and an
  empty session never reaches hc. Task and home labels gate input and close.
- bin/fm-backend.sh, bin/fm-spawn.sh: hc arms, explicit-only selection,
  endpoint validation, hc_session/hc_terminal metadata, secondmate refusal.
- tests: fake-CLI suite and a real-hc smoke test on a private core.
- docs: hc-backend.md, configuration, verification record, README links.

* fix(hc): submit the spawn launch line by paste and add the hc liveness live guard

The launch line always carries a + that hc keys cannot type, so fm-spawn
pastes it with hc send and consumes the Enter that follows. The launch
environment floor keeps HC_SESSION, HC_TERMINAL_ID, HC_TERMINAL_SOCKET and
HC_SCOPE. tests/fm-backend-hc-liveness-live-e2e.test.sh launches every
installed harness bare in a private core and requires alive. The
verification record gains the end-to-end spawn, steer, peek and teardown run.

* no-mistakes(review): Allow hc interrupt keys and drop unused hc send_literal

* no-mistakes(document): Sync hc backend inventories and adapter header comment

* no-mistakes(ci): Fixed. When an hc task was torn down, the kill function read the task's expected label from the wrong argument, so it ended up accepting any terminal in the same home and could close another task's worker. - Invariant: every hc close must be gated by the task label that teardown passes as the third argument to fm_backend_kill. - Where it must hold: fm-teardown.sh calls `fm_backend_kill <backend> <target> <zellij_tab_id> fm-<id>` at all its sites (around lines 3482, 3491, 3494, 3876, 3986 and 3995). The dispatcher at bin/fm-backend.sh:1156 passes "$@" through to fm_backend_hc_kill, and that function is the only hc close path. So fixing that one function's arguments covers every teardown site. - Fix in bin/backends/hc.sh:279: the signature is now `<target> [unused] [expected-label]` and it reads `expected=${3:-'*'}`, the same shape tern, rex, cmux and paseo use. The label value matches what hc terminals carry: spawn creates them with firstmate.task=$W where W="fm-$ID" (bin/fm-spawn.sh:4545 and 4955), and teardown passes "fm-$ID". - New test in tests/fm-backend-hc.test.sh, test_kill_refuses_another_tasks_terminal, goes through the public fm_backend_kill path. A terminal labeled fm-other is refused for expected label fm-a1, stays alive and gets no `hc kill`. The terminal labeled fm-a1 is closed and removed. Before the fix the test failed ("expected a refusal"), and after it the whole suite passes. - Checks: `bash tests/fm-backend-hc.test.sh` passes every test and `shellcheck -x` is clean on both files. The live smoke and e2e hc tests call kill without a label, which keeps the existing behavior of accepting any task label from this home. I did not run them because they need a real herdr-core. VERIFIED with the unit tests on the fake hc CLI, not against a real hc core

* fix(hc): keep the live liveness guard from repointing the operator's claude

A real claude started under the guard's scratch XDG_DATA_HOME can self-update into it and repoint ~/.local/bin/claude there, leaving the link dangling once the scratch directory is removed.
Export DISABLE_AUTOUPDATER=1, as bin/fm-live-lab.sh already does for its live harnesses.

* fix(hc): drop an inherited HC_SOCKET so the session pin holds

* no-mistakes(document): Document hc dropping inherited HC_SOCKET for session pin

* no-mistakes(ci): I fixed both Greptile findings. The hc unit suite passes all 12 tests, three runs in a row, and `shellcheck -x` is clean on the 4 touched files. VERIFIED with unit tests (a fake hc CLI plus a real process group). NOT VERIFIED against a real hc core, because the live tests need herdr-core. ci-1, live tests could stop an unrelated core - Invariant: every direct `hc` call a test makes must reach only its private scratch core, so an inherited HC_SOCKET (which wins over HC_SESSION in hc 0.1.14) must never be set. - Where it must hold: the two suites that call `hc` directly (`hc server status` at startup and `hc server stop` in cleanup), `tests/fm-backend-hc-liveness-live-e2e.test.sh` and `tests/fm-backend-hc-smoke.test.sh`. Adapter calls already go through `fm_backend_hc_cli`, which drops HC_SOCKET. - Fix: both suites add HC_SOCKET to the `unset HC_TERMINAL_ID HC_TERMINAL_SOCKET HC_SCOPE` line, before any `hc` call. ci-2, a shell wrapper running a live worker was reported as dead - Invariant: `fm_backend_hc_agent_state` may return `dead` only when neither the foreground process nor anything else in its process group is a harness. - Where it must hold: there is one classification path, `bin/backends/hc.sh` around line 326. Before the fix, the `shell` branch returned `dead` before the process-group check ran. Callers such as the inbox ring and the watcher read this value through `fm_backend_agent_state`, so fixing this one function covers all of them. - Fix: the result is now `alive` when the foreground process is a harness. Otherwise the process group is checked, which can also give `alive`. After that a shell gives `dead` and anything else gives `ambiguous`. An idle shell, whose group holds no harness, is still `dead`, and the existing test_agent_state_classifies_foreground_and_absence still passes (`t2=dead`). - New test `test_agent_state_reads_a_shell_wrappers_group` in `tests/fm-backend-hc.test.sh`. It starts a real `bash` wrapper in its own process group with a child that runs as `claude`, and points the fake hc terminal's foreground at the wrapper. With the old code the test fails ("expected 'dead', got 'alive'"). With the fix it passes. The comment in the code was updated. `docs/hc-backend.md` already describes the process-group read, so it did not need a change. Not run: `fm-backend-hc-smoke.test.sh` and `fm-backend-hc-liveness-live-e2e.test.sh`, because they need a real hc core

* fix: refresh Herdr upstream references and licensing (#8000)

* docs(herdr): record the Apache-2.0 relicense and herdrdev org rename

Herdr relicensed from AGPL-3.0-or-later to Apache-2.0 in 0.8.0 and the
GitHub organization moved ogulcancelik/herdr to herdrdev/herdr. The old
release URLs redirect to the same assets, so the CI installer and the
version-floor guard now fetch via the canonical org with the pinned
version and checksums unchanged; verified end to end by running the
installer against the new URL.

* no-mistakes(document): Clarify Herdr product boundaries and preserve historical evidence

* fix(pi): stop repeated numbered and byte excerpt reads (#7992)

Fixes #7990

* fix(bin): keep the PR merge watch working when a worker with a PR is relaunched (#7996)

* Preserve PR poll authentication on relaunch

* no-mistakes(review): Keep trace and polytoken meta ahead of PR lines

* test: pin lock staleness in malformed presentation lock wake-queue case (#7837)

* fix(tests): pin lock staleness in malformed presentation lock case

A plain-file presentation lock older than FM_LOCK_STALE_AFTER (default 2s) is reclaimed as garbage, so a slow runner could age the malformed-lock fixture into a successful acquire. Pin the staleness window far above the case runtime so the case is deterministic.

* test(wake-queue): correct the malformed presentation lock staleness comment

---------

Co-authored-by: Trillium Smith <5898009+trillium@users.noreply.github.com>

* feat(bin): add configurable self-update source for /updatefirstmate (#5603)

* feat(bin): let /updatefirstmate follow a configured self-update source

An optional local config/self-update-source ("<remote> <branch>") makes
fm-update.sh fast-forward the primary from that one remote branch instead of
origin/<default>, under the same fast-forward-only guards, and makes local
secondmates advance to the primary's resulting commit (a standalone clone
imports it from the primary first). A home can then run its own fixes from a
branch that carries them on top of upstream, while worker spawns, review
diffs, the cleanup landed-work test, lint and default-branch detection keep
using origin, so new contributions still branch from upstream.

Absent, behaviour is unchanged. An unreadable or malformed file, an unknown
remote or an invalid branch name refuses the whole update before anything
moves rather than falling back to origin. A remote secondmate's host follows
its own code root's config, which the docs record as the limit.

* no-mistakes(document): List config/self-update-source in AGENTS.md config inventory

* no-mistakes(document): Mention self-update source in updatefirstmate skill description

* fix: bound watcher auto-arm failures and recover interrupted locks (#8018)

* fix(bin): commit the attended alarm from the exhausted Stop auto-arm

A Claude failure episode could suppress indefinitely without ever raising
the attended alarm. On every Stop cycle the auto-arm opens its generation
claim before the guard's sync-wait decision, so the guard always steps
aside; terminal_fail_open is never reached and no participant knew that
automatic continuation was exhausted. The block budget still climbed
because the guard's step-aside path accounts for the epoch, so Stops kept
rewaking with empty failed-suppressed bodies forever.

The auto-arm is the only participant that knows its own continuation is
exhausted, so it now owns the terminal escalation: once the failure
notice was consumed and the session block budget is over, the terminal
failure path commits .claude-autoarm-failure-alarmed and the
failed-suppressed outcome inside the owner lock (owner then budget, the
same order the guard's writer uses), then emits one loud final rewake
telling the operator to keep the session attended and diagnose the
Stop-hook supervision. A healthy watcher verified inside that hold resets
the episode instead of alarming, and a refused commit stays suppressed
without a false alarm.

Later Stops in the same episode see the alarm, record failed-suppressed,
and exit 0 so no further continuation or alarm is produced. Positive
watcher recovery still clears the notice, the alarm, and the budget.

Every failed-suppressed commit now carries a one-line stderr reason
naming why the operator notice is not repeated and whether the
Stop-owned retry stays alive, replacing the silent empty bodies that
made suppressed Stops indistinguishable from a wedged hook.

Adds an integrated guard/auto-arm regression driving both hooks through
the exhaustion boundary and asserting the single alarm, post-alarm
suppression, and clean recovery; updates existing tests for the reasoned
suppression contract.

* fix(bin): outlast an unpublished lock pid for one freshness window

CI run 40805704864 ("recovery drain after forced arm interruption")
failed because a dying watcher could not publish .watcher-down inside
its bounded cleanup window, so the drain saw no downtime marker to ack.

The blocker was an empty-pid lock artifact: fm_lock_claim and the
bounded-wait handoff published ownerdir/pid with a truncating write,
and a creator killed mid-write (the bounded handoff helper runs under
timeout -k with a process-group KILL) left a resolvable symlink whose
pid file stayed empty forever. fm_lock_try_acquire treats that as a
fresh mid-acquire hold for a full freshness window, cannot steal it,
and a bounded waiter whose bound equals the window gave up before the
evidence expired.

Two changes. First, both pid writes now go through a same-directory
pid.tmp file renamed into place, so a killed write can no longer leave
a live lock with a permanently empty pid; fm_lock_clean_known_files
sweeps leftover tmp files. Second, fm_lock_acquire_wait_max polls one
extra freshness window when the remaining blocker still has no
published pid, so a waiter outlives the residue instead of failing at
its bound; the moment a pid publishes or the artifact goes stale the
ordinary live-holder and steal rules apply unchanged, and published
live holders keep the original bound.

Adds a regression test that links an owner dir with no pid and asserts
the bounded wait outlasts the freshness window to reclaim it, while a
live holder still fails at the nominal bound; verified to fail against
the pre-change implementation.

* no-mistakes(review): Route every suppressed exit through alarm decision

* no-mistakes(document): Clarify exhaustion and lock-wait documentation

* no-mistakes(lint): Quote empty grace deadline assignment for ShellCheck

* no-mistakes(ci): Fixed tests/fm-x-mode.test.sh: atomic lock-pid publication consumed its overly broad injected mv failure. Targeted the counter-record destination and asserted injection occurred. Reproduced failure before fix; full X-mode test script, pinned lint, bash syntax, and diff checks pass afterward. Full suite failure is downstream of this lane failure; no separate fix needed

* no-mistakes(ci): Fixed Full suite’s underlying shard timeout: the PR marker test’s broad mv failure injection blocked atomic lock-PID publication indefinitely. Restricted injection to the marker destination. Reproduced the hang before fixing; targeted regression, all 49 PR-security tests, ShellCheck, bash syntax, and diff checks pass

* no-mistakes(ci): Fixed load-sensitive remote lifecycle test timeout: all three inheritance/launch barrier waits now honor the existing convergence budget instead of failing after 30 seconds. Full suite failure is downstream of this shard. Full lifecycle E2E, Bash syntax, ShellCheck excluding SC1091, and diff checks pass. Production behavior unchanged

* no-mistakes(ci): Fixed remote-reply fixture races, preserved the committing auto-arm’s final rewake on signals, and asserted the live-holder wait bound. Remote-reply and turnend-guard suites and focused lock test pass; signal regression fails before fix and passes after. Full watcher-lock suite fails earlier in an unchanged macOS watcher-replacement test. Full suite CI failure is downstream of the shard failure

* no-mistakes(ci): Fixed teardown race in tests/fm-watch-arm.test.sh: atomically rename state/home/root fixtures away before deleting contents after process exit. Preserved all existing assertions; production code unchanged. Affected suite passed three runs, including two concurrent copies; targeted unpublished-PID lock test and syntax/diff checks passed. Additional full lock suite failed twice at a separate watcher-replacement exit assertion. Standalone ShellCheck reported existing warnings

* fix(bin): cut stat forks in the wake drain by reading identity and size together (#6271)

Local cherry-pick of https://github.com/kunchenguid/firstmate/pull/6271 pending upstream merge.

* fix(bin): keep pr= merge-poll identity last when recording captain-hold completion (#6732)

* fix(bin): keep PR merge polls authenticated across relaunch

A relaunch rewrote the task record with control_relaunch_tx after the
preserved pr= line. fm_pr_metadata_identity_parse rejects any key after
pr= other than pr_head= and x_*, so the watcher stopped authenticating
the armed merge poll and reported it as an unauthenticated state check,
and the merged-PR wake never arrived. Write the transaction id before
the preserved lines, as fm-remote-secondmate-relaunch.sh already does.

* no-mistakes(review): Keep pr= last for traceparent and completion writes

* no-mistakes(document): Note completion record placement ahead of pr= lines

* no-mistakes(ci): Fixed the Greptile P1 finding (ci-1) as the user decided. **Invariant:** a task's `.meta` record holds exactly one `decisions_reviewed`/`decision_keys` pair, and it sits before `pr=`. Then `meta_value` (which reads the last match) returns the current inventory, and `fm_pr_metadata_identity_parse` still sees `pr=` last. The only place that writes this pair is the awk rewrite in `command_complete` (`bin/fm-captain-hold.sh`). The other hits for these keys under `bin/` are only a comment and an error message. `verify` and later `complete` calls read the pair through `meta_value`, so fixing this one writer fixes them too. **Fix:** added one …
trillium added a commit to trillium/firstmate that referenced this pull request Nov 5, 2026
* feat(bin): opt-in spawn base from the primary checkout for local-only work (#7352)

* feat(bin): add opt-in config/spawn-base-primary-checkout for local landings

A fresh pooled task worktree is reset to origin/<default>. A local-only
project lands work on the primary checkout's default branch through
fm-merge-local.sh and never pushes, so that ref stays frozen at the last
push and every fresh task starts behind work already landed, loading the
project's instruction files from the stale tree. The always-on fix proposed
in #3812 replaced the specified origin-only refresh for every home; this
rework keeps that rule as the default and moves the new base behind an
explicit, default-off presence flag, following the existing config/<flag>
pattern.

With config/spawn-base-primary-checkout present:
- fm-spawn.sh starts a fresh local-only ship, or a scout without
  --base-branch, from the primary checkout's <default> when it strictly
  contains origin's tip. Publishing modes and named base branches keep
  origin's tip, because that work is delivered against origin. A diverged
  primary keeps origin's tip and prints a note counting both sides. The
  commit is read from the local object store, so nothing extra is fetched,
  and the clean-slot refusal still runs first.
- fm-review-diff.sh anchors a remote-backed task without base_branch= on the
  branch it delivers to: publishing modes stay on origin/<default>, while a
  local-only ship or a scout is compared against whichever of the local
  <default> and origin/<default> meets the branch later, so the review shows
  the task's own work instead of every locally landed commit.
- fm-promote.sh tells a scout promoted to a publishing mode to return to
  origin's default branch, because in this home the scout may have started
  from the primary checkout's branch, whose unpushed commits would otherwise
  be published with the work.

fm-dod-lib.sh gains fm_mode_publishes as the one predicate those three
readers share. Without the flag every path is unchanged: the spawn resets
to origin's tip, the review anchors on origin/<default>, and promotion keeps
its wording; the existing tests run unmodified. Treehouse 3 (verified on
3.1.3) already hands a slot out at whichever of the local and remote default
branch is further ahead, so with the flag the refresh keeps that slot where
Treehouse put it for a local landing instead of rewinding it, and a project
without origin is untouched as before.

Supersedes #3812.

* no-mistakes(document): Drop change-relative wording from spawn-base config docs

* no-mistakes(ci): The Greptile Review check failed on two review findings, not on a broken build or test. I fixed both as the user directed, and the tests and lint pass. ci-1 (bin/fm-promote.sh): promotion must name origin's default branch only when spawn could actually have started the scout from the primary checkout. Spawn does that only when the project has an origin remote and is recorded on the task. Before this fix, the opt-in flag alone made promotion to no-mistakes or direct-PR say "copy of origin's default branch...", even on a project with no origin. - The new wording now also requires a recorded project (`[ -n "$PROMOTE_PROJECT" ]`) whose `git remote get-url origin` succeeds. That is the same check bin/fm-review-diff.sh already makes. The empty-project guard is needed because `git -C ""` would run in the current directory. Otherwise the existing "default-branch base" wording stays. - The three places that read the flag now agree: spawn, review-diff and promote. - I updated the header and inline comments in fm-promote.sh, and the promote line in docs/configuration.md, to say this applies only to a project with an origin remote. - Test: `test_promote_names_origin_for_a_publishing_mode_in_an_opted_in_home` in tests/fm-task-delivery.test.sh now records a real `project=` with a registry entry, and covers flag on/off × origin/none × direct-PR/no-mistakes/local-only. Only flag on + origin + a publishing mode gets the new wording. The named-base case is unchanged. - Before the fix, the test fails with "not ok - flag on, remote none, direct-PR: the promotion changed the default-branch wording". With the fix, it passes. ci-2 (tests/fm-spawn-pool-base-freshen.test.sh): with the flag set, both publishing modes must start from origin's tip and print no divergence note. - The opted-in spawn test now covers no-mistakes as well as direct-PR, local-only and scout. - The expectations no longer single out direct-PR. Both publishing modes now expect origin's tip, no "note: pooled worktree", and a review anchored at the slot's start, in the leading, diverged and trailing cases. Verification: - `bash tests/fm-task-delivery.test.sh`: exit 0. - `bash tests/fm-spawn-pool-base-freshen.test.sh`: exit 0. - `bin/fm-lint.sh` on the three changed shell files: exit 0 (ShellCheck 0.11.0, pinned, with extended analysis)

* fix: preserve whitespace when proving patches landed (#7910)

* fix: report unavailable Git containment proofs during teardown (#7915)

* fix(teardown): distinguish unavailable content-landed proof

* no-mistakes(document): Clarify teardown proof failure documentation

* no-mistakes(ci): Captain, CI failed in unchanged watcher recovery code, independent of this PR. The focused failing case passed locally with exit 0. The full suite stalled earlier and was stopped. No tracked changes. Command guard rejected cleanup; scratch remains at .ci-7915/ and tests/.ci-7915-cycle.sh

* chore: untrack CI validation scratch

* feat(bin): prefer a configured provider family in dispatch resolution (#7876)

* feat(dispatch): prefer configured provider family

* no-mistakes(review): drop policy_why field and dead auth fixture from preference tests

* no-mistakes(document): docs: record preferred_provider in schema, diagnostics, verification

* fix: pin local-only merges to the accepted done commit (#7916)

* fix: pin local-only landing to its accepted done head

Persist the accepted local-only commit in task metadata and refuse landing when the branch or the recorded head changes. Merge the full commit ID under the task control and metadata locks.

Closes https://github.com/kunchenguid/firstmate/issues/7782

* no-mistakes(test): Refuse local landing races with atomic ref transactions

* no-mistakes(document): Document pinned local landing and recovery contracts

* no-mistakes(ci): Applied only the verified incremental patch and preserved existing repairs. Complete diff matches the supplied candidate hash. Both focused test files, default lint, and source-aware lint passed with exit 0. Evidence retained at /tmp/up7782-local-repair/ci-phase-fresh-*. No commits, pushes, or pipeline-control actions performed; publication remains with the outer executor

* no-mistakes(ci): Fixed both SC2031 false positives in tests/fm-merge-local.test.sh with narrowly scoped suppressions. Tier 2 lint correction; runtime changes were unnecessary. Default lint, source-aware lint, all 8 focused tests, and git diff --check passed. No commits, pushes, or pipeline-control actions performed

* fix: coalesce repeated extension host errors (#6548) (#7928)

* fix(procevent): coalesce unhandled extension host errors

* no-mistakes(document): Document host-error coalescing and recovery semantics

* fix: preserve wake grants when queue-lock acquisition fails (#7912)

* fix: stop wake grants when lock acquisition fails

* no-mistakes(document): Document wake grant lock acquisition failure behavior

* fix(bin): send remote second mate steers over stdin (#7902)

* fix: send remote steers over stdin

* fix: version remote stdin send protocol

* no-mistakes(document): document stdin transport for remote steer in fm-send header

* no-mistakes(ci): Two tests failed in CI. One is caused by this PR; the other is not. 1. Behavior portable serial 5: `tests/fm-secondmate-reconcile.test.sh` failed with "supervision did not deliver the durable reconcile request later". This PR caused it. The PR now sends a remote steer's body on stdin, using `fm-on.sh --stdin` with the `send-stdin` verb. This test's fake ssh started with `cat > /dev/null`, so it threw the body away before it ran the real `fm-remote-secondmate-control.sh`. `cmd_send_stdin` then read an empty message, died with "remote steer message must be nonempty", and no inbox record was written. Rule that broke: a fake ssh that runs the real remote leg must pass the caller's stdin through, as real ssh does. I checked every fake ssh that runs the real leg. `fm-send-remote-delivery.test.sh` already passes stdin through. `fm-secondmate-sync.test.sh` (`make_remote_leg_ssh_stub`) had the same discard line. The stub in `fm-send-resolve-key.test.sh` never runs the leg, so it is fine. The fix deletes the `cat > /dev/null` line in the reconcile and sync stubs. Calls made without `--stdin` still get /dev/null from fm-on, so nothing else changes. Checks run locally: the reconcile test fails before the fix with the same CI message. After the fix, the reconcile test passes (rc=0) and the sync test passes (rc=0). 2. Behavior portable serial 3: `tests/fm-wake-queue.test.sh` failed in `test_concurrent_append_and_drain` with "wake drain: queue lock could not be acquired safely". This PR did not cause it. The PR does not touch `bin/fm-wake-drain.sh`, the wake tests or the wake helpers. The failure is lock contention: 40 appenders run at the same time as a drain, on a loaded CI runner. Locally the whole test passed (70 ok, rc=0). I made no change for it. It is an existing flake in wake-queue lock acquisition and needs its own fix outside this PR. Open PR #7912 ("preserve wake grants when queue-lock acquisition fails") works in the same area

* fix(bin): stop herdr server_ensure from starting servers an external owner manages (#7357)

* fix(herdr): never start a server an external owner manages or is replacing

fm_backend_herdr_server_ensure started a detached herdr server whenever
status reported the session not running. When a service manager owns the
server, that races a unit restart or a server live-handoff and splits panes
across two servers.

The session directory reported by herdr session list can now carry a
firstmate-server-owner marker (persistent, naming the owner) and a
firstmate-server-replacing marker (for the duration of a restart or handoff).
While either exists and the server is not running, server_ensure never starts
a server: it waits a bounded time (FM_BACKEND_HERDR_EXTERNAL_SERVER_POLLS,
default 30s) for the server to report running, and otherwise fails naming the
owner or the replacement. A running server is still used at once, and a
session with no marker keeps the Firstmate-owned autostart unchanged.

Fixes #7320

* no-mistakes(review): Enforce herdr replacement marker on fast path; fixed wait bound

* no-mistakes(ci): Both CI failures had one cause in this PR, and I fixed it in code; no test assertions changed. `fm_backend_herdr_server_ensure` had started running `herdr session list --json` on every call to find the session directory for the ownership markers. Two existing tests treat that call as a sign of something else: - `tests/fm-control-relaunch.test.sh` failed with "a herdr reclaim touched a session the record does not name: session list --json", because it allows only `--session fmlab` calls and `status --json`. - `tests/fm-backend-herdr-presentation-e2e.test.sh` failed with "opted-out spawn added presentation-ordering capability or socket calls", because there `session list` means presentation ordering ran. Invariant: `server_ensure` must not make Herdr calls beyond its own `status` read, so ordinary spawns and reclaims stay free of `session list` and only touch the session they name. Every caller goes through `server_ensure`, so fixing it there covers all of them. Fix (`bin/backends/herdr.sh`): the session directory now comes from the `status --json` read `server_ensure` already makes. It is the directory containing `.server.socket`. I removed the `fm_backend_herdr_session_dir` helper. On a running server, the only added work is one check for the replacement marker, which is what the user asked for. I checked this against real Herdr 0.9.5: - `status` reports the socket even when the server is stopped, for both the default and named sessions. - The socket's directory is the same `session_dir` that `session list` reports, and it follows `XDG_CONFIG_HOME`. - With `--session`, an inherited `HERDR_SOCKET_PATH` does not change it. - The read creates nothing on disk. If a Herdr version omits the socket, `server_ensure` keeps the old Firstmate-owned behavior, as the docs already said for a missing `session_dir`. Other changes: the marker-test fakes now report the socket under the session directory, and I removed the `session list` stub this PR had added to the shared fake. `docs/herdr-backend.md` and `docs/verification/runtime-backends.md` ("Session directory") now describe and record the `status`-socket measurement. Verification: - `tests/fm-backend-herdr.test.sh` passes: 239 ok, 0 not ok, including all the externally-managed and replacement-marker tests. - `tests/fm-control-relaunch.test.sh` passes; it was the shard 3 failure. - shellcheck shows only existing info-level notes. Not verified locally: the real-Herdr presentation test. Here it stopped earlier, at an unrelated Treehouse timeout ("treehouse get did not enter an isolated worktree within 60s"). After the fix `server_ensure` no longer runs `session list`, which is the call that assertion caught. No lab session was left running, and I removed the test's temp directory

* fix: reset idle backoff for actionable heartbeat wakes (#7903)

* fix: classify actionable heartbeat backstop as a check

* no-mistakes(document): Correct heartbeat routing docs and remove stale test count

* fix: preserve heartbeat routing when resetting actionable backoff

* fix(bin): reclaim a live watch lock whose pid-identity no longer recomputes (#7931)

* fix(bin): reclaim a lock whose recorded pid-identity no longer recomputes

#7886 made fm_lock_holder_alive reject a live pid whose start time no
longer matches the lock's recorded pid-start. A holder that predates that
record still falls back to pid liveness, which leaves issue #7801 open: on
a /proc-less host outside UTC, a watcher started before fm_pid_identity
pinned TZ=UTC0 recorded a local-time pid-identity. After the update that
live holder no longer matches its own identity, so the health predicate
rejects it, yet every new watcher stands down beside it and the home stays
unsupervised.

fm_lock_holder_alive now also requires a recorded pid-identity, when
present, to still recompute for the pid, after the existing start-time
check and with the same missing-evidence fallbacks: no record, a pid
rewritten mid-read, or an unreadable value keeps the pid-liveness answer.
Both records go through one helper, _fm_lock_record_matches. Only
long-lived holders that never exec write a pid-identity (the watcher, the
supervise daemon), so a genuine holder still matches. A watcher replaced
this way stands down unsignalled at its next poll through the existing
self-eviction. The fm_pid_identity comment and docs/turnend-guard.md
claimed the upgrade-window residual is cleared by the post-update restart,
which never reaches a primary home's own watcher; they now say the next
lock claim clears it.

Verification:
- Drove: real bin/fm-watch.sh processes with /proc hidden through
  FM_PROC_ROOT_OVERRIDE and TZ=America/Los_Angeles: a live genuine watcher
  whose lock record was rewritten to its own local-time ps lstart identity
  with no pid-start, as a pre-pin build wrote it, then a fresh watcher;
  plus fm_lock_try_acquire against a live pid with a mismatched, matching,
  and unrecorded pid-identity and no pid-start.
- Observed: on the unchanged library the fresh watcher exits "lock held by
  live pid ... but heartbeat is stale" and fm_lock_try_acquire returns
  held for the mismatch. With this change the fresh watcher takes the
  lock, the legacy holder exits 0 by standing down, the live pid is never
  signalled, and matching or unrecorded identities stay held.
- Re-check: tests/fm-watcher-lock.test.sh cases
  test_watch_replaces_live_holder_with_legacy_local_time_identity and
  test_lock_reclaims_holder_whose_identity_no_longer_recomputes.

* no-mistakes(review): Limit pid-identity lock reclaim to the watch lock

* no-mistakes(document): Correct fm_lock_holder_alive comment on non-watch identity locks

* no-mistakes(ci): I made two small fixes. CI and "Require no-mistakes" never ran: GitHub shows both as `action_required`, waiting for approval to run workflows from a fork, so the code didn't cause those. Greptile failed because it scored the PR 4/5 against a required 5/5, with one P2 comment. 1. **Greptile P2, test children left running (`tests/fm-watcher-lock.test.sh`).** The two new lock tests start a `sleep 300` holder that only gets killed after every assertion passes, and the suite's cleanup only reaps processes whose command line contains the fixture root. Each holder now starts as `(exec -a "$dir/holder" sleep 300)`, so cleanup reaps it if the test fails early. To check, I forced a `fail` right after the child starts: on HEAD the `sleep 300` was still running afterwards, and with the fix it was reaped. Both tests pass normally. 2. **Flaky takeover test (`bin/fm-watch.sh`).** This edit was already uncommitted in the worktree. Twelve isolated runs passed without it, so I first dropped it as out of scope, but the full suite then failed on exactly this race. When a successor takes over a live watcher's lock, it deletes the lock and recreates it while holding `.watch.lock.steal`. If the old watcher checks during that gap, it sees no lock `pid` and exits as "state directory was torn down", not by standing down cleanly as the PR intends. That race only happens once this PR lets a healthy, live watcher's lock be taken. The guard treats a missing `pid` as teardown only when no `.steal` marker exists, with a comment explaining why. With it restored, 15 runs of the takeover test (three at a time, to add load) all passed, and all three PR tests passed in the full suite. **Remaining failures:** with the guard restored, I ran the full suite three times and it failed each time, but always on tests this change doesn't touch: "bounded child cleanup regression" twice and "bounded ledger cycle 2 did not start" once. The host's load average was about 100, and these tests depend on timing; one of them runs before any watcher starts. I didn't confirm they also fail on the base commit. shellcheck reports nothing in the test file beyond info notes about files it didn't follow, and one existing warning in `fm-watch.sh` at line 2598, not from this change. I deleted the leftover temporary runner `tests/.tmp-one.sh`. Nothing is committed or pushed

* fix(bin): re-read the watch lock holder after the steal check

The steal-gap guard read the lock pid, then the steal mutex. A successor
that removed and relinked the lock between those reads let the old
watcher see no pid and then no steal mutex, so it exited as "state
directory was torn down" instead of standing down. Upstream CI hit this
in tests/fm-watcher-lock.test.sh
(test_watch_replaces_live_holder_with_legacy_local_time_identity).

The teardown branch now re-reads the pid after the steal mutex. The
steal mutex is held for the whole remove-and-relink, so a steal that
finished between the first two reads has already relinked the lock by
the third read, and the self-eviction below stands the watcher down.

Verification:
- Drove: the takeover test (real bin/fm-watch.sh processes) 48 times,
  six at a time, with and without this change, plus the whole
  tests/fm-watcher-lock.test.sh file.
- Observed: the interleaving is too narrow to hit locally (48 of 48
  passed either way); the whole file passes with this change. The
  failing CI run shows the old watcher's exit 1 teardown message.
- Re-check: Behavior portable serial 6 on this PR's CI.

* no-mistakes(review): Scope fm_pid_identity residual comment to the watch lock

* no-mistakes(review): Align fm_pid_identity residual comment with autoarm reclaim behaviour

* no-mistakes(document): Note watch-lock identity mismatch skips lock stale grace

* fix(bin): tell a released watch lock from a torn-down state directory

A watcher replaced by a successor still exited 1 as "state directory was
torn down" on upstream CI. The successor that reclaims the lock delivers
its recovery wake and exits, releasing the lock, and on a fast runner
that happens before the old watcher's next poll. The old watcher then
found no lock holder and no steal in progress, which the teardown check
read as a recreated state directory.

The watcher now holds its state directory open (fd 6) from startup, and
a lock with no holder is a teardown only when the directory at that path
is no longer the one it holds; otherwise the lock was released by a
successor and the self-eviction stands the watcher down with exit 0. The
held descriptor keeps the inode from being reused by a recreated
directory. A host that cannot open a directory keeps the old reading.
This replaces the steal-marker check and pid re-read, which only covered
a successor still relinking the lock.

Verification:
- Drove: real bin/fm-watch.sh processes. A new regression,
  test_watch_replaced_holder_stands_down_after_successor_exits, pauses
  the old holder (SIGSTOP, only while it holds no other state lock) until
  the successor has delivered its wake and exited, then resumes it. Also
  a standalone run with the old watcher polling every 5s.
- Observed: on the previous head the old watcher exits 1 "state
  directory was torn down (singleton lock removed)", the CI failure,
  every time; with this change it exits 0 by standing down. Both
  takeover tests passed 20 of 20 runs four at a time on one loaded CPU.
  The teardown tests in tests/fm-watch-arm.test.sh (state directory and
  home removed) still pass.
- Re-check: tests/fm-watcher-lock.test.sh and Behavior portable serial 6.

* no-mistakes(test): Hold the watcher's state directory open before claiming the lock

* no-mistakes(document): Docs already match watch-lock identity reclaim change

---------

Co-authored-by: mangocabs2025 <250559406+mangocabs2025@users.noreply.github.com>

* fix(bin): fall back to perl when timeout is not GNU coreutils (#7911)

* Fix non-GNU timeout fallback

* no-mistakes(review): Assert INT reaches watcher in non-GNU timeout fallback test

* no-mistakes(document): Document GNU-only timeout selection in watch checkpoint

* no-mistakes(ci): Greptile flagged that only the non-GNU-timeout-to-Perl path had an isolated test. I added two isolated tests in tests/fm-watch-checkpoint.test.sh, as you asked. The production code is unchanged. The rule being tested: run_bounded must run GNU `timeout` first, then GNU `gtimeout`, then Perl. Whichever GNU command it runs must receive `--signal=INT --kill-after=<bound>s <seconds> <watcher>`. What changed: - **Shared setup:** a new helper, `make_isolated_checkpoint`, copies the checkpoint into a temporary root. It also builds a PATH that holds only the named host tools, so the stubs decide which timeout is found. The existing Perl-fallback test now uses this helper too. Its assertions are the same. - **Stubs:** a non-GNU stub reports `uutils` for `--version` and exits 137 if it is ever used. A GNU stub reports `GNU coreutils` and writes its own name and arguments to `$FM_HOME/timeout-calls`, then exits 124. - **`test_gnu_timeout_runs_the_watcher_bound`:** GNU `timeout` and GNU `gtimeout` are both on PATH. The test asserts exit 124, the quiet checkpoint line, and exactly one call: `timeout --signal=INT --kill-after=5s 1 <root>/bin/fm-watch.sh`. - **`test_non_gnu_timeout_uses_gnu_gtimeout`:** a non-GNU `timeout` is next to a GNU `gtimeout`. The test asserts the same exact call, made by `gtimeout`. - In both new tests, Perl is not on PATH. So if the code picked Perl by mistake, the run would fail with 127. How I checked it: - The full test file passes: all 14 tests. - I broke the code on purpose twice. When I swapped the order to try `gtimeout` first, the GNU timeout test failed. When the code always picked Perl, the run exited 127 instead of 124. I then put the production file back; `git status` shows only the test file changed. - `shellcheck -x` passes on the test file. This is a change to tests only, so there is nothing a user would see to check by hand

* fix: recover ownerless extension readiness records (#7933)

* fix: recover ownerless extension readiness and announce cleanup refusals

* no-mistakes(review): Reset cleanup failure episodes and classify failure wakes

* no-mistakes(document): Document ownerless readiness recovery and cleanup failure wakes

* no-mistakes(document): Clarify cleanup failure documentation ownership

---------

Co-authored-by: Kun Chen <3233006+kunchenguid@users.noreply.github.com>

* fix(bin): keep failed or non-schema remote reply reads out of captures (#7874)

* Keep malformed remote reply captures from wedging

* no-mistakes(document): Fix garbled remote reply source failure comment

* no-mistakes(document): Document remote reply failure handling

---------

Co-authored-by: Pitch Perfekt Collective <pitchperfekt@Pitchs-Mac-Studio.local>

* feat(bin): add per-project pr=manual registry token for worker-written PR text (#7937)

* feat(bin): per-project pr=manual registry token for hand-written PR text

A no-mistakes ship on a project where an outside maintainer reviews the PR let
the pipeline's pr step rewrite the hand-written title and body on every
validated push. The registry now records pr=manual, resolved by
fm-project-mode.sh --pr and carried by fm-brief.sh --pr, fm-spawn.sh and
fm-promote.sh like forge=. The generated brief skips pr and ci, and the worker
writes and publishes the PR text itself.

* no-mistakes(review): Drop pr_text key; fix manual-PR checks wait and base

* no-mistakes(review): Remove dead PR_TEXT and timeout example

* no-mistakes(document): Fix README pr=manual sentence grammar

* test(bin): restore the displaced placeholder comment and rename the spawn agreement test

The comment for the leftover-placeholder test sat above the new pr=manual tests.
The spawn test said it recorded the PR text, but it only checks that a launch happens.

* fix: refuse teardown when Git hides untracked files (#7909)

* fix(teardown): detect untracked work regardless of Git status config

* test(watcher): avoid blocking FIFO contention handshakes

* no-mistakes(document): Document hidden-untracked teardown safety

---------

Co-authored-by: Kun Chen <3233006+kunchenguid@users.noreply.github.com>

* fix(bin): keep newest run attribution in crew-state (#5954)

* fix: prefer current run over stale overview row

* fix: preserve newest run precedence over stale status

* no-mistakes(document): Document live-run precedence in crew-state attribution

* fix: use ledger order for same-minute run precedence

* test: cover both overview orders for same-minute run attribution

Document and pin newer-first (recorded AXI) and historical-first overview
orders. Same-minute ledger timestamps use row order as the tie-break so an
older live bare status cannot hide a newer completed run.

* no-mistakes(review): Treat failed as overridable terminal overview status

* no-mistakes(review): Fix equal-head live run precedence with identity ordering

* no-mistakes(document): Updated run identity ordering documentation

* no-mistakes(lint): Fix ShellCheck export warning

* no-mistakes(review): Prove same-head ordering or report unknown

* no-mistakes(review): Guard failed selected-run reads and drop dead same-head ordering

* no-mistakes(ci): I fixed both Greptile findings (ci-1, ci-2) in bin/fm-crew-state.sh. The change is in the working tree. I did not commit it, push it, or reply to the Greptile threads, because those steps belong to the outer pipeline. ci-1. Invariant: a live run from bare `axi status` may replace a terminal overview selection only when it is proven newer than every other run on the same branch. Previously the code compared it only against the selected run. Now crew-state reads each other candidate with `axi status --run <id>` and compares the live run against each one: - If another candidate is also live, it reports `unknown`, "competing live runs". This keeps the competing-live-runs check. - If two runs share a head and a ULID timestamp, it reports `unknown`, "same-head run ordering unverified", as before. - It promotes the live run only when it is proven newer than all other candidates. - If the live run is newer than the selected run but not proven newer than some other candidate, it reports `unknown`, "run ordering unverified", and names every run id. This means neither the stale selected run nor the live run can hide a newer failed run. This branch is the one judgement call: without it, the stale "done" row A would still hide C's failure. - In all other cases the overview's selection stands. The lib helper is now a pairwise compare called `fm_nm_run_is_newer_than` (it was `fm_nm_run_is_newer_than_selected`). The selected run's detail from the loop is reused when the read succeeded, as in the round-1 fix. I updated the sentence in docs/architecture.md to match. ci-2. Invariant: the `no-mistakes runs` ledger is read only to order runs with different heads. It is now fetched lazily, at most once, and only when a candidate's head differs from the live run's head. Same-head ULID comparisons never call it. Regression test: `test_live_run_newer_than_selection_does_not_hide_newer_failed_run` covers A (stale completed, listed first), C (newer failed) and B (live, created between them). All three share one head and use ULID ids. It expects `state: unknown`, C's id in the output, and no `state: working`. Before the fix it fails: with the fixed code stashed it printed `state: working ... run: 01M1...` (run B). On the original base 3fbace9f the overview would select A, so the output would be `done`, which also fails the `unknown` check. I did not run that base case. Verification: `bash tests/fm-crew-state.test.sh` passes in full ("all fm-crew-state tests passed", the new test included). `shellcheck` on the three changed shell files reports only the existing info-level SC1091 "not following sourced file" notes. No end-to-end run against a live no-mistakes daemon was possible here. I checked the change with the crew-state test harness and its fake `no-mistakes` CLI

---------

Co-authored-by: mehulbhagwani <mehulbhagwani@users.noreply.github.com>
Co-authored-by: Pitch Perfekt Collective <pitchperfekt@Pitchs-Mac-Studio.local>

* chore(ci): run the full suite on outside pull requests only after the full-ci label

Outside pull requests run only the coverage guard and repo invariants until the full-ci label is added; lint and every test lane wait.

A new Full suite check fails naming the full-ci label until it is added, and fails whenever a lane fails or is cancelled.

The label starts the full suite, and later pushes run it again; main pushes, own branches and write-access authors run everything as before.

Other labels run no job at all: their skipped checks take a 'Not run for label - ' prefix, so they cannot hide an earlier failure or a later pass.

Close main pushes keep only the newest run; CONTRIBUTING.md explains the label, and the full-ci label now exists.

* feat(bin): add opt-in systemone and openai decision providers to dispatch resolution (#7664)

* feat(bin): add opt-in systemone and openai providers to typed dispatch resolution

Extend the FM_DISPATCH_PROVIDER/FM_DISPATCH_MODEL seam with a generic
systemone provider (any System One-compatible host at FM_DISPATCH_BASE_URL,
optional FM_DISPATCH_API_KEY) and an openai provider that maps the Choice
request to OpenAI's Decisions API and its answer back. No provider set keeps
the original off line; the never-send check runs on the endpoint and the final
per-provider body. Live provider captures are recorded as pending.

Refs #7643, builds on #7149.

* docs(verification): record the live OpenAI Decisions capture for dispatch resolution

Add a dated 2026-10-23 section for the openai provider: 25 hand-labeled
synthetic briefs against gpt-6-luna, outcome and latency tables, the usage
and header fields actually returned, a calibration note, and one verbatim
request and response pair. The systemone live check stays pending.

Refs #7643.

* docs(verification): record the live Clef capture for the systemone provider

Replace the pending systemone section with a dated 2026-10-23 run against
Cloudflare Workers AI's @cf/cloudflare/clef, reached through a local
test-only relay because Workers AI serves System One at /ai/run/<model> in
a {result, success} envelope. Adds the outcome and latency tables, a
calibration note compared with the gpt-6-luna run, and one verbatim request
and envelope pair. A direct Workers AI option stays out of scope.

Refs #7643.

* feat(bin): promote agy to a full primary and secondmate harness (#7941)

* feat(agy): promote Antigravity CLI to full primary and secondmate harness

Add tracked .agents/hooks.json, bin/fm-sessionstart-agy.sh, bin/fm-turnend-guard-agy.sh, PreToolUse --agy seatbelt flags, session-lock agy ancestry, autoarm supervision model, and --secondmate agy workspace trust pre-registration and spawn support.

* no-mistakes(review): Fix agy Stop-hook park, hooks.json shape, and live coverage

* no-mistakes(review): Unbound agy Stop park, raise ceiling, prove live deny

* no-mistakes(review): Correct agy verification doc park-bound wording

* no-mistakes(document): Document agy as verified primary and secondmate harness

* no-mistakes(ci): I fixed all three selected findings, and every check I ran passed, including the live agy end-to-end run. **ci-1 (`tests/fm-agy-primary-live-e2e.test.sh`):** The invariant is that the live Stop-hook test passes only if a real watcher starts and its wake reaches a follow-up turn. The old test passed as soon as `.agy-park-owner` existed. I replaced the Stop-hook park block with the one the user specified. It waits until both `.agy-park-owner` and `.last-watcher-beat` exist, wakes the watcher with a `done:` status line, and asserts that the park owner was recorded, the watcher started, and `DONE` appears in the agy output. **ci-2 (agy away daemon):** The invariant is that `/afk` must not launch a separate away daemon on any primary whose home runs the supervision host. The agy Stop-hook guard already runs the host when it is enabled, but `fm_afk_launch_host_primary` left agy out. I added `agy` there, which is the one shared check all three callers use. I also added agy to: - the header comment in `bin/fm-afk-launch.sh`; - the three harness loops and the pass message in `tests/fm-afk-launch.test.sh`; - the primary lists and counts in `docs/supervision-host.md`, the matching lines in its engine-selection section, and a new Antigravity (`agy`) row in its Arm owners table; - the header comment in `bin/fm-supervision-instructions.sh`. **user-1 (`.agents/hooks.json`):** The invariant is that each hook command stays one script under Windows `cmd /c` and exits 0 when `sh` is missing. All 5 commands now use `sh -c "..." || cd .`. This does not change behaviour on Linux or macOS, because the `--agy` hooks report deny or continue as JSON on stdout and exit 0. The file keeps its live-verified `{"firstmate":{...}}` shape, matchers and 28800s Stop timeout. **Verification:** - `tests/fm-agy-primary.test.sh` passes, including running the SessionStart hook command from both `.agents/` and the repo root. - `tests/fm-afk-launch.test.sh` has no failures, and the new agy check passes. Its rex end-to-end cases were skipped because the rex CLI is not installed. - `tests/fm-supervision-instructions.test.sh` has no failures. - `bin/fm-lint.sh` and `bin/fm-doc-audience-check.sh` pass. - `FM_AGY_PRIMARY_LIVE=1 tests/fm-agy-primary-live-e2e.test.sh` printed all four `ok` lines and no failures, including "Stop hook parks on a real watcher and delivers its wake to a follow-up turn". The output went through `tail`, so the exit code shown is `tail`'s, not the test script's

* feat(bin): add shared_quota opt-out from quota-based dispatch ranking (#7894)

* feat(dispatch): add shared_quota home opt-out from quota-based ranking

A home whose Claude and other provider usage draws on one combined AI
budget has no meaningful per-provider quota rows, so spendPriority
ranking and runway gates pick the wrong candidate. An optional
top-level "shared_quota": true in config/crew-dispatch.json now opts
the home out: the typed resolver makes no quota-axi call, applies no
quota floor or runway gate, ranks nothing by spendPriority, and
resolves the matched rule's use profiles in declared order, printing
every candidate line with quota ranking off by home declaration.
Firstmate's quota-array-dispatch intake honors the same declaration.
Without the setting, behavior is unchanged. Non-boolean values are
actionable configuration errors in both the resolver and bootstrap.

* test(dispatch): cover shared-quota bypass of unmet rule and profile floors

The shared_quota opt-out test picked a rule with no quota floor, so the
separate rule-floor and profile-floor bypass paths stayed untested.
Two cases now run against the same fixture: a rule whose model:fable
floor (20%) exceeds the snapshot's 15%, and a profile whose all_models
floor (50%) exceeds codex's 31%, each asserting the declared-order pick
still wins with no quota-axi invocation.

* no-mistakes(review): Narrow shared-quota skill opt-out to quota-only gates

* no-mistakes(review): Document preferred_provider under shared_quota opt-out and test it

* no-mistakes(document): Document shared_quota in schema example and verification inventory

* fix(bin): distinguish recycled reaper PIDs in tombstone cleanup (#7958)

* fix(bin): distinguish recycled reaper PIDs in tombstone cleanup

* no-mistakes(ci): ci-2 fixed in tests/fm-watcher-lock.test.sh (test_lock_tombstone_tracks_reaper_start_time). Invariant: no fixture child may outlive a SIGKILLed runner without a bound. (1) The paused reaper's wait loop now also stops when FM_TEST_SUITE_PID is no longer alive or when SECONDS reaches FM_TEST_STUB_MAX_BLOCK_SECONDS. (2) The one sibling child in the same test, the unrelated `sleep 300`, now sleeps for FM_TEST_STUB_MAX_BLOCK_SECONDS so it uses the same bound. Verification, run serially: bash tests/fm-watcher-lock.test.sh. The new test passed on 4 of 4 runs. Red-before still holds: with the base bin/fm-wake-lib.sh from c9da5523, the test fails with 'not ok - recycled reaper pid kept an abandoned tombstone alive'. Separately, the known stand-down flake ('the replaced watcher did not stand down on its own', watch-legacy-local-time-identity) failed on every run on this host and also fails on base c9da5523 without this change, so the test file still exits 1; left unfixed as instructed. ci-1 (Full suite waiting on the full-ci maintainer label) was ignored per the user's decision

* feat(bin): allow omp as a remote secondmate harness (#7939)

* feat: allow omp as a remote secondmate harness

* test: cover omp on the remote secondmate gates

* fix: retire a remote secondmate whose busy state left with its home

* docs: record omp remote retirement evidence

* review: Refresh pinned remote doctor bootstrap checksum

* fix(bin): name a consumed branch grant instead of a wiring bug (#7969)

* fix(bin): name a consumed branch grant instead of a wiring bug

When a supervision branch's own acknowledgement consumes every granted
row, the drain removes the branch-eligible row snapshot while the owner
record stays live. A repeat drain or acknowledgement in the same turn then
refused with a message implying a broken handoff. Say instead that the
grant was already consumed; the refusal and its exit status are unchanged.

* no-mistakes(document): Document consumed-grant refusal in watcher continuity doc

---------

Co-authored-by: c-c6aw <225476801+c-c6aw@users.noreply.github.com>

* fix: preserve literal ampersands in spawn and supervision paths (#7906)

* feat(bin): read dispatch provider keys from a declared credential source (#5409)

* feat(dispatch): read Typesafe key from Keychain

* no-mistakes(review): Share Keychain key lookup with bootstrap; hard-code service name

* no-mistakes(review): Use one readable-secret Keychain check for bootstrap and resolver

* no-mistakes(document): Point AGENTS key row to owner; record Keychain bootstrap evidence

* feat(dispatch): read provider keys from a declared credential source

bin/fm-dispatch-resolve.sh took the typesafe.ai and OpenRouter keys only
from the environment or $FM_HOME/.env, so a home that keeps its key in the
macOS Keychain needed a wrapper to supply it, and the documented direct
call reported off.

Let the resolver consume an optional, provider-keyed declaration in the
effective config directory, config/dispatch-credential-sources.json. It
names where a key lives and never holds one. macos-keychain is the first
adapter (service, optional account), kept behind a small schema and adapter
registry in bin/fm-credential-source-lib.sh so the shared surface binds to
no one OS or provider.

- Precedence is the environment, then .env, then the declared source, which
  is read only when neither supplied a key and only for the selected
  provider.
- No entry and no key stays off, exactly as before. An unreadable or
  invalid declaration exits 2 with a line that names the problem and never
  a declared value.
- A declared source that this host cannot run, that yields no key, or that
  does not answer within FM_CREDENTIAL_SOURCE_TIMEOUT ends as a structured
  error outcome with nothing sent, so it is not mistaken for an
  unconfigured resolver.
- The key is captured into the same private variable as before and still
  reaches curl only as an fd 3 header. The adapter puts only the service
  and account on argv and discards the tool's stderr.
- --supports-credential-source <source> answers supported or unsupported
  without reading a declaration or running the credential tool, so an
  installer can refuse an unsupported activation before it writes anything.

The resolver tests cover the mapping, effective-home and provider
isolation, precedence, the three failure kinds, and secret containment
with a stubbed security and uname.

Closes #7879

* no-mistakes(review): Gate bootstrap typed checks on declared source; fix timeout

* no-mistakes(review): Document storing the declared Keychain item without access dialog

* no-mistakes(document): Clarify that only a typesafe declaration keeps resolver on

* no-mistakes(document): Merge dispatch key-source precedence into one configuration sentence

---------

Co-authored-by: Kun Chen <kunchenguid@users.noreply.github.com>

* fix: clean up remote reply temporary files and locks on exit (#6489)

* fix(bin): clean remote reply temp paths on every exit

The remote reply adapter left its temporary staging directory and fetch files behind on several exit paths.
The ingest staging directory leaked on the continuity-broken return, whose EXIT trap fired after its local tmp left scope.
The trap cmd_ingest installed also replaced the lifecycle-lock release of the handle subshell.
One EXIT trap now owns every temporary path, each lock subshell runs it before releasing its lock, and the empty hash no longer stages a file.
A test under a private TMPDIR covers the continuity return, a die after staging, a locked handle, and a signal during a document fetch.

* no-mistakes(document): Document remote-reply temporary-file cleanup

* no-mistakes(ci): Fixed ci-1 in tests/fm-remote-reply.test.sh: interrupt the blocked SSH child before waiting, fail if it already exited, and require adapter exit status 143 before checking cleanup. Confirmed the strengthened test rejects an adapter that ignores TERM; the temporary mutation was restored. The full remote-reply suite passed on a serial rerun, and syntax, pinned ShellCheck, and diff checks passed. One earlier run alongside lint timed out waiting for the third reply generation

* fix(bin): clean up the staged source-read output on every exit path

The source leg stages the remote read's output in a temporary file. Track it
with the adapter's other temporary paths so a signal during the read removes
it, and extend the regression test and docs to cover that path.

* chore: ignore Claude Code per-user settings (#6482)

* chore: gitignore Claude Code's per-user local settings file

* no-mistakes(ci): Addressed ci-1 by preserving the staged --no-index correction for both Claude settings assertions in tests/fm-gitignore-config.test.sh, making ignore-rule checks independent of tracking state. Reproduced the original false pass with tracked shared settings and an overly broad .claude/ rule; the corrected test rejects it. Verified normal tracked/untracked settings cases and rejection of a missing local-settings ignore rule. Targeted test runner, pinned ShellCheck, Bash syntax check, and diff checks all passed. No unrelated changes were made

* fix: prefilter inbox history for idempotent remote steering (#7905)

* fix(inbox): prefilter idempotent steering history

* no-mistakes(document): Clarify delivery mode in steering retry contract

* test(inbox): cover acknowledgement before prefilter opens

* feat(bin): add Kiro CLI as a crewmate/scout harness adapter (port of #7956) (#7979)

* feat(bin): add Kiro CLI as a crewmate/scout harness adapter

Port of #7956 onto current main so it gets a fresh CI run.

Adds a `kiro` (Kiro CLI, V2 engine) harness adapter, crewmate/scout only
(--secondmate launches are refused). fm-harness.sh detects it by kiro-cli
ancestry; fm-spawn.sh launches it with a per-task KIRO_HOME under
state/<id>.kiro-home (generated userPromptSubmit and stop hooks plus
chat.disableTrustAllConfirmation); busy, control, send, watch, procevent,
teardown and bootstrap wiring recognise it. Composer ghost-text and busy
footer matching is scoped to FM_COMPOSER_HARNESS=kiro, so other harnesses
read exactly as before. Adds references/harness/kiro.md,
docs/verification/kiro.md, tests/fm-kiro-harness.test.sh and an opt-in
live e2e signals guard.

Conflicts with main were resolved by keeping main's agy promotion and
adding kiro to the crewmate-only lists next to it.

Co-authored-by: kiatng <1106470+kiatng@users.noreply.github.com>
Co-authored-by: Marsjohn-11 <74795701+Marsjohn-11@users.noreply.github.com>

* fix(send): detect kiro on meta-less explicit targets

An explicit session:window send has no task meta, so TARGET_HARNESS stayed
empty and the kiro composer rules never applied. A finished kiro idle
placeholder then read as pending, extra Enters were pressed, and fm-send
exited 3 even though kiro accepted the message.

Resolve kiro from the live pane's foreground process group when meta is
absent, and keep every other explicit-target send on the unknown-harness
path. Move the kiro live e2e version probe to after the live gate so an
opted-out run never starts kiro-cli.

Co-authored-by: Kun Chen <kunchenguid@users.noreply.github.com>

---------

Co-authored-by: kiatng <1106470+kiatng@users.noreply.github.com>
Co-authored-by: Marsjohn-11 <74795701+Marsjohn-11@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Kun Chen <kunchenguid@users.noreply.github.com>

* fix(bin): publish hold origins only after backend success (#6777)

* fix(captain-hold): refuse a previous origin's answer after an incomplete hold move

A hold moved to a new origin wrote its stamp and origin before the backend
hold. A process stopped between those writes, or a refused hold whose rollback
also failed, left the task associated with the new origin while it carried
only the earlier call's answer, and complete and verify accepted that answer.

Verification now treats an open, unheld task that leads with a hold-set stamp
above a recorded answer as a re-hold that never completed, so the answer no
longer satisfies the new origin however the move was interrupted. A refused
hold also restores the body the attempt started from, and the origin lookup
runs before any write, so a clean failure leaves the earlier answer valid.

Closes #6461

* no-mistakes(review): Publish hold origins only after backend success

* no-mistakes(review): Publish verified holds before origin writes

* no-mistakes(document): Clarify hold-origin durability documentation and regression coverage

* no-mistakes(lint): Quote done subcommand to resolve ShellCheck warning

* no-mistakes(document): Clarify recorded-origin provenance guarantees

* feat(backends): add experimental explicit-only hc (herdr-core) runtime backend (#7963)

* feat(backends): add experimental explicit-only hc (herdr-core) runtime backend

herdr-core is the terminal core under Herdr.app and is not Herdr 1.
The adapter follows the tmux shape: one login-shell terminal per task,
Treehouse keeps the worktree, and fm-spawn drives it through the same
send/current-path primitives.

- bin/backends/hc.sh: create, capture, visible capture, send line, typed
  literal through hc keys, named keys, current path, composer state,
  submit, native busy state, recovery agent state from the foreground
  process and its process group, and a close that proves the terminal gone.
  Targets are <session>:<address>; every call pins that HC_SESSION, and an
  empty session never reaches hc. Task and home labels gate input and close.
- bin/fm-backend.sh, bin/fm-spawn.sh: hc arms, explicit-only selection,
  endpoint validation, hc_session/hc_terminal metadata, secondmate refusal.
- tests: fake-CLI suite and a real-hc smoke test on a private core.
- docs: hc-backend.md, configuration, verification record, README links.

* fix(hc): submit the spawn launch line by paste and add the hc liveness live guard

The launch line always carries a + that hc keys cannot type, so fm-spawn
pastes it with hc send and consumes the Enter that follows. The launch
environment floor keeps HC_SESSION, HC_TERMINAL_ID, HC_TERMINAL_SOCKET and
HC_SCOPE. tests/fm-backend-hc-liveness-live-e2e.test.sh launches every
installed harness bare in a private core and requires alive. The
verification record gains the end-to-end spawn, steer, peek and teardown run.

* no-mistakes(review): Allow hc interrupt keys and drop unused hc send_literal

* no-mistakes(document): Sync hc backend inventories and adapter header comment

* no-mistakes(ci): Fixed. When an hc task was torn down, the kill function read the task's expected label from the wrong argument, so it ended up accepting any terminal in the same home and could close another task's worker. - Invariant: every hc close must be gated by the task label that teardown passes as the third argument to fm_backend_kill. - Where it must hold: fm-teardown.sh calls `fm_backend_kill <backend> <target> <zellij_tab_id> fm-<id>` at all its sites (around lines 3482, 3491, 3494, 3876, 3986 and 3995). The dispatcher at bin/fm-backend.sh:1156 passes "$@" through to fm_backend_hc_kill, and that function is the only hc close path. So fixing that one function's arguments covers every teardown site. - Fix in bin/backends/hc.sh:279: the signature is now `<target> [unused] [expected-label]` and it reads `expected=${3:-'*'}`, the same shape tern, rex, cmux and paseo use. The label value matches what hc terminals carry: spawn creates them with firstmate.task=$W where W="fm-$ID" (bin/fm-spawn.sh:4545 and 4955), and teardown passes "fm-$ID". - New test in tests/fm-backend-hc.test.sh, test_kill_refuses_another_tasks_terminal, goes through the public fm_backend_kill path. A terminal labeled fm-other is refused for expected label fm-a1, stays alive and gets no `hc kill`. The terminal labeled fm-a1 is closed and removed. Before the fix the test failed ("expected a refusal"), and after it the whole suite passes. - Checks: `bash tests/fm-backend-hc.test.sh` passes every test and `shellcheck -x` is clean on both files. The live smoke and e2e hc tests call kill without a label, which keeps the existing behavior of accepting any task label from this home. I did not run them because they need a real herdr-core. VERIFIED with the unit tests on the fake hc CLI, not against a real hc core

* fix(hc): keep the live liveness guard from repointing the operator's claude

A real claude started under the guard's scratch XDG_DATA_HOME can self-update into it and repoint ~/.local/bin/claude there, leaving the link dangling once the scratch directory is removed.
Export DISABLE_AUTOUPDATER=1, as bin/fm-live-lab.sh already does for its live harnesses.

* fix(hc): drop an inherited HC_SOCKET so the session pin holds

* no-mistakes(document): Document hc dropping inherited HC_SOCKET for session pin

* no-mistakes(ci): I fixed both Greptile findings. The hc unit suite passes all 12 tests, three runs in a row, and `shellcheck -x` is clean on the 4 touched files. VERIFIED with unit tests (a fake hc CLI plus a real process group). NOT VERIFIED against a real hc core, because the live tests need herdr-core. ci-1, live tests could stop an unrelated core - Invariant: every direct `hc` call a test makes must reach only its private scratch core, so an inherited HC_SOCKET (which wins over HC_SESSION in hc 0.1.14) must never be set. - Where it must hold: the two suites that call `hc` directly (`hc server status` at startup and `hc server stop` in cleanup), `tests/fm-backend-hc-liveness-live-e2e.test.sh` and `tests/fm-backend-hc-smoke.test.sh`. Adapter calls already go through `fm_backend_hc_cli`, which drops HC_SOCKET. - Fix: both suites add HC_SOCKET to the `unset HC_TERMINAL_ID HC_TERMINAL_SOCKET HC_SCOPE` line, before any `hc` call. ci-2, a shell wrapper running a live worker was reported as dead - Invariant: `fm_backend_hc_agent_state` may return `dead` only when neither the foreground process nor anything else in its process group is a harness. - Where it must hold: there is one classification path, `bin/backends/hc.sh` around line 326. Before the fix, the `shell` branch returned `dead` before the process-group check ran. Callers such as the inbox ring and the watcher read this value through `fm_backend_agent_state`, so fixing this one function covers all of them. - Fix: the result is now `alive` when the foreground process is a harness. Otherwise the process group is checked, which can also give `alive`. After that a shell gives `dead` and anything else gives `ambiguous`. An idle shell, whose group holds no harness, is still `dead`, and the existing test_agent_state_classifies_foreground_and_absence still passes (`t2=dead`). - New test `test_agent_state_reads_a_shell_wrappers_group` in `tests/fm-backend-hc.test.sh`. It starts a real `bash` wrapper in its own process group with a child that runs as `claude`, and points the fake hc terminal's foreground at the wrapper. With the old code the test fails ("expected 'dead', got 'alive'"). With the fix it passes. The comment in the code was updated. `docs/hc-backend.md` already describes the process-group read, so it did not need a change. Not run: `fm-backend-hc-smoke.test.sh` and `fm-backend-hc-liveness-live-e2e.test.sh`, because they need a real hc core

* fix: refresh Herdr upstream references and licensing (#8000)

* docs(herdr): record the Apache-2.0 relicense and herdrdev org rename

Herdr relicensed from AGPL-3.0-or-later to Apache-2.0 in 0.8.0 and the
GitHub organization moved ogulcancelik/herdr to herdrdev/herdr. The old
release URLs redirect to the same assets, so the CI installer and the
version-floor guard now fetch via the canonical org with the pinned
version and checksums unchanged; verified end to end by running the
installer against the new URL.

* no-mistakes(document): Clarify Herdr product boundaries and preserve historical evidence

* fix(pi): stop repeated numbered and byte excerpt reads (#7992)

Fixes #7990

* fix(bin): keep the PR merge watch working when a worker with a PR is relaunched (#7996)

* Preserve PR poll authentication on relaunch

* no-mistakes(review): Keep trace and polytoken meta ahead of PR lines

* test: pin lock staleness in malformed presentation lock wake-queue case (#7837)

* fix(tests): pin lock staleness in malformed presentation lock case

A plain-file presentation lock older than FM_LOCK_STALE_AFTER (default 2s) is reclaimed as garbage, so a slow runner could age the malformed-lock fixture into a successful acquire. Pin the staleness window far above the case runtime so the case is deterministic.

* test(wake-queue): correct the malformed presentation lock staleness comment

---------

Co-authored-by: Trillium Smith <5898009+trillium@users.noreply.github.com>

* feat(bin): add configurable self-update source for /updatefirstmate (#5603)

* feat(bin): let /updatefirstmate follow a configured self-update source

An optional local config/self-update-source ("<remote> <branch>") makes
fm-update.sh fast-forward the primary from that one remote branch instead of
origin/<default>, under the same fast-forward-only guards, and makes local
secondmates advance to the primary's resulting commit (a standalone clone
imports it from the primary first). A home can then run its own fixes from a
branch that carries them on top of upstream, while worker spawns, review
diffs, the cleanup landed-work test, lint and default-branch detection keep
using origin, so new contributions still branch from upstream.

Absent, behaviour is unchanged. An unreadable or malformed file, an unknown
remote or an invalid branch name refuses the whole update before anything
moves rather than falling back to origin. A remote secondmate's host follows
its own code root's config, which the docs record as the limit.

* no-mistakes(document): List config/self-update-source in AGENTS.md config inventory

* no-mistakes(document): Mention self-update source in updatefirstmate skill description

* fix: bound watcher auto-arm failures and recover interrupted locks (#8018)

* fix(bin): commit the attended alarm from the exhausted Stop auto-arm

A Claude failure episode could suppress indefinitely without ever raising
the attended alarm. On every Stop cycle the auto-arm opens its generation
claim before the guard's sync-wait decision, so the guard always steps
aside; terminal_fail_open is never reached and no participant knew that
automatic continuation was exhausted. The block budget still climbed
because the guard's step-aside path accounts for the epoch, so Stops kept
rewaking with empty failed-suppressed bodies forever.

The auto-arm is the only participant that knows its own continuation is
exhausted, so it now owns the terminal escalation: once the failure
notice was consumed and the session block budget is over, the terminal
failure path commits .claude-autoarm-failure-alarmed and the
failed-suppressed outcome inside the owner lock (owner then budget, the
same order the guard's writer uses), then emits one loud final rewake
telling the operator to keep the session attended and diagnose the
Stop-hook supervision. A healthy watcher verified inside that hold resets
the episode instead of alarming, and a refused commit stays suppressed
without a false alarm.

Later Stops in the same episode see the alarm, record failed-suppressed,
and exit 0 so no further continuation or alarm is produced. Positive
watcher recovery still clears the notice, the alarm, and the budget.

Every failed-suppressed commit now carries a one-line stderr reason
naming why the operator notice is not repeated and whether the
Stop-owned retry stays alive, replacing the silent empty bodies that
made suppressed Stops indistinguishable from a wedged hook.

Adds an integrated guard/auto-arm regression driving both hooks through
the exhaustion boundary and asserting the single alarm, post-alarm
suppression, and clean recovery; updates existing tests for the reasoned
suppression contract.

* fix(bin): outlast an unpublished lock pid for one freshness window

CI run 40805704864 ("recovery drain after forced arm interruption")
failed because a dying watcher could not publish .watcher-down inside
its bounded cleanup window, so the drain saw no downtime marker to ack.

The blocker was an empty-pid lock artifact: fm_lock_claim and the
bounded-wait handoff published ownerdir/pid with a truncating write,
and a creator killed mid-write (the bounded handoff helper runs under
timeout -k with a process-group KILL) left a resolvable symlink whose
pid file stayed empty forever. fm_lock_try_acquire treats that as a
fresh mid-acquire hold for a full freshness window, cannot steal it,
and a bounded waiter whose bound equals the window gave up before the
evidence expired.

Two changes. First, both pid writes now go through a same-directory
pid.tmp file renamed into place, so a killed write can no longer leave
a live lock with a permanently empty pid; fm_lock_clean_known_files
sweeps leftover tmp files. Second, fm_lock_acquire_wait_max polls one
extra freshness window when the remaining blocker still has no
published pid, so a waiter outlives the residue instead of failing at
its bound; the moment a pid publishes or the artifact goes stale the
ordinary live-holder and steal rules apply unchanged, and published
live holders keep the original bound.

Adds a regression test that links an owner dir with no pid and asserts
the bounded wait outlasts the freshness window to reclaim it, while a
live holder still fails at the nominal bound; verified to fail against
the pre-change implementation.

* no-mistakes(review): Route every suppressed exit through alarm decision

* no-mistakes(document): Clarify exhaustion and lock-wait documentation

* no-mistakes(lint): Quote empty grace deadline assignment for ShellCheck

* no-mistakes(ci): Fixed tests/fm-x-mode.test.sh: atomic lock-pid publication consumed its overly broad injected mv failure. Targeted the counter-record destination and asserted injection occurred. Reproduced failure before fix; full X-mode test script, pinned lint, bash syntax, and diff checks pass afterward. Full suite failure is downstream of this lane failure; no separate fix needed

* no-mistakes(ci): Fixed Full suite’s underlying shard timeout: the PR marker test’s broad mv failure injection blocked atomic lock-PID publication indefinitely. Restricted injection to the marker destination. Reproduced the hang before fixing; targeted regression, all 49 PR-security tests, ShellCheck, bash syntax, and diff checks pass

* no-mistakes(ci): Fixed load-sensitive remote lifecycle test timeout: all three inheritance/launch barrier waits now honor the existing convergence budget instead of failing after 30 seconds. Full suite failure is downstream of this shard. Full lifecycle E2E, Bash syntax, ShellCheck excluding SC1091, and diff checks pass. Production behavior unchanged

* no-mistakes(ci): Fixed remote-reply fixture races, preserved the committing auto-arm’s final rewake on signals, and asserted the live-holder wait bound. Remote-reply and turnend-guard suites and focused lock test pass; signal regression fails before fix and passes after. Full watcher-lock suite fails earlier in an unchanged macOS watcher-replacement test. Full suite CI failure is downstream of the shard failure

* no-mistakes(ci): Fixed teardown race in tests/fm-watch-arm.test.sh: atomically rename state/home/root fixtures away before deleting contents after process exit. Preserved all existing assertions; production code unchanged. Affected suite passed three runs, including two concurrent copies; targeted unpublished-PID lock test and syntax/diff checks passed. Additional full lock suite failed twice at a separate watcher-replacement exit assertion. Standalone ShellCheck reported existing warnings

* fix(bin): cut stat forks in the wake drain by reading identity and size together (#6271)

Local cherry-pick of https://github.com/kunchenguid/firstmate/pull/6271 pending upstream merge.

* fix(bin): keep pr= merge-poll identity last when recording captain-hold completion (#6732)

* fix(bin): keep PR merge polls authenticated across relaunch

A relaunch rewrote the task record with control_relaunch_tx after the
preserved pr= line. fm_pr_metadata_identity_parse rejects any key after
pr= other than pr_head= and x_*, so the watcher stopped authenticating
the armed merge poll and reported it as an unauthenticated state check,
and the merged-PR wake never arrived. Write the transaction id before
the preserved lines, as fm-remote-secondmate-relaunch.sh already does.

* no-mistakes(review): Keep pr= last for traceparent and completion writes

* no-mistakes(document): Note completion record placement ahead of pr= lines

* no-mistakes(ci): Fixed the Greptile P1 finding (ci-1) as the user decided. **Invariant:** a task's `.meta` record holds exactly one `decisions_reviewed`/`decision_keys` pair, and it sits before `pr=`. Then `meta_value` (which reads the last match) returns the current inventory, and `fm_pr_metadata_identity_parse` still sees `pr=` last. The only place that writes this pair is the awk rewrite in `command_complete` (`bin/fm-captain-hold.sh`). The other hits for these keys under `bin/` are only a comment and an error message. `verify` and later `complete` calls read the pair through `meta_value`, so fixing this one writer fixes them too. **Fix:**…
joergoss pushed a commit to joergoss/firstmate that referenced this pull request Nov 23, 2026
* fix: send remote steers over stdin

* fix: version remote stdin send protocol

* no-mistakes(document): document stdin transport for remote steer in fm-send header

* no-mistakes(ci): Two tests failed in CI. One is caused by this PR; the other is not. 1. Behavior portable serial 5: `tests/fm-secondmate-reconcile.test.sh` failed with "supervision did not deliver the durable reconcile request later". This PR caused it. The PR now sends a remote steer's body on stdin, using `fm-on.sh --stdin` with the `send-stdin` verb. This test's fake ssh started with `cat > /dev/null`, so it threw the body away before it ran the real `fm-remote-secondmate-control.sh`. `cmd_send_stdin` then read an empty message, died with "remote steer message must be nonempty", and no inbox record was written. Rule that broke: a fake ssh that runs the real remote leg must pass the caller's stdin through, as real ssh does. I checked every fake ssh that runs the real leg. `fm-send-remote-delivery.test.sh` already passes stdin through. `fm-secondmate-sync.test.sh` (`make_remote_leg_ssh_stub`) had the same discard line. The stub in `fm-send-resolve-key.test.sh` never runs the leg, so it is fine. The fix deletes the `cat > /dev/null` line in the reconcile and sync stubs. Calls made without `--stdin` still get /dev/null from fm-on, so nothing else changes. Checks run locally: the reconcile test fails before the fix with the same CI message. After the fix, the reconcile test passes (rc=0) and the sync test passes (rc=0). 2. Behavior portable serial 3: `tests/fm-wake-queue.test.sh` failed in `test_concurrent_append_and_drain` with "wake drain: queue lock could not be acquired safely". This PR did not cause it. The PR does not touch `bin/fm-wake-drain.sh`, the wake tests or the wake helpers. The failure is lock contention: 40 appenders run at the same time as a drain, on a loaded CI runner. Locally the whole test passed (70 ok, rc=0). I made no change for it. It is an existing flake in wake-queue lock acquisition and needs its own fix outside this PR. Open PR kunchenguid#7912 ("preserve wake grants when queue-lock acquisition fails") works in the same area
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.

fm-send to a remote second mate fails for large messages: the body travels as an SSH exec argument

2 participants