Repository navigation
fix(bin): refuse teardown when a task's endpoint close fails - #4510
Conversation
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.
… and retirement owners
|
Speaking as Kun's firstmate: CI is still running after fork-workflow approval; holding for green checks before merge. Closes verified: body has 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 ( 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
|
Speaking as Kun's firstmate: tip moved to |
|
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
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. |
|
Speaking as Kun's firstmate: this is merged. Thank you @aminry — really appreciate you taking the time on this. |
Intent
bin/fm-teardown.shdiscards the result of everyfm_backend_killcall, so a kill that genuinelyfailed 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:
fm_backend_killdoes report failure, including an expliciterror: 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.mdalready makesteardown 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
mainand classed it restore. It also established that thefail-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-windowfails the sameway 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.shis changed in this PR and is not part of this fix's subject, soit 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/shinstead of letting tmux fall back todefault-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
da5e658failing the identical case "an idle shell paneclassifies 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-shellis whoever runs the suite, sothe 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
sleepthere classifies as
other, so the verdict becameambiguousinstead ofdeadon exactly the runswhere such a helper overlapped the poll window. A bare
/bin/shis 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
--changedfor 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.shnow propagates the status of all fourfm_backend_killcall sites instead of discarding it behind2>/dev/null || true, routing a failed close into a newendpoint_close_refusalhelper that stops the cleanup before any record naming the endpoint is removed.--forceoverrides 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_killresolves a failedkill-windowby re-reading the window's exact recorded identity (=sessionplus a whole-line name match) through a new sharedfm_backend_tmux_window_inventoryhelper, whichfm_backend_tmux_agent_statenow 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_killreturns nonzero when the missingorcaCLI means no close was ever attempted; Zellij, cmux, and Herdr arms are unchanged and still report 0.tests/fm-teardown-endpoint-safety.test.shandtests/fm-backend-orca.test.sh(refusal,--forcecontinue, unreadable re-read, forced child close, already-exited endpoint and dead server still completing silently), plus a per-backend "Endpoint close" table indocs/verification/runtime-backends.mdand matching notes indocs/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 realbin/fm-teardown.shCLI against real tmux 3.7c servers on isolated sockets in isolatedFM_HOMEs, with the surviving window and the survivingstate/<id>.metainspected directly after each run. The headline case uses no injection at all: a live task window plus a teardown whose PATH has notmux. 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--forceis 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 withouttmuxon PATH now refuses even for an endpoint that is genuinely gone, with--forceas 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.teardown strand-demo complete, removes st…fm-strand-demois gone from the real session's window list, and the record is removedteardown gone-task complete, no close refusal on stderr, record removederror: tmux window crew:fm-survivor-task is still present after its close, exit 1, record retained, window still listed--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…fm-neighbourabsent whilefm-neighbour-extrais live and the close fails; teardown completes at exit 0, removes the record, and leaves the neighbour untouchedbackend=orca selected but the 'orca' CLI is not installed, no--force authorizes continuingline, state/orca-strand.meta retained; unforced run refuses identicallybin/fm-teardown.sh mate-task --forceexits 1, nameschild child-task, retains both the parent and child records, and the child's tmux window is still livereturn 0or|| 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
Evidence: Evidence index mapping each scenario to its observed result
Source: Evidence index mapping each scenario to its observed result
Evidence: Driver scripts that produced the transcripts
Source: Driver scripts that produced the transcripts
Evidence: tests/fm-teardown-endpoint-safety.test.sh run
Source: tests/fm-teardown-endpoint-safety.test.sh run
Evidence: tests/fm-backend-orca.test.sh run
Source: tests/fm-backend-orca.test.sh run
Evidence: Before/after on the same live tmux window: base strands it, branch refuses
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 "=$session" ... 2>/dev/null | grep -qxF -- "$window" || return 0cannot 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 definitivecan't find session:/no server running on/error connecting to ...response asmissing, and any other inventory failure asunreadable, 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 wheretmuxis not on teardown's curated lifecycle PATH (tests/fm-teardown.test.sh:659 builds exactly such a PATH), sokill-windowfails ANDlist-windowsfails 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 printsteardown <id> completewhile 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 theexit 1. The next bin/fm-bootstrap.sh run sweeps"$STATE"/*.backlog-close(bin/fm-bootstrap.sh:1238) and fm_backlog_close_marker_replay deletes the retained record withfm_backlog_atomic_transition remove "$meta"(bin/fm-backlog-transition-lib.sh:1189, which is a plainrm -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 whenevercommand -v orcafails, and bin/fm-teardown.sh:3338 turns that intoexit 1unconditionally ---forcedoes 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--forceshould 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 runsfm_backend_kill "$backend" "$target" 2>/dev/null || trueand 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 readdead(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--forceoverride 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_checkfailed, i.e. noorcaon PATH. The very next statement after the forced continue isfm_backend_remove_worktree "$BACKEND" "$ORCA_WORKTREE_ID"(bin/fm-teardown.sh:3367), which callsfm_backend_orca_remove_worktree->fm_backend_orca_tool_check || return 1(bin/backends/orca.sh:183). It is an unguarded simple command underset -eu(bin/fm-teardown.sh:259), so the script dies with status 1 right there. Concrete sequence: orca-backed scout task,orcauninstalled, recorded worktree path already gone (sorequire_orca_worktree_path_match_if_presentat 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's records anyway; nothing on disk will name <terminal> 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--forcedoes 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--forceonly 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--forcearm 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 drivingfm_backend_killagainst 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 drivesfm_backend_orca_kill(orfm_backend_kill orca) withorcaoff 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 anorcastub 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 1at 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 drivingfm_backend_orca_killunder a PATH with noorcaand 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.
teardown strand-demo complete, removes st…fm-strand-demois gone from the real session's window list, and the record is removedteardown gone-task complete, no close refusal on stderr, record removederror: tmux window crew:fm-survivor-task is still present after its close, exit 1, record retained, window still listed--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…fm-neighbourabsent whilefm-neighbour-extrais live and the close fails; teardown completes at exit 0, removes the record, and leaves the neighbour untouchedbackend=orca selected but the 'orca' CLI is not installed, no--force authorizes continuingline, state/orca-strand.meta retained; unforced run refuses identicallybin/fm-teardown.sh mate-task --forceexits 1, nameschild child-task, retains both the parent and child records, and the child's tmux window is still livereturn 0or|| 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(includestest_kill_refuses_when_the_orca_cli_is_absent)Manual operator drive A: live tmux window +bin/fm-teardown.sh strand-demounder a curated PATH with notmuxManual operator drive A': identical fixture against the base commit tree extracted fromda5e658(git archive), showing the pre-fix strandingManual operator drive B: rerun of the same task id with tmux reachableManual operator drive C:bin/fm-teardown.sh gone-taskwith the recorded window already exitedManual operator drive D/E:kill-windowfailing while the window is really alive, without and with--forceManual operator drive F: recorded window absent, prefix neighbourfm-neighbour-extraalive, close failingManual operator drive G:backend=orcarecord with noorcaCLI on the host, run with--forceand withoutManual operator drive H:bin/fm-teardown.sh mate-task --forcewith a secondmate child whose tmux close failsManual operator drive I:bin/fm-teardown.shforbackend=zellijandbackend=cmuxrecords on a host with neither CLIManual drive J:fm_backend_kill <backend> <target>invoked directly for tmux/zellij/cmux/herdr already-gone targetstests/fm-backend-orca.test.sh:355-test_kill_is_best_effort_closeand 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 astest_kill_stays_best_effort_once_the_cli_accepted_the_closein a later change that is already touching this file.✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.