Skip to content

fix(bin): stop processes a gone worker left in its worktree - #3168

Open
cisrd wants to merge 24 commits into
kunchenguid:mainfrom
cisrd:fm/fm-orphan-reaper
Open

cisrd wants to merge 24 commits into
kunchenguid:mainfrom
cisrd:fm/fm-orphan-reaper

Conversation

@cisrd

@cisrd cisrd commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

The problem, measured

On a live fleet host the machine hit 97% CPU with 90.6% of it in system time and the operator could not work.

Root cause: a node apps/api/dist/main.js server started by a crewmate whose agent later hit its quota limit and stopped. The process outlived its agent by eight and a half hours, accumulating 1460 Redis connections, each crossing docker-proxy in userland — hence the system time.

Killing that one process took the load from 98 to 22 and system time from 90.6% to 3.9%. It was not isolated: 41 orphans of the same kind had been found and killed by hand the day before.

The lifecycle gap

bin/fm-teardown.sh does kill a worktree's processes — but it only runs on a deliberate teardown. When the agent dies on its own (quota exhausted, crash, session end) nothing cleans up: the worktree stays allocated and its servers run forever. bin/fm-control.sh relaunch did not close the gap either.

What this adds

  • On relaunch: bin/fm-control.sh relaunch now stops what the previous incarnation left running in that worktree before starting the replacement.
  • On detection: bin/fm-orphan-reap.sh scans recorded tasks whose endpoint is gone and reports what it finds; the session-start digest surfaces it. Reaping is reported for decision rather than done silently.

Guardrails

  • Never a process outside a disposable worktree — the criterion is the process's real cwd read from /proc.
  • Never by command-name pattern; attribution is by worktree, never by name.
  • Never the processes of a task whose agent is alive.
  • Only processes are stopped: no file removal, no destructive git.
  • No lsof dependency (absent on the validation host); /proc and ss only.

Review findings fixed during validation

Three worth naming:

  • an unlistable worktree was reported as clean — the scan claimed "no orphans" for a copy it had not been able to inspect. It now reports UNSCANNABLE: with the reason and exits non-zero.
  • every session leader was spared, including exactly the re-parented servers that caused the incident. Only the recorded endpoint's own shell is spared now, and the mechanism refuses to act rather than guess when that identification is not reliable.
  • a malformed task record could direct the reaper at ~/projects/ — the tasktmp root bypassed the worktree guards. Fixed.

Validation

Review, integration tests, documentation and lint all pass. Test evidence includes an operator-facing transcript demonstrating that an orphan is stopped, plus the symmetric proof that a live task's processes and anything outside a disposable worktree are left alone.

Publication went through a fork because the contributing account has no write access to this repository.

@greptile-apps

greptile-apps Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

Confidence Score: 4/5

The PR is not yet safe to merge because teardown can still terminate another task’s processes through its second unvalidated reap.

The first teardown reap correctly binds roots to the recorded task and allocation token, but execution later reaches another reap using raw WT and TASK_TMP metadata, preserving the previously reported reassignment failure.

Files Needing Attention: bin/fm-teardown.sh

Comments Outside Diff (1)

  1. bin/fm-teardown.sh, line 2958-2968 (link)

    P1 When a stale task record names a worktree or tasktmp root that has been reassigned, this second reap passes the raw metadata paths into the signalling loop without the task-and-allocation-token validation used by the earlier reap, causing the current owner’s processes to be terminated.

    Knowledge Base Used: Session transitions and teardown

Reviews (13): Last reviewed commit: "test(teardown): make the ownership and g..." | Re-trigger Greptile

Comment thread bin/fm-worktree-proc-lib.sh Resolved
Comment thread bin/fm-worktree-proc-lib.sh Resolved
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate:

Reviewed HEAD 3428e0e41883e375c8c7198db71eb661da38e006 vs main 10b93b2cc6f4241e87fccaee2e357c33a7347a53. Full diff reviewed (bin/fm-orphan-reap.sh, bin/fm-worktree-proc-lib.sh, relaunch/teardown/session-start wiring, docs, tests). No .github/workflows/* changes. Not security/fishy.

Class: corrective. Closes the lifecycle gap where a gone worker leaves processes in its disposable copy: scan reports only; reap <id> is explicit; unattended auto-kill is deliberately not wired. Relaunch cleanup runs only after that incarnation was commanded to stop and watched stopping — completing an existing relaunch contract, not a new default sweep.

VISION (per rule, inspected evidence):

  • One captain, one interface — aligns. Session-start surfaces LEFTOVER:/UNRESOLVED:/UNSCANNABLE: for decision rather than silent mutation.
  • Authority is explicit — aligns. Header documents why scan never stops; reap is an explicit instruction; attribution is by cwd, never by command name.
  • Scripts own the mechanics — aligns. Resolution/guards live in fm-worktree-proc-lib.sh; judgement to reap stays with firstmate/captain.
  • A restart is a non-event — aligns. Leftovers are discoverable from durable task records + /proc, not chat memory.
  • Delegation with a spine — aligns. Strengthens a refuse/report path before destructive cleanup.
  • The fleet outlives any vendor — aligns. /proc-first with lsof fallback; no vendor UI coupling.
  • Scope — aligns. Process cleanup in the command layer; no forge/CI expansion.

What is not cleared:

  1. No no-mistakes-pipeline-attestation:v1 for this HEAD. Blocking (Require-no-mistakes failed).
  2. Greptile P1 (agreed on inspection): when endpoint is misread as dead/missing and crew-state is unknown, accepting unknown as corroboration can authorize relaunch/reap against a live worker's processes. Corroboration must require affirmative terminal evidence (done/failed or equivalent), not indeterminate.
  3. Greptile P1 (agreed): tasktmp root validation can accept an unrelated existing directory ending in fm-<id>; that must be bound to the recorded per-task temp path before any signalling.
  4. CI still running after fork approval.

Fork CI approved after this review: CI run 33073310244, Require no-mistakes run 33073310278.

This is waiting on the author, not the captain: push a matching attestation, fix the two P1 guard holes, and let CI finish green.

Merge-eligible: NO.

@cisrd

cisrd commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

Both P1s are fixed. They were reviewed at 3428e0e, which predates the fixes; the branch is now at 3179ace.

P1.1 — an indeterminate current state corroborating a bad endpoint verdict. Fixed in 52bdd9b. unknown is the current-state reader declining to answer, not a second source agreeing the worker is gone, and a stale record pointing at a copy since handed to a live task reads exactly that way — which is not hypothetical: on 2026-08-27 a forced cleanup on that reading stopped a working agent. Only done and failed corroborate now. The copy is still reported, under its own UNDETERMINED label, and a reap of it is refused. Pinned by test_an_undetermined_current_state_never_authorises_a_stop, which flips only the second source on one fixture.

P1.2 — a tasktmp root accepted by name. Fixed in 52bdd9b. Any directory anywhere whose name ended in fm-<id> used to qualify. It is now bound to the exact path bin/fm-spawn.sh creates, both sides deriving it from FM_TASK_TMP_ROOT with the same /tmp default; the home and projects/ refusals still run first, so the operator's own tree is turned away by the boundary that names it. Pinned by test_a_temp_root_outside_the_recorded_path_is_refused.

Three further defects were found and fixed after that review, in fb6f1e0:

  • A regression this branch introduced. Moving teardown's reap to the shared working-directory resolver turned that scan on for the first time on hosts without lsof — without the ancestor guard the two sibling paths carry inside fm_wtproc_select. Teardown does its own signalling, so cd <copy> && fm-teardown.sh <id> had the operator's own shell in the scan and stopped it. It now spares its own process tree, and the descendant test walks up to the teardown process only, never past it, so a server that shell started earlier stays a leftover. Pinned by a test that fails against the previous code with the invoker dead.
  • alive is the only reading that means a living owner. ambiguous, unreadable, unverified, and a failed classifier call all returned the copy as clean while the diagnostic asserted a living owner the classifier had never given — so a backend carrying no recovery classifier reported every leaking copy under it as empty. Those now report under the same UNDETERMINED label and refuse a reap. Pinned by test_an_undetermined_agent_state_is_never_reported_as_a_clean_copy.
  • scan_task reset two of the globals it publishes and left the other six holding the previously examined copy's values on each of its early returns.

Both new tests were verified to fail against the immediately preceding commit before being accepted.

@cisrd

cisrd commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

Answering the four items left uncleared at 3428e0e. The branch is now at 3179ace.

2. Greptile P1 — indeterminate current state as corroboration. Fixed in 52bdd9b, and your reading of it was right. Only done and failed corroborate a dead/missing endpoint now; unknown is the reader declining to answer. The copy is still reported, under an UNDETERMINED label, and a reap of it is refused — the leak stays visible, but only an operator judges it.

3. Greptile P1 — tasktmp root validation. Fixed in 52bdd9b. The root is bound to the exact path bin/fm-spawn.sh creates, both sides deriving it from FM_TASK_TMP_ROOT; a record naming anything else is refused rather than reconciled, with nothing in it examined or signalled, and the refusal is reported rather than silently narrowing the scan.

1. Attestation — still not cleared, and I want to be exact about why. This head carries no no-mistakes-pipeline-attestation:v1, so Require-no-mistakes will still fail. The pipeline was attempted three times and failed each time on its own review agent exhausting itself, not on this code. The last two commits were therefore reviewed, tested, and linted by hand instead. Whether that is acceptable is not mine to decide, and I am not presenting it as equivalent.

4. CI. Re-running against 3179ace now.

One thing the earlier review could not have caught, because this branch introduced it after it: moving teardown's reap onto the shared working-directory resolver turned that scan on for the first time on hosts without lsof, and teardown did not carry the ancestor guard its two sibling paths have. In that state cd <copy> && fm-teardown.sh <id> stopped the operator's own shell. fb6f1e0 adds the guard and a test that fails against the previous commit with the invoker dead. 3428e0e should not be merged as it stands.

Also in fb6f1e0: an unclassifiable agent state (ambiguous, unreadable, unverified, a failed classifier call) no longer reads as a clean copy, and no diagnostic claims a living owner the classifier did not give; scan_task now resets every global it publishes rather than two of eight; the local-copy validator is called once instead of twice on refusal; and FM_TASK_TMP_ROOT, which two scripts must read identically, is documented.

Verified by hand at 3179ace: bin/fm-lint.sh clean (ShellCheck extended + actionlint), and green on fm-worktree-proc (26), fm-control-relaunch (51), fm-control (35), fm-session-start (50), fm-teardown (59). Both new tests were confirmed to fail against the immediately preceding commit before being accepted. Not verified by hand: the full suite, and the pipeline's own review and documentation gates.

Comment thread bin/fm-worktree-proc-lib.sh Resolved
@cisrd

cisrd commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

Round 3 pushed: 87ea8b0. All four review findings from the last validation run are fixed, each in its own commit and each pinned by a test proven to fail against the preceding commit.

unverified-backend-reports-every-live-task-as-undetermined — fef7d0a..87ea8b0, fixed in 87ea8b0. The previous round treated every non-alive classifier answer alike, but unverified is what fm_backend_agent_state answers for every backend carrying no recovery classifier — zellij, orca, cmux — for a live worker exactly as for a dead one, so it carries no information about the copy. Every healthy task on such a home was reported at every session start. Two facts are now separated: "the classifier could not answer for THIS task" (ambiguous, unreadable, a failed call) stays real doubt and is still reported UNDETERMINED; "this runtime has no classifier at all" raises no alert. The safety rule is unchanged in both directions — neither reading may authorise a stop, and a new refusal status names the missing classifier when a cleanup is attempted. Not alerting and not authorising a stop are independent, and only the first changed. The accepted trade-off, decided above the implementation: a genuine leak on a classifier-less runtime is no longer surfaced by this report, because a report that fires on every healthy task every session is one people stop reading.

missing-temp-root-reported-unscannable-with-no-reason — 89bc257. A recorded temp root that no longer exists is not an unexaminable root: fm_wtproc_pids_under already treats a missing directory as "nothing is running there" and returns cleanly. fm_wtproc_task_tmp now answers with three outcomes rather than two — accepted, refused with a reason, absent — and both callers drop an absent root silently while still reporting a refused one. Every refusing path states a reason, and the callers' fallbacks now say something actionable instead of "no reason was given". The test's control arm keeps a present-but-refused root reported with the scan still exiting 3.

resolver-memoisation-defeated-by-every-call-site — fef7d0a. Detection moved into _fm_wtproc_resolve, which sets the global in the caller's shell and must be called bare; fm_wtproc_collect, fm_wtproc_pids_under, and teardown's reap loop resolve once and read it, so the per-root scans inside command substitutions inherit a settled answer. Pinned by a test that counts the self-test's calls across one observation over three roots and requires exactly one.

living-owner-assertion-cannot-fail — 87ea8b0. You were right that it proved nothing: it ran without diagnostics, where the sentence is never emitted, and matched bare words that honest messages use to say the opposite. It now runs on the --task path and matches the exact claim. Demonstrated on one fixture against 696914b: the old code prints "its processes have a living owner and are left alone" for an unreadable verdict, and the current code does not.

Verified by hand at this head: bin/fm-lint.sh clean (ShellCheck 0.11.0 extended, actionlint 1.7.12); green suites for process attribution (27 cases), relaunch, control, session start, and teardown.

Still not cleared: there is no pipeline attestation on this head, so Require-no-mistakes stays red. The pipeline's review step succeeded and produced exactly the four findings above; its automatic fix agent then applied them, reported lint clean, and stopped to wait for a background verification event that never arrived, so it was killed by a 30-minute silence timeout and its uncommitted work was lost. That has now happened four times, always in the same place, which is why these four were fixed by hand instead.

Comment thread bin/fm-worktree-proc-lib.sh Resolved
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate:

Re-verified newer activity. HEAD is now 87ea8b04adc87e24afb1d2086792c5dcd5dde352 (was 3428e0e4 at the previous stamp). Whole thread re-read, including the author's P1-fix comments. Full diff re-reviewed: bin/fm-orphan-reap.sh, bin/fm-worktree-proc-lib.sh, relaunch/teardown/session-start/spawn wiring, docs, tests. No .github/workflows/*. Not disguised security. cisrd is not blocked.

Class: corrective. Closes the lifecycle gap where a gone worker leaves processes in its disposable copy: scan reports only; reap <id> is explicit; unattended auto-kill is still not wired. Relaunch cleanup remains part of an existing relaunch contract.

VISION (per rule, inspected evidence):

  • One captain, one interface — aligns. Session-start surfaces leftovers for decision rather than silent mutation.
  • Authority is explicit — aligns. Header documents why scan never stops; reap is an explicit instruction; attribution is by cwd, never by command name. fm_wtproc_worker_is_gone now corroborates only with done/failed (inspected), not unknown.
  • Scripts own the mechanics — aligns. Resolution/guards live in fm-worktree-proc-lib.sh; judgement to reap stays with firstmate/captain.
  • A restart is a non-event — aligns. Leftovers are discoverable from durable task records + /proc.
  • Delegation with a spine — aligns. Strengthens a refuse/report path before destructive cleanup.
  • The fleet outlives any vendor — aligns. /proc-first with lsof fallback; no vendor UI coupling.
  • Scope — aligns. Process cleanup of disposable copies, not workshop.

Prior P1s: the unknown-as-corroboration hole and the unbound fm-<id> name match are fixed in this HEAD (done/failed only; temp root bound to ${FM_TASK_TMP_ROOT:-/tmp}/fm-$id with home/projects/ refusals). Remaining Greptile P1 is occupancy of that canonical spawn path if something unrelated reuses it while a stale record still names it. That is a real residual of cwd-based cleanup of a recorded path, not the earlier unbounded-name bug. Not a reason to withhold CI; still not auto-merge-ready.

Overlap hold: open #3161 (mackcee) rewrites teardown's lsof-absent process-group fallback so it cannot signal processes outside the task worktree. This PR also replaces teardown's reaper with the shared cwd resolver. Do not merge one leftover while the other is open.

Attestation: still none. Author said the pipeline review agent exhausted itself; that is not a matching no-mistakes-pipeline-attestation:v1 for this HEAD. no-mistakes is blocking.

First-time fork CI (this HEAD): after that full-diff review I approved workflow runs 33101744299 (CI) and 33101744198 (Require no-mistakes). Previous approval was for the older HEAD.

This is waiting on the author, not the captain: push an attestation whose head_sha matches HEAD; keep the occupancy residual in mind if you add a generation/occupancy bind; leave #3161 in play (overlap hold). Merge-eligible: NO.

Comment thread bin/fm-control.sh Resolved
Comment thread bin/fm-control.sh Resolved
Comment thread bin/fm-worktree-proc-lib.sh Resolved
@cisrd

cisrd commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

Round 6 pushed: 92213ea. Three findings fixed, one classified as follow-up. Two limitations below need to be read before merging — they are stated here deliberately rather than left to be inferred from the diff.

teardown-signals-into-an-unvalidated-recorded-root-now-that-the-scan-is-live — fixed, and it is the most important change on the branch.

bin/fm-teardown.sh passed the record's own worktree= and tasktmp= values straight into the loop that signals processes. Nothing stood behind them: no refusal of the filesystem root, of a path sitting directly in the home, or of anything under projects/, which is where an operator's own long-running stack lives.

The gap predates this branch, and was harmless only by accident — the scan was gated on lsof, absent on the host this was built for, so that loop never ran. Moving it onto the shared resolver switched it on. Making an unvalidated path reachable is taking responsibility for it.

Both recorded roots now clear the same shape refusals the two sibling paths apply, and a root that fails them refuses the teardown rather than narrowing it: signalling nothing and then running the destructive half against a record the safe half just rejected would be the worse outcome. An absent root is not a refusal and is dropped.

Deliberately the shape refusals alone, not fm_wtproc_disposable_worktree's linked-worktree proof: teardown supports a task copy that is an ordinary clone, which its own suite pins, so that proof would refuse a shape the command is required to handle.

Pinned by a test that fails against the previous commit with a process under the operator's own projects/ tree was signalled by teardown.

lsof-scan-reports-failure-on-a-correct-answer and lsof-path-reports-the-scanners-own-helper-as-a-leftover — fixed, and NOT EXERCISED HERE.

Both corrections its /proc twin already carries: an if so a failing test is not returned as the function's own exit status, and the liveness recheck so a scan run from inside a copy does not report lsof's own exited pid. lsof is absent from the machine this branch was written and verified on, so that arm has no test coverage here and was corrected by inspection alone. It is labelled as such in the code. Left asymmetric, a reader finding one arm fixed and the other untouched would reasonably conclude the second had been examined and judged sound.

endpoint-shell-unnameable-on-every-non-tmux-backend — out of scope, classified as follow-up.

fm_wtproc_endpoint_shell_pid implements only the tmux arm; there is no pane-pid abstraction to fall back to. On herdr, zellij, orca and cmux the record can never name the endpoint's shell, so every session leader in a copy is held back unconditionally. That is safe and it is reported — it is the right way to fail — and implementing resolution for four more runtimes is a new subsystem, not a fix.

The consequence is not theoretical: this fleet runs on one of those four. The batch is therefore systematically blunted there, and a reader should not have to deduce that.

Two fixtures were corrected rather than worked around. Both modelled a process that was listed but not running — a pid that had never existed, and a witness the reap really killed. The scan now resolves that contradiction itself, since a pid that is not there is not a leftover, so they model a persistently respawning leak and a wedged process that is alive, which is what each is in the field.

Verified by hand at 92213ea: bin/fm-lint.sh clean (ShellCheck 0.11.0 extended, actionlint 1.7.12); green suites for process attribution, relaunch, control, session start and teardown.

@cisrd
cisrd force-pushed the fm/fm-orphan-reaper branch from ba74dc2 to 6a133da Compare August 27, 2026 22:03
Comment thread bin/fm-control.sh Resolved
Comment thread bin/fm-worktree-proc-lib.sh Resolved
Comment thread bin/fm-worktree-proc-lib.sh Resolved
@cisrd

cisrd commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

Round 7 pushed: 6a133da. This head is the first one to carry a completed no-mistakes run, and the reason it still shows no attestation is a permission fact rather than a code fact. Both are below, along with the three fixes.

The three fixes (3621569)

unreadable and no-reader are two different answers and no longer share one. Only the literal current state unknown was treated as the reader declining to answer. A reader that timed out or exited non-zero sets unreadable, which fell through to the "the two sources disagree" branch and returned the copy CLEAN — a leak hidden by a slow reader, against this file's own header. unreadable now reports UNDETERMINED alongside unknown.

no-reader deliberately keeps the quieter treatment, and it is now stated as its own case rather than folded in: it means the installation carries no current-state reader at all, so it answers identically for every task, live or dead, and therefore says nothing about this copy. Alerting on it would put a line on every task every session, which is the report people stop reading. The accepted trade-off is recorded in the header and in AGENTS.md: (none) in that section is not proof a classifier-less runtime's copies are clean.

The safety rule moved in neither direction. Neither reading has ever licensed stopping a process, and neither does now. Only the reporting changed, and only for unreadable.

The lsof arm's liveness recheck called kill -0, which this library's own header — written three commits earlier — names as the thing it deliberately is not. kill -0 answers "may I signal this", so another user's live process fails it; dropping such a pid would let a teardown remove a copy with one still running in it. Both arms now ask _fm_wtproc_pid_exists, which reads the proc entry where there is one and falls back to ps -p on the hosts reached through lsof, which are exactly the hosts with no /proc.

Skipping the reap when both recorded roots were absent also skipped the fallback that lives at the top of that same call — the process-group path for hosts with no working-directory source. With both roots gone, that fallback had become unreachable, so a leaked group survived. Restored.

Verification, and what is not covered

Both behaviour tests were confirmed to fail against the immediately preceding commit with their reported symptoms — a copy whose state reader could not answer was not reported, and the process-group fallback never ran, so the leaked group survived. The third new test is a characterization pin on the two probes rather than a before/after regression test, and is described that way rather than counted with the other two.

By hand at this head: bin/fm-lint.sh clean (ShellCheck 0.11.0 extended, actionlint 1.7.12); green suites for process attribution, relaunch, control, teardown, teardown endpoint safety, session start, and remote-job orphan reap — 7 suites, 0 failures.

lsof is still absent from this machine, so that arm remains inspection-only here, as labelled in the code.

The pipeline: completed, then denied at the last step

The run reached the end of its work. intent, rebase, review (3 findings, all auto-fix), test, document, and lint all completed. It then failed in under a second at push:

remote: Permission to kunchenguid/firstmate.git denied to cisrd
fatal: ... The requested URL returned error: 403

The pipeline pushes to origin, which is the upstream repository, and this branch is authored from the cisrd fork. So the attestation cannot be produced by re-running: every future run will do the full review, test, document and lint work and then fail at the same step for the same reason, because the push target is not writable by the author. That is a configuration mismatch to resolve above this PR, not something the branch can fix. I am not presenting the hand verification as equivalent to an attestation.

6a133da is that completed run's own documentation commit, applied on top of the rebase it performed; I fast-forwarded to its head and published it rather than re-deriving the work.

Residual, unchanged and not widened

The occupancy residual you both named is still open and still correctly described: the temp root is bound to the exact path fm-spawn.sh creates, but a canonical path reused by something unrelated while a stale record still names it is not distinguished by path equality alone.

One field event since the last round is worth recording because it is the same shape from the other side: a stale task record pointed at a copy that had since been reassigned to a live task, and a forced teardown stopped that agent. This branch's guards make that reading report UNDETERMINED and refuse a reap, which is the safe half. A positive ownership bind — refusing to act when a copy belongs to a different registered owner — would close the residual properly, but it is a new mechanism rather than a fix, and I have deliberately not added it here without direction. Flagging it as the natural follow-up.

The overlap hold with #3161 still stands from my side.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate:

Re-verified newer activity. HEAD is now 6a133daff03980dd9f9c4ed04b66bbda5ded85bf (prior stamp was 87ea8b04). Whole thread re-read, including Round 6/7 author notes on teardown root validation, lsof asymmetry, attestation push-403, and the occupancy residual. Full diff re-reviewed for this HEAD: bin/fm-orphan-reap.sh, bin/fm-worktree-proc-lib.sh, relaunch/teardown/session-start/spawn wiring, docs, tests. No .github/workflows/*. Not disguised security. cisrd is not blocked.

Class: corrective. Closes the lifecycle gap where a gone worker leaves processes in its disposable copy: scan reports only; reap <id> is explicit; unattended auto-kill is still not wired. Relaunch cleanup remains part of an existing relaunch contract. Round 7 keeps unreadable as UNDETERMINED (report-only; still never licenses a stop) and restores the process-group fallback when both recorded roots are absent.

VISION (per rule, inspected evidence):

  • One captain, one interface — aligns. Session-start surfaces leftovers for decision rather than silent mutation.
  • Authority is explicit — aligns. Header documents why scan never stops; reap is an explicit instruction; attribution is by cwd, never by command name. Corroboration remains done/failed only (inspected), not unknown/unreadable.
  • Scripts own the mechanics — aligns. Resolution/guards live in fm-worktree-proc-lib.sh; judgement to reap stays with firstmate/captain.
  • A restart is a non-event — aligns. Leftovers are discoverable from durable task records + /proc.
  • Delegation with a spine — aligns. Strengthens a refuse/report path before destructive cleanup.
  • The fleet outlives any vendor — aligns. /proc-first with lsof fallback; no vendor UI coupling. Non-tmux endpoint-shell sparing remains fail-closed (author-classified follow-up).
  • Scope — aligns. Process cleanup of disposable copies, not workshop.

Overlap hold: open #3161 (mackcee) still rewrites teardown's lsof-absent process-group fallback / outside-worktree signalling. This PR still replaces teardown's reaper with the shared cwd resolver and validates recorded roots before signalling. Do not merge one leftover while the other is open. Author agrees the hold still stands.

Attestation: still none on the PR body. Author reports the no-mistakes run completed intent→lint then failed at push with Permission to kunchenguid/firstmate.git denied to cisrd (fork cannot push origin). That is a real upstream/fork pipeline mismatch, but it is not a matching no-mistakes-pipeline-attestation:v1 for this HEAD. no-mistakes remains blocking until an attestation whose head_sha matches HEAD is present (however it is produced).

Residual (unchanged): canonical spawn-path occupancy while a stale record still names it — author correctly left as follow-up, not widened here.

Fork CI (this HEAD): after this full-diff review I approved workflow runs 33120886876 (CI) and 33120886880 (Require no-mistakes).

Merge-eligible: NO. Overlap-hold with #3161 + attestation missing. Waiting on author/coordination, not an auto-merge decision.

Comment thread bin/fm-spawn.sh Resolved
@cisrd

cisrd commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

Round 8 pushed: cd7a68d. This closes the occupancy residual that has been carried openly since round 6 — both halves of it, because either half alone leaves the incident possible.

Why it stopped being a follow-up

I flagged a positive ownership bind as the natural next mechanism and deliberately did not add it without direction. Direction came, and so did the argument for it: the residual is not hypothetical spare capacity in the threat model, it is the exact shape of a field event — a stale record naming a copy since reassigned to a live task, and a forced cleanup that stopped that agent.

Path equality cannot fail on it. The temp root's path is derived from the task id, so anything recreating it matches exactly; a pool worktree is a valid linked worktree for whichever task holds it now, so every structural check passes identically for the task that left and the task that arrived. That is why shape was never going to close it.

Identity required at read (477784c)

bin/fm-spawn.sh stamps each root at allocation with the task id and a token minted for that allocation, recorded in state/<id>.meta. Both validators end with fm_wtproc_owns_root, which accepts only a marker naming this task and this allocation token, and names which of the three refusals it took — no marker, another task, another allocation of this task.

The token, not the id, is what makes the reassignment case fail: an id alone would still match once a pool copy came back around to the same task. A worktree's marker lives in its per-worktree git directory, so it never shows in git status, never blocks teardown's dirty check, and never reaches a commit.

An unmarked root is refused. A copy predating this binding and a reused path are indistinguishable, so the reading that stops is taken. That is a real loss of cleanup coverage on existing copies and is stated where the refusal surfaces, not left to be inferred.

Identity written blockingly at allocation (cd7a68d)

The first commit warned and continued when a marker could not be written, reasoning that an unstamped root only forfeits its own cleanup since the reader refuses what it cannot attribute. That reasoning holds for a root never stamped and fails for the case the marker exists for. A reassigned copy still holds the previous holder's marker, and overwriting it is the only thing that retires it — so a failed write leaves this task working in a copy carrying the departed task's identity, whose stale record then validates against it exactly.

Every failure on that path now refuses the spawn — unmintable token, unresolvable root, unwritable marker — each saying which. A spawn that has to be restarted costs a task; continuing costs a live worker.

The relaunch path's second source, restored (477784c)

Round 5 narrowed relaunch's gate to the endpoint alone, on the reasoning that firstmate is deliberately replacing this worker so the copy has a known owner being retired by the caller. That premise does not survive the failure it has to withstand. "This worker is being replaced" is not an independent fact; it is the same classifier reading re-used as its own justification. When the backend misreads a live worker as dead, do_exit returns already-stopped without ever sending an exit command, and the recheck asks that same classifier again and gets the same wrong answer. Two readings from one source are one reading.

stopped is not exempt either — "watched it go" is that same classifier reporting a transition.

The cost is real and is not hidden: the quota-exhaustion case that motivated this whole batch is no longer cleaned up automatically on relaunch. It is reported, and an operator decides. Saturation costs hours of nuisance; stopping a live worker costs work and trust.

Verification

Both new tests were confirmed to fail against the immediately preceding commit, with the reported symptom:

  • test_an_unwritable_allocation_marker_refuses_the_spawn — drives the temp root's marker write into a denial and requires the refusal; fails against 477784c as a root that could not be stamped should refuse the spawn.
  • test_a_root_that_matches_the_path_but_not_the_allocation_is_refused — four arms on the exact recorded path (no marker, another allocation, another task, and a control proving a correctly stamped root is still accepted), closing with the end-to-end case: a reassigned linked worktree, a live process in it, a cleanup driven from the stale record, and that process still running afterwards.

By hand at this head: bin/fm-lint.sh clean (ShellCheck 0.11.0 extended, actionlint 1.7.12), and green on process attribution, relaunch, control, session start, teardown, and the five spawn suites — the last because making the marker write blocking touches every spawn, not only a relaunch.

Unchanged

lsof is still absent from this machine, so that arm remains inspection-only, as labelled in the code. There is still no pipeline attestation on this head, for the fork-push reason set out in round 7 — every run does the full work and then fails at push because the pipeline targets origin, which the fork author cannot write. I am not presenting hand verification as equivalent. The overlap hold with #3161 still stands from my side.

Comment thread bin/fm-teardown.sh Resolved
@cisrd

cisrd commented Aug 28, 2026

Copy link
Copy Markdown
Contributor Author

Round 9 pushed: 4782d96. The ownership binding is now uniform across all three paths, which closes the residual this branch has carried openly since round 6.

What changed and why it is not a fourth patch on a shaky model

The three paths were converging on one mechanism, and only one design question was actually open: teardown declines the linked-worktree proof because it must support a task copy that is an ordinary clone, which its own suite pins — so binding ownership there meant either exempting that shape or including it.

It is included, not exempted. A spawn stamps every copy it allocates whatever its shape, and a clone keeps its marker in its own .git directory just as a linked worktree keeps it in its per-worktree git directory. The supported shape stays supported, its test still pins it, and it gains the same proof as the others.

The guarantee has to be uniform because teardown is where the damage happens. Requiring the marker at allocation and on the two reporting paths while the destructive path alone accepted shape left the mechanism exactly as strong as its weakest link — and that link is the one that stopped a live agent on 2026-08-27.

--force does not reach past an ownership refusal. It sits outside every force branch on purpose: forcing past exactly this check is what caused the incident, so insisting is the one thing that must not work. Its own test arm pins that.

The refusals were made worth reading

A copy allocated before this binding carries no marker and will be refused, so that message is the one an operator meets while cleaning up older work — a command they expected to run, stopping. Every refusal now names the marker file it looked for, which of the four causes it was (no recorded token, no marker, another task, another allocation of this task), and what to do about it: correct the record when the copy is someone else's, or write the two marker lines deliberately when it really is this task's.

The remedy is the marker rather than a flag, deliberately. Adopting a copy should be something someone did after looking at what is running in it, not something a flag does quietly.

Verification

test_a_copy_that_cannot_be_shown_to_be_this_tasks_refuses_teardown runs both arms against an otherwise perfectly ordinary copy, so the teardown genuinely reaches the signalling loop and the refusal is the ownership check rather than something upstream — the mistake an earlier test on this branch made once already. Arm one strips the marker; arm two stamps it for another task, which is the reassignment case itself. Both assert the live process in that copy is still running afterwards, that the copy and the record survive, and that the refusal names its cause and the marker path. A third arm asserts --force refuses identically.

Confirmed to fail against cd7a68d, the first arm with a process in a copy that could not be shown to be this task's was signalled by teardown.

Green at this head: teardown, teardown endpoint safety, process attribution, relaunch, control, session start, and remote-job orphan reap — seven suites, zero failures — with bin/fm-lint.sh clean (ShellCheck 0.11.0 extended, actionlint 1.7.12).

Three fixtures were corrected rather than worked around, because each modelled something the code now refuses: two task copies that carried no allocation marker, and one that was a bare directory rather than a repository at all. They now model an ordinary allocation, which is what the cases around them are about.

Unchanged

lsof is still absent from this machine, so that arm remains inspection-only, as labelled in the code. There is still no pipeline attestation on this head, for the fork-push reason set out in round 7 — every run does the full work then fails at push because the pipeline targets origin, which the fork author cannot write. I am not presenting hand verification as equivalent. The overlap hold with #3161 still stands from my side.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate:

Re-verified newer activity. HEAD is now 4782d96bab6e262e381d1ae1c767c8bde70e79f1 (prior stamp was 6a133da). Whole thread re-read, including Round 8/9 author notes on occupancy binding. Full diff re-reviewed for this HEAD: bin/fm-worktree-proc-lib.sh (fm_wtproc_write_owner / fm_wtproc_owns_root), spawn/teardown/relaunch/session-start wiring, docs, tests. No .github/workflows/*. Not disguised security. cisrd is not blocked.

Class: corrective. Rounds 8–9 close the occupancy residual: spawn stamps each allocated root with task= + a per-allocation token; fm_wtproc_owns_root accepts only that pair; teardown's signalling path is included, not exempted; --force does not bypass an ownership refusal. Corroboration remains done/failed only. Scan still reports; reap stays explicit.

VISION (per rule, inspected evidence):

  • One captain, one interface — aligns. Session-start still surfaces leftovers for decision rather than silent mutation.
  • Authority is explicit — aligns. Ownership refusal is readable; --force cannot skip it (fm_wtproc_owns_root + teardown wiring).
  • Scripts own the mechanics — aligns. Marker write/check live in fm-worktree-proc-lib.sh.
  • A restart is a non-event — aligns. Leftovers stay discoverable from durable records + /proc + the allocation marker.
  • Delegation with a spine — aligns. Strengthens the refuse path before destructive cleanup.
  • The fleet outlives any vendor — aligns. /proc-first with lsof fallback; no vendor UI.
  • Scope — aligns. Process cleanup of disposable copies, not workshop.

Overlap hold: open #3161 (mackcee) still rewrites teardown's lsof-absent process-group fallback / outside-worktree signalling. This PR still replaces teardown's reaper with the shared cwd resolver plus the new ownership bind. Do not merge one leftover while the other is open. This is a leftover overlap hold, not waiting on you for that decision.

Attestation: still none on the PR body. no-mistakes remains blocking until a no-mistakes-pipeline-attestation:v1 whose head_sha matches HEAD is present.

Fork CI (this HEAD): after that full-diff review I approved workflow runs 33129907138 (CI) and 33129906952 (Require no-mistakes).

Merge-eligible: NO. Overlap-hold with #3161 + attestation missing.

Alex William added 7 commits September 4, 2026 15:24
A worker that ends without a teardown - quota exhausted, harness crash,
terminal closed - leaves whatever it started running in its task copy, and
nothing in the lifecycle comes back for it. Observed 2026-08-27: a server
outlived its agent by eight and a half hours and drove the host to 97% CPU,
90.6% of it system time; 41 processes of the same shape were reaped by hand
the day before.

bin/fm-worktree-proc-lib.sh becomes the single owner of "which processes
belong to a task's disposable copy". Attribution is the process's real working
directory and nothing else, read from /proc first because lsof is not
installed everywhere and a cwd scan that depends on it degrades silently
exactly where the reap matters most. lsof stays the fallback for a host with
no /proc; a host with neither says so instead of guessing. A working directory
that cannot be read leaves its process alone.

Two paths use it:

- fm-control.sh relaunch stops what the replaced incarnation left running
  before the replacement is launched into the same copy. The endpoint's own
  shell is spared because relaunch reuses it, a secondmate is skipped because
  its recorded worktree is its firstmate home, and a cleanup that cannot be
  completed warns rather than stranding the task with no agent.
- fm-orphan-reap.sh scan reports copies whose worker is gone, surfaced in the
  session-start fleet digest; reap stops one on an explicit instruction. Its
  header owns why nothing does this unattended.

Nothing is ever matched by command name, and a copy must prove itself a linked
git worktree that is not a primary checkout, so no clone anyone works in
directly can be a target. A verdict also needs two independent sources to
agree: the Herdr endpoint classifier was observed reporting `dead` for a
worker that was running, and acting on that alone would have stopped a live
worker's processes.

fm-teardown.sh now shares the resolver, so its reaper no longer degrades to
the process-group fallback on a host without lsof.
… its own path

Two ways the cleanup could reach processes that were never the task's.

An undetermined current state used to corroborate the endpoint's dead
verdict. `unknown` is the reader saying it could not determine the state,
not a second source agreeing the worker is gone, and a stale record
pointing at a copy since handed to a live task reads exactly that way -
observed 2026-08-27, where a forced teardown on that reading stopped a
working agent. Only `done` and `failed` corroborate now. The leak is
still reported, under its own UNDETERMINED label, and a reap of such a
copy is refused: an operator sees it, and only an operator judges it.

The per-task temp root was accepted by name, so any directory anywhere on
the machine whose name ended in `fm-<id>` qualified. It is now bound to
the one path bin/fm-spawn.sh actually creates, both sides deriving it
from FM_TASK_TMP_ROOT with the same /tmp default; the home and projects/
refusals still run first, so the operator's own tree is turned away by
the boundary that names it.

Both are pinned by tests that fail against the previous code: an
undetermined state never authorises a stop, and a correctly named temp
root outside the recorded path is refused with nothing in it reached.
Alex William and others added 17 commits September 4, 2026 15:25
…er alive

Five defects, one of them a regression this branch introduced.

The teardown reap moved to the shared working-directory resolver without
the ancestor guard its two sibling paths carry inside fm_wtproc_select.
On a host without lsof that scan had never been live, so switching the
resolver turned it on for the first time - and teardown does its own
signalling. An operator running `cd <copy> && fm-teardown.sh <id>` had
their own shell in the scan, and it was stopped along with the leftovers.
The guard spares this teardown's own process tree: the shells above it
and the short-lived helpers each pass spawns, which would otherwise be
counted as leftovers and make the reap refuse instead of converge. The
descendant test walks up to this process only, never past it, so a server
the operator's shell started earlier stays a leftover. Pinned by a test
that fails against the previous code with the invoker dead.

An agent state that is not `alive` is not the same as a living owner.
`ambiguous`, `unreadable`, `unverified`, and a failed classifier call are
all the classifier declining to answer, and each returned the copy as
clean while the diagnostic asserted a living owner that had never been
given - so a backend carrying no recovery classifier reported every
leaking copy under it as empty. Such a copy is now reported under the
same UNDETERMINED label an unreadable current state earns, and a reap of
it is refused. Each line names which source declined, since the label now
covers both.

scan_task reset two of the globals it publishes and left the other six
holding the previously examined copy's values on every one of its early
returns. cmd_reap's duplicate reset list is gone with it.

The local-copy validator was called twice on refusal, once to decide and
once to reproduce its reason, re-running several git invocations per
refused copy and quoting a second reading that need not match the first.

FM_TASK_TMP_ROOT decides a path two scripts must agree on and was
documented in neither.
…a clean copy

The companion to the undetermined-current-state case beside it, for the
other source. A backend with no recovery classifier answers `unverified`
for every task under it; the copy is reported under the UNDETERMINED
label, the cleanup refuses it, and the report never claims a living owner
the classifier did not give. Flipping only the backend on the same
fixture lets it through, so the case hinges on that reading alone.

Fails against the previous code with the copy reported as clean.
`fm_wtproc_resolver` memoised into a global, but every call site invoked
it inside a command substitution, so the assignment died with the
subshell and the memo never once survived. The self-test is not cheap -
its second half takes a whole machine listing - and the question is asked
once per scanned root, on hosts that are already saturated when this code
matters most.

The detection moves into `_fm_wtproc_resolve`, which sets the global in
the CALLER's shell and must be called bare. The hot paths -
`fm_wtproc_collect`, `fm_wtproc_pids_under`, and teardown's reap loop -
resolve bare once and read the global, so the per-root scans that follow
inside command substitutions inherit a settled answer. `fm_wtproc_resolver`
stays as the printing form for callers that ask once.

Pinned by a test that counts the self-test's calls across one observation
over three roots and requires exactly one. It fails against the previous
code with the resolver still unset in the collect's own shell.
A recorded temp root that no longer exists was refused like any other,
and every refusal had just become an UNSCANNABLE report - a root that
"cannot be called clean", with an empty reason attached, on every scan
for as long as the stale path stayed in the record. Nothing is there to
examine: fm_wtproc_pids_under itself treats a missing directory as
"nothing is running there" and returns cleanly. "I could not look" and
"there is nothing to look at" send an operator to different places, and
a report that raises contentless alarms is one people stop reading.

fm_wtproc_task_tmp now answers with three outcomes rather than two -
accepted, refused with a reason, or absent - and both callers drop an
absent root silently while still reporting a refused one. Every refusing
path in the validator states a reason; the two callers' fallbacks say
something actionable instead of "no reason was given".

Pinned by a test whose control arm keeps a present-but-refused root
reported and the scan exiting 3. It fails against the previous code with
the absent root reported unexaminable and reasonless.
…ut a copy

Treating every non-alive reading alike went too far. `unverified` is what
fm_backend_agent_state answers for every backend carrying no recovery
classifier - for a live worker exactly as for a dead one - so it says
nothing about the copy at all. Reporting it put every healthy task on a
zellij, orca, or cmux home into the report at every session start, and a
report that cries wolf every session is one people learn to ignore, which
costs the leak this mechanism exists to surface.

Two different facts are now separated. "The classifier could not answer
for THIS task" - ambiguous, unreadable, a failed call - stays real doubt
about this copy and is still reported UNDETERMINED. "This runtime has no
classifier at all" raises no alert.

The safety rule is untouched in both directions: neither reading may
authorise a stop, and the new status 5 refuses a reap with the missing
classifier named. Not alerting and not authorising a stop are
independent, and only the first changed.

Two tests, each hinging on one variable: the unverified case flips the
backend on one fixture and fails against the previous code with the
healthy copy alerted on; the undetermined case now drives real per-task
doubt through a tmux inventory failure.

The round-2 test's living-owner assertion could not fail: it ran without
diagnostics, where the sentence is never emitted, and matched bare words
that honest messages use to say the opposite. It now runs on the --task
path and matches the exact claim. Demonstrated against 696914b on one
fixture: the old code prints "its processes have a living owner and are
left alone" for an unreadable verdict, and the current code does not.
Three defects, and the first is the batch's own purpose.

The relaunch cleanup required the current-state reader to say `done` or
`failed` before touching anything an already-stopped agent left running.
That corroboration is right on the detection path, where nobody is
replacing anybody and the worker may well be alive. On the relaunch path
it closed the cleanup in exactly the case it was written for: a worker
killed mid-run by quota exhaustion leaves the endpoint reading dead while
the current state still reads `working`, from a run that never finished
or from the status log's last verb. The cleanup therefore withheld on the
very process that saturated the host on 2026-08-27.

Here there is no living owner for a second source to protect - firstmate
is replacing this worker, deliberately, at this moment - so the endpoint
is the whole test, and it must still read gone. bin/fm-orphan-reap.sh's
detection path is untouched and still requires both sources.

The shared scanner reported its own helpers as leftovers. Taking the
machine listing needs command substitutions whose subshells inherit the
caller's working directory, so a scan run from inside the copy being
scanned - where an operator naturally stands - listed them as occupants
of it. The entry is now re-checked against /proc at collection. Not by
descent, which would hide the many real leftovers that are descendants of
the shell a cleanup runs from; and not with `kill -0`, which answers "may
I signal it" and would drop another user's live process, letting a
teardown remove a copy with one still in it.

Two refusal fallbacks still said "no reason was given" against the
standing rule that no report line may carry an empty reason.

Both new tests fail against the previous code with the reported symptoms:
the process the dead worker left running survives its own replacement,
and an empty copy scanned from inside it reports the scanner's helpers.
Each carries a control arm that keeps the opposite case honest.
The liveness recheck was written as `test && printf`, and it is the last
command of the case, of the while body, and of the function. A failing
test therefore became the function's own exit status: it reported failure
having produced a perfectly correct answer.

Callers do not treat that lightly. bin/fm-teardown.sh reads it as "the
scan could not be done" and refuses, preserving a copy it should have
cleaned; the fleet sweep calls a copy it read correctly unexaminable. And
the trigger is the very thing the recheck exists for - a process that
exits between the listing and the read - so it would fire routinely
rather than rarely.

An `if` returns 0 where the `&&` list returned 1.

Pinned by a test that reproduces the race deterministically: a held
snapshot keeps a listing whose last matching entry names a pid whose
directory has since gone. It fails against the previous code with exactly
the reported symptom, rc=1 alongside the correct answer.
Teardown passed the record's own `worktree=` and `tasktmp=` values into a
loop that signals processes, with nothing behind them: no refusal of the
filesystem root, of a path sitting directly in the home, or of anything
under projects/ - where the operator's own stack lives.

The gap predated this branch and was harmless only by accident. The scan
was gated on lsof, absent on the host this matters for, so the loop never
ran; moving it onto the shared resolver switched it on. Making an
unvalidated path live is taking responsibility for it.

Both recorded roots now clear the same shape refusals the two sibling
paths apply, and a root that fails them refuses the teardown rather than
narrowing it - signalling nothing and then running the destructive half
against a record the safe half rejected would be worse. An absent root is
not a refusal and is dropped. Deliberately the shape refusals alone, not
the linked-worktree proof: this command supports a task copy that is an
ordinary clone, which its own suite pins.

The lsof resolver gets both corrections its /proc twin already carries -
an `if` so a failing test is not returned as the function's own status,
and the liveness recheck so a scan run from inside a copy does not report
lsof's own exited pid. NOT EXERCISED HERE: lsof is absent from this
machine, so that arm was corrected by inspection alone. It is labelled in
the code rather than left asymmetric, where a reader would take the
untouched arm for an examined one.

Two fixtures modelled processes that were listed but not running - a pid
that never existed, and a witness the reap really killed. A scan now
resolves that contradiction on its own, so they describe a persistently
respawning leak and a wedged process that is alive, which is what both
are in the field.

The guardrail test fails against the previous code with a process under
the operator's own projects/ tree signalled by teardown.
…ds took

Three corrections, two of them to defects this branch introduced while
fixing the last round.

Only the literal current state `unknown` was treated as the second source
declining to answer. A reader that timed out or exited non-zero sets
`unreadable`, and that fell to the "the two disagree" branch and returned
the copy CLEAN - a leak hidden by a slow reader, against this file's own
header. `unreadable` now reports as UNDETERMINED like `unknown`.
`no-reader` keeps the quieter treatment and is stated as a separate case:
it means the installation carries no reader at all, so it answers
identically for every task, live or dead, and says nothing about this
copy. Neither reading licenses a stop; only the reporting changed.

The lsof arm's liveness recheck called `kill -0`, which the library
header - written three commits earlier - names as the thing this
deliberately is not: it answers "may I signal it", so another user's live
process fails it, and dropping such a pid would let a teardown remove a
copy with one still running in it. Both arms now ask
_fm_wtproc_pid_exists, which reads the proc entry where there is one and
`ps -p` on the hosts reached through lsof, which are the hosts with no
/proc. Pinned by a test that asks both probes about a live process owned
by another user, signalling nothing.

Skipping the reap when both recorded roots turned out absent also skipped
that call's first act: the backend process-group fallback for a host that
can answer the working-directory question from neither source, which is
the only cleanup such a host has. The call is unconditional again.

Both new behaviour tests fail against the previous code with the reported
symptoms: the copy unreported when its reader could not answer, and the
leaked process group surviving when both roots are gone.
Ownership could rest on path equality alone, and path equality is
reproducible: the task temp root is derived from the task id, so anything
that recreates it matches, and a pool worktree is a valid linked worktree
for whichever task holds it now. A stale record naming either path therefore
reached a live stranger's processes with every shape check passing - the
shape it named to be exactly the shape it was.

fm-spawn now stamps each root at allocation with the task id and a token
minted for that allocation and recorded in the task's own record, and the
signalling validators refuse any root that cannot produce a matching marker.
An unmarked root is refused rather than accepted: a copy predating this
binding and a reused path look identical, so the reading that stops is the
safe one, at a stated cost in cleanup coverage.

The relaunch path also gets its second source back. Requiring only the
endpoint rested on "this worker is being replaced", which is not an
independent fact but the same classifier reading re-used as its own
justification: when the backend misreads a live worker as dead, the exit
never sends and the recheck asks that same classifier again. The
corroborating current-state read is restored, so the quota-exhaustion case
is reported for an operator rather than cleaned up automatically.
… write

Wrapping the fixture's marker write in a subshell made every later reference
to that fixture's own variables read as a use of something a subshell had
changed, which the pinned linter reports twelve times across two suites.
The library is sourced at file scope instead; the fixtures still exercise
the real writer.
…is task's

The marker write warned and carried on, on the reasoning that an unstamped
root only forfeits this task's own cleanup because the reader refuses what it
cannot attribute. That holds for a root never stamped. It does not hold for a
copy the pool has REASSIGNED, where the previous holder's marker is still in
place and overwriting it is the only thing that retires it: a failed write
leaves this task working in a copy that still carries the departed task's
identity, and that task's stale record validates against it exactly. It is
the 2026-08-27 incident verbatim.

So every failure on this path now refuses the spawn - an unmintable token, an
unresolvable root, and a marker that could not be written - and says which.
The test drives the temp root's write into a denial and asserts the refusal;
it fails against the previous commit.
…s require

Shape says a path COULD be a task's copy; it cannot say whose. A pool copy
handed back and given out again passes every shape refusal identically for
the task that left and the task that arrived, so a stale record naming a
reassigned copy reached teardown's signalling loop with nothing left to stop
it - and on 2026-08-27 a forced teardown on such a record stopped a live
agent and reset its work.

Requiring the marker at allocation and on the two reporting paths while the
destructive path alone accepted shape left the mechanism as strong as its
weakest link, and that link is the one that kills. Teardown now ends its root
validation with the same ownership check, and --force does not reach past it:
forcing past an ownership refusal is precisely the action that caused the
incident.

The clone shape is included rather than exempted. A spawn stamps every copy
it allocates whatever its shape, and a clone keeps its marker in its own .git
directory just as a linked worktree keeps it in its per-worktree git
directory, so the shape teardown is required to support stays supported and
gains the same proof.

A copy allocated before this binding carries no marker and will be refused.
That refusal is the one an operator meets while cleaning up older work, so
every refusal now names the marker file it looked for, which of the four
causes it was, and what to do about it - correcting the record when the copy
is someone else's, adopting it deliberately when it is this task's. A refusal
that explains costs a minute; a bare one costs an investigation.

Both arms of the new test fail against the previous commit, the first with
'a process in a copy that could not be shown to be this task's was signalled
by teardown'.
The lane's script list and its measured hints both moved under this branch:
main went from four shards to five and gained scripts, and this branch adds
tests/fm-worktree-proc.test.sh. The generated table and the counts around it
are regenerated from the runner at this head so the document describes the
partition CI will actually build.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TWatGXZLWPQyVvWaJuGe3R
test_relaunch_serializes_concurrent_durable_metadata_publication waited two
seconds for the relaunch to reach trace delivery. That path now also performs
the leftover cleanup's backend read, and measurement on an idle machine puts it
at 1.84-1.89s against that 2s bound, against 1.60-1.73s before this branch.

The bound is a liveness guard, not the assertion: the case is about delivery
and concurrent metadata publication serializing. It was failing on load rather
than on that behavior, so the guard is widened and the two sibling budgets,
which wait on work already under way, are left as they are.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TWatGXZLWPQyVvWaJuGe3R
…y assert

The suite aborted on its first case, so nothing after it had run: write_meta's
owner_token argument had lost its line continuation and was executed as a
command, which under set -e ended the script. Restoring the continuation is
what exposed the rest of this.

Four cases were taking their non-zero exit from an unresolvable backlog data
directory rather than from the behavior they name. Setting FM_HOME to a fixture
home moves $DATA there too, and teardown stops on it long before the signalling
loop:

- the recorded-root guardrail, whose own comment warns against exactly this
  ("refusing for an unrelated reason and looking like it had proved something"),
- all three arms of the ownership refusal, including the --force arm,
- the invoker-sparing case, which pinned neither home nor data and so resolved
  against whatever home the suite ran in.

Each now pins $DATA the way run_teardown documents, so the refusals asserted are
the refusals produced. The secondmate parent-channel case gained a temp root
from main that this branch's ownership check refuses; it is stamped like every
other ordinary allocation here, since that case is about the undelivered parent
line rather than about ownership.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01TWatGXZLWPQyVvWaJuGe3R
@cisrd
cisrd force-pushed the fm/fm-orphan-reaper branch from c8ebabc to bbfa53e Compare September 4, 2026 14:30
@cisrd

cisrd commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main at 8f7b79c7, resolving the base conflict. HEAD is now bbfa53e2. No behavior was changed by the rebase itself; the branch's own diff covers exactly the same files it did before.

What the conflict actually was

Two files, both mechanical. bin/fm-test-run.sh's portable-serial timing hints, where main has fresher measurements and this branch adds one entry for tests/fm-worktree-proc.test.sh; the union is taken with main's values, which is what that block's own comment prescribes. And docs/fm-test-portable-shards.md's generated shard table, where the branch still carried a four-shard layout and main has moved to five. That table is regenerated from the runner at this head, so it now describes the partition CI will actually build rather than either stale copy.

The suite was aborting on its first case

This is the part worth reading. write_meta's owner_token argument had lost its line continuation, so the string was executed as a command and set -e ended tests/fm-teardown.test.sh immediately. The suite reported a single failure and stopped, and nothing after that first case had run at any point on this branch - which is why the rounds above could report it green.

Restoring the continuation exposed four cases that were passing their exit-code assertion for the wrong reason. Setting FM_HOME to a fixture home also moves $DATA there, and teardown stops on an unresolvable backlog data directory long before it reaches the signalling loop:

  • test_a_recorded_root_under_projects_refuses_instead_of_signalling - the guardrail this batch rests on. Its own comment warns against exactly this ("refusing for an unrelated reason and looking like it had proved something"), and that is what it was doing.
  • All three arms of test_a_copy_that_cannot_be_shown_to_be_this_tasks_refuses_teardown, including the --force arm. The ownership refusal introduced in the last round was never reached by the test written to prove it.
  • test_teardown_never_signals_the_shell_it_was_started_from, which pinned neither home nor data and so resolved against whatever home the suite ran in.

Each now pins $DATA the way run_teardown documents, so the refusal asserted is the refusal produced. Verified by reverting each pin individually and confirming the case fails.

One further fixture: main added a secondmate parent-channel case carrying a temp root, which this branch's ownership check refuses. It is stamped like every other ordinary allocation in the suite, since that case is about the undelivered parent line rather than about ownership.

One test budget widened

test_relaunch_serializes_concurrent_durable_metadata_publication waited two seconds for the relaunch to reach trace delivery. That path now also performs the cleanup's backend read: measured 1.84-1.89s on an idle machine against that 2s bound, where main measures 1.60-1.73s. The bound is a liveness guard rather than the assertion, so it is widened; the two sibling budgets in the same case wait on work already under way and are unchanged.

Verification at this head

bin/fm-lint.sh clean (ShellCheck 0.11.0 extended, actionlint 1.7.12). bin/fm-test-run.sh --check-coverage reports ok total=180 parallel=24 serial=143 serial_shards=5 serial_unhinted=3 herdr=13.

Fifteen suites green, zero failures: teardown, teardown endpoint safety, process attribution, relaunch, control, session start, remote-job orphan reap, the four spawn suites, trace-context spawn, documentation audiences, and the two test-fixture suites.

Worth noting against the incident this branch is about: tests/fm-teardown.test.sh fails on current main on this host with leaked-process-reap: leaked worktree process survived teardown, because lsof is absent here and that is the gate the reap still sits behind. At this head that case passes.

Unchanged

lsof is still absent from this machine, so that arm remains inspection-only, as labelled. There is still no pipeline attestation on this head. The overlap hold with #3161 still stands from my side; that PR is still open.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: this is waiting on the author.

Re-verified newer activity after rebase onto main 8f7b79c7. HEAD is now bbfa53e2a7d0e01a60dcd05dbe796850bc28a45f (prior stamp 4782d96… / outcome=overlap-hold-waiting-author). Author note at 2026-09-04T14:31Z: rebase resolved base conflict; no intentional behavior change. Whole thread re-read. Diff still covers orphan-reap / worktree-proc ownership / relaunch-teardown-session-start wiring / docs / tests. No .github/workflows/*. Not disguised security. cisrd is not blocked.

Contract-class: restore (prior stamps said corrective; same lifecycle gap — gone worker leaves processes; scan reports; reap stays explicit; relaunch reaps previous incarnation in disposable worktree only).

VISION: prior per-rule writeup still holds on this tip (session-start surfaces leftovers; authority via ownership bind; scripts own markers; refuse path before destructive cleanup).

Overlap hold: still open. #3161 (mackcee) remains OPEN — teardown lsof-absent / outside-worktree signalling overlap. Do not land one leftover while the other is open. That hold is with the captain/Firstmate lane, not a ping for you on #3161 itself.

Attestation: MISSING on the PR body. no-mistakes remains blocking until a MATCH no-mistakes-pipeline-attestation:v1 binds this HEAD.

Workflow approval this pass (post-rebase action_required): approved CI 33884180304 and Require no-mistakes 33884180460 after re-review. NM will stay red without attestation.

14-day stale: not applicable — author push/comment today (2026-09-04).

Merge-eligible: NO (overlap-hold + attestation missing).

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: this is waiting on the author — security surface on tip.

Follow-up to the overlap-hold stamp on this HEAD: Greptile P1 verified in bin/fm-teardown.sh.

After the validated path (validate_recorded_reap_roots → reap_task_worktree_processes worktree ${REAP_ROOTS…} ~2903–2911), the tip still runs a second reap_task_worktree_processes worktree \"$WT\" \"$TASK_TMP\" (~2967) with no ownership bind — main's pre-PR call kept through the rebase, so both fire. At prior stamped HEAD 4782d96 only the validated call existed. That duplicate can signal processes under raw recorded paths without the ownership proof this PR added.

Please remove the unvalidated second reap (or ownership-bind it in that post-backlog position) and push a MATCH attestation for the new tip. Overlap hold with open #3161 still applies. CI already showing behavior failures on this HEAD — treat those as author blockers too.

Firstmate security flag raised for this tip regression. Not the blocked-authors banner.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: captain word on the security card — skip is not close. Leave this open. This is waiting on the author, not a captain close.

HEAD still bbfa53e2a7d0e01a60dcd05dbe796850bc28a45f. Class restore with security residual unchanged: after validated REAP_ROOTS reap, tip still runs unbound reap_task_worktree_processes worktree "$WT" "$TASK_TMP". Overlap with open #3161 unchanged — neither PR is closed from this skip.

Still owed before any land path: remove the duplicate unvalidated reap + bind no-mistakes attestation to HEAD (MATCH). Do not merge. Do not close. CI left as-is.

Firstmate will only re-flag if the tip clears the unbound reap (or becomes otherwise-ready again).

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.

2 participants