Skip to content

fix(teardown): reap only processes owned by the task's endpoint shell - #7566

Open
Azd325 wants to merge 30 commits into
kunchenguid:mainfrom
Azd325:fm/fm-7420-teardown-foreign-shell
Open

Azd325 wants to merge 30 commits into
kunchenguid:mainfrom
Azd325:fm/fm-7420-teardown-foreign-shell

Conversation

@Azd325

@Azd325 Azd325 commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

What Changed

  • bin/fm-teardown.sh no longer kills every process whose cwd is the task worktree or tasktmp. It records the endpoint shell's ownership before the pane or backend closes. It reaps only descendants of that shell and members of the session it leads. Foreign or unowned processes are spared.
  • Teardown keeps the worktree, slot, or secondmate home and its metadata, and exits 1, when a spared process still runs there, when work appears during the wait, or when the process scan cannot complete. It appends each kill, spare, and kept-worktree decision to state/teardown-processes.log. The Orca pending backlog close marker is written before the irreversible removal. Every later refusal clears it, so startup replay does not close a retained task. Without lsof, Orca and tasktmp cleanup warns and then removes the worktree.
  • tests/fm-teardown.test.sh and tests/fm-backend-t3code.test.sh add and update cases for the new behavior. The docs (configuration, herdr-backend, orca-backend, t3code-backend) describe the ownership rules, the kept-worktree behavior, and the log file.

Risk Assessment

✅ Low: The test changes match the reviewed teardown behavior: unowned processes are spared, kept roots are reported, and the close marker survives a startup replay. Each new test is wired into the runner, and only two refusal-replay cases have a weaker check on which path refused.

Testing

The HEAD commit only edits one sentence in docs/orca-backend.md. I checked it against reap_task_backend_process_group by reading the code. I ran the relevant teardown tests against the real scripts. All passed. The full teardown suite hit my 570s limit, so I ran selected tests instead. I did not run the full suite to completion. I ran no live Herdr scenario.

  • Live validation: ✅ go - 3 of 4 scenarios driven live against the product
Scenario Result Live Evidence
Doc sentence about Orca cleanup without lsof matches the teardown code (warns, no process-group fallback, then removes the worktree) ⏸️ untested no The prior payload recorded live=false for this scenario. It checked the doc by reading code only, so it did not establish a live result.
Shared refusal step: after a refusal the task record and in_flight backlog row survive startup replay, on every refusal path ✅ pass live teardown-selected.log: test_post_reap_refusals_keep_backlog_open_after_replay passes for endpoint-close, export, inactive-report, grok-auth, kimi-auth, busy-state, pr-poll, status-archive and the t3 p…
Orca worktree occupied by a spared process is kept, and the records survive for a retry ✅ pass live teardown-selected.log
Missing lsof does not block Orca or tasktmp removal, or a local secondmate's tasktmp removal, with and without force ✅ pass live teardown-selected.log
Evidence: selected teardown tests log

Source: selected teardown tests log

ok - teardown leaves opencode's busy plugin in the returned pool worktree as on main
ok - reaper-scan preserves the task record and in_flight row after startup replay
ok - post-reap-work preserves the task record and in_flight row after startup replay
ok - treehouse-pre-return preserves the task record and in_flight row after startup replay
ok - treehouse-write preserves the task record and in_flight row after startup replay
ok - treehouse-commit preserves the task record and in_flight row after startup replay
ok - orca-write preserves the task record and in_flight row after startup replay
ok - orca-commit preserves the task record and in_flight row after startup replay
ok - orca-kept preserves the task record and in_flight row after startup replay
ok - treehouse-return preserves the task record and in_flight row after startup replay
ok - orca-remove preserves the task record and in_flight row after startup replay
ok - endpoint-close preserves the task record and in_flight row after startup replay
ok - export preserves the task record and in_flight row after startup replay
ok - inactive-report preserves the task record and in_flight row after startup replay
ok - grok-auth preserves the task record and in_flight row after startup replay
ok - kimi-auth preserves the task record and in_flight row after startup replay
ok - busy-state preserves the task record and in_flight row after startup replay
ok - pr-poll preserves the task record and in_flight row after startup replay
ok - status-archive preserves the task record and in_flight row after startup replay
ok - t3-close preserves the task record and in_flight row after startup replay
ok - t3-env preserves the task record and in_flight row after startup replay
ok - t3-home preserves the task record and in_flight row after startup replay
ok - t3-home-scan preserves the task record and in_flight row after startup replay
ok - an Orca worktree that a spared process occupies is kept and the records survive for a retry
ok - a missing lsof falls back to base behavior for Orca and tasktmp removal, with and without force
ok - a missing lsof does not keep a local secondmate's tasktmp, with and without force
Evidence: full teardown suite partial log (timed out at 570s, all tests up to the limit passed)

Source: full teardown suite partial log (timed out at 570s, all tests up to the limit passed)

ok - teardown leaves opencode's busy plugin in the returned pool worktree as on main
ok - reaper-scan preserves the task record and in_flight row after startup replay
ok - post-reap-work preserves the task record and in_flight row after startup replay
ok - treehouse-pre-return preserves the task record and in_flight row after startup replay
ok - treehouse-write preserves the task record and in_flight row after startup replay
ok - treehouse-commit preserves the task record and in_flight row after startup replay
ok - orca-write preserves the task record and in_flight row after startup replay
ok - orca-commit preserves the task record and in_flight row after startup replay
ok - orca-kept preserves the task record and in_flight row after startup replay
ok - treehouse-return preserves the task record and in_flight row after startup replay
ok - orca-remove preserves the task record and in_flight row after startup replay
ok - endpoint-close preserves the task record and in_flight row after startup replay
ok - export preserves the task record and in_flight row after startup replay
ok - inactive-report preserves the task record and in_flight row after startup replay
ok - grok-auth preserves the task record and in_flight row after startup replay
ok - kimi-auth preserves the task record and in_flight row after startup replay
ok - busy-state preserves the task record and in_flight row after startup replay
ok - pr-poll preserves the task record and in_flight row after startup replay
ok - status-archive preserves the task record and in_flight row after startup replay
ok - t3-close preserves the task record and in_flight row after startup replay
ok - t3-env preserves the task record and in_flight row after startup replay
ok - t3-home preserves the task record and in_flight row after startup replay
ok - t3-home-scan preserves the task record and in_flight row after startup replay
ok - hidden untracked work is refused before return while a clean control returns
ok - content fallback distinguishes unavailable Git proof, containment, conflicts, and unlanded content
orca/reap-refusal: teardown_exit=1 replay_exit=0 metadata_after_replay=retained backlog_after_replay=in_flight
tmux/reap-refusal: teardown_exit=1 replay_exit=0 metadata_after_replay=retained backlog_after_replay=in_flight
ok - post-reap proof retains late work and retry records on ordinary and Orca paths, preserving clean/force/scout behavior
ok - status archival is opt-in and preserves the complete log
ok - config-absent teardown does not read or invoke record export
ok - unopted teardown ignores symlinked config when record export is absent
ok - teardown commits the record archive before deleting sources and fails closed when export cannot commit
ok - forced secondmate teardown exports task records from the child sub-state
ok - record export waits for endpoint quiescence and retry captures records changed after refusal
ok - forced secondmate retirement preserves two descendant levels and refuses linked child directories
ok - local missing-status retirement stays lock-free without creating an archive
ok - reused task IDs never overwrite archives and retention removes only old owned logs
ok - archive sources and directories reject symlinks; pruning never follows children links
ok - failed archive publication preserves presentation and watcher bookkeeping
ok - cursor retirement failure removes its archive so retry publishes one history
ok - archive publication and cold logs never re-wake or re-present
ok - retention failures warn without aborting unrelated teardown
ok - a missing teardown startup source refuses before cleanup
ok - an unreadable teardown startup source refuses before cleanup
ok - a missing adapter sibling refuses before cleanup
ok - a forced descendant with a missing adapter sibling refuses before cleanup
ok - a forced secondmate with a missing own adapter sibling refuses before child cleanup
ok - present required sources still reach the ordinary teardown refusal
ok - local-only worktree with HEAD on a fork remote is torn down and the home summary is refreshed
ok - teardown closes its own backlog item before reporting success
ok - teardown closes a landed Gerrit task with its change URL as a note and a GitHub task with --pr
ok - teardown closes a landed GitLab task with its merge request URL as a note and GitHub and Forgejo tasks with --pr
ok - teardown honors config/backlog-backend=manual and still finishes cleanly
ok - local-only worktree with truly unpushed work is refused (safety preserved)
ok - local-only worktree with work merged into local main is torn down (no regression)
ok - no-mistakes worktree with HEAD on origin is torn down (no regression)
ok - no-mistakes worktree with genuinely unlanded work is refused (safety preserved)
ok - branch pushed only to the no-mistakes mirror is refused as unlanded
ok - local-only worktree with unpushed work is torn down under --force (escape hatch)
ok - fm-pr-check publishes the PR-ready line on a secondmate's parent channel once
ok - fm-pr-check withholds the PR-ready line until checks are green when config/ready-after-green is present
ok - fm-pr-check releases the PR-ready line on a checks-green report that carries surrounding text
ok - a secondmate home's teardown delivers the child's final line or refuses until it can
ok - teardown completes when an exact busy-state sidecar is already absent
ok - teardown retires a polytoken task's generated worktree wiring on pool return
ok - teardown never deletes a tracked .polytoken hook layer
ok - teardown never deletes a .polytoken hook layer firstmate did not generate
ok - teardown scopes .polytoken wiring removal to polytoken tasks
ok - herdr teardown removes pane-owned escalation dedupe state
ok - herdr flat teardown refuses before returning the isolated copy under lock contention and the retry completes cleanly
ok - herdr flat teardown never erases records when pane presence is unparseable
ok - herdr flat teardown preflight refuses before every destructive change
ok - herdr teardown refuses a foreign-owned per-account namespace (owner-shim arms need the non-Darwin stat branch; skipped on Darwin)
ok - forced secondmate teardown preflights every Herdr child before cleanup mutation
ok - forced secondmate teardown holds every descendant lifecycle and metadata lock
ok - forced secondmate teardown retains Herdr child identity until exact pane disappearance
ok - forced teardown retains a nested secondmate home and its grandchild's Herdr identity when the grandchild close is unconfirmed
ok - herdr projection teardown retires its journal only after confirming the exact recorded pane is gone

Pipeline

Updates from git push no-mistakes

✅ **Intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

⚠️ **Review** - 1 info
  • ℹ️ tests/fm-teardown.test.sh:6893 - In test_post_reap_refusals_keep_backlog_open_after_replay, the grok-auth and kimi-auth cases set expected='' (:6891-6894). The test then checks only that the exit code is 1 and that the backlog row survives a replay. It never confirms that the refusal came from the auth-token step. Concrete case: an earlier refusal before the marker is written (for example a fixture setup error) also exits 1, and the replay check then passes trivially. In that case the auth exits after the marker are not exercised. Every other case greps a path-specific stderr string. Remedy: set expected to the auth refusal message that fm-teardown.sh prints for a leftover <kind>-turnend-token, so the case fails when a different path refuses.
✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 3 of 4 scenarios driven live against the product
Scenario Result Live Evidence
Doc sentence about Orca cleanup without lsof matches the teardown code (warns, no process-group fallback, then removes the worktree) ⏸️ untested no The prior payload recorded live=false for this scenario. It checked the doc by reading code only, so it did not establish a live result.
Shared refusal step: after a refusal the task record and in_flight backlog row survive startup replay, on every refusal path ✅ pass live teardown-selected.log: test_post_reap_refusals_keep_backlog_open_after_replay passes for endpoint-close, export, inactive-report, grok-auth, kimi-auth, busy-state, pr-poll, status-archive and the t3 p…
Orca worktree occupied by a spared process is kept, and the records survive for a retry ✅ pass live teardown-selected.log
Missing lsof does not block Orca or tasktmp removal, or a local secondmate's tasktmp removal, with and without force ✅ pass live teardown-selected.log
  • Read git show HEAD: one doc line changed
  • Read reap_task_backend_process_group in bin/fm-teardown.sh: it warns and returns for non-tmux backends when lsof is missing
  • Ran a trimmed copy of tests/fm-teardown.test.sh with test_post_reap_refusals_keep_backlog_open_after_replay, test_orca_worktree_with_a_spared_process_is_not_removed, test_missing_lsof_does_not_block_orca_or_tasktmp_removal and test_missing_lsof_does_not_block_local_secondmate_tasktmp_removal: exit 0
  • Ran full tests/fm-teardown.test.sh in the foreground: the 570s timeout hit, with every test up to that point passing
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thank you @Azd325 for picking up #7420. That's the suggestion that actually lost work, and the deferred-return and keep logic is thoughtful. Checked against main a65dceee at head 171990a5. CI is green (20/20), and the no-mistakes attestation matches this head.

This is waiting on you. Here's what's needed:

  1. Live validation. The pipeline reports 0 of 4 scenarios driven live. Could you run a real teardown on a scratch task, with a foreign shell whose cwd is in the worktree and a task-owned background child? Then post the evidence (shell survives and is reported, child reaped, worktree kept), or re-raise through no-mistakes with live validation.
  2. Don't drop the original Fix 2 case. Ownership here means "descendant of the endpoint shell, or in its process group". A disowned/backgrounded process whose parent already exited gets reparented to init. Those are exactly the leaked go test binaries the header was written for, and this PR now spares them as "reparented orphans". On backends where task_reap_endpoint_pid returns nothing (cmux, orca, zellij), every process is spared, so the leak reap is effectively off there. Could you keep reaping those? One option is to also treat processes in the endpoint shell's session (same SID) as task-owned. A foreign login shell on another TTY has a different SID, while an orphaned task child keeps the pane's. Please also say how non-tmux/herdr backends should behave.
  3. Durable record. Teardown can kill the primary session's shell; stopped duplicate instances then append calm notes to a stale branch and resume continues there #7420 also asked that every kill (and now every spare) be logged durably under state/, not only on stderr, because the caller's output was lost in the incident. Please add that or say why not.

Contract-class: new-default (as built). On the triage of #7420, the "don't kill what teardown doesn't own" part was classed restore, because the header promised the reap can't reach the primary's processes. This tip goes further. It replaces the specified Fix 2 path (reap leaked task processes, including init-reparented ones) with "spare anything not provably descended". It also disables the reap on backends with no endpoint pid. That changes the unconfigured run beyond the restore, so it would need Kun's call. If the orphan and backend cases are kept, the restore reading comes back into reach.

VISION.md, rule by rule

  • One captain, one interface: aligns. Spared processes are named rather than silently killed.
  • Authority is explicit and never inferred: aligns on the direction (refuse to destroy what can't be proven owned). Cannot tell on the orphan regression until point 2 is answered.
  • Scripts own the mechanics, agents own the judgment: aligns. The ownership check is exact.
  • A restart is a non-event: partly. A stderr-only report isn't a durable record (point 3).
  • Delegation with a spine: aligns. It keeps the worktree when it can't prove cleanliness.
  • The fleet outlives any vendor: does not align yet. The reap now works only on tmux/herdr.
  • Scope: aligns. Command-layer lifecycle with regression tests.

Overlap: it touches the same lsof-absent fallback as #3161 and the treehouse return area as #6067 (conflicting), so expect a rebase if either lands. No overlap with your other three PRs.

@Azd325
Azd325 force-pushed the fm/fm-7420-teardown-foreign-shell branch from 171990a to b08de43 Compare October 20, 2026 18:25
@Azd325 Azd325 changed the title fix: spare unowned processes during task teardown reap fix(teardown): spare foreign shells and log every kill in task teardown Oct 20, 2026
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thank you @Azd325. This round covers everything I asked for.

  • Live: 4 of 4 scenarios on real, isolated Herdr panes, including the process logs. Thanks for that.
  • Orphans: the session rule keeps the Fix 2 leak case. An init-reparented child in the endpoint shell's session is now reaped, and test_reparented_child_in_endpoint_session_is_reaped pins it.
  • Durable record: state/teardown-processes.log gets a killed/force-killed/spared/kept line for each decision.
  • On head b08de432 I also checked the review findings. Ownership inputs are snapshotted once per scan. The endpoint shell is signaled last. Without lsof, the worktree is kept instead of force-returned.

CI: two jobs are red, and neither is caused by this change. Behavior portable serial 5 is the same fm-remote-secondmate-lifecycle-e2e "watcher did not exit on its auto-relaunch wake" failure that main 9d76aa8e has right now (run 39472834148). Serial 3 is a fm-public-followup cleanup flake. I re-ran the failed jobs once (run 39474562904).

Contract-class: new-default (my own read, now narrower). What remains is a default change: on backends with no endpoint pid (cmux, orca, zellij), teardown now spares and reports every process instead of reaping it. The treehouse return order also changes, so a spared survivor keeps the worktree. Both are reasonable "refuse when ownership can't be proved" choices, but they replace the specified Fix 2 path on those backends. That makes this a captain decision, not an auto-merge.

VISION: One captain: aligns. Authority: aligns (it refuses to kill what it can't prove it owns). Scripts: aligns. Restart: aligns (durable log). Delegation: aligns (live 4/4). Vendor: aligns, with the stated trade-off that there is no reap on cmux/orca/zellij. Scope: aligns.

Next step: once the re-run is green, this goes to Kun for the merge-or-leave call on the default change. That will be a captain-decision hold, so nothing more is needed from you unless the re-run fails for a reason tied to this branch. Issue #7420 stays open (the body says Refs, not Fixes).

@Azd325 Azd325 changed the title fix(teardown): spare foreign shells and log every kill in task teardown fix(bin): reap only task-owned processes in fm-teardown Oct 24, 2026
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thank you @Azd325 for bringing this up to date with main and for chasing down the T3 failure.

What I checked on head 830a266f against main d96bff00: the new commit only touches tests/fm-backend-t3code.test.sh. bin/fm-teardown.sh is the same as at b08de432, and the no-mistakes attestation binds this head. You read the failure correctly. The T3 backend (#7518, landed this morning) has no endpoint pid, so under this PR's rule a provider process rooted in a T3 secondmate home is now spared and reported instead of being ended before the home is removed. The three updated tests (single, pooled and nested) now assert that.

CI: two jobs are red on run 40117064304, and neither comes from this branch. Serial 4 is the known fm-watcher-lock "recovery drain after forced arm interruption" flake, and serial 1 hit the 30-minute cap that main still has. I re-ran the failed jobs.

Contract-class: still new-default, and a little wider now. Besides cmux/orca/zellij, the explicit T3 backend now also leaves a lingering provider process alive (and named) when the secondmate home is removed. #7518 had specified and tested the opposite behavior. It's the same "refuse when ownership can't be proved" choice. I'll put it in front of Kun as part of the same decision.

VISION: unchanged from my last note. Every rule aligns, and on vendor the stated trade-off now includes T3.

Next step: once the re-run is green, this goes to Kun as a merge-or-leave call. That's a captain-decision hold, so it's not waiting on you unless the re-run fails for a reason tied to this branch.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thanks @Azd325 for going one step further on the T3 path.

What's new on head 732b582b (vs 830a266f): t3code_secondmate_home_shutdown_barrier now re-checks, after the reap, which spared pids are still rooted in the T3 secondmate home. If any are, it keeps the home, writes a kept line and exits non-zero, instead of removing the home under a live process. teardown_spared_pids_in_worktree only moved and takes an optional dir. I read the delta. It's safe, and it does hold main's "never remove a home under a live process" guarantee. The no-mistakes attestation binds 732b582b.

One ask, if you can: your live run was on f8614fdf. These two commits change runtime behavior on the T3 secondmate path, which is no longer test-only, and that path wasn't covered live. Could you live-check one T3 secondmate teardown with a lingering provider (home kept, pid named, exit non-zero, and a clean retry once it exits) and post the evidence? Re-raising through git push no-mistakes works too. If T3 isn't something you can run live, just say so, and I'll note it for Kun.

CI: run 40121604061 has two red jobs, and neither comes from this branch. Serial 1 hit main's 30-minute cap. Serial 5 stalled in the host-worker suite after "quarantine recovery refuses unverifiable supervisors", which this PR doesn't touch. I re-ran the failed jobs.

Contract-class: still new-default. On T3 it now goes further than leaving a provider alive. A lingering provider also keeps the home and makes teardown exit non-zero. #7518 had specified and tested reaping it. VISION is unchanged: all rules align, and the vendor trade-off includes T3.

Next step: this is waiting on you only for the T3 live evidence. Once that's in and CI is green, it goes to Kun as a merge-or-leave decision.

@Azd325

Azd325 commented Oct 25, 2026

Copy link
Copy Markdown
Contributor Author

Thanks. I ran the T3 secondmate check live on 732b582b. The result is in the PR description's Testing section.

Setup: a real T3 Code 0.1.2 server on loopback with telemetry off, a scratch primary home, and a scratch secondmate home. The T3 thread was real: it was launched idle and bound to the secondmate home's root. The lingering provider is a stand-in process in its own session with its cwd in the home. That makes the "provider still running after the archive" case deterministic. Both attempts ran bin/fm-teardown.sh live-t3sm --force, as the secondmate tests do.

First teardown, with the process still running:

teardown: spared unowned process 66002: lingering-provider
teardown: kept secondmate home <home>; spared unowned process(es) still run in it: 66002
exit=1

state/teardown-processes.log:

2026-10-25T08:27:38Z	live-t3sm	66002	spared	no endpoint pid on t3code	lingering-provider
2026-10-25T08:27:38Z	live-t3sm	-	kept	spared pid(s) still in secondmate home: 66002 	<home>

After the first attempt, the thread read back archived:true with no active run. The home and the task record were still there, and 66002 was alive.

Retry, after 66002 exited:

teardown live-t3sm complete (window mcp:bee4995a-df9f-48f3-844d-28db41e36500, worktree <home>)
exit=0

After the retry, the home and the task record were removed, and the thread was still archived. Result: the home is kept, the pid is named, teardown exits non-zero, and a retry after the process exits cleans up. The T3 project entry for the scratch home remains in T3, because teardown never deletes a project.

@kunchenguid

kunchenguid commented Oct 25, 2026 •

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thank you @Azd325, that T3 live run is exactly what I was hoping for.

Live evidence: on head 732b582b, the first teardown kept the home, named pid 66002, wrote the spared and kept lines and exited 1. The retry after the process exited removed the home and the task record cleanly. That covers the T3 runtime delta, so nothing more is needed from you on evidence.

CI: serial 1 hit main's 30-minute cap again on attempt 2 of run 40121604061. That flake comes from main, not this branch, and it stays until main's own fix lands. I re-ran the failed job. Everything else is green, the no-mistakes attestation binds 732b582b, and the branch still merges cleanly with main 147b2672.

Contract-class: new-default. Teardown now spares unowned processes on cmux/orca/zellij/T3, and on T3 it keeps the home and exits non-zero while one is still running. #7518 had specified and tested reaping that process. VISION: all rules align. "Unlanded work is never torn down" and "scripts stop safely and report" both fit.

Next step: this isn't waiting on you. Once serial 1 is green, it goes to Kun as a merge-or-leave decision, since it changes a default path.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thanks @Azd325. The serial 1 rerun came back green, so this is now ready for a decision.

State on head 732b582b: all 19 checks pass, the branch merges cleanly with main ffb2aca0 (after this pass's merges of #7536, #7729 and #7740; #7729 touched the same T3 test file and still merges cleanly), and the no-mistakes attestation binds this head. Your T3 live run covers the runtime delta, and the earlier live runs cover the rest.

Contract-class: new-default (my own read, unchanged). Teardown now spares and reports processes it can't prove the task owns, instead of reaping them. That covers every process on backends with no endpoint pid (cmux, orca, zellij, T3). On T3 it also keeps the secondmate home and exits non-zero while one is still running. That reverses the reap that #7518 specified and tested. VISION: every rule aligns. "Scripts stop safely and report" and "unlanded work is never torn down" both fit, and the durable state/teardown-processes.log record supports "a restart is a non-event".

Next step: this is a captain-decision hold, not waiting on you. Because it changes a default teardown path, Kun decides whether to merge it or leave it. Nothing more is needed from you. If Kun says go, I will run CI fresh on current main first, since your CI ran before #7729 touched the same T3 test file.

@Azd325
Azd325 force-pushed the fm/fm-7420-teardown-foreign-shell branch from 732b582 to 648864f Compare November 4, 2026 13:26
@Azd325 Azd325 changed the title fix(bin): reap only task-owned processes in fm-teardown fix(bin): spare unowned processes during task teardown Nov 4, 2026
@greptile-apps

greptile-apps Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] No new blocking issue was established in this review.

Reviews (6) · Last reviewed commit: "docs: correct Orca cleanup behavior with..." · Reviewed by Greptile

Comment thread bin/fm-teardown.sh Resolved
Comment thread bin/fm-teardown.sh Resolved
Comment thread bin/fm-teardown.sh Resolved
Comment thread bin/fm-teardown.sh Resolved
Comment thread bin/fm-teardown.sh Resolved
Comment thread bin/fm-teardown.sh Resolved
Comment thread tests/fm-teardown.test.sh Resolved
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thank you @Azd325 for the fresh re-raise on 49f265e6, and for working through Greptile's teardown findings so quickly. Capturing Herdr ownership before the pane closes, rescanning every live process, keeping occupied Orca worktrees and TASK_TMP, and re-running the safety proof after the wait are all the right direction.

What I checked: the no-mistakes attestation binds this head with every step completed. The coverage guard and repo invariants pass, and the branch merges cleanly with main bb8dd209. The red Full suite is our full-ci label gate, not your code.

Waiting on you: a few things before this can go back to Kun:

  1. Open Greptile P1 ("Replay tests lack their backlog"). I checked it, and it's real. test_late_work_refusal_leaves_no_close_marker_for_startup_replay and test_orca_work_saved_during_the_wait_is_not_removed never call seed_backlog_in_flight, so no close marker is written and the in_flight row assertions can't pass. Please seed the backlog in both tests and resolve the thread.
  2. Validation on this head. Your head commit says the change is not validated yet: the full tests/fm-teardown.test.sh, the T3 and Orca suites, the mutation checks and bin/fm-lint.sh hadn't run. Please let those finish green before the re-raise.
  3. The Orca check before branch deletion. The same commit says the safety check still runs after the branch is detached and deleted, not before it as asked. Please either move it ahead of the branch deletion, or reply here explaining why a refused Orca teardown with the branch already deleted still keeps the late work safe. The detached HEAD is kept in the worktree, so a short explanation is fine if that's your reasoning.
  4. Live evidence for the new runtime paths. The body's live rows are fixture tests, and its evidence logs come from an older commit. The changed behavior isn't covered live: Herdr ownership captured before the pane close (a background child reaped after a real Herdr pane closes), and a late write during the wait refusing teardown with no pending close left behind. Could you run those live and post the output, or re-raise through no-mistakes with live validation?

Then please re-raise through git push no-mistakes so the attestation binds the new head.

Contract-class stays new-default, by my own read of the diff against main. Teardown spares and reports processes it can't prove the task owns. This head also keeps occupied Orca worktrees and TASK_TMP, exiting non-zero. VISION.md still aligns on every rule: "scripts stop safely and report" and "unlanded work is never torn down" both fit. The merge-or-leave decision on that default change is still Kun's. That part is waiting on Kun, not on you.

@Azd325 Azd325 changed the title fix(bin): spare unowned processes during task teardown fix(teardown): keep worktrees and records when foreign processes remain Nov 4, 2026
@Azd325

Azd325 commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

Live evidence for item 4 of #7566 (comment), run on head 2f197c077d8cd5c00c0d1ee2b6458b08a8150fd5 with Herdr 0.9.5 on macOS.

Setup: every Herdr call went through bin/fm-herdr-lab.sh in named non-default lab sessions, with a throwaway FM_HOME holding its own backlog, task records and work copies. The scratch work copies are plain git clones, not treehouse slots, so case (a) ends with the expected treehouse return failed abort after the reap.

(a) Herdr ownership captured before the pane close: pass.
Task shell 30193 started a launcher whose grandchild 34216 called fork + setsid (new session 34216, not the pane session), ignored SIGHUP and SIGTERM, and kept its cwd in the work copy.

teardown: reaping leaked worktree process(es) for fm-7566-a3: 34216
teardown: force-killing leaked worktree process(es) for fm-7566-a3: 34216

state/teardown-processes.log:

2026-11-04T18:14:54Z	fm-7566-a3	34216	killed	task-owned via endpoint 30193	...
2026-11-04T18:14:56Z	fm-7566-a3	34216	force-killed	task-owned via endpoint 30193	...

The reap runs only after the pane-gone check, so 34216 was still alive after the real pane closed, and it was attributed to the task through the endpoint recorded before the close. Afterwards 34216, its parent, the launcher and the shell were all not running.

Two earlier attempts with background children that stayed in the pane session (a sleep 600 and a SIGHUP-ignoring Python, once with its own process group) produced no reap line: closing the pane already ended them, so they never reached the reaper. On this Herdr version the pre-close capture matters for children that leave the pane session.

(b) Late write during the wait refuses teardown and leaves no pending close: pass.
Process 7370, not a child of the pane shell, with cwd in the work copy, waited for state/fm-7566-b.backlog-close to appear, slept 2 s, wrote late-write.txt, and exited 0.

teardown: spared unowned process 7370: ...
REFUSED: worktree .../repo-b/wt has uncommitted changes.
uncommitted changes present (untracked-only leftovers)
untracked paths (up to 10):
  late-write.txt

Exit 1. After teardown: fm-7566-b.backlog-close absent, fm-7566-b.meta present, backlog row state: in_flight. Running the startup close-marker replay afterwards left the task record and the in_flight row unchanged.

Side note, separate from this PR: on a Mac whose PATH has GNU coreutils first, bin/fm-lab-home.sh tmux-dir fails because its Darwin branch runs stat -f '%Lp', which GNU stat reads as a file-system query.

@Azd325
Azd325 force-pushed the fm/fm-7420-teardown-foreign-shell branch from 2f197c0 to 5878a86 Compare November 5, 2026 00:06
@Azd325 Azd325 changed the title fix(teardown): keep worktrees and records when foreign processes remain fix(bin): reap only task-owned processes at teardown and keep worktrees with spared ones Nov 5, 2026
Comment thread docs/orca-backend.md Resolved
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thank you @Azd325 for the new head 5878a867 and for the real Herdr 0.9.5 lab evidence. Bringing the lsof-less Orca and TASK_TMP removal back to main's behavior, with the two new tests, keeps the change narrow, and it doesn't widen scope. The attestation binds this head with no skipped steps, the quick checks pass, it merges cleanly with main, and all eight earlier Greptile threads are resolved.

One small, optional thing: Greptile's new P2 on docs/orca-backend.md is right. reap_task_backend_process_group only handles tmux, so with no lsof, Orca cleanup warns and removes the worktree without reaping anything. Its one-line suggestion would make the doc accurate.

Otherwise, nothing else is needed from you. This is still a captain-decision hold because it changes a default teardown path, so it's waiting on Kun, not on you.

Preserve and report cwd matches without live endpoint ancestry or a dedicated endpoint process group. Refuse worktree removal while unowned processes remain.

Refs kunchenguid#7420
Azd325 and others added 27 commits November 5, 2026 09:04
Teardown treats a process with its cwd under the worktree or tasktmp as
task-owned when it is in the session the endpoint shell leads, so an
init-reparented leaked child is reaped again. Processes in other sessions
and every process on a backend with no endpoint pid stay spared.

Each kill and each spare appends one line to state/teardown-processes.log.

Refs kunchenguid#7420
…rdown. In tests/fm-backend-t3code.test.sh, three T3 secondmate teardown tests (single, pooled and nested) still expected teardown to kill a provider process rooted in the secondmate home. T3 has no endpoint pid, so under the recorded owner decision teardown now spares and reports such processes. I changed those tests to assert the process survives. The first also checks that the pid is reported, and the pooled test checks that the slot still returns. They kill the process themselves at the end. The whole tests/fm-backend-t3code.test.sh passes locally, but I did not re-run the rest of shard 1. I did not mutation-check the new assertions. No change to bin/fm-teardown.sh
…now kept while a spared process remains rooted in it: no home removal and no slot return. t3code_secondmate_home_shutdown_barrier in bin/fm-teardown.sh now re-checks, after the reap, which spared pids are still under the home. If any are, it prints "teardown: kept secondmate home ...; spared unowned process(es) still run in it: <pids>" on stderr, writes a `kept` line to state/teardown-processes.log, and returns 1. That is the existing refusal path, so teardown exits non-zero and keeps the home and its records for retry. teardown_spared_pids_in_worktree now takes an optional directory (default $WT) and moved above its first use, because the nested-child path calls it before the old definition. The three tests in tests/fm-backend-t3code.test.sh now assert that the provider survives and that the home is kept (single, nested) or the slot is not returned (pooled). They also expect a non-zero exit. The single test also checks the stderr line, the log line and the kept meta record. All other assertions stay. tests/fm-backend-t3code.test.sh passes. I did not run the rest of the suite. Mutation check: making the barrier ignore survivors turned the single test red, but the run stopped at the first failure, so the pooled and nested tests were not confirmed red
…r there (kunchenguid#8052)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* fix(teardown): retain leased copy when Herdr close is refused
…tests: ci-2 captures Herdr shell ownership before the pane close, ci-3 rescans all current processes and fails closed on scan failure, ci-4 revalidates worktree safety after the deferred wait, ci-5 keeps occupied Orca worktrees (exit 1) and TASK_TMP. Each fix was mutation-checked (removed, test went red, restored). The targeted run of the new tests passed (12/12). The full fm-teardown and t3code suites were still running at the end of this round, so their final result is not confirmed. Lint was not re-run after the final edits. Nothing committed or pushed
…n suite was still running when I had to return. No mutation checks ran, and the T3 suite, the Orca suite and bash bin/fm-lint.sh have not been run. ci-2 (refused task looks finished): the marker is written before the final safety check. When that check refuses, teardown now removes the pending close marker and exits 1. The new helper `teardown_final_safety_or_exit` in bin/fm-teardown.sh does this with `fm_backlog_close_marker_clear`. Startup replay then finds no marker, so the task record and the open backlog item stay. ci-3 (Orca loses shutdown changes): the Orca path now calls the same helper after the post-close wait and before `fm_backend_remove_worktree`. The branch is still detached and deleted before the wait, as before. I did not move that, because `validate_worktree_teardown_safety` checks HEAD, so late commits still count. The brief asked for the check before branch deletion. That is not done. Tests in tests/fm-teardown.test.sh: - `spawn_late_actor` has a new `commit` action that makes an unlanded commit. - New helper `replay_close_marker` runs the real `fm_backlog_close_marker_replay`. - New test `test_late_work_refusal_leaves_no_close_marker_for_startup_replay` (Treehouse path): for late write and late commit, it expects exit 1 with REFUSED, then runs replay. It asserts the task meta is kept and the backlog row is still `in_flight`. - New test `test_orca_work_saved_during_the_wait_is_not_removed`: for late write and late commit, it expects exit 1 and no `removal.log`. After replay it asserts the meta is kept and the backlog row is still `in_flight`. - Both tests are registered in the run list. Validation state: - `bash bin/fm-test-run.sh tests/fm-teardown.test.sh` was running in the background, logging to /tmp/nm-td1.log. It has no exit code yet. A second watcher was waiting on that log. - Not done: removing each guard to confirm its test goes red, then restoring it; the T3 and Orca suites; `bash bin/fm-lint.sh`. The driving worker must run these before accepting the change
A pending close could retire records after a later teardown refusal.
Defer T3 preparation until cleanup checks pass and clear prepared markers on later refusals.
Preserve pending markers when the atomic backlog transition needs recovery.
Repeat worktree safety before both Treehouse return paths.

Cover twenty-two refusal scenarios with seeded backlog rows and actual startup replay.
The early-marker mutation and removed-return-check mutation both fail their regression checks.
The full teardown, T3 and Orca suites pass, along with final lint.
@Azd325
Azd325 force-pushed the fm/fm-7420-teardown-foreign-shell branch from 5878a86 to 3beb6a3 Compare November 5, 2026 08:52
@Azd325 Azd325 changed the title fix(bin): reap only task-owned processes at teardown and keep worktrees with spared ones fix(teardown): reap only processes owned by the task's endpoint shell Nov 5, 2026
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thank you @Azd325 for the new head 3beb6a3b. It rebases onto current main and takes Greptile's one-line docs/orca-backend.md suggestion, so the Orca no-lsof sentence is accurate now. Nothing else changed in scope: the diff against main is still the seven teardown, docs and test files. The attestation binds this head with no skipped steps, the quick checks pass, and it merges cleanly.

Nothing is needed from you. This is still a captain-decision hold because it changes a default teardown path, so it's waiting on Kun, not on you.

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.

3 participants