Skip to content

fix(bin): refuse teardown when the recorded worktree is not a Treehouse pool slot, and guard Claude hook removal - #3723

Closed
MLA82 wants to merge 10 commits into
kunchenguid:mainfrom
MLA82:publish/r2-teardown-safety
Closed

MLA82 wants to merge 10 commits into
kunchenguid:mainfrom
MLA82:publish/r2-teardown-safety

Conversation

@MLA82

@MLA82 MLA82 commented Sep 4, 2026 •

Copy link
Copy Markdown

Summary

This PR closes two teardown safety gaps:

  1. Prove a recorded worktree before reaping it. bin/fm-teardown.sh used
    to trust a task's recorded worktree= (and, for Orca, its recorded
    worktree id) without proof. If that field was ever stale or wrong -
    pointing at the wrong directory, or even at the primary firstmate
    checkout - teardown could kill live processes and hard-reset the wrong
    worktree before any later check caught the mistake.

  2. Guard Claude hook removal. remove_claude_hook_file deleted a
    worktree's .claude/settings.local.json without checking whether that
    worktree was still in use, and treated a missing treehouse binary the
    same as a confirmed "not in use" - silently removing a live hook.

Behavior change

Teardown now refuses, before touching a single process or file, whenever a
task's recorded worktree cannot be proven to be a real Treehouse pool slot
(same project's Git common directory, present pool state). The refusal is
non-mutating - the task record, backlog row, and worktree are all left
exactly as found - and explains itself the same way every other refusal in
this file does. This is a deliberate new restriction: a mis-recorded
worktree= or project= must never be reaped, only reported.

Claude hook removal now checks the worktree's actual in-use state before
deleting the hook file, and treats an inconclusive check (including a
missing treehouse binary) as "do not remove" rather than "safe to remove".

Testing

Verified locally, including under a PATH with treehouse and herdr
removed to simulate a runner without them installed:

  • tests/fm-teardown.test.sh - the full teardown safety suite, including the
    Treehouse pool-slot proof, the Claude hook removal guard (in-use, not
    in-use, inconclusive, and missing-binary cases), and the forced
    secondmate-teardown fixtures.
  • tests/fm-backlog-atomicity.test.sh - the backlog/record pairing
    invariant, including interrupted-cleanup recovery.
  • tests/fm-teardown-endpoint-safety.test.sh and
    tests/fm-captain-hold-lifecycle.test.sh - adjacent teardown-related
    suites, unaffected by this change.

All four suites pass. shellcheck on the changed scripts is clean (no new
findings versus the pre-change baseline).

@greptile-apps

greptile-apps Bot commented Sep 4, 2026 •

Copy link
Copy Markdown

Confidence Score: 4/5

The PR is not yet safe to merge because forced secondmate cleanup can still remove an active task’s Claude hook when Treehouse is unavailable.

The moved Orca proof and status-error handling address the earlier failures, but the missing-binary branch still skips the fail-closed lease check on the child-cleanup path and proceeds to delete the hook.

Files Needing Attention: bin/fm-teardown.sh

Reviews (3): Last reviewed commit: "no-mistakes(review): placeholder" | Re-trigger Greptile

Comment thread bin/fm-teardown.sh Outdated
Comment on lines +1042 to +1048
if [ -n "$wt" ] && [ -n "$proj" ] && command -v treehouse >/dev/null 2>&1; then
if worktree_is_in_use "$wt" "$proj"; then
return 1 # Worktree is in-use; leave the hook alone.
fi
fi
# All safety checks passed.
rm -f -- "$hook_file"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Hook ownership check fails open

When treehouse is unavailable or treehouse status fails, worktree_is_in_use returns the same nonzero result as a confirmed unused worktree, so this branch proceeds to delete the hook. During same-home pool-slot reuse, that removes the active task's Claude Stop hook and prevents its turn-end and busy-state signals from firing.

Knowledge Base Used: Session transitions and teardown

Comment thread bin/fm-teardown.sh Resolved
Comment thread bin/fm-teardown.sh Outdated
local meta_path="${state_ref}/${id}.meta"
[ -f "$meta_path" ] || return 0
# Check treehouse status: refuse if worktree is in-use.
if [ -n "$wt" ] && [ -n "$proj" ] && command -v treehouse >/dev/null 2>&1; then

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Missing Treehouse deletes active hook

When Treehouse is absent while a same-home pool slot contains another active task's Claude hook, the command -v treehouse condition skips the in-use check and proceeds to remove the hook, preventing the active task's turn-end and busy-state signals from firing.

Suggested change
if [ -n "$wt" ] && [ -n "$proj" ] && command -v treehouse >/dev/null 2>&1; then
if [ -n "$wt" ] && [ -n "$proj" ]; then

Knowledge Base Used: Session transitions and teardown

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

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate:

Triage (tip 083a7ae2618a9c712a1c64660de58d21192744d8): fork CI approved (CI 33904191117 / NM 33904191091). Direction is right — prove treehouse membership before reaping, and stop blind Claude hook rm. Attestation MISSING.

Real residuals (waiting on you, not a captain hold):

  1. remove_claude_hook_file still fails open when treehouse is missing: the in-use check is skipped and the hook is removed anyway, contrary to the stated “inconclusive → do not remove” rule.
  2. For backend=orca, Fix 0 is skipped and reap_task_worktree_processes still runs before Orca's own path-match proof — a stale recorded worktree can still be TERM/KILL'd first.
  3. Related open hold: fix(bin): stop processes a gone worker left in its worktree #3168 (teardown duplicate unvalidated reap) — do not treat this PR as clearing that card.

Contract-class: restore (promised teardown safety before destructive reap).

VISION: R1–R7 align for fail-closed teardown; Authority/refusal paths strengthen when the residuals above are closed.

@MLA82

MLA82 commented Sep 4, 2026

Copy link
Copy Markdown
Author

Both confirmed real, verified against the actual code (not just the summary).

1. Hook removal on inconclusive status. worktree_is_in_use returned "not in use" both when the real path couldn't be resolved and when treehouse status itself errored (its own command-substitution failure was silently swallowed). remove_claude_hook_file treats "not in use" as license to delete the hook, so an inconclusive check - not just a genuine "not in use" - let it proceed and remove an active task's hook. Unknown must fail closed toward "in use" (preserve), the opposite of what a destructive path's unknown state should default to.

2. Unconditional treehouse-membership guard blocking Orca. Confirmed from docs/architecture.md: "treehouse pools clean worktrees for tmux, herdr, zellij, and cmux tasks, while Orca creates its own worktrees for backend=orca." The new worktree_is_treehouse_managed guard ran for every non-secondmate task with no backend check, so it would refuse every Orca teardown before ever reaching Orca's own worktree-path verification (require_orca_worktree_path_match_if_present) further down - Orca worktrees never appear in treehouse status by design. The existing Orca teardown test coverage didn't catch this because it always registers the worktree with the fake treehouse pool via fm_fake_treehouse_pool "$FB" "$wt", which isn't representative of a real Orca worktree.

Both fixed in 083a7ae2:

  • worktree_is_in_use now returns 0 (in-use/unknown) on either failure mode, with an updated doc comment on the intended fail-closed direction.
  • The membership guard now skips backend=orca, relying on Orca's own downstream path-match check instead.

Added two regression tests: one that makes treehouse status error specifically on the in-use check (while still passing the earlier membership check, via a call-counting fake) and asserts the hook survives; one that runs an Orca teardown against an empty treehouse pool (the realistic case) and asserts it still succeeds. Re-ran fm-teardown, fm-teardown-endpoint-safety, and fm-backend-orca: all pass, 0 failures, including both new tests.

@MLA82 MLA82 changed the title fix(teardown): prove a recorded worktree is treehouse-managed before reaping, and stop blind Claude hook removal fix(teardown): verify worktree ownership before reaping processes and removing hook files Sep 4, 2026
@greptile-apps

greptile-apps Bot commented Sep 4, 2026

Copy link
Copy Markdown

Want your agent to iterate on Greptile's feedback? Try greploops.

@MLA82
MLA82 force-pushed the publish/r2-teardown-safety branch 2 times, most recently from 03c6784 to c1687fe Compare September 11, 2026 13:21
@MLA82 MLA82 changed the title fix(teardown): verify worktree ownership before reaping processes and removing hook files fix(bin): prove teardown's worktree is a pool slot before reaping, and guard Claude hook removal Sep 11, 2026
…reaping, and stop blind Claude hook removal

Two teardown paths trusted recorded task metadata as verified fact.

1. reap_task_worktree_processes acted on state/<id>.meta's worktree= without
   checking it. A spawn can isolate the worker correctly and still record the
   wrong path, and the only check that would have caught it ran after the
   reap. In one incident that killed live processes in the primary checkout,
   including the primary firstmate's own session. worktree_is_treehouse_managed
   now runs before any reap for a non-secondmate task and refuses loudly,
   without touching a process, when the recorded path is not among
   `treehouse status`'s own pool members. It fails closed: a missing treehouse
   or a status error counts as not managed.

2. The worktree return removed .claude/settings.local.json with a blind rm -f.
   Removal is now gated on the hook's own embedded state directory matching
   this home, the task's meta file still existing there, and treehouse not
   reporting the worktree in use, so a returned pool slot re-leased to another
   home can no longer lose (or fire) a hook that belongs to someone else.

The teardown fixtures gain a shared fm_fake_treehouse_pool baseline so every
suite that reaches the new guard supplies a pool status instead of each test
rolling its own.
Review found two real issues in the treehouse-membership and in-use checks
added by the previous commit:

- worktree_is_in_use returned "not in use" both when the real path could
  not be resolved and when `treehouse status` itself errored, so an
  inconclusive check let remove_claude_hook_file proceed to delete an
  active task's hook instead of leaving it alone. The caller treats "not
  in use" as license to remove, so an unknown state must fail closed
  toward "in use", not toward "not in use". Added a regression test
  covering an erroring `treehouse status`.

- The new worktree_is_treehouse_managed guard ran unconditionally for
  every non-secondmate task, including backend=orca ones. Orca creates
  and owns its own worktrees entirely outside the treehouse pool
  (docs/architecture.md), so they never appear in `treehouse status` and
  this guard would refuse every Orca teardown before it ever reached
  Orca's own worktree-path verification further down. The existing test
  coverage for this path always registered the worktree with the fake
  treehouse pool, which is why it passed despite the bug being real.
  Added a regression test using an empty pool - the realistic case for
  Orca - to prove teardown still succeeds.
remove_claude_hook_file skipped its in-use check entirely whenever the
treehouse binary was absent from PATH, since the check was gated behind
`command -v treehouse`, and fell through to an unconditional rm -f. A
missing binary must be treated the same as an inconclusive treehouse
status: unknown must fail closed toward preserving the hook, not toward
deleting it. Drop the command -v gate so worktree_is_in_use runs
unconditionally; it already fails closed toward "in use" when
`treehouse status` cannot run at all.

Adds a regression test alongside the existing inconclusive-status case,
using backend=orca (the only main-task path that still reaches the
hook-cleanup code when treehouse is fully absent, since every other
backend already refuses earlier at the treehouse-membership guard).
…refusal

run_teardown() in tests/fm-teardown.test.sh now defaults FM_HOME to the case
directory (needed for the new pool-slot lock resolution), which activates
several pre-existing ancestor-safety checks in bin/fm-teardown.sh
(validate_removal_target/validate_child_worktree_for_removal) that were
previously dormant because FM_HOME was never set in tests. Four kind=secondmate
fixtures placed their secondmate-home and descendant worktrees nested inside
the case directory - unrealistic relative to how a secondmate's home and a
task's Treehouse-pool worktree actually sit outside the primary firstmate's
own FM_HOME - so those now-active checks fired before the tests' own intended
refusal (the herdr child preflight, a lock-contention refusal, etc.) ever ran.
Move those fixtures to sibling paths, still cleaned up by the same TMP_ROOT
self-cleaning trap, so the intended refusal fires first again.

Also give Fix 0's own "not a Treehouse pool slot" refusal the same
non-mutating-boundary sentence every other refusal in this file carries, and
update its now-uncovered fixture (a plain, non-pool clone with a stale
index.lock) to assert the refusal instead, adding a direct check of the
non-linked index.lock path resolution so that coverage isn't lost.
…l slot

bin/fm-teardown.sh's new "not a Treehouse pool slot" proof (Fix 0) now
refuses to reap any worktree it cannot prove is a real pool slot. This test
file's shared spawn fixture creates a linked worktree without ever marking it
as one, so its interrupted-cleanup and recovery tests started hitting that
refusal instead of exercising the recovery paths they test. Every other test
file with an equivalent fixture already calls the fm_treehouse_pool_slot test
helper for this; this file predates Fix 0 and never needed it before.
@MLA82
MLA82 force-pushed the publish/r2-teardown-safety branch from c1687fe to 8c6b587 Compare September 11, 2026 17:15
@MLA82 MLA82 changed the title fix(bin): prove teardown's worktree is a pool slot before reaping, and guard Claude hook removal fix(bin): refuse teardown when the recorded worktree is not a Treehouse pool slot, and guard Claude hook removal Sep 11, 2026
@MLA82

MLA82 commented Sep 18, 2026

Copy link
Copy Markdown
Author

Closing in favour of #4838, which replaces this proposal.

The change here sits on a base from 2026-09-04 and had grown to 15 files for a change of this size. #4838 is cut fresh against current main and comes to 3 files.

Both residuals raised on this pull request are addressed there: the first no longer reproduces on current main, because ownership is now established through teardown_owns_worktree, which does not treat an unresolved check as permission to delete; the second — reaping an Orca-owned worktree before Orca's own path-match proof — is fixed, with regression tests that fail without the fix.

@MLA82 MLA82 closed this Sep 18, 2026
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