Skip to content

fix(bin): require per-target authority to retire a secondmate home - #3657

Open
RooseveltAdvisors wants to merge 5 commits into
kunchenguid:mainfrom
RooseveltAdvisors:fm/fm-secondmate-retire-guard
Open

RooseveltAdvisors wants to merge 5 commits into
kunchenguid:mainfrom
RooseveltAdvisors:fm/fm-secondmate-retire-guard

Conversation

@RooseveltAdvisors

@RooseveltAdvisors RooseveltAdvisors commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Intent

The developer (acting on a captain's order to "push firstmate to close all gaps now") needed two firstmate shell tools fixed so that two leftover records in the main home could finally be closed honestly, because both tools still assumed the pre-Beads markdown world. First, bin/fm-captain-hold.sh's complete path re-read a scout report's attested legacy hold ids and looked them up by grepping data/backlog.md, so on a Beads-backend home whose holds had been migrated to fm- prefixed ids it failed with an empty-name message ("captain-held task is absent from data/backlog.md") and the scout todo-md-verify-ingest-20260830 could never pass its completion gate; the fix had to resolve ids through the configured backend, accept a migrated row via the exact "migrated from data/backlog.md id " note or the legacy id under the configured prefix, name the unresolved id in any refusal, and keep the markdown path working. Second, bin/fm-teardown.sh refused to tear down task portal-insurance-path-owner because its record predates spawn_gen, so a finished, clean, superseded worktree could never be cleaned; teardown had to accept such a record behind an explicit --legacy-record flag only when the endpoint is dead or agent-less and the worktree passes the ordinary landed test, log the accepted incarnation, and never relax the unlanded-work refusal. The developer also required colocated behavior tests for both (Beads fixture home plus a legacy meta fixture without spawn_gen) that stay CI-portable by self-skipping when only markdown-capable tooling is installed, and required the change to be validated through the no-mistakes pipeline with every gate answered explicitly (never --yes), escalating ask-user findings rather than self-answering them.

What Changed

  • bin/fm-teardown.sh now refuses a kind=secondmate teardown unless --retire-secondmate <task-id> names the exact target, refuses the flag on any other kind as a mis-selected target, and does not accept --force as a substitute; argument parsing was reworked so the first positional argument is always the target (ids that spell an option stay reachable), extra targets are refused before the lock while naming the count and any secondmates among them, and bin/fm-remote-secondmate-control.sh passes the new authority on both its retire paths.
  • bin/fm-fleet-view.sh gained --cleanup-candidates, rendering the snapshot as a kind-labeled table of live tasks with a persistent/disposable column; disposable rows carry their runnable fm-teardown.sh command while a secondmate home carries a pointer to the retirement contract instead, so the report cannot be piped to a shell to retire standing homes.
  • Added teardown tests for the missing/mismatched/wrong-kind authority refusals, the multi-target refusal, and a leading-dash task id, plus a cleanup-candidates rendering test; updated existing secondmate teardown call sites to pass the flag and bumped the CI snapshot/fleet-view test count from 18 to 19, with the contract documented in AGENTS.md, CONTRIBUTING.md, docs/architecture.md, docs/remote-secondmates.md, docs/scripts.md, and the secondmate-provisioning skill.

Risk Assessment

✅ Low: The change is a well-bounded, fail-closed CLI hardening: the authority check reads the target's own recorded kind before any destructive step, every unrecognized-argument path refuses rather than proceeding, the sole production caller (bin/fm-remote-secondmate-control.sh) and every in-repo test call site on a kind=secondmate record were updated, and the pipeline fix round made the minimal report change the ruling asked for without weakening the guard.

Testing

Completed 1 recorded test check.

  • Outcome: ⚠️ 1 error across 1 run (13m13s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 3 issues found → auto-fixed ✅
  • ⚠️ bin/fm-fleet-view.sh:47 - The --retire-secondmate &lt;id&gt; token carries no information beyond the target id it must equal, and the report designated as the sanctioned source of cleanup targets prints the complete pre-authorized retirement command for every persistent home (bin/fm-teardown.sh &lt;id&gt; --retire-secondmate &lt;id&gt;). Concrete path: an operator or agent runs bin/fm-fleet-view.sh --cleanup-candidates, takes the Teardown command column, and pipes it to a shell — every standing secondmate is retired, one invocation each, with the one-target rule satisfied and no refusal fired. That weakens the invariant asserted at AGENTS.md:391 ("a selection list can never retire a standing second mate as a side effect") and .agents/skills/secondmate-provisioning/SKILL.md:243 ("a cleanup list a caller assembled cannot retire standing homes as a side effect"). The guard does genuinely block the failure it was built for — an unlabeled path-globbed or pane-swept list, since a path suffix yields no --retire-secondmate token — so this is not a defect in the code as written; it is a question about whether the claimed invariant should be narrowed to that case, or whether the report should stop emitting the authority token for persistent rows (e.g. print the kind and a pointer to the retirement contract instead of a runnable command). Flagging the remedy, not the defect: either narrowing the documented claim or changing what the report emits is a product-behavior decision belonging to the author, not a mechanical fix.
  • ℹ️ tests/fm-teardown.test.sh:3577 - ! grep -q &#39;unknown teardown option&#39; &#34;$case_dir/stderr&#34; asserts against a string bin/fm-teardown.sh never emits. The parser's only failure messages are error: invalid teardown request (bin/fm-teardown.sh:270,277) and the multi-target refusal (bin/fm-teardown.sh:293), so this guard cannot fail no matter how the parser regresses. The regression it is meant to catch — a dash-leading id being consumed as an option — is already covered by the surrounding expect_code 0 and assert_absent .../state/$dash_id.meta assertions in the same loop, which are genuinely behavioral. Either drop the dead grep or point it at the message the code would actually produce if --force were parsed as a flag rather than a target (invalid teardown request).
  • ℹ️ bin/fm-teardown.sh:267 - The catch-all now reclassifies any unrecognized option as an extra target, so a typo'd flag produces a misdirecting diagnostic: bin/fm-teardown.sh task-x1 --dry-run exits 2 with "teardown acts on exactly one task, but 2 targets were given: task-x1 --dry-run" and advises listing candidates with --cleanup-candidates, instead of naming the unknown flag as the previous parser did. This still fails closed (no invocation can silently succeed with a swallowed flag, because the first argument is already consumed as the target, so any extra token forces the multi-target refusal), and the author documented the tradeoff inline: fm_task_id_path_safe (bin/fm-pr-lib.sh:97) permits dash-leading ids, so an id spelling an option name must remain reachable. Noting the diagnostic cost of that deliberate choice; no action needed.

🔧 Fix: stop printing runnable retirement command in cleanup report
✅ Re-checked - no issues remain.

⚠️ **Test** - 1 error
  • 🚨 tests failed with exit code 1
  • bin/fm-test-run.sh --changed --exclude-family real-herdr-gated
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@greptile-apps

greptile-apps Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 4/5

The PR is not yet safe to merge because a later option-shaped task ID can still bypass the multi-target refusal and cause the first task to be torn down with unintended flags.

Findings

  1. P1 Option-shaped targets bypass refusal ▶

Comment thread bin/fm-teardown.sh Resolved
Comment thread bin/fm-teardown.sh Resolved
@greptile-apps

greptile-apps Bot commented Sep 3, 2026

Copy link
Copy Markdown

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

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

Copy link
Copy Markdown
Contributor Author

Two notes for reviewers that belong with this PR rather than in its description.

What the new refusals change for existing operator workflows. This PR is not purely additive, and the behaviour change is deliberate rather than incidental. Three invocations that used to work now refuse:

  1. bin/fm-teardown.sh <id> on a kind=secondmate record refuses unless it also carries --retire-secondmate <id> naming that same id. Any script, alias, or habit that retires a persistent home by id alone must add the flag. --force does not satisfy it, because discarding work and choosing which home to retire are separate decisions.
  2. Passing --retire-secondmate for a ship or scout task refuses instead of being ignored. That mismatch means the caller selected the wrong target, so it fails closed on purpose.
  3. More than one task id in one invocation refuses. Previously a trailing id was silently ignored and the first target was torn down anyway; that silence is exactly the loop-shape hazard this closes, so it is now a refusal naming the target count and any secondmates among them.

Ordinary ship and scout teardown is untouched and takes no new flag, and the landed-work, scout-report, captain-hold, public-followup and forced-discard gates are unchanged. bin/fm-fleet-view.sh --cleanup-candidates is purely additive.

A process disclosure about how this branch was validated. While iterating locally I stopped one of my own background test runs with a broad pkill -f "tests/fm-.*test.sh". That pattern is home-agnostic: it matches any process on the box whose command line contains it, so it could have killed a sibling firstmate home's test run as well as my own. The blast radius is bounded - a killed test run loses only that run, with no repository, worktree or state damage, and it surfaces as a failed validation that normal supervision catches - and every session on the box was confirmed alive afterwards. I have replaced that habit with tracking my own background PID and killing only that PID. Nothing in this diff came from that incident; it is disclosed because a reviewer evaluating a safety PR should know how its own validation was run.

For completeness on the test evidence: the local test step was accepted over eight pre-existing suite failures on that box. Six of them fail with byte-identical messages on unmodified upstream main, and the other two (fm-remote-job-orphan-reap, fm-x-mode) pass on both this branch and base outside the pipeline sandbox. None is a suite this PR touches, and CI here is green on all of them.

@RooseveltAdvisors
RooseveltAdvisors force-pushed the fm/fm-secondmate-retire-guard branch from 9c85b73 to 6eea34b Compare September 5, 2026 07:06
@RooseveltAdvisors RooseveltAdvisors changed the title fix(bin): require per-target authority to retire a secondmate fix(bin): require per-target authority to retire a second mate Sep 5, 2026
@RooseveltAdvisors
RooseveltAdvisors force-pushed the fm/fm-secondmate-retire-guard branch from 6eea34b to 08145cc Compare September 5, 2026 21:09
@RooseveltAdvisors RooseveltAdvisors changed the title fix(bin): require per-target authority to retire a second mate fix(bin): require per-target authority to retire a secondmate home Sep 5, 2026
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate:

First stamp on #3657 this fetch (HEAD 6cebb65728050941cd4c5fb8a27b0b0df1c5198d vs main d6660d75d0fc534ee7f8c41f3415272ce51bb76f).

Contract-class: restore. Retiring a persistent secondmate home now requires per-target authority (--retire-secondmate <same-id>), matching VISION: authority is explicit and never inferred; destructive/irreversible acts need the captain's explicit word. --force does not substitute. One target per invocation; cleanup-candidate report labels kinds and prints no runnable retire command for persistent homes. Author note acknowledged: three formerly-working invocations now refuse by design.

Attestation: MATCH (head_sha=6cebb65728050941cd4c5fb8a27b0b0df1c5198d).
CI / Require no-mistakes: no tip workflow runs present (CONFLICTING/DIRTY — checks not meaningfully green). Greptile green on last review. Did not approve any runs.
mergeable / mergeStateStatus: CONFLICTING / DIRTY (ahead 2 / behind 2, diverged). Do not resolve conflicts here.

VISION verdict (aligns as restore):

  • Authority is explicit and never inferred — naming the exact home is the decision.
  • Merging/discarding/destructive require explicit word — idle queue is not evidence a secondmate is done.
  • Not new-default convenience; it restores the refusal path VISION already requires.

Security: clean on reviewed surface. .github/workflows/ci.yml only bumps the fleet-view expected test count 18→19 (no secrets, permissions, or untrusted checkout changes). FYI only while CONFLICTING — not otherwise fully ready, so no captain-flag.

Overlap: fm-teardown.sh also touched by #3417; land/rebase order matters after conflicts clear.

Stamp outcome: waiting-author (conflicts). Resolve against main and re-push; do not merge while DIRTY. Not waiting-captain.

@RooseveltAdvisors

Copy link
Copy Markdown
Contributor Author

Responding to the three inline P1 findings on bin/fm-teardown.sh (leading-dash, double-dash, and option-spelled task ids): all three are addressed by restructuring the parser so the first argument is always a target, and only arguments after it are read as options. A task id is accepted in any position it may legitimately appear, including ids that spell --force or --retire-secondmate (both satisfy the canonical task-id validator), so there is no invocation that strands a task's record, worktree, or lease - including the double-dash spelling the regression test initially missed. The test now covers the option-spelled ids as well. Greptile's latest pass at commit ba9a08b3 reflects this head.

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.
@RooseveltAdvisors
RooseveltAdvisors force-pushed the fm/fm-secondmate-retire-guard branch from ba9a08b to f99f09a Compare September 8, 2026 15:15
@RooseveltAdvisors

Copy link
Copy Markdown
Contributor Author

Rebased onto main (b84e0e36) after the conflicts surfaced; one test-followup commit was needed because main's newer forced duplicated-slot teardown test predates the per-target authority flag. Both the architecture-doc and slot-collision conflict resolutions keep upstream's slot-ownership language alongside this PR's authority language.

Current check state on 904584c: all green except two, neither in this PR's diff:

  1. "PR must be raised via no-mistakes" - the standing policy label for this direct PR, unchanged since it was opened.
  2. "Behavior portable serial 4" is cancelled by the 20-minute job tripwire mid-fm-bearings-board.test.sh, with no failing assertion before the cut. The same cancellation appears on upstream main's own tip: run 34192318251 (push event on b84e0e36) also ends cancelled on serial 4 alone. So the serial 4 shard appears to have outgrown its cap on main itself (healthy shard target ~12.7 min per the ci.yml comment) - flagging it here since it is unrelated to this PR and will also block merges of other PRs against current main.

Happy to help with a shard rebalance if useful, but leaving that decision to you.

Comment thread bin/fm-teardown.sh Outdated
Comment on lines +286 to +289
--force) FORCE=--force ;;
--legacy-record) LEGACY_RECORD_GIVEN=1 ;;
*)
echo "error: invalid teardown request" >&2
exit 2
--retire-secondmate)
shift

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Option-shaped targets bypass refusal

When a cleanup list contains a valid later task ID such as --force or --legacy-record, this parser consumes that ID as a flag instead of recording a second target. The multi-target check therefore sees only one target and proceeds with its teardown; --force can additionally discard that first target's work instead of refusing the mistaken list.

…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

Copy link
Copy Markdown
Contributor Author

Fixed on the head now (58f4fb3): the parser takes a -- end-of-options escape. Everything after -- is a target, so a mistaken selection list whose later ids spell option names - --force, --legacy-record, --retire-secondmate - now reaches the multi-target refusal and is named in its error, instead of being silently read as flags where a --force could discard the first target's work. Flag meanings before -- are unchanged, and the positional-first first-argument rule from the earlier findings still stands, so a task id that spells an option remains targetable as the first argument. Regression test added: three-target list task-x1 -- --force --legacy-record refuses with 3 targets were given, names the option-spelled ids, and leaves every record intact.

Comment thread bin/fm-teardown.sh
Comment on lines +300 to +314
--force) FORCE=--force ;;
--legacy-record) LEGACY_RECORD_GIVEN=1 ;;
--retire-secondmate)
shift
[ "$#" -gt 0 ] || {
echo "error: --retire-secondmate needs the exact task id it authorizes" >&2
exit 2
}
RETIRE_AUTH=$1
RETIRE_AUTH_GIVEN=1
;;
--retire-secondmate=*)
RETIRE_AUTH=${1#*=}
RETIRE_AUTH_GIVEN=1
;;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Option-shaped targets bypass refusal

When a mistaken multi-target invocation such as fm-teardown.sh task-x1 --force uses a valid option-shaped ID as the later target, the parser consumes that ID as a flag instead of adding it to TEARDOWN_TARGETS. The target count remains one, so teardown bypasses the multi-target refusal and force-discards the first task's work while silently ignoring the intended second target.

@RooseveltAdvisors

Copy link
Copy Markdown
Contributor Author

On the remaining inline finding at the option branch: fm-teardown.sh task-x1 --force reading --force as the force flag is the documented, pre-existing contract, not something this PR introduced - upstream's usage line at the merge base is already fm-teardown.sh <task-id> [--force] [--legacy-record], and main's parser treats post-target --force identically. A later --force is genuinely ambiguous between "force flag" and "second task whose id spells --force" (the id validator permits that spelling), and reading it as a second target would make flag-based forced teardown unreachable for every existing caller and test.

What this PR changes is the unambiguous path for the mistaken-list case: the first argument is always a target, genuinely multi-target lists now refuse before any change, and as of 58f4fb3 a -- end-of-options escape makes option-spelled later targets expressible - fm-teardown.sh task-x1 -- --force refuses with both ids named and nothing torn down, pinned by the new regression test. Within the flag-precedes--- grammar the two readings cannot be separated by bytes alone, so we believe the flag reading plus the -- escape is the correct resolution; happy to adjust if you'd prefer a different trade.

RooseveltAdvisors added a commit to RooseveltAdvisors/firstmate that referenced this pull request Sep 27, 2026
…id#4225)

Upstream: kunchenguid#4225
State: open
Slug: stale-sweep-capacity

Upstream PR kunchenguid#4225 (open); supersedes closed kunchenguid#3720. Also sibling kunchenguid#4224.
Includes bin/fm-spawn.sh and bin/fm-captain-hold.sh full house delta
(capacity + kunchenguid#3712 actor bits + kunchenguid#3458 label bits) and bin/fm-teardown.sh
full house delta (capacity release + kunchenguid#3657 retire-secondmate authority),
because those files are not cleanly separable at tip.

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).
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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants