Skip to content

fix(bin): protect durable secondmate homes with owned Git locks and payload cleanup - #7607

Open
kesslerio wants to merge 32 commits into
kunchenguid:mainfrom
kesslerio:fix/6921-durable-home-worktree-lock
Open

kesslerio wants to merge 32 commits into
kunchenguid:mainfrom
kesslerio:fix/6921-durable-home-worktree-lock

Conversation

@kesslerio

@kesslerio kesslerio commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

What Changed

  • Adds bin/fm-home-worktree-lock-lib.sh, which gives linked-worktree secondmate homes a Git worktree lock backed by a validated firstmate-home-lock receipt binding schema, mate, canonical home, canonical parent, and lock reason; check stays read-only, acquire converges, release keeps the receipt for restoration, and foreign or unknown locks refuse even under --force.
  • Adds bin/fm-home-payload-lib.sh, which clears a retiring home's payload (data/, state/, config/, projects/, and both identity markers) by staging it under the returning parent's state/ before the slot release, restoring it on failure or a handled INT/TERM/HUP, and discarding the staging only once the return commits; a payload path with tracked files refuses the return instead.
  • Wires both libraries into bin/fm-home-seed.sh (acquire protection before identity publication, attempt-owned rollback that returns only homes and locks this attempt created) and bin/fm-teardown.sh (lock validation in home removal checks, owned release and receipt forget before return, git worktree remove for locked linked homes, protection restored after a failed removal), with matching docs, a serial hint for the new test, and expanded seed/teardown/payload-return test coverage.

Risk Assessment

✅ Low: The changes satisfy the authorized restore contract, preserve ownership checks and nonempty-path refusal, and introduce no substantiated material defects.

Testing

Drove the retirement path end-to-end through the real fleet CLIs (bin/fm-home-seed.sh and bin/fm-teardown.sh) against disposable git worktrees and a marked lab home, with only the external treehouse boundary stood in for. With the fix, a failed pool return that recreates an empty state/ restores the whole home and the retried teardown retires it; the same run against the pre-fix library reproduces the reported symptom (restore refuses, markers stranded in staging, retry refused as 'not a seeded secondmate home'). A recreated state/ carrying real new content is still refused with the new file preserved, and ordinary pooled retirement still returns a clean slot the next mate leases. The declined task-set-lock split and the already-covered ci-4 (overridden-state) case were not re-litigated; no visual surface exists for this change, so evidence is CLI transcripts and persisted filesystem state.

  • Live validation: ✅ go - 4 of 4 scenarios driven live against the product
Scenario Result Live Evidence
Retire a durable secondmate home whose pool return recreates an empty state/ and then fails: bin/fm-teardown.sh restores the whole home (payload, markers, Git lock, receipt) and the retried teardown r… ✅ pass live ~/.no-mistakes/evidence/01M7KW3DZZMFGHW8TY4C9T74X8/payload-restore-empty-fixed.txt - attempt 1 exit=1 with 'error: treehouse return failed for secondmate home ...; preserving the home and its…
Restore still refuses a recreated payload dir that carries real new content, instead of deleting it: teardown reports the refusal, the new file survives, and staged payload is not clobbered into the h… ✅ pass live ~/.no-mistakes/evidence/01M7KW3DZZMFGHW8TY4C9T74X8/payload-restore-content-fixed.txt - 'error: cannot restore staged payload path state for durable home ...; it exists again', 'new content: re…
Ordinary pooled retirement (no recreated dir) still hands back a clean slot that the next seed leases with its own identity and protection ✅ pass live ~/.no-mistakes/evidence/01M7KW3DZZMFGHW8TY4C9T74X8/payload-restore-clean-fixed.txt - retirement exit=0, kept checkout has data/state/config/projects and both markers absent, staging empty; fol…
The pre-fix library reproduces the maintainer-reported symptom on the same recreated-empty-state/ failure: restore refuses, markers and payload stay stranded in staging, and the retried teardown refus… ✅ pass live ~/.no-mistakes/evidence/01M7KW3DZZMFGHW8TY4C9T74X8/payload-restore-empty-prefix.txt ('cannot restore staged payload path state ...; it exists again', staging .home-return.* stranded, retry exi…
Evidence: Live retirement transcript: failed return recreates an empty state/, restore puts the whole home back, retried teardown succeeds (fixed code)

Source: Live retirement transcript: failed return recreates an empty state/, restore puts the whole home back, retried teardown succeeds (fixed code)

seed rc=0 home=scaffolded: /tmp/fm-live-payload-restore.rFRzzC/lab/data/mate/brief.md (secondmate charter)
home=/tmp/fm-live-payload-restore.rFRzzC/slot
--- snapshot: after seed (/tmp/fm-live-payload-restore.rFRzzC/slot)
home entries: .agents AGENTS.md assets bin .claude CLAUDE.md .codex config CONTRIBUTING.md .cursor data docs .fm-secondmate-home .fm-secondmate-parent .git .gitattributes .github .gitignore .greptile .grok GROK_BOT.md LICENSE .no-mistakes.yaml .omp .opencode .pi projects README.md skills state .tasks.toml tests VISION.md 
git lock: Firstmate durable home mate [fm-home-lock.ZGgiPB]
receipt: present
marker: mate
parent marker: schema=fm-secondmate-parent.v1
route=local
parent_home=/tmp/fm-live-payload-restore.rFRzzC/lab
state payload: live payload
new content: absent
data payload: durable data
route meta: present
staging: 
worktree dir: present
retirement attempt 1 exit=1
  err1: ●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  err1: ●  WATCHER DOWN - SUPERVISION IS OFF
  err1: ●  1 task(s) in flight, but no watcher has a fresh beacon (last beat: never, grace 300s).
  err1: ●  Trust the emitted supervision protocol for this harness; do not use shell & for watcher repair.
  err1: ●  This is a supervision warning only; the guarded operation WILL still run.
  err1: ●  repair a missing or failed watcher cycle with the Pi tool fm_watch_arm_pi, or restart Pi with -e /tmp/fm-live-payload-restore.rFRzzC/code/.pi/extensions/fm-primary-turnend-guard.ts -e /tmp/fm-live-payload-restore.rFRzzC/code/.pi/extensions/fm-primary-pi-watch.ts if the extensions are not loaded.
  err1: ●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  err1: treehouse: pool return failed (synthetic external boundary)
  err1: error: treehouse return failed for secondmate home /tmp/fm-live-payload-restore.rFRzzC/slot; preserving the home and its records for retry (lease may still be held)
--- snapshot: after failed return (/tmp/fm-live-payload-restore.rFRzzC/slot)
home entries: .agents AGENTS.md assets bin .claude CLAUDE.md .codex config CONTRIBUTING.md .cursor data docs .fm-secondmate-home .fm-secondmate-parent .git .gitattributes .github .gitignore .greptile .grok GROK_BOT.md LICENSE .no-mistakes.yaml .omp .opencode .pi projects README.md skills state .tasks.toml tests VISION.md 
git lock: Firstmate durable home mate [fm-home-lock.ZGgiPB]
receipt: present
marker: mate
parent marker: schema=fm-secondmate-parent.v1
route=local
parent_home=/tmp/fm-live-payload-restore.rFRzzC/lab
state payload: live payload
new content: absent
data payload: durable data
route meta: present
staging: 
worktree dir: present
retirement attempt 2 (retry) exit=0
  err2: WARNING: watcher still down (same stale episode; last beat: never, grace 300s) - full banner already printed this episode.
after retry: home worktree=gone route meta=gone git admin=gone
staging after retry: 
MODE=empty attempt1=1 attempt2=0
Evidence: Pre-fix contrast: same failure refuses the restore, strands markers in staging and makes the retried teardown refuse the home

Source: Pre-fix contrast: same failure refuses the restore, strands markers in staging and makes the retried teardown refuse the home

seed rc=0 home=scaffolded: /tmp/fm-live-payload-restore.n91Etv/lab/data/mate/brief.md (secondmate charter)
home=/tmp/fm-live-payload-restore.n91Etv/slot
--- snapshot: after seed (/tmp/fm-live-payload-restore.n91Etv/slot)
home entries: .agents AGENTS.md assets bin .claude CLAUDE.md .codex config CONTRIBUTING.md .cursor data docs .fm-secondmate-home .fm-secondmate-parent .git .gitattributes .github .gitignore .greptile .grok GROK_BOT.md LICENSE .no-mistakes.yaml .omp .opencode .pi projects README.md skills state .tasks.toml tests VISION.md 
git lock: Firstmate durable home mate [fm-home-lock.PYpe7Z]
receipt: present
marker: mate
parent marker: schema=fm-secondmate-parent.v1
route=local
parent_home=/tmp/fm-live-payload-restore.n91Etv/lab
state payload: live payload
new content: absent
data payload: durable data
route meta: present
staging: 
worktree dir: present
retirement attempt 1 exit=1
  err1: ●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  err1: ●  WATCHER DOWN - SUPERVISION IS OFF
  err1: ●  1 task(s) in flight, but no watcher has a fresh beacon (last beat: never, grace 300s).
  err1: ●  Trust the emitted supervision protocol for this harness; do not use shell & for watcher repair.
  err1: ●  This is a supervision warning only; the guarded operation WILL still run.
  err1: ●  repair a missing or failed watcher cycle with the Pi tool fm_watch_arm_pi, or restart Pi with -e /tmp/fm-live-payload-restore.n91Etv/code/.pi/extensions/fm-primary-turnend-guard.ts -e /tmp/fm-live-payload-restore.n91Etv/code/.pi/extensions/fm-primary-pi-watch.ts if the extensions are not loaded.
  err1: ●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  err1: treehouse: pool return failed (synthetic external boundary)
  err1: error: cannot restore staged payload path state for durable home /tmp/fm-live-payload-restore.n91Etv/slot; it exists again
  err1: error: treehouse return failed for secondmate home /tmp/fm-live-payload-restore.n91Etv/slot; preserving the home and its records for retry (lease may still be held)
--- snapshot: after failed return (/tmp/fm-live-payload-restore.n91Etv/slot)
home entries: .agents AGENTS.md assets bin .claude CLAUDE.md .codex CONTRIBUTING.md .cursor data docs .git .gitattributes .github .gitignore .greptile .grok GROK_BOT.md LICENSE .no-mistakes.yaml .omp .opencode .pi README.md skills state .tasks.toml tests VISION.md 
git lock: absent
receipt: absent
marker: absent
parent marker: absent
state payload: absent
new content: absent
data payload: durable data
route meta: present
staging: /tmp/fm-live-payload-restore.n91Etv/lab/state/.home-return.6avwiR 
worktree dir: present
retirement attempt 2 (retry) exit=1
  err2: WARNING: watcher still down (same stale episode; last beat: never, grace 300s) - full banner already printed this episode.
  err2: REFUSED: unsafe secondmate home removal target /tmp/fm-live-payload-restore.n91Etv/slot is not a seeded secondmate home
after retry: home worktree=present route meta=present git admin=present
staging after retry: /tmp/fm-live-payload-restore.n91Etv/lab/state/.home-return.6avwiR 
MODE=empty attempt1=1 attempt2=1
Evidence: Adversarial: recreated state/ carrying real new content is still refused, new content preserved, no clobber

Source: Adversarial: recreated state/ carrying real new content is still refused, new content preserved, no clobber

seed rc=0 home=scaffolded: /tmp/fm-live-payload-restore.8eiUZR/lab/data/mate/brief.md (secondmate charter)
home=/tmp/fm-live-payload-restore.8eiUZR/slot
--- snapshot: after seed (/tmp/fm-live-payload-restore.8eiUZR/slot)
home entries: .agents AGENTS.md assets bin .claude CLAUDE.md .codex config CONTRIBUTING.md .cursor data docs .fm-secondmate-home .fm-secondmate-parent .git .gitattributes .github .gitignore .greptile .grok GROK_BOT.md LICENSE .no-mistakes.yaml .omp .opencode .pi projects README.md skills state .tasks.toml tests VISION.md 
git lock: Firstmate durable home mate [fm-home-lock.7Mnc5I]
receipt: present
marker: mate
parent marker: schema=fm-secondmate-parent.v1
route=local
parent_home=/tmp/fm-live-payload-restore.8eiUZR/lab
state payload: live payload
new content: absent
data payload: durable data
route meta: present
staging: 
worktree dir: present
retirement attempt 1 exit=1
  err1: ●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  err1: ●  WATCHER DOWN - SUPERVISION IS OFF
  err1: ●  1 task(s) in flight, but no watcher has a fresh beacon (last beat: never, grace 300s).
  err1: ●  Trust the emitted supervision protocol for this harness; do not use shell & for watcher repair.
  err1: ●  This is a supervision warning only; the guarded operation WILL still run.
  err1: ●  repair a missing or failed watcher cycle with the Pi tool fm_watch_arm_pi, or restart Pi with -e /tmp/fm-live-payload-restore.8eiUZR/code/.pi/extensions/fm-primary-turnend-guard.ts -e /tmp/fm-live-payload-restore.8eiUZR/code/.pi/extensions/fm-primary-pi-watch.ts if the extensions are not loaded.
  err1: ●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  err1: treehouse: pool return failed (synthetic external boundary)
  err1: error: cannot restore staged payload path state for durable home /tmp/fm-live-payload-restore.8eiUZR/slot; it exists again
  err1: error: treehouse return failed for secondmate home /tmp/fm-live-payload-restore.8eiUZR/slot; preserving the home and its records for retry (lease may still be held)
--- snapshot: after failed return (/tmp/fm-live-payload-restore.8eiUZR/slot)
home entries: .agents AGENTS.md assets bin .claude CLAUDE.md .codex CONTRIBUTING.md .cursor data docs .git .gitattributes .github .gitignore .greptile .grok GROK_BOT.md LICENSE .no-mistakes.yaml .omp .opencode .pi README.md skills state .tasks.toml tests VISION.md 
git lock: absent
receipt: absent
marker: absent
parent marker: absent
state payload: absent
new content: recreated by a live process
data payload: durable data
route meta: present
staging: /tmp/fm-live-payload-restore.8eiUZR/lab/state/.home-return.D5YwXV 
worktree dir: present
retirement attempt 2 (retry) exit=1
  err2: WARNING: watcher still down (same stale episode; last beat: never, grace 300s) - full banner already printed this episode.
  err2: REFUSED: unsafe secondmate home removal target /tmp/fm-live-payload-restore.8eiUZR/slot is not a seeded secondmate home
after retry: home worktree=present route meta=present git admin=present
staging after retry: /tmp/fm-live-payload-restore.8eiUZR/lab/state/.home-return.D5YwXV 
MODE=content attempt1=1 attempt2=1
Evidence: Happy path: ordinary pooled retirement returns a clean slot and the next seed leases it

Source: Happy path: ordinary pooled retirement returns a clean slot and the next seed leases it

seed rc=0 home=scaffolded: /tmp/fm-live-payload-restore.HJcmH8/lab/data/mate/brief.md (secondmate charter)
home=/tmp/fm-live-payload-restore.HJcmH8/slot
--- snapshot: after seed (/tmp/fm-live-payload-restore.HJcmH8/slot)
home entries: .agents AGENTS.md assets bin .claude CLAUDE.md .codex config CONTRIBUTING.md .cursor data docs .fm-secondmate-home .fm-secondmate-parent .git .gitattributes .github .gitignore .greptile .grok GROK_BOT.md LICENSE .no-mistakes.yaml .omp .opencode .pi projects README.md skills state .tasks.toml tests VISION.md 
git lock: Firstmate durable home mate [fm-home-lock.SqFDDN]
receipt: present
marker: mate
parent marker: schema=fm-secondmate-parent.v1
route=local
parent_home=/tmp/fm-live-payload-restore.HJcmH8/lab
state payload: live payload
new content: absent
data payload: durable data
route meta: present
staging: 
worktree dir: present
retirement attempt 1 exit=0
  err1: ●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  err1: ●  WATCHER DOWN - SUPERVISION IS OFF
  err1: ●  1 task(s) in flight, but no watcher has a fresh beacon (last beat: never, grace 300s).
  err1: ●  Trust the emitted supervision protocol for this harness; do not use shell & for watcher repair.
  err1: ●  This is a supervision warning only; the guarded operation WILL still run.
  err1: ●  repair a missing or failed watcher cycle with the Pi tool fm_watch_arm_pi, or restart Pi with -e /tmp/fm-live-payload-restore.HJcmH8/code/.pi/extensions/fm-primary-turnend-guard.ts -e /tmp/fm-live-payload-restore.HJcmH8/code/.pi/extensions/fm-primary-pi-watch.ts if the extensions are not loaded.
  err1: ●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
--- snapshot: after first retirement attempt (/tmp/fm-live-payload-restore.HJcmH8/slot)
home entries: .agents AGENTS.md assets bin .claude CLAUDE.md .codex CONTRIBUTING.md .cursor docs .git .gitattributes .github .gitignore .greptile .grok GROK_BOT.md LICENSE .no-mistakes.yaml .omp .opencode .pi README.md skills .tasks.toml tests VISION.md 
git lock: absent
receipt: absent
marker: absent
parent marker: absent
state payload: absent
new content: absent
data payload: absent
route meta: absent
staging: 
worktree dir: present
re-seed of the returned slot rc=0 home=scaffolded: /tmp/fm-live-payload-restore.HJcmH8/lab/data/next/brief.md (secondmate charter)
home=/tmp/fm-live-payload-restore.HJcmH8/slot
re-seeded marker=next
re-seeded lock=Firstmate durable home next [fm-home-lock.q5PmfJ]
re-seeded receipt=present
re-seeded staging=
MODE=clean attempt1=0 reseed=0
Evidence: tests/fm-home-payload-return.test.sh on the target commit (rc=0)

Source: tests/fm-home-payload-return.test.sh on the target commit (rc=0)

# tests/fm-home-payload-return.test.sh on {run-worktree} (target commit)
error: durable home /tmp/fm-home-payload-return.H1v74X/slot tracks payload paths (data/notes); leaving its slot payload in place
ok - pool return observes a clean slot, failures preserve retry ownership, and a handled interrupt restores the home

real	0m1.868s
user	0m0.321s
sys	0m0.434s
rc=0
Evidence: tests/fm-home-payload-return.test.sh against the pre-fix library (rc=1, handled interrupt lost state payload)

Source: tests/fm-home-payload-return.test.sh against the pre-fix library (rc=1, handled interrupt lost state payload)

# tests/fm-home-payload-return.test.sh against the pre-fix library (last commit's bin/fm-home-payload-lib.sh hunk reverted)
error: durable home /tmp/fm-home-payload-return.vfQcCk/slot tracks payload paths (data/notes); leaving its slot payload in place
error: cannot restore staged payload path state for durable home /tmp/fm-home-payload-return.vfQcCk/slot; it exists again
error: interrupted return of durable home /tmp/fm-home-payload-return.vfQcCk/slot could not restore /tmp/fm-home-payload-return.vfQcCk/parent/state/.home-return.79fiLx
cat: /tmp/fm-home-payload-return.vfQcCk/slot/state/alive: No such file or directory
not ok - handled interrupt lost state payload
rc=1
  • Outcome: ⚠️ 1 info across 1 run (5m52s)

Pipeline

Updates from git push no-mistakes

✅ **Intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

⚠️ **Test** - 1 info
  • ℹ️ Transient live driver (a /tmp script invoking the real bin/fm-home-seed.sh, bin/fm-teardown.sh and the payload/lock libraries with a stand-in treehouse boundary) was deleted after the runs; the per-run transcripts in the evidence directory record every command outcome, and the change's own regression test (tests/fm-home-payload-return.test.sh) is now the repeatable check for the fixed behavior.
  • Live validation: ✅ go - 4 of 4 scenarios driven live against the product
Scenario Result Live Evidence
Retire a durable secondmate home whose pool return recreates an empty state/ and then fails: bin/fm-teardown.sh restores the whole home (payload, markers, Git lock, receipt) and the retried teardown r… ✅ pass live ~/.no-mistakes/evidence/01M7KW3DZZMFGHW8TY4C9T74X8/payload-restore-empty-fixed.txt - attempt 1 exit=1 with 'error: treehouse return failed for secondmate home ...; preserving the home and its…
Restore still refuses a recreated payload dir that carries real new content, instead of deleting it: teardown reports the refusal, the new file survives, and staged payload is not clobbered into the h… ✅ pass live ~/.no-mistakes/evidence/01M7KW3DZZMFGHW8TY4C9T74X8/payload-restore-content-fixed.txt - 'error: cannot restore staged payload path state for durable home ...; it exists again', 'new content: re…
Ordinary pooled retirement (no recreated dir) still hands back a clean slot that the next seed leases with its own identity and protection ✅ pass live ~/.no-mistakes/evidence/01M7KW3DZZMFGHW8TY4C9T74X8/payload-restore-clean-fixed.txt - retirement exit=0, kept checkout has data/state/config/projects and both markers absent, staging empty; fol…
The pre-fix library reproduces the maintainer-reported symptom on the same recreated-empty-state/ failure: restore refuses, markers and payload stay stranded in staging, and the retried teardown refus… ✅ pass live ~/.no-mistakes/evidence/01M7KW3DZZMFGHW8TY4C9T74X8/payload-restore-empty-prefix.txt ('cannot restore staged payload path state ...; it exists again', staging .home-return.* stranded, retry exi…
  • ROOT=$PWD MODE=empty EVID=<evidence> bash /tmp/fm-live-payload-restore.sh - real bin/fm-home-seed.sh mate - --no-projects then real bin/fm-teardown.sh mate on a disposable code root, git worktree home and marked lab FM_HOME, with the treehouse return boundary recreating an empty state/ and failing: attempt 1 exit 1 with the whole home restored (marker mate, parent binding, state/alive, data/notes, Git lock, ownership receipt, empty staging), attempt 2 exit 0, worktree and Git admin removed
  • ROOT=<checkout with the last commit's bin/fm-home-payload-lib.sh hunk reversed> MODE=empty bash /tmp/fm-live-payload-restore.sh - pre-fix contrast: cannot restore staged payload path state ...; it exists again, marker/state lost, staging .home-return.* stranded, retry exit 1 REFUSED: ... is not a seeded secondmate home
  • ROOT=$PWD MODE=content bash /tmp/fm-live-payload-restore.sh - recreated state/ carrying a real new file: teardown reports the same refusal, state/live.txt survives intact, staged payload is not clobbered into the home, staging retained for a later look
  • ROOT=$PWD MODE=clean bash /tmp/fm-live-payload-restore.sh - ordinary pooled retirement returns 0 and leaves the kept checkout with no data/, state/, config/, projects/ or identity markers; a following bin/fm-home-seed.sh next - --no-projects leases the same slot with marker=next, its own Git lock and receipt
  • bash tests/fm-home-payload-return.test.sh (rc=0, 1.9 s) and the same test against the pre-fix library copy (rc=1, not ok - handled interrupt lost state payload)
  • manual snapshot assertions after each teardown attempt on home entries, $gitdir/locked, $gitdir/firstmate-home-lock, marker/parent marker, payload files, route meta, .home-return.* staging and worktree presence
✅ **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 @kesslerio. Protecting idle durable homes from an ordinary git worktree remove is a real gap, and the fail-closed ownership receipt is careful work. I read head 0489e71c against main 2c93247f (it's current, 0 behind).

What I checked:

  • New bin/fm-home-worktree-lock-lib.sh. The receipt in the worktree's admin dir binds schema, mate id, canonical home, parent and a unique reason. Foreign or unknown locks, symlinked metadata and a mismatched backlink all refuse. Clone homes are untouched.
  • fm-home-seed.sh now locks every linked-worktree home at seed (and on reseed of an existing unlocked one). Rollback releases only an attempt-owned lock, and a failed treehouse return restores it.
  • fm-teardown.sh: removal validates the lock and releases it only when it matches the mate and parent, so a foreign lock now refuses even with --force. An unpooled linked home is now removed with git worktree remove --force instead of safe_rm_rf. Failed unlock, return or removal restores the lock and the process-event registrations (the fix from the review step).
  • No workflow, network or credential changes. The attestation binds this head, and "PR must be raised via no-mistakes" passed. The CI run is still in progress.

Contract-class (mine): new-default. On main, seeding an unconfigured home never puts a Git lock on it, and teardown removes an unpooled linked home with a plain recursive delete. With this tip, every linked-worktree secondmate home gets a lock by default, ordinary Git removal refuses it, and teardown refuses some homes it used to remove. That's a sensible protection, but it's new default behavior rather than the repair of a broken, already-specified path. So it goes to Kun as merge-or-leave once it's otherwise ready.

VISION.md, rule by rule

  • One captain, one interface: aligns (no new captain-facing surface; refusals are loud).
  • Authority is explicit and never inferred: aligns. It strengthens a refusal path, and only matching Firstmate ownership can unlock.
  • Scripts own the mechanics, agents own the judgment: aligns (exact receipt checks in a library).
  • A restart is a non-event: aligns. The durable home survives an idle mate, and failed returns keep the route for retry.
  • Delegation with a spine: cannot tell yet. See live evidence below.
  • The fleet outlives any vendor: aligns (Git-native, with treehouse and plain clones handled).
  • Scope: aligns (command layer only; about 6 lines in docs/configuration.md, nothing in the always-loaded contract).

One warm ask, no rush (waiting on you): the two "live" rows both point at bash tests/fm-secondmate-safety.test.sh, which is the fixture suite. When you get a chance, could you seed a real linked-worktree secondmate home (treehouse-leased if you have the pool), show that git worktree remove refuses it, then retire it with fm-teardown.sh and show the lock and receipt are gone? Please post that trace here, or re-raise through git push no-mistakes with it. We won't run our own live test. After that, and once CI is green, this goes to Kun for merge-or-leave.

@kesslerio
kesslerio force-pushed the fix/6921-durable-home-worktree-lock branch from 0489e71 to d495e61 Compare October 21, 2026 16:54
@kesslerio kesslerio changed the title fix: protect durable linked-worktree homes fix(teardown): protect durable homes with Git worktree locks Oct 21, 2026
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thank you @kesslerio for the update.

What changed since my 14:21Z stamp: the head is now d495e615, rebased onto main 3847411b. I range-diffed it. Your three reviewed commits are identical. The two new ones are 616657c0, which links fm-home-worktree-lock-lib.sh into the fm-gotmp teardown fixture (a fixture fix, with no assertion changes), and d495e615, a docs trim in the secondmate-provisioning skill. No .github, network or credential changes, and I have no security concerns.

Where it stands:

  • The no-mistakes attestation matches d495e615, and "PR must be raised via no-mistakes" passed.
  • CI is green except Behavior tests (Herdr), which hit the known concurrent secondmate recovery flake. That's the same case that fails on main, as you noted. I reran the failed job (run 39638974899).
  • Thanks for the new live transcript. It shows an ordinary git worktree remove refusing a home locked by the shipped library (rc=128, "cannot remove a locked working tree"). That's half of what I asked for.
  • Contract-class: new-default, unchanged. Every linked-worktree home gets a lock at seed by default, and teardown now refuses some homes it used to remove. So it goes to Kun as merge-or-leave, not auto-merge.
  • VISION: unchanged from my last stamp. All rules align except Delegation with a spine, which is still cannot-tell until the end-to-end trace below.

Still waiting on you, warmly: the transcript locks the home with the library directly. Could you also drive the product path end to end: seed a real linked-worktree secondmate home with fm-home-seed.sh, show the refusal, then retire it with fm-teardown.sh and show the lock and receipt are gone and the home is removed? Please post that here, or re-raise through git push no-mistakes with it. We won't run our own live test. Once that's posted and CI is green, this goes to Kun.

@kesslerio

Copy link
Copy Markdown
Contributor Author

@kunchenguid — CI on this PR is 18 of 19 green, and the one red job needs a re-run.

Head d495e615. The only red job is Behavior tests (Herdr), on tests/fm-backend-herdr-presentation-e2e.test.sh — "concurrent secondmate recovery failed". The identical case fails on origin/main at 3847411b, so it is pre-existing. This branch's diff is bin/fm-home-worktree-lock-lib.sh (new), bin/fm-teardown.sh, docs/configuration.md and tests/fm-secondmate-safety.test.sh — none of it touches the Herdr presentation path.

The fix this PR makes, for the record: the durable-home lock is published in the home's own state dir, so git worktree remove on a locked Firstmate home now exits 128 with fatal: cannot remove a locked working tree, lock reason: Firstmate durable home mate-1 [...] and the home survives. That was exercised against a disposable repo with a linked worktree, through the shipped library.

Ask — re-run Behavior tests (Herdr) on this head. kesslerio has no admin rights on kunchenguid/firstmate, so I cannot trigger the re-run myself.

One limit worth naming: the protected-home path was exercised against GNU git on Linux, not against a desktop workspace manager calling worktree remove + trash_rename. The fm-secondmate-safety suite is 83 scenarios green; fm-backlog-handoff and fm-gotmp are green; fm-secondmate-sync and fm-teardown fail identically on this head and on the unchanged base for environment reasons (restricted PATH without cat, tasks-axi absent), so they are not this branch's.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thanks @kesslerio, you're right about the Herdr job.

Where it stands at head d495e615 (1 behind main 83b70ef4. The one new main commit, #7155, touches session-start and supervision files only, so it doesn't overlap this PR):

  • The head is unchanged since my 18:26Z stamp. The no-mistakes attestation still matches, and "PR must be raised via no-mistakes" passed.
  • CI is 18 of 19 green. Behavior tests (Herdr) failed again on its first rerun with the same concurrent secondmate recovery / "could not acquire its session lock" case we've seen on main, so I've rerun the failed job once more (run 39638974899). That job isn't yours to fix.
  • Contract-class: new-default, unchanged. Linked-worktree homes get a lock at seed by default, and teardown now refuses some homes it used to remove. So this goes to Kun as merge-or-leave, not auto-merge.
  • VISION: unchanged. Every rule aligns except Delegation with a spine, which stays cannot-tell until the trace below is posted.

Still waiting on you, warmly: the transcript you posted locks the home through the library directly. The one thing I still need is the product path end to end:

  1. Seed a real linked-worktree secondmate home with fm-home-seed.sh.
  2. Show that git worktree remove refuses it.
  3. Retire it with fm-teardown.sh, and show the lock and receipt are gone and the home is removed.

Post it here, or re-raise through git push no-mistakes with it. We won't run our own live test. Once that's posted and CI is green, I'll send this to Kun.

@kesslerio

Copy link
Copy Markdown
Contributor Author

Product path, end to end: seed -> refused removal -> retirement

This is the live trace you asked for, plus one defect it exposed and the minimal fix for it.

How the trace was driven

A disposable lab home (bin/fm-lab-home.sh create, the same home bin/fm-live-lab.sh up builds), a private tmux server under the lab root's own TMUX_TMPDIR, and a real Treehouse pool whose treehouse.toml root points inside the lab root, so the user's Treehouse pool was never read or written. The home is a genuine linked worktree from treehouse get --lease, seeded by the shipped bin/fm-home-seed.sh, retired by the shipped bin/fm-teardown.sh.

One deliberate stand-in, stated plainly: the second mate's launch command is bash -lc "sleep 900" rather than a model session. fm-spawn.sh --secondmate still publishes the real state/<id>.meta record (kind=secondmate, home=, window=) that retirement reads, and the lock lifecycle does not depend on what the agent inside the home is doing. Everything else below is the product binaries against real git, real treehouse, real tmux.

The transcript

Paths are rewritten to $LABROOT (the throwaway lab root) and $REPO (the checkout the lab was built from); nothing else is edited.


=== build a disposable lab home from $REPO at 0037fcec ===
$ bash $REPO/bin/fm-lab-home.sh create $LABROOT/home
$LABROOT/home
[exit 0]
$ git -C $LABROOT/home init -q -b main && git -C $LABROOT/home fetch -q $REPO HEAD && git -C $LABROOT/home checkout -q -f -B main FETCH_HEAD
[exit 0]
$ git -C $LABROOT/home config user.name lab && git -C $LABROOT/home config user.email [email protected]
[exit 0]
$ mkdir -p $LABROOT/home/state $LABROOT/home/data $LABROOT/home/config $LABROOT/home/projects && printf 'tmux\n' > $LABROOT/home/config/backend
[exit 0]
$ git -C $LABROOT/home log --oneline -1
0037fce fix(retirement): hand back a clean pool slot from a retired durable home
[exit 0]

=== one real Treehouse pool, rooted inside the lab so the user's Treehouse pool is untouched ===
$ cd $LABROOT/home && treehouse init >/dev/null 2>&1; sed -i 's|^root = ""|root = "$LABROOT/throot"|' $LABROOT/home/treehouse.toml && grep '^root' $LABROOT/home/treehouse.toml
root = "$LABROOT/throot"
[exit 0]

=== 1. seed a real linked-worktree secondmate home (fm-home-seed.sh leases it) ===
$ cd $LABROOT/home && bash $LABROOT/home/bin/fm-home-seed.sh lab-mate - --no-projects
A new version of treehouse is available: v2.0.1 → v3.1.8
Run "treehouse update" to update

🌳 Setting up worktree...
🌳 Leased worktree at $LABROOT/throot/.treehouse/home-a6031f/1/home. Run 'treehouse return $LABROOT/throot/.treehouse/home-a6031f/1/home' to release it.
scaffolded: $LABROOT/home/data/lab-mate/brief.md (secondmate charter)
home=$LABROOT/throot/.treehouse/home-a6031f/1/home
[exit 0]
MATE=$LABROOT/throot/.treehouse/home-a6031f/1/home
$ ls -A $MATE | head -4
.agents
AGENTS.md
assets
bin
[exit 0]
$ cat $MATE/.git
gitdir: $LABROOT/home/.git/worktrees/home
[exit 0]
$ git -C $LABROOT/home worktree list
$LABROOT/home                                  0037fce [main]
$LABROOT/throot/.treehouse/home-a6031f/1/home  0037fce (detached HEAD) locked
[exit 0]
$ cat $(git -C $MATE rev-parse --absolute-git-dir)/locked
Firstmate durable home lab-mate [fm-home-lock.D6X0z9]
[exit 0]
$ cat $(git -C $MATE rev-parse --absolute-git-dir)/firstmate-home-lock
schema=fm-home-worktree-lock.v1
id=lab-mate
home=$LABROOT/throot/.treehouse/home-a6031f/1/home
parent=$LABROOT/home
reason=Firstmate durable home lab-mate [fm-home-lock.D6X0z9]
[exit 0]
$ cat $LABROOT/home/data/secondmates.md
- lab-mate - Idle lab second mate for a durable-home lock trace no external work. (home: $LABROOT/throot/.treehouse/home-a6031f/1/home; scope: lab durable home lock trace; projects: ; added 2026-10-30)
[exit 0]

=== 2. an ordinary 'git worktree remove' refuses the seeded home ===
$ cd $LABROOT/home && git worktree remove $MATE
fatal: cannot remove a locked working tree, lock reason: Firstmate durable home lab-mate [fm-home-lock.D6X0z9]
use 'remove -f -f' to override or unlock first
[exit 128]
$ ls -d $MATE && git -C $LABROOT/home worktree list | tail -1
$LABROOT/throot/.treehouse/home-a6031f/1/home
$LABROOT/throot/.treehouse/home-a6031f/1/home  0037fce (detached HEAD) locked
[exit 0]

=== 3. guarded retirement with bin/fm-teardown.sh ===
$ env -u TMUX TMUX_TMPDIR=$(bash $LABROOT/home/bin/fm-lab-home.sh tmux-dir $LABROOT/home) tmux -f /dev/null new-session -d -s firstmate -n lab -x 200 -y 50 -c $LABROOT
[exit 0]
$ cd $LABROOT/home && env -u TMUX TMUX_TMPDIR=$(bash $LABROOT/home/bin/fm-lab-home.sh tmux-dir $LABROOT/home) FM_HOME=$LABROOT/home FM_BACKEND=tmux bash $LABROOT/home/bin/fm-spawn.sh lab-mate --secondmate --harness 'bash -lc "sleep 900"'
spawned lab-mate harness=bash kind=secondmate mode=secondmate yolo=off window=firstmate:fm-lab-mate worktree=$LABROOT/throot/.treehouse/home-a6031f/1/home
[exit 0]
$ grep -E '^(kind|home|window)=' $LABROOT/home/state/lab-mate.meta
window=firstmate:fm-lab-mate
kind=secondmate
home=$LABROOT/throot/.treehouse/home-a6031f/1/home
[exit 0]
$ cd $LABROOT/home && env -u TMUX TMUX_TMPDIR=$(bash $LABROOT/home/bin/fm-lab-home.sh tmux-dir $LABROOT/home) FM_HOME=$LABROOT/home FM_BACKEND=tmux bash $LABROOT/home/bin/fm-teardown.sh lab-mate
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
●  WATCHER DOWN - SUPERVISION IS OFF
●  1 task(s) in flight, but no watcher has a fresh beacon (last beat: never, grace 300s).
●  Trust the emitted supervision protocol for this harness; do not use shell & for watcher repair.
●  This is a supervision warning only; the guarded operation WILL still run.
●  repair a missing or failed watcher cycle with the Pi tool fm_watch_arm_pi, or restart Pi with -e $LABROOT/home/.pi/extensions/fm-primary-turnend-guard.ts -e $LABROOT/home/.pi/extensions/fm-primary-pi-watch.ts if the extensions are not loaded.
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
A new version of treehouse is available: v2.0.1 → v3.1.8
Run "treehouse update" to update

🌳 Worktree returned to pool.
teardown lab-mate complete (window firstmate:fm-lab-mate, worktree $LABROOT/throot/.treehouse/home-a6031f/1/home)
[exit 0]
$ git -C $LABROOT/home worktree list
$LABROOT/home                                  0037fce [main]
$LABROOT/throot/.treehouse/home-a6031f/1/home  0037fce (detached HEAD)
[exit 0]
$ ls -A $MATE | grep -E 'fm-secondmate|^(data|state|config|projects)$' || echo '(no home payload left in the returned slot)'
(no home payload left in the returned slot)
[exit 0]
$ ls $MATE/AGENTS.md
$LABROOT/throot/.treehouse/home-a6031f/1/home/AGENTS.md
[exit 0]
$ ls $(git -C $MATE rev-parse --absolute-git-dir)/locked $(git -C $MATE rev-parse --absolute-git-dir)/firstmate-home-lock 2>&1
ls: cannot access '$LABROOT/home/.git/worktrees/home/locked': No such file or directory
ls: cannot access '$LABROOT/home/.git/worktrees/home/firstmate-home-lock': No such file or directory
[exit 2]
$ cat $LABROOT/home/data/secondmates.md 2>&1; ls $LABROOT/home/state/lab-mate.meta 2>&1
ls: cannot access '$LABROOT/home/state/lab-mate.meta': No such file or directory
[exit 2]
$ cd $LABROOT/home && treehouse status
A new version of treehouse is available: v2.0.1 → v3.1.8
Run "treehouse update" to update

1     available    $LABROOT/throot/.treehouse/home-a6031f/1/home
[exit 0]

=== 4. the returned slot is leasable again: the next mate seeds into it ===
$ cd $LABROOT/home && bash $LABROOT/home/bin/fm-home-seed.sh lab-mate-2 - --no-projects
A new version of treehouse is available: v2.0.1 → v3.1.8
Run "treehouse update" to update

🌳 Setting up worktree...
🌳 Leased worktree at $LABROOT/throot/.treehouse/home-a6031f/1/home. Run 'treehouse return $LABROOT/throot/.treehouse/home-a6031f/1/home' to release it.
scaffolded: $LABROOT/home/data/lab-mate-2/brief.md (secondmate charter)
home=$LABROOT/throot/.treehouse/home-a6031f/1/home
[exit 0]
$ ls -d $MATE; cat $MATE/.fm-secondmate-home; cat $(git -C $MATE rev-parse --absolute-git-dir)/locked
$LABROOT/throot/.treehouse/home-a6031f/1/home
lab-mate-2
Firstmate durable home lab-mate-2 [fm-home-lock.CLlKN3]
[exit 0]
$ grep -E '^(id|reason)' $(git -C $MATE rev-parse --absolute-git-dir)/firstmate-home-lock
id=lab-mate-2
reason=Firstmate durable home lab-mate-2 [fm-home-lock.CLlKN3]
[exit 0]

=== cleanup: retire the second mate and remove the lab ===
$ cd $LABROOT/home && env -u TMUX TMUX_TMPDIR=$(bash $LABROOT/home/bin/fm-lab-home.sh tmux-dir $LABROOT/home) FM_HOME=$LABROOT/home FM_BACKEND=tmux bash -c 'bash $LABROOT/home/bin/fm-spawn.sh lab-mate-2 --secondmate --harness "bash -lc \"sleep 900\"" >/dev/null 2>&1; bash $LABROOT/home/bin/fm-teardown.sh lab-mate-2 2>&1 | tail -3'

🌳 Worktree returned to pool.
teardown lab-mate-2 complete (window firstmate:fm-lab-mate-2, worktree $LABROOT/throot/.treehouse/home-a6031f/1/home)
[exit 0]
$ cd $LABROOT/home && env -u TMUX TMUX_TMPDIR=$(bash $LABROOT/home/bin/fm-lab-home.sh tmux-dir $LABROOT/home) tmux kill-server 2>/dev/null; bash $LABROOT/home/bin/fm-lab-home.sh teardown $LABROOT/home
[exit 0]
$ rm -rf $LABROOT && echo 'lab root removed'
lab root removed
[exit 0]

What it shows

  1. Seeding a linked-worktree home takes the Git lock and publishes the ownership receipt, so git -C <primary> worktree list reports the home locked and the lock reason names Firstmate durable home lab-mate [fm-home-lock....].
  2. An ordinary git worktree remove refuses with exit 128: fatal: cannot remove a locked working tree, lock reason: Firstmate durable home lab-mate [...]. The home survives; nothing else was holding it.
  3. bin/fm-teardown.sh retires it: lock gone, receipt gone, state/<id>.meta gone, registry route gone, the slot back to available, and the checkout still intact with no home payload in it.
  4. The returned slot is leasable again: the next mate seeds into the same slot and owns it as lab-mate-2 with its own fresh lock and receipt.

The defect the trace exposed, and the fix

A real pool keeps the checkout when it returns a slot. Before this fix, retirement left the retired mate's .fm-secondmate-home marker, .fm-secondmate-parent, data/, state/, config/ and projects/ inside the slot the pool hands out again. Reproduced on this PR's previous head d495e615 (same lab, same commands):

$ bash bin/fm-teardown.sh lab-mate        # retires it, slot shows "available"
$ ls -A $SLOT | grep -E 'fm-secondmate|^(data|state|config|projects)$'
config
data
.fm-secondmate-home
.fm-secondmate-parent
projects
state
$ bash bin/fm-home-seed.sh lab-mate-2 - --no-projects
error: secondmate home .../1/home is already marked for lab-mate
error: secondmate home .../1/home is already marked for lab-mate
[exit 1]
$ treehouse status
1     leased       .../1/home  (held by lab-mate-2)

So one ordinary retirement made the pool slot impossible to seed again, and this branch's rollback ownership guard then declined to return a home marked for another mate, which stranded the lease on a mate that does not exist. The slot-poisoning predates this branch; the stranded lease is what this branch's guard added on top.

The fix (commit 0037fcec, on top of d495e615):

  • bin/fm-home-payload-lib.sh owns the cleanup: retirement and seed rollback clear the retired home's payload from the slot (both identity markers plus data/, state/, config/, projects/).
  • It runs only after the return succeeded, so a failed return still leaves the whole home for the retry this branch is careful to preserve, and the existing "failed return restores owned protection" contract is untouched.
  • It refuses a payload path that carries tracked files, so a checkout is never dirtied into a failed return; it deletes only the retired home's own records.
  • tests/fm-gotmp.test.sh links the second library the real teardown sources (same fixture fix as 616657c0 did for the lock library).
  • tests/fm-secondmate-safety.test.sh gains a pooled-slot scenario that retires a seeded linked home, asserts the returned slot carries no payload, reseeds that same slot as the next mate and asserts the new mate's lock and receipt, and pins the tracked-file refusal. It also asserts a failed return keeps the home and its prerequisite for retry.

Suites on the fixed head, on this host: tests/fm-secondmate-safety.test.sh exit 0 (84 scenarios), tests/fm-secondmate-lifecycle-e2e.test.sh exit 0, tests/fm-gotmp.test.sh exit 0, bin/fm-lint.sh exit 0, bin/fm-doc-audience-check.sh exit 0.

Delivery state, stated plainly

The fix is committed on this host as 0037fcec (branch pr7607-homelock-revalidate in the pr7607-homelock worktree). It is not on this PR's head yet, and I did not force that, for two reasons:

  1. git push no-mistakes fix/6921-durable-home-worktree-lock is refused by the gate: daemon admit-push only authorizes the pipeline's own process, and a raw push falls back to "not an open PR for that branch / issue not labeled ready-for-pr". Delivery has to come from a pipeline run on this branch name.
  2. That pipeline run cannot reach the push step cleanly: the branch is CONFLICTING with current origin/main (109 commits ahead), and the pipeline's rebase gate reports merge conflict rebasing onto origin/main in bin/fm-teardown.sh. The conflict is semantic, not mechanical: upstream changed remove_firstmate_home to # <home> <label> <task-id> <backend>, while this branch added a 4th positional lock_parent, so the two occupy the same slot and the call sites have to be reconciled by hand.

You asked for no rebase and no conflicts from me, so I stopped at the gate rather than resolving that merge for you. Say the word and I will resolve it (the shape I would use: keep upstream's backend argument, carry lock_parent as a 5th argument so both t3code_secondmate_lsof_check and the durable-lock checks keep their inputs), rebase on origin/main, and drive the pipeline through push/PR/CI.

@kesslerio

Copy link
Copy Markdown
Contributor Author

Status note on 95f0a6cf, and a patch that needs a port decision.

The live trace asked for is posted above — seed → worktree remove refusal → teardown, end to end on the real path. While driving it, a real defect surfaced and was fixed: a retired durable home's payload (.fm-secondmate-home, data/, state/, config/, projects/) survived into a pooled slot, making the returned slot unseedable ("already marked for …", then the rollback guard stranded the lease).

The fix clears the payload only after a successful return and refuses any payload path carrying tracked files. Verified: fm-secondmate-safety 84 ok, fm-secondmate-lifecycle-e2e, fm-gotmp, fm-lint.sh all green. (One fm-teardown-endpoint-safety failure reproduces identically on clean origin/main — pre-existing, not this diff.)

I could not push it through the gate: the branch is rebased onto 095db3bc to resolve the bin/fm-teardown.sh positional collision — upstream added backend as remove_firstmate_home's 4th arg while this branch had lock_parent; the rebase keeps upstream's signature byte-identical and appends lock-parent as the 5th positional — and the gate refuses admission for a rewritten published series (blocked_diverged), while the direct-push admission can't find this cross-repo PR and UPSTREAM_ISSUE=6921 is existing-pr, not ready-for-pr. The maintainer-side port may be the cleaner route either way; the tip commit's patch follows in full.

From 95f0a6cfb97b12dcbf1d285e5879261945a17c61 Mon Sep 17 00:00:00 2001
From: Martin Kessler [email protected]
Date: Fri, 30 Oct 2026 23:14:12 -0700
Subject: [PATCH] fix(retirement): hand back a clean pool slot from a retired
durable home

A real Treehouse pool keeps the checkout when it returns a slot, so a
retired durable linked-worktree home left its identity markers, data/,
state/, config/ and project clones inside a slot the pool hands out
again. The next seed in that slot refused it as "already marked for
", so one ordinary retirement turned the pool slot into a
home no secondmate could ever lease again.

Retirement and seed rollback now clear that payload from the slot once
the return succeeds. Pruning only after a released slot keeps the
retry contract intact: a failed return still leaves the whole home for
the retry the route is preserved for, and the cleanup refuses a payload
path that carries tracked files rather than dirtying a checkout into a
failed return. bin/fm-home-payload-lib.sh owns the cleanup.

The gotmp fixture builds a home that runs the real teardown, so it now
links the second library the teardown sources.

Verified on this host: tests/fm-secondmate-safety.test.sh exits 0 with
84 scenarios, including a new pooled-slot scenario that retires a seeded
linked home, asserts the returned slot carries no payload, and reseeds
the same slot as the next mate; tests/fm-secondmate-lifecycle-e2e.test.sh,
tests/fm-gotmp.test.sh, bin/fm-lint.sh and bin/fm-doc-audience-check.sh
exit 0.

bin/fm-home-payload-lib.sh | 28 ++++++++++++
bin/fm-home-seed.sh | 10 ++++-
bin/fm-teardown.sh | 13 ++++++
docs/configuration.md | 2 +
tests/fm-gotmp.test.sh | 4 ++
tests/fm-secondmate-safety.test.sh | 68 ++++++++++++++++++++++++++++++
tests/secondmate-helpers.sh | 6 ++-
7 files changed, 128 insertions(+), 3 deletions(-)
create mode 100644 bin/fm-home-payload-lib.sh

diff --git a/bin/fm-home-payload-lib.sh b/bin/fm-home-payload-lib.sh
new file mode 100644
index 00000000..a787897d
--- /dev/null
+++ b/bin/fm-home-payload-lib.sh
@@ -0,0 +1,28 @@
+#!/usr/bin/env bash
+# What a durable linked-worktree home leaves behind when its slot is returned.
+# A returned slot is an ordinary pool checkout again, so it must not keep the
+# retired mate's home payload: identity markers, data/, state/, config/ and
+# projects/. A slot that keeps them is not reusable - the next seed in that slot
+# refuses it as a home "already marked for " - and it turns a
+# routine retirement into a pool slot no secondmate can ever lease again.
+# Prune runs only on a return path, because that is the point where the caller
+# has already decided the home is retired; removal paths delete the whole home
+# and never reach here. A payload path that carries tracked files is left in
+# place and refuses the prune, so a home whose tree tracks any of them keeps its
+# checkout intact instead of being dirtied into a failed return.
+# The home-lock library owns Git lock ownership; this library owns only the
+# payload cleanup that makes the returned slot reusable.
+
+fm_home_payload_prune() { #

  • local home=$1 tracked
  • [ -d "$home" ] || return 0
  • if git -C "$home" rev-parse --git-dir >/dev/null 2>&1; then
  • tracked=$(git -C "$home" ls-files -- data state config projects 2>/dev/null) || tracked=
  • [ -z "$tracked" ] || {
  •  echo "error: durable home $home tracks payload paths ($tracked); leaving its slot payload in place" >&2
    
  •  return 1
    
  • }
  • fi
  • rm -rf -- "$home/data" "$home/state" "$home/config" "$home/projects" || return 1
  • rm -f -- "$home/.fm-secondmate-home" "$home/.fm-secondmate-parent" || return 1
    +}
    diff --git a/bin/fm-home-seed.sh b/bin/fm-home-seed.sh
    index e3cb8784..66c37373 100755
    --- a/bin/fm-home-seed.sh
    +++ b/bin/fm-home-seed.sh
    @@ -24,7 +24,8 @@

generated briefs, new homes, new project clones, and registry edits are

rolled back. Treehouse-acquired homes are returned only when the rollback

target is safe and belongs to this attempt; existing homes and foreign

-# locks are preserved. A failed return restores owned protection and warns
+# locks are preserved. A returned slot keeps no home payload, so the next
+# seed can lease it. A failed return restores owned protection and warns

because the lease may still be held.

Set FM_SECONDMATE_CHARTER='' to seed from inline charter text

when no filled charter brief exists. Set FM_SECONDMATE_SCOPE=''

@@ -53,6 +54,8 @@ SUB_HOME_PARENT_MARKER=".fm-secondmate-parent"
. "$SCRIPT_DIR/fm-secondmate-charter-lib.sh"

shellcheck source=bin/fm-home-worktree-lock-lib.sh

. "$SCRIPT_DIR/fm-home-worktree-lock-lib.sh"
+# shellcheck source=bin/fm-home-payload-lib.sh
+. "$SCRIPT_DIR/fm-home-payload-lib.sh"

shellcheck source=bin/fm-wake-lib.sh

. "$SCRIPT_DIR/fm-wake-lib.sh"

@@ -624,6 +627,11 @@ seed_return_treehouse_home() {
echo "warning: failed to return treehouse-acquired home $abs_home during seed rollback; lease may still be held" >&2
return 0
}

  • A returned slot is an ordinary pool checkout again, so a home this attempt

  • half-seeded does not leave its payload behind for the next seed to refuse.

  • Only a released slot is pruned, so a failed return above keeps the home whole.

  • fm_home_payload_prune "$abs_home" \
  • || echo "warning: could not clear the retired home payload at $abs_home; the next seed in that slot may refuse it" >&2
    fm_home_worktree_lock_forget "$abs_home" "$SEED_ID" "$FM_HOME" || return 0
    }

diff --git a/bin/fm-teardown.sh b/bin/fm-teardown.sh
index 8d3e6687..e1edd1c2 100755
--- a/bin/fm-teardown.sh
+++ b/bin/fm-teardown.sh
@@ -205,6 +205,11 @@

Before returning a protected home, the home-lock library verifies and releases

only this mate and parent's Git lock; foreign or unknown locks refuse even

with --force. A failed return restores owned protection for retry.

+# A slot that goes back to the pool carries no home payload with it, because a
+# returned slot is an ordinary checkout again and a slot still marked for the
+# retired mate refuses the next seed; bin/fm-home-payload-lib.sh owns that
+# cleanup, and it runs only after a successful return so a failed return still
+# leaves the home whole for the retry.

Usage: fm-teardown.sh [--force] [--legacy-record]

--force skips ordinary-task dirty and landed-work checks, skips scout report

checks, and discards secondmate child work for kind=secondmate. Only use it

@@ -346,6 +351,8 @@ set -eu
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

shellcheck source=bin/fm-home-worktree-lock-lib.sh

. "$SCRIPT_DIR/fm-home-worktree-lock-lib.sh"
+# shellcheck source=bin/fm-home-payload-lib.sh
+. "$SCRIPT_DIR/fm-home-payload-lib.sh"
FM_ROOT="${FM_ROOT_OVERRIDE:-$(cd "$SCRIPT_DIR/.." && pwd)}"
FM_HOME="${FM_HOME:-${FM_ROOT_OVERRIDE:-$FM_ROOT}}"
STATE="${FM_STATE_OVERRIDE:-$FM_HOME/state}"
@@ -2923,6 +2930,12 @@ remove_firstmate_home() { #
restore_firstmate_home_process_events "$abs_home_path" "$label" "$process_event_backup" || return $?
return 1
}

  • A returned slot is a plain pool checkout again, so the retired home's

  • payload leaves with it; a slot that kept it would refuse the next seed.

  • This runs after the return, never before, so a failed return still leaves

  • the whole home intact for the retry the route is preserved for.

  • fm_home_payload_prune "$abs_home_path" \
  •  || echo "warning: could not clear the retired home payload at $abs_home_path; the next seed in that slot may refuse it" >&2
    
    fm_home_worktree_lock_forget "$abs_home_path" "$expected_id" "$lock_parent" || return 1
    [ -z "$process_event_backup" ] || rm -rf -- "$process_event_backup"
    return 0
    diff --git a/docs/configuration.md b/docs/configuration.md
    index 84812cf9..b8d55d1f 100644
    --- a/docs/configuration.md
    +++ b/docs/configuration.md
    @@ -1173,6 +1173,8 @@ A failed return restores protection when the worktree survives and preserves the
    This lock does not prevent filesystem trash operations or an explicit Git lock override by a tool that ignores the protection.
    The home-lock library owns receipt validation and release mechanics.
    Teardown of a leased home fails closed if treehouse return cannot release the lease; plain-clone homes with no treehouse pool slot are removed directly.
    +A returned slot is an ordinary pool checkout again, so retirement clears the retired home's payload (data/, state/, config/, projects/, and both identity markers) once the return succeeds, and a failed return keeps the whole home for the preserved retry; a slot that kept the payload would refuse the next seed in it as already marked for a mate that no longer exists.
    +The payload library owns that cleanup.

Project modes and backlog handoff

diff --git a/tests/fm-gotmp.test.sh b/tests/fm-gotmp.test.sh
index 231467cc..82ad3a66 100755
--- a/tests/fm-gotmp.test.sh
+++ b/tests/fm-gotmp.test.sh
@@ -61,6 +61,8 @@ SH
ln -s "$ROOT/bin/fm-session-lock-lib.sh" "$fake/bin/fm-session-lock-lib.sh"

fm-home-worktree-lock-lib.sh: teardown sources it for the durable-home lock.

ln -s "$ROOT/bin/fm-home-worktree-lock-lib.sh" "$fake/bin/fm-home-worktree-lock-lib.sh"

  • fm-home-payload-lib.sh: teardown sources it for the returned pool slot payload.

  • ln -s "$ROOT/bin/fm-home-payload-lib.sh" "$fake/bin/fm-home-payload-lib.sh"
    ln -s "$ROOT/bin/fm-agent-process-lib.sh" "$fake/bin/fm-agent-process-lib.sh"
    ln -s "$ROOT/bin/fm-gemini-lib.sh" "$fake/bin/fm-gemini-lib.sh"
    ln -s "$ROOT/bin/fm-cursor-lib.sh" "$fake/bin/fm-cursor-lib.sh"
    @@ -171,6 +173,8 @@ SH
    ln -s "$ROOT/bin/fm-session-lock-lib.sh" "$fake/bin/fm-session-lock-lib.sh"

    fm-home-worktree-lock-lib.sh: teardown sources it for the durable-home lock.

    ln -s "$ROOT/bin/fm-home-worktree-lock-lib.sh" "$fake/bin/fm-home-worktree-lock-lib.sh"

  • fm-home-payload-lib.sh: teardown sources it for the returned pool slot payload.

  • ln -s "$ROOT/bin/fm-home-payload-lib.sh" "$fake/bin/fm-home-payload-lib.sh"
    ln -s "$ROOT/bin/fm-agent-process-lib.sh" "$fake/bin/fm-agent-process-lib.sh"
    ln -s "$ROOT/bin/fm-gemini-lib.sh" "$fake/bin/fm-gemini-lib.sh"
    ln -s "$ROOT/bin/fm-cursor-lib.sh" "$fake/bin/fm-cursor-lib.sh"
    diff --git a/tests/fm-secondmate-safety.test.sh b/tests/fm-secondmate-safety.test.sh
    index d34023dc..05d5196e 100755
    --- a/tests/fm-secondmate-safety.test.sh
    +++ b/tests/fm-secondmate-safety.test.sh
    @@ -140,6 +140,8 @@ test_durable_home_git_lock_lifecycle() {
    fi
    [ "$(cat "$gitdir/locked")" = "$reason" ] || fail "failed retirement did not restore the exact lock"
    assert_present "$home/state/domain.meta" "failed return cleared route metadata"

  • assert_present "$sub/.fm-secondmate-home" "failed return pruned a home that was never released"

  • assert_present "$sub/data/charter.md" "failed return discarded the retryable home payload"

    real_git=$(command -v git)
    cat > "$fakebin/git" <<'SH'
    @@ -260,6 +262,71 @@ SH
    pass "failed seed releases attempt protection and preserves earlier owned protection"
    }

+# A real Treehouse pool keeps the checkout when it returns a slot, so retirement
+# has to hand back a slot the next seed can lease again. A slot that kept the
+# retired mate's payload refuses the next seed as "already marked for ",
+# which turns one ordinary retirement into a permanently unusable pool slot.
+test_durable_home_pool_slot_reuse() {

  • local fmroot home sub fakebin log gitdir guard
  • fmroot="$TMP_ROOT/slot-reuse-code"
  • home="$TMP_ROOT/slot-reuse-parent"
  • sub="$TMP_ROOT/slot-reuse-subhome"
  • clone_reviewed_head "$ROOT" "$fmroot" || fail "cannot create disposable code root"
  • git -C "$fmroot" worktree add --quiet --detach "$sub" HEAD || fail "cannot create disposable home worktree"
  • mkdir -p "$home/data" "$home/state"
  • fakebin=$(make_fake_tmux "$TMP_ROOT/slot-reuse-fake")
  • log="$TMP_ROOT/slot-reuse-fake/tmux.log"
  • gitdir=$(git -C "$sub" rev-parse --absolute-git-dir)
  • PATH="$fakebin:$PATH" FM_ROOT_OVERRIDE="$fmroot" FM_HOME="$home" FM_FAKE_TREEHOUSE_HOME="$sub" FM_FAKE_TMUX_LOG="$log" \
  • FM_SECONDMATE_CHARTER='first slot reuse domain' FM_SECONDMATE_SCOPE='first slot reuse domain' \
  • bash "$ROOT/bin/fm-home-seed.sh" first - --no-projects >/dev/null \
  • || fail "seed failed for the first pooled mate"
  • [ "$(cat "$sub/.fm-secondmate-home")" = first ] || fail "first seed did not mark the pooled home"
  • fm_write_secondmate_meta "$home/state/first.meta" "$sub"
  • PATH="$fakebin:$PATH" FM_ROOT_OVERRIDE="$fmroot" FM_HOME="$home" FM_FAKE_TMUX_LOG="$log" \
  • FM_FAKE_TMUX_CAPTURE="$TMP_ROOT/slot-reuse-fake/pane.txt" FM_FAKE_TREEHOUSE_KEEP_HOME=1 \
  • bash "$ROOT/bin/fm-teardown.sh" first >/dev/null 2>"$TMP_ROOT/slot-reuse-retire.err" \
  • || { cat "$TMP_ROOT/slot-reuse-retire.err" >&2; fail "retirement of a pooled durable home failed"; }
  • assert_absent "$gitdir/locked" "retirement left the Git worktree lock"
  • assert_absent "$gitdir/firstmate-home-lock" "retirement left the ownership receipt"
  • assert_absent "$home/state/first.meta" "retirement left the retired mate's task record"
  • assert_present "$sub/AGENTS.md" "the returned pool slot lost its checkout"
  • assert_absent "$sub/.fm-secondmate-home" "the returned slot still carried the retired home marker"
  • assert_absent "$sub/.fm-secondmate-parent" "the returned slot still carried the retired parent binding"
  • assert_absent "$sub/data" "the returned slot still carried the retired home data"
  • assert_absent "$sub/state" "the returned slot still carried the retired home state"
  • assert_absent "$sub/config" "the returned slot still carried the retired home config"
  • assert_absent "$sub/projects" "the returned slot still carried the retired home project clones"
  • The slot is leasable again, and the next mate owns it without inheriting the

  • retired mate's identity or its protection.

  • PATH="$fakebin:$PATH" FM_ROOT_OVERRIDE="$fmroot" FM_HOME="$home" FM_FAKE_TREEHOUSE_HOME="$sub" FM_FAKE_TMUX_LOG="$log" \
  • FM_SECONDMATE_CHARTER='second slot reuse domain' FM_SECONDMATE_SCOPE='second slot reuse domain' \
  • bash "$ROOT/bin/fm-home-seed.sh" second - --no-projects >/dev/null 2>"$TMP_ROOT/slot-reuse-reseed.err" \
  • || { cat "$TMP_ROOT/slot-reuse-reseed.err" >&2; fail "the next mate could not lease the returned slot"; }
  • [ "$(cat "$sub/.fm-secondmate-home")" = second ] || fail "the re-leased slot kept the retired mate's identity"
  • assert_present "$sub/data/charter.md" "the re-seeded home carries no charter"
  • grep -F 'id=second' "$gitdir/firstmate-home-lock" >/dev/null || fail "the re-seeded home carries no ownership receipt"
  • grep -F 'Firstmate durable home second' "$gitdir/locked" >/dev/null || fail "the re-seeded home carries no Git lock"
  • The cleanup never deletes a checkout's own tracked files: a home whose tree

  • tracks a payload path is refused instead of being dirtied into a failed return.

  • guard="$TMP_ROOT/slot-reuse-tracked"
  • git -C "$fmroot" worktree add --quiet --detach "$guard" HEAD || fail "cannot create tracked-payload worktree"
  • mkdir -p "$guard/data"
  • printf 'tracked\n' > "$guard/data/notes.md"
  • git -C "$guard" add -f data/notes.md || fail "cannot stage a tracked payload file"
  • git -C "$guard" -c user.name=test -c user.email=[email protected] commit -q -m 'track payload' \
  • || fail "cannot commit a tracked payload file"
  • if bash -c '. "$1"; fm_home_payload_prune "$2"' _ "$ROOT/bin/fm-home-payload-lib.sh" "$guard" 2>/dev/null; then
  • fail "payload prune deleted a payload path that carries tracked files"
  • fi
  • assert_present "$guard/data/notes.md" "refused payload prune removed a tracked file"
  • pass "pooled retirement returns a clean slot, the next seed leases it, and tracked payload is never pruned"
    +}

test_fm_home_parameterization() {
local brief home_one home_two out
home_one="$TMP_ROOT/home one"
@@ -3328,6 +3395,7 @@ EOF

test_durable_home_git_lock_lifecycle
test_durable_home_git_lock_rollback
+test_durable_home_pool_slot_reuse

test_fm_home_parameterization
test_lock_status_is_per_home
diff --git a/tests/secondmate-helpers.sh b/tests/secondmate-helpers.sh
index 7fc7e1c5..380c6c1d 100644
--- a/tests/secondmate-helpers.sh
+++ b/tests/secondmate-helpers.sh
@@ -13,8 +13,9 @@

A fake tmux (window ops are logged to FM_FAKE_TMUX_LOG, list-windows returns

FM_FAKE_TMUX_WINDOW, capture-pane echoes FM_FAKE_TMUX_CAPTURE) plus a fake

treehouse (durable lease of FM_FAKE_TREEHOUSE_HOME, recording the lease holder

-# to FM_FAKE_TREEHOUSE_LEASE_FILE; return removes the target and lease unless
-# FM_FAKE_TREEHOUSE_RETURN_FAIL is set). Echoes the fakebin dir.
+# to FM_FAKE_TREEHOUSE_LEASE_FILE; return removes the target and leases unless
+# FM_FAKE_TREEHOUSE_RETURN_FAIL is set, and keeps the target as a real pool does
+# when FM_FAKE_TREEHOUSE_KEEP_HOME is set). Echoes the fakebin dir.
make_fake_tmux() {
local dir=$1 fakebin capture
fakebin=$(fm_fakebin "$dir")
@@ -162,6 +163,7 @@ case "${1:-}" in
done
[ -z "${FM_FAKE_TREEHOUSE_RETURN_FAIL:-}" ] || exit 17
[ -n "${FM_FAKE_TREEHOUSE_LEASE_FILE:-}" ] && rm -f "$FM_FAKE_TREEHOUSE_LEASE_FILE"

  • [ -n "${FM_FAKE_TREEHOUSE_KEEP_HOME:-}" ] && exit 0
    [ -n "$target" ] && rm -rf -- "$target"
    exit 0
    ;;
    --
    2.51.2

@kesslerio
kesslerio force-pushed the fix/6921-durable-home-worktree-lock branch from d495e61 to a156dba Compare November 10, 2026 03:04
@kesslerio kesslerio changed the title fix(teardown): protect durable homes with Git worktree locks fix(bin): protect durable linked-worktree secondmate homes with owned Git locks Nov 10, 2026
@greptile-apps

greptile-apps Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The changes affect secondmate home seeding and retirement, including pooled worktree reuse.

Do not merge yet: returning a home still moves the lock that prevents concurrent task creation.

Reviews (9) · Last reviewed commit: "no-mistakes(document): Correct manual po..." · Reviewed by Greptile

Comment thread bin/fm-home-payload-lib.sh Resolved
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thanks @kesslerio for the update, and for the end-to-end trace on Oct 31. It is exactly the product path I asked for (fm-home-seed.sh → git worktree remove refused → fm-teardown.sh retirement), and the payload-cleanup defect it surfaced is a good catch. I'm sorry that reply waited this long.

What I read: head a156dba9 against main 913bb7a7. It is 9 ahead and 10 behind, mergeable, with no conflict. I read the full diff. No .github, CI config, network or credential changes, and I have no security concerns. The no-mistakes attestation binds a156dba9 with no skipped steps, and "PR must be raised via no-mistakes" passed. The new live table (5 of 5 scenarios, plus the base-commit reproduction) covers what I asked for.

Contract class (mine): new-default, same as before. On main, seeding never Git-locks a linked-worktree home. With this tip every linked-worktree seed is locked by default, teardown refuses some homes it used to remove, and returned pool slots get their payload cleared. No flag gates any of it. Once the items below are done, this goes to Kun to decide, not auto-merge.

VISION: every rule aligns except "A restart is a non-event", which is blocked by the first item below.

Waiting on you (author), three things:

  1. Greptile P1, still open: "Interrupted retirement cannot retry" (thread). This is the same issue your own no-mistakes review step left open as an error at bin/fm-home-payload-lib.sh:53. fm_home_payload_return moves the payload and identity markers into state/.home-return.* and releases the lock before treehouse return commits. If teardown is interrupted there (for example SIGINT/SIGTERM during the index.lock retry sleep), the home is left stripped, and the next teardown refuses it because .fm-secondmate-home is missing. Please make that handoff recoverable (cleanup on interruption, or a recovery record that a retry picks up), or reply on the thread explaining why it can't happen.
  2. Test coverage guard is red because of this PR (job): 45 of 297 portable serial scripts have no measured duration hint (max 15%). The new tests/fm-home-payload-return.test.sh has no hint, and that pushes the count over the limit (main passes this guard). Please add a provisional serial hint for it in docs/fm-test-portable-shards.md, following the existing "provisional local measurement" entries.
  3. Closes line: the body no longer links Desktop workspace tool can trash a Firstmate home listed as a worktree while the mate is idle #6921. Please add Closes #6921 back if this still fully fixes it.

Please re-raise through git push no-mistakes so the attestation binds the new head. The 10-commit lag behind main doesn't need any work from you. The unlabelled Full suite result isn't yours to chase either.

@kesslerio kesslerio changed the title fix(bin): protect durable linked-worktree secondmate homes with owned Git locks fix(bin): protect durable secondmate homes and keep returned pool slots reusable Nov 11, 2026
Comment thread bin/fm-home-payload-lib.sh Resolved
@kesslerio
kesslerio force-pushed the fix/6921-durable-home-worktree-lock branch from 8ab74cb to d4d4edd Compare November 11, 2026 01:26
@kesslerio kesslerio changed the title fix(bin): protect durable secondmate homes and keep returned pool slots reusable fix(bin): protect durable secondmate homes and clear payload from returned pool slots Nov 11, 2026
@kesslerio
kesslerio force-pushed the fix/6921-durable-home-worktree-lock branch from d4d4edd to e35e217 Compare November 11, 2026 02:25
@kesslerio kesslerio changed the title fix(bin): protect durable secondmate homes and clear payload from returned pool slots fix(bin): guard durable secondmate homes with owned locks and clean slot returns Nov 11, 2026
Comment thread docs/t3code-backend.md Resolved
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thanks @kesslerio, this round covers a lot. Both Greptile P1s are fixed and resolved: Interrupted retirement cannot retry and Failed return discards home data. A return now stages the payload atomically on the parent's filesystem, and it keeps a recovery record until the retirement records are finalized. Recovery restores the home unless the pool shows the slot was really given away. The tests/fm-home-payload-return.test.sh duration hint is in, and the Test coverage guard passes. Closes #6921 is back in the body. The attestation binds e35e2173 with no skipped steps and live 9/9. Greptile gives 5/5 on this head, and it merges cleanly with main 1d43f9cb.

Waiting on you for one thing: the new Greptile P2 Manual cleanup keeps old protection on docs/t3code-backend.md:257. I checked it against bin/fm-home-worktree-lock-lib.sh on this head, and it looks right to me. The receipt lives in the worktree's admin directory (.../worktrees/<name>/firstmate-home-lock), outside the checkout. So the manual step clears the payload, but it leaves the owned Git lock and the receipt in place. The next seed for a different mate then fails fm_home_worktree_lock_check. Please add the release step, or point to the guarded helper that does it, or reply on the thread if you see it differently. Then resolve the thread and re-raise once with git push no-mistakes.

The red Full suite row is only the maintainer full-ci label gate. Contract-class: new-default, unchanged: linked-worktree homes are locked by default, and returned slots get their payload cleared. Once the thread is settled we add full-ci. If the full suite then passes, the PR goes to Kun for a merge-or-leave call.

@kesslerio kesslerio changed the title fix(bin): guard durable secondmate homes with owned locks and clean slot returns fix(bin): lock durable home worktrees and return clean pool slots Nov 11, 2026
@kesslerio kesslerio changed the title fix(bin): lock durable home worktrees and return clean pool slots fix(bin): protect durable secondmate homes and return reusable pool slots Nov 11, 2026
@kunchenguid kunchenguid added the full-ci Maintainer go-ahead: run the full CI suite on this outside pull request label Nov 11, 2026
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thanks @kesslerio. c62d7f5d settles the last open item. The Manual cleanup keeps old protection step in docs/t3code-backend.md now releases the owned Git lock with git worktree unlock and removes the firstmate-home-lock receipt before the return. The thread is resolved. The narrowed interrupt handling also reads right to me. A handled INT, TERM or HUP during staging restores the payload, identity, ownership and protection for the retry. The residual, a kill outright or a signal during the slot release itself, is documented in the library header and in docs/configuration.md. All three Greptile threads are resolved, and Greptile gives 5/5 on this head. The no-mistakes attestation binds c62d7f5d with no skipped steps and live 5/5. The coverage guard and repo invariants pass, Closes #6921 is in the body, and it is 0 behind main 1d43f9cb with no conflict.

I've added the full-ci label, so the full suite is queued on this head. Contract-class: new-default, unchanged. Every linked-worktree seed is Git-locked by default, teardown refuses some homes it used to remove, and returned pool slots get their payload cleared. So once Full is green, this goes to Kun as a merge-or-leave decision. That step waits on Kun, not on you.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thanks @kesslerio. The labelled full suite ran on c62d7f5d (run 42983594666) and two lanes failed. Both failures come from this PR's changes, not from flakes. The same tests pass on main and on other PRs' runs.

Waiting on you (author), two fixes:

  1. Lint 1 (job): fm-lint reports a finding in the new tests/fm-home-payload-return.test.sh:
    In tests/fm-home-payload-return.test.sh line 3:
    . "$(dirname "${BASH_SOURCE[0]}")/lib.sh"
      ^-- SC1091 (info): Not following: ./lib.sh: openBinaryFile: does not exist
    
    The other test files put # shellcheck source=tests/lib.sh disable=SC1091 above that line.
  2. Behavior portable parallel 1 (job): tests/fm-backend-t3code.test.sh fails with
    not ok - the refusal names the unproven process scan (missing: 'cannot determine leaked processes')
    bin/fm-home-worktree-lock-lib.sh: line 18: cd: /tmp/fm-backend-t3code-tests.*/teardown-secondmate-claude/home: No such file or directory
    
    That case tears down a T3 secondmate when lsof exits 1. With this branch, fm_home_worktree_lock_context runs cd into the lock parent (FM_HOME, which doesn't exist in that fixture) and fails there. So teardown never reaches the "cannot determine leaked processes" refusal. Please either keep the process-scan refusal ahead of the lock check, or handle a missing parent in the lock lib with a clear refusal, then update the test if the order changes on purpose.

Then re-raise with git push no-mistakes. The full-ci label stays, so the suite reruns on your next head. Contract class: new-default (unchanged). Once the suite is green, this goes to Kun for a merge-or-leave decision. No merge conflicts.

@kesslerio
kesslerio force-pushed the fix/6921-durable-home-worktree-lock branch from c62d7f5 to 14c84d5 Compare November 12, 2026 00:25
…dds tests/fm-home-payload-return.test.sh, which lands in the derived portable-serial lane, but no duration hint was added to `portable_serial_weight_hints`. That took the unhinted share from 43/292 (14.7%, passing) to 45/297 (15.2%, failing) in CI. Fix: added `tests/fm-home-payload-return.test.sh 1300` to the hint table in bin/fm-test-run.sh (slowest of five local `bin/fm-test-run.sh` samples: 331-1255 ms, rounded up) and documented the provisional measurement provenance in docs/fm-test-portable-shards.md, matching the doc-owned refresh convention for every other provisional hint. This is the single shared boundary: hints are the one place the guard reads, so the new member is now measured like every sibling serial member. Verified `bin/fm-test-run.sh --check-coverage` now prints `FM_TEST_COVERAGE ok ... serial_unhinted=43 serial_max_ms=1185722 serial_budget_ms=1200000` (exit 0), bin/fm-lint.sh exits 0, and tests/fm-home-payload-return.test.sh, tests/fm-gotmp.test.sh, tests/fm-secondmate-safety.test.sh, tests/fm-documentation-audiences.test.sh, and the coverage-guard cases in tests/fm-test-run.test.sh pass. I deliberately did not raise the stale tests/fm-secondmate-safety.test.sh hint (local 147674 ms vs hint 69424 ms): local timing is not CI evidence and that provisional bump would push serial_max_ms past the 1200000 ms budget, breaking the same guard; per docs/fm-test-portable-shards.md it belongs to a CI timing-artifact refresh. ci-1 (Full suite) is not code-caused: full-suite gate job exits at `if [ "$FM_CI_FULL" != true ]` because this is an outside PR without the maintainer-added full-ci label; its other lanes are skipped, and `FM_CI_LANES_FAILED` was true only because test-coverage (a need) failed. No code change is warranted for that label/attestation gate. Note: tests/fm-session-lock-ancestry.test.sh fails on this sandbox only (`the pty-host was not reparented to init`, ps shows orphans reparent to a subreaper pid 1121, not 1), and that failure also trips the unrelated `--jobs on a proven family must be admitted` case in fm-test-run.test.sh; both files and the library they exercise are untouched by this PR, so this is a host-environment artifact, not a regression
…ry) was code-caused by the test added in this PR, and the prior rounds left that test broken plus an orphaned runner. Root cause found and fixed. Invariant: a home whose slot return has begun must never be left stripped of its payload/identity with its records stranded in staging — either the home is whole again with its owned lock, or a staging record exists that the next entry recovers (and a return that already committed its slot discards the staging instead of restoring payload into a leasable slot). The in-progress implementation already held that invariant at every move/failure/exit path (record written before any move, `fm_home_payload_abort` on every rc!=0, INT/TERM/HUP handler, `fm_home_payload_recover` at both entries: `fm_home_payload_return` and teardown's `validate_firstmate_home_for_removal`, which is the single shared boundary for direct, nested and pooled retirement). No logic change was needed there; I preserved committed=1, trap-restore and recover-before-decide. What was actually broken: `fm_home_payload_return` is a subshell-bodied function, so `f() ( ... ) &` forks twice — the test signalled `$!` (the outer async shell, no traps), which died with default TERM while the real mover kept looping forever (proven: that orphan, reparented to pid 1121, is exactly the ~55-minute runner the last round saw). The home was therefore never restored and the test failed. I killed the leftover orphans from prior rounds and my own repro, then fixed the test to publish `$BASHPID` from the callback and signal the process that installs the restore trap, which is what production does (a terminal/process-group signal reaches the mover). I also bounded every wait, contained the SIGKILL job notice, and extracted `assert_home_restored`/`kill_return` so the recovery assertions are shared. I strengthened the test because the old shape could not tell "recover restores" from "recover just discards": it now kills a return, asserts the home is stripped and staged, calls `fm_home_payload_recover` directly and asserts payload/identity/parent binding/protection/ownership/lease are back and staging is empty, then kills again and proves a retrying return recovers before deciding and leaves the slot clean. Oracles are the PR's stated slot-reusable contract and the library's documented record-before-move contract; a "discard the staging" implementation fails it (verified). It also fails on the base library (verified). Verification (all local, bounded): tests/fm-home-payload-return.test.sh passes 3/3 in ~4s with no leaked processes; tests/fm-secondmate-safety.test.sh rc=0; tests/fm-gotmp.test.sh rc=0; tests/fm-documentation-audiences.test.sh rc=0; bin/fm-lint.sh rc=0; bin/fm-test-run.sh --check-coverage ok (serial_unhinted=43, serial_max_ms=1185722/1200000). tests/fm-teardown.test.sh passed all 14 of its early secondmate/retirement tests before hanging in the unrelated status-archive-publication retry loop (spawns `sleep 0.1` polls); that test and its code path are untouched by this PR, and the hang reproduces as an environment/loop artifact, so I killed it rather than chase it. No changes were made outside the four files in this worktree
…ry queries omitempty verification_blocked? Need actual valid no weird
…s pool reconciliation. Invariant: a pool snapshot only proves that THIS attempt returned the slot when it shows a lease transition - the lease this home held is gone (released, reassigned, or another holder acquired the slot). A slot that was already unleased when the return started (an explicit-path seed that took an existing pool checkout without `treehouse get --lease`) is unleased whether the return succeeded or failed, so it is not evidence, and the home must keep its payload for the retry. That invariant has one owner: fm_home_payload_pool_state's `check` branch, which fm_home_payload_reconcile alone consumes, so every consumer (fm_home_payload_return's own failure recovery, teardown's recovery-before-decide at :2907/:2915 and the pooled/nested/direct retirements, fm-home-seed.sh's rollback and reseed paths, and fm_home_payload_finalize) now holds it without per-caller changes. Change: an unchanged saved entry now always reports 'slot still owed' (restore) instead of 'committed' when it was never leased; a snapshot that was already unleased only reports committed when another holder took the slot; an unchanged held lease and a released/reassigned held lease keep their previous meanings, and a held lease with partial ownership drift still reads as an unreconcilable error rather than a guess. committed=1, the trap-restore, and recover-before-decide invariants are untouched. Also updated the reconcile doc comment and the matching docs/configuration.md contract sentence. Test: added a case to tests/fm-home-payload-return.test.sh that drives an unleased pool entry through a failed return (asserting the home's payload, identity, parent binding, owned lock and receipt are back and staging is empty) and then a successful return (payload/identity/protection cleared, RETIRED=1, staging finalized). Oracle: the documented contract that a failed return puts the whole home back and only a successful return clears the payload; it rejects the pre-fix 'unchanged unleased = committed' behavior - verified by stashing only the library, where the new test fails with 'failed return of an unleased slot reported success', and passes with the fix. Verification (all bounded): tests/fm-home-payload-return.test.sh rc=0 (~36s, no leaked processes); tests/fm-secondmate-safety.test.sh rc=0 (84 ok, 4m14s); tests/fm-documentation-audiences.test.sh rc=0; bin/fm-lint.sh rc=0 (ShellCheck 0.11.0 + actionlint). tests/fm-teardown-endpoint-safety.test.sh refuses to run in this gate worktree because it is not on `main` (environmental guard, not a code failure). No changes outside the three files in this worktree
The P1 fix for interrupted durable-home retirement grew a recovery-record
protocol - staged return records, committed flags, incarnation identity,
recovery-before-decide at every entry boundary, and pool-state
reconciliation - and each review round surfaced deeper races inside that
machinery (recovery vs descendant locks, stale committed records vs
replacement seeds, unleased-slot evidence). The maintainer's ask was
cleanup on interruption; those races exist only because the recovery
design exists.

This backs the machinery out to the narrow invariant: if the payload
move is interrupted before the slot is released, restore the home's
payload, identity, ownership and protection so a retry teardown is not
refused. INT/TERM/HUP traps cover staging through the owned-lock
release and are disarmed before the slot-release command runs, since a
signal during "$@" can arrive after the slot is gone and restoring into
it would re-mark a leasable checkout. A return killed outright can
still strand staging; that residual is documented as out of scope.

bin/fm-teardown.sh, bin/fm-home-seed.sh, docs/configuration.md and the
test return to their pre-recovery shape; the same-filesystem staging
check stays because atomic moves are what make the restore reliable.
The pre-V2 transport migration flow clears a retired home's payload and
force-returns its pool slot by hand, but a durable home's Git worktree
lock and firstmate-home-lock receipt live in the worktree's
administrative gitdir outside the checkout, so both survive the payload
clear and the in-place treehouse return. The next seed in that slot then
refuses it as foreign-locked or still marked for the retired mate.
Document the owned-lock release and receipt removal the guarded return
already performs.
The labelled full suite exposed two regressions. The lint lane flagged
tests/fm-home-payload-return.test.sh for a missing shellcheck source
directive on its lib.sh include. And fm_home_worktree_lock_context
resolved the lock parent before checking whether the home is a linked
worktree at all, so a caller whose parent directory does not exist
failed inside the lock check before teardown reached its earlier
leaked-process refusal; the parent is consumed only by the ownership
receipt, which exists only for linked worktrees, so resolve it after
the .git check and reset the global for non-worktree homes. Two t3code
fixtures also never created their FM_HOME parent or its state/ (which
payload staging needs), so their worktree homes could not pass the
check; create it like every sibling fixture.
@kesslerio
kesslerio force-pushed the fix/6921-durable-home-worktree-lock branch from 14c84d5 to 5fe546d Compare November 14, 2026 22:16
@kesslerio kesslerio changed the title fix(bin): protect durable secondmate homes and hand back clean pool slots fix(bin): protect and cleanly return durable secondmate pool homes Nov 14, 2026
Comment thread bin/fm-home-payload-lib.sh Resolved
Comment thread bin/fm-home-payload-lib.sh Resolved
…g test, and it was code-fixable in the test itself: tests/fm-live-lab.test.sh, subtest "up re-registers primary trust after a concurrent Claude write" (assertion at line 737, `not ok - primary launched trusted after the rival write (expected 'present', got '')` was the only non-zero exit in shard 11). Invariant violated: the test's stand-in rival writer must drop the home's trust entry only *after* that entry becomes visible, and drop it exactly once, so its store write can never land inside `up`'s read-modify-write or its presence re-check. The rival's wait used `process.exit(j.projects?.[k] ? 1 : 0)` inside `until`, i.e. it stopped on *absence* and fired its deletion on a fixed ~0.55 s timer after test start. Where that timer landed depended on machine speed: too early and the drop happened before registration (so the assertion proved nothing about re-registration); inside `up`'s register/verify cycle (fm-live-lab.sh:592-597) and the retry budget was spent, `up` died with "the lab home's Claude trust keeps disappearing", the primary never launched, and the marker file was absent - exactly the CI `got ''`. I reproduced that signature with the old timer-based drop at several delay offsets (empty `claude-launch-trust` plus the "keeps disappearing" death), and 'absent' at others. The invariant has one owner here: the rival's single wait condition, whose only consumers are `up`'s registration retry loop and the stand-in primary's startup check. Fix is the same small correction at that one boundary: exit 0 when the entry is present so `until` stops on the registration it is meant to race, plus a comment naming the ordering requirement. Nothing else in the file schedules a store write, so no sibling site is left reachable. Verification (all local, bounded): isolated repro of the same subtest with the corrected wait passed 3/3 runs with `launch-trust=present`; tests/fm-live-lab.test.sh passed 2/2 full runs (~73 s each, no leaked processes); bin/fm-lint.sh rc=0 (ShellCheck 0.11.0 + actionlint); bin/fm-test-run.sh --check-coverage ok (serial_max_ms=1195835 of 1200000 budget, membership unchanged). Oracle check: a copy of bin/fm-live-lab.sh reduced to a single registration attempt (`retry<1`) makes the corrected subtest fail (primary never launches trusted), so the test still requires the re-registration path rather than passing vacuously after a pre-registration drop. ci-2 (Full suite) needs no code change: it is the aggregation gate and its log shows `FM_CI_FULL=true` with `FM_CI_LANES_FAILED=true`, failing solely because Behavior portable serial 11 failed (`##[error]A full-suite job failed or was cancelled`). With serial 11 green it passes; there is no independent defect to fix. Change is limited to tests/fm-live-lab.test.sh (+5/-1); no production code, hints, docs, or pipeline state touched
…h:104). Invariant violated: a durable-home payload return must never fail just because the returning parent keeps its state elsewhere and never created its own state/ directory; staging only needs a same-filesystem place to move payload, not a directory the caller already uses. Every pooled, direct, nested, and seed-rollback return funnels through fm_home_payload_return, and its single staging creation was `staging=$(mktemp -d "$parent/state/.home-return.XXXXXX")`, which fails with ENOENT when FM_STATE_OVERRIDE points outside the parent home (e.g. remote secondmate retire passes FM_HOME=FM_ROOT with FM_STATE_OVERRIDE=$TARGET_HOME/state/parent-route), so remove_firstmate_home reported failure and left the slot leased, and seed rollback left its lease held. Fix at that one shared boundary: create the staging parent explicitly (`mkdir -p "$parent/state" || return 1`) immediately before mktemp; nothing else in the return or lock library creates or requires the staging directory, so both production callers (fm-home-seed.sh:628 seed rollback, fm-teardown.sh:3021 pooled/nested/direct retirement) now hold the invariant without per-caller changes. I deliberately did not adopt the alternative 'pass the caller's chosen state directory': in the supported remote-retire setup the effective state dir is inside the very home being retired ($TARGET_HOME/state/parent-route), so staging there would make the later `mv $home/state -> $staging/state` move a directory into its own descendant. Ordinary path re-traced: when $parent/state already exists, `mkdir -p` is a no-op and the move/release/forget/abort sequence is unchanged; when it is absent it is now created, the same-device check still refuses a cross-filesystem parent before any payload moves, and a failure still aborts/restores exactly as before. Test: tests/fm-home-payload-return.test.sh no longer pre-creates "$parent/state"; it creates only the overridden state dir and exports FM_STATE_OVERRIDE, reproducing the reported caller setup through the public return interface (it asserts a return observes a clean slot, preserves ownership on refusal/failure, restores after a handled interrupt, and clears the payload on success). RED before the fix: `mktemp: failed to create directory ... parent/state/.home-return.XXXXXX: No such file or directory` then `not ok - return saw an uncleared slot` (rc=1). GREEN after: rc=0, 3/3 consecutive runs. Verification run locally (all bounded): tests/fm-home-payload-return.test.sh rc=0 (3/3), tests/fm-gotmp.test.sh rc=0, tests/fm-secondmate-safety.test.sh rc=0 (full file, 1m1s), bin/fm-lint.sh rc=0 (ShellCheck 0.11.0 + actionlint, 3 workflows valid), bin/fm-test-run.sh --check-coverage ok (serial_max_ms=1195835/1200000, membership unchanged, test ~1s so no hint change), bash -n and git diff --check clean. No doc change needed: docs/configuration.md and the operational-home-layout skill already state that staging is created under the returning parent's state/; the fix makes that true even when the parent does not otherwise use it. Change limited to bin/fm-home-payload-lib.sh (+4) and tests/fm-home-payload-return.test.sh (+7/-1)
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thanks @kesslerio for rebasing onto main 427056c4. I compared the new head 5fe546d9 with 14c84d52. The code is the same, and the only new change is the reworded .home-return.* line in the operational-home-layout skill. The attestation binds this head with no skipped steps, live validation is 5/5, the coverage guard and repo invariants pass, and Closes #6921 holds.

This is back with you (author), not with Kun. Greptile re-reviewed 5fe546d9, dropped to 3/5, and opened two P1 threads on bin/fm-home-payload-lib.sh:

  1. Retirement loses its lock: moving state/ into staging also moves the held .task-set.lock. A concurrent fm-spawn.sh could then recreate state/ and take a fresh lock while teardown still holds the moved one, and a failed return would refuse to restore state/.
  2. Separate state blocks retirement: mktemp -d "$parent/state/.home-return.XXXXXX" fails when FM_STATE_OVERRIDE points outside the parent home and $parent/state doesn't exist. Pooled retirement and seed rollback would then fail and leave the slot leased.

Please fix both, or reply on each thread explaining why it can't happen, then re-raise once with git push no-mistakes. The full-ci label stays on.

The one failed lane in the labelled run on this head, Behavior portable serial 11, is the tests/fm-live-lab.test.sh Claude trust-store race. It also fails on unrelated PRs, and this PR doesn't touch it, so it isn't yours to fix.

Contract class: new-default, unchanged. Once the P1s are settled and the full suite is green, this goes back to Kun for a merge-or-leave decision.

@kesslerio kesslerio changed the title fix(bin): protect and cleanly return durable secondmate pool homes fix(bin): protect durable secondmate homes and return clean pool slots Nov 14, 2026
A process still running in the home recreates an empty state/ - sourcing
fm-wake-lib mkdir -p's the state dir - while the staged move or the slot
release is in flight. The restore then refused on "it exists again",
stranding the markers and remaining payload in staging so a retry teardown
refused the home. rmdir clears only an empty directory, so that bare
recreation cannot refuse the restore; a path carrying real new content
still hits the refusal.
@kesslerio kesslerio changed the title fix(bin): protect durable secondmate homes and return clean pool slots fix(bin): protect durable secondmate homes with owned Git locks and payload cleanup Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

full-ci Maintainer go-ahead: run the full CI suite on this outside pull request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants