Repository navigation
fix(bin): stop teardown's lsof-absent fallback from killing processes outside the task worktree - #3161
Open
mackcee wants to merge 3 commits into
Open
fix(bin): stop teardown's lsof-absent fallback from killing processes outside the task worktree#3161mackcee wants to merge 3 commits into
mackcee wants to merge 3 commits into
Conversation
fm-teardown.sh's Fix 2 reap promises, in its own header, that it "can never reach another task's or the primary's processes" because it scopes by working directory. That held only on the lsof path. With lsof absent it fell back to TERMing the backend pane's ENTIRE process group with no cwd check, so any process in that group died regardless of where it was working - including an ApplyPilot dev server running from the primary clone, which exited 143 right after a task's cleanup. The fallback also failed at its own job: a job backgrounded in the pane gets a process group of its own, so the group kill missed exactly the backgrounded leaks Fix 2 exists to catch. On a host without lsof the existing leaked-process test fails against the old code. Read /proc/<pid>/cwd when lsof is absent, keeping identical cwd scoping, and drop the process-group kill entirely. A host with neither source reaps nothing and says so, because no cheaper signal (a pane's process group, a port, a process name) proves a process belongs to the task. A scan error still refuses before destructive teardown. The regression test asserts both halves in one run: the task-owned process under the worktree is still reaped, and a process sharing the pane's process group while working outside the worktree survives.
Confidence Score: 5/5The PR appears safe to merge, with the new fallback preserving task ownership boundaries and no actionable defects identified. The changed teardown path identifies processes by canonical task-root cwd before signaling them, avoids guessing when neither scanner is available, and has focused tests covering both cleanup and isolation behavior. Reviews (1): Last reviewed commit: "no-mistakes(document): document teardown..." | Re-trigger Greptile |
This was referenced Aug 27, 2026
This was referenced Oct 17, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Intent
Investigate and fix the mechanism that sent SIGTERM to an ApplyPilot development server running from the primary clone while unrelated isolated tasks were active.
Evidence given at intake: three separate Next.js development-server exits with code 143 on 2026-08-19. One occurred during a task spawn/design window, one immediately after another task's cleanup, and one while no cleanup was running - only two worker messages and two isolated workers rebasing/rerunning suites. That weakened a cleanup-only theory. Plausible sources named at intake: worker test/build commands killing by process name or port, treehouse/Herdr process-group cleanup, or Next/Turbopack itself. The server already has an auto-respawn wrapper, so this was diagnosis, not emergency recovery.
Acceptance criteria set at intake: follow the firstmate-coding-guidelines skill before changing shared tracked material; reproduce or instrument the signal path enough to identify the sender/mechanism from evidence, inspecting only this home's relevant task/runtime records and never broadly sweeping or killing processes; use the generated guarded Herdr lab for any Herdr lifecycle experiment and never touch the captain's live workspace or other active workers; distinguish the cleanup, worker-command, process-group and server-self-exit hypotheses with disconfirming evidence; implement the smallest justified correction plus focused regression/verification coverage, without weakening cleanup of genuine task-owned descendants and without protecting arbitrary unrelated processes; run shellcheck and colocated tests for changed scripts plus the maintainer-verification evidence the coding guidelines require.
WHAT WAS FOUND (root cause, since accepted by the supervising firstmate). bin/fm-teardown.sh's "Fix 2" leaked-process reap promises in its own header that it "can never reach another task's or the primary's processes", because it scopes by working directory. That promise held only on the lsof path. When lsof is missing, reap_task_worktree_processes fell back to reap_task_backend_process_group, which sent SIGTERM to the backend tmux pane's ENTIRE process group with no cwd check at all. lsof is not installed on this host, so that unscoped fallback was the only path that ever ran here.
Confirmed empirically, not inferred: a probe using Python's sigwaitinfo to capture the sending PID showed the group kill delivering SIGTERM (exit 143) to a process whose working directory was the primary clone, entirely outside the task worktree. The same isolated tmux experiment (run on a private tmux socket, never the captain's server) also disconfirmed the fallback's own purpose: a job backgrounded inside a pane receives its own process group, so the group kill misses exactly the backgrounded/disowned leaks Fix 2 exists to catch. Running the unmodified code on this host, teardown's own existing leaked-process test fails - the old fallback does not reap a genuinely task-owned process here.
Hypotheses ruled out with disconfirming evidence: ApplyPilot's e2e suite starts each server on an unused ephemeral port in its own detached process group and never probes port 3000, and neither repo's tracked tooling contains any pkill/port-based kill; treehouse scopes its own "terminate lingering processes" by cwd-in-worktree (pool.cwdInWorktree via gopsutil Process.Cwd), the same correct contract; no script auto-invokes fm-teardown.sh, so teardown only runs when explicitly invoked.
THE FIX. Add task_cwd_scan_source (lsof, else /proc, else none) and pids_with_cwd_under_proc, which reads /proc//cwd directly so a host without lsof keeps identical cwd scoping. Delete reap_task_backend_process_group entirely. A host with neither source now reaps nothing and says so, deliberately preserving the previous non-fatal behaviour for that case rather than refusing teardown, because no cheaper signal (a pane's process group, a port, a process name) can prove a process belongs to the task. A scan ERROR still refuses before destructive teardown, unchanged.
DELIBERATE DECISIONS a reviewer reading only the diff would not know:
HONEST LIMITATION, deliberately not overclaimed: this mechanism explains the event that followed a task's cleanup. The two events with no cleanup running were not this mechanism, and the remaining evidence points to ad-hoc worker kill commands, which this home's own recorded learning from that period already warns about.
Verification run: shellcheck clean; bin/fm-lint.sh exits 0 (ShellCheck 0.11.0 pinned, actionlint 1.7.12, 3 workflows valid); tests/fm-teardown.test.sh 0 failures; tests/fm-teardown-endpoint-safety.test.sh 0 failures; bin/fm-test-run.sh --changed selected 5 scripts, total=5 failed=0; bin/fm-doc-audience-check.sh ok.
What Changed
bin/fm-teardown.shno longer falls back to SIGTERMing the backend tmux pane's entire process group whenlsofis missing — a path that could kill unrelated processes working outside the task worktree (e.g. a dev server run from the primary clone, exit 143) while still missing backgrounded leaks.reap_task_backend_process_groupis deleted; a newtask_cwd_scan_sourcepickslsof, else a direct/proc/<pid>/cwdscan (pids_with_cwd_under_proc), so hosts withoutlsofkeep the same task-owned cwd scoping. With neither source available, teardown reaps nothing and warns instead of guessing; a scan error still refuses before destructive teardown, and the refusal message now says "process scan failed" instead of "lsof failed".tests/fm-teardown.test.shreplaces the test that asserted the old process-group fallback withtest_lsof_absent_scopes_reap_by_cwd_not_process_group(asserts in one run that the task-owned process is reaped and a pane-group process outside the worktree survives) and addstest_no_scan_source_reaps_nothing_and_warnsusing an unmounted-/procoverride; the exec-changed-process fixture now emits-Fpncwd records from/procwhen no reallsofexists.docs/configuration.mddocuments thatFM_PROC_ROOT_OVERRIDEalso covers fm-teardown.sh's lsof-absent leaked-process cwd scan.Risk Assessment
✅ Low: Both accepted fix-round findings are correctly and minimally implemented, the new tests deterministically discriminate the fixed behavior from every plausible regression (group-kill return, empty-scan-as-success, refusal), and a full re-review of the change against the base found no remaining reachable path that violates the cwd-scoping invariant or any intent constraint.
Testing
Ran both colocated teardown suites (59 + 4 tests, all passing, exit 0) on a host matching the incident configuration (no lsof, /proc mounted), proved the regression test fails before the fix by running it against the base-commit script (it catches both the outside-the-worktree kill and the missed task-owned leak), and captured an end-to-end CLI transcript where an unrelated task's teardown reaps only its own leaked process while a stand-in dev server running from a primary-clone directory survives; no UI surface is involved, so transcripts are the reviewer-visible evidence.
Evidence: Before-fix regression transcript (base 10b93b2: outside process killed, task-owned leak missed)
=== BEFORE FIX (bin/fm-teardown.sh at base 10b93b2, host without lsof) === --- new regression test: outside-the-worktree process (stand-in for the primary-clone dev server) --- not ok - lsof-absent-cwd-scoped-reap: teardown killed a process working outside the worktree exit code: 1 --- existing leaked-process test: genuinely task-owned backgrounded leak --- not ok - leaked-process-reap: leaked worktree process survived teardown exit code: 1Evidence: After-fix regression transcript (target 7ad376a: cwd-scoped via /proc, none-branch honest)
=== AFTER FIX (bin/fm-teardown.sh at target 7ad376a, same host without lsof) === ok - without lsof, teardown reaps by cwd via /proc and never signals the pane's process group (exit 0) ok - a leaked descendant process rooted under the task's worktree is reaped by teardown, not left surviving (exit 0) ok - with no usable scan source, teardown reaps nothing, warns honestly, and still succeeds (exit 0)Evidence: End-to-end demo: dev server from primary clone survives unrelated task teardown
stand-in dev server (cwd = primary clone, NOT the task worktree): pid 2464039 task-owned leaked process (cwd = task worktree): pid 2464040 running: fm-teardown.sh task-x1 (host has no lsof) teardown exit code: 0 teardown stderr (reap/warning lines): teardown: reaping leaked worktree process(es) for task-x1: 2464040 RESULT: dev server pid 2464039 SURVIVED the unrelated task's teardown RESULT: task-owned leaked pid 2464040 was reaped as intendedEvidence: Full fm-teardown.test.sh suite transcript (59 ok, exit 0)
Evidence: fm-teardown-endpoint-safety.test.sh transcript (exit 0)
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
🔧 **Review** - 3 issues found → auto-fixed ✅
tests/fm-teardown.test.sh:2328- The new 'neither lsof nor /proc' branch (bin/fm-teardown.sh:1672-1674, which skips reaping with a warning) is only exercised by the test's else-branch, which requires a host without /proc — dead on every Linux/CI host. Since FM_PROC_ROOT_OVERRIDE already flows through run_teardown and is used by sibling tests, add a deterministic case combining FM_TEARDOWN_TEST_PATH=<path-without-lsof> with FM_PROC_ROOT_OVERRIDE=<missing dir>, asserting the 'cannot identify leaked ... so none are reaped' warning, that teardown still succeeds, and that neither sentinel process is signalled.bin/fm-teardown.sh:1544- task_cwd_scan_source classifies an existing-but-unmounted /proc mountpoint (empty dir, e.g. a chroot or rescue environment) as source 'proc': the scan then returns success with zero pids, so teardown proceeds silently as if it had scanned, bypassing the explicit 'none' warning path the design reserves for hosts that cannot scan. A cheap sanity check such as [ -e "$proc_root/self" ] (or "$proc_root/$$") before returning 'proc' would route that host to the honest 'none' warning instead.bin/fm-teardown.sh:1564- pids_with_cwd_under_proc forks one readlink per /proc entry per scan, and reap_task_worktree_processes rescans up to ~5 times per pass across up to 3 passes and 2 roots, so an lsof-less host pays O(passes x nprocs) forks per teardown versus one lsof process per scan previously. Acceptable for an infrequent, human-invoked teardown (common case is a single scan per root); noted as a deliberate portability tradeoff, no action needed.🔧 Fix: detect unmounted /proc as unscannable; pin none-branch with test
✅ Re-checked - no issues remain.
✅ **Test** - passed
✅ No issues found.
bash tests/fm-teardown.test.sh(full colocated suite, 59 ok / 0 failures, exit 0)bash tests/fm-teardown-endpoint-safety.test.sh(exit 0)Fail-before check:test_lsof_absent_scopes_reap_by_cwd_not_process_groupandtest_leaked_worktree_process_is_reapedrun againstbin/fm-teardown.shat base 10b93b2 via a transient single-test runner — both fail as the intent claims (outside-the-worktree process killed; task-owned leak not reaped)Pass-after check: same two tests plustest_no_scan_source_reaps_nothing_and_warnsagainst target 7ad376a — all passManual end-to-end demo: fm-teardown.sh run on a task with no lsof on PATH, with a stand-in dev server (cwd = primary-clone directory) and a task-owned leaked process (cwd = task worktree); teardown exited 0, reaped only the task-owned pid, and the dev server survivedEnvironment verification:command -v lsofabsent and/proc/selfpresent, matching the incident host configuration so the new /proc scan path is the live path exercised✅ **Document** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.