Skip to content

fix(bin): require explicit per-home authority to retire secondmates in teardown - #4219

Open
RooseveltAdvisors wants to merge 15 commits into
kunchenguid:mainfrom
RooseveltAdvisors:fix/fm-secondmate-retire-validation-r2
Open

RooseveltAdvisors wants to merge 15 commits into
kunchenguid:mainfrom
RooseveltAdvisors:fix/fm-secondmate-retire-validation-r2

Conversation

@RooseveltAdvisors

@RooseveltAdvisors RooseveltAdvisors commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Intent

Captain, via main: in the same pass as the 3682 rebase, check the other parked upstream PRs for drift from the 12-commit advance and rebase any that went conflicting. Force-push to OUR fork branch is authorized; CI re-greens; then the babysit continues.

Context to read that: firstmate ran the drift sweep. 3552, 3543 and 3417 are clean. This PR, 3657, went CONFLICTING - and it is the messier of the two conflicting ones.

What Changed

  • bin/fm-teardown.sh now refuses to retire a kind=secondmate task and changes nothing unless it gets --retire-secondmate <id> naming that exact home. --force does not stand in for the flag. Teardown also refuses when the flag is passed for a non-secondmate task or names a different id. A request with more than one target is rejected before anything is locked, and the error names any secondmate homes in the list. bin/fm-remote-secondmate-control.sh now passes the flag on its own retire calls.
  • bin/fm-fleet-view.sh gains a --cleanup-candidates mode. It lists each live task with its kind and whether it is persistent or disposable. It prints a runnable fm-teardown.sh command only for disposable tasks. Secondmate homes get a pointer to the retirement contract instead.
  • The secondmate-provisioning skill, AGENTS.md, CONTRIBUTING.md and the architecture, remote-secondmates and scripts docs now describe the new contract. The teardown, safety, fleet-view and lifecycle tests are extended to cover it, and the CI count of snapshot/fleet-view tests goes from 18 to 19. The default per-root lint memory cap in bin/fm-lint.sh goes from 12 GiB to 14 GiB.

🤖 Generated with Claude Code

Risk Assessment

✅ Low: The merge with main left main's 12-commit content intact and touched no file this PR owns. The new teardown logic only adds refusals, and they all fire before anything destructive runs: a secondmate home now needs per-target authority, and more than one target is refused. Every in-repo caller that tears down a secondmate (fm-remote-secondmate-control.sh and the affected tests) passes the flag naming that exact home. The fleet-view cleanup report is read-only, and the lint memory cap goes up from 12 GiB to 14 GiB, documented with measured numbers.

Testing

I ran the real teardown and fleet-view scripts against a throwaway lab home made with bin/fm-lab-home.sh, seeded with one secondmate record and one ship record, then deleted the lab. The new report labels each task's kind and gives no runnable command for the persistent home. A secondmate teardown with no flag, with only --force, with the flag naming another task, or with the flag missing its value is refused and nothing changes. A two-target call is refused and names the secondmate. Arguments after -- are read as targets, not options, so -- --force is refused as a two-target call. Putting the flag on a ship task is refused. The correctly authorized retirement removed the home, the record and its report row. The plain ship teardown got past the new check and then stopped because my fixture worktree isn't managed by treehouse, so its full cleanup is untested live and rests on the suite tests. Of five targeted suites, fleet-snapshot-view and secondmate-lifecycle-e2e finished with rc=0. teardown, secondmate-safety and teardown-endpoint-safety were still running at my last check, with no failing case so far. This is a shell tool, so there is no visual surface; the CLI transcripts are the evidence.

  • Live validation: ✅ go - 8 of 9 scenarios driven live against the product
Scenario Result Live Evidence
Operator runs fm-fleet-view.sh --cleanup-candidates and sees each task's kind: the ship task with its teardown command, the secondmate marked persistent with no runnable command ✅ pass live live-teardown-refusals.txt (S1); live-teardown-authorized-retire.txt (S1b, the retired home's row is gone)
Tearing down a secondmate with no --retire-secondmate is refused and leaves the record and home in place ✅ pass live live-teardown-refusals.txt S2: REFUSED, rc=1, state unchanged
Adversarial: --force alone does not retire a secondmate ✅ pass live live-teardown-refusals.txt S3: REFUSED, rc=1, home present
Adversarial: --retire-secondmate naming another task, or given no value, is refused ✅ pass live live-teardown-refusals.txt S4 and S4b: rc=1 and rc=2, nothing changed
Adversarial: a two-target call that includes a secondmate is refused before anything changes, and the secondmate is named ✅ pass live live-teardown-refusals.txt S5: rc=2, names mate-a, both records intact
Adversarial: after --, a later target spelled like an option (--force) is treated as a second target and refused, not read as a flag ✅ pass live live-teardown-refusals.txt S6: rc=2 '2 targets were given: crew-b --force', worktree intact
Putting --retire-secondmate on an ordinary ship task is refused as a mis-selected target ✅ pass live live-teardown-refusals.txt S7: REFUSED, rc=1
A correctly authorized retirement (mate-a --retire-secondmate mate-a) removes the home and its record ✅ pass live live-teardown-authorized-retire.txt S9: rc=0, 'teardown mate-a complete', record gone, home GONE
An ordinary ship teardown needs no retirement flag and completes cleanup ⏸️ untested no The prior payload did not establish a live result for full cleanup: the live run passed the new check but stopped at treehouse return because the lab worktree isn't managed by treehouse. Creating a…
Evidence: Live refusal scenarios transcript (S1-S7)

Source: Live refusal scenarios transcript (S1-S7)

## S1 cleanup-candidates labels kinds

$ bin/fm-fleet-view.sh --cleanup-candidates
# Cleanup Candidates

Home: /tmp/fm-lab.2HS8N0

| ID | Kind | Persistence | Teardown |
| --- | --- | --- | --- |
| crew-b | ship | disposable | bin/fm-teardown.sh crew-b |
| mate-a | secondmate | persistent | retire only by an explicit decision naming this home - see .agents/skills/secondmate-provisioning |

A persistent home is retired only by a decision naming that exact home; an idle queue is healthy, not finished.
This report prints no runnable retirement command, so retiring a standing home has to be typed deliberately.
Teardown takes one target per invocation.
[rc=0]
## S2 secondmate without authority

$ bin/fm-teardown.sh mate-a
fm-gate-refuse: gate agent lifecycle permitted only against lab home /tmp/fm-lab.2HS8N0
REFUSED: task mate-a is a persistent secondmate home, not a finished worker; nothing was changed.
An idle queue is a healthy secondmate's normal state, never evidence it is done.
Retiring it takes authority naming that exact home: bin/fm-teardown.sh mate-a --retire-secondmate mate-a
List candidates with their kinds using bin/fm-fleet-view.sh --cleanup-candidates rather than inferring persistence from a worktree path.
[rc=1]
  state: crew-b.meta mate-a.meta   mate-home: present  crew-wt: present
## S3 --force without authority

$ bin/fm-teardown.sh mate-a --force
fm-gate-refuse: gate agent lifecycle permitted only against lab home /tmp/fm-lab.2HS8N0
REFUSED: task mate-a is a persistent secondmate home, not a finished worker; nothing was changed.
An idle queue is a healthy secondmate's normal state, never evidence it is done.
Retiring it takes authority naming that exact home: bin/fm-teardown.sh mate-a --retire-secondmate mate-a
List candidates with their kinds using bin/fm-fleet-view.sh --cleanup-candidates rather than inferring persistence from a worktree path.
[rc=1]
  state: crew-b.meta mate-a.meta   mate-home: present  crew-wt: present
## S4 authority naming a different home

$ bin/fm-teardown.sh mate-a --retire-secondmate crew-b
fm-gate-refuse: gate agent lifecycle permitted only against lab home /tmp/fm-lab.2HS8N0
REFUSED: --retire-secondmate names crew-b, but this teardown targets mate-a; nothing was changed.
Authority for retiring a persistent home must name that exact home.
[rc=1]
  state: crew-b.meta mate-a.meta   mate-home: present  crew-wt: present
## S4b authority with no value

$ bin/fm-teardown.sh mate-a --retire-secondmate
error: --retire-secondmate needs the exact task id it authorizes
[rc=2]
  state: crew-b.meta mate-a.meta   mate-home: present  crew-wt: present
## S5 multi-target selection list

$ bin/fm-teardown.sh crew-b mate-a
error: teardown acts on exactly one task, but 2 targets were given: crew-b mate-a
error: 1 of those targets are persistent secondmate homes, not finished workers: mate-a
Retiring a secondmate is a per-target decision. Nothing was changed.
List candidates with their kinds using bin/fm-fleet-view.sh --cleanup-candidates, then act on one target per invocation.
[rc=2]
  state: crew-b.meta mate-a.meta   mate-home: present  crew-wt: present
## S6 end-of-options: later target spelled as an option

$ bin/fm-teardown.sh crew-b -- --force
error: teardown acts on exactly one task, but 2 targets were given: crew-b --force
List candidates with their kinds using bin/fm-fleet-view.sh --cleanup-candidates, then act on one target per invocation.
[rc=2]
  state: crew-b.meta mate-a.meta   mate-home: present  crew-wt: present
## S7 authority on an ordinary ship task

$ bin/fm-teardown.sh crew-b --retire-secondmate crew-b
fm-gate-refuse: gate agent lifecycle permitted only against lab home /tmp/fm-lab.2HS8N0
REFUSED: --retire-secondmate was given for task crew-b, which is a ship task and not a secondmate home; nothing was changed.
That mismatch means the target was selected wrong; re-check it with bin/fm-fleet-view.sh --cleanup-candidates.
[rc=1]
  state: crew-b.meta mate-a.meta   mate-home: present  crew-wt: present
Evidence: Ordinary ship teardown (stopped at treehouse return) and first retirement attempt (stopped by the home-location check)

Source: Ordinary ship teardown (stopped at treehouse return) and first retirement attempt (stopped by the home-location check)

## S8 ordinary ship teardown needs no authority

$ bin/fm-teardown.sh crew-b
fm-gate-refuse: gate agent lifecycle permitted only against lab home /tmp/fm-lab.2HS8N0
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
●  WATCHER DOWN - SUPERVISION IS OFF
●  2 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.
●  watcher supervision needs Stop-owned automatic recovery; inspect the hook registration and startup status before ending the turn.
●━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
A new version of treehouse is available: v1.8.1-0.20260905115643-6e0ac79a026b → v3.1.1
Run "treehouse update" to update

worktree /tmp/fm-lab.2HS8N0/wt-crew-b is not managed by treehouse
error: treehouse return failed for worktree /tmp/fm-lab.2HS8N0/wt-crew-b; teardown aborted
[rc=1]
  state: crew-b.meta mate-a.meta   mate-home: present  crew-wt: present
## S9 authorized secondmate retirement

$ bin/fm-teardown.sh mate-a --retire-secondmate mate-a
fm-gate-refuse: gate agent lifecycle permitted only against lab home /tmp/fm-lab.2HS8N0
WARNING: watcher still down (same stale episode; last beat: never, grace 300s) - full banner already printed this episode.
REFUSED: unsafe secondmate home removal target /tmp/fm-lab.2HS8N0/mates/mate-a is inside the active firstmate home
[rc=1]
  state: crew-b.meta mate-a.meta   mate-home: present  crew-wt: present
## S1b cleanup-candidates after cleanup

$ bin/fm-fleet-view.sh --cleanup-candidates
# Cleanup Candidates

Home: /tmp/fm-lab.2HS8N0

| ID | Kind | Persistence | Teardown |
| --- | --- | --- | --- |
| crew-b | ship | disposable | bin/fm-teardown.sh crew-b |
| mate-a | secondmate | persistent | retire only by an explicit decision naming this home - see .agents/skills/secondmate-provisioning |

A persistent home is retired only by a decision naming that exact home; an idle queue is healthy, not finished.
This report prints no runnable retirement command, so retiring a standing home has to be typed deliberately.
Teardown takes one target per invocation.
[rc=0]
Evidence: Authorized secondmate retirement and cleanup-candidates afterwards

Source: Authorized secondmate retirement and cleanup-candidates afterwards

## S9 authorized secondmate retirement (home outside FM_HOME)
home=/tmp/fm-lab-mates.n7EVk7/mate-a
  state: crew-b.meta mate-a.meta   mate-home: present

$ bin/fm-teardown.sh mate-a --retire-secondmate mate-a
fm-gate-refuse: gate agent lifecycle permitted only against lab home /tmp/fm-lab.2HS8N0
WARNING: watcher still down (same stale episode; last beat: never, grace 300s) - full banner already printed this episode.
teardown mate-a complete (window fm-lab-none:fm-mate-a, worktree /tmp/fm-lab-mates.n7EVk7/mate-a)
[rc=0]
  state: crew-b.meta   mate-home: GONE
## S1b cleanup-candidates after retirement

$ bin/fm-fleet-view.sh --cleanup-candidates
# Cleanup Candidates

Home: /tmp/fm-lab.2HS8N0

| ID | Kind | Persistence | Teardown |
| --- | --- | --- | --- |
| crew-b | ship | disposable | bin/fm-teardown.sh crew-b |

A persistent home is retired only by a decision naming that exact home; an idle queue is healthy, not finished.
This report prints no runnable retirement command, so retiring a standing home has to be typed deliberately.
Teardown takes one target per invocation.
[rc=0]
Evidence: fm-teardown suite log (still running at last check)

Source: fm-teardown suite log (still running at last check)

ok - a missing teardown startup source refuses before cleanup
ok - an unreadable teardown startup source refuses before cleanup
ok - a missing adapter sibling refuses before cleanup
ok - a forced descendant with a missing adapter sibling refuses before cleanup
ok - a forced secondmate with a missing own adapter sibling refuses before child cleanup
ok - present required sources still reach the ordinary teardown refusal
ok - local-only worktree with HEAD on a fork remote is torn down and the home summary is refreshed
ok - an ordinary ship teardown is unchanged by the secondmate retirement guard
ok - an ordinary scout teardown is unchanged by the secondmate retirement guard
ok - retirement authority offered for an ordinary task refuses as a mis-selected target
ok - a multi-target teardown refuses with the count and the secondmate ids before any change
ok - ids spelling option names after -- refuse as targets instead of being read as flags
ok - a dash-leading task id, including one spelling an option name, is torn down as a target
ok - teardown closes its own backlog item before reporting success
ok - teardown closes a landed Gerrit task with its change URL as a note and a GitHub task with --pr
ok - teardown honors config/backlog-backend=manual and still finishes cleanly
ok - local-only worktree with truly unpushed work is refused (safety preserved)
ok - local-only worktree with work merged into local main is torn down (no regression)
ok - no-mistakes worktree with HEAD on origin is torn down (no regression)
ok - no-mistakes worktree with genuinely unlanded work is refused (safety preserved)
ok - local-only worktree with unpushed work is torn down under --force (escape hatch)
ok - fm-pr-check publishes the PR-ready line on a secondmate's parent channel once
ok - a secondmate home's teardown delivers the child's final line or refuses until it can
ok - teardown completes when an exact busy-state sidecar is already absent
ok - herdr teardown removes pane-owned escalation dedupe state
ok - herdr flat teardown refuses before returning the isolated copy under lock contention and the retry completes cleanly
ok - herdr flat teardown never erases records when pane presence is unparseable
ok - herdr flat teardown preflight refuses before every destructive change
ok - forced secondmate teardown preflights every Herdr child before cleanup mutation
Evidence: fm-secondmate-safety suite log (still running at last check)

Source: fm-secondmate-safety suite log (still running at last check)

ok - FM_HOME parameterizes data and state paths
ok - fm-lock status is scoped per home
ok - seed allows overlapping project clone lists and drops the owns/owner routing
ok - home-seed validation rejects registry records no operational parser can consume
ok - home seeding refuses broken registry symlinks before provisioning
ok - home seeding refuses unreadable registries before provisioning
ok - home seed validation rejects duplicate home routes
ok - home seed validation rejects duplicate id routes
ok - home seed validation rejects nested home routes
leased worktree for dash
ok - home seeding durably leases treehouse-acquired dash homes under the secondmate id
ok - home seeding returns rejected acquired homes through treehouse
ok - home seed rollback warns when treehouse-acquired return fails
ok - home seeding leaves unsafe acquired active homes untouched
ok - home seeding rolls back failed clone attempts without residue
ok - home seeding refuses direct seed without filled charter text
ok - home seeding refuses unfilled placeholder charters
ok - home seeding refuses empty normalized charter fields
ok - home seeding scaffolds, registers, and spawns a project-less home end to end
ok - secondmate spawn resolves home validation and projects from punctuated registry fields
ok - secondmate spawn refuses ambiguous, supplied-home, and metadata-home registry bindings
ok - home seeding validates reused project-less charters before mutation
ok - home seeding refuses project-less conversion of a populated home
ok - home seeding refuses project-less homes whose projects directory cannot be inspected
ok - home seeding refuses project-less homes with symlinked projects directories
ok - home seeding refuses project-less homes with non-directory projects paths
ok - home seeding refuses project-less homes whose project registry cannot be inspected
ok - home seeding fails loudly on accidental project omission and rejects mixed --no-projects
ok - home seeding refuses local-only projects
ok - home seeding refuses a registry entry whose posture does not resolve
ok - home seeding refuses registry delimiter home paths
ok - home seeding refuses active home and repo root
ok - home seeding refuses homes marked for another id
ok - home seeding refuses homes registered to another id
ok - home seeding refuses same-id reassignment to a different home
ok - home seeding refuses registered home overlaps
ok - remote-backed subhome seeding requires a source origin
ok - remote-backed subhome seeding validates existing destination origins
ok - home seeding resolves relative source origins against the source project
ok - home seeding skips initialized existing no-mistakes clones
ok - home seeding refuses uninitialized existing no-mistakes clones
ok - home seeding refuses project destinations outside the subhome
ok - home seeding refuses operational directories outside the subhome
ok - home seeding refuses symlinked and non-regular leaf files
ok - home reseeding preserves and enforces the durable parent binding
ok - secondmate spawn validates homes before launch
ok - secondmate spawn refuses operational directories outside the subhome
ok - fm-send refuses a bare firstmate window with no metadata in this home
ok - secondmate teardown retires empty homes and releases routing
ok - secondmate teardown refuses without authority naming that exact home
ok - the supervision branch cannot retire a secondmate and leaves it fully intact
ok - secondmate teardown refuses ambiguous and identity-mismatched registry bindings
ok - normal secondmate teardown sweeps process events before removal
ok - secondmate teardown preserves state when process-event sweeping is unavailable
ok - later teardown refusals preserve active process-event sources
ok - force teardown sweeps nested secondmate homes before deletion
ok - force teardown preserves nested process-event restoration status and recovery state
ok - secondmate teardown refuses to hide failed leased-home return
ok - secondmate teardown raw-removes plain-clone homes, including a leaked read-only strip dir
ok - secondmate force teardown discards child work
ok - forced secondmate teardown refuses duplicated descendant pool slots
ok - secondmate force teardown preserves child worktree after unproven lock refusal
ok - force teardown allows non-state operational directory symlinks inside the subhome
ok - force teardown refuses operational directory symlinks outside the subhome
ok - secondmate teardown refuses homes containing registered nested homes
ok - secondmate teardown refuses nested homes from the child registry
ok - force teardown validates subhome before child cleanup
ok - forced teardown refuses a non-directory descendant state path
ok - forced teardown refuses a symlinked descendant state path
Terminated
Evidence: fm-fleet-snapshot-view suite log

Source: fm-fleet-snapshot-view suite log

ok - empty fleet snapshot and view use explicit absence markers
ok - fixture snapshot covers task rows, backlog rows, pointers, stable ordering, and emission-time event age
ok - home-summary excludes kind=secondmate from unowned_current and terminal_in_flight
ok - undated captain holds age after a configurable threshold, decided only from structured fields
ok - captain-hold buckets are total, mutually exclusive, and never decided by prose
ok - main_inventory discloses orphan/unstructured and clears when inventory is consistent
ok - backlog normalization preserves strict roles and resolves every blocker compatibly
ok - snapshot event hints follow reconciled current state
ok - durable fold keeps an open decision past a later unrelated event
ok - a live secondmate endpoint preserves unrelated open decisions
ok - durable captain-held transfer closes the duplicate live status decision
ok - durable fold clears a decision only on a keyed resolution
ok - a completed scout's stale decision surfaces as a report pointer, not pending
ok - a scout still parked at a decision stays pending (terminal clear does not over-fire)
ok - snapshot includes durable scout reports after teardown
ok - snapshot parses tasks-axi rows and respects operational overrides
ok - fleet view renders the snapshot without secondmate peek guidance
ok - fleet view lists cleanup candidates labeled by kind
ok - fleet view renders secondmate agent liveness
rc=0
Evidence: fm-secondmate-lifecycle-e2e suite log

Source: fm-secondmate-lifecycle-e2e suite log

ok - seed: registry scope+projects, charter copied, clones+origins, no-mistakes init in subhome only
warning: secondmate design sync skipped before launch: primary default-branch commit cannot be resolved
ok - spawn: launches in the subhome with persistent charter, records routing meta
ok - send: a bare fm-<id> secondmate enqueues a marked request and rings the meta window
ok - handoff: in-scope items move verbatim, out-of-scope stays, idempotent
ok - recovery: respawns from the durable registry and persistent home
ok - teardown: removes the home, then clears meta and the registry route
rc=0
Evidence: fm-teardown-endpoint-safety suite log (still running at last check)

Source: fm-teardown-endpoint-safety suite log (still running at last check)

ok - fm-teardown: missing, empty, malformed, ambiguous, and task-mismatched endpoints refuse before every mutation or runtime call
ok - fm-teardown: a concurrent lifecycle action refuses before mutation
ok - fm-teardown: non-pool cleanup ignores unrelated task publication locks
ok - fm-teardown: destructive cleanup serializes with metadata writers
ok - cleanup identity: valid tmux, Herdr, Zellij, Orca, and cmux records validate while every empty backend target refuses
ok - cleanup identity: an Orca record's real composite worktree id validates while a separatorless or newline-carrying id refuses
ok - tmux backend: direct empty target returns nonzero without invoking tmux
ok - process cleanup: creation-time PID identity removes only the exact child and preserves the control child
ok - fm-teardown: exact tmux cleanup preserves invalid and prefix-matched neighbors while removing only the recorded target
ok - fm-teardown: a close that genuinely failed refuses and keeps the record naming the surviving endpoint, and the same teardown finishes once the close works
ok - fm-teardown: --force continues past a close it could not make while still reporting it, and the same case refuses without --force
ok - fm-teardown: a close re-read that could not run refuses, while a definitively absent session or server still completes silently
ok - fm-teardown: forced secondmate cleanup still refuses on a child endpoint close that failed
ok - fm-teardown: an Orca close its missing CLI never attempted refuses even under --force, keeping the record naming the terminal
ok - fm-teardown: an already-exited endpoint, and a server that is already gone, still complete cleanup silently
ok - Treehouse locking resolves a bare local origin against its source project, matching the provisioned clone
ok - fm-teardown: a pool slot named by a second task record is never returned, killed, or reset
ok - fm-teardown: a pool slot held by another firstmate home is never returned
ok - fm-teardown: a task that solely holds its slot still returns it
ok - fm-teardown: a pool slot claimed by another task is left alone while the task's own cleanup finishes
ok - fm-teardown: a stale record on a claimed slot retires, then the claimant tears down
ok - fm-teardown: a task's own slot claim, and an unclaimed slot, both still tear down
ok - fm-teardown: an exact recorded endpoint still tears down after changing cwd outside its worktree
ok - Treehouse project locking anchors at the local root for main-home, local-secondmate, and remote-seeded layouts

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 8 of 9 scenarios driven live against the product
Scenario Result Live Evidence
Operator runs fm-fleet-view.sh --cleanup-candidates and sees each task's kind: the ship task with its teardown command, the secondmate marked persistent with no runnable command ✅ pass live live-teardown-refusals.txt (S1); live-teardown-authorized-retire.txt (S1b, the retired home's row is gone)
Tearing down a secondmate with no --retire-secondmate is refused and leaves the record and home in place ✅ pass live live-teardown-refusals.txt S2: REFUSED, rc=1, state unchanged
Adversarial: --force alone does not retire a secondmate ✅ pass live live-teardown-refusals.txt S3: REFUSED, rc=1, home present
Adversarial: --retire-secondmate naming another task, or given no value, is refused ✅ pass live live-teardown-refusals.txt S4 and S4b: rc=1 and rc=2, nothing changed
Adversarial: a two-target call that includes a secondmate is refused before anything changes, and the secondmate is named ✅ pass live live-teardown-refusals.txt S5: rc=2, names mate-a, both records intact
Adversarial: after --, a later target spelled like an option (--force) is treated as a second target and refused, not read as a flag ✅ pass live live-teardown-refusals.txt S6: rc=2 '2 targets were given: crew-b --force', worktree intact
Putting --retire-secondmate on an ordinary ship task is refused as a mis-selected target ✅ pass live live-teardown-refusals.txt S7: REFUSED, rc=1
A correctly authorized retirement (mate-a --retire-secondmate mate-a) removes the home and its record ✅ pass live live-teardown-authorized-retire.txt S9: rc=0, 'teardown mate-a complete', record gone, home GONE
An ordinary ship teardown needs no retirement flag and completes cleanup ⏸️ untested no The prior payload did not establish a live result for full cleanup: the live run passed the new check but stopped at treehouse return because the lab worktree isn't managed by treehouse. Creating a…
  • bin/fm-lab-home.sh create $LAB, then seeded one secondmate record (mate-a) and one ship record (crew-b) with a real git worktree
  • FM_HOME=$LAB bin/fm-fleet-view.sh --cleanup-candidates (before and after retirement)
  • FM_HOME=$LAB bin/fm-teardown.sh mate-a (no authority flag)
  • FM_HOME=$LAB bin/fm-teardown.sh mate-a --force
  • FM_HOME=$LAB bin/fm-teardown.sh mate-a --retire-secondmate crew-b
  • FM_HOME=$LAB bin/fm-teardown.sh mate-a --retire-secondmate (flag with no value)
  • FM_HOME=$LAB bin/fm-teardown.sh crew-b mate-a
  • FM_HOME=$LAB bin/fm-teardown.sh crew-b -- --force
  • FM_HOME=$LAB bin/fm-teardown.sh crew-b --retire-secondmate crew-b
  • FM_HOME=$LAB bin/fm-teardown.sh crew-b
  • FM_HOME=$LAB bin/fm-teardown.sh mate-a --retire-secondmate mate-a (home moved outside FM_HOME)
  • bash tests/fm-teardown.test.sh
  • bash tests/fm-secondmate-safety.test.sh
  • bash tests/fm-fleet-snapshot-view.test.sh
  • bash tests/fm-secondmate-lifecycle-e2e.test.sh
  • bash tests/fm-teardown-endpoint-safety.test.sh
  • rm -rf $LAB lab teardown
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@RooseveltAdvisors
RooseveltAdvisors force-pushed the fix/fm-secondmate-retire-validation-r2 branch from c0a1108 to 963ccc3 Compare September 15, 2026 06:49
@RooseveltAdvisors RooseveltAdvisors changed the title fix(bin): require per-target authority to retire a secondmate home fix(bin): guard secondmate retirement behind per-target authority Sep 15, 2026
A caller built a cleanup target list by matching worktree path suffix
*/firstmate. That suffix matches both a crewmate worktree of the firstmate
project and a persistent secondmate home, because homes are laid out
.treehouse/<...>/N/firstmate, and every idle seat passed the existing in-flight
guard - an idle queue is a healthy second mate's normal state, not evidence it
is finished. Roughly 17 standing second mates were retired in one unattended
batch. The homes survived with charter, backlog, learnings, and clones intact,
so recovery through the registry respawn path worked; that was luck, not a
guarantee.

Three refusals close the gap:

- Per-target authority. A kind=secondmate teardown now requires
  --retire-secondmate <task-id> naming the exact home being retired, so a list a
  caller assembled cannot retire one as a side effect. --force does not
  substitute for it, because discarding work and choosing which home to retire
  are separate decisions. Offering the flag for any other kind also refuses,
  since that mismatch means the target was selected wrong.
- Loop-shape refusal. Teardown acts on one target per invocation, and extra task
  ids are now refused before anything is locked, naming the count and any
  secondmates among them, so a mistaken selection list is caught while every
  seat is still alive. Previously a trailing id was silently ignored and the
  first target was torn down anyway.
- Kind-scoped selection. bin/fm-fleet-view.sh --cleanup-candidates renders the
  existing fleet snapshot as a kind-labeled report - id, kind, persistent or
  disposable, and the teardown command that kind takes - so no caller has to
  infer persistence from a worktree path. This extends the existing fleet
  inventory owner rather than adding a new script.

Every non-destructive path is unchanged: ordinary ship and scout teardowns take
no new flag, and the landed-work, scout-report, captain-hold, public-followup,
and forced-discard gates are untouched. The remote retirement path carries the
authority through to the host-side cleanup of the same record.

The first argument is collected as a target unconditionally before the option
loop begins, so a task id that spells --force or --retire-secondmate stays
tearable exactly as it was at the base commit.
…ter targets refuse as a batch

A selection list whose later ids spell option names was read as flags:
the multi-target refusal saw one target and proceeded, and a later
--force could silently discard the first target's work. After --, every
argument is a target, so the mistaken list reaches the refusal naming
all of its ids; flag meanings before -- are unchanged.
@RooseveltAdvisors
RooseveltAdvisors force-pushed the fix/fm-secondmate-retire-validation-r2 branch from 963ccc3 to ed9c890 Compare September 15, 2026 23:00
@RooseveltAdvisors RooseveltAdvisors changed the title fix(bin): guard secondmate retirement behind per-target authority fix(bin): require per-target authority to retire a secondmate home Sep 15, 2026
…erial 4' check: tests/fm-teardown-endpoint-safety.test.sh failed its assertion 'the refusal did not name the child whose endpoint could not be closed'. Root cause: this PR (commit 644ed57) added a per-target retire guard so a kind=secondmate teardown now requires --retire-secondmate <task-id> naming that exact home, with --force explicitly not substituting (per the PR contract and review ruling). Commit da0173e updated one pre-existing forced-secondmate test to pass that authority (tests/fm-secondmate-safety.test.sh), but test_forced_secondmate_child_close_failure_still_refuses in tests/fm-teardown-endpoint-safety.test.sh was missed, so its `--force`-only invocation was correctly refused by the new guard before ever reaching the child endpoint close path it exists to exercise. Reproduced locally (the refusal was 'REFUSED: task mate-task is a persistent secondmate home...'), and fixed the test with the same pattern as da0173e: the teardown invocation now passes --retire-secondmate "$parent" alongside --force, with an updated comment explaining that the per-target authority is what reaches the forced path. No production code changed - the guard behaves exactly as specified. Verified: tests/fm-teardown-endpoint-safety.test.sh now passes all 25 assertions including 'fm-teardown: forced secondmate cleanup still refuses on a child endpoint close that failed'; sibling contract suites tests/fm-teardown.test.sh (90 ok) and tests/fm-secondmate-safety.test.sh (0 failures) also pass
RooseveltAdvisors added a commit to RooseveltAdvisors/firstmate that referenced this pull request Sep 27, 2026
…unchenguid#3657)

Upstream: kunchenguid#3657
State: open
Slug: retire-secondmate-authority

Upstream PR kunchenguid#3657 (open); duplicate tracker kunchenguid#4219. Teardown --retire-secondmate
implementation lives in the kunchenguid#4225 commit (shared bin/fm-teardown.sh); this
commit carries the rest of the authority surface (fleet-view, remote control,
docs, safety tests).

House tracking: one commit ↔ one upstream PR. When this PR merges to
origin/main, drop this commit from house main (rebase onto new origin/main
or reset residue without this feature).
@greptile-apps

greptile-apps Bot commented Oct 2, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 5/5

[High risk] Adds mandatory flag to retire persistent task homes.

The PR appears safe to merge, although the existing non-blocking cleanup-report issue for unknown task kinds remains unresolved.

Reviews (4) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..."

Comment thread bin/fm-fleet-view.sh
Comment on lines +51 to +54
def persistence($t): if $t.kind == "secondmate" then "persistent" else "disposable" end;
def teardown_for($t):
if $t.kind == "secondmate" then "retire only by an explicit decision naming this home - see .agents/skills/secondmate-provisioning"
else "bin/fm-teardown.sh \($t.id)" end;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Unknown kinds appear disposable

This report treats every kind other than the exact value secondmate as disposable and prints a runnable teardown command. The snapshot passes through non-empty, noncanonical kind values without validation, so a malformed or future kind would be presented as safe to remove instead of unknown. Please emit teardown commands only for known disposable kinds such as ship and scout, and fail closed for everything else.

Suggested change
def persistence($t): if $t.kind == "secondmate" then "persistent" else "disposable" end;
def teardown_for($t):
if $t.kind == "secondmate" then "retire only by an explicit decision naming this home - see .agents/skills/secondmate-provisioning"
else "bin/fm-teardown.sh \($t.id)" end;
def persistence($t):
if $t.kind == "secondmate" then "persistent"
elif $t.kind == "ship" or $t.kind == "scout" then "disposable"
else "unknown" end;
def teardown_for($t):
if $t.kind == "secondmate" then "retire only by an explicit decision naming this home - see .agents/skills/secondmate-provisioning"
elif $t.kind == "ship" or $t.kind == "scout" then "bin/fm-teardown.sh \($t.id)"
else "refuse cleanup until this task kind is understood" end;

Knowledge Base Used: Secondmate coordination

…-teardown.sh (+119/-19 lines for the retire-secondmate authority and end-of-options parsing) pushed its ShellCheck analysis over fm-lint's per-root memory envelope. Evidence: the run's telemetry sidecar (artifact fm-lint-telemetry-1) records `end ... bin/fm-teardown.sh ... rc=251 reason=memory rss_kib=8388016`, and the job exits 251 after `shellcheck: out of memory`. Reproduced exactly: under the CI envelope (ulimit -v 12582912, `shellcheck --norc --external-sources`) the base-commit bin/fm-teardown.sh passes at 8,263,224 KiB RSS while the PR head fails with rc 251; head passes uncapped (8,448,828 KiB) and at 12.5/13 GiB caps - so the root needs just over the 12 GiB cap's ~8 GiB GHC heap, i.e. the envelope (not the script) is the shared boundary at fault. Invariant: every canonical root's full source-aware analysis must fit inside FM_LINT_ROOT_MEMORY_KIB so a required-bounds partition run completes; it must hold for all 451 roots in both partitions under CI's FM_LINT_REQUIRE_BOUNDS=1. Fix at that one shared boundary: bin/fm-lint.sh default FM_LINT_ROOT_MEMORY_KIB 12582912 -> 14680064 (14 GiB, following this file's documented precedent of raising the wall when a root outgrows it, e.g. 8 -> 12 GiB) with the sizing rationale updated to the measured ~8.4 GiB resident peak, plus the roots-sidecar contract value updated in tests/fm-lint.test.sh:1697. Verification: bounded single-root run of bin/fm-teardown.sh now rc=0 (sidecar records 14680064, result_exit 0); full CI-parity local runs of `FM_LINT_REQUIRE_BOUNDS=1 FM_LINT_JOBS=1 bin/fm-lint.sh --partition 1of2` (rc=0, 226/226 roots ok) and `--partition 2of2` (rc=0, 225/225 ok) covering all 451 canonical roots with zero abnormal ends, backend-purity clean and actionlint validating 3 workflow files; `tests/fm-lint.test.sh` passes end to end. No other check, doc, or config pins the old constant. Only ci-1 was addressed; the declined round-1 findings and the unselected Greptile P2 were left untouched as instructed
…-delta-read.test.sh: 'not ok - no attempt landed the rewrite in the same ctime second' (job 110751921321, run 36979934096, exit=1 at 07:57:36, the shard's only failed=1). The test is not in the PR diff: it landed on main via kunchenguid#6363 (65e2aa4) and reaches this PR only through the pull_request merge ref, which is also why it appears in shard 4 (after merging origin/main locally, bin/fm-test-run.sh --list --lane portable-serial-4of9 reproduces CI's exact 25-test order). It is a real flake in that new test, not an infra/stale check: it fails ~80% of local runs on pure main content (4/5 and later 1/5 pre-fix), main's own run 36978723064 passed it, and an unrelated branch failed the same assertion in run 36979550661. Root cause, measured in-process: the retry loop aligns the first write to a second boundary with perl sleep(1-(time-int(time))) (wake lands at X.0000x), but the filesystem stamps inode mtime/ctime from the kernel's coarse timestamp clock, which trails the process clock by ~4ms (observed: write at now=X.003489 recorded mtime=X-1.999419), so the initial write is stamped in the previous whole second while the rewrite 0.15s later lands in the new one; every one of the 3 attempts repeats the same systematic race, so the retry never saves it (probe: before=...0555 while the wall clock already read ...0556.006 on every attempt). Invariant: for both same-second writes to compare equal, the first write's filesystem stamp must fall after the boundary in whole-second terms, i.e. the write must be issued past the coarse-clock lag; the only site with this boundary-aligned same-second pattern is this test's retry loop (grep 'sleep(1 - (time' and 'ctime_second' find no siblings), so the fix is that one write site: sleep 0.05 after the boundary wake and before the first printf, well past the measured ~5ms lag yet far short of the next boundary (first write ~0.05s, rewrite ~0.23s, still the same second; any genuine overrun is still handled by the existing BEFORE!=AFTER retry). The merge of origin/main (dd5a4a7) was required to ship this file: the branch pre-merge lacked it, so adding it fresh would have been an add/add conflict against main in the pull_request merge ref; the merge touched no PR-owned file (git diff 604042b HEAD intersects the PR's changed-file set in zero files) and CI already ran this exact merged content green for all other 24 shard-4 tests. Verification: tests/fm-remote-delta-read.test.sh passes 16/16 consecutive runs post-fix (pre-fix 4/5 failed), bash -n clean, shellcheck -x clean, bin/fm-lint.sh tests/fm-remote-delta-read.test.sh rc=0 with pinned ShellCheck 0.11.0 full dataflow; the declined round-1 findings and the unselected Greptile P2 remain untouched
…ire-validation-r2

# Conflicts:
#	tests/fm-remote-delta-read.test.sh
@RooseveltAdvisors RooseveltAdvisors changed the title fix(bin): require per-target authority to retire a secondmate home fix(bin): require explicit per-home authority to retire a secondmate Oct 2, 2026
@RooseveltAdvisors RooseveltAdvisors changed the title fix(bin): require explicit per-home authority to retire a secondmate fix(bin): require explicit per-home authority to retire secondmates in teardown Oct 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant