Skip to content

fix(bin): refuse teardown when a task's endpoint close fails - #4510

Merged
kunchenguid merged 5 commits into
kunchenguid:mainfrom
aminry:fm/fm-teardown-kill-failure-refusal-w8
Sep 15, 2026
Merged

kunchenguid merged 5 commits into
kunchenguid:mainfrom
aminry:fm/fm-teardown-kill-failure-refusal-w8

Conversation

@aminry

@aminry aminry commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Intent

bin/fm-teardown.sh discards the result of every fm_backend_kill call, so a kill that genuinely
failed is indistinguishable from one that succeeded. Teardown then continues past it, deletes the
task's durable records, returns its worktree, and reports the cleanup as completed.

All four call sites swallow both the stderr and the exit status:

2978: ( ... fm_backend_kill ... ) 2>/dev/null || true
2980: fm_backend_kill "$child_backend" ... 2>/dev/null || true
3316: [ -z "$T_ORCA" ] || fm_backend_kill "$BACKEND" ... 2>/dev/null || true
3394: fm_backend_kill "$BACKEND" "$T" ... 2>/dev/null || true

fm_backend_kill does report failure, including an explicit error: no kill implementation for backend '<name>' with a non-zero return. Both halves of that signal are dropped at every site.

The metadata teardown deletes is the only durable record of which endpoint belongs to the task, so
a swallowed kill failure does not merely leave a stray session behind, it strands one: nothing left
on disk names it. Meanwhile the operator is told the task was cleaned up.

The goal is that a kill which genuinely failed becomes the refusal teardown already knows how to
produce, before any destructive step, rather than a silent continue. AGENTS.md already makes
teardown the owner of the landed-work test and treats its refusal as a stop-and-investigate result,
and VISION's "delegation with a spine" is about refusing rather than reporting a success that did
not happen. This restores that promise rather than adding a new guarantee, so it applies by default
and is not placed behind a flag.

An endpoint that is already legitimately gone is not a failure and must keep completing silently.
Only a kill that genuinely could not do its job becomes a refusal, so ordinary cleanup of an
already-exited session is unchanged.

Upstream triage reproduced this on main and classed it restore. It also established that the
fail-closed endpoint-record validation proposed elsewhere does not cover these four sites, because
those backends already have kill arms.

Closes #4483.

Scope, stated plainly so the per-backend limits are not left to be discovered in the verification
record. All four call sites now propagate a failed close instead of discarding it, and a reported
failure reaches teardown's existing retain-and-stop refusal before any record naming the endpoint
is removed. That is the whole of what the issue asked for, and it is done.

Adapter-level detection is a different and narrower thing, and it is only partly addressed here.
Measured by driving the real code first: an endpoint that is already gone returns 0 silently on
every backend arm, but so did every genuine failure, so the two were indistinguishable everywhere
and the four sites had no signal to propagate until an arm could produce one. Two arms can now
produce one without depending on a vendor binary to prove it. The tmux arm resolves a close that
did not succeed against the window's exact recorded identity, because kill-window fails the same
way for a window that is already gone and one that is still there. The Orca arm reports a close its
missing CLI never even attempted.

Zellij and cmux are deliberately unchanged rather than improved: neither can yet distinguish a
close command that failed after the backend accepted it, so both still report success there. Herdr
reports success from that arm too, and teardown continues to gate every Herdr record removal on its
own confirmed-gone check instead. Closing those gaps needs a presence re-read taken after each
adapter's own close, and the close-then-read timing it depends on cannot be established without the
real Zellij, Orca, and cmux binaries. Guessing it was rejected rather than deferred quietly: a gate
that refused an already-exited session would break ordinary cleanup on every task, which is a worse
failure than the stranded endpoint it would be trying to prevent. The per-backend table in
docs/verification/runtime-backends.md carries exactly what each arm can and cannot prove today.

Why an unrelated liveness test is touched here

tests/fm-tmux-agent-liveness.test.sh is changed in this PR and is not part of this fix's subject, so
it deserves its own explanation rather than being read as scope creep.

The change is test-only: one line plus an explanatory comment. It starts that suite's idle window with
an explicit bare /bin/sh instead of letting tmux fall back to default-shell.

The flake it fixes is pre-existing, not introduced here, and that was proven rather than assumed. An
interleaved A/B run showed the base commit da5e658 failing the identical case "an idle shell pane
classifies dead" on 2 of 6 runs, alongside this branch failing it on 3 of 7. This change only extracted
the tmux inventory read into a shared helper with identical semantics and never touched the foreground
process-group read that case depends on.

The mechanism is the reason a bare shell is the right fix. default-shell is whoever runs the suite, so
the idle window inherited the operator's own login shell and therefore that operator's shell
configuration. A prompt or update hook that spawns a helper puts a non-shell process directly into the
pane's foreground process group, which is the single surface the liveness classifier reads: a sleep
there classifies as other, so the verdict became ambiguous instead of dead on exactly the runs
where such a helper overlapped the poll window. A bare /bin/sh is idle because nothing configured it,
which is what that case means to assert, and its foreground group is exactly one process.

It is fixed in this PR rather than deferred because this suite is selected by --changed for this diff,
so it would have run against this PR as soon as CI was authorized, and an intermittent failure there
would have cost a red CI run and another round.

What Changed

  • bin/fm-teardown.sh now propagates the status of all four fm_backend_kill call sites instead of discarding it behind 2>/dev/null || true, routing a failed close into a new endpoint_close_refusal helper that stops the cleanup before any record naming the endpoint is removed. --force overrides the stop at exactly one site (the generic non-Herdr/non-Orca close); the Orca site and both forced secondmate child sites refuse regardless.
  • fm_backend_tmux_kill resolves a failed kill-window by re-reading the window's exact recorded identity (=session plus a whole-line name match) through a new shared fm_backend_tmux_window_inventory helper, which fm_backend_tmux_agent_state now also uses: a still-present window fails, a definitively absent session or server succeeds silently, and an inventory that could not be read refuses. fm_backend_orca_kill returns nonzero when the missing orca CLI means no close was ever attempted; Zellij, cmux, and Herdr arms are unchanged and still report 0.
  • Added endpoint-close coverage to tests/fm-teardown-endpoint-safety.test.sh and tests/fm-backend-orca.test.sh (refusal, --force continue, unreadable re-read, forced child close, already-exited endpoint and dead server still completing silently), plus a per-backend "Endpoint close" table in docs/verification/runtime-backends.md and matching notes in docs/architecture.md, docs/orca-backend.md, and the secondmate-provisioning skill.

Risk Assessment

✅ Low: The change is tightly scoped to the four enumerated call sites plus two adapter arms, every behavior branch of the new tmux close-resolution logic was verified empirically against real tmux 3.7c (including the ordinary already-gone path that would have broken every teardown if wrong), all other callers guard the newly-nonzero return, and both prior-round findings were applied exactly and subtractively with no false claims surviving in code or docs.

Testing

Ran the two repository suites that own this area (tests/fm-teardown-endpoint-safety.test.sh, tests/fm-backend-orca.test.sh) - both green - and then drove the product myself as an operator would, because a passing suite is not evidence that the refusal reaches a real terminal. Every manual scenario ran the real bin/fm-teardown.sh CLI against real tmux 3.7c servers on isolated sockets in isolated FM_HOMEs, with the surviving window and the surviving state/&lt;id&gt;.meta inspected directly after each run. The headline case uses no injection at all: a live task window plus a teardown whose PATH has no tmux. On the base commit that reports a completed cleanup and deletes the only record naming the window while the window keeps running; on this branch it refuses at exit 1 with the record retained, and the rerun with tmux reachable closes the real window and finishes - so the regression reproduces before the fix and is gone after it. The two guards the intent calls out were attacked rather than confirmed: a prefix-named neighbour is not read as the recorded window's survivor, and --force is honoured only where continuing is reachable (generic tmux site) while the Orca and forced-secondmate-child sites still refuse with every record kept. One documented consequence surfaced and is working as the change's own verification record specifies rather than as a defect: because an unreadable inventory never proves absence, a teardown run without tmux on PATH now refuses even for an endpoint that is genuinely gone, with --force as the operator's way through. This is a shell CLI with no rendered UI surface, so the reviewer-visible evidence is CLI transcripts rather than screenshots. Only the zellij branch of the forced secondmate child close could not be driven, because that adapter cannot return a nonzero close today by design.

  • Live validation: ✅ go - 9 of 10 scenarios driven live against the product
Scenario Result Live Evidence
A genuinely failed close on a live tmux window refuses and keeps the record naming it, where the base commit reported success and deleted it ✅ pass live Scenario A / A' in teardown-endpoint-close-operator-transcript.log: branch exits 1 with the record retained and the window alive; base commit da5e658 prints teardown strand-demo complete, removes st…
The retained record lets the same teardown finish once the close can succeed ✅ pass live Scenario B: rerun with tmux reachable exits 0, fm-strand-demo is gone from the real session's window list, and the record is removed
An already-exited endpoint still completes cleanup silently ✅ pass live Scenario C: exit 0, teardown gone-task complete, no close refusal on stderr, record removed
A close that fails while the window is demonstrably still there is reported as a survivor, not a success ✅ pass live Scenario D: error: tmux window crew:fm-survivor-task is still present after its close, exit 1, record retained, window still listed
--force continues past the generic tmux close while still naming what it could not close ✅ pass live Scenario E: exit 0, --force authorizes continuing past a close that failed ... reconcile crew:fm-survivor-task yourself, record removed, window still alive; the identical unforced run in Scenario D…
A prefix-named neighbour window is not mistaken for the recorded window's survivor ✅ pass live Scenario F: recorded fm-neighbour absent while fm-neighbour-extra is live and the close fails; teardown completes at exit 0, removes the record, and leaves the neighbour untouched
An Orca task whose CLI is missing refuses even under --force and keeps the record naming the terminal ✅ pass live Scenario G: exit 1 with backend=orca selected but the &#39;orca&#39; CLI is not installed, no --force authorizes continuing line, state/orca-strand.meta retained; unforced run refuses identically
Forced secondmate cleanup refuses on a child endpoint it could not close ✅ pass live Scenario H: bin/fm-teardown.sh mate-task --force exits 1, names child child-task, retains both the parent and child records, and the child's tmux window is still live
Backends left unchanged by this commit do not start refusing ordinary cleanup ✅ pass live Scenario I: zellij and cmux task records both tear down at exit 0 on a host with neither CLI installed; Scenario J shows zellij/cmux/herdr already-gone targets returning a silent 0 from fm_backend_kil…
The zellij branch of the forced secondmate child close propagates a failed close ⏸️ untested no fm_backend_zellij_kill cannot return nonzero today - every path in it ends in return 0 or || true - so no input, including an installed zellij binary, can make that call site fail. Making it driva…
Evidence: Live operator transcripts for all 10 endpoint-close scenarios

Source: Live operator transcripts for all 10 endpoint-close scenarios


================ SCENARIO A - live tmux window, teardown run with no tmux on PATH (TARGET build) ================
--- before: windows in session ---
  control
  fm-strand-demo
--- before: task record ---
strand-demo.meta
$ bin/fm-teardown.sh strand-demo     (PATH without tmux)
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
●  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.
●  watcher supervision needs Stop-owned automatic recovery; inspect the hook registration and startup status before ending the turn.
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
error: tmux window crew:fm-strand-demo could not be read after its close, so whether it survived is unknown
error: the tmux endpoint crew:fm-strand-demo for strand-demo could not be closed, so it may still be live.
error: stopping this cleanup without removing the task's records, so the record naming crew:fm-strand-demo is still here to reconcile from.
error: that retention is not durable across a session start: if this task carries a backlog transition, the next session replays its pending close and removes the retained record, so reconcile the surviving endpoint yourself rather than trusting the retention.
error: rerun teardown once the close can succeed, or rerun with --force to discard this task's records deliberately.
exit=1
--- after: task record ---
strand-demo.meta
--- after: windows in session ---
  control
  fm-strand-demo

================ SCENARIO A' - SAME fixture, SAME situation, BASE build (the bug being fixed) ================
$ bin/fm-teardown.sh strand-demo     (base commit da5e658, PATH without tmux)
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
●  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.
●  watcher supervision needs Stop-owned automatic recovery; inspect the hook registration and startup status before ending the turn.
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
/tmp/fm-e2e-01M2HP/run/Abase/nonexistent-project: skipped: not a directory
teardown strand-demo complete (window base-crew:fm-strand-demo, worktree /tmp/fm-e2e-01M2HP/run/Abase/nonexistent-worktree)
Backlog: strand-demo just finished (this home keeps no markdown backlog at /private/tmp/fm-e2e-01M2HP/run/Abase/home/data/backlog.md). Update /private/tmp/fm-e2e-01M2HP/run/Abase/home/data/backlog.md - move strand-demo to Done, keep Done to the 10 most recent, then re-scan Queued and dispatch only work whose blockers are gone and date is due.
exit=0
--- after: task record (base) ---
home-summary.json
terminal-outcomes
--- after: windows in session (base) ---
  control
  fm-strand-demo

================ SCENARIO B - same task, tmux back on PATH: the retained record lets the rerun finish ================
$ bin/fm-teardown.sh strand-demo
WARNING: watcher still down (same stale episode; last beat: never, grace 300s) - full banner already printed this episode.
/tmp/fm-e2e-01M2HP/run/A/nonexistent-project: skipped: not a directory
teardown strand-demo complete (window crew:fm-strand-demo, worktree /tmp/fm-e2e-01M2HP/run/A/nonexistent-worktree)
Backlog: strand-demo just finished (this home keeps no markdown backlog at /private/tmp/fm-e2e-01M2HP/run/A/home/data/backlog.md). Update /private/tmp/fm-e2e-01M2HP/run/A/home/data/backlog.md - move strand-demo to Done, keep Done to the 10 most recent, then re-scan Queued and dispatch only work whose blockers are gone and date is due.
exit=0
--- after: task record ---
home-summary.json
terminal-outcomes
--- after: windows in session ---
  control

================ SCENARIO C - recorded window already exited: ordinary cleanup must stay silent ================
before windows:
  control
$ bin/fm-teardown.sh gone-task
/tmp/fm-e2e-01M2HP/run2/C/nonexistent-project: skipped: not a directory
teardown gone-task complete (window crew:fm-gone-task, worktree /tmp/fm-e2e-01M2HP/run2/C/nonexistent-worktree)
Backlog: gone-task just finished (this home keeps no markdown backlog at /private/tmp/fm-e2e-01M2HP/run2/C/home/data/backlog.md). Update /private/tmp/fm-e2e-01M2HP/run2/C/home/data/backlog.md - move gone-task to Done, keep Done to the 10 most recent, then re-scan Queued and dispatch only work whose blockers are gone and date is due.
exit=0
state dir after: home-summary.json terminal-outcomes 

================ SCENARIO D - close fails, re-read shows the window STILL PRESENT (adversarial: close accepted-then-failed) ================
$ bin/fm-teardown.sh survivor-task     (kill-window blocked, window really alive)
error: tmux window crew:fm-survivor-task is still present after its close
error: the tmux endpoint crew:fm-survivor-task for survivor-task could not be closed, so it may still be live.
error: stopping this cleanup without removing the task's records, so the record naming crew:fm-survivor-task is still here to reconcile from.
error: that retention is not durable across a session start: if this task carries a backlog transition, the next session replays its pending close and removes the retained record, so reconcile the surviving endpoint yourself rather than trusting the retention.
error: rerun teardown once the close can succeed, or rerun with --force to discard this task's records deliberately.
exit=1
state dir after: .guard-watcher-stale-banner survivor-task.meta 
windows after:
  control
  fm-survivor-task

================ SCENARIO E - SAME failure, operator passes --force (generic tmux site) ================
$ bin/fm-teardown.sh survivor-task --force
error: tmux window crew:fm-survivor-task is still present after its close
error: the tmux endpoint crew:fm-survivor-task for survivor-task could not be closed, so it may still be live.
error: --force authorizes continuing past a close that failed, so this cleanup proceeds toward removing the task's records; reconcile crew:fm-survivor-task yourself, because nothing here can still be relied on to name it.
/tmp/fm-e2e-01M2HP/run2/D/nonexistent-project: skipped: not a directory
teardown survivor-task complete (window crew:fm-survivor-task, worktree /tmp/fm-e2e-01M2HP/run2/D/nonexistent-worktree)
Backlog: survivor-task just finished (this home keeps no markdown backlog at /private/tmp/fm-e2e-01M2HP/run2/D/home/data/backlog.md). Update /private/tmp/fm-e2e-01M2HP/run2/D/home/data/backlog.md - move survivor-task to Done, keep Done to the 10 most recent, then re-scan Queued and dispatch only work whose blockers are gone and date is due.
exit=0
state dir after: home-summary.json terminal-outcomes 
windows after:
  control
  fm-survivor-task

================ SCENARIO F - adversarial exactness: recorded window gone, PREFIX NEIGHBOUR alive, kill blocked ================
live windows (recorded target fm-neighbour does NOT exist):
  control
  fm-neighbour-extra
$ bin/fm-teardown.sh fm-prefix-demo     (kill-window blocked)
REFUSED: tmux endpoint 'prefixsess:fm-neighbour' is malformed or does not belong to task fm-prefix-demo; preserving task state.
exit=1
state dir after: fm-prefix-demo.meta 
windows after (neighbour must be untouched):
  control
  fm-neighbour-extra

================ SCENARIO F - adversarial exactness: recorded window gone, PREFIX NEIGHBOUR alive, kill blocked ================
live windows (recorded target fm-neighbour does NOT exist; only its prefix neighbour does):
  control
  fm-neighbour-extra
$ bin/fm-teardown.sh neighbour     (kill-window blocked)
/tmp/fm-e2e-01M2HP/run3/F/nonexistent-project: skipped: not a directory
teardown neighbour complete (window prefixsess:fm-neighbour, worktree /tmp/fm-e2e-01M2HP/run3/F/nonexistent-worktree)
Backlog: neighbour just finished (this home keeps no markdown backlog at /private/tmp/fm-e2e-01M2HP/run3/F/home/data/backlog.md). Update /private/tmp/fm-e2e-01M2HP/run3/F/home/data/backlog.md - move neighbour to Done, keep Done to the 10 most recent, then re-scan Queued and dispatch only work whose blockers are gone and date is due.
exit=0
state dir after: home-summary.json terminal-outcomes 
windows after (neighbour must be untouched):
  control
  fm-neighbour-extra

================ SCENARIO G - Orca task record, 'orca' CLI absent, operator uses --force ================
(host has no orca CLI at all)
$ bin/fm-teardown.sh orca-strand --force
error: backend=orca selected but the 'orca' CLI is not installed
error: the orca endpoint term-7 for orca-strand could not be closed, so it may still be live.
error: stopping this cleanup without removing the task's records, so the record naming term-7 is still here to reconcile from.
error: that retention is not durable across a session start: if this task carries a backlog transition, the next session replays its pending close and removes the retained record, so reconcile the surviving endpoint yourself rather than trusting the retention.
exit=1
state dir after: .guard-watcher-stale-banner orca-strand.meta 

================ SCENARIO H - forced secondmate cleanup, child endpoint close fails ================
$ bin/fm-teardown.sh mate-task --force     (child kill-window blocked, child window alive)
error: tmux window mates:fm-child-task is still present after its close
error: the tmux endpoint mates:fm-child-task for child child-task could not be closed, so it may still be live.
error: stopping this cleanup without removing the task's records, so the record naming mates:fm-child-task is still here to reconcile from.
error: that retention is not durable across a session start: if this task carries a backlog transition, the next session replays its pending close and removes the retained record, so reconcile the surviving endpoint yourself rather than trusting the retention.
exit=1
parent state dir after: .guard-watcher-stale-banner mate-task.meta 
child  state dir after: child-task.meta 
windows after:
  control
  fm-child-task

================ SCENARIO I - unchanged backends must not start refusing: zellij + cmux tasks on a host with neither CLI installed ================
$ bin/fm-teardown.sh zellij-task     (backend=zellij, 'zellij' CLI not installed on this host)
/tmp/fm-e2e-01M2HP/run4/zellij/nonexistent-project: skipped: not a directory
teardown zellij-task complete (window lab:7, worktree /tmp/fm-e2e-01M2HP/run4/zellij/nonexistent-worktree)
exit=0
state dir after: home-summary.json terminal-outcomes 

$ bin/fm-teardown.sh cmux-task     (backend=cmux, 'cmux' CLI not installed on this host)
/tmp/fm-e2e-01M2HP/run4/cmux/nonexistent-project: skipped: not a directory
teardown cmux-task complete (window workspace-1:surface-2, worktree /tmp/fm-e2e-01M2HP/run4/cmux/nonexistent-worktree)
exit=0
state dir after: home-summary.json terminal-outcomes 


================ SCENARIO J - fm_backend_kill contract, driven directly: already-gone endpoints on every arm stay a silent 0 ================
fm_backend_kill zellij  lab:7                    -> exit=0 stderr/stdout=<silent>
fm_backend_kill cmux    workspace-1:surface-2    -> exit=0 stderr/stdout=<silent>
fm_backend_kill herdr   lab:w1:p2                -> exit=0 stderr/stdout=error: herdr server for session 'lab' did not report running within 10s
fm_backend_kill tmux    gone-session:fm-nope (no tmux on PATH) -> exit=1 stderr/stdout=error: tmux window gone-session:fm-nope could not be read after its close, so whether it survived is unknown
Evidence: Evidence index mapping each scenario to its observed result

Source: Evidence index mapping each scenario to its observed result

# Endpoint-close refusal - live operator evidence

All transcripts in `teardown-endpoint-close-operator-transcript.log` come from running the real
`bin/fm-teardown.sh` CLI against real tmux 3.7c servers on isolated sockets, in isolated `FM_HOME`s.
`drive*.sh` are the driver scripts that produced them.

| Scenario | What was driven | Result |
| --- | --- | --- |
| A | Live `fm-strand-demo` tmux window; teardown run under a PATH with no `tmux` | exit 1, refuses, record retained, window still alive |
| A' | Identical fixture on base commit `da5e658` | exit 0, `teardown ... complete`, record deleted, window still alive - the stranded endpoint |
| B | Same task re-run with tmux reachable | exit 0, real window closed, record removed |
| C | Recorded window already exited | exit 0, silent, record removed - ordinary cleanup unchanged |
| D | `kill-window` fails, re-read shows the window still present | exit 1, `is still present after its close`, record retained |
| E | Same failure with `--force` | exit 0, states what `--force` authorizes, record removed, failure still reported |
| F | Recorded window gone, prefix neighbour `fm-neighbour-extra` alive, kill fails | exit 0, silent, neighbour untouched - no prefix match |
| G | `backend=orca` record, no `orca` CLI, `--force` | exit 1, refuses, no continue announcement, record retained |
| H | Forced secondmate cleanup, child close fails | exit 1, both records retained, child window alive |
| I | zellij and cmux tasks with neither CLI installed | exit 0 both - unchanged backends do not start refusing |
| J | `fm_backend_kill` driven directly per backend | zellij/cmux/herdr already-gone -> silent 0; tmux with unreadable inventory -> 1 |

`teardown-endpoint-safety.log` and `orca-backend.log` are the repository's own suites for this area.
Evidence: Driver scripts that produced the transcripts

Source: Driver scripts that produced the transcripts

#!/usr/bin/env bash
# Manual operator-style drive of fm-teardown's endpoint-close refusal.
set -u
export FM_GATE_REFUSE_BYPASS=1
WT=~/.no-mistakes/worktrees/041bc5e421de/01M2HP1H8ZGN90K5AEEN2QP4PY
BASE=/tmp/fm-e2e-01M2HP/base
SCRATCH=/tmp/fm-e2e-01M2HP/run
REAL_TMUX=$(command -v tmux)
rm -rf "$SCRATCH"; mkdir -p "$SCRATCH"

# a curated PATH that resolves everything EXCEPT tmux (genuine "tmux not on PATH")
NOTMUX="$SCRATCH/pathsans"
mkdir -p "$NOTMUX"
IFS=: read -ra DIRS <<< "$PATH"
for d in "${DIRS[@]}"; do
  [ -d "$d" ] || continue
  for e in "$d"/*; do
    [ -e "$e" ] || [ -L "$e" ] || continue
    n=${e##*/}
    [ "$n" = tmux ] && continue
    [ -e "$NOTMUX/$n" ] && continue
    ln -s "$e" "$NOTMUX/$n" 2>/dev/null
  done
done
command -v tmux >/dev/null && PATH="$NOTMUX" command -v tmux >/dev/null && { echo "FATAL: tmux still resolvable"; exit 1; }
PATH="$NOTMUX" command -v git >/dev/null || { echo "FATAL: curated PATH lost git"; exit 1; }

mk_case() {  # <name>
  local d="$SCRATCH/$1"
  mkdir -p "$d/home/state" "$d/home/data" "$d/home/config" "$d/project"
  git init -q "$d/project"
  printf '%s\n' "$d"
}
win_exists() {  # <dir> <socket> <session> <window>
  ( cd "$1" && "$REAL_TMUX" -S "$2" list-windows -t "=$3" -F '#{window_name}' 2>/dev/null ) | grep -Fqx "$4"
}
meta() {  # <dir> <id> <window>
  printf 'window=%s\nendpoint_task_id=%s\nworktree=%s\nproject=%s\nkind=ship\nmode=no-mistakes\n' \
    "$3" "$2" "$1/nonexistent-worktree" "$1/nonexistent-project" > "$1/home/state/$2.meta"
}

mk_tmux_shim() {  # <dir> <socket>  -> prints a bin dir whose tmux is real tmux pinned to <dir>/<socket>
  local d=$1 sock=$2
  mkdir -p "$d/shimbin"
  cat > "$d/shimbin/tmux" <<SH
#!/usr/bin/env bash
cd '$d'
exec '$REAL_TMUX' -S '$sock' "\$@"
SH
  chmod +x "$d/shimbin/tmux"
  printf '%s\n' "$d/shimbin"
}

hdr() { printf '\n================ %s ================\n' "$*"; }

######################################################################
hdr "SCENARIO A - live tmux window, teardown run with no tmux on PATH (TARGET build)"
D=$(mk_case A); SOCK=s.sock; SESS='crew'; ID=strand-demo
( cd "$D" && env -u TMUX -u TMUX_PANE "$REAL_TMUX" -S "$SOCK" new-session -d -s "$SESS" -n control )
( cd "$D" && env -u TMUX -u TMUX_PANE "$REAL_TMUX" -S "$SOCK" new-window -d -t "=$SESS:" -n "fm-$ID" )
meta "$D" "$ID" "$SESS:fm-$ID"
echo "--- before: windows in session ---"; ( cd "$D" && "$REAL_TMUX" -S "$SOCK" list-windows -t "=$SESS" -F '  #{window_name}' )
echo "--- before: task record ---"; ls "$D/home/state"
echo "\$ bin/fm-teardown.sh $ID     (PATH without tmux)"
env -u TMUX -u TMUX_PANE FM_HOME="$D/home" FM_ROOT_OVERRIDE="$WT" PATH="$NOTMUX" \
  "$WT/bin/fm-teardown.sh" "$ID"; echo "exit=$?"
echo "--- after: task record ---"; ls "$D/home/state"
echo "--- after: windows in session ---"; ( cd "$D" && "$REAL_TMUX" -S "$SOCK" list-windows -t "=$SESS" -F '  #{window_name}' )

hdr "SCENARIO A' - SAME fixture, SAME situation, BASE build (the bug being fixed)"
DB=$(mk_case Abase); IDB=strand-demo
( cd "$DB" && env -u TMUX -u TMUX_PANE "$REAL_TMUX" -S "$SOCK" new-session -d -s base-crew -n control )
( cd "$DB" && env -u TMUX -u TMUX_PANE "$REAL_TMUX" -S "$SOCK" new-window -d -t "=base-crew:" -n "fm-$IDB" )
meta "$DB" "$IDB" "base-crew:fm-$IDB"
echo "\$ bin/fm-teardown.sh $IDB     (base commit da5e658, PATH without tmux)"
env -u TMUX -u TMUX_PANE FM_HOME="$DB/home" FM_ROOT_OVERRIDE="$BASE" PATH="$NOTMUX" \
  "$BASE/bin/fm-teardown.sh" "$IDB"; echo "exit=$?"
echo "--- after: task record (base) ---"; ls -A "$DB/home/state" || true
echo "--- after: windows in session (base) ---"; ( cd "$DB" && "$REAL_TMUX" -S "$SOCK" list-windows -t "=base-crew" -F '  #{window_name}' )

######################################################################
hdr "SCENARIO B - same task, tmux back on PATH: the retained record lets the rerun finish"
SHIM=$(mk_tmux_shim "$D" "$SOCK")
echo "\$ bin/fm-teardown.sh $ID"
env -u TMUX -u TMUX_PANE FM_HOME="$D/home" FM_ROOT_OVERRIDE="$WT" PATH="$SHIM:$NOTMUX" \
  "$WT/bin/fm-teardown.sh" "$ID"; echo "exit=$?"
echo "--- after: task record ---"; ls -A "$D/home/state" || true
echo "--- after: windows in session ---"; ( cd "$D" && "$REAL_TMUX" -S "$SOCK" list-windows -t "=$SESS" -F '  #{window_name}' )
( cd "$D" && "$REAL_TMUX" -S "$SOCK" kill-server 2>/dev/null )
( cd "$DB" && "$REAL_TMUX" -S "$SOCK" kill-server 2>/dev/null )
Evidence: tests/fm-teardown-endpoint-safety.test.sh run

Source: tests/fm-teardown-endpoint-safety.test.sh run

ok - fm-teardown: missing, empty, malformed, ambiguous, and task-mismatched endpoints refuse before every mutation or runtime call
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, and cmux records validate while every empty backend target 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: 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
Evidence: tests/fm-backend-orca.test.sh run

Source: tests/fm-backend-orca.test.sh run

ok - fm_backend_orca_capture: parses result.terminal.tail and calls terminal read
ok - fm_backend_orca_capture: falls back to result text fields
ok - fm_backend_orca_capture: fails closed on Orca read error JSON
ok - fm_backend_orca_runtime_check: accepts reachable ready runtime
ok - fm_backend_orca_runtime_check: fails closed when runtime is not ready
ok - fm_backend_orca_send_text_submit: verifies empty composer after Enter with one bounded read
ok - fm_backend_orca_send_text_submit: a borderless claude composer confirms delivery (the missing #2029 shape)
ok - fm_backend_orca_composer_state: a stale startup banner cannot outrank the live composer row
ok - fm_backend_orca_send_text_submit: retries Enter while composer remains pending
ok - fm_backend_orca_composer_state: a slash-command popup's argument-hint placeholder still reads pending
ok - fm_backend_orca_composer_state: a bare dead-shell prompt reads unknown (unsafe-for-injection), never empty
ok - fm_backend_orca_send_text_submit: a slash-command popup's placeholder fill on Enter #1 does not short-circuit as submitted; Enter #2 is retried and lands it
ok - fm_backend_orca_send_literal: sends text without submitting
ok - fm_backend_orca_send_text_submit: reports send-failed when Orca send fails
ok - Orca send helpers: fail closed on ok:false JSON
ok - fm_backend_orca_send_key: Enter maps to empty enter, C-c maps to interrupt
ok - fm_backend_orca_send_key: refuses unsupported keys loudly
ok - fm_backend_orca_send_key: refuses Escape instead of mapping it to interrupt
ok - fm_backend_orca_kill: calls terminal close and stays best-effort
ok - fm_backend_orca_kill: a close its missing CLI never attempted reports the failure instead of a success
ok - fm_backend_orca_remove_worktree: refuses empty worktree ids
ok - fm_backend_orca_remove_worktree: fails closed on ok:false JSON
ok - fm_backend_orca_worktree_path: resolves an Orca worktree id to its path
ok - fm-backend dispatcher: accepts orca and routes capture through bin/backends/orca.sh
ok - fm_backend_orca_json_get: ignores undocumented terminal id shapes
ok - Orca lifecycle helpers: register repo, create worktree, create terminal, parse stable ids
ok - fm_backend_orca_worktree_create: removes created worktree when path is missing
ok - fm-spawn.sh --backend orca: preserves metadata when pathless cleanup fails
ok - fm-spawn.sh --backend orca: reuses implicit terminal, records metadata, launches harness
ok - fm-spawn.sh --backend orca --secondmate: refuses before secondmate-home mutation
ok - fm-spawn.sh --backend orca: refuses before mutation when Orca runtime is not ready
ok - fm-spawn.sh --backend orca: refuses non-isolated worktrees and closes implicit terminals
ok - fm-spawn.sh --backend orca: removes worktree when terminal creation fails
ok - fm-spawn.sh --backend orca: preserves metadata when abort cleanup fails
ok - fm-spawn.sh --backend orca: releases terminal and worktree on later aborts
ok - fm-peek/fm-send/fm-crew-state route through backend=orca metadata and its durable inbox
ok - fm-peek/fm-crew-state: Orca read error JSON fails closed
ok - fm_backend_target_exists: Orca ok:false read JSON is not live
ok - fm-teardown.sh backend=orca: scout report gate then helper-backed worktree removal
ok - fm-teardown.sh backend=orca: scout teardown refuses id/path mismatches
ok - fm-teardown.sh backend=orca: releases terminal/worktree when path is absent
ok - fm-teardown.sh backend=orca: preserves metadata on remove ok:false JSON
ok - fm-teardown.sh backend=orca: scout report gate precedes pathless helper cleanup
ok - fm-teardown.sh backend=orca: ship teardown fails closed when worktree path is missing
ok - fm-teardown.sh backend=orca: ship teardown requires a matching Orca id path
ok - fm-teardown.sh backend=orca: ship teardown fails closed when id resolution fails
ok - fm-teardown.sh backend=orca: ship teardown refuses id/path mismatches
ok - fm-teardown.sh backend=orca: refuses missing worktree ids before cleanup
ok - fm-teardown.sh backend=orca: refuses incomplete worktree-only endpoint metadata before runtime dispatch
ok - fm-teardown.sh --force: removes Orca secondmate children through Orca
ok - fm-teardown.sh --force: refuses Orca child id/path mismatches
ok - fm-teardown.sh --force: refuses partial Orca secondmate children before runtime dispatch
Evidence: Before/after on the same live tmux window: base strands it, branch refuses
=== BRANCH (target) ===
--- before: windows in session ---
control
fm-strand-demo
--- before: task record ---
strand-demo.meta
$ bin/fm-teardown.sh strand-demo (PATH without tmux)
error: tmux window crew:fm-strand-demo could not be read after its close, so whether it survived is unknown
error: the tmux endpoint crew:fm-strand-demo for strand-demo could not be closed, so it may still be live.
error: stopping this cleanup without removing the task's records, so the record naming crew:fm-strand-demo is still here to reconcile from.
error: that retention is not durable across a session start: if this task carries a backlog transition, the next session replays its pending close and removes the retained record, so reconcile the surviving endpoint yourself rather than trusting the retention.
error: rerun teardown once the close can succeed, or rerun with --force to discard this task's records deliberately.
exit=1
--- after: task record ---
strand-demo.meta
--- after: windows in session ---
control
fm-strand-demo

=== BASE da5e658, identical fixture ===
$ bin/fm-teardown.sh strand-demo (PATH without tmux)
teardown strand-demo complete (window base-crew:fm-strand-demo, worktree .../nonexistent-worktree)
exit=0
--- after: task record (base) ---
home-summary.json
terminal-outcomes
--- after: windows in session (base) ---
control
fm-strand-demo <-- stranded: still live, nothing on disk names it

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 4 issues found → auto-fixed (2) ✅
  • ⚠️ bin/backends/tmux.sh:152 - The new tmux re-read treats a failed inventory read as proof the window is gone: tmux list-windows -t &#34;=$session&#34; ... 2&gt;/dev/null | grep -qxF -- &#34;$window&#34; || return 0 cannot distinguish "the session/server is genuinely gone" from "the read itself could not run". The same adapter already owns the opposite rule - fm_backend_tmux_agent_state (bin/backends/tmux.sh:282-295) classifies only a definitive can&#39;t find session: / no server running on / error connecting to ... response as missing, and any other inventory failure as unreadable, with the stated rationale that "a transient tmux problem never licenses a duplicate". Concrete sequence: teardown of a tmux task where the server is momentarily unresponsive, or where tmux is not on teardown's curated lifecycle PATH (tests/fm-teardown.test.sh:659 builds exactly such a PATH), so kill-window fails AND list-windows fails with a non-definitive status; grep matches nothing, fm_backend_tmux_kill returns 0, fm-teardown.sh:3418 sees a successful close, removes state/<id>.meta and prints teardown &lt;id&gt; complete while the window is still live - the stranding this change exists to prevent, now reachable through the new code path itself. Note this is the same reasoning the Orca arm was just changed to apply (bin/backends/orca.sh:296: no CLI means no read that could show the endpoint absent, therefore failure), so the two arms are inconsistent. Smallest honest remedy: classify the re-read the way fm_backend_tmux_agent_state already does - a definitive missing-session/server response stays a silent success (preserving the documented dead-server case), any other read failure refuses. Flagged ask-user rather than auto-fix because it adds a refusal condition the author deliberately reasoned about excluding.
  • ⚠️ bin/fm-teardown.sh:3419 - The refusal retains state/<id>.meta only until the next session start. For any task where TEARDOWN_BACKLOG_APPLIES=1 (ordinary ship/scout tasks), fm_backlog_close_marker_write runs at bin/fm-teardown.sh:3281 - before the endpoint close at 3418 - and the marker survives the exit 1. The next bin/fm-bootstrap.sh run sweeps &#34;$STATE&#34;/*.backlog-close (bin/fm-bootstrap.sh:1238) and fm_backlog_close_marker_replay deletes the retained record with fm_backlog_atomic_transition remove &#34;$meta&#34; (bin/fm-backlog-transition-lib.sh:1189, which is a plain rm -f, not an archive), emitting only the generic "its endpoint or local copy may remain and should be reconciled" line. After that, nothing on disk names the surviving endpoint - the exact stranding the refusal message promises to prevent ("retaining every durable record naming that endpoint"), deferred by one bootstrap rather than avoided. The pre-existing Herdr confirmed-gone gate (bin/fm-teardown.sh:3440) has the identical property, so this is not a regression introduced here, but it does bound the durability of the claimed fix. The remedy - carrying the endpoint identity into the pending-close marker, or making replay refuse while an unclosed endpoint is recorded - adds durable state beyond this change's stated scope, so it needs authorization rather than being applied as a mechanical fix.
  • ℹ️ bin/backends/orca.sh:296 - fm_backend_orca_kill now returns 1 whenever command -v orca fails, and bin/fm-teardown.sh:3338 turns that into exit 1 unconditionally - --force does not bypass it. So an Orca-backed task record on a host where the Orca CLI has since been uninstalled (or a teardown run under a PATH without it) can never be cleaned up through teardown; every rerun refuses. The intent explicitly authorizes this arm's behavior ("The Orca arm reports a close its missing CLI never even attempted"), so this is not a contradiction - the open question is only whether --force should retain an operator escape hatch for a host that will never have the CLI again. Noting also that the bootstrap close-marker replay described in the other finding will eventually remove the record for backlog-bearing tasks, so the wedge is not permanent for those.
  • ℹ️ bin/fm-bootstrap.sh:819 - Sibling path, outside this change's stated four call sites: the secondmate liveness sweep still runs fm_backend_kill &#34;$backend&#34; &#34;$target&#34; 2&gt;/dev/null || true and then immediately respawns via fm-spawn.sh, which overwrites state/<id>.meta with the new endpoint. A swallowed kill failure there strands the old endpoint the same way, since the record naming it is replaced rather than retained. Lower stakes than teardown's case because this arm only fires when fm_backend_agent_state already read dead (the endpoint is confirmed agent-less), and the intent deliberately scopes this change to fm-teardown.sh. Recorded for awareness, no action required in this change.

🔧 Fix applied.
2 warnings still open:

  • ⚠️ bin/fm-teardown.sh:2975 - The --force override at the Orca close site can never let a cleanup complete, and the rationale given for it is the inverse of what the code does. fm_backend_orca_kill (bin/backends/orca.sh:295) returns nonzero for exactly one reason: fm_backend_orca_tool_check failed, i.e. no orca on PATH. The very next statement after the forced continue is fm_backend_remove_worktree &#34;$BACKEND&#34; &#34;$ORCA_WORKTREE_ID&#34; (bin/fm-teardown.sh:3367), which calls fm_backend_orca_remove_worktree -> fm_backend_orca_tool_check || return 1 (bin/backends/orca.sh:183). It is an unguarded simple command under set -eu (bin/fm-teardown.sh:259), so the script dies with status 1 right there. Concrete sequence: orca-backed scout task, orca uninstalled, recorded worktree path already gone (so require_orca_worktree_path_match_if_present at 3341 short-circuits at bin/fm-teardown.sh:2097). Unforced -> refusal, exit 1. Forced -> endpoint_close_refusal prints --force was given, so this cleanup continues and removes the task&#39;s records anyway; nothing on disk will name &lt;terminal&gt; afterwards, then teardown aborts at 3367 having removed nothing. The operator is told the records are gone and the endpoint unnamed while both are still on disk - a wrong user-visible statement, not merely a missing feature. If the recorded worktree still exists, 3341 exits 1 before the close is even attempted, so --force does not help there either. The stated justification is therefore false in both sub-cases: bin/fm-teardown.sh:2960-2961 ("without it an endpoint whose backend can never close again (an uninstalled Orca CLI, say) would refuse every rerun with no way out") and the same sentence in docs/verification/runtime-backends.md:371. The narrower form that satisfies the authorized remedy is to honor --force only at the generic non-orca site (bin/fm-teardown.sh:3445), where it demonstrably does open a way out and is covered by test_forced_teardown_continues_past_a_close_it_could_not_make, and to drop the Orca-CLI justification from both the comment and the verification doc. Flagged ask-user rather than auto-fix because the --force arm and its two-site placement were an explicit prior-round instruction; the alternative remedy (making forced orca cleanup tolerate a missing CLI for worktree removal) would extend this change's scope and also needs authorization. Note also the milder form of the same over-claim at the generic site: a forced run that continues here can still be stopped afterwards by the fm-inactive-reconcile refusal at bin/fm-teardown.sh:3477, which retains every record - so "nothing on disk will name <target> afterwards" is a prediction the function cannot make. Softening that line to state what --force authorizes rather than what will have happened would fix both.
  • ⚠️ docs/verification/runtime-backends.md:337 - The verification record claims more than the change proves: "Verified on 2026-09-14 with tmux 3.7c by driving fm_backend_kill against real endpoints and against each adapter with its CLI absent." All five new cases in tests/fm-teardown-endpoint-safety.test.sh drive tmux only; no test in the repository drives fm_backend_orca_kill (or fm_backend_kill orca) with orca off PATH, and none drives zellij or cmux with its CLI absent. The one existing orca kill test, tests/fm-backend-orca.test.sh:355-364, puts an orca stub on PATH and still asserts exit 0, so it passes identically before and after this change and cannot detect the new arm. The result is that the only other behavior change this commit makes to a backend adapter - fm_backend_orca_tool_check || return 1 at bin/backends/orca.sh:296 - has no executable evidence behind it, while the doc that is this repository's per-backend contract asserts it was measured. Smallest honest remedy: add one case driving fm_backend_orca_kill under a PATH with no orca and asserting a nonzero return plus the existing "'orca' CLI is not installed" line, and narrow the doc sentence to name the adapters actually driven. This is non-functional and does not touch the author's intent, so it is safe to apply directly.

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

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 9 of 10 scenarios driven live against the product
Scenario Result Live Evidence
A genuinely failed close on a live tmux window refuses and keeps the record naming it, where the base commit reported success and deleted it ✅ pass live Scenario A / A' in teardown-endpoint-close-operator-transcript.log: branch exits 1 with the record retained and the window alive; base commit da5e658 prints teardown strand-demo complete, removes st…
The retained record lets the same teardown finish once the close can succeed ✅ pass live Scenario B: rerun with tmux reachable exits 0, fm-strand-demo is gone from the real session's window list, and the record is removed
An already-exited endpoint still completes cleanup silently ✅ pass live Scenario C: exit 0, teardown gone-task complete, no close refusal on stderr, record removed
A close that fails while the window is demonstrably still there is reported as a survivor, not a success ✅ pass live Scenario D: error: tmux window crew:fm-survivor-task is still present after its close, exit 1, record retained, window still listed
--force continues past the generic tmux close while still naming what it could not close ✅ pass live Scenario E: exit 0, --force authorizes continuing past a close that failed ... reconcile crew:fm-survivor-task yourself, record removed, window still alive; the identical unforced run in Scenario D…
A prefix-named neighbour window is not mistaken for the recorded window's survivor ✅ pass live Scenario F: recorded fm-neighbour absent while fm-neighbour-extra is live and the close fails; teardown completes at exit 0, removes the record, and leaves the neighbour untouched
An Orca task whose CLI is missing refuses even under --force and keeps the record naming the terminal ✅ pass live Scenario G: exit 1 with backend=orca selected but the &#39;orca&#39; CLI is not installed, no --force authorizes continuing line, state/orca-strand.meta retained; unforced run refuses identically
Forced secondmate cleanup refuses on a child endpoint it could not close ✅ pass live Scenario H: bin/fm-teardown.sh mate-task --force exits 1, names child child-task, retains both the parent and child records, and the child's tmux window is still live
Backends left unchanged by this commit do not start refusing ordinary cleanup ✅ pass live Scenario I: zellij and cmux task records both tear down at exit 0 on a host with neither CLI installed; Scenario J shows zellij/cmux/herdr already-gone targets returning a silent 0 from fm_backend_kil…
The zellij branch of the forced secondmate child close propagates a failed close ⏸️ untested no fm_backend_zellij_kill cannot return nonzero today - every path in it ends in return 0 or || true - so no input, including an installed zellij binary, can make that call site fail. Making it driva…
  • bash tests/fm-teardown-endpoint-safety.test.sh (25 cases, including the 6 new endpoint-close cases)
  • bash tests/fm-backend-orca.test.sh (includes test_kill_refuses_when_the_orca_cli_is_absent)
  • Manual operator drive A: live tmux window + bin/fm-teardown.sh strand-demo under a curated PATH with no tmux
  • Manual operator drive A': identical fixture against the base commit tree extracted from da5e658 (git archive), showing the pre-fix stranding
  • Manual operator drive B: rerun of the same task id with tmux reachable
  • Manual operator drive C: bin/fm-teardown.sh gone-task with the recorded window already exited
  • Manual operator drive D/E: kill-window failing while the window is really alive, without and with --force
  • Manual operator drive F: recorded window absent, prefix neighbour fm-neighbour-extra alive, close failing
  • Manual operator drive G: backend=orca record with no orca CLI on the host, run with --force and without
  • Manual operator drive H: bin/fm-teardown.sh mate-task --force with a secondmate child whose tmux close fails
  • Manual operator drive I: bin/fm-teardown.sh for backend=zellij and backend=cmux records on a host with neither CLI
  • Manual drive J: fm_backend_kill &lt;backend&gt; &lt;target&gt; invoked directly for tmux/zellij/cmux/herdr already-gone targets
⚠️ **Document** - 1 info
  • ℹ️ tests/fm-backend-orca.test.sh:355 - test_kill_is_best_effort_close and its pass line "fm_backend_orca_kill: calls terminal close and stays best-effort" still describe the whole arm as best-effort, while after this change only the post-accept close is best-effort and a missing CLI is a reported failure. The new sibling case's comment already explains that the two are read together, so nothing is wrong, but the older name now reads as the contract rather than as one half of it. Out of scope here because this phase may not edit tests; worth a rename such as test_kill_stays_best_effort_once_the_cli_accepted_the_close in a later change that is already touching this file.
✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

bin/fm-teardown.sh discarded both the exit status and the stderr of every
fm_backend_kill call, so a close that genuinely failed was indistinguishable
from one that succeeded. Teardown continued past it, deleted the task's durable
records, returned its worktree, and reported the cleanup as completed. The
deleted metadata is the only record of which endpoint belongs to the task, so
such a close did not merely leave a stray session behind, it stranded one:
nothing was left on disk naming it.

The adapters could not carry that signal either. Driven against the real code,
every backend arm returned 0 for a genuine failure exactly as it did for an
already-exited endpoint, so there was nothing for the four call sites to
propagate even once they stopped swallowing it.

The tmux arm now resolves a close that did not succeed against the window's
exact recorded identity, since kill-window fails the same way for a window that
is gone and one that is still there. The Orca arm reports a close its missing
CLI never attempted. Both stay silent for an endpoint that is already
legitimately gone, and the remaining arms are unchanged: their close-command
timing cannot be established without the real Zellij, Orca, and cmux binaries,
and a gate that refused ordinary cleanup of an already-exited session would be
worse than the defect. docs/verification/runtime-backends.md records what each
backend can prove.

A reported close failure now reaches teardown's existing retain-and-stop
refusal before the records naming the endpoint are removed, matching where the
Herdr confirmed-gone gates already sit for the same hazard, and the retained
records let a rerun finish once the close works.
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: CI is still running after fork-workflow approval; holding for green checks before merge.

Closes verified: body has Closes #4483 and the diff addresses the four swallowed fm_backend_kill sites plus tmux/orca adapter honesty — matches the ready-for-pr restore filing.

Contract-class: restore — restores teardown's refuse-rather-than-fake-success spine when an endpoint close fails; already-gone stays silent; not a new default capability.

VISION: aligns — "Delegation with a spine" / honest refusal; does not hide a failed close behind a completed cleanup.

Attestation: MATCH (cc27cd59b269e23b6d2fadcef488b6c4b9f2c427 == HEAD).
no-mistakes: green (run 34935529206).
CI: in progress (run 34935529184); workflows approved.
Security: clean (shell/docs/tests only; no workflow/cred paths). Author aminry not blocked.
Mergeable: MERGEABLE; not draft.

Outcome: waiting-ci — will auto-merge when CI is fully green if still otherwise ready.

…. Both "CI" (run 34935529184) and "Require no-mistakes" (run 34935529206) returned conclusion=action_required with zero jobs and 0s duration (run_started_at == updated_at), which is this repo's workflow-approval gate holding the run before any job starts. No job executed, so nothing in the diff could have caused them; two unrelated branches (fm/captain-hold-json-nonref, fm/presenter-core-l1) show the identical shape in the same time window. Verified the change locally instead: bin/fm-lint.sh clean, bin/fm-test-run.sh --check-coverage ok, and all suites the diff touches pass (fm-teardown-endpoint-safety 25/25 including the five new endpoint-close cases, fm-backend-orca, fm-backend, fm-backend-tmux-smoke, fm-backend-cmux, fm-backend-zellij, fm-backend-herdr). Separately, I found and fixed a genuinely flaky test that the phase rules require me to make deterministic: tests/fm-tmux-agent-liveness.test.sh intermittently failed "an idle shell pane must classify dead" (verdict ambiguous, comms=[bash sleep]). It is selected by --changed for this diff, so it would run against this PR once CI is approved. Root cause, established by instrumenting the pane's process group: the idle window was created by `new-session` with no command, so it inherited tmux's default-shell, i.e. whoever runs the suite. ps on the pane tty showed `-zsh` -> `bash` -> `sleep`, all sharing pgid==tpgid, i.e. the host operator's shell configuration spawning a periodic helper directly into the pane's FOREGROUND process group, which is the one surface the classifier reads. `sleep` classifies as `other`, so fg_other=1 and the verdict became `ambiguous` instead of `dead` whenever that helper overlapped the 10s poll window. Every other window in the suite runs an explicit command via new_window; the idle case was the only one whose process group the host defined. Fix (smallest root-cause, test-only, 1 line + explanatory comment): create the idle window with an explicit bare `/bin/sh` (`-- /bin/sh`), the same shell the neighbouring background case already execs. Its foreground group is now exactly one process (verified: `/bin/sh` alone), so no host configuration can inject into it. This flake is pre-existing and NOT caused by this PR: an interleaved A/B showed base commit da5e658 failing the identical case (2/6 runs) alongside head (3/7 runs), and the diff only extracted the tmux inventory read into a helper with identical semantics while never touching fm_backend_tmux_foreground_comms. After the fix: 8/8 consecutive passes, with lint and the coverage guard still clean. Change left uncommitted in the working tree
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: tip moved to 2d14cff79ab8a132619142cad837763ebb0dfbd7 after the earlier waiting-ci stamp. Attestation still MATCH. Contract-class remains restore (refuse teardown when endpoint close fails — restores the promised unlanded/refusal path). Re-approved fork CI + Require no-mistakes for the new tip; holding for green CI before auto-merge. Still waiting on CI, not on the captain.

@aminry

aminry commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

Checking in on the auto-merge, with the facts rather than an ask.

Your 07:24 stamp said you had re-approved CI for tip 2d14cff7 and were holding for green before auto-merge. That condition has been met for about twelve hours:

  • last check run completed 2026-09-15T07:48:45Z
  • 15/15 SUCCESS, nothing failed, nothing skipped
  • mergeable: true, mergeable_state: clean, not draft, no requested reviewers
  • attestation MATCH on the same tip

Other PRs have merged since, so this does not look like a general hold. I mention it only in case the auto-merge pass did not pick this one up after the tip moved; if it is simply queued behind something, ignore this.

Nothing has changed on my side and I am not asking for priority. Happy to wait.

@kunchenguid
kunchenguid merged commit 1bdfd8c into kunchenguid:main Sep 15, 2026
15 checks passed
@kunchenguid

Copy link
Copy Markdown
Owner

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