Skip to content

fix: preserve late worker changes during teardown - #7932

Merged
kunchenguid merged 9 commits into
kunchenguid:mainfrom
WTF-Am-ID:fm/up-fm-7783
Nov 3, 2026
Merged

kunchenguid merged 9 commits into
kunchenguid:mainfrom
WTF-Am-ID:fm/up-fm-7783

Conversation

@WTF-Am-ID

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

Copy link
Copy Markdown
Contributor

Intent

WHen one issue is completed closed or submitted open another one. Im going away now, same marching orders. (Earlier: Land it all keep communication to a minimum to preserve opus tokens you have your marching orders. (Campaign: next batch of upstream scan 4 picks, Codex only, no cross-model review.)

Context: this task is upstream scan 4 pick P3: upstream issue #7783 in kunchenguid/firstmate. The owner approved fixing upstream scan picks upstream through PRs, written and reviewed by Codex only, with no cross-model review. Scan notes for this pick:

Issue: #7783

Maintainer triage stamps restore.
Current bin/fm-teardown.sh:3688-3699 proves safety before :3804 reaps task processes.
Branch deletion and return follow at :3840-3893.
The later callback is only supplied for the stale-lock return path.
The issue's live trigger is explicitly plausible rather than field-reproduced.

Competing work: no exact target in the full open index.
The inspected diff of #7566 changes which processes may be reaped and whether spared processes retain the tree.
It does not add the post-reap landed-work proof.
The already-excluded whitespace and hidden-untracked-file contributions strengthen different predicates.

Closure test: use scratch Git repositories and fake endpoint/reaper/pool boundaries.
Make the fake reap boundary introduce a tracked edit, untracked file or unlanded commit after the first proof.
Ordinary teardown must refuse before branch deletion or pool return and retain the work and retry records.
A clean final tree must still complete.
Cover the ordinary and Orca branches that share this ordering, without administering a real backend.
Test forced/scout behavior separately so the correction cannot widen their authority.
Use the canonical teardown suites and runner.
A deterministic boundary fixture establishes the red case before implementing the correction.

bring in current upstream main by merge, then re-raise.

ACCEPT comment-only commit 651c0b8 (six comment lines in bin/fm-teardown.sh) as part of the #7932 re-raise, and publish.

AUTHORIZED to resolve the conflict. Keep upstream's new behaviour (exact-pane close moved ahead of reaping) AND preserve this PR's intent (preserve late worker changes during teardown: re-check landed/discard-work safety after workers stop). Make the smallest resolution that keeps both; no unrelated edits, no refactor. Fixes the pipeline itself makes to the conflict resolution are allowed; stop and report if a step would expand scope beyond this PR's teardown change. If upstream main advances again, do not merge again; report it.

What Changed

  • Recheck landed-work safety after process reaping, before deleting branches or returning worktrees, to preserve late worker edits, files, and commits.
  • Delay legacy stamping and backlog-close marker publication until the final safety check passes, retaining retry records on refusal.
  • Add ordinary and Orca teardown regression cases for late writes, reaper failures, and clean/force/scout behavior, and update cleanup-order documentation.

Risk Assessment

✅ Low: The merge resolution only relocates the existing backlog-close/legacy-stamp block verbatim to after upstream's Herdr exact-pane close and the process reap, inserts one non-forced, scout/secondmate-exempt validate_worktree_teardown_safety re-check before pending-close publication, branch deletion and pool return, and adds a behavioral boundary test; every early exit on the new path is exit 1 under set -eu and records stay retained.

Testing

Both focused suites passed, the synthetic regression reproduced failures on the baseline, and three corrected real CLI flows passed with transcripts retained. Termination races and Herdr ordering remain synthetic-only. Live labs were removed, tracked files are unchanged, and command-policy refusal left 22 MB of scratch data at .tools/phase-validation.

  • Live validation: ⚠️ inconclusive - 3 of 8 scenarios driven live against the product
Scenario Result Live Evidence
Clean ordinary task cleanup stops its endpoint, returns its pool slot, removes its branch and retry records, and completes its backlog item ✅ pass live Real CLI cleanup transcripts: SCENARIO clean
Explicit forced cleanup discards disposable edits and a nested repository, stops its endpoint, and returns a clean pool slot ✅ pass live Real CLI cleanup transcripts: SCENARIO force
Scout cleanup with a completed report discards scratch work and completes with its report link ✅ pass live Real CLI cleanup transcripts: SCENARIO scout
Tracked edits written during worker termination retain work, branch, and retry records on ordinary and Orca paths ⏸️ untested no The fake-reaper fixture passed on the candidate and failed on the baseline. The previously recorded PreToolUse refusal blocks the independent terminating-worker probe, and standing instructions prohib…
An untracked file written during worker termination survives cleanup refusal on ordinary and Orca paths ⏸️ untested no Both paths passed with synthetic reaper boundaries and failed on the baseline. A real termination-timed write remains blocked by the previously recorded PreToolUse refusal. A hook-approved isolated te…
An unlanded commit created during worker termination retains its branch and task on ordinary and Orca paths ⏸️ untested no Real scratch Git repositories passed the synthetic boundary case on the candidate and failed on the baseline. Live worker termination was not driven because the recorded probe refusal remains binding.…
A failed reap cannot publish a close that replay uses to retire the retained task ⏸️ untested no Synthetic reap failure and replay passed on the candidate. The baseline lost metadata and completed the backlog item. No real failed-reap lifecycle was driven because the independent termination probe…
Herdr closes the exact pane before reaping and preserves the task copy when closing is refused ⏸️ untested no Canonical synthetic close/refusal checks passed. Named-helper prepare and teardown checks succeeded without provisioning a session. Real backend administration remains outside the supplied closure sco…
Evidence: Real CLI cleanup transcripts

Source: Real CLI cleanup transcripts

~/.no-mistakes-upstream-codex/worktrees/809f8997b687/01M6FXHRYH31ZKSRYWYT26KKH6/.tools/phase-validation/fm-lab.rVjfVz
A new version of treehouse is available: v3.1.7 → v3.1.8
Run "treehouse update" to update

🌳 Setting up worktree...
🌳 Leased worktree at ~/.no-mistakes-upstream-codex/worktrees/809f8997b687/01M6FXHRYH31ZKSRYWYT26KKH6/.tools/phase-validation/fm-lab.rVjfVz/pool/.treehouse/demo-3dc5d9/1/demo. Run 'treehouse return ~/.no-mistakes-upstream-codex/worktrees/809f8997b687/01M6FXHRYH31ZKSRYWYT26KKH6/.tools/phase-validation/fm-lab.rVjfVz/pool/.treehouse/demo-3dc5d9/1/demo' to release it.

SCENARIO clean
Before cleanup:
A new version of treehouse is available: v3.1.7 → v3.1.8
Run "treehouse update" to update

base  main  (repository default)
1     leased       ~/.no-mistakes-upstream-codex/worktrees/809f8997b687/01M6FXHRYH31ZKSRYWYT26KKH6/.tools/phase-validation/fm-lab.rVjfVz/pool/.treehouse/demo-3dc5d9/1/demo  [fm/live-clean]
fm-gate-refuse: gate agent lifecycle permitted only against lab home ~/.no-mistakes-upstream-codex/worktrees/809f8997b687/01M6FXHRYH31ZKSRYWYT26KKH6/.tools/phase-validation/fm-lab.rVjfVz
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
●  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.
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
A new version of treehouse is available: v3.1.7 → v3.1.8
Run "treehouse update" to update

🌳 Worktree returned to pool.
teardown live-clean complete (window primary:fm-live-clean, worktree ~/.no-mistakes-upstream-codex/worktrees/809f8997b687/01M6FXHRYH31ZKSRYWYT26KKH6/.tools/phase-validation/fm-lab.rVjfVz/pool/.treehouse/demo-3dc5d9/1/demo)
Backlog: live-clean is closed in ~/.no-mistakes-upstream-codex/worktrees/809f8997b687/01M6FXHRYH31ZKSRYWYT26KKH6/.tools/phase-validation/fm-lab.rVjfVz/data/backlog.md. Run bin/fm-tasks-axi.sh ready for dependency-cleared candidates, check date gates, and dispatch only work whose blockers are gone and date is due.
cleanup_exit=0
VERIFIED: real task endpoint stopped on private fm-lab socket
After cleanup:
task:
  id: live-clean
  title: Live clean cleanup
  state: done
  blocked: no
  blocked_by: none
  held: no
  hold_reason: "-"
  hold_kind: "-"
  hold_until: "-"
  kind: ship
  repo: "-"
  priority: "-"
  created: "-"
  closed: 2026-11-03
  deps: none
  links: none
  body: local main
A new version of treehouse is available: v3.1.7 → v3.1.8
Run "treehouse update" to update

base  main  (repository default)
1     available    ~/.no-mistakes-upstream-codex/worktrees/809f8997b687/01M6FXHRYH31ZKSRYWYT26KKH6/.tools/phase-validation/fm-lab.rVjfVz/pool/.treehouse/demo-3dc5d9/1/demo  (detached)
VERIFIED: clean copy, removed branch and retry records, completed backlog transition
A new version of treehouse is available: v3.1.7 → v3.1.8
Run "treehouse update" to update

🌳 Setting up worktree...
🌳 Leased worktree at ~/.no-mistakes-upstream-codex/worktrees/809f8997b687/01M6FXHRYH31ZKSRYWYT26KKH6/.tools/phase-validation/fm-lab.rVjfVz/pool/.treehouse/demo-3dc5d9/1/demo. Run 'treehouse return ~/.no-mistakes-upstream-codex/worktrees/809f8997b687/01M6FXHRYH31ZKSRYWYT26KKH6/.tools/phase-validation/fm-lab.rVjfVz/pool/.treehouse/demo-3dc5d9/1/demo' to release it.

SCENARIO force
Before cleanup:
 M worker.txt
?? nested/
A new version of treehouse is available: v3.1.7 → v3.1.8
Run "treehouse update" to update

base  main  (repository default)
1     leased       ~/.no-mistakes-upstream-codex/worktrees/809f8997b687/01M6FXHRYH31ZKSRYWYT26KKH6/.tools/phase-validation/fm-lab.rVjfVz/pool/.treehouse/demo-3dc5d9/1/demo  [fm/live-force]
fm-gate-refuse: gate agent lifecycle permitted only against lab home ~/.no-mistakes-upstream-codex/worktrees/809f8997b687/01M6FXHRYH31ZKSRYWYT26KKH6/.tools/phase-validation/fm-lab.rVjfVz
WARNING: watcher still down (same stale episode; last beat: never, grace 300s) - full banner already printed this episode.
A new version of treehouse is available: v3.1.7 → v3.1.8
Run "treehouse update" to update

🌳 Worktree returned to pool.
teardown live-force complete (window primary:fm-live-force, worktree ~/.no-mistakes-upstream-codex/worktrees/809f8997b687/01M6FXHRYH31ZKSRYWYT26KKH6/.tools/phase-validation/fm-lab.rVjfVz/pool/.treehouse/demo-3dc5d9/1/demo)
Backlog: live-force is closed in ~/.no-mistakes-upstream-codex/worktrees/809f8997b687/01M6FXHRYH31ZKSRYWYT26KKH6/.tools/phase-validation/fm-lab.rVjfVz/data/backlog.md. Run bin/fm-tasks-axi.sh ready for dependency-cleared candidates, check date gates, and dispatch only work whose blockers are gone and date is due.
cleanup_exit=0
VERIFIED: real task endpoint stopped on private fm-lab socket
After cleanup:
task:
  id: live-force
  title: Live force cleanup
  state: done
  blocked: no
  blocked_by: none
  held: no
  hold_reason: "-"
  hold_kind: "-"
  hold_until: "-"
  kind: ship
  repo: "-"
  priority: "-"
  created: "-"
  closed: 2026-11-03
  deps: none
  links: none
  body: local main
A new version of treehouse is available: v3.1.7 → v3.1.8
Run "treehouse update" to update

base  main  (repository default)
1     available    ~/.no-mistakes-upstream-codex/worktrees/809f8997b687/01M6FXHRYH31ZKSRYWYT26KKH6/.tools/phase-validation/fm-lab.rVjfVz/pool/.treehouse/demo-3dc5d9/1/demo  (detached)
VERIFIED: clean copy, removed branch and retry records, completed backlog transition
A new version of treehouse is available: v3.1.7 → v3.1.8
Run "treehouse update" to update

🌳 Setting up worktree...
🌳 Leased worktree at ~/.no-mistakes-upstream-codex/worktrees/809f8997b687/01M6FXHRYH31ZKSRYWYT26KKH6/.tools/phase-validation/fm-lab.rVjfVz/pool/.treehouse/demo-3dc5d9/1/demo. Run 'treehouse return ~/.no-mistakes-upstream-codex/worktrees/809f8997b687/01M6FXHRYH31ZKSRYWYT26KKH6/.tools/phase-validation/fm-lab.rVjfVz/pool/.treehouse/demo-3dc5d9/1/demo' to release it.

SCENARIO scout
Before cleanup:
 M worker.txt
?? nested/
A new version of treehouse is available: v3.1.7 → v3.1.8
Run "treehouse update" to update

base  main  (repository default)
1     leased       ~/.no-mistakes-upstream-codex/worktrees/809f8997b687/01M6FXHRYH31ZKSRYWYT26KKH6/.tools/phase-validation/fm-lab.rVjfVz/pool/.treehouse/demo-3dc5d9/1/demo  [fm/live-scout]
fm-gate-refuse: gate agent lifecycle permitted only against lab home ~/.no-mistakes-upstream-codex/worktrees/809f8997b687/01M6FXHRYH31ZKSRYWYT26KKH6/.tools/phase-validation/fm-lab.rVjfVz
WARNING: watcher still down (same stale episode; last beat: never, grace 300s) - full banner already printed this episode.
A new version of treehouse is available: v3.1.7 → v3.1.8
Run "treehouse update" to update

🌳 Worktree returned to pool.
teardown live-scout complete (window primary:fm-live-scout, worktree ~/.no-mistakes-upstream-codex/worktrees/809f8997b687/01M6FXHRYH31ZKSRYWYT26KKH6/.tools/phase-validation/fm-lab.rVjfVz/pool/.treehouse/demo-3dc5d9/1/demo)
Backlog: live-scout is closed in ~/.no-mistakes-upstream-codex/worktrees/809f8997b687/01M6FXHRYH31ZKSRYWYT26KKH6/.tools/phase-validation/fm-lab.rVjfVz/data/backlog.md. Run bin/fm-tasks-axi.sh ready for dependency-cleared candidates, check date gates, and dispatch only work whose blockers are gone and date is due.
cleanup_exit=0
VERIFIED: real task endpoint stopped on private fm-lab socket
After cleanup:
task:
  id: live-scout
  title: Live scout cleanup data/live-scout/report.md
  state: done
  blocked: no
  blocked_by: none
  held: no
  hold_reason: "-"
  hold_kind: "-"
  hold_until: "-"
  kind: scout
  repo: "-"
  priority: "-"
  created: "-"
  closed: 2026-11-03
  deps: none
  links: "report:data/live-scout/report.md"
  body: ""
A new version of treehouse is available: v3.1.7 → v3.1.8
Run "treehouse update" to update

base  main  (repository default)
1     available    ~/.no-mistakes-upstream-codex/worktrees/809f8997b687/01M6FXHRYH31ZKSRYWYT26KKH6/.tools/phase-validation/fm-lab.rVjfVz/pool/.treehouse/demo-3dc5d9/1/demo  (detached)
VERIFIED: clean copy, removed branch and retry records, completed backlog transition
Evidence: Repeatable live CLI recipe

Source: Repeatable live CLI recipe

#!/usr/bin/env bash
set -euo pipefail
ROOT=$PWD
EVIDENCE=~/.no-mistakes-upstream-codex/evidence/01M6FXHRYH31ZKSRYWYT26KKH6
. "$ROOT/tests/git-config-helpers.sh"
LAB=$(mktemp -d "$ROOT/.tools/phase-validation/fm-lab.XXXXXX")
SOCKET_DIR=
cleanup() {
  if [ -n "$SOCKET_DIR" ]; then
    TMUX_TMPDIR="$SOCKET_DIR" tmux -L fm-lab kill-server 2>/dev/null || true
    "$ROOT/bin/fm-lab-home.sh" teardown "$LAB"
  fi
  rm -rf -- "$LAB"
}
trap cleanup EXIT
"$ROOT/bin/fm-lab-home.sh" create "$LAB"
SOCKET_DIR=$("$ROOT/bin/fm-lab-home.sh" tmux-dir "$LAB")
export TMUX_TMPDIR="$SOCKET_DIR"
unset FM_ROOT_OVERRIDE FM_STATE_OVERRIDE FM_DATA_OVERRIDE FM_CONFIG_OVERRIDE FM_PROJECTS_OVERRIDE FM_GATE_REFUSE_BYPASS
export FM_HOME="$LAB"
printf 'tmux\n' > "$LAB/config/backend"
export GIT_AUTHOR_NAME=LiveTest [email protected] GIT_COMMITTER_NAME=LiveTest [email protected]
mkdir -p "$LAB/projects/demo"
PROJ="$LAB/projects/demo"
git -C "$PROJ" init -q -b main
printf 'baseline\n' > "$PROJ/worker.txt"
git -C "$PROJ" add worker.txt
git -C "$PROJ" commit -qm baseline
printf '# Backlog\n\n## In flight\n\n## Queued\n\n## Done\n' > "$LAB/data/backlog.md"
for scenario in clean force scout; do
  ID="live-$scenario"
  WT=$(cd "$PROJ" && treehouse --root "$LAB/pool" get --lease --no-fetch --base main -b "fm/$ID")
  kind=ship
  [ "$scenario" != scout ] || kind=scout
  tasks-axi add "$ID" "Live $scenario cleanup" --kind "$kind" --file "$LAB/data/backlog.md" >/dev/null
  tasks-axi start "$ID" --file "$LAB/data/backlog.md" >/dev/null
  mkdir -p "$LAB/data/$ID" "$LAB/state/$ID.inbox"
  printf 'report\n' > "$LAB/data/$ID/report.md"
  printf 'done: live case\n' > "$LAB/state/$ID.status"
  printf 'retained steer\n' > "$LAB/state/$ID.inbox/001.msg"
  cat > "$LAB/state/$ID.meta" <<META
window=primary:fm-$ID
endpoint_task_id=$ID
worktree=$WT
project=$PROJ
kind=$kind
mode=local-only
backend=tmux
harness=codex
spawn_gen=live-$scenario-generation
decisions_reviewed=1
decision_keys=
META
  if [ "$scenario" != clean ]; then
    printf 'disposable scratch edit\n' > "$WT/worker.txt"
    mkdir -p "$WT/nested"
    git -C "$WT/nested" init -q
    printf 'disposable nested content\n' > "$WT/nested/scratch.txt"
  fi
  env -u NO_MISTAKES_GATE -u FM_GATE_REFUSE_BYPASS -u FM_ROOT_OVERRIDE -u FM_STATE_OVERRIDE -u FM_DATA_OVERRIDE -u FM_CONFIG_OVERRIDE -u FM_PROJECTS_OVERRIDE \
    TMUX_TMPDIR="$SOCKET_DIR" tmux -L fm-lab new-session -d -s primary -n "fm-$ID" -x 120 -y 40 -c "$ROOT" -e FM_HOME="$LAB" codex
  tmux -L fm-lab set-window-option -t "primary:fm-$ID" automatic-rename off
  tmux -L fm-lab set-window-option -t "primary:fm-$ID" allow-rename off
  TMUX=$(tmux -L fm-lab display-message -p -t primary '#{socket_path},#{pid},#{session_id}' | sed 's/,\$/,/')
  export TMUX
  tmux -L fm-lab has-session -t primary
  for i in $(seq 1 20); do
    tmux -L fm-lab capture-pane -p -t primary > "$EVIDENCE/$scenario-codex-pane.txt"
    if rg -q 'OpenAI Codex|Do you trust|codex|Hooks need review' "$EVIDENCE/$scenario-codex-pane.txt"; then break; fi
    sleep 1
  done
  printf '\nSCENARIO %s\n' "$scenario"
  printf 'Before cleanup:\n'
  git -C "$WT" status --short --untracked-files=all
  treehouse --root "$LAB/pool" status -C "$PROJ" 2>/dev/null || (cd "$PROJ" && treehouse --root "$LAB/pool" status)
  rc=0
  if [ "$scenario" = force ]; then
    "$ROOT/bin/fm-teardown.sh" "$ID" --force || rc=$?
  else
    "$ROOT/bin/fm-teardown.sh" "$ID" || rc=$?
  fi
  printf 'cleanup_exit=%s\n' "$rc"
  if tmux -L fm-lab has-session -t primary 2>/dev/null; then
    printf 'ERROR: exact task endpoint survived cleanup\n'
    exit 1
  fi
  printf 'VERIFIED: real task endpoint stopped on private fm-lab socket\n'
  [ "$rc" = 0 ]
  printf 'After cleanup:\n'
  [ ! -e "$LAB/state/$ID.meta" ]
  [ ! -e "$LAB/state/$ID.inbox" ]
  [ ! -e "$LAB/state/$ID.backlog-close" ]
  [ -z "$(git -C "$WT" status --porcelain --untracked-files=all)" ]
  ! git -C "$PROJ" show-ref --verify --quiet "refs/heads/fm/$ID"
  tasks-axi show "$ID" --file "$LAB/data/backlog.md"
  (cd "$PROJ" && treehouse --root "$LAB/pool" status)
  printf 'VERIFIED: clean copy, removed branch and retry records, completed backlog transition\n'
  tmux -L fm-lab kill-server 2>/dev/null || true
  unset TMUX
 done
Evidence: Focused candidate validation

Source: Focused candidate validation

FM_TEST_BEGIN 2026-11-03T05:21:00Z tests/fm-teardown.test.sh family=pr-forge expected_gate_skip=none
ok - teardown leaves opencode's busy plugin in the returned pool worktree as on main
ok - hidden untracked work is refused before return while a clean control returns
ok - content fallback distinguishes unavailable Git proof, containment, conflicts, and unlanded content
orca/reap-refusal: teardown_exit=1 replay_exit=0 metadata_after_replay=retained backlog_after_replay=in_flight
tmux/reap-refusal: teardown_exit=1 replay_exit=0 metadata_after_replay=retained backlog_after_replay=in_flight
ok - post-reap proof retains late work and retry records on ordinary and Orca paths, preserving clean/force/scout behavior
ok - status archival is opt-in and preserves the complete log
ok - config-absent teardown does not read or invoke record export
ok - unopted teardown ignores symlinked config when record export is absent
ok - teardown commits the record archive before deleting sources and fails closed when export cannot commit
ok - forced secondmate teardown exports task records from the child sub-state
ok - record export waits for endpoint quiescence and retry captures records changed after refusal
ok - forced secondmate retirement preserves two descendant levels and refuses linked child directories
ok - local missing-status retirement stays lock-free without creating an archive
ok - reused task IDs never overwrite archives and retention removes only old owned logs
ok - archive sources and directories reject symlinks; pruning never follows children links
ok - failed archive publication preserves presentation and watcher bookkeeping
ok - cursor retirement failure removes its archive so retry publishes one history
ok - archive publication and cold logs never re-wake or re-present
ok - retention failures warn without aborting unrelated teardown
ok - a missing teardown startup source refuses before cleanup
ok - an unreadable teardown startup source refuses before cleanup
ok - a missing adapter sibling refuses before cleanup
ok - a forced descendant with a missing adapter sibling refuses before cleanup
ok - a forced secondmate with a missing own adapter sibling refuses before child cleanup
ok - present required sources still reach the ordinary teardown refusal
ok - local-only worktree with HEAD on a fork remote is torn down and the home summary is refreshed
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
●  WATCHER DOWN - SUPERVISION IS OFF
●  1 task(s) in flight, but no live watcher process holds this home lock (last beat: 1s ago).
●  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 according to the session-start block for this harness; do not use shell &.
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ok - teardown closes its own backlog item before reporting success
ok - teardown closes a landed Gerrit task with its change URL as a note and a GitHub task with --pr
ok - teardown closes a landed GitLab task with its merge request URL as a note and GitHub and Forgejo tasks with --pr
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
●  WATCHER DOWN - SUPERVISION IS OFF
●  1 task(s) in flight, but no live watcher process holds this home lock (last beat: 1s ago).
●  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 according to the session-start block for this harness; do not use shell &.
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ok - teardown honors config/backlog-backend=manual and still finishes cleanly
ok - local-only worktree with truly unpushed work is refused (safety preserved)
ok - local-only worktree with work merged into local main is torn down (no regression)
ok - no-mistakes worktree with HEAD on origin is torn down (no regression)
ok - no-mistakes worktree with genuinely unlanded work is refused (safety preserved)
ok - local-only worktree with unpushed work is torn down under --force (escape hatch)
ok - fm-pr-check publishes the PR-ready line on a secondmate's parent channel once
ok - fm-pr-check withholds the PR-ready line until checks are green when config/ready-after-green is present
ok - fm-pr-check releases the PR-ready line on a checks-green report that carries surrounding text
ok - a secondmate home's teardown delivers the child's final line or refuses until it can
ok - teardown completes when an exact busy-state sidecar is already absent
ok - teardown retires a polytoken task's generated worktree wiring on pool return
ok - teardown never deletes a tracked .polytoken hook layer
ok - teardown never deletes a .polytoken hook layer firstmate did not generate
ok - teardown scopes .polytoken wiring removal to polytoken tasks
ok - herdr teardown removes pane-owned escalation dedupe state
ok - herdr flat teardown refuses before returning the isolated copy under lock contention and the retry completes cleanly
ok - herdr flat teardown never erases records when pane presence is unparseable
ok - herdr flat teardown preflight refuses before every destructive change
ok - herdr teardown refuses a foreign-owned per-account namespace (owner-shim arms need the non-Darwin stat branch; skipped on Darwin)
ok - forced secondmate teardown preflights every Herdr child before cleanup mutation
ok - forced secondmate teardown holds every descendant lifecycle and metadata lock
ok - forced secondmate teardown retains Herdr child identity until exact pane disappearance
ok - forced teardown retains a nested secondmate home and its grandchild's Herdr identity when the grandchild close is unconfirmed
ok - herdr projection teardown retires its journal only after confirming the exact recorded pane is gone
ok - herdr projection teardown retains every record when post-close presence is unknown
ok - herdr projection teardown surfaces failed focus restoration without turning confirmed cleanup into a hard failure
ok - herdr projection teardown closes its exact pane, restoring focus, before returning the copy that holds its shell
ok - herdr projection teardown retains the task, pane shell, and leased copy after a refused close
ok - teardown retires the task's own watcher markers and orphaned presentation journal, leaving other tasks' markers alone
ok - teardown retains a presentation journal bound to a pane other than the closed endpoint
ok - teardown retires a v1 presentation journal once its token workspace is confirmed gone
ok - teardown retains a v1 presentation journal while its token workspace is still present
ok - teardown retains a v1 presentation journal when the workspace query is ambiguous
ok - squash-merged + deleted-branch worktree (PR merged) is torn down (the fix)
ok - squash-merged PR accepts a local HEAD that is an ancestor of the final PR head
ok - teardown discovers a merged PR by branch name and tears down when no pr= was ever recorded
ok - squash-merged PR accepts replayed unpushed local patches contained in the PR head
ok - merged PR patch matching preserves indentation, allows exact replays, and refuses unsupported Git
ok - merged PR does not allow teardown after a later local commit
ok - squash-merged task whose local branch followed the pipeline rebase is torn down
ok - teardown proves a Forgejo task landed from the merged pull request when the con

... [7447 bytes truncated] ...

point tears down and logs its accepted incarnation
ok - --legacy-record never relaxes the unlanded-work refusal
ok - an endpoint that cannot be confidently read as dead refuses --legacy-record teardown
ok - --legacy-record teardown rolls its stamp back when the close marker write fails
ok - a legacy stamp a failed rollback left behind still faces the endpoint gate
ok - a corrupt spawn_gen is never accepted as a legacy record
ok - provably-stale worktree index.lock (old, no live holder) is cleared and teardown succeeds
ok - live-held worktree index.lock is never removed and teardown refuses
ok - lsof errors leave worktree index.lock in place and refuse teardown
ok - stale lock cleanup rechecks and refuses dirty worktree before return
ok - normal repo index.lock is resolved from the worktree and cleared when stale
ok - index-lock mtime fault injection is PATH-based; skipped on Darwin where stat is /usr/bin/stat
ok - transient index.lock cleared after first failed return is retried successfully without force-remove
ok - persistent index.lock exhausts retries and refuses without force-removing the lock
ok - empty retry wait overrides use the default without aborting teardown
ok - fractional legacy retry wait remains supported without arithmetic
ok - teardown records the task's pipeline spend before removing its branch and record
ok - teardown skips all pipeline-spend recording when the home has not opted in
ok - teardown records unavailable pipeline spend for an owned ship task whose copy is gone
ok - a task's own parked no-mistakes run is aborted, not orphaned, before the worker is removed
ok - a parked run in a resolved workspace no-mistakes home is aborted before the worker is removed
ok - a run that lands on passed-with-override after abort is still recognized as terminal
ok - a run that lands on passed-with-skips after abort is still recognized as terminal
ok - a parked run the pipeline advanced past the task copy is still concluded from the runs ledger, not orphaned
ok - a ledger row for a different head never authorizes a parked-run abort
ok - a malformed ledger row never authorizes a parked-run abort
ok - an impossible ledger date never authorizes a parked-run abort
ok - a terminal status with a stale gate never reaches ledger cleanup
ok - an advanced head present locally aborts through the strict rule alone - the ledger fallback stays dormant
ok - an unresolvable active row with no same-branch anchor is never concluded (conservative refusal)
ok - an ancestor-only anchor never binds an advanced parked run to this task
ok - a terminal unfetched-head row is stale history and never concludes a run
ok - a terminal newest row anchored at this worktree's head never authorizes an abort
ok - a resolvable diverged newer same-branch row makes every older row stale history; no run is concluded
ok - consecutive unresolvable rows are ambiguous and never conclude a run
ok - a ledger-proven continuation is still left alone while the run is autonomously active
ok - teardown refuses before reap or removal when a task-owned run remains parked
ok - a different run cannot confirm the targeted abort
ok - empty post-abort status is not accepted as confirmation
ok - the CLI's exact run-not-found signal confirms completion
ok - a parked run on another branch is never aborted by this task's teardown (ownership is precise)
ok - a task-owned autonomous running step is left alone rather than aborted
ok - a leaked descendant process rooted under the task's worktree is reaped by teardown, not left surviving
ok - a leaked descendant process rooted under the task's per-task tasktmp is reaped by teardown too
ok - missing lsof falls back to reaping the tmux pane process group
ok - an erroring lsof scan refuses teardown and preserves the task
ok - a reused pid with a different start time is never force-killed
ok - an exec change preserves birth identity and the process is reaped
ok - a process spawned during grace is reaped on a later pass
ok - persistent leaked processes refuse teardown after bounded retries
ok - a process exiting during identity lookup does not block teardown
ok - the run abort and the leaked-process reap both complete before the destructive worktree return
FM_TEST_END 2026-11-03T05:29:27Z tests/fm-teardown.test.sh exit=0 duration_ms=507240 gate_skip=false
FM_TEST_BEGIN 2026-11-03T05:29:27Z tests/fm-teardown-endpoint-safety.test.sh family=backend-dispatch expected_gate_skip=none
ok - fm-teardown: missing, empty, malformed, ambiguous, and task-mismatched endpoints refuse before every mutation or runtime call
ok - fm-teardown: an unusable worktree identity refuses as before and names a repair path that runs as printed
ok - fm-teardown: a concurrent lifecycle action refuses before mutation
ok - fm-teardown: non-pool cleanup ignores unrelated task publication locks
ok - fm-teardown: destructive cleanup serializes with metadata writers
ok - cleanup identity: valid tmux, Herdr, Zellij, Orca, cmux, Paseo, Rex, and tern records validate, inconsistent Rex records refuse, and every empty backend target refuses
ok - cleanup identity: an Orca record's real composite worktree id validates while a separatorless or newline-carrying id refuses
ok - tmux backend: direct empty target returns nonzero without invoking tmux
ok - process cleanup: creation-time PID identity removes only the exact child and preserves the control child
ok - fm-teardown: exact tmux cleanup preserves invalid and prefix-matched neighbors while removing only the recorded target
ok - fm-teardown: a close that genuinely failed refuses and keeps the record naming the surviving endpoint, and the same teardown finishes once the close works
ok - fm-teardown: --force continues past a close it could not make while still reporting it, and the same case refuses without --force
ok - fm-teardown: a close re-read that could not run refuses, while a definitively absent session or server still completes silently
ok - fm-teardown: forced secondmate cleanup still refuses on a child endpoint close that failed
ok - fm-teardown: an Orca close its missing CLI never attempted refuses even under --force, keeping the record naming the terminal
ok - fm-teardown: an already-exited endpoint, and a server that is already gone, still complete cleanup silently
ok - Treehouse locking resolves a bare local origin against its source project, matching the provisioned clone
ok - fm-teardown: a pool slot named by a second task record is never returned, killed, or reset
ok - fm-teardown: a pool slot held by another firstmate home is never returned
ok - fm-teardown: a task that solely holds its slot still returns it
ok - fm-teardown: a pool slot claimed by another task is left alone while the task's own cleanup finishes
ok - fm-teardown backend=t3code: a reassigned pool slot keeps its claimant's Codex overlay while the task's own thread is archived
ok - fm-teardown: a stale record on a claimed slot retires, then the claimant tears down
ok - fm-teardown: a task's own slot claim, and an unclaimed slot, both still tear down
ok - fm-teardown: an exact recorded endpoint still tears down after changing cwd outside its worktree
ok - Treehouse project locking anchors at the local root for main-home, local-secondmate, and remote-seeded layouts
ok - fm-teardown: a remote-seeded secondmate home returns its own uncontested pool slot
ok - fm-teardown: slot ownership across a remote-seeded home and its local child still refuses
ok - Treehouse project locking still serializes two homes across the remote-seeded boundary
FM_TEST_END 2026-11-03T05:30:25Z tests/fm-teardown-endpoint-safety.test.sh exit=0 duration_ms=57950 gate_skip=false
FM_TEST_SUMMARY total=2 failed=0 skipped_gate=0 duration_ms=565298
FM_TEST_SUMMARY_FAMILY family=backend-dispatch count=1 duration_ms=57950 failed=0
FM_TEST_SUMMARY_FAMILY family=pr-forge count=1 duration_ms=507240 failed=0
FM_TEST_SLOWEST rank=1 script=tests/fm-teardown.test.sh duration_ms=507240
FM_TEST_SLOWEST rank=2 script=tests/fm-teardown-endpoint-safety.test.sh duration_ms=57950
fm-test-run: wrote timing artifact: ~/.no-mistakes-upstream-codex/evidence/01M6FXHRYH31ZKSRYWYT26KKH6/targeted-tests.json
Evidence: Baseline regression reproduction

Source: Baseline regression reproduction

FM_TEST_BEGIN 2026-11-03T05:21:57Z tests/fm-teardown.test.sh family=pr-forge expected_gate_skip=none
ok - teardown leaves opencode's busy plugin in the returned pool worktree as on main
orca/reap-refusal: teardown_exit=1 replay_exit=0 metadata_after_replay=missing backlog_after_replay=done
not ok - orca/reap-refusal: metadata lost
not ok - orca/tracked: late work must refuse teardown: expected exit 1, got 0
not ok - orca/untracked: late work must refuse teardown: expected exit 1, got 0
not ok - orca/commit: late work must refuse teardown: expected exit 1, got 0
tmux/reap-refusal: teardown_exit=1 replay_exit=0 metadata_after_replay=missing backlog_after_replay=done
not ok - tmux/reap-refusal: metadata lost
not ok - tmux/tracked: late work must refuse teardown: expected exit 1, got 0
not ok - tmux/untracked: late work must refuse teardown: expected exit 1, got 0
not ok - tmux/commit: late work must refuse teardown: expected exit 1, got 0
not ok - 8 post-reap boundary cases failed
FM_TEST_END 2026-11-03T05:23:01Z tests/fm-teardown.test.sh exit=1 duration_ms=63685 gate_skip=false
FM_TEST_SUMMARY total=1 failed=1 skipped_gate=0 duration_ms=63759
FM_TEST_SUMMARY_FAMILY family=pr-forge count=1 duration_ms=63685 failed=1
FM_TEST_SLOWEST rank=1 script=tests/fm-teardown.test.sh duration_ms=63685
fm-test-run: wrote timing artifact: ~/.no-mistakes-upstream-codex/evidence/01M6FXHRYH31ZKSRYWYT26KKH6/baseline-race.json

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

⚠️ **Test** - 1 warning
  • ⚠️ live validation verdict: inconclusive (3 of 8 scenarios were driven live against the product); untested: Tracked edits written during worker termination retain work, branch, and retry records on ordinary and Orca paths, An untracked file written during worker termination survives cleanup refusal on ordinary and Orca paths, An unlanded commit created during worker termination retains its branch and task on ordinary and Orca paths, A failed reap cannot publish a close that replay uses to retire the retained task, Herdr closes the exact pane before reaping and preserves the task copy when closing is refused
  • Live validation: ⚠️ inconclusive - 3 of 8 scenarios driven live against the product
Scenario Result Live Evidence
Clean ordinary task cleanup stops its endpoint, returns its pool slot, removes its branch and retry records, and completes its backlog item ✅ pass live Real CLI cleanup transcripts: SCENARIO clean
Explicit forced cleanup discards disposable edits and a nested repository, stops its endpoint, and returns a clean pool slot ✅ pass live Real CLI cleanup transcripts: SCENARIO force
Scout cleanup with a completed report discards scratch work and completes with its report link ✅ pass live Real CLI cleanup transcripts: SCENARIO scout
Tracked edits written during worker termination retain work, branch, and retry records on ordinary and Orca paths ⏸️ untested no The fake-reaper fixture passed on the candidate and failed on the baseline. The previously recorded PreToolUse refusal blocks the independent terminating-worker probe, and standing instructions prohib…
An untracked file written during worker termination survives cleanup refusal on ordinary and Orca paths ⏸️ untested no Both paths passed with synthetic reaper boundaries and failed on the baseline. A real termination-timed write remains blocked by the previously recorded PreToolUse refusal. A hook-approved isolated te…
An unlanded commit created during worker termination retains its branch and task on ordinary and Orca paths ⏸️ untested no Real scratch Git repositories passed the synthetic boundary case on the candidate and failed on the baseline. Live worker termination was not driven because the recorded probe refusal remains binding.…
A failed reap cannot publish a close that replay uses to retire the retained task ⏸️ untested no Synthetic reap failure and replay passed on the candidate. The baseline lost metadata and completed the backlog item. No real failed-reap lifecycle was driven because the independent termination probe…
Herdr closes the exact pane before reaping and preserves the task copy when closing is refused ⏸️ untested no Canonical synthetic close/refusal checks passed. Named-helper prepare and teardown checks succeeded without provisioning a session. Real backend administration remains outside the supplied closure sco…
  • bash bin/fm-test-run.sh tests/fm-teardown.test.sh tests/fm-teardown-endpoint-safety.test.sh --json &lt;evidence&gt;/targeted-tests.json exited 0 without gate skips at 1f64ff7ded5d4f25d31e3619fece5393e78d9033.
  • Archived baseline f641b44 into a disposable snapshot and ran the candidate boundary fixture through its canonical runner. It exited 1, reproducing late-edit, untracked-file, commit, and replay failures on both paths.
  • bash .tools/phase-validation/live-cli.sh exercised real Treehouse, tasks-axi, tmux, and idle Codex endpoints at 120x40. Corrected private-socket setup and re-ran all three flows successfully.
  • bin/fm-herdr-lab.sh prepare fm-lab-up7783-test and matching teardown succeeded with helper records inside the worktree. No Herdr session was provisioned.
  • git diff --exit-code, git status --short, and git rev-parse HEAD confirmed unchanged tracked files at the target revision.
  • Inventoried scratch files. Command policy rejected baseline deletion, so no alternative deletion was attempted. .tools/phase-validation remains at 22 MB.
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@greptile-apps

greptile-apps Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no blocking issue was found.

Reviews (5) · Last reviewed commit: "no-mistakes(document): Correct teardown ..." · Reviewed by Greptile

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thank you @WTF-Am-ID. This closes #7783 in the smallest way that works. It re-runs the existing safety check after the reap, keeps the force and scout exemptions, and clears the prepared backlog close so startup replay can't erase the task it just protected. The 12 scenarios across tmux and Orca made it easy to review.

What I checked (head ec695763, main b04154bd): in bin/fm-teardown.sh, right after reap_task_worktree_processes and before the pipeline-spend record, branch -D and the worktree return, the new block re-runs validate_worktree_teardown_safety. It applies to owned worktrees and skips --force. On a refusal it calls fm_backlog_close_marker_clear (or exits loudly if that fails) and exits 1 with the task records intact. No workflow, network or credential changes.

Optional, not blocking: the first safety check treats return code 3 (TEARDOWN_WORKTREE_SAFETY_LOCK_BLOCKED) as "wait for the git lock to go stale, then retry". The post-reap check treats it as a plain refusal, so a worker killed mid-git-write leaves teardown printing "checking whether the lock is stale" and then exiting with no clear REFUSED line. It still fails closed, and a rerun clears it through the first check. Handling rc 3 the same way here, or printing a clear refusal, would make the message honest.

Overlap, FYI: your #7929 edits the same teardown section (branch-cleanup identity plus a --branch-cleanup-pending close marker), and #7927 also clears the close marker on an Orca refusal. Whichever lands second should cover the interaction. tests/fm-teardown.test.sh now conflicts with main after #7915 landed. It's only the test call list, the conflict is ours to fix, and you don't need to rebase.

contract-class: restore. Teardown already promises that unlanded work is never torn down, and this makes the existing check hold across the reap window. VISION: aligns. One captain: no silent loss. Authority: discarding still needs --force. Scripts/agents: it reuses the deterministic predicate. Restart: records and backlog intent survive the refusal. Delegation: "Unlanded work is never torn down". Vendor: the tmux and Orca paths both go through the same check. Scope: teardown only.

no-mistakes binds this head, Greptile is 5/5 and live validation is 6/6. CI run 40733963583 has 12 passing and 8 still queued. Nothing is needed from you. Once CI is green I'll resolve the test-file conflict and merge after fresh CI.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: quick update, @WTF-Am-ID. CI on your head ec695763 came back fully green (21/21), and the no-mistakes check passed on it. The only thing in the way was a conflict with main in the tests/fm-teardown.test.sh call list after #7915 landed. I've fixed that on our side by merging current main into your branch (046b6c3d). The resolution keeps both calls, test_content_fallback_git_capability_boundary and test_work_written_at_reap_boundary_is_preserved. No other file conflicted, and no workflow files changed. You don't need to rebase.

Contract-class: still restore. The teardown change is the same one I reviewed last pass.

One small ask, when you have a moment: the "PR must be raised via no-mistakes" gate binds its attestation to the exact head, so my merge commit will make it fail even though your change is untouched (the same thing happened on #7909). Could you pull the branch and re-raise it with git push no-mistakes so the attestation binds the merged head? Once that passes and the fresh CI is green, I'll merge it on a later pass. Thanks again for this one.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thank you for the re-raise, @WTF-Am-ID. The no-mistakes attestation now binds 81681c9d, CI is green (21/21), Greptile is 5/5, and it still merges cleanly onto main 0adf422e.

What changed since my merge head (046b6c3d): the re-raise did more than refresh the attestation. 879e2be9 moves the no-mistakes conclude, the process reap and the post-reap safety proof in bin/fm-teardown.sh to before the pending-close marker is written, so a refusal no longer has to clear a marker. I read it through, and it looks right to me. Every path still refuses before anything destructive to the work, and an interrupted run after the reap leaves the worktree and records intact for a plain rerun. The new reap-refusal case is a good addition. Contract-class: still restore. The order change is internal to the same refuse-and-retain promise, and a clean teardown ends the same way as before.

One ask before merge: this head's validation shows 0 of 6 scenarios driven live. The earlier head had live tmux + Orca runs, but they were on the old ordering. When you have a moment, could you live-test the new order on this head and post the evidence here (or re-raise with git push no-mistakes with live validation enabled)? The cases that matter most are a late edit refusing teardown with the task and backlog row kept, and a clean teardown closing its backlog item, on both tmux and Orca. That's all that's left. This is waiting on you, and once the evidence is in I can merge it on a later pass.

@WTF-Am-ID

Copy link
Copy Markdown
Contributor Author

The live tmux evidence on head 81681c9d3eb5b628fb47c7d01ca525d63200c3e3 is now in the PR description. A late edit refused teardown (exit 1), keeping the task bytes, metadata, status and in-flight backlog row, with no close marker. Clean teardown completed (exit 0), removed the metadata and marked the backlog item done. CI is 21/21 green, including the no-mistakes check on that head.

We will not test the two Orca cases on our side because Orca is unavailable in our environment. Those cases remain untested and are your call.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thank you @WTF-Am-ID for the live runs on 81681c9d. They're exactly what I asked for on tmux. A late edit during the reap refused teardown and kept the task, its metadata, status and in-flight backlog row, with no close marker written. A clean teardown returned the slot and closed its backlog item.

On Orca: I'm accepting this without the two live Orca cases. The reordering lives in the shared part of bin/fm-teardown.sh that both backends run through, the Orca refusal, replay and clean paths have synthetic regressions in tests/fm-teardown.test.sh, and you've told us plainly that Orca isn't available on your side. That's my call, not something you still owe.

Where it stands: the attestation binds this head with no skipped steps, quick checks and CI on this head were green, Greptile is 5/5, and there are no open threads. Main has moved since (#7909 also changed teardown), and tests/fm-teardown.test.sh now conflicts again. It's the test call list, and that conflict is ours to fix, so you don't need to rebase. Contract-class: still restore. "Unlanded work is never torn down" now holds across the reap window. VISION: aligns (no silent loss, --force is still the only discard, a deterministic recheck, records survive the refusal, teardown scope only).

Nothing else is needed from you right now. The next steps are on our side.

@kunchenguid kunchenguid added the full-ci Maintainer go-ahead: run the full CI suite on this outside pull request label Nov 1, 2026
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thank you @WTF-Am-ID for merging main in yourself. You didn't have to, but it saved us a step. I checked 30b11917. The teardown, backlog and docs changes are exactly the ones I reviewed, and the test file keeps main's new hidden-untracked case alongside your reap-boundary case. Nothing else moved. It still merges cleanly with today's main 95f006f8. The attestation binds this head, and its skipped rebase is fine here because the branch already contains main. The quick checks pass and Greptile is 5/5.

I've added full-ci so the full suite runs on this head. If it's green, I'll merge it. Contract-class: restore, unchanged. Nothing more is needed from you.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: a correction to my last note here. I shouldn't have treated the skipped rebase step in the no-mistakes attestation as harmless. Our merge gate needs no-mistakes bound to the current head with no skipped steps, and there's no exception for this case.

@WTF-Am-ID, when you have a moment, could you re-raise this branch through no-mistakes so the attestation for 30b11917 shows every step run? The branch already contains main, so the rebase step should just pass. I'm leaving the full-ci label on, so the Full suite result will still count. Once the clean attestation is up, this is ready to merge. Thanks for your patience, and sorry for the mixed signal.

@kunchenguid
kunchenguid merged commit 5b91acf into kunchenguid:main Nov 3, 2026
24 checks passed
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: this is merged. Thank you @WTF-Am-ID for the clean re-raise and for carrying this through two upstream merges. The post-reap safety re-check, with backlog-close publication held until it passes, now holds alongside main's exact-pane-close ordering. Really appreciate your patience with the stricter gate.

kayis-rahman added a commit to kayis-rahman/firstmate that referenced this pull request Nov 4, 2026
* feat: monitor author-actionable pull request states (#8055)

* feat(pr-health): distinguish maintainer approval states

* feat(pr-health): alert authors on requested changes

* feat(pr-health): read owned PRs on GitHub notification events

Classify maintainer-gated CI from ACTION_REQUIRED check suites, which an
awaiting-approval fork PR shows while its rollup stays green, keep required
approval and author action as distinct once-per-commit states, and drive
reads from a conditional notifications feed with the poll as fallback.

* no-mistakes(review): Preserve same-timestamp notifications; regression added; focused test timed out

* no-mistakes(review): Record maintainer waits without waking tasks

* no-mistakes(review): Retain notification cursor until feed page completes

* no-mistakes(review): Retry truncated check suites and clarify wake behavior

* no-mistakes(review): Record pending reviewers without review decisions

* fix(pr-health): advance the notifications cursor on a full page

A full page already forces a full read of every owned PR in that pass, so
holding the cursor back only pinned a busy account to full sweeps; the
first read of such an account never saved a cursor at all.

* feat(pr-health): read owned PRs on GitHub notification events

Classify maintainer-gated CI from ACTION_REQUIRED check suites, which an
awaiting-approval fork PR shows while its rollup stays green, keep required
approval and author action as distinct once-per-commit states, and drive
reads from a conditional notifications feed with the poll as fallback.

* no-mistakes(review): Restore unrelated hc documentation changes

* no-mistakes(ci): Fixed ci-3 by keeping successful reads with `mergeable: null` pending, and ci-4 by persisting selected URLs as pending alongside the advanced notification cursor before reads. **ci-2 remains unresolved:** check-suite pagination is not implemented, so lists exceeding 100 suites may still be treated as unsettled. `bash tests/fm-pr-health.test.sh` timed out after 120 seconds; earlier cases passed, but verification is incomplete

* no-mistakes(ci): No code changes completed. The conflict check was corrected to distinguish `mergeable: null` from `false`, but check-suite pagination and its page-2 regression test remain unfinished. Verification was not run; this phase cannot be marked complete

* no-mistakes(ci): Fixed ci-2 in `bin/fm-pr-health.sh` and added regression coverage in `tests/fm-pr-health.test.sh`. Check suites now paginate up to 10 pages; exceeding that bound leaves the read unsettled. The patch also covers mergeability retry behavior and interrupted notification passes. `FM_LIVE=0 bash tests/fm-pr-health.test.sh` passed all 33 tests, and `bash bin/fm-lint.sh` passed. Left ci-1 unchanged

* fix(pr-health): read check suites in their own query

gh --paginate follows a single pageInfo, so nesting the paginated
check-suite connection in the PR query stopped it paging the check
contexts: a PR with more than 100 checks never finished a read and was
never classified.

* fix(pr-health): judge a full notifications page against the cursor

GitHub ignores since= on a conditional (If-Modified-Since) request and
answers with the newest page, so a busy account always got a full page and
every changed feed forced a full sweep. A page now forces the sweep only
when it is full and its oldest entry is still newer than the saved cursor.

* no-mistakes(lint): Fix ShellCheck empty cursor assignment

* no-mistakes(ci): Fixed the interruption regression test to terminate the captured main poll PID and assert that it exits unsuccessfully before verifying the event is retried. The interruption test passed. The full test script timed out after 120 seconds, though the tests reported before the timeout passed; `git diff --check` passed

* no-mistakes(ci): Updated `tests/fm-pr-health.test.sh` to run and terminate the main poll directly, and assert during the interrupted read that the advanced notification cursor and selected event are saved together. `FM_LIVE=0 bash tests/fm-pr-health.test.sh` passed (34/34); `git diff --check` passed

* test(pr-health): stop the main pass in the interruption test

The fake gh now stops the outermost poll process rather than a background
read shell or a wrapper subshell, and the test asserts that the advanced
cursor and the selected event were saved together before the reads. A PR
with more than a page of pending review requests is covered too; only
whether any request is pending matters, so the first page decides it.

* test(pr-health): interrupt the pass by its own PID

The interruption case starts the check in the background, whose PID is the
poll itself because the check execs it, and the fake gh stops that PID.
This drops the ps ancestry walk, which Git for Windows cannot run.

* no-mistakes(document): Update PR health monitor documentation

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Kun Chen <[email protected]>

* test: keep shared-captain spawn test off a live Herdr server (#8064)

The spawn convergence test cleared TMUX but inherited HERDR_ENV from a
Herdr pane, so backend auto-detection picked Herdr and created a real
workspace. Pin the spawn to the tmux backend the test stubs, shadow herdr
with a recording stub, and assert the spawn never calls it.

* fix(watch): surface timed-out checks on both timeout paths (#8068)

A registered check cut off at FM_CHECK_TIMEOUT before it printed
anything stayed silent: run_check_capture discarded the exit status,
so the timeout never reached a wake. On hosts without GNU timeout or
gtimeout, the perl fallback in owned-group mode also sent SIGKILL to
its own process group, so perl died with 137 before it could exit 124.

run_check_capture now appends "timed out after <seconds>s" to anything
the check printed before the cut. In owned-group mode the perl
fallback sends SIGKILL only to the check it forked; the watcher
already kills the rest of the group after its wait.

Refs #4338. Original fix by @kynjal26.

* test: resolve host tools in watcher lock fixtures (#8070)

* test: resolve host tools in watcher lock fixtures

The watcher-lock suite's three fake ln shims exec'd a hardcoded /bin/ln,
and two identity fixtures named their holder process through exec -a. Both
assume a host whose /bin carries coreutils and whose sleep still runs under
a rewritten argv[0]. On a host that keeps only sh in /bin, and whose sleep
is a multicall binary that dispatches on argv[0], the shim exits 127 and the
holder dies at once, so those cases fail on the fixture instead of on the
lock behavior they assert.

Each shim now receives the host's own ln path through FM_TEST_REAL_LN,
resolved with command -v as this repository's other fixtures already do,
and the two holders are python3 processes that carry the fixture path as an
argument, which keeps them reapable through the fixture root. CONTRIBUTING's
test-fixture rules name the pattern so a new shim does not reintroduce a
hardcoded /bin path.

Before, on a host without /bin/ln: "not ok - acquirer could not reclaim dead
steal owner (rc=8)" and, with the shims fixed but the holders unchanged,
"not ok - could not identify the fixture holder". After: the full suite is
58 ok with exit 0.

Provenance: ports 8a0b7b8b ("no-mistakes(test): Make watcher lock fixtures
portable across host tools"), which fixed one of the three shims plus both
holders. The other two shims are the same defect in the same file, so they
are carried here rather than left to fail on the same hosts.

* no-mistakes(test): test: resolve rm and ps in watcher lock fixtures

* no-mistakes(document): correct fixture-portability guidance in CONTRIBUTING

* feat: support Rex for remote second mates (#8058)

* feat(bin): support rex as a remote secondmate backend

Remote second mates no longer require herdr: --backend rex launches the
mate on the remote account's own persistent `rex server start` server in
that home's per-home 2ndmate-<id>-<hash> session, where its endpoint
survives every SSH disconnection the route depends on. Herdr stays the
default and the only backend a pre-Rex remote can verify.

- fm-spawn accepts --backend rex, threads it through the readiness gate
  and the remote control launch, and refuses a returned rex route that
  does not pin a host-local unix:// server and a session-matched
  <session-uuid>:<block-uuid> target; it records remote_backend,
  remote_rex_session_id, and remote_rex_server.
- fm-remote-secondmate-control.sh accepts {herdr, rex} per verb: rex
  endpoints require a host-local unix:// rex_server, state probes are
  pinned to the recorded server through the endpoint absence recheck
  (unproven reads stay unverified, never missing), route output reports
  the rex identity trio, and launch refuses an endpoint recorded on a
  different backend than the one requested.
- fm-remote-readiness-lib passes the selected backend to the doctor. A
  pre-Rex remote exits 2 on --backend, so an explicit herdr request
  retries bare while a rex request stays refused.
- fm-remote-doctor.sh gains --backend herdr|rex|any: rex verifies the
  CLI, client and server API revisions against the verified floor, and
  a persistent unix:// server (exit_empty=false); --fix may start or
  restart that server but never installs the CLI.
- fm-secondmate-liveness-lib re-checks an alive remote route's backend
  against the recorded remote_backend and reports drift instead of
  migrating; records without remote_backend stay herdr.
- tests share a stateful fake rex fixture (version, whoami, server
  lifecycle, sessions/windows/blocks, process/status/capture,
  send/send-key, events, agent-on-send) across the adapter, doctor,
  liveness, and lifecycle e2e suites.

Verified on disposable Linux (Apple container, Debian 12 aarch64, rex
0.1.0-preview.12, API rev 8): nested-shell foreground tracking and
input delivery, peer-vs-anonymous whoami, rex do/events, --exit-empty
vs persistent server durability, and session restore on identical
socket+state.

* fix(bin): keep rex on recovery, route keys, never stop rex

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test: assert exact rex fake state in new regressions

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test: request bootstrap relaunch facts in rex recovery check

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* no-mistakes(review): keep remote rex control plane from autostarting

* no-mistakes(document): Correct remote Rex documentation contracts

* no-mistakes(document): Point provisioning to remote backend contract

* no-mistakes(lint): Silence intentional deferred expansion lint warning

* no-mistakes(ci): Diagnosed Full suite failure as serial shard 9 exceeding its 30-minute cap. Updated the expanded remote lifecycle test’s measured scheduling weight and increased serial shards from 10 to 11, preserving timeouts and complete coverage. Coverage guard, runner and workflow contract tests, actionlint, source-aware ShellCheck, and diff checks passed. Hosted CI rerun remains for the outer executor

* no-mistakes(ci): Fixed fm-on’s stale Herdr-specific test assumptions by explicitly selecting Herdr in both fixtures, and refreshed the entrypoint’s stale doctor bootstrap hash. Reproduced both failures before fixing. fm-on and remote-doctor behavior suites and git diff --check pass locally. Full suite failure was downstream of the failing shard; hosted CI rerun remains for the outer executor

* no-mistakes(ci): Fixed both findings: Rex retirement now refuses block close and home deletion unless the answering server matches the recorded endpoint; readiness reads whoami once and requires explicit boolean exit_empty=false. Refreshed the doctor bootstrap digest. Reproduced both regressions before fixing. Doctor, full remote lifecycle, entrypoint tests, targeted ShellCheck, and diff checks pass

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

* docs(harness-adapters): correct claude --setting-sources worker claim (#8076)

* docs(harness-adapters): correct claude --setting-sources worker claim

* no-mistakes(review): Correct sibling setting-sources claim in fm-claude-trust.sh comment

* no-mistakes(document): Rewrap corrected setting-sources comment in fm-claude-trust.sh

* fix(bin): settle contributions per owner and bound record reads (#8023)

* fix(contributions): keep maintainer-comment polls inside the check timeout

In a home with a few hundred contribution records, the contribution poll
spent most of the watcher's 30-second check bound on local bookkeeping
before its forge budget started: three jq processes per saved record file
plus several per already-final URL. The watcher killed the poll before it
read most open PRs, so a maintainer comment on an open PR could wait many
hours, or never, for its wake. The PR health monitor had the same cost in
its enrollment step: it re-enrolled every owned pair on each pass and
saved nothing until the end, so a killed pass never converged and a PR on
a later task branch was never enrolled.

- read_saved validates every record in one jq process and keeps the
  per-file path only to count unreadable records.
- poll skips final URLs that every owner already holds error-free, with
  one jq pass deciding settled, final and live URLs.
- owned reports the tasks holding a durable record for each URL, and the
  PR health monitor skips enrolling pairs that already have one, so a pass
  cut short still makes durable progress.

* no-mistakes(review): Isolate record validation errors per file in one jq

* no-mistakes(review): Read each record file whole to avoid joining

* no-mistakes(ci): Fixed ci-2: read_saved in bin/fm-contributions.sh now validates records in bounded jq batches (FM_CONTRIBUTIONS_READ_BATCH, default 100) instead of one jq with every record path, so a long-lived home cannot hit the argument-length limit. Batch results are merged; malformed-record, task-identity, no-trailing-newline behavior and the per-file unreadable count are unchanged. Added test_records_beyond_one_read_batch_are_all_read (5 records, batch 2, jq wrapper rejecting more than 2 record files); it fails on the old code and passes now. The full contributions suite passed before the wrapper was added. I re-ran only the new test afterwards. ci-1 (Full suite) is the maintainer full-ci label gate, so no change was made for it. I did not reply on the review thread

* no-mistakes(review): Hard-code contributions read batch at 100

* no-mistakes(lint): Silence ShellCheck SC2016 in contributions test

* fix(bin): keep authenticated PR polls armed across template updates and relaunches (#8069)

* fix(pr-lib): preserve authenticated PR polls across updates and relaunches

An armed merge poll binds to the hashes and file objects it was registered
with, so a repository template update no longer invalidates it. Validation
previously required the published check to be byte-identical to the current
bin/fm-pr-poll.sh, which an update or a control relaunch silently broke even
though the watcher executes the current repository poll with validated data
and never executes the registered state-file bytes.

Accept control_relaunch_tx among the metadata fields that may follow the PR
identity, and pin both behaviours in the security suite: an older registered
generation still detects its merge without executing sidecar code, and forged
bytes or forged trailing metadata are refused.

* no-mistakes(document): Align poll-registration docs with hash-bound validation

* no-mistakes(ci): Addressed the selected Greptile finding (ci-2) in tests/fm-pr-check-security.test.sh:3474 (test_registered_poll_survives_template_update_and_relaunch). Problem: for the template-update and combined scenarios, the "historical generation" fixture was bin/fm-pr-poll.sh with a marker line appended after the poll's unconditional exit, so the marker was unreachable and the copy still performed the same gh call. Both the marker-absence and gh-call assertions could therefore pass even if the watcher had executed the registered bytes instead of dispatching the current repository poll. Invariant: the historical registered check bytes are never executed; only the current repository poll runs, and it must be the sole source of the merge result and the sole forge call. Places this must hold: the template-update scenario, the combined (template-update + control_relaunch_tx) scenario, and the relaunch-only scenario (which legitimately has byte-identical check bytes). Fix: for non-relaunch scenarios the fixture is now a self-contained stub whose whole body is reachable — it writes the sidecar marker file and prints the distinct line `historical-generation`, and never touches gh. The relaunch scenario keeps the unchanged cp of the current poll as before. No existing assertion was weakened or changed: marker absence, `task-a.check.sh: merged`, the `pr view ... --json state` gh log entry, poll retirement, and forged-check refusal all remain. Verification (FM_TEST_BASE_PATH=/run/current-system/sw/bin, required on this NixOS host because mkdir is not under /usr/bin): full `bash tests/fm-pr-check-security.test.sh` passes with no `not ok` lines, including the registered-generations case; `bash -n` and `shellcheck -S warning` pass on the file. Negative control: temporarily patching bin/fm-watch.sh to execute the registered check bytes made the same test fail, then the patch was reverted (git status shows only the test-file change). ci-1 (Full suite) was marked ignore by the human decision and its suite passes locally

* no-mistakes(test): Prove live that template-update polls stay armed and keep their merge wake

* feat: auto-select hc inside Herdr app-projected terminals (#8060)

* feat(hc): auto-detect the Herdr app signals for the hc backend

Stage 3 of Herdr Core support: a Firstmate running inside the Herdr app
now selects the hc backend automatically, while classic Herdr TUI,
nested tmux, and bare hc terminals keep their existing verdicts.

Two app-owned signals, checked after every other surface marker:

- app-terminal: the process's own HC_TERMINAL_ID carries a non-empty
  herdr.space label in its core's record - the exact condition the app
  projects a terminal into its window. An app terminal's env is
  deliberately identical to any other hc terminal's (the core rewrites
  the app's TERM_PROGRAM=herdr claim to ghostty), so the claim is read
  from the record via `hc get`, gated by a live unix-connect probe
  because `hc` autostarts a core on contact with a missing socket.
- app-window: a live herdr-app.sock under the resolved app home
  (HERDR_APP_HOME, else XDG_CONFIG_HOME/herdr-app, else ~/.config),
  probed by an actual unix connect - the app's own liveness rule. The
  app is never launched and the core is never contacted for it.

Both require a usable hc toolchain (executable FM_HC_BIN or a
self-identifying herdr-core/hc on PATH, plus jq); a live window without
one records app-window-unusable and fm_backend_name prints a notice
naming the missing piece instead of switching. Explicit --backend,
FM_BACKEND, and config/backend always win; auto-detected hc prints a
loud opt-out notice and meta records backend_detect=app-terminal or
app-window alongside the existing herdr.space/herdr.tab presentation
labels.

Supervisor-endpoint discovery resolves an hc terminal to
<session>:<address> and backend hc so the away daemon fails loudly at
its supported-backend check instead of silently steering firstmate:0
tmux; full hc away support stays out of scope.

Verified against herdr-app 0.1.11 source/binary and an isolated hc
0.1.14 lab session (docs/verification/runtime-backends.md); a real
app window's socket and in-window label display remain unverified.

* no-mistakes(review): Bind hc auto-detection to the live spawn core

* no-mistakes(document): Correct hc selection and supervisor documentation

* fix(hc): gate app auto-detection on the adapter's verified core version

Greptile on PR #8060: fm_backend_detect_hc_usable accepted any
self-identifying 'hc x.y.z', but the adapter's container gate requires
FM_BACKEND_HC_MIN_VERSION (0.1.14). A live app window or terminal beside
an older core would auto-select hc, then have the spawn abort at the
version check - breaking an otherwise usable default spawn.

Detection now runs the adapter's own fm_backend_hc_version_check through
fm_backend_source (the same source path spawn and the bootstrap tool
check use), so an auto-selection can never resolve a binary the spawn
would refuse. The duplicated detection-side bin resolver is folded into
the adapter's fm_backend_hc_bin, and the unusable notices name the
verified minimum. A below-floor binary reports app-terminal-unusable or
app-window-unusable, covered by new fake-version assertions.

* no-mistakes(review): Make app-detect negative tests reject detection

* no-mistakes(document): Point hc metadata guidance to its owner

* fix: drop the app-window signal from hc auto-detection

The live real-Herdr-app exercise proved app-window cannot distinguish
"firstmate inside an app terminal" from "the app is open somewhere on
this host": marker-less bare processes selected hc solely because a
window existed, binding whatever core the spawn would reach. The
app-terminal signal (this terminal's own herdr.space label on the
spawn-reachable core) is the only claim that actually places the
process inside the app, so it is now the sole auto-select signal.
A marker-less process near a live window resolves the default backend
silently; explicit --backend/FM_BACKEND/config selection is unchanged.

* no-mistakes(document): Correct hc single-signal documentation

* feat(bin): add opt-in native Codex Stop-hook park for watcher supervision (#7525)

* Park verified native Codex supervision outside the model

* Document native Codex park verification and fallback

* no-mistakes(review): Extend Codex park startup grace to ten seconds

* no-mistakes(review): Document ten-second Codex park startup grace rationale

* no-mistakes(document): Name Codex native park in supervision host header

* no-mistakes(document): Add native Codex park script to scripts inventory

* Gate native Codex park behind config/codex-stop-park and cover it with behavioral tests

The native Codex Stop park now runs only in a home that opts in with
config/codex-stop-park; without it the session start, the synchronous
guard, and the asynchronous Stop hook behave as before the park existed
and the foreground checkpoint stays the default. A fixture-driven suite
with a fake codex covers the opt-in and version gates, the single-flight
claim, the fallback latch on a failed queue delivery or repeated arm
failure, the owner-gone watcher exit, and the retained quiet boundary.

* ci: add a tenth portable serial shard for the Codex stop-park suite

* no-mistakes(document): Point Codex park verification record at behavioral suite

* ci: retrigger checks

* Revert the tenth portable serial shard (added by #7838)

* no-mistakes(ci): I fixed both Greptile findings (ci-1, ci-2) with the small changes you asked for. No new state, subsystem or protocol change. The changes are not committed, so there is no Co-Authored-By trailer anywhere. **ci-1: a woken turn could lose its rearm (`bin/fm-codex-stop-park.sh`)** - Rule that must hold: when a registered session that still needs supervision hits Stop, a park must end up rearmed. A delivering park that still holds the claim must not make the next hook give up. - The only place that gives up is the claim acquisition in the async Stop hook. `--guard` already accepts a recent delivered record, so it needed no change. - Fix: if acquiring the claim fails, the hook reads the holder pid that the lock library reports. It checks that `.codex-park.json` shows this session, outcome `delivered` and that same pid, and that the pid is alive. Only then does it poll for up to 3 seconds (30 × 0.1 s) until `CLAIM` is gone, and retry the acquire once. Any other busy claim still does the old `exit 0`, so the single-flight case behaves as before. **ci-2: compaction skipped after a quiet boundary (`bin/fm-supervision-host.sh`)** - Rule that must hold: when the park clock restarts, every value measured on that clock restarts with it. `WARM_COMPACT_LAST_TICK` is the only such value. - Fix: one line, `WARM_COMPACT_LAST_TICK=-1`, in the Codex model-free quiet-boundary branch of `boundary_reached`. **Tests (`tests/fm-codex-stop-park.test.sh`)** - New case `test_stop_rearms_after_a_delivering_park_releases_its_claim`: a helper process holds the claim with a delivered record that names it, and releases it after 1 s. The Stop hook must wait, arm once, deliver one wake with no recovery notice, and leave a record that belongs to the new park. - Extended `test_host_quiet_boundary_retains_the_watcher` to use `config/warm-compact`, `FM_WARM_COMPACT_TICK=2` (equal to the 2 s park interval) and a stub engine that fails. The engine record is only written after the first quiet boundary, so compaction (`warm-compact engine failed` in the log, `/compact` passed to the stub) can only happen if the tick runs on the restarted clock. The watcher-retention checks still apply, now across three boundaries. - Mutation checks: with ci-1 reverted, the suite fails ("must rearm … expected '1', got '0'"). With ci-2 reverted, it fails with no warm-compact line in the log. I restored both fixes after each check. **Verification** - The whole suite passes (8 of 8). - `shellcheck -x` is clean on all three files. - `bin/fm-test-run.sh --check-coverage` passes: `FM_TEST_COVERAGE ok`, serial_max_ms=1140457 against a 1200000 budget, with 10 serial shards in the current tree. - Measured cost went up by about 3–4 s: three local runs took 25.6 s, 26.8 s and 24.8 s, against about 22 s recorded earlier. That is still under the 30000 ms hint, so I left the hint as it is

* no-mistakes(ci): Fixed the remaining ci-1 gap: a woken turn that reaches Stop while the earlier park is still sending its wake now waits for that park to release the claim, then rearms. Before, it gave up and left no watcher. The changes are not committed. What had to hold: when a registered session that still needs supervision hits Stop, a park must end up rearmed. That depends on two places: the record the park writes while it sends a wake, and the check that decides whether to wait when the claim is busy. Changes in bin/fm-codex-stop-park.sh: 1. Timeout constant: the literal 20 in deliver's fm_run_timed is now DELIVERY_TIMEOUT=20. The busy-claim wait is derived from it: (DELIVERY_TIMEOUT + 5) * 10 polls of 0.1 s, about 25 s. A comment names the constant. 2. New outcome before sending: the wake path now writes `record delivering` just before deliver. Every way out of it already overwrites that: success writes delivered, failure writes delivery-failed, HUP/INT/TERM write interrupted. 3. Wait check: the busy-claim check now accepts delivering or delivered, still for the same session and holder pid, and still only if that pid is alive. 4. One addition not asked for: delivering is added to the outcomes that trigger the recovery notice (with waiting, arming and interrupted). Before this change, a park killed with SIGKILL mid-send left waiting behind and the next park sent a recovery notice. Without this word that notice would silently stop. --guard and the claim model are unchanged. Test: the existing case in tests/fm-codex-stop-park.test.sh now takes two arguments: the outcome the holder records and how long it holds the claim. The holder then records delivered and releases, as a real park does. The suite runs it as `delivered 1` (old case) and `delivering 4` (new case, over 3 s and under the 25 s bound). Both require the Stop hook to arm exactly once, send one wake with no recovery notice, and leave a record that belongs to the new park. Mutation checks: - With the wait check set back to delivered only, the new case fails ("must rearm ... expected '1', got '0'"); fix restored. - Removing the new `record delivering` line fails no test, because the test's holder writes its own record. The delivering recovery trigger also has no test. Verification: - shellcheck -x is clean on all three touched files. - One unexplained failure: the suite passed in 12 of 13 full runs (3 run in parallel). The failed run was a timing run with output discarded, so the failing case is unknown; it did not reproduce in 13 more runs. - Hint raised: measured runs took 29.8 s, 34.0 s and 34.7 s, over the 30000 ms hint, so the hint is now 35000 in bin/fm-test-run.sh. bin/fm-test-run.sh --check-coverage passes: serial_max_ms=1140951 against the 1200000 budget, 10 shards. - The commit-message and comment wording rules don't apply yet, since nothing is committed

* no-mistakes(review): Gate latched fallback on supervision need; fix shard doc

* no-mistakes(document): Align Codex Stop-guard docs with park behavior

* no-mistakes(document): Document latched-fallback Stop block in turn-end guard doc

* no-mistakes(ci): Fixed ci-2 and ci-3; ci-1 left untouched and no CI file changed. ci-2 (bin/fm-codex-stop-park.sh): added settle_idle, called at both idle decisions (top of arm loop and inner poll loop) when fm_supervision_needed turns false. If state/.wake-queue is non-empty it records delivering, calls the existing deliver path, then records delivered; on delivery failure it records delivery-failed, latches the fallback and exits 1. With an empty queue it records idle and exits as before. Away mode, lost session lock and unregistered session still exit idle without delivering. The single-flight claim, fallback latch and rearm path are unchanged. ci-3 (bin/fm-supervision-instructions.sh): the codex case of ordinary_wake_line now splits on CODEX_PARK. A parked session is told the Codex Stop hook owns watcher continuity (drain and handle the wake, do not arm another cycle). A non-park Codex session keeps the foreground-checkpoint line unchanged. The existing codex assertions are unchanged and still pass. Verification: tests/fm-codex-stop-park.test.sh and tests/fm-supervision-instructions.test.sh both exit 0. shellcheck -x -S warning is clean on both scripts. No new tests were added, because neither suite had a matching case. Neither the settle_idle delivery path nor the parked ordinary-wake line is exercised by those suites

* test: cover the idle settle delivery and the parked ordinary-wake line

* no-mistakes(document): Document final-result delivery when Codex park ends

---------

Co-authored-by: crewmate <crewmate@localhost>

* fix: preserve piped stdin in timed commands (#8079)

* fix(timeout): preserve stdin in background runners

Explicitly inherit stdin before backgrounding the bounded command so Bash
does not replace piped input with /dev/null. Cover inherited input and
pipeline functions across timeout, gtimeout, perl, and bash.

* chore(document): Document stdin preservation in timed runner

* fix(secondmate): respawn a local second mate on its recorded backend (#8082)

A dead local second mate was respawned through a fresh --secondmate spawn,
which re-read config/backend. With config/backend=hc that spawn was
refused, so a second mate whose Herdr pane died stayed down. The liveness
respawn now passes the backend the mate's record names, so a changed
config/backend only affects new spawns. Remote mates keep their host's
routing.

Tests: fm-secondmate-liveness passes, including a new pinned-backend case.

* fix(bin): stop a stale terminal run outranking newer crew-state truth (#3701)

* fix: stop a stale failed run outranking newer truth

bin/fm-crew-state.sh matched a no-mistakes run against the worktree's current
code identity, so it inherited whatever run last sat on that head. A terminal
failed or cancelled run then outranked every newer record: a declared pause, a
crew's own terminal done line, and even a run still in flight on the same
branch. That was not merely a misleading state line - the stale failure was
promoted into a durable terminal-outcome record and queued for captain
presentation, naming a pull request the current run had never opened.

Two independent fixes.

The reader now proves a terminal failure is current before reporting it. A
later run the pipeline's own ledger proves current answers instead; a later
self-declared pause or done in the status log answers instead where the
ledger's date proves the log was appended after the failed run began; and a
later run that cannot be bound here reads as unknown - history, but no proof of
the present. Nothing else may, so a stale working, needs-decision, or blocked
line still cannot mask a real failure, and with no ordering evidence at all the
failure stands. A terminal reading also publishes the pull request its own run
opened, or none when it opened none.

bin/fm-inactive-reconcile.sh no longer inherits either half of the claim. A
terminal outcome is built only when the crew's own last self-declared word does
not contradict it, in both directions, and its pull-request identity comes from
the same record as its state rather than from a separately recorded task PR.

bin/fm-nm-run-lib.sh keeps the one attribution owner: the supersession check
reuses its existing rules and adds only the branch's newest ledger row and the
one-directional reading of the ledger's date column.

* no-mistakes(review): Captain: fix terminal run and PR provenance

* no-mistakes(review): Captain: preserve newest terminal run provenance

* no-mistakes(review): Captain: consolidate terminal provenance and status snapshots

* no-mistakes(review): Captain: enforce precise terminal outcome provenance

* no-mistakes(document): Consolidate terminal-state documentation ownership

* test(crew-state): expect unknown for an unprovable live replacement

f5d7f5f2 (#4476) raised the attribution bar: the runs ledger carries no run
id, so a LIVE replacement cannot be proven current and the reader answers
unknown. That moves three cases from rule 2b's case (a) to its case (c),
which this branch already documents as the honest answer for a replacement
that cannot be bound here.

Only the state label changes. Every safety assertion is unchanged and still
passing: no false failed state surfaces, and no stale pull request is
published.

* no-mistakes(review): gate status-log supersession off the attributed run's failure

* no-mistakes(review): accept only ready-signal PRs from a status-log outcome

* no-mistakes(review): report unknown for an unbindable live replacement run

* no-mistakes(review): make ordering and gate regression tests non-vacuous

* no-mistakes(review): restore current-run shape for ordering regression tests

* no-mistakes(review): require ordered status line to be log's last line

* no-mistakes(review): share ledger row validation, match run heads both ways

* no-mistakes(review): require a terminal ledger row for status-log ordering

* no-mistakes(document): name shared ledger-row validity owner in architecture

* no-mistakes(review): let reader ordering evidence keep a failure reportable

* no-mistakes(review): establish crew-word ordering from the log alone

* no-mistakes(document): record proven-older crew word exception in architecture

* no-mistakes(review): remove status-log ordering rules from crew-state reader

* no-mistakes(review): let run-step terminal states outrank the crew's own word

* no-mistakes(review): state the narrowed corroboration rule in architecture doc

* no-mistakes(review): run rule 2b after the socket-down status-log override

* no-mistakes(review): name the ledger verdict's own run, document applied precedence

* no-mistakes(review): skip rule 2b on coarse path, restore scout PR guard

* no-mistakes(document): note scout PR exception in reconcile header contract

* no-mistakes(review): extend terminal-reading precedence to done readings

* no-mistakes(review): derive ledger status from the run record's status field

* no-mistakes(review): drop vacuous checks-passed test, record traced evidence

* no-mistakes(review): name the unbindable ledger row, not an earlier run

* no-mistakes(review): append run id as a field, keep PR without ledger row

* no-mistakes(document): document run-id field and corrected terminal PR rule

* no-mistakes(lint): quote keyword literals in terminal-state comparison (SC1010)

* Preserve cancellation as unknown in ledger precedence

* Align completed-run selection fixture PR identity

* no-mistakes(document): Align crew-state rule 2b comment with cancelled-as-unknown

* no-mistakes(ci): I fixed the Greptile finding (ci-1): crews in the main home that reported a GitLab or Gerrit review now keep the review link in their completion notice. I left the changes uncommitted in the worktree for no-mistakes to validate and publish to PR 3701. I made no other changes and did not rebase, push or touch history. The rule that was broken: a terminal outcome taken from the status log must carry the review URL that its own ready report names, for every forge the project supports. **What changed** - In `bin/fm-inactive-reconcile.sh`, `terminal_outcome_pr` no longer uses its own regex, which accepted only GitHub-style `/pull/<n>` URLs. It now takes the note, strips the leading `PR `, strips an optional ` checks green` or ` published for review` (the Gerrit ready shape), and passes what is left to the existing `fm_pr_url_parse` in `bin/fm-pr-lib.sh`. That library is already loaded through `fm-dod-lib.sh`. This means GitHub, GitLab merge requests, Forgejo and Gerrit URLs are all accepted. The function returns the parsed URL, still taken only from the state line itself. - The run-step path, the scout rule, the rule against claiming URLs that are only mentioned in prose, and the cancellation-as-unknown and terminal-identity rules are unchanged. - I updated the comment above the function, because it said the rule was the same as `pr_for_task`'s, which is no longer true. **One stricter result you should know about:** a GitHub URL must now pass the shared parser's host check. It must be `github.com` or a host listed in the `github-hosts` config, and it must use `https`. For this reason I changed one fixture in `test_status_log_sourced_outcome_keeps_its_own_pr` from `https://example.test/.../pull/7` to `https://github.com/.../pull/7`. No other test depended on the old pattern. **Test:** I added one regression test, `test_status_log_outcome_keeps_gitlab_and_gerrit_reviews`, in `tests/fm-inactive-reconcile.test.sh`. It uses `PR https://gitlab.example/group/sub/project/-/merge_requests/8 checks green` and `PR https://gerrit.example/c/group/project/+/4201 published for review`. **Verification** - With the old `bin/fm-inactive-reconcile.sh`, the new test fails ("the gitlab terminal outcome dropped its review link"). - With the fix, `bash tests/fm-inactive-reconcile.test.sh` passes completely ("all inactive reconciliation tests passed"). - `shellcheck -x` reports no problems in either file. **Not changed, as you instructed:** `pr_for_task`, the ledger-first fallback in the same file, also accepts only `/pull/` URLs. That is the same problem in a sibling function. If a reviewer reports it, you said to stop and report rather than run another repair round

* fix: name the closing key in OPEN DECISIONS and keep the message when --resolve-key refuses (#3983)

* fix(supervision): make the OPEN DECISIONS listing name the key that closes it

An operator answering a listed decision runs the command the listing itself
advises, and that command refused - discarding the steer with it.

The two folds never disagreed. Both the whole-file fold and fm-send's resolver
read the same status_open_decisions rule, and both correctly keyed
`blocked: axi run hung ... [key=no-mistakes-start]` as `default`: the key
grammar states a key before the colon or at the head of the note, so a token
trailing a summary is prose. The reader that was wrong is the third one, the
drain's OPEN DECISIONS renderer. It suppressed `[key=default]` and printed the
note verbatim, so the only bracket token a reader could see on such an entry
was the one that is NOT the key - and the entry named a key it had not folded.

Every entry now states its folded key, `default` included, so the key the
listing shows is the key its advised command closes.

An unresolvable key still refuses rather than delivering: an answer this send
cannot close would leave the decision open behind an answer the operator
believes settled it. The refusal no longer costs the message instead - it
diagnoses a key that is only mentioned inside an open decision's note, names
the keys that are actually open, and prints the resend commands with the
message quoted back verbatim.

* no-mistakes(review): Remove automatic key selection from resend advice

* no-mistakes(document): Clarify operator key selection in resend documentation

* fix(send): carry the caller's routing context into every printed resend

A refused --resolve-key preserves the operator's message by printing a
resend command, but the command could not run: it reused $0 and dropped
the routing environment. A one-shot "FM_HOME=<home> bin/fm-send.sh ..."
exports nothing to the next command, and a relative $0 is valid only from
the directory that invocation ran in, so a copied line resolved to another
home's state, to no script at all, or refused with FM_HOME unset - and the
preserved message still never reached the worker.

The unconfirmed-remote retry path already solved this. Both printed resend
paths now share that one statement of it: the absolute home always, the
state override only when this invocation was given one, and this script's
absolute path.

Covered by a test that invokes fm-send through a relative path with a
one-shot FM_HOME, then runs what it printed from a different directory
with nothing supplied - what an operator copying the line actually does.

* no-mistakes(review): remove unprovable decoy-key diagnosis, quote resend key placeholder

* no-mistakes(review): scope empty open-set claim to status file, always offer keyed resend

* no-mistakes(review): Keep already-accepted keys in the refused-key resend

* no-mistakes(review): Check every resolve key before refusing, keep order

* no-mistakes(document): Reflow fm-send resolve-key refusal header comment

* feat(pr-check): record reported PRs from done lines during the check sweep (#8086)

* fix(pr-check): record every PR a task reports in a done line

Merge and health monitoring of a task's PR began only when the supervisor
ran fm-pr-check.sh by hand on the ready signal. When that step was missed,
for example on a rebase of an existing PR whose done line did not use the
canonical wording, the task kept no pr= and no merge poll, so failing
checks and maintainer requests on that PR went unnoticed.

fm-pr-check.sh scan now records each task whose newest done line naming a
supported PR URL ("PR <url>" anywhere in the note) has no pr= yet, through
the ordinary registration path, so every refusal still applies. The
watcher runs it at the start of each check sweep. A refusal is reported
once per task and PR as a check: pr-register: wake and retried silently on
later sweeps; teardown removes its marker.

* no-mistakes(review): Scan new PR reports before refused retries

* no-mistakes(review): Rotate scan start so hung PR registrations cannot starve

* no-mistakes(review): Resume PR scan after last attempted task

* no-mistakes(lint): Fix SC1007 in fm-pr-check.sh candidates declaration

* no-mistakes(ci): Fixed ci-2 and ci-4 in bin/fm-pr-check.sh. ci-2: the scan now treats a task whose pr= equals the reported done-line URL but has no valid published poll as unregistered, so a later sweep republishes the poll. ci-4: scan-driven registrations run with FM_PR_CHECK_SCAN=1 and, under the metadata lock, exit 0 without writing if pr= is now set to a different URL; manual registration is unchanged. Added two tests in tests/fm-pr-check-security.test.sh (test_scan_publishes_a_missing_poll_for_a_recorded_pr, test_scan_does_not_overwrite_a_pr_recorded_meanwhile), and a configurable FM_TEST_GH_SLOW_SECONDS in the slow gh stub. Both new tests fail without the fix and pass with it; the four existing scan tests still pass; shellcheck shows only SC1091 info notes. The full test file aborts earlier on this machine at an unrelated test (GNU stat '%Lp' errors / flaky), so I ran the scan tests as a separate set. ci-1 and ci-3 are declined, with no code change; the ci-3 known-limit line (a refusal notice can be lost if the watcher stops between writing the refusal marker and queueing the wake) still needs to go into the PR description, which I cannot edit from here. Known tradeoff: a merged task whose poll was retired but whose pr= and done line still match would look unregistered and be re-armed until teardown

* no-mistakes(ci): Part (1) is fixed. The scan in bin/fm-pr-check.sh now skips a task that has state/<id>.pr-poll-merge-notified or state/<id>.pr-poll-retirement. A merged task's retired poll is no longer re-armed. I added test_scan_does_not_rearm_a_retired_merged_poll to tests/fm-pr-check-security.test.sh. With the exclusion removed, the test fails ("the scan re-armed the poll of a merged task"). With it restored, the test passes. The existing missing-poll and concurrent-PR scan tests also pass. I ran only these three tests, because the full file is slow and was already known to abort early on this machine at an unrelated stat test. shellcheck -S warning is clean. Part (2) needed no change. The scan-only recheck already sits inside the META_LOCK section, right after the lock is taken and the metadata file is re-validated, before the meta rewrite. It exits 0 without writing or publishing when pr= is a different URL. The ci-4 test still passes

* no-mistakes(ci): Fixed ci-2. The scan in bin/fm-pr-check.sh now skips a task only when its merge-notified marker or poll retirement receipt names the same PR as the recorded pr=. A new helper, pr_check_pr_retired, does the check. An older PR's marker no longer hides a newer recorded pr= whose poll is missing. Tests, in tests/fm-pr-check-security.test.sh: - Added test_scan_arms_a_replacement_pr_despite_an_old_merge_marker. It uses an old PR 7 merge marker and a recorded pr=9 with no poll. The scan must arm the poll. With the old unconditional skip restored, the test fails ("an older PR's merge marker hid the replacement PR's missing poll"). With the fix, it passes. - test_scan_does_not_rearm_a_retired_merged_poll now writes a valid marker for the same PR. The old marker was a bare version line, which the new check correctly rejects. This test still passes. - The other scan tests pass: publishes_a_missing_poll and does_not_overwrite_a_pr_recorded_meanwhile. - I ran only the four scan tests, because the full file is slow and aborts early on an unrelated stat test on this machine. shellcheck -S warning is clean. ci-1 is declined: only the maintainer full-ci label gate failed. I made no PR description edits, because I cannot edit the PR from here. The earlier requested statements still need to go in the description: the #8023 (comment-wake) coverage of the waiting-author comment case, and the refusal-notice known limit

* feat(pr-check): run the done-line PR scan only with config/pr-register-scan

The watcher check sweep runs bin/fm-pr-check.sh scan only when the
home opts in with the config/pr-register-scan presence flag. With the
flag absent, the sweep is unchanged from before the scan existed.
The watcher test covers both settings.

* fix(dispatch): parenthesise openai answer check for jq 1.8 (#8066)

Co-authored-by: yeti <yeti@alps>

* test(tests): make anchored absence assertions real regex checks (#8017)

* test: give anchored absence assertions a regex that can match

assert_grep and assert_no_grep are fixed-string greps. An anchored pattern
handed to them searches for a literal caret, which no line can contain, so
every anchored assert_no_grep passed no matter what the file held.

Eighteen call sites across six suites asserted their absence that way, so
they were silently checking nothing: the merge-local readiness snapshot,
the public-followup request and platform links, the secondmate backend and
harness records, the restart literal-stop path, the delivery mode and yolo
fields, and the remote-doctor launchctl calls.

Add assert_regex and assert_no_regex for patterns that describe a line
rather than a literal, and convert those sites. The remote-doctor
alternation becomes a real ERE group instead of a fixed string containing
backslash-pipes.

The three suites that run on this host pass unchanged: merge-local 8,
task-delivery 34, public-followup 90. The other three fail identically on
unmodified main here because their fixtures pin a PATH without tr, sed, or
head; that is environmental and unrelated.

* no-mistakes(review): Fix regex absence errors and interactive label guard

* test(assertions): name lib.sh for ShellCheck source following

* no-mistakes(test): Fix vacuous anchored absence guard in fm-pr-merge help test

* no-mistakes(review): Restore pre-existing help assertion exactly

* no-mistakes(document): Document new assertion suite coverage in its header comment

* fix(spawn): lease the Herdr task copy so a restart restores the worker there (#8052)

* fix(spawn): lease the Herdr task copy so a restart restores the worker there

* test(spawn): align Herdr abort fixture with lease failure

* no-mistakes(review): Return Herdr lease when projected abort closes task pane

* no-mistakes(document): Note Herdr spawns no longer leave nested treehouse shell

* no-mistakes(ci): ci-2 (Greptile, bin/backends/herdr.sh): the invariant is that the projected abort cleanup must report a closed endpoint exactly when the task pane is confirmed gone. fm_backend_herdr_projection_close_pane_focus_preserving can confirm the close and then return 2 only because focus restoration failed. It can also return 2 or 1 after a close that did not happen. The only place where this result becomes SPAWN_ENDPOINT_CLOSED is fm_backend_herdr_projection_cleanup_exact; its single caller is bin/fm-spawn.sh:1691. I fixed it at that shared boundary. When the close call fails, the function now checks the exact pane with the existing fm_backend_herdr_pane_presence_state, and it reports success only when the result is `dead` (pane_not_found). It does not treat a return value of 2 as closed, so a present or unknown pane keeps the lease. I also updated the comment above the function. Tests (tests/fm-backend-herdr.test.sh, test_projection_cleanup_exact_succeeds_only_when_the_task_pane_closed): I added two behavioural cases that run the real cleanup and the real presence classifier against a stubbed herdr CLI response. (1) The close returns 2 and the pane get returns pane_not_found: the result is rc=0, so the endpoint is closed. (2) The close returns 2 and the pane get still shows the pane: the result is rc=1. I also stubbed the CLI in the existing refused-close case so that it cannot reach a real herdr. Before the fix, the confirmed-close-then-failed-restore case failed ("got 'CLOSED w1:p1;rc=1'"). After the fix, the full tests/fm-backend-herdr.test.sh and tests/fm-spawn-herdr-lease.test.sh pass. shellcheck -S warning is clean on both changed files. ci-1 (Full suite): this is not a code defect. The job stopped at the label gate with FM_CI_FULL=false and FM_CI_LANES_FAILED=false, so no lane failed. I did not change code for it. I did not re-run the workflow: this phase must not control CI, and a re-run cannot pass until a maintainer adds the full-ci label to PR #8052, because the gate reads that label. This is still an external label requirement. Note: a temporary copy of the fixed herdr.sh remains at /tmp/herdr.fixed, because my clean-up command was denied by permissions

* no-mistakes(review): Release or name Herdr lease after post-launch rollback

* no-mistakes(review): Return Herdr lease only when the pane is confirmed gone

* no-mistakes(review): Keep dirty Herdr slots leased after failed spawns

* no-mistakes(test): Count Herdr pane-death removal in concurrent abort ordering check

* no-mistakes(document): Clarify Herdr aborted-spawn lease return condition

* test(herdr): allow explicit lab session for presentation e2e

* fix(teardown): close Herdr pane before returning its lease

* no-mistakes(review): Remove inherited HERDR_LAB_SESSION override from presentation e2e

* no-mistakes(document): Document Herdr teardown closing pane before returning lease

* fix(teardown): retain leased copy when Herdr close is refused

* fix(bin): keep inactive reconcile from reporting terminal state while agent is live (#8085)

* fix(inactive-reconcile): withhold terminal outcome while the agent is alive

Fixes #6553

* no-mistakes(review): Bound liveness read; withhold only busy or relaunched agents

* no-mistakes(review): Judge incarnation by spawn epoch; use remaining budget

* no-mistakes(document): Document live-agent withholding in architecture scan rule

* no-mistakes(lint): Fix ShellCheck SC2143 and SC2016 findings

* no-mistakes(ci): ci-2 and ci-3 are fixed in tests/fm-inactive-reconcile.test.sh. ci-1 (Full suite) needs no code change, as the captain decided. I ran only the new test in isolation, plus a mutation check; the full test file did not pass in this environment (details at the end). - **ci-2 (macOS sed):** `arm_claude_busy` no longer uses `sed -i`. It writes the edited meta to `<id>.meta.new` and moves it over the original, so it works with both GNU and macOS sed. - **ci-3 (liveness-read timeout):** I added `test_stalled_liveness_read_is_bounded_and_scan_progresses`. - The fake `fm-crew-state.sh` sleeps 1s, then returns `failed` for child `a`. - The fake `tmux` then stalls for 30s, which stalls the liveness read. - With a 2s scan budget, the scan must finish within 4s. - After the stall is cleared, the next scan must still reach child `b`. - **Mutation check:** I removed `fm_run_timed "$timeout"` from the liveness read at `bin/fm-inactive-reconcile.sh:517`. The new test then failed, so it catches a lost timeout. I restored the file afterwards. - **Full test file:** it did not pass in this environment, because the existing `test_stalled_state_read_is_bounded_and_scan_progresses` failed on timing. In one run it exceeded its 3s elapsed bound (4s); in another, its next scan did not reach child `b`. I never ran it against `HEAD` alone; this PR changed that file only by adding the new test and the sed fix. - **Not checked:** I did not investigate why that existing test fails here

* fix(herdr): call an unresolvable launcher pane id stale instead of ambiguous (#7568)

* fix(herdr): name a stale launcher pane id as gone instead of ambiguous

The launcher pane id a shell inherits outlives the pane itself.
When herdr no longer knows that id, `pane get` answers with whatever
pane it still has, the exact-id filter in
fm_backend_herdr_launcher_identity keeps nothing, and the guard
refused with "returned an ambiguous tab or workspace identity".
There is no ambiguity to report: the pane does not exist any more, so
the id is stale.

The refusal now names the stale pane id, says the pane no longer
exists in the session, and names HERDR_PANE_ID, HERDR_TAB_ID and
HERDR_WORKSPACE_ID as the values to refresh.
The return codes, the refusal behavior, the identity-matching logic
and the spawn behavior are unchanged, and no other error path changed.

tests/fm-backend-herdr.test.sh covers both shapes of this path: a pane
id herdr answers with a different pane, and a pane record that names
no tab.

* fix(herdr): stale launcher pane message covers the no-tab shape too

The empty-tab shape is a pane record that still answers but names no tab,
so 'no longer exists' was not literally true for it. The refusal now says
the pane is stale: it no longer exists or names no tab or workspace in the
session. Return codes, refusal and identity matching are unchanged.

* no-mistakes(review): Reword unreadable launcher pane error as stale

* no-mistakes(document): Document stale launcher pane refusal in herdr backend docs

* fix(herdr): keep the could-not-be-read wording when the launcher pane get fails

* no-mistakes(test): docs(herdr): describe destroyed panes as unreadable, not stale

* feat(bin): add Hermes TUI worker adapter for tmux crewmates (#8084)

* feat(bin): add verified Hermes TUI worker adapter

* no-mistakes(document): Document Hermes owner in tmux composer identity comment

* no-mistakes(ci): Fixed ci-4: a Hermes worker that stalls at setup or misses the readiness deadline is now stopped before its task record is removed. Rule that must hold: once the Hermes launch command has been sent, any failure exit from the Hermes readiness gate closes the launched endpoint first. Only after that may the abort trap (spawn_abort_cleanup) roll back a fresh spawn's record and retire its busy generation. Two exits in the gate broke this rule, and both are now fixed in bin/fm-spawn.sh: 1. **Readiness timeout:** after the existing error message, the gate now calls `rovo_endpoint_cleanup`. This is the same close step the rovo launch-then-confirm gate already uses: it calls the backend's kill (just the exact terminal on orca) and sets SPAWN_ENDPOINT_CLOSED. It runs before `exit 1`, so the window is closed while the record still exists. 2. **Failed Enter on the first-run decline:** this used to `exit 1` straight away. It now `break`s out of the poll loop, so it reaches the same close-then-exit path. The ordinary path is unchanged. A ready screen or a hook record sets HERMES_READY=1 and skips the cleanup. Regression test in tests/fm-hermes-harness.test.sh: a fake tmux shows a stalled provider-setup screen, and the test uses tiny poll settings (FM_HERMES_READY_POLLS=2, interval 0). The fake `kill-window` writes down whether the task's .meta file still exists at the moment it is called. The test asserts that the spawn fails with the Hermes diagnostic, that `kill-window` ran while the record was present, and that the fresh record was removed afterwards. I confirmed it fails without the fix ("missing: 'kill-window record=present'") and passes with it. It uses only throwaway fixtures and a generic `example` profile. Checks run: tests/fm-hermes-harness.test.sh and tests/fm-rovo-harness.test.sh both pass with 0 failures, shellcheck on both changed files is clean, and `bash -n` passes. Changes are left uncommitted so the pipeline can record them as their own fix commit, with no squash. ci-1, ci-2 and ci-3 were not touched, as instructed

* no-mistakes(ci): I fixed ci-3. If the stalled Hermes worker can't be closed, a failed spawn now keeps its task record, so supervision and teardown can still reach the worker. **What must always hold:** once the Hermes launch command has been sent, the spawn rollback may remove a fresh task record and its busy generation only after the launched endpoint has actually closed. The last round's ci-4 fix tried to close the pane first, but it ignored whether that close worked. The cleanup at exit (`spawn_abort_cleanup`) still saw `SPAWN_FRESH_COMMIT_PENDING=1` and removed the record anyway, leaving a possibly live Hermes worker with nothing pointing at it. **Fix** (`bin/fm-spawn.sh`, the Hermes readiness gate's failure exit): after `rovo_endpoint_cleanup`, if `SPAWN_ENDPOINT_CLOSED` is not 1, the gate clears `SPAWN_FRESH_COMMIT_PENDING`. It also prints a warning that the record is kept and the worker should be inspected and torn down. This uses the existing flag the abort cleanup already relies on, the same way other kept-record paths skip rollback. The readiness timeout and the failed-Enter exit from the first-run decline both reach this single exit, so the fix covers both. Nothing else changes: - When the close succeeds, the record is rolled back exactly as before (the earlier stalled-launch test still passes). - When Hermes becomes ready, this branch is skipped. - On a relaunch, `SPAWN_FRESH_COMMIT_PENDING` is already 0, so nothing changes there. I left the other harnesses' gates alone. Changing how they roll back would go beyond this finding. **New test** in `tests/fm-hermes-harness.test.sh`: a fake tmux shows a stalled provider-setup screen, and its `kill-window` can be made to fail (`FM_FAKE_HERMES_KILL_FAIL`). The test checks four things: - the spawn fails with the Hermes error; - a close was attempted while the record existed; - the kept-record warning is printed; - the `.meta` record survives and still has `hermes_profile=example`. It uses only throwaway fixtures and a generic `example` profile. Without the fix the test fails ("missing: 'task record is kept'"); with it, it passes. **Checks run:** - `tests/fm-hermes-harness.test.sh`: all cases pass, 0 failures. - `tests/fm-rovo-harness.test.sh`: passes. - `shellcheck` on both changed files: only the usual SC1091 info notes about sourced files not being followed (it was run without `-x`), no warnings. As instructed, I didn't touch ci-1 (the full-suite label gate maintainers apply) or ci-2 (stale). The changes are uncommitted so the pipeline can record them as their own fix commit, with no squash

* test: include Hermes process helper in partial-bin fixtures

* no-mistakes(review): Add Hermes process helper to remaining fm-harness fixtures

* fix: preserve late worker changes during teardown (#7932)

* fix: recheck landed work after teardown process reap

* no-mistakes(review): Delay backlog close markers until post-reap safety proof

* no-mistakes(document): Correct stale pending-close publication references

* no-mistakes(document): Clarify initial teardown safety check ordering

* no-mistakes(document): Correct teardown ordering comments and stale retention documentation

---------

Co-authored-by: Kun Chen <[email protected]>

* fix(bin): share timed background launch and isolate terminal stdin (#8099)

* fix(timeout): keep redirected stdin on backgrounded runners

Non-interactive bash assigns /dev/null to an async command, so the external
timeout and bash runners dropped a piped payload before it reached the
command. Restore that stdin with an explicit redirection, leave a terminal
or closed stdin on the old assignment, and cover every mechanism the host
can select.

* no-mistakes(test): Give terminal stdin /dev/null in timed background runs

* no-mistakes(ci): No new code change is needed. The fix for ci-1 is already in commit db61d47a, which is HEAD, and the working tree is clean. Greptile pointed out that the old fd 3 check could never fail: fm_run_timed ran inside a pipeline subshell while `echo still >&3` ran in the parent shell. The committed test now calls the runner directly, with stdin redirected from a file, in the same shell that then writes to fd 3. It covers the external-timeout mechanism when one is installed and always covers the bash override. It checks the exit status, that the fd 3 write landed, and that the payload came through. Following the driver's instructions, I kept that commit and did not rework it. I re-ran `bash tests/fm-timeout-lib.test.sh` and it exited 0 with every case passing. The Greptile check is still failing only because the earlier push to the PR hit a GitHub Internal Server Error and never landed. The test code is not the cause. Re-publishing the existing commit through the pipeline will resolve it, and that step belongs to the outer executor

* fix: isolate interrupted auto-arm failures by session (#7921)

* Bind interrupted auto-arm notices to their producing session

* no-mistakes(document): Document session-bound auto-arm interruption recovery

* no-mistakes(ci): Fixed all three lint-inventory expectations to exclude hidden scripts, matching the documented shell globs. Tier 2 test correction; production behavior was correct. fm-lint.test.sh passes, with four platform capability skips. Targeted ShellCheck and git diff --check pass

* no-mistakes(ci): Repair blocked: the command guard rejected test authoring as “Indirect command execution not allowed.” Stopped dependent work without switching tools. Independently untracked exactly the six authorized files with git rm --cached; verified every physical file remains and every ignore pattern still matches. ci-1, ci-2, and ci-3 remain unresolved. Neither reproduction nor verification ran. No commit, push, or new scratch files were created

* Preserve interrupted auto-arm episodes by session identity

* no-mistakes(document): Clarify session-bound auto-arm failure documentation

* test: keep the exhausted-interruption fixture on one session

The integrated Stop driver starts a new fake-claude pid per Stop. Bind those
Stops to one recorded session id so a session-scoped interrupted episode can
still exhaust its budget and commit the attended alarm.

Co-authored-by: Kun Chen <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Kun Chen <[email protected]>

* feat(bin): choose a Claude account per ship or scout from a declared list (#8121)

* feat(bin): choose a Claude account per ship or scout from a declared list

Add an opt-in config/claude-accounts list of Claude config directories.
When it is present, every Claude ship or scout spawn names one declared
entry with --account; that entry passes the same root, raw-command, and
stripped-environment `claude auth status` refusals as c…
hoang-ross-dinh added a commit to hoang-ross-dinh/firstmate that referenced this pull request Nov 4, 2026
* origin/main: (38 commits)
  fix(bin): share timed background launch and isolate terminal stdin (kunchenguid#8099)
  fix: preserve late worker changes during teardown (kunchenguid#7932)
  feat(bin): add Hermes TUI worker adapter for tmux crewmates (kunchenguid#8084)
  fix(herdr): call an unresolvable launcher pane id stale instead of ambiguous (kunchenguid#7568)
  fix(bin): keep inactive reconcile from reporting terminal state while agent is live (kunchenguid#8085)
  fix(spawn): lease the Herdr task copy so a restart restores the worker there (kunchenguid#8052)
  test(tests): make anchored absence assertions real regex checks (kunchenguid#8017)
  fix(dispatch): parenthesise openai answer check for jq 1.8 (kunchenguid#8066)
  feat(pr-check): record reported PRs from done lines during the check sweep (kunchenguid#8086)
  fix: name the closing key in OPEN DECISIONS and keep the message when --resolve-key refuses (kunchenguid#3983)
  fix(bin): stop a stale terminal run outranking newer crew-state truth (kunchenguid#3701)
  fix(secondmate): respawn a local second mate on its recorded backend (kunchenguid#8082)
  fix: preserve piped stdin in timed commands (kunchenguid#8079)
  feat(bin): add opt-in native Codex Stop-hook park for watcher supervision (kunchenguid#7525)
  feat: auto-select hc inside Herdr app-projected terminals (kunchenguid#8060)
  fix(bin): keep authenticated PR polls armed across template updates and relaunches (kunchenguid#8069)
  fix(bin): settle contributions per owner and bound record reads (kunchenguid#8023)
  docs(harness-adapters): correct claude --setting-sources worker claim (kunchenguid#8076)
  feat: support Rex for remote second mates (kunchenguid#8058)
  test: resolve host tools in watcher lock fixtures (kunchenguid#8070)
  ...
kayis-rahman pushed a commit to kayis-rahman/firstmate that referenced this pull request Nov 8, 2026
* fix: recheck landed work after teardown process reap

* no-mistakes(review): Delay backlog close markers until post-reap safety proof

* no-mistakes(document): Correct stale pending-close publication references

* no-mistakes(document): Clarify initial teardown safety check ordering

* no-mistakes(document): Correct teardown ordering comments and stale retention documentation

---------

Co-authored-by: Kun Chen <[email protected]>
vinicius928e8r84 pushed a commit to vinicius928e8r84/firstmate that referenced this pull request Nov 11, 2026
* fix: recheck landed work after teardown process reap

* no-mistakes(review): Delay backlog close markers until post-reap safety proof

* no-mistakes(document): Correct stale pending-close publication references

* no-mistakes(document): Clarify initial teardown safety check ordering

* no-mistakes(document): Correct teardown ordering comments and stale retention documentation

---------

Co-authored-by: Kun Chen <[email protected]>
(cherry picked from commit 5b91acf)
kayis-rahman added a commit to kayis-rahman/firstmate that referenced this pull request Nov 14, 2026
* feat: monitor author-actionable pull request states (#8055)

* feat(pr-health): distinguish maintainer approval states

* feat(pr-health): alert authors on requested changes

* feat(pr-health): read owned PRs on GitHub notification events

Classify maintainer-gated CI from ACTION_REQUIRED check suites, which an
awaiting-approval fork PR shows while its rollup stays green, keep required
approval and author action as distinct once-per-commit states, and drive
reads from a conditional notifications feed with the poll as fallback.

* no-mistakes(review): Preserve same-timestamp notifications; regression added; focused test timed out

* no-mistakes(review): Record maintainer waits without waking tasks

* no-mistakes(review): Retain notification cursor until feed page completes

* no-mistakes(review): Retry truncated check suites and clarify wake behavior

* no-mistakes(review): Record pending reviewers without review decisions

* fix(pr-health): advance the notifications cursor on a full page

A full page already forces a full read of every owned PR in that pass, so
holding the cursor back only pinned a busy account to full sweeps; the
first read of such an account never saved a cursor at all.

* feat(pr-health): read owned PRs on GitHub notification events

Classify maintainer-gated CI from ACTION_REQUIRED check suites, which an
awaiting-approval fork PR shows while its rollup stays green, keep required
approval and author action as distinct once-per-commit states, and drive
reads from a conditional notifications feed with the poll as fallback.

* no-mistakes(review): Restore unrelated hc documentation changes

* no-mistakes(ci): Fixed ci-3 by keeping successful reads with `mergeable: null` pending, and ci-4 by persisting selected URLs as pending alongside the advanced notification cursor before reads. **ci-2 remains unresolved:** check-suite pagination is not implemented, so lists exceeding 100 suites may still be treated as unsettled. `bash tests/fm-pr-health.test.sh` timed out after 120 seconds; earlier cases passed, but verification is incomplete

* no-mistakes(ci): No code changes completed. The conflict check was corrected to distinguish `mergeable: null` from `false`, but check-suite pagination and its page-2 regression test remain unfinished. Verification was not run; this phase cannot be marked complete

* no-mistakes(ci): Fixed ci-2 in `bin/fm-pr-health.sh` and added regression coverage in `tests/fm-pr-health.test.sh`. Check suites now paginate up to 10 pages; exceeding that bound leaves the read unsettled. The patch also covers mergeability retry behavior and interrupted notification passes. `FM_LIVE=0 bash tests/fm-pr-health.test.sh` passed all 33 tests, and `bash bin/fm-lint.sh` passed. Left ci-1 unchanged

* fix(pr-health): read check suites in their own query

gh --paginate follows a single pageInfo, so nesting the paginated
check-suite connection in the PR query stopped it paging the check
contexts: a PR with more than 100 checks never finished a read and was
never classified.

* fix(pr-health): judge a full notifications page against the cursor

GitHub ignores since= on a conditional (If-Modified-Since) request and
answers with the newest page, so a busy account always got a full page and
every changed feed forced a full sweep. A page now forces the sweep only
when it is full and its oldest entry is still newer than the saved cursor.

* no-mistakes(lint): Fix ShellCheck empty cursor assignment

* no-mistakes(ci): Fixed the interruption regression test to terminate the captured main poll PID and assert that it exits unsuccessfully before verifying the event is retried. The interruption test passed. The full test script timed out after 120 seconds, though the tests reported before the timeout passed; `git diff --check` passed

* no-mistakes(ci): Updated `tests/fm-pr-health.test.sh` to run and terminate the main poll directly, and assert during the interrupted read that the advanced notification cursor and selected event are saved together. `FM_LIVE=0 bash tests/fm-pr-health.test.sh` passed (34/34); `git diff --check` passed

* test(pr-health): stop the main pass in the interruption test

The fake gh now stops the outermost poll process rather than a background
read shell or a wrapper subshell, and the test asserts that the advanced
cursor and the selected event were saved together before the reads. A PR
with more than a page of pending review requests is covered too; only
whether any request is pending matters, so the first page decides it.

* test(pr-health): interrupt the pass by its own PID

The interruption case starts the check in the background, whose PID is the
poll itself because the check execs it, and the fake gh stops that PID.
This drops the ps ancestry walk, which Git for Windows cannot run.

* no-mistakes(document): Update PR health monitor documentation

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Kun Chen <[email protected]>

* test: keep shared-captain spawn test off a live Herdr server (#8064)

The spawn convergence test cleared TMUX but inherited HERDR_ENV from a
Herdr pane, so backend auto-detection picked Herdr and created a real
workspace. Pin the spawn to the tmux backend the test stubs, shadow herdr
with a recording stub, and assert the spawn never calls it.

* fix(watch): surface timed-out checks on both timeout paths (#8068)

A registered check cut off at FM_CHECK_TIMEOUT before it printed
anything stayed silent: run_check_capture discarded the exit status,
so the timeout never reached a wake. On hosts without GNU timeout or
gtimeout, the perl fallback in owned-group mode also sent SIGKILL to
its own process group, so perl died with 137 before it could exit 124.

run_check_capture now appends "timed out after <seconds>s" to anything
the check printed before the cut. In owned-group mode the perl
fallback sends SIGKILL only to the check it forked; the watcher
already kills the rest of the group after its wait.

Refs #4338. Original fix by @kynjal26.

* test: resolve host tools in watcher lock fixtures (#8070)

* test: resolve host tools in watcher lock fixtures

The watcher-lock suite's three fake ln shims exec'd a hardcoded /bin/ln,
and two identity fixtures named their holder process through exec -a. Both
assume a host whose /bin carries coreutils and whose sleep still runs under
a rewritten argv[0]. On a host that keeps only sh in /bin, and whose sleep
is a multicall binary that dispatches on argv[0], the shim exits 127 and the
holder dies at once, so those cases fail on the fixture instead of on the
lock behavior they assert.

Each shim now receives the host's own ln path through FM_TEST_REAL_LN,
resolved with command -v as this repository's other fixtures already do,
and the two holders are python3 processes that carry the fixture path as an
argument, which keeps them reapable through the fixture root. CONTRIBUTING's
test-fixture rules name the pattern so a new shim does not reintroduce a
hardcoded /bin path.

Before, on a host without /bin/ln: "not ok - acquirer could not reclaim dead
steal owner (rc=8)" and, with the shims fixed but the holders unchanged,
"not ok - could not identify the fixture holder". After: the full suite is
58 ok with exit 0.

Provenance: ports 8a0b7b8b ("no-mistakes(test): Make watcher lock fixtures
portable across host tools"), which fixed one of the three shims plus both
holders. The other two shims are the same defect in the same file, so they
are carried here rather than left to fail on the same hosts.

* no-mistakes(test): test: resolve rm and ps in watcher lock fixtures

* no-mistakes(document): correct fixture-portability guidance in CONTRIBUTING

* feat: support Rex for remote second mates (#8058)

* feat(bin): support rex as a remote secondmate backend

Remote second mates no longer require herdr: --backend rex launches the
mate on the remote account's own persistent `rex server start` server in
that home's per-home 2ndmate-<id>-<hash> session, where its endpoint
survives every SSH disconnection the route depends on. Herdr stays the
default and the only backend a pre-Rex remote can verify.

- fm-spawn accepts --backend rex, threads it through the readiness gate
  and the remote control launch, and refuses a returned rex route that
  does not pin a host-local unix:// server and a session-matched
  <session-uuid>:<block-uuid> target; it records remote_backend,
  remote_rex_session_id, and remote_rex_server.
- fm-remote-secondmate-control.sh accepts {herdr, rex} per verb: rex
  endpoints require a host-local unix:// rex_server, state probes are
  pinned to the recorded server through the endpoint absence recheck
  (unproven reads stay unverified, never missing), route output reports
  the rex identity trio, and launch refuses an endpoint recorded on a
  different backend than the one requested.
- fm-remote-readiness-lib passes the selected backend to the doctor. A
  pre-Rex remote exits 2 on --backend, so an explicit herdr request
  retries bare while a rex request stays refused.
- fm-remote-doctor.sh gains --backend herdr|rex|any: rex verifies the
  CLI, client and server API revisions against the verified floor, and
  a persistent unix:// server (exit_empty=false); --fix may start or
  restart that server but never installs the CLI.
- fm-secondmate-liveness-lib re-checks an alive remote route's backend
  against the recorded remote_backend and reports drift instead of
  migrating; records without remote_backend stay herdr.
- tests share a stateful fake rex fixture (version, whoami, server
  lifecycle, sessions/windows/blocks, process/status/capture,
  send/send-key, events, agent-on-send) across the adapter, doctor,
  liveness, and lifecycle e2e suites.

Verified on disposable Linux (Apple container, Debian 12 aarch64, rex
0.1.0-preview.12, API rev 8): nested-shell foreground tracking and
input delivery, peer-vs-anonymous whoami, rex do/events, --exit-empty
vs persistent server durability, and session restore on identical
socket+state.

* fix(bin): keep rex on recovery, route keys, never stop rex

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test: assert exact rex fake state in new regressions

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test: request bootstrap relaunch facts in rex recovery check

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* no-mistakes(review): keep remote rex control plane from autostarting

* no-mistakes(document): Correct remote Rex documentation contracts

* no-mistakes(document): Point provisioning to remote backend contract

* no-mistakes(lint): Silence intentional deferred expansion lint warning

* no-mistakes(ci): Diagnosed Full suite failure as serial shard 9 exceeding its 30-minute cap. Updated the expanded remote lifecycle test’s measured scheduling weight and increased serial shards from 10 to 11, preserving timeouts and complete coverage. Coverage guard, runner and workflow contract tests, actionlint, source-aware ShellCheck, and diff checks passed. Hosted CI rerun remains for the outer executor

* no-mistakes(ci): Fixed fm-on’s stale Herdr-specific test assumptions by explicitly selecting Herdr in both fixtures, and refreshed the entrypoint’s stale doctor bootstrap hash. Reproduced both failures before fixing. fm-on and remote-doctor behavior suites and git diff --check pass locally. Full suite failure was downstream of the failing shard; hosted CI rerun remains for the outer executor

* no-mistakes(ci): Fixed both findings: Rex retirement now refuses block close and home deletion unless the answering server matches the recorded endpoint; readiness reads whoami once and requires explicit boolean exit_empty=false. Refreshed the doctor bootstrap digest. Reproduced both regressions before fixing. Doctor, full remote lifecycle, entrypoint tests, targeted ShellCheck, and diff checks pass

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>

* docs(harness-adapters): correct claude --setting-sources worker claim (#8076)

* docs(harness-adapters): correct claude --setting-sources worker claim

* no-mistakes(review): Correct sibling setting-sources claim in fm-claude-trust.sh comment

* no-mistakes(document): Rewrap corrected setting-sources comment in fm-claude-trust.sh

* fix(bin): settle contributions per owner and bound record reads (#8023)

* fix(contributions): keep maintainer-comment polls inside the check timeout

In a home with a few hundred contribution records, the contribution poll
spent most of the watcher's 30-second check bound on local bookkeeping
before its forge budget started: three jq processes per saved record file
plus several per already-final URL. The watcher killed the poll before it
read most open PRs, so a maintainer comment on an open PR could wait many
hours, or never, for its wake. The PR health monitor had the same cost in
its enrollment step: it re-enrolled every owned pair on each pass and
saved nothing until the end, so a killed pass never converged and a PR on
a later task branch was never enrolled.

- read_saved validates every record in one jq process and keeps the
  per-file path only to count unreadable records.
- poll skips final URLs that every owner already holds error-free, with
  one jq pass deciding settled, final and live URLs.
- owned reports the tasks holding a durable record for each URL, and the
  PR health monitor skips enrolling pairs that already have one, so a pass
  cut short still makes durable progress.

* no-mistakes(review): Isolate record validation errors per file in one jq

* no-mistakes(review): Read each record file whole to avoid joining

* no-mistakes(ci): Fixed ci-2: read_saved in bin/fm-contributions.sh now validates records in bounded jq batches (FM_CONTRIBUTIONS_READ_BATCH, default 100) instead of one jq with every record path, so a long-lived home cannot hit the argument-length limit. Batch results are merged; malformed-record, task-identity, no-trailing-newline behavior and the per-file unreadable count are unchanged. Added test_records_beyond_one_read_batch_are_all_read (5 records, batch 2, jq wrapper rejecting more than 2 record files); it fails on the old code and passes now. The full contributions suite passed before the wrapper was added. I re-ran only the new test afterwards. ci-1 (Full suite) is the maintainer full-ci label gate, so no change was made for it. I did not reply on the review thread

* no-mistakes(review): Hard-code contributions read batch at 100

* no-mistakes(lint): Silence ShellCheck SC2016 in contributions test

* fix(bin): keep authenticated PR polls armed across template updates and relaunches (#8069)

* fix(pr-lib): preserve authenticated PR polls across updates and relaunches

An armed merge poll binds to the hashes and file objects it was registered
with, so a repository template update no longer invalidates it. Validation
previously required the published check to be byte-identical to the current
bin/fm-pr-poll.sh, which an update or a control relaunch silently broke even
though the watcher executes the current repository poll with validated data
and never executes the registered state-file bytes.

Accept control_relaunch_tx among the metadata fields that may follow the PR
identity, and pin both behaviours in the security suite: an older registered
generation still detects its merge without executing sidecar code, and forged
bytes or forged trailing metadata are refused.

* no-mistakes(document): Align poll-registration docs with hash-bound validation

* no-mistakes(ci): Addressed the selected Greptile finding (ci-2) in tests/fm-pr-check-security.test.sh:3474 (test_registered_poll_survives_template_update_and_relaunch). Problem: for the template-update and combined scenarios, the "historical generation" fixture was bin/fm-pr-poll.sh with a marker line appended after the poll's unconditional exit, so the marker was unreachable and the copy still performed the same gh call. Both the marker-absence and gh-call assertions could therefore pass even if the watcher had executed the registered bytes instead of dispatching the current repository poll. Invariant: the historical registered check bytes are never executed; only the current repository poll runs, and it must be the sole source of the merge result and the sole forge call. Places this must hold: the template-update scenario, the combined (template-update + control_relaunch_tx) scenario, and the relaunch-only scenario (which legitimately has byte-identical check bytes). Fix: for non-relaunch scenarios the fixture is now a self-contained stub whose whole body is reachable — it writes the sidecar marker file and prints the distinct line `historical-generation`, and never touches gh. The relaunch scenario keeps the unchanged cp of the current poll as before. No existing assertion was weakened or changed: marker absence, `task-a.check.sh: merged`, the `pr view ... --json state` gh log entry, poll retirement, and forged-check refusal all remain. Verification (FM_TEST_BASE_PATH=/run/current-system/sw/bin, required on this NixOS host because mkdir is not under /usr/bin): full `bash tests/fm-pr-check-security.test.sh` passes with no `not ok` lines, including the registered-generations case; `bash -n` and `shellcheck -S warning` pass on the file. Negative control: temporarily patching bin/fm-watch.sh to execute the registered check bytes made the same test fail, then the patch was reverted (git status shows only the test-file change). ci-1 (Full suite) was marked ignore by the human decision and its suite passes locally

* no-mistakes(test): Prove live that template-update polls stay armed and keep their merge wake

* feat: auto-select hc inside Herdr app-projected terminals (#8060)

* feat(hc): auto-detect the Herdr app signals for the hc backend

Stage 3 of Herdr Core support: a Firstmate running inside the Herdr app
now selects the hc backend automatically, while classic Herdr TUI,
nested tmux, and bare hc terminals keep their existing verdicts.

Two app-owned signals, checked after every other surface marker:

- app-terminal: the process's own HC_TERMINAL_ID carries a non-empty
  herdr.space label in its core's record - the exact condition the app
  projects a terminal into its window. An app terminal's env is
  deliberately identical to any other hc terminal's (the core rewrites
  the app's TERM_PROGRAM=herdr claim to ghostty), so the claim is read
  from the record via `hc get`, gated by a live unix-connect probe
  because `hc` autostarts a core on contact with a missing socket.
- app-window: a live herdr-app.sock under the resolved app home
  (HERDR_APP_HOME, else XDG_CONFIG_HOME/herdr-app, else ~/.config),
  probed by an actual unix connect - the app's own liveness rule. The
  app is never launched and the core is never contacted for it.

Both require a usable hc toolchain (executable FM_HC_BIN or a
self-identifying herdr-core/hc on PATH, plus jq); a live window without
one records app-window-unusable and fm_backend_name prints a notice
naming the missing piece instead of switching. Explicit --backend,
FM_BACKEND, and config/backend always win; auto-detected hc prints a
loud opt-out notice and meta records backend_detect=app-terminal or
app-window alongside the existing herdr.space/herdr.tab presentation
labels.

Supervisor-endpoint discovery resolves an hc terminal to
<session>:<address> and backend hc so the away daemon fails loudly at
its supported-backend check instead of silently steering firstmate:0
tmux; full hc away support stays out of scope.

Verified against herdr-app 0.1.11 source/binary and an isolated hc
0.1.14 lab session (docs/verification/runtime-backends.md); a real
app window's socket and in-window label display remain unverified.

* no-mistakes(review): Bind hc auto-detection to the live spawn core

* no-mistakes(document): Correct hc selection and supervisor documentation

* fix(hc): gate app auto-detection on the adapter's verified core version

Greptile on PR #8060: fm_backend_detect_hc_usable accepted any
self-identifying 'hc x.y.z', but the adapter's container gate requires
FM_BACKEND_HC_MIN_VERSION (0.1.14). A live app window or terminal beside
an older core would auto-select hc, then have the spawn abort at the
version check - breaking an otherwise usable default spawn.

Detection now runs the adapter's own fm_backend_hc_version_check through
fm_backend_source (the same source path spawn and the bootstrap tool
check use), so an auto-selection can never resolve a binary the spawn
would refuse. The duplicated detection-side bin resolver is folded into
the adapter's fm_backend_hc_bin, and the unusable notices name the
verified minimum. A below-floor binary reports app-terminal-unusable or
app-window-unusable, covered by new fake-version assertions.

* no-mistakes(review): Make app-detect negative tests reject detection

* no-mistakes(document): Point hc metadata guidance to its owner

* fix: drop the app-window signal from hc auto-detection

The live real-Herdr-app exercise proved app-window cannot distinguish
"firstmate inside an app terminal" from "the app is open somewhere on
this host": marker-less bare processes selected hc solely because a
window existed, binding whatever core the spawn would reach. The
app-terminal signal (this terminal's own herdr.space label on the
spawn-reachable core) is the only claim that actually places the
process inside the app, so it is now the sole auto-select signal.
A marker-less process near a live window resolves the default backend
silently; explicit --backend/FM_BACKEND/config selection is unchanged.

* no-mistakes(document): Correct hc single-signal documentation

* feat(bin): add opt-in native Codex Stop-hook park for watcher supervision (#7525)

* Park verified native Codex supervision outside the model

* Document native Codex park verification and fallback

* no-mistakes(review): Extend Codex park startup grace to ten seconds

* no-mistakes(review): Document ten-second Codex park startup grace rationale

* no-mistakes(document): Name Codex native park in supervision host header

* no-mistakes(document): Add native Codex park script to scripts inventory

* Gate native Codex park behind config/codex-stop-park and cover it with behavioral tests

The native Codex Stop park now runs only in a home that opts in with
config/codex-stop-park; without it the session start, the synchronous
guard, and the asynchronous Stop hook behave as before the park existed
and the foreground checkpoint stays the default. A fixture-driven suite
with a fake codex covers the opt-in and version gates, the single-flight
claim, the fallback latch on a failed queue delivery or repeated arm
failure, the owner-gone watcher exit, and the retained quiet boundary.

* ci: add a tenth portable serial shard for the Codex stop-park suite

* no-mistakes(document): Point Codex park verification record at behavioral suite

* ci: retrigger checks

* Revert the tenth portable serial shard (added by #7838)

* no-mistakes(ci): I fixed both Greptile findings (ci-1, ci-2) with the small changes you asked for. No new state, subsystem or protocol change. The changes are not committed, so there is no Co-Authored-By trailer anywhere. **ci-1: a woken turn could lose its rearm (`bin/fm-codex-stop-park.sh`)** - Rule that must hold: when a registered session that still needs supervision hits Stop, a park must end up rearmed. A delivering park that still holds the claim must not make the next hook give up. - The only place that gives up is the claim acquisition in the async Stop hook. `--guard` already accepts a recent delivered record, so it needed no change. - Fix: if acquiring the claim fails, the hook reads the holder pid that the lock library reports. It checks that `.codex-park.json` shows this session, outcome `delivered` and that same pid, and that the pid is alive. Only then does it poll for up to 3 seconds (30 × 0.1 s) until `CLAIM` is gone, and retry the acquire once. Any other busy claim still does the old `exit 0`, so the single-flight case behaves as before. **ci-2: compaction skipped after a quiet boundary (`bin/fm-supervision-host.sh`)** - Rule that must hold: when the park clock restarts, every value measured on that clock restarts with it. `WARM_COMPACT_LAST_TICK` is the only such value. - Fix: one line, `WARM_COMPACT_LAST_TICK=-1`, in the Codex model-free quiet-boundary branch of `boundary_reached`. **Tests (`tests/fm-codex-stop-park.test.sh`)** - New case `test_stop_rearms_after_a_delivering_park_releases_its_claim`: a helper process holds the claim with a delivered record that names it, and releases it after 1 s. The Stop hook must wait, arm once, deliver one wake with no recovery notice, and leave a record that belongs to the new park. - Extended `test_host_quiet_boundary_retains_the_watcher` to use `config/warm-compact`, `FM_WARM_COMPACT_TICK=2` (equal to the 2 s park interval) and a stub engine that fails. The engine record is only written after the first quiet boundary, so compaction (`warm-compact engine failed` in the log, `/compact` passed to the stub) can only happen if the tick runs on the restarted clock. The watcher-retention checks still apply, now across three boundaries. - Mutation checks: with ci-1 reverted, the suite fails ("must rearm … expected '1', got '0'"). With ci-2 reverted, it fails with no warm-compact line in the log. I restored both fixes after each check. **Verification** - The whole suite passes (8 of 8). - `shellcheck -x` is clean on all three files. - `bin/fm-test-run.sh --check-coverage` passes: `FM_TEST_COVERAGE ok`, serial_max_ms=1140457 against a 1200000 budget, with 10 serial shards in the current tree. - Measured cost went up by about 3–4 s: three local runs took 25.6 s, 26.8 s and 24.8 s, against about 22 s recorded earlier. That is still under the 30000 ms hint, so I left the hint as it is

* no-mistakes(ci): Fixed the remaining ci-1 gap: a woken turn that reaches Stop while the earlier park is still sending its wake now waits for that park to release the claim, then rearms. Before, it gave up and left no watcher. The changes are not committed. What had to hold: when a registered session that still needs supervision hits Stop, a park must end up rearmed. That depends on two places: the record the park writes while it sends a wake, and the check that decides whether to wait when the claim is busy. Changes in bin/fm-codex-stop-park.sh: 1. Timeout constant: the literal 20 in deliver's fm_run_timed is now DELIVERY_TIMEOUT=20. The busy-claim wait is derived from it: (DELIVERY_TIMEOUT + 5) * 10 polls of 0.1 s, about 25 s. A comment names the constant. 2. New outcome before sending: the wake path now writes `record delivering` just before deliver. Every way out of it already overwrites that: success writes delivered, failure writes delivery-failed, HUP/INT/TERM write interrupted. 3. Wait check: the busy-claim check now accepts delivering or delivered, still for the same session and holder pid, and still only if that pid is alive. 4. One addition not asked for: delivering is added to the outcomes that trigger the recovery notice (with waiting, arming and interrupted). Before this change, a park killed with SIGKILL mid-send left waiting behind and the next park sent a recovery notice. Without this word that notice would silently stop. --guard and the claim model are unchanged. Test: the existing case in tests/fm-codex-stop-park.test.sh now takes two arguments: the outcome the holder records and how long it holds the claim. The holder then records delivered and releases, as a real park does. The suite runs it as `delivered 1` (old case) and `delivering 4` (new case, over 3 s and under the 25 s bound). Both require the Stop hook to arm exactly once, send one wake with no recovery notice, and leave a record that belongs to the new park. Mutation checks: - With the wait check set back to delivered only, the new case fails ("must rearm ... expected '1', got '0'"); fix restored. - Removing the new `record delivering` line fails no test, because the test's holder writes its own record. The delivering recovery trigger also has no test. Verification: - shellcheck -x is clean on all three touched files. - One unexplained failure: the suite passed in 12 of 13 full runs (3 run in parallel). The failed run was a timing run with output discarded, so the failing case is unknown; it did not reproduce in 13 more runs. - Hint raised: measured runs took 29.8 s, 34.0 s and 34.7 s, over the 30000 ms hint, so the hint is now 35000 in bin/fm-test-run.sh. bin/fm-test-run.sh --check-coverage passes: serial_max_ms=1140951 against the 1200000 budget, 10 shards. - The commit-message and comment wording rules don't apply yet, since nothing is committed

* no-mistakes(review): Gate latched fallback on supervision need; fix shard doc

* no-mistakes(document): Align Codex Stop-guard docs with park behavior

* no-mistakes(document): Document latched-fallback Stop block in turn-end guard doc

* no-mistakes(ci): Fixed ci-2 and ci-3; ci-1 left untouched and no CI file changed. ci-2 (bin/fm-codex-stop-park.sh): added settle_idle, called at both idle decisions (top of arm loop and inner poll loop) when fm_supervision_needed turns false. If state/.wake-queue is non-empty it records delivering, calls the existing deliver path, then records delivered; on delivery failure it records delivery-failed, latches the fallback and exits 1. With an empty queue it records idle and exits as before. Away mode, lost session lock and unregistered session still exit idle without delivering. The single-flight claim, fallback latch and rearm path are unchanged. ci-3 (bin/fm-supervision-instructions.sh): the codex case of ordinary_wake_line now splits on CODEX_PARK. A parked session is told the Codex Stop hook owns watcher continuity (drain and handle the wake, do not arm another cycle). A non-park Codex session keeps the foreground-checkpoint line unchanged. The existing codex assertions are unchanged and still pass. Verification: tests/fm-codex-stop-park.test.sh and tests/fm-supervision-instructions.test.sh both exit 0. shellcheck -x -S warning is clean on both scripts. No new tests were added, because neither suite had a matching case. Neither the settle_idle delivery path nor the parked ordinary-wake line is exercised by those suites

* test: cover the idle settle delivery and the parked ordinary-wake line

* no-mistakes(document): Document final-result delivery when Codex park ends

---------

Co-authored-by: crewmate <crewmate@localhost>

* fix: preserve piped stdin in timed commands (#8079)

* fix(timeout): preserve stdin in background runners

Explicitly inherit stdin before backgrounding the bounded command so Bash
does not replace piped input with /dev/null. Cover inherited input and
pipeline functions across timeout, gtimeout, perl, and bash.

* chore(document): Document stdin preservation in timed runner

* fix(secondmate): respawn a local second mate on its recorded backend (#8082)

A dead local second mate was respawned through a fresh --secondmate spawn,
which re-read config/backend. With config/backend=hc that spawn was
refused, so a second mate whose Herdr pane died stayed down. The liveness
respawn now passes the backend the mate's record names, so a changed
config/backend only affects new spawns. Remote mates keep their host's
routing.

Tests: fm-secondmate-liveness passes, including a new pinned-backend case.

* fix(bin): stop a stale terminal run outranking newer crew-state truth (#3701)

* fix: stop a stale failed run outranking newer truth

bin/fm-crew-state.sh matched a no-mistakes run against the worktree's current
code identity, so it inherited whatever run last sat on that head. A terminal
failed or cancelled run then outranked every newer record: a declared pause, a
crew's own terminal done line, and even a run still in flight on the same
branch. That was not merely a misleading state line - the stale failure was
promoted into a durable terminal-outcome record and queued for captain
presentation, naming a pull request the current run had never opened.

Two independent fixes.

The reader now proves a terminal failure is current before reporting it. A
later run the pipeline's own ledger proves current answers instead; a later
self-declared pause or done in the status log answers instead where the
ledger's date proves the log was appended after the failed run began; and a
later run that cannot be bound here reads as unknown - history, but no proof of
the present. Nothing else may, so a stale working, needs-decision, or blocked
line still cannot mask a real failure, and with no ordering evidence at all the
failure stands. A terminal reading also publishes the pull request its own run
opened, or none when it opened none.

bin/fm-inactive-reconcile.sh no longer inherits either half of the claim. A
terminal outcome is built only when the crew's own last self-declared word does
not contradict it, in both directions, and its pull-request identity comes from
the same record as its state rather than from a separately recorded task PR.

bin/fm-nm-run-lib.sh keeps the one attribution owner: the supersession check
reuses its existing rules and adds only the branch's newest ledger row and the
one-directional reading of the ledger's date column.

* no-mistakes(review): Captain: fix terminal run and PR provenance

* no-mistakes(review): Captain: preserve newest terminal run provenance

* no-mistakes(review): Captain: consolidate terminal provenance and status snapshots

* no-mistakes(review): Captain: enforce precise terminal outcome provenance

* no-mistakes(document): Consolidate terminal-state documentation ownership

* test(crew-state): expect unknown for an unprovable live replacement

f5d7f5f2 (#4476) raised the attribution bar: the runs ledger carries no run
id, so a LIVE replacement cannot be proven current and the reader answers
unknown. That moves three cases from rule 2b's case (a) to its case (c),
which this branch already documents as the honest answer for a replacement
that cannot be bound here.

Only the state label changes. Every safety assertion is unchanged and still
passing: no false failed state surfaces, and no stale pull request is
published.

* no-mistakes(review): gate status-log supersession off the attributed run's failure

* no-mistakes(review): accept only ready-signal PRs from a status-log outcome

* no-mistakes(review): report unknown for an unbindable live replacement run

* no-mistakes(review): make ordering and gate regression tests non-vacuous

* no-mistakes(review): restore current-run shape for ordering regression tests

* no-mistakes(review): require ordered status line to be log's last line

* no-mistakes(review): share ledger row validation, match run heads both ways

* no-mistakes(review): require a terminal ledger row for status-log ordering

* no-mistakes(document): name shared ledger-row validity owner in architecture

* no-mistakes(review): let reader ordering evidence keep a failure reportable

* no-mistakes(review): establish crew-word ordering from the log alone

* no-mistakes(document): record proven-older crew word exception in architecture

* no-mistakes(review): remove status-log ordering rules from crew-state reader

* no-mistakes(review): let run-step terminal states outrank the crew's own word

* no-mistakes(review): state the narrowed corroboration rule in architecture doc

* no-mistakes(review): run rule 2b after the socket-down status-log override

* no-mistakes(review): name the ledger verdict's own run, document applied precedence

* no-mistakes(review): skip rule 2b on coarse path, restore scout PR guard

* no-mistakes(document): note scout PR exception in reconcile header contract

* no-mistakes(review): extend terminal-reading precedence to done readings

* no-mistakes(review): derive ledger status from the run record's status field

* no-mistakes(review): drop vacuous checks-passed test, record traced evidence

* no-mistakes(review): name the unbindable ledger row, not an earlier run

* no-mistakes(review): append run id as a field, keep PR without ledger row

* no-mistakes(document): document run-id field and corrected terminal PR rule

* no-mistakes(lint): quote keyword literals in terminal-state comparison (SC1010)

* Preserve cancellation as unknown in ledger precedence

* Align completed-run selection fixture PR identity

* no-mistakes(document): Align crew-state rule 2b comment with cancelled-as-unknown

* no-mistakes(ci): I fixed the Greptile finding (ci-1): crews in the main home that reported a GitLab or Gerrit review now keep the review link in their completion notice. I left the changes uncommitted in the worktree for no-mistakes to validate and publish to PR 3701. I made no other changes and did not rebase, push or touch history. The rule that was broken: a terminal outcome taken from the status log must carry the review URL that its own ready report names, for every forge the project supports. **What changed** - In `bin/fm-inactive-reconcile.sh`, `terminal_outcome_pr` no longer uses its own regex, which accepted only GitHub-style `/pull/<n>` URLs. It now takes the note, strips the leading `PR `, strips an optional ` checks green` or ` published for review` (the Gerrit ready shape), and passes what is left to the existing `fm_pr_url_parse` in `bin/fm-pr-lib.sh`. That library is already loaded through `fm-dod-lib.sh`. This means GitHub, GitLab merge requests, Forgejo and Gerrit URLs are all accepted. The function returns the parsed URL, still taken only from the state line itself. - The run-step path, the scout rule, the rule against claiming URLs that are only mentioned in prose, and the cancellation-as-unknown and terminal-identity rules are unchanged. - I updated the comment above the function, because it said the rule was the same as `pr_for_task`'s, which is no longer true. **One stricter result you should know about:** a GitHub URL must now pass the shared parser's host check. It must be `github.com` or a host listed in the `github-hosts` config, and it must use `https`. For this reason I changed one fixture in `test_status_log_sourced_outcome_keeps_its_own_pr` from `https://example.test/.../pull/7` to `https://github.com/.../pull/7`. No other test depended on the old pattern. **Test:** I added one regression test, `test_status_log_outcome_keeps_gitlab_and_gerrit_reviews`, in `tests/fm-inactive-reconcile.test.sh`. It uses `PR https://gitlab.example/group/sub/project/-/merge_requests/8 checks green` and `PR https://gerrit.example/c/group/project/+/4201 published for review`. **Verification** - With the old `bin/fm-inactive-reconcile.sh`, the new test fails ("the gitlab terminal outcome dropped its review link"). - With the fix, `bash tests/fm-inactive-reconcile.test.sh` passes completely ("all inactive reconciliation tests passed"). - `shellcheck -x` reports no problems in either file. **Not changed, as you instructed:** `pr_for_task`, the ledger-first fallback in the same file, also accepts only `/pull/` URLs. That is the same problem in a sibling function. If a reviewer reports it, you said to stop and report rather than run another repair round

* fix: name the closing key in OPEN DECISIONS and keep the message when --resolve-key refuses (#3983)

* fix(supervision): make the OPEN DECISIONS listing name the key that closes it

An operator answering a listed decision runs the command the listing itself
advises, and that command refused - discarding the steer with it.

The two folds never disagreed. Both the whole-file fold and fm-send's resolver
read the same status_open_decisions rule, and both correctly keyed
`blocked: axi run hung ... [key=no-mistakes-start]` as `default`: the key
grammar states a key before the colon or at the head of the note, so a token
trailing a summary is prose. The reader that was wrong is the third one, the
drain's OPEN DECISIONS renderer. It suppressed `[key=default]` and printed the
note verbatim, so the only bracket token a reader could see on such an entry
was the one that is NOT the key - and the entry named a key it had not folded.

Every entry now states its folded key, `default` included, so the key the
listing shows is the key its advised command closes.

An unresolvable key still refuses rather than delivering: an answer this send
cannot close would leave the decision open behind an answer the operator
believes settled it. The refusal no longer costs the message instead - it
diagnoses a key that is only mentioned inside an open decision's note, names
the keys that are actually open, and prints the resend commands with the
message quoted back verbatim.

* no-mistakes(review): Remove automatic key selection from resend advice

* no-mistakes(document): Clarify operator key selection in resend documentation

* fix(send): carry the caller's routing context into every printed resend

A refused --resolve-key preserves the operator's message by printing a
resend command, but the command could not run: it reused $0 and dropped
the routing environment. A one-shot "FM_HOME=<home> bin/fm-send.sh ..."
exports nothing to the next command, and a relative $0 is valid only from
the directory that invocation ran in, so a copied line resolved to another
home's state, to no script at all, or refused with FM_HOME unset - and the
preserved message still never reached the worker.

The unconfirmed-remote retry path already solved this. Both printed resend
paths now share that one statement of it: the absolute home always, the
state override only when this invocation was given one, and this script's
absolute path.

Covered by a test that invokes fm-send through a relative path with a
one-shot FM_HOME, then runs what it printed from a different directory
with nothing supplied - what an operator copying the line actually does.

* no-mistakes(review): remove unprovable decoy-key diagnosis, quote resend key placeholder

* no-mistakes(review): scope empty open-set claim to status file, always offer keyed resend

* no-mistakes(review): Keep already-accepted keys in the refused-key resend

* no-mistakes(review): Check every resolve key before refusing, keep order

* no-mistakes(document): Reflow fm-send resolve-key refusal header comment

* feat(pr-check): record reported PRs from done lines during the check sweep (#8086)

* fix(pr-check): record every PR a task reports in a done line

Merge and health monitoring of a task's PR began only when the supervisor
ran fm-pr-check.sh by hand on the ready signal. When that step was missed,
for example on a rebase of an existing PR whose done line did not use the
canonical wording, the task kept no pr= and no merge poll, so failing
checks and maintainer requests on that PR went unnoticed.

fm-pr-check.sh scan now records each task whose newest done line naming a
supported PR URL ("PR <url>" anywhere in the note) has no pr= yet, through
the ordinary registration path, so every refusal still applies. The
watcher runs it at the start of each check sweep. A refusal is reported
once per task and PR as a check: pr-register: wake and retried silently on
later sweeps; teardown removes its marker.

* no-mistakes(review): Scan new PR reports before refused retries

* no-mistakes(review): Rotate scan start so hung PR registrations cannot starve

* no-mistakes(review): Resume PR scan after last attempted task

* no-mistakes(lint): Fix SC1007 in fm-pr-check.sh candidates declaration

* no-mistakes(ci): Fixed ci-2 and ci-4 in bin/fm-pr-check.sh. ci-2: the scan now treats a task whose pr= equals the reported done-line URL but has no valid published poll as unregistered, so a later sweep republishes the poll. ci-4: scan-driven registrations run with FM_PR_CHECK_SCAN=1 and, under the metadata lock, exit 0 without writing if pr= is now set to a different URL; manual registration is unchanged. Added two tests in tests/fm-pr-check-security.test.sh (test_scan_publishes_a_missing_poll_for_a_recorded_pr, test_scan_does_not_overwrite_a_pr_recorded_meanwhile), and a configurable FM_TEST_GH_SLOW_SECONDS in the slow gh stub. Both new tests fail without the fix and pass with it; the four existing scan tests still pass; shellcheck shows only SC1091 info notes. The full test file aborts earlier on this machine at an unrelated test (GNU stat '%Lp' errors / flaky), so I ran the scan tests as a separate set. ci-1 and ci-3 are declined, with no code change; the ci-3 known-limit line (a refusal notice can be lost if the watcher stops between writing the refusal marker and queueing the wake) still needs to go into the PR description, which I cannot edit from here. Known tradeoff: a merged task whose poll was retired but whose pr= and done line still match would look unregistered and be re-armed until teardown

* no-mistakes(ci): Part (1) is fixed. The scan in bin/fm-pr-check.sh now skips a task that has state/<id>.pr-poll-merge-notified or state/<id>.pr-poll-retirement. A merged task's retired poll is no longer re-armed. I added test_scan_does_not_rearm_a_retired_merged_poll to tests/fm-pr-check-security.test.sh. With the exclusion removed, the test fails ("the scan re-armed the poll of a merged task"). With it restored, the test passes. The existing missing-poll and concurrent-PR scan tests also pass. I ran only these three tests, because the full file is slow and was already known to abort early on this machine at an unrelated stat test. shellcheck -S warning is clean. Part (2) needed no change. The scan-only recheck already sits inside the META_LOCK section, right after the lock is taken and the metadata file is re-validated, before the meta rewrite. It exits 0 without writing or publishing when pr= is a different URL. The ci-4 test still passes

* no-mistakes(ci): Fixed ci-2. The scan in bin/fm-pr-check.sh now skips a task only when its merge-notified marker or poll retirement receipt names the same PR as the recorded pr=. A new helper, pr_check_pr_retired, does the check. An older PR's marker no longer hides a newer recorded pr= whose poll is missing. Tests, in tests/fm-pr-check-security.test.sh: - Added test_scan_arms_a_replacement_pr_despite_an_old_merge_marker. It uses an old PR 7 merge marker and a recorded pr=9 with no poll. The scan must arm the poll. With the old unconditional skip restored, the test fails ("an older PR's merge marker hid the replacement PR's missing poll"). With the fix, it passes. - test_scan_does_not_rearm_a_retired_merged_poll now writes a valid marker for the same PR. The old marker was a bare version line, which the new check correctly rejects. This test still passes. - The other scan tests pass: publishes_a_missing_poll and does_not_overwrite_a_pr_recorded_meanwhile. - I ran only the four scan tests, because the full file is slow and aborts early on an unrelated stat test on this machine. shellcheck -S warning is clean. ci-1 is declined: only the maintainer full-ci label gate failed. I made no PR description edits, because I cannot edit the PR from here. The earlier requested statements still need to go in the description: the #8023 (comment-wake) coverage of the waiting-author comment case, and the refusal-notice known limit

* feat(pr-check): run the done-line PR scan only with config/pr-register-scan

The watcher check sweep runs bin/fm-pr-check.sh scan only when the
home opts in with the config/pr-register-scan presence flag. With the
flag absent, the sweep is unchanged from before the scan existed.
The watcher test covers both settings.

* fix(dispatch): parenthesise openai answer check for jq 1.8 (#8066)

Co-authored-by: yeti <yeti@alps>

* test(tests): make anchored absence assertions real regex checks (#8017)

* test: give anchored absence assertions a regex that can match

assert_grep and assert_no_grep are fixed-string greps. An anchored pattern
handed to them searches for a literal caret, which no line can contain, so
every anchored assert_no_grep passed no matter what the file held.

Eighteen call sites across six suites asserted their absence that way, so
they were silently checking nothing: the merge-local readiness snapshot,
the public-followup request and platform links, the secondmate backend and
harness records, the restart literal-stop path, the delivery mode and yolo
fields, and the remote-doctor launchctl calls.

Add assert_regex and assert_no_regex for patterns that describe a line
rather than a literal, and convert those sites. The remote-doctor
alternation becomes a real ERE group instead of a fixed string containing
backslash-pipes.

The three suites that run on this host pass unchanged: merge-local 8,
task-delivery 34, public-followup 90. The other three fail identically on
unmodified main here because their fixtures pin a PATH without tr, sed, or
head; that is environmental and unrelated.

* no-mistakes(review): Fix regex absence errors and interactive label guard

* test(assertions): name lib.sh for ShellCheck source following

* no-mistakes(test): Fix vacuous anchored absence guard in fm-pr-merge help test

* no-mistakes(review): Restore pre-existing help assertion exactly

* no-mistakes(document): Document new assertion suite coverage in its header comment

* fix(spawn): lease the Herdr task copy so a restart restores the worker there (#8052)

* fix(spawn): lease the Herdr task copy so a restart restores the worker there

* test(spawn): align Herdr abort fixture with lease failure

* no-mistakes(review): Return Herdr lease when projected abort closes task pane

* no-mistakes(document): Note Herdr spawns no longer leave nested treehouse shell

* no-mistakes(ci): ci-2 (Greptile, bin/backends/herdr.sh): the invariant is that the projected abort cleanup must report a closed endpoint exactly when the task pane is confirmed gone. fm_backend_herdr_projection_close_pane_focus_preserving can confirm the close and then return 2 only because focus restoration failed. It can also return 2 or 1 after a close that did not happen. The only place where this result becomes SPAWN_ENDPOINT_CLOSED is fm_backend_herdr_projection_cleanup_exact; its single caller is bin/fm-spawn.sh:1691. I fixed it at that shared boundary. When the close call fails, the function now checks the exact pane with the existing fm_backend_herdr_pane_presence_state, and it reports success only when the result is `dead` (pane_not_found). It does not treat a return value of 2 as closed, so a present or unknown pane keeps the lease. I also updated the comment above the function. Tests (tests/fm-backend-herdr.test.sh, test_projection_cleanup_exact_succeeds_only_when_the_task_pane_closed): I added two behavioural cases that run the real cleanup and the real presence classifier against a stubbed herdr CLI response. (1) The close returns 2 and the pane get returns pane_not_found: the result is rc=0, so the endpoint is closed. (2) The close returns 2 and the pane get still shows the pane: the result is rc=1. I also stubbed the CLI in the existing refused-close case so that it cannot reach a real herdr. Before the fix, the confirmed-close-then-failed-restore case failed ("got 'CLOSED w1:p1;rc=1'"). After the fix, the full tests/fm-backend-herdr.test.sh and tests/fm-spawn-herdr-lease.test.sh pass. shellcheck -S warning is clean on both changed files. ci-1 (Full suite): this is not a code defect. The job stopped at the label gate with FM_CI_FULL=false and FM_CI_LANES_FAILED=false, so no lane failed. I did not change code for it. I did not re-run the workflow: this phase must not control CI, and a re-run cannot pass until a maintainer adds the full-ci label to PR #8052, because the gate reads that label. This is still an external label requirement. Note: a temporary copy of the fixed herdr.sh remains at /tmp/herdr.fixed, because my clean-up command was denied by permissions

* no-mistakes(review): Release or name Herdr lease after post-launch rollback

* no-mistakes(review): Return Herdr lease only when the pane is confirmed gone

* no-mistakes(review): Keep dirty Herdr slots leased after failed spawns

* no-mistakes(test): Count Herdr pane-death removal in concurrent abort ordering check

* no-mistakes(document): Clarify Herdr aborted-spawn lease return condition

* test(herdr): allow explicit lab session for presentation e2e

* fix(teardown): close Herdr pane before returning its lease

* no-mistakes(review): Remove inherited HERDR_LAB_SESSION override from presentation e2e

* no-mistakes(document): Document Herdr teardown closing pane before returning lease

* fix(teardown): retain leased copy when Herdr close is refused

* fix(bin): keep inactive reconcile from reporting terminal state while agent is live (#8085)

* fix(inactive-reconcile): withhold terminal outcome while the agent is alive

Fixes #6553

* no-mistakes(review): Bound liveness read; withhold only busy or relaunched agents

* no-mistakes(review): Judge incarnation by spawn epoch; use remaining budget

* no-mistakes(document): Document live-agent withholding in architecture scan rule

* no-mistakes(lint): Fix ShellCheck SC2143 and SC2016 findings

* no-mistakes(ci): ci-2 and ci-3 are fixed in tests/fm-inactive-reconcile.test.sh. ci-1 (Full suite) needs no code change, as the captain decided. I ran only the new test in isolation, plus a mutation check; the full test file did not pass in this environment (details at the end). - **ci-2 (macOS sed):** `arm_claude_busy` no longer uses `sed -i`. It writes the edited meta to `<id>.meta.new` and moves it over the original, so it works with both GNU and macOS sed. - **ci-3 (liveness-read timeout):** I added `test_stalled_liveness_read_is_bounded_and_scan_progresses`. - The fake `fm-crew-state.sh` sleeps 1s, then returns `failed` for child `a`. - The fake `tmux` then stalls for 30s, which stalls the liveness read. - With a 2s scan budget, the scan must finish within 4s. - After the stall is cleared, the next scan must still reach child `b`. - **Mutation check:** I removed `fm_run_timed "$timeout"` from the liveness read at `bin/fm-inactive-reconcile.sh:517`. The new test then failed, so it catches a lost timeout. I restored the file afterwards. - **Full test file:** it did not pass in this environment, because the existing `test_stalled_state_read_is_bounded_and_scan_progresses` failed on timing. In one run it exceeded its 3s elapsed bound (4s); in another, its next scan did not reach child `b`. I never ran it against `HEAD` alone; this PR changed that file only by adding the new test and the sed fix. - **Not checked:** I did not investigate why that existing test fails here

* fix(herdr): call an unresolvable launcher pane id stale instead of ambiguous (#7568)

* fix(herdr): name a stale launcher pane id as gone instead of ambiguous

The launcher pane id a shell inherits outlives the pane itself.
When herdr no longer knows that id, `pane get` answers with whatever
pane it still has, the exact-id filter in
fm_backend_herdr_launcher_identity keeps nothing, and the guard
refused with "returned an ambiguous tab or workspace identity".
There is no ambiguity to report: the pane does not exist any more, so
the id is stale.

The refusal now names the stale pane id, says the pane no longer
exists in the session, and names HERDR_PANE_ID, HERDR_TAB_ID and
HERDR_WORKSPACE_ID as the values to refresh.
The return codes, the refusal behavior, the identity-matching logic
and the spawn behavior are unchanged, and no other error path changed.

tests/fm-backend-herdr.test.sh covers both shapes of this path: a pane
id herdr answers with a different pane, and a pane record that names
no tab.

* fix(herdr): stale launcher pane message covers the no-tab shape too

The empty-tab shape is a pane record that still answers but names no tab,
so 'no longer exists' was not literally true for it. The refusal now says
the pane is stale: it no longer exists or names no tab or workspace in the
session. Return codes, refusal and identity matching are unchanged.

* no-mistakes(review): Reword unreadable launcher pane error as stale

* no-mistakes(document): Document stale launcher pane refusal in herdr backend docs

* fix(herdr): keep the could-not-be-read wording when the launcher pane get fails

* no-mistakes(test): docs(herdr): describe destroyed panes as unreadable, not stale

* feat(bin): add Hermes TUI worker adapter for tmux crewmates (#8084)

* feat(bin): add verified Hermes TUI worker adapter

* no-mistakes(document): Document Hermes owner in tmux composer identity comment

* no-mistakes(ci): Fixed ci-4: a Hermes worker that stalls at setup or misses the readiness deadline is now stopped before its task record is removed. Rule that must hold: once the Hermes launch command has been sent, any failure exit from the Hermes readiness gate closes the launched endpoint first. Only after that may the abort trap (spawn_abort_cleanup) roll back a fresh spawn's record and retire its busy generation. Two exits in the gate broke this rule, and both are now fixed in bin/fm-spawn.sh: 1. **Readiness timeout:** after the existing error message, the gate now calls `rovo_endpoint_cleanup`. This is the same close step the rovo launch-then-confirm gate already uses: it calls the backend's kill (just the exact terminal on orca) and sets SPAWN_ENDPOINT_CLOSED. It runs before `exit 1`, so the window is closed while the record still exists. 2. **Failed Enter on the first-run decline:** this used to `exit 1` straight away. It now `break`s out of the poll loop, so it reaches the same close-then-exit path. The ordinary path is unchanged. A ready screen or a hook record sets HERMES_READY=1 and skips the cleanup. Regression test in tests/fm-hermes-harness.test.sh: a fake tmux shows a stalled provider-setup screen, and the test uses tiny poll settings (FM_HERMES_READY_POLLS=2, interval 0). The fake `kill-window` writes down whether the task's .meta file still exists at the moment it is called. The test asserts that the spawn fails with the Hermes diagnostic, that `kill-window` ran while the record was present, and that the fresh record was removed afterwards. I confirmed it fails without the fix ("missing: 'kill-window record=present'") and passes with it. It uses only throwaway fixtures and a generic `example` profile. Checks run: tests/fm-hermes-harness.test.sh and tests/fm-rovo-harness.test.sh both pass with 0 failures, shellcheck on both changed files is clean, and `bash -n` passes. Changes are left uncommitted so the pipeline can record them as their own fix commit, with no squash. ci-1, ci-2 and ci-3 were not touched, as instructed

* no-mistakes(ci): I fixed ci-3. If the stalled Hermes worker can't be closed, a failed spawn now keeps its task record, so supervision and teardown can still reach the worker. **What must always hold:** once the Hermes launch command has been sent, the spawn rollback may remove a fresh task record and its busy generation only after the launched endpoint has actually closed. The last round's ci-4 fix tried to close the pane first, but it ignored whether that close worked. The cleanup at exit (`spawn_abort_cleanup`) still saw `SPAWN_FRESH_COMMIT_PENDING=1` and removed the record anyway, leaving a possibly live Hermes worker with nothing pointing at it. **Fix** (`bin/fm-spawn.sh`, the Hermes readiness gate's failure exit): after `rovo_endpoint_cleanup`, if `SPAWN_ENDPOINT_CLOSED` is not 1, the gate clears `SPAWN_FRESH_COMMIT_PENDING`. It also prints a warning that the record is kept and the worker should be inspected and torn down. This uses the existing flag the abort cleanup already relies on, the same way other kept-record paths skip rollback. The readiness timeout and the failed-Enter exit from the first-run decline both reach this single exit, so the fix covers both. Nothing else changes: - When the close succeeds, the record is rolled back exactly as before (the earlier stalled-launch test still passes). - When Hermes becomes ready, this branch is skipped. - On a relaunch, `SPAWN_FRESH_COMMIT_PENDING` is already 0, so nothing changes there. I left the other harnesses' gates alone. Changing how they roll back would go beyond this finding. **New test** in `tests/fm-hermes-harness.test.sh`: a fake tmux shows a stalled provider-setup screen, and its `kill-window` can be made to fail (`FM_FAKE_HERMES_KILL_FAIL`). The test checks four things: - the spawn fails with the Hermes error; - a close was attempted while the record existed; - the kept-record warning is printed; - the `.meta` record survives and still has `hermes_profile=example`. It uses only throwaway fixtures and a generic `example` profile. Without the fix the test fails ("missing: 'task record is kept'"); with it, it passes. **Checks run:** - `tests/fm-hermes-harness.test.sh`: all cases pass, 0 failures. - `tests/fm-rovo-harness.test.sh`: passes. - `shellcheck` on both changed files: only the usual SC1091 info notes about sourced files not being followed (it was run without `-x`), no warnings. As instructed, I didn't touch ci-1 (the full-suite label gate maintainers apply) or ci-2 (stale). The changes are uncommitted so the pipeline can record them as their own fix commit, with no squash

* test: include Hermes process helper in partial-bin fixtures

* no-mistakes(review): Add Hermes process helper to remaining fm-harness fixtures

* fix: preserve late worker changes during teardown (#7932)

* fix: recheck landed work after teardown process reap

* no-mistakes(review): Delay backlog close markers until post-reap safety proof

* no-mistakes(document): Correct stale pending-close publication references

* no-mistakes(document): Clarify initial teardown safety check ordering

* no-mistakes(document): Correct teardown ordering comments and stale retention documentation

---------

Co-authored-by: Kun Chen <[email protected]>

* fix(bin): share timed background launch and isolate terminal stdin (#8099)

* fix(timeout): keep redirected stdin on backgrounded runners

Non-interactive bash assigns /dev/null to an async command, so the external
timeout and bash runners dropped a piped payload before it reached the
command. Restore that stdin with an explicit redirection, leave a terminal
or closed stdin on the old assignment, and cover every mechanism the host
can select.

* no-mistakes(test): Give terminal stdin /dev/null in timed background runs

* no-mistakes(ci): No new code change is needed. The fix for ci-1 is already in commit db61d47a, which is HEAD, and the working tree is clean. Greptile pointed out that the old fd 3 check could never fail: fm_run_timed ran inside a pipeline subshell while `echo still >&3` ran in the parent shell. The committed test now calls the runner directly, with stdin redirected from a file, in the same shell that then writes to fd 3. It covers the external-timeout mechanism when one is installed and always covers the bash override. It checks the exit status, that the fd 3 write landed, and that the payload came through. Following the driver's instructions, I kept that commit and did not rework it. I re-ran `bash tests/fm-timeout-lib.test.sh` and it exited 0 with every case passing. The Greptile check is still failing only because the earlier push to the PR hit a GitHub Internal Server Error and never landed. The test code is not the cause. Re-publishing the existing commit through the pipeline will resolve it, and that step belongs to the outer executor

* fix: isolate interrupted auto-arm failures by session (#7921)

* Bind interrupted auto-arm notices to their producing session

* no-mistakes(document): Document session-bound auto-arm interruption recovery

* no-mistakes(ci): Fixed all three lint-inventory expectations to exclude hidden scripts, matching the documented shell globs. Tier 2 test correction; production behavior was correct. fm-lint.test.sh passes, with four platform capability skips. Targeted ShellCheck and git diff --check pass

* no-mistakes(ci): Repair blocked: the command guard rejected test authoring as “Indirect command execution not allowed.” Stopped dependent work without switching tools. Independently untracked exactly the six authorized files with git rm --cached; verified every physical file remains and every ignore pattern still matches. ci-1, ci-2, and ci-3 remain unresolved. Neither reproduction nor verification ran. No commit, push, or new scratch files were created

* Preserve interrupted auto-arm episodes by session identity

* no-mistakes(document): Clarify session-bound auto-arm failure documentation

* test: keep the exhausted-interruption fixture on one session

The integrated Stop driver starts a new fake-claude pid per Stop. Bind those
Stops to one recorded session id so a session-scoped interrupted episode can
still exhaust its budget and commit the attended alarm.

Co-authored-by: Kun Chen <[email protected]>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Kun Chen <[email protected]>

* feat(bin): choose a Claude account per ship or scout from a declared list (#8121)

* feat(bin): choose a Claude account per ship or scout from a declared list

Add an opt-in config/claude-accounts list of Claude config directories.
When it is present, every Claude ship or scout spawn names one declared
entry with --account; that entry passes the same root, raw-command, and
stripped-environment `claude auth statu…
joergoss pushed a commit to joergoss/firstmate that referenced this pull request Nov 23, 2026
* fix: recheck landed work after teardown process reap

* no-mistakes(review): Delay backlog close markers until post-reap safety proof

* no-mistakes(document): Correct stale pending-close publication references

* no-mistakes(document): Clarify initial teardown safety check ordering

* no-mistakes(document): Correct teardown ordering comments and stale retention documentation

---------

Co-authored-by: Kun Chen <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

full-ci Maintainer go-ahead: run the full CI suite on this outside pull request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants