Skip to content

fix(bin): stop teardown's lsof-absent fallback from killing processes outside the task worktree - #3161

Open
mackcee wants to merge 3 commits into
kunchenguid:mainfrom
mackcee:fm/fm-devserver-killed-by-teardown
Open

mackcee wants to merge 3 commits into
kunchenguid:mainfrom
mackcee:fm/fm-devserver-killed-by-teardown

Conversation

@mackcee

@mackcee mackcee commented Aug 27, 2026

Copy link
Copy Markdown

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:

  • This strengthens rather than weakens cleanup of genuine task-owned descendants: on a host without lsof the reap previously missed backgrounded leaks and now catches them. It protects no arbitrary process; the only scoping is the same per-task worktree/tasktmp cwd rule that already existed.
  • Chose the /proc fallback over two rejected alternatives: refusing teardown outright whenever lsof is absent (would break every teardown on such a host and push users to --force), and keeping the group kill with extra guards (a group signal cannot be filtered per member, so it can never satisfy the cwd contract).
  • The existing test test_lsof_absent_reaps_tmux_process_group asserted the old, buggy fallback, so it was replaced rather than kept. Its replacement deliberately asserts BOTH halves in one run so neither can regress alone, and it still installs a tmux stub reporting the outside-the-worktree process as the pane pid, so any return to process-group signalling fails the test.
  • The refusal message text changed from "(lsof failed)" to "(process scan failed)" because the scan is no longer lsof-specific; the one existing assertion on that string was updated to match.
  • The exec-changed-process fixture delegated to $REAL_LSOF_FOR_TEST, which is empty on a host without lsof. It now emits the same -Fpn cwd records from /proc in that case. This is a fixture that time-shifts a REAL scan, not one that fakes scan contents. That test was previously unreachable here because tests/lib.sh's fail() exits on the first failure and an earlier test was already failing on this host.
  • Intentionally NOT done, to keep the correction minimal: bin/fm-lint.sh's fm_lint_cleanup has a related latent pattern (kill -TERM -- "-$pid" on workers that are never process-group leaders because they are backgrounded without set -m). It is not the cause here and is effectively unreachable on this host (pid_max 4194304, sequential allocation, no wraparound), so it was left alone and flagged rather than folded into this change.
  • No docs/verification record was added: the guarantee is pinned by a portable regression test that CI enforces, and the change REMOVES harness dependence (it no longer reads tmux's #{pane_pid}) rather than adding a harness-dependent check, so the coding guidelines' live-harness guard requirement does not apply.
  • No AGENTS.md change: per the coding guidelines' knowledge-placement decision tree this is script mechanics, which belongs in the script's own header (where it was documented), not in the always-loaded instruction surface.
  • No Herdr lab was provisioned because no Herdr lifecycle experiment was required; the investigation concerned tmux process groups and /proc scanning.

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.sh no longer falls back to SIGTERMing the backend tmux pane's entire process group when lsof is 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_group is deleted; a new task_cwd_scan_source picks lsof, else a direct /proc/<pid>/cwd scan (pids_with_cwd_under_proc), so hosts without lsof keep 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.sh replaces the test that asserted the old process-group fallback with test_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 adds test_no_scan_source_reaps_nothing_and_warns using an unmounted-/proc override; the exec-changed-process fixture now emits -Fpn cwd records from /proc when no real lsof exists.
  • docs/configuration.md documents that FM_PROC_ROOT_OVERRIDE also 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: 1

=== 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: 1
Evidence: 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)

=== AFTER FIX (bin/fm-teardown.sh at target 7ad376a, same host without lsof) ===

--- new regression test: cwd-scoped reap via /proc, pane process group never signalled ---
ok - without lsof, teardown reaps by cwd via /proc and never signals the pane's process group
exit code: 0

--- existing leaked-process test: genuinely task-owned backgrounded leak ---
ok - a leaked descendant process rooted under the task's worktree is reaped by teardown, not left surviving
exit code: 0

--- new none-branch test: neither lsof nor /proc -> reap nothing, warn honestly ---
ok - with no usable scan source, teardown reaps nothing, warns honestly, and still succeeds
exit code: 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 intended

=== END-TO-END DEMO: unrelated task teardown vs a dev server running from the primary clone ===
=== bin/fm-teardown.sh at target 7ad376a, host without lsof (the incident configuration) ===

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 intended
Evidence: Full fm-teardown.test.sh suite transcript (59 ok, exit 0)
ok - local-only worktree with HEAD on a fork remote is torn down (fix holds)
ok - teardown prompts tasks-axi backlog refresh when compatible
ok - teardown honors config/backlog-backend=manual even when tasks-axi is compatible
ok - local-only worktree with truly unpushed work is refused (safety preserved)
ok - local-only worktree with work merged into local main is torn down (no regression)
ok - no-mistakes worktree with HEAD on origin is torn down (no regression)
ok - no-mistakes worktree with genuinely unlanded work is refused (safety preserved)
ok - local-only worktree with unpushed work is torn down under --force (escape hatch)
ok - teardown completes when an exact busy-state sidecar is already absent
ok - herdr teardown removes pane-owned escalation dedupe state
ok - herdr flat teardown refuses before returning the isolated copy under lock contention and the retry completes cleanly
ok - herdr flat teardown never erases records when pane presence is unparseable
ok - herdr flat teardown preflight refuses before every destructive change
ok - forced secondmate teardown preflights every Herdr child before cleanup mutation
ok - forced secondmate teardown holds every descendant lifecycle and metadata lock
ok - forced secondmate teardown retains Herdr child identity until exact pane disappearance
ok - forced teardown retains a nested secondmate home and its grandchild's Herdr identity when the grandchild close is unconfirmed
ok - herdr projection teardown retires its journal only after confirming the exact recorded pane is gone
ok - herdr projection teardown retains every record when post-close presence is unknown
ok - herdr projection teardown surfaces failed focus restoration without turning confirmed cleanup into a hard failure
ok - squash-merged + deleted-branch worktree (PR merged) is torn down (the fix)
ok - squash-merged PR accepts a local HEAD that is an ancestor of the final PR head
ok - teardown discovers a merged PR by branch name and tears down when no pr= was ever recorded
ok - squash-merged PR accepts replayed unpushed local patches contained in the PR head
ok - merged PR does not allow teardown after a later local commit
ok - fm-pr-check does not refresh PR head after HEAD moves
ok - fm-pr-check records the remote PR head when the local worktree lags
ok - worktree whose content already landed in the default branch is torn down (content fallback)
ok - content fallback refreshes origin default before comparing trees
ok - dirty worktree is refused even when its committed work has landed (dirty always wins)
ok - gh lookup error with content not in default refuses (fail-safe)
ok - provably-stale worktree index.lock (old, no live holder) is cleared and teardown succeeds
ok - live-held worktree index.lock is never removed and teardown refuses
ok - lsof errors leave worktree index.lock in place and refuse teardown
ok - stale lock cleanup rechecks and refuses dirty worktree before return
ok - normal repo index.lock is resolved from the worktree and cleared when stale
ok - lock mtime read failures leave worktree index.lock in place and refuse teardown
ok - transient index.lock cleared after first failed return is retried successfully without force-remove
ok - persistent index.lock exhausts retries and refuses without force-removing the lock
ok - empty retry wait overrides use the default without aborting teardown
ok - fractional legacy retry wait remains supported without arithmetic
ok - a task's own parked no-mistakes run is aborted, not orphaned, before the worker is removed
ok - teardown refuses before reap or removal when a task-owned run remains parked
ok - a different run cannot confirm the targeted abort
ok - empty post-abort status is not accepted as confirmation
ok - the CLI's exact run-not-found signal confirms completion
ok - a parked run on another branch is never aborted by this task's teardown (ownership is precise)
ok - a task-owned autonomous running step is left alone rather than aborted
ok - a leaked descendant process rooted under the task's worktree is reaped by teardown, not left surviving
ok - a leaked descendant process rooted under the task's per-task tasktmp is reaped by teardown too
ok - without lsof, teardown reaps by cwd via /proc and never signals the pane's process group
ok - with no usable scan source, teardown reaps nothing, warns honestly, and still succeeds
ok - an erroring lsof scan refuses teardown and preserves the task
ok - a reused pid with a different start time is never force-killed
ok - an exec change preserves birth identity and the process is reaped
ok - a process spawned during grace is reaped on a later pass
ok - persistent leaked processes refuse teardown after bounded retries
ok - a process exiting during identity lookup does not block teardown
ok - the run abort and the leaked-process reap both complete before the destructive worktree return
fm-teardown.test.sh exit code: 0
Evidence: fm-teardown-endpoint-safety.test.sh transcript (exit 0)
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: 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
fm-teardown-endpoint-safety.test.sh exit code: 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_group and test_leaked_worktree_process_is_reaped run against bin/fm-teardown.sh at 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 plus test_no_scan_source_reaps_nothing_and_warns against target 7ad376a — all pass
  • Manual 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 survived
  • Environment verification: command -v lsof absent and /proc/self present, matching the incident host configuration so the new /proc scan path is the live path exercised
✅ **Document** - passed

✅ No issues found.

⚠️ **Lint** - 1 warning
  • ⚠️ linter found issues (exit code 1)
✅ **Push** - passed

✅ No issues found.

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.
@greptile-apps

greptile-apps Bot commented Aug 27, 2026

Copy link
Copy Markdown

Confidence Score: 5/5

The 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant