Skip to content

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

Merged
kunchenguid merged 5 commits into
kunchenguid:mainfrom
WTF-Am-ID:fm/up-fm-7782
Oct 28, 2026
Merged

kunchenguid merged 5 commits into
kunchenguid:mainfrom
WTF-Am-ID:fm/up-fm-7782

Conversation

@WTF-Am-ID

@WTF-Am-ID WTF-Am-ID commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Closes #7782

Review was single-family (Codex) by the owner's temporary choice.

Intent

ok same instructions i gave you before pick high value issues from scan, in all the repos you scanning and use codex only to close them

Context: this task is scan pick P7: upstream issue #7782 in kunchenguid/firstmate. Local-only landing merges the live branch tip instead of the commit that was reported and approved. Triage contract class: restore. Scan notes for this pick:
Issue: #7782

Local-only landing merges the live branch tip instead of the commit that was reported and approved.
Bind the existing approval to a durable owned commit identity.
Size M.
Contract class: restore.
Maintainer triage.

Evidence: bin/fm-merge-local.sh:139 merges "$BRANCH" after the hold check. The inspected path has no persisted done-head comparison.

Competing work: No exact target or approved-head pin found in the final open index. #4284 changes which local base new work starts from, and #2475 protects local commits. They do not pin the reported approval head.

Closure test: In a scratch local-only project record a done head X, approve that state through fixture metadata, then advance the worker branch to Y. Landing must refuse without moving main. Reset the fixture to the approved X and verify exactly X lands. Missing/malformed approval-head records and approval/branch-move races must refuse. Add a focused registered fixture suite if no existing owner fits. The current tree has no tests/fm-merge-local*.test.sh.
The owner approved fixing the scan's high-value picks upstream through PRs, written and reviewed by Codex only.

What Changed

  • Pinned the first accepted local-only commit as local_done_head in live task metadata, and reused the caller-held metadata lock when inactive reconciliation reports readiness.
  • Required the worker branch to match that pin and landed the exact commit through an atomic Git ref transaction. A shared checkout lock serialized different tasks across checks, staging, ref updates, and rollback.
  • Added registered landing and inactive-report regressions, corrected the PR fixtures' delivery modes, and documented pinned-head landing and recovery.

Risk Assessment

Local landing holds its task locks and the shared checkout lock through the Git transaction and rollback. Missing or malformed pins, moved worker branches, and changed approval records refuse landing.

Testing

The repaired candidate at 56f7c1f24cfbc5f6b4964b2a0d08209774070843 passed fresh Codex validation in no-mistakes run 01M615GR82CTFFPXAXTV2V7AC7:

  • TMPDIR=/tmp bash bin/fm-test-run.sh --jobs 1 tests/fm-merge-local.test.sh tests/fm-inactive-reconcile.test.sh passed both files, including all eight landing cases and the real inactive scan/report regression.
  • TMPDIR=/tmp bash bin/fm-lint.sh passed.
  • TMPDIR=/tmp bash bin/fm-lint.sh bin/fm-dod-lib.sh bin/fm-inactive-reconcile.sh bin/fm-teardown.sh bin/fm-merge-local.sh passed source-aware extended analysis.

Additional local runs through bin/fm-test-run.sh passed the full teardown, PR-security, task-delivery, and DoD library files. Failing-first runs reproduced the missing parent report, the competing task's rollback reverting landed files, the PR fixture failures, and SC2031 lint findings. The published repair diff exactly matched the locally validated candidate.

The earlier baseline and live scenario evidence below was collected before the CI repair.

  • Live validation: ✅ go - 11 of 11 scenarios driven live against the product
Scenario Result Live Evidence
S1: Record and approve X, advance to Y and receive refusal, then restore X and land exactly X ✅ pass live Live landing transcript, S1
S2: Missing, empty, abbreviated, symbolic, duplicate and nonhex approval heads refuse with main unchanged ✅ pass live Live landing transcript, S2
S3: Pending approval prevents landing without changing main ✅ pass live Live landing transcript, S3
S4: Change the branch or approval record during the approval read and receive refusal ✅ pass live Live landing transcript, S4
S5: Move the worker branch inside the final Git invocation and receive refusal with main and its checkout unchanged ✅ pass live Live landing transcript, S5
S6: Stale captured readiness cannot approve a replacement task generation ✅ pass live Live landing transcript, S6
S7: Diverged main refuses landing without changing its checkout ✅ pass live Live landing transcript, S7
S8: Replace the approved head while landing waits for its lock and receive refusal ✅ pass live Live lock-race transcript, S8
S9: Replace the task generation while landing waits for its lock and receive refusal ✅ pass live Live lock-race transcript, S9
S10: Forced cleanup during validated landing refuses, then exactly approved X lands cleanly ✅ pass live Live cleanup-race transcript, S10
B1: Baseline reproduces the defect by landing unapproved Y after approval at X ✅ pass live Live landing transcript, B1
Evidence: Observed landing and refusal evidence

Source: Observed landing and refusal evidence

Candidate: a6728a4cde587d506e248b3f37884daca0409111
Preserved lifecycle checkpoint diff SHA-256: 11d760b58cc3933141e3b510fdd53eeca0102537fd9302ee3c53f9cfa2b32f6e
Excerpts from real CLI transcripts from this validation retry. Full transcripts are retained beside this file.

Transcript: live-landing-retry.log
SCENARIO S1: Approved X persists, advancing to Y refuses, stale readiness refuses, restoring X lands exactly X
error: branch fm/local-task differs from the recorded local done head; refusing
OBSERVED refusal exit=1, main=ac7fb882dd2d4af6f72dfd065169f8ce77d30e65, clean checkout, approved.txt absent
merged fm/local-task into local main (ac7fb882dd2d4af6f72dfd065169f8ce77d30e65 -> 76e1ffa) in ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/project
OBSERVED approved X landed exactly: main=76e1ffa945625b0fb521841c97e055b64e658162; approved.txt=approved X; no unapproved.txt; clean checkout
RESULT pass
SCENARIO S2: Missing, empty, abbreviated, symbolic, duplicate and nonhex approval heads refuse
error: missing or malformed local done head for task local-task; report readiness before approval
OBSERVED refusal exit=1, main=8bd76b1f61b943d2a9fca8fa781fcab92413deb4, clean checkout, approved.txt absent
error: missing or malformed local done head for task local-task; report readiness before approval
OBSERVED refusal exit=1, main=98085f0bd95dd6489964c5110ecb834e3d09e568, clean checkout, approved.txt absent
error: missing or malformed local done head for task local-task; report readiness before approval
OBSERVED refusal exit=1, main=3db7f7149fc844887e7f41ee6fe1224e28d2003b, clean checkout, approved.txt absent
error: missing or malformed local done head for task local-task; report readiness before approval
OBSERVED refusal exit=1, main=4955d34b56b83a87250d81387262f60b7ba6c8c8, clean checkout, approved.txt absent
error: missing or malformed local done head for task local-task; report readiness before approval
OBSERVED refusal exit=1, main=4955d34b56b83a87250d81387262f60b7ba6c8c8, clean checkout, approved.txt absent
error: missing or malformed local done head for task local-task; report readiness before approval
OBSERVED refusal exit=1, main=c8507a65890c7ad062cfd27e440195cbb874320d, clean checkout, approved.txt absent
RESULT pass
SCENARIO S3: An unreleased captain hold prevents local landing
error: task local-task is still held for the captain; release it before merging
OBSERVED refusal exit=1, main=8322ebf2bc6b5919486a1dd6551211ee2f259457, clean checkout, approved.txt absent
RESULT pass
SCENARIO S4: Branch and approval-record changes during the real approval read refuse
error: local done head or branch changed during approval check; refusing
OBSERVED refusal exit=1, main=9c13a7d67c0e1033535169fcb295096c06899a4d, clean checkout, approved.txt absent
error: local done head or branch changed during approval check; refusing
OBSERVED refusal exit=1, main=b96e8758a061e5c6fbb5e20073518a465d2d509d, clean checkout, approved.txt absent
RESULT pass
SCENARIO S5: A branch move inside the final Git invocation refuses and restores the checkout
fatal: prepare: cannot lock ref 'refs/heads/fm/local-task': is at e905a2b59961c4b1bc00dd3e1a08d079cea25ba8 but expected fc70630f1e32656f68b1ae535d7ce70d2471b925
OBSERVED refusal exit=128, main=cea6320a97445c43ef0cda3d071134ba5062328e, clean checkout, approved.txt absent
RESULT pass
SCENARIO S6: Captured readiness cannot pin a replacement task generation
OBSERVED replacement generation remains unpinned after stale captured readiness
RESULT pass
SCENARIO S7: Diverged main refuses without changing its checkout
REFUSED: fm/local-task is not a fast-forward of main (it has diverged).
OBSERVED refusal exit=1, main=00fb83e47af89d766abaea5bd90ece9fcdd5eab1, clean checkout, approved.txt absent
RESULT pass
SCENARIO B1: Baseline lands Y after approval at X, reproducing the original defect
merged fm/local-task into local main (c0982de -> dd22ae8) in ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/baseline/project
BASELINE REPRODUCED defect: approved=c6c03e37c79995862a1aef5a908e2e8f9e338b82; main landed unapproved Y=dd22ae8d5c79929cf24251f85c66dc239285c080
RESULT pass
CLEANUP removed ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp

Transcript: live-lock-races-retry.log
SCENARIO S8: Replacing a valid approval head while landing waits for its control lock refuses
error: task local-task local done head changed while waiting to merge; refusing
OBSERVED refusal exit=1, main=c7fd164a6762261af238439b16807e3d6cbb96ea, clean checkout, approved.txt absent
RESULT pass
SCENARIO S9: Replacing the task generation while landing waits for its control lock refuses
error: task local-task changed incarnation while waiting to merge; refusing
OBSERVED refusal exit=1, main=0e53fa3370d7a0a5ed5b601fbf8f01f170a5b6e0, clean checkout, approved.txt absent
RESULT pass
CLEANUP removed ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-_qt8nipu

Transcript: live-teardown-race-retry.log
SCENARIO S10: Forced teardown during validated landing refuses, then exactly approved X lands
OBSERVED landing paused after ancestry validation with task control lock held
error: another lifecycle action is already running for task local-task; nothing was changed
OBSERVED forced teardown refused; task metadata and worker remain
merged fm/local-task into local main (2a98a9147c0523b6d8511c44aa989241f70513c5 -> 4833e45) in ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-4omsii4b/teardown-race/project
OBSERVED exactly approved X landed after forced teardown was rejected
RESULT pass
CLEANUP removed ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-4omsii4b
Evidence: Live landing transcript

Source: Live landing transcript


SCENARIO S1: Approved X persists, advancing to Y refuses, stale readiness refuses, restoring X lands exactly X
$ bash ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/bin/fm-lab-home.sh create ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/home
~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/home
exit=0
$ git init -q -b main ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/project

exit=0
$ /opt/homebrew/bin/git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/project add base.txt

exit=0
$ /opt/homebrew/bin/git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/project commit -qm base

exit=0
$ /opt/homebrew/bin/git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/project rev-parse HEAD
ac7fb882dd2d4af6f72dfd065169f8ce77d30e65
exit=0
$ /opt/homebrew/bin/git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/project worktree add -q -b fm/local-task ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/worker

exit=0
$ /opt/homebrew/bin/git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/worker add approved.txt

exit=0
$ /opt/homebrew/bin/git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/worker commit -qm X

exit=0
$ /opt/homebrew/bin/git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/worker rev-parse HEAD
76e1ffa945625b0fb521841c97e055b64e658162
exit=0
$ /opt/homebrew/bin/tasks-axi add local-task Land approved X --kind ship --start
ok: added local-task (ship) -> In flight
task:
  id: local-task
  title: Land approved X
  state: in_flight
  blocked: no
  blocked_by: none
  held: no
  hold_reason: "-"
  hold_kind: "-"
  hold_until: "-"
  kind: ship
  repo: "-"
  priority: "-"
  created: 2026-10-28
  closed: "-"
  deps: none
  links: none
  body: ""
help[2]:
  - Run `tasks-axi done local-task --pr <url>` when it ships
  - Run `tasks-axi block local-task --by <other>` to record a dependency
exit=0
$ bash -c source "$1/bin/fm-dod-lib.sh"; fm_dod_accept_ship_done ship local-only "$2" "$3" "done: ready in branch fm/local-task" "$4/state" local-task "$5" live-done ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7 ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/worker ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/project ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/home ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/home/state/local-task.meta

exit=0
PERSISTED kind=ship
mode=local-only
branch=fm/local-task
project=~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/project
worktree=~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/worker
spawn_gen=live-1
harness=codex

local_done_head=76e1ffa945625b0fb521841c97e055b64e658162

$ bash ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/bin/fm-captain-hold.sh hold local-task --reason Local merge approval
local-task
exit=0
$ bash ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/bin/fm-captain-hold.sh answer local-task --release --decision-file ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/home/approval.txt
released: local-task
exit=0
$ /opt/homebrew/bin/git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/worker add unapproved.txt

exit=0
$ /opt/homebrew/bin/git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/worker commit -qm Y

exit=0
$ /opt/homebrew/bin/git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/worker rev-parse HEAD
376d33a9e4266c19d7e837a4f1dfd8d2b8685065
exit=0
$ bash ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/bin/fm-merge-local.sh local-task
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
●  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 guarded operation WILL still run.
●  repair missing watcher supervision with a foreground checkpoint: bin/fm-watch-checkpoint.sh --seconds 180.
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
error: branch fm/local-task differs from the recorded local done head; refusing
exit=1
$ /opt/homebrew/bin/git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/project rev-parse main
ac7fb882dd2d4af6f72dfd065169f8ce77d30e65
exit=0
$ /opt/homebrew/bin/git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/project status --porcelain

exit=0
OBSERVED refusal exit=1, main=ac7fb882dd2d4af6f72dfd065169f8ce77d30e65, clean checkout, approved.txt absent
$ bash -c source "$1/bin/fm-dod-lib.sh"; fm_dod_accept_ship_done ship local-only "$2" "$3" "done: ready in branch fm/local-task" "$4/state" local-task "$5" live-done ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7 ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/worker ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/project ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/home ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/home/state/local-task.meta
local-only done head could not be recorded or differs from the recorded head; revised work requires a new task/approval record
exit=1
$ /opt/homebrew/bin/git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/approved/worker reset --hard 76e1ffa945625b0fb521841c97e055b64e658162
HEAD is now at 76e1ffa X
exit=0
$ bash ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/bin/fm-merge-local.sh local-task
WARNING: watcher still down (same stale ep

... [68363 bytes truncated] ...

utable ship branch recorded in
# state/<task-id>.meta ("fm/<id>" for records created before that field existed).
#
# This is firstmate's merge gate-action (the captain's merge authority applied
# locally instead of via a GitHub PR). It is the one sanctioned exception to hard
# rule #1 "never run state-changing git in projects/", and it is narrow: it only
# runs for mode=local-only tasks, only after the captain approves (or yolo=on
# auto-approves), and only as a clean fast-forward - it refuses a diverged branch
# and tells you to have the crewmate rebase. See AGENTS.md prime directives,
# project management, and task lifecycle.
# The task's existing per-task control lock serializes the captain-hold check
# through that fast-forward. A still-held or unreadable row refuses before the
# merge, so a captain approval must be recorded as an `answer --release` before
# this entrypoint is invoked. The lock ends when the fast-forward returns;
# docs/captain-hold-lifecycle.md owns the accepted merge-to-cleanup residual.
# Usage: fm-merge-local.sh <task-id>
set -eu

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
FM_ROOT="${FM_ROOT_OVERRIDE:-$(cd "$SCRIPT_DIR/.." && pwd)}"
FM_HOME="${FM_HOME:-${FM_ROOT_OVERRIDE:-$FM_ROOT}}"
STATE="${FM_STATE_OVERRIDE:-$FM_HOME/state}"
# shellcheck source=bin/fm-pr-lib.sh
. "$SCRIPT_DIR/fm-pr-lib.sh"
# shellcheck source=bin/fm-backlog-transition-lib.sh
. "$SCRIPT_DIR/fm-backlog-transition-lib.sh"
if [ "$#" -ne 1 ] || ! fm_pr_task_id_valid "$1"; then
  echo "error: invalid local merge request" >&2
  exit 2
fi
ID=$1
fm_backlog_directory_present "$STATE" "state directory" || {
  echo "error: local merge refused: $FM_BACKLOG_TRANSITION_ERROR" >&2
  exit 1
}
META="$STATE/$ID.meta"

# shellcheck source=bin/fm-wake-lib.sh
. "$SCRIPT_DIR/fm-wake-lib.sh"
"$FM_ROOT/bin/fm-guard.sh" || true
# Role partition: landing local-only work is MAIN-owned; the Pi supervision
# branch reports readiness and never lands (contract: bin/fm-lease-lib.sh;
# no-op in homes without a branch actor). This action is deliberately NOT
# relocated under the away-posture record: unlike the PR merge it has no
# record-side grant gate of its own, so a parked main keeps it held for the
# captain's return. This precedes reading the task record, because the wrong
# actor is refused for its role whatever it says.
# shellcheck source=bin/fm-lease-lib.sh
. "$SCRIPT_DIR/fm-lease-lib.sh"
fm_lease_forbid_branch "local-only landing (fm-merge-local)"

[ -f "$META" ] || { echo "error: no meta for task $ID at $META" >&2; exit 1; }
if ! fm_backlog_meta_spawn_gen_optional "$META" "$STATE"; then
  echo "error: local merge refused: $FM_BACKLOG_TRANSITION_ERROR" >&2
  exit 1
fi
MERGE_EXPECTED_SPAWN_GEN=$FM_BACKLOG_META_SPAWN_GEN

MERGE_CONTROL_LOCK=
merge_control_cleanup() {
  [ -z "$MERGE_CONTROL_LOCK" ] || fm_lock_release "$MERGE_CONTROL_LOCK" || true
}
trap merge_control_cleanup EXIT
MERGE_CONTROL_LOCK="$STATE/.control-$ID.lock"
fm_lock_acquire_wait "$MERGE_CONTROL_LOCK"
if ! fm_backlog_meta_spawn_gen_optional "$META" "$STATE"; then
  echo "error: task $ID changed while waiting to merge; refusing: $FM_BACKLOG_TRANSITION_ERROR" >&2
  exit 1
fi
if [ "$FM_BACKLOG_META_SPAWN_GEN" != "$MERGE_EXPECTED_SPAWN_GEN" ]; then
  echo "error: task $ID changed incarnation while waiting to merge; refusing" >&2
  exit 1
fi

PROJ=$(grep '^project=' "$META" | cut -d= -f2-)
MODE=$(grep '^mode=' "$META" | cut -d= -f2- || true)
[ "$MODE" = local-only ] || { echo "error: task $ID is mode=$MODE, not local-only; merge PR tasks with bin/fm-pr-merge.sh <id> <PR url> after approval" >&2; exit 1; }

default_branch() {
  local ref branch
  ref=$(git -C "$PROJ" symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)
  if [ -n "$ref" ]; then
    echo "${ref#origin/}"
    return 0
  fi
  for branch in main master; do
    if git -C "$PROJ" show-ref --verify --quiet "refs/heads/$branch"; then
      echo "$branch"
      return 0
    fi
  done
  return 1
}

BRANCH=$(grep '^branch=' "$META" | cut -d= -f2- || true)
[ -n "$BRANCH" ] || BRANCH="fm/$ID"
if ! git check-ref-format --branch "$BRANCH" >/dev/null 2>&1; then
  echo "error: task $ID has an invalid recorded ship branch '$BRANCH'" >&2
  exit 1
fi
git -C "$PROJ" rev-parse --verify --quiet "refs/heads/$BRANCH" >/dev/null || { echo "error: branch $BRANCH does not exist in $PROJ" >&2; exit 1; }

DEFAULT=$(default_branch) || { echo "error: cannot determine default branch for $PROJ; expected origin/HEAD, main, or master" >&2; exit 1; }

# The project's main checkout must be on its default branch and clean, so the
# fast-forward lands predictably (firstmate never writes here otherwise).
cur=$(git -C "$PROJ" symbolic-ref --short HEAD 2>/dev/null || echo "")
[ "$cur" = "$DEFAULT" ] || { echo "error: $PROJ is on '$cur', expected default branch '$DEFAULT'; cannot merge safely" >&2; exit 1; }
if [ -n "$(git -C "$PROJ" status --porcelain 2>/dev/null | head -1)" ]; then
  echo "error: $PROJ has a dirty working tree; refusing to merge into it" >&2
  exit 1
fi

# Clean fast-forward only: DEFAULT must be an ancestor of BRANCH.
if ! git -C "$PROJ" merge-base --is-ancestor "$DEFAULT" "$BRANCH"; then
  echo "REFUSED: $BRANCH is not a fast-forward of $DEFAULT (it has diverged)." >&2
  echo "Have the crewmate rebase $BRANCH onto $DEFAULT, then retry." >&2
  exit 1
fi

before=$(git -C "$PROJ" rev-parse --short "$DEFAULT")
hold_status=0
FM_HOME="$FM_HOME" FM_STATE_OVERRIDE="$STATE" \
  "$SCRIPT_DIR/fm-captain-hold.sh" open "$ID" --distinguish-absent || hold_status=$?
case "$hold_status" in
  0)
    echo "error: task $ID is still held for the captain; release it before merging" >&2
    exit 1
    ;;
  1|3) ;;
  *)
    echo "error: could not determine whether task $ID is still held for the captain; refusing to merge" >&2
    exit 1
    ;;
esac
merge_status=0
git -C "$PROJ" merge --ff-only "$BRANCH" >/dev/null || merge_status=$?
fm_lock_release "$MERGE_CONTROL_LOCK" || true
MERGE_CONTROL_LOCK=
[ "$merge_status" -eq 0 ] || exit "$merge_status"
after=$(git -C "$PROJ" rev-parse --short "$DEFAULT")
# Opt-in fleet activity ledger (docs/fleet-ledger.md); off costs one file test.
[ ! -e "${FM_CONFIG_OVERRIDE:-$FM_HOME/config}/fleet-ledger" ] || FM_HOME=$FM_HOME FM_STATE_OVERRIDE=$STATE "$SCRIPT_DIR/fm-fleet-ledger.sh" merged "$ID" local || true
echo "merged $BRANCH into local $DEFAULT ($before -> $after) in $PROJ"
exit=0
$ bash ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/baseline/baseline-bin/fm-merge-local.sh local-task
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
●  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 guarded operation WILL still run.
●  repair missing watcher supervision with a foreground checkpoint: bin/fm-watch-checkpoint.sh --seconds 180.
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
merged fm/local-task into local main (c0982de -> dd22ae8) in ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/baseline/project
exit=0
$ /opt/homebrew/bin/git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp/baseline/project rev-parse main
dd22ae8d5c79929cf24251f85c66dc239285c080
exit=0
BASELINE REPRODUCED defect: approved=c6c03e37c79995862a1aef5a908e2e8f9e338b82; main landed unapproved Y=dd22ae8d5c79929cf24251f85c66dc239285c080
RESULT pass
CLEANUP removed ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-wxd4t4kp
Evidence: Live cleanup-race transcript

Source: Live cleanup-race transcript


SCENARIO S10: Forced teardown during validated landing refuses, then exactly approved X lands
$ bash ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/bin/fm-lab-home.sh create ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-4omsii4b/teardown-race/home
~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-4omsii4b/teardown-race/home
exit=0
$ git init -q -b main ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-4omsii4b/teardown-race/project

exit=0
$ /opt/homebrew/bin/git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-4omsii4b/teardown-race/project add base.txt

exit=0
$ /opt/homebrew/bin/git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-4omsii4b/teardown-race/project commit -qm base

exit=0
$ /opt/homebrew/bin/git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-4omsii4b/teardown-race/project rev-parse HEAD
2a98a9147c0523b6d8511c44aa989241f70513c5
exit=0
$ /opt/homebrew/bin/git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-4omsii4b/teardown-race/project worktree add -q -b fm/local-task ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-4omsii4b/teardown-race/worker

exit=0
$ /opt/homebrew/bin/git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-4omsii4b/teardown-race/worker add approved.txt

exit=0
$ /opt/homebrew/bin/git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-4omsii4b/teardown-race/worker commit -qm X

exit=0
$ /opt/homebrew/bin/git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-4omsii4b/teardown-race/worker rev-parse HEAD
4833e455932279b5c5b71385f76df7f5dd045eb7
exit=0
$ /opt/homebrew/bin/tasks-axi add local-task Land approved X --kind ship --start
ok: added local-task (ship) -> In flight
task:
  id: local-task
  title: Land approved X
  state: in_flight
  blocked: no
  blocked_by: none
  held: no
  hold_reason: "-"
  hold_kind: "-"
  hold_until: "-"
  kind: ship
  repo: "-"
  priority: "-"
  created: 2026-10-28
  closed: "-"
  deps: none
  links: none
  body: ""
help[2]:
  - Run `tasks-axi done local-task --pr <url>` when it ships
  - Run `tasks-axi block local-task --by <other>` to record a dependency
exit=0
$ bash -c source "$1/bin/fm-dod-lib.sh"; fm_dod_accept_ship_done ship local-only "$2" "$3" "done: ready in branch fm/local-task" "$4/state" local-task "$5" live-done ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7 ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-4omsii4b/teardown-race/worker ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-4omsii4b/teardown-race/project ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-4omsii4b/teardown-race/home ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-4omsii4b/teardown-race/home/state/local-task.meta

exit=0
$ bash ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/bin/fm-captain-hold.sh hold local-task --reason Local merge approval
local-task
exit=0
$ bash ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/bin/fm-captain-hold.sh answer local-task --release --decision-file ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-4omsii4b/teardown-race/home/approval.txt
released: local-task
exit=0
$ bash ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/bin/fm-merge-local.sh local-task [paused after ancestry validation]
OBSERVED landing paused after ancestry validation with task control lock held
$ bash ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/bin/fm-teardown.sh local-task --force
error: another lifecycle action is already running for task local-task; nothing was changed
exit=1
OBSERVED forced teardown refused; task metadata and worker remain
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
●  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 guarded operation WILL still run.
●  repair missing watcher supervision with a foreground checkpoint: bin/fm-watch-checkpoint.sh --seconds 180.
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
merged fm/local-task into local main (2a98a9147c0523b6d8511c44aa989241f70513c5 -> 4833e45) in ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-4omsii4b/teardown-race/project
exit=0
$ /opt/homebrew/bin/git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-4omsii4b/teardown-race/project rev-parse main
4833e455932279b5c5b71385f76df7f5dd045eb7
exit=0
$ /opt/homebrew/bin/git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-4omsii4b/teardown-race/project status --porcelain

exit=0
OBSERVED exactly approved X landed after forced teardown was rejected
RESULT pass
CLEANUP removed ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7/.test-live-7782-retry-4omsii4b
- Outcome: 🔧 2 issues found → auto-fixed → no changes applied ✅ across 3 runs (1h21m37s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

🔧 **Test** - 2 issues found → auto-fixed → no changes applied ✅
  • 🚨 bin/fm-merge-local.sh:168 - F1: A branch move after the final comparison does not refuse landing. The live probe advanced the worker branch to Y immediately before real Git executed the merge. Landing exited 0 and advanced main to X. This preserves the approved commit but violates the authoritative closure requirement that branch-move races refuse without moving main. The focused fixture accepts successful landing of X in this case, following the weaker verification plan.
  • 🚨 live validation verdict: no-go (7 of 7 scenarios were driven live against the product); failed: S7: Move the worker branch inside the final Git invocation and require landing to refuse without moving main
  • Live validation: ❌ no-go - 7 of 7 scenarios driven live against the product
Scenario Result Live Evidence
S1: Approve X, advance the worker branch to Y, observe refusal, then restore X and land exactly X ✅ pass live Live landing CLI transcript, first scenario
S2: Attempt landing while approval remains held and observe refusal with main unchanged ✅ pass live Live landing CLI transcript, held-task refusals and release outputs
S3: Supply missing, empty, abbreviated, expression, nonhex, nonexistent or duplicate head records and observe refusal ✅ pass live Live landing CLI transcript, invalid durable identities
S4: Submit captured metadata from an earlier task generation and observe readiness rejection without metadata changes ✅ pass live Live landing CLI transcript, stale task generation
S5: Change the recorded head while landing waits for its metadata lock and observe refusal with main unchanged ✅ pass live Live landing CLI transcript, metadata-lock race
S6: Mutate the branch or recorded head during approval checking and observe refusal ✅ pass live Live landing CLI transcript, real approval-read races
S7: Move the worker branch inside the final Git invocation and require landing to refuse without moving main ❌ fail live Final race acceptance failure
  • TMPDIR=&#34;$PWD/.test-7782-tmp&#34; bash bin/fm-test-run.sh tests/fm-merge-local.test.sh passed.
  • TMPDIR=&#34;$PWD/.test-7782-tmp&#34; bash bin/fm-test-run.sh tests/fm-dod-lib.test.sh tests/fm-task-delivery.test.sh tests/fm-fleet-ledger.test.sh tests/fm-captain-hold-lifecycle.test.sh: DoD and ledger passed; delivery and hold-lifecycle encountered diagnosed fixture-location errors.
  • TMPDIR=/tmp bash bin/fm-test-run.sh tests/fm-captain-hold-lifecycle.test.sh tests/fm-task-delivery.test.sh was interrupted with exit 130 after identifying F1; no pass claimed.
  • python3 .test-7782-tmp/live-landing.py drove real landing, readiness, approval and Git operations against disposable projects.
  • python3 .test-7782-tmp/baseline-landing.py reproduced unapproved Y landing through the base merge entrypoint.
  • git check-ref-format --branch confirmed the initial promotion-fixture path was invalid and the normal temporary-path form was valid.

🔧 Fix applied.
4 issues (3 errors, 1 warning) still open:

  • ⚠️ The Test agent did not finish within its invocation budget. Reported: agent run tests timed out after 30m0s: agent last produced output 1s ago (101 observed); agent reported: codex exited: signal: terminated:. The cut does not clear the findings reported alongside it. Re-running the same request costs another full budget, so no further attempt is made automatically. If this repository's targeted tests or evidence gathering routinely approach the default 30m0s, raise test_agent_timeout in global config. Respond with fix to spend another budget: a repair turn runs only for selected findings other than this budget cut, then validation re-runs. Or abort and retry after raising the budget.
  • 🚨 Approval is refused: the run worktree at ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7 holds work no Test turn validated, and the steps after Test would commit and publish it. It holds commits 1c773b7..a6728a4, recorded locally as the run head and not pushed (inspect with git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7 log -p 1c773b7384ab75dbc54dc2a86f11e72dd0728bf7..a6728a4cde587d506e248b3f37884daca0409111); uncommitted changes to tests/fm-captain-hold-lifecycle.test.sh (inspect with git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7 status and git -C ~/.no-mistakes-upstream-codex/worktrees/4a2a74270675/01M615GR82CTFFPXAXTV2V7AC7 diff). Respond with fix to validate it, or abort.
  • 🚨 bin/fm-merge-local.sh:168 - F1: A branch move after the final comparison does not refuse landing. The live probe advanced the worker branch to Y immediately before real Git executed the merge. Landing exited 0 and advanced main to X. This preserves the approved commit but violates the authoritative closure requirement that branch-move races refuse without moving main. The focused fixture accepts successful landing of X in this case, following the weaker verification plan.
  • 🚨 live validation verdict: no-go (7 of 7 scenarios were driven live against the product); failed: S7: Move the worker branch inside the final Git invocation and require landing to refuse without moving main
  • Live validation: ❌ no-go - 7 of 7 scenarios driven live against the product
Scenario Result Live Evidence
S1: Approve X, advance the worker branch to Y, observe refusal, then restore X and land exactly X ✅ pass live Live landing CLI transcript, first scenario
S2: Attempt landing while approval remains held and observe refusal with main unchanged ✅ pass live Live landing CLI transcript, held-task refusals and release outputs
S3: Supply missing, empty, abbreviated, expression, nonhex, nonexistent or duplicate head records and observe refusal ✅ pass live Live landing CLI transcript, invalid durable identities
S4: Submit captured metadata from an earlier task generation and observe readiness rejection without metadata changes ✅ pass live Live landing CLI transcript, stale task generation
S5: Change the recorded head while landing waits for its metadata lock and observe refusal with main unchanged ✅ pass live Live landing CLI transcript, metadata-lock race
S6: Mutate the branch or recorded head during approval checking and observe refusal ✅ pass live Live landing CLI transcript, real approval-read races
S7: Move the worker branch inside the final Git invocation and require landing to refuse without moving main ❌ fail live Final race acceptance failure
  • TMPDIR=&#34;$PWD/.test-7782-tmp&#34; bash bin/fm-test-run.sh tests/fm-merge-local.test.sh passed.
  • TMPDIR=&#34;$PWD/.test-7782-tmp&#34; bash bin/fm-test-run.sh tests/fm-dod-lib.test.sh tests/fm-task-delivery.test.sh tests/fm-fleet-ledger.test.sh tests/fm-captain-hold-lifecycle.test.sh: DoD and ledger passed; delivery and hold-lifecycle encountered diagnosed fixture-location errors.
  • TMPDIR=/tmp bash bin/fm-test-run.sh tests/fm-captain-hold-lifecycle.test.sh tests/fm-task-delivery.test.sh was interrupted with exit 130 after identifying F1; no pass claimed.
  • python3 .test-7782-tmp/live-landing.py drove real landing, readiness, approval and Git operations against disposable projects.
  • python3 .test-7782-tmp/baseline-landing.py reproduced unapproved Y landing through the base merge entrypoint.
  • git check-ref-format --branch confirmed the initial promotion-fixture path was invalid and the normal temporary-path form was valid.

🔧 No changes applied.
✅ Re-checked - no issues remain.

  • Live validation: ✅ go - 11 of 11 scenarios driven live against the product
Scenario Result Live Evidence
S1: Record and approve X, advance to Y and receive refusal, then restore X and land exactly X ✅ pass live Live landing transcript, S1
S2: Missing, empty, abbreviated, symbolic, duplicate and nonhex approval heads refuse with main unchanged ✅ pass live Live landing transcript, S2
S3: Pending approval prevents landing without changing main ✅ pass live Live landing transcript, S3
S4: Change the branch or approval record during the approval read and receive refusal ✅ pass live Live landing transcript, S4
S5: Move the worker branch inside the final Git invocation and receive refusal with main and its checkout unchanged ✅ pass live Live landing transcript, S5
S6: Stale captured readiness cannot approve a replacement task generation ✅ pass live Live landing transcript, S6
S7: Diverged main refuses landing without changing its checkout ✅ pass live Live landing transcript, S7
S8: Replace the approved head while landing waits for its lock and receive refusal ✅ pass live Live lock-race transcript, S8
S9: Replace the task generation while landing waits for its lock and receive refusal ✅ pass live Live lock-race transcript, S9
S10: Forced cleanup during validated landing refuses, then exactly approved X lands cleanly ✅ pass live Live cleanup-race transcript, S10
B1: Baseline reproduces the defect by landing unapproved Y after approval at X ✅ pass live Live landing transcript, B1
  • TMPDIR=/tmp bin/fm-test-run.sh --jobs 1 --json /tmp/fm-7782-focused-retry.json tests/fm-merge-local.test.sh tests/fm-dod-lib.test.sh tests/fm-task-delivery.test.sh tests/fm-fleet-ledger.test.sh tests/fm-captain-hold-lifecycle.test.sh exited 0.
  • TMPDIR=/tmp python3 &lt;evidence&gt;/live-landing-retry.py exercised S1–S7 and reproduced the baseline defect.
  • TMPDIR=/tmp python3 &lt;evidence&gt;/live-lock-races-retry.py exercised S8–S9.
  • TMPDIR=/tmp python3 &lt;evidence&gt;/live-teardown-race-retry.py exercised S10.
  • Verified candidate identity, preserved lifecycle diff, removal of new disposable projects, and preservation of prior scratch records.
⚠️ **Document** - 1 warning
  • ⚠️ bin/fm-merge-local.sh:145 - The divergence diagnostic still says to rebase and retry, but rebasing changes the pinned head and requires a new task/approval record. Documentation now explains this. Changing executable output exceeds this documentation-only phase.
✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

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 kunchenguid#7782
@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; no new actionable issues remain.

Reviews (3) · Last reviewed commit: "no-mistakes(ci): Fixed both SC2031 false..." · Reviewed by Greptile

Comment thread bin/fm-dod-lib.sh Resolved
Comment thread bin/fm-merge-local.sh Resolved
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thank you @WTF-Am-ID. This is a real gap (#7782), and pinning the landing to the commit that was reported and approved is the right shape. The live scenario table, including the baseline that reproduces the bug, made this easy to check.

What I checked (head e1ca516e, main 417cec2f): fm_dod_accept_ship_done now latches local_done_head= (one full hex id) into the live meta the first time a local-only done is accepted. fm-merge-local.sh refuses a missing or malformed head, or a branch that has moved off it, and re-checks after the captain-hold read. It then lands that exact commit through a two-tree checkout plus a verify/update ref transaction, with rollback if the transaction fails. A legacy task with no recorded head refuses with "report readiness before approval". That fails closed, which is right. No workflow, network or credential changes.

Before this can merge, please look at Greptile's two P1s. Both match my reading of the code:

  1. Done reports blocked under the reconcile lock. report_child_ledger_locked in bin/fm-inactive-reconcile.sh calls fm_dod_accept_ship_done while it already holds the child's meta lock. The new fm_dod_pin_local_done_head subshell then try-acquires that same lock (and the control lock), fails, and the gate returns non-zero. So a local-only child's done is skipped on that path, even when the head is already pinned, and every retry hits the same wall. A lock-aware path for callers that already hold the lock (or pinning outside the locked section) plus a regression test through the reconcile path would close it.
  2. Rollback across two landings into one project. The control and meta locks are per task, but two tasks can land into the same project checkout. If both stage the same tree, the second call's failed ref update rolls the checkout back to its own before while the default branch has already advanced, which leaves the worktree reverted against the new tip. A project-level checkout lock held across the clean check, the checkout, the ref transaction and the rollback would cover it.

CI run 40697859154 is still queued behind today's Actions backlog, and the no-mistakes check passes on this head. After the fixes, a git push no-mistakes re-raise will bind the attestation to the new head and give us fresh CI.

contract-class: restore. The captain's merge word on a local-only task already covered the head that was reported, and the PR path already pins its head with --match-head-commit. This makes the local path keep that same promise. VISION: aligns rule by rule. One captain: no surprise landings. Authority: the approval binds to exactly what was approved. Scripts/agents: an exact sha compare in scripts. Restart: the head lives in durable meta. Delegation: workers are supervised, not trusted. Vendor: plain git. Scope: stays in the landing gate.

This is waiting on you for the two fixes above plus a re-raise. Thanks again!

…erved 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
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thanks @WTF-Am-ID. Both earlier P1s are fixed on the new head.

Re-checked (head 56f7c1f2, main b04154bd):

  1. Reconcile lock: report_child_ledger_locked now passes meta-locked, so fm_dod_pin_local_done_head reuses the caller's lock and doesn't try to take it a second time. The new inactive-reconcile regression covers that path.
  2. Two landings into one checkout: fm-merge-local.sh now takes a per-checkout fm-local-landing.lock in the project's Git directory. It holds that lock across the clean check, staging, the ref transaction and rollback.

One thing left: the Lint 1 job fails on this head. I reproduced it locally with the pinned ShellCheck 0.11.0. bin/fm-lint.sh tests/fm-merge-local.test.sh exits 1 on SC2031 at tests/fm-merge-local.test.sh:272 (first_pid=$!) and :279 (second_pid=$!). Capturing the PIDs outside the subshell, or adding a narrow # shellcheck disable=SC2031 with a reason, should clear it. Optional, not blocking: the divergence refusal still says "Have the crewmate rebase", but a rebase moves the pinned head and needs a new approval, as your docs now say. It might be worth making the message say so too.

contract-class: restore, unchanged. The captain's approval already covered the head that was reported. VISION: aligns, as in my earlier note. The new checkout lock keeps landing inside the existing landing gate.

This one is waiting on you for the lint fix plus a git push no-mistakes re-raise, so the attestation and fresh CI bind the new head. Thank you!

…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
@kunchenguid
kunchenguid merged commit 9905462 into kunchenguid:main Oct 28, 2026
21 checks passed
@kunchenguid

Copy link
Copy Markdown
Owner

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

@Authentis

Copy link
Copy Markdown
Contributor

Possible self-wait in the reconcile path. I read this in the diff but did not run it.

  • bin/fm-inactive-reconcile.sh: reconcile_direct_child takes the task meta lock (via fm_meta_lock_path) and then calls reconcile_direct_child_locked, which runs fm-crew-state.sh as a separate process.
  • bin/fm-crew-state.sh (~line 263): it calls fm_dod_accept_ship_done "$KIND" "$mode" "$WT" "$project" "$LOG_LINE" "$STATE" "$ID" "$META" without the meta-locked argument.
  • bin/fm-dod-lib.sh (~line 784): fm_dod_pin_local_done_head takes the meta lock unless its 6th argument is meta-locked.

If that chain is reached for a local-only done head while the reconcile caller still holds the lock, the child process would wait on a lock its parent holds. Only the report_child_ledger_locked path passes meta-locked. Worth checking whether the crew-state call can be reached from the locked reconcile path.

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: 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 kunchenguid#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
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-merge-local fast-forwards to the current branch tip, not to the head that was reported and approved

3 participants