Skip to content

feat: support persistent secondmates - #37

Merged
kunchenguid merged 41 commits into
mainfrom
fm/sub-firstmate-q3
Jun 22, 2026
Merged

kunchenguid merged 41 commits into
mainfrom
fm/sub-firstmate-q3

Conversation

@kunchenguid

@kunchenguid kunchenguid commented Jun 22, 2026 •

Copy link
Copy Markdown
Owner

Intent

Pure mechanical rename of the subordinate domain-supervisor entity from 'sub-firstmate' to 'secondmate' on the existing PR #37 branch, per the captain's decision (nautical: captain -> first mate -> second mate). This is a RENAME ONLY: no behavior change, no logic change, no test additions/removals beyond renaming. The diff is intentionally balanced (487 insertions / 487 deletions) and all 48 behavior tests pass.

A deliberate, load-bearing DISAMBIGUATION governs every change, so apparent inconsistencies are intentional, not mistakes. ONLY the subordinate entity is renamed: the entity name (sub-firstmate -> secondmate), the routing registry file (firstmates.md -> secondmates.md, including parent-firstmates.md backup and all path references), the seed marker (.fm-sub-firstmate-home -> .fm-secondmate-home), the meta values kind=firstmate -> kind=secondmate and mode=firstmate -> mode=secondmate (plus every KIND/kind/child_kind bash comparison and window_kind check), the spawn/brief flag --firstmate -> --secondmate, the env vars FM_FIRSTMATE_CHARTER/SCOPE -> FM_SECONDMATE_CHARTER/SCOPE, the registry-specific identifiers (FIRSTMATE_REG -> SECONDMATE_REG, firstmate_registry_value -> secondmate_registry_value, remove_firstmate_registry_entry -> remove_secondmate_registry_entry, and the local FIRSTMATE_CHARTER/SCOPE/PROJECTS mirrors), and the test file (tests/fm-sub-firstmate.test.sh -> tests/fm-secondmate.test.sh, its test_secondmate_* functions, scaffold_secondmate_charter helper, and subordinate-lifecycle pass/fail labels like 'secondmate spawn/teardown/launch').

The MAIN firstmate role is intentionally PRESERVED and must NOT be renamed: the firstmate playbook/repo, 'the main firstmate', the generic concept of a 'firstmate home' / 'the active firstmate home' / 'the firstmate repo' (a secondmate's workspace genuinely IS a firstmate home because it runs the firstmate playbook), the generic home-validator/operation function names (validate_firstmate_home_for_spawn/removal, validate_firstmate_operational_dirs(_for_removal), verify_firstmate_home, remove_firstmate_home, cleanup_firstmate_home_children, mark_firstmate_home) and the FIRSTMATE_HOME variable and arg placeholder, the tmux session name 'firstmate' (e.g. window=firstmate:fm-domain), and fm-send/fm-peek's generic 'bare firstmate window' resolution (so test_fm_send_resolves_bare_firstmate_window_from_home_meta keeps its name). The 'child firstmate home' teardown label was preserved exactly as the original author wrote it (the original already used generic 'firstmate home' there, distinct from the top-level 'sub-firstmate home' -> 'secondmate home'); preserving that asymmetry is correct for a rename-only change.

Unrelated PR #30 content (the /afk skill, fm-supervise-daemon.sh, the AGENTS.md Sub-supervisor section, state/.afk and .subsuper-*) was intentionally left untouched - its uses of 'firstmate' mean the main role. CLAUDE.md remains a symlink to AGENTS.md; executable bits on the scripts/test are preserved (755).

What Changed

  • Adds persistent secondmate routing and lifecycle support, including secondmate home seeding, registry validation, scoped spawn/recovery, and teardown safety for isolated firstmate homes.
  • Updates firstmate supervision, brief generation, send/peek, project path resolution, wake handling, and local merge/review helpers to honor active FM_HOME boundaries and secondmate metadata.
  • Documents secondmate operations and adds focused coverage for secondmate seeding, spawn, teardown, wake queue behavior, and batch spawning.

Risk Assessment

⚠️ Medium: Captain, the review found no material issues, but the branch changes core spawn, routing, watcher, and teardown behavior, including guarded removal paths.

Testing

Captain, I inspected the supplied base-to-target diff and commit shape, ran the focused secondmate and spawn-path behavior tests, broadened to the remaining behavior scripts, and captured a manual CLI transcript showing secondmate seeding and spawn metadata working end to end. The worktree was clean after testing; evidence is in the dedicated no-mistakes evidence directory.

Evidence: secondmate behavior transcript
ok - FM_HOME parameterizes data and state paths
ok - fm-lock status is scoped per home
ok - secondmates registry records scopes and allows overlapping project clone lists
ok - home seeding records routing scope from filled charter briefs
ok - home seed validation rejects duplicate home routes
ok - home seed validation rejects duplicate id routes
ok - home seed validation rejects nested home routes
ok - home seeding accepts treehouse-acquired dash homes
ok - home seeding returns rejected acquired homes through treehouse
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 refuses local-only projects
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 leaf files
ok - kind=secondmate spawn launches in the home and records routing meta
ok - secondmate spawn validates homes before launch
ok - secondmate spawn refuses operational directories outside the subhome
ok - fm-send resolves bare firstmate windows through this home
ok - restart recovery can respawn a secondmate from durable registry and charter
ok - secondmate teardown retires empty homes and releases routing
ok - secondmate force teardown discards child work
ok - force teardown allows operational directory symlinks inside the subhome
ok - force teardown refuses operational directory symlinks outside the subhome
ok - secondmate teardown requires seeded home marker
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 - force teardown refuses child worktrees inside the active home
ok - force teardown refuses child worktrees inside the firstmate repo
ok - force teardown refuses unregistered child worktree paths
ok - secondmate teardown refuses ancestor homes
ok - secondmate teardown refuses descendant homes
ok - idle kind=secondmate pane is healthy and not stale
Evidence: spawn batch behavior transcript
ok - batch dispatch re-execs and reports every id=repo pair
ok - a single id=repo pair routes through batch dispatch
ok - single-task invocation (no '=') is untouched by batch detection
ok - batch dispatch rejects an argument that is not id=repo
ok - an arg whose id part contains '/' is not treated as a batch pair
ok - FM_HOME scopes projects/ paths for single-task spawn
ok - FM_PROJECTS_OVERRIDE scopes projects/ paths for single-task spawn
Evidence: wake queue behavior transcript
ok - supervise daemon state root is scoped by FM_HOME
ok - concurrent append plus drain preserves queue records
ok - signal written while no watcher runs is caught on next run
ok - stale wake is queued before suppressor state is advanced
ok - check output is queued before cadence suppression
ok - simultaneous watcher starts leave exactly one live process
ok - two atomic drains cannot consume the same records twice
ok - drain collapses obvious duplicate heartbeat and signal records
ok - killed watcher stale lock is reclaimed
ok - live watcher lock with stale heartbeat is actionable
ok - guard warns when queued wakes are pending
ok - guard orders watcher re-arm after queued wake drain
ok - routine signal self-handles
ok - captain-relevant status verbs escalate
ok - check + unknown escalate; heartbeat self-handles
ok - transient stale self-handles and records a persistence marker
ok - stale + terminal status escalates immediately
ok - persistent stale escalates after threshold and clears its marker
ok - resumed (busy) stale clears its marker without escalating
ok - multiple escalations flush as a single batched digest
ok - batch flush measures max-delay from the first append, not the last
ok - catch-all scan escalates a missed terminal once, not twice
ok - handle_wake routes routine->self and captain->escalate
ok - INJECT_SKIP forces self-handle, bypassing captain-relevant classification
ok - is_wake_reason distinguishes watcher wake reasons from singleton-status stdout
ok - terminal-stale escalate removes its marker so housekeeping does not re-escalate
ok - captain signal escalate marks seen so the catch-all scan does not re-fire
ok - _collapse_newlines replaces newlines with literal separator
ok - afk flag absent: daemon does not inject, buffer preserved
ok - afk flag present: daemon injects with sentinel marker prefix
ok - injected digest is single-line (no embedded newlines)
ok - busy-guard defers injection when supervisor pane is busy
ok - marker detection: marker -> stay afk, no marker -> exit afk
ok - /afk invocation is exempt from afk exit (no self-cancel)
ok - should_exit_afk returns false when afk is not active
ok - strip_injection_marker removes the sentinel marker cleanly
ok - pane_input_pending detects partial input on the cursor line
ok - pane_input_pending: blank cursor line is not pending
ok - pane_input_pending: bare prompts are not pending (idle)
ok - composer guard defers injection when pane has pending input
ok - swallowed Enter: type-once + Enter-retry, no concatenation
ok - normal inject: exactly one digest, one Enter, no duplicates
ok - classify_signal dedupes against the catch-all scan seen marker
ok - classify_stale dedupes against the signal path seen marker
Evidence: AFK injection E2E transcript
ok - Scenario A: partial input defers injection; digest arrives clean after idle
ok - Scenario B: swallowed Enter produces exactly one clean digest
all e2e injection tests passed
Evidence: manual secondmate CLI demo

CLI demo shows data/secondmates.md route creation, .fm-secondmate-home marker value design, and spawn output kind=secondmate mode=secondmate with persisted meta projects=alpha.

$ fm-home-seed.sh provisions a secondmate route
scaffolded: /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T//fm-secondmate-demo.GjlaAK/main-home/data/design/brief.md (secondmate charter)
home=/private/var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/fm-secondmate-demo.GjlaAK/design-secondmate-home

$ cat data/secondmates.md
- design - feature design and implementation for alpha (home: /private/var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/fm-secondmate-demo.GjlaAK/design-secondmate-home; scope: feature design and implementation for alpha; projects: alpha; added 2026-06-22)

$ cat <secondmate-home>/.fm-secondmate-home
design

$ fm-spawn.sh design <secondmate-home> "echo launched-secondmate" --secondmate
spawned design harness=echo kind=secondmate mode=secondmate yolo=off window=firstmate:fm-design worktree=/private/var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/fm-secondmate-demo.GjlaAK/design-secondmate-home

$ cat state/design.meta
window=firstmate:fm-design
worktree=/private/var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/fm-secondmate-demo.GjlaAK/design-secondmate-home
project=/private/var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/fm-secondmate-demo.GjlaAK/design-secondmate-home
harness=echo
kind=secondmate
mode=secondmate
yolo=off
home=/private/var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/fm-secondmate-demo.GjlaAK/design-secondmate-home
projects=alpha

$ tmux commands issued by spawn
has-session -t firstmate
list-windows -t firstmate -F #{window_name}
new-window -d -t firstmate -n fm-design -c /private/var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/fm-secondmate-demo.GjlaAK/design-secondmate-home
send-keys -t firstmate:fm-design -l FM_ROOT_OVERRIDE= FM_STATE_OVERRIDE= FM_DATA_OVERRIDE= FM_PROJECTS_OVERRIDE= FM_CONFIG_OVERRIDE= FM_HOME='/private/var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/fm-secondmate-demo.GjlaAK/design-secondmate-home' echo launched-secondmate
send-keys -t firstmate:fm-design Enter

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 1 issue found → auto-fixed (2) ✅
  • ⚠️ bin/fm-brief.sh:83 - The generated status command leaves the redirected path unquoted, so any FM_HOME/FM_STATE_OVERRIDE containing spaces makes crewmates append to the wrong path or fail; render the generated command with a quoted or shell-escaped status-file path in all brief variants.

🔧 Fix: Captain, quote generated status paths
1 warning still open:

  • ⚠️ bin/fm-spawn.sh:291 - FM_HOME makes projects/ an operational directory under the active home, but ordinary and batch spawns still resolve projects/foo relative to the caller's cwd. When firstmate is run from the shared repo with FM_HOME pointing at a secondmate or external home, this will either fail to spawn or target the wrong clone while writing meta into the active home; resolve projects/* through $FM_PROJECTS_OVERRIDE/$FM_HOME/projects before cd.

🔧 Fix: Captain, resolve FM_HOME project paths
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • git status --short --branch
  • git diff --stat b7c933e795f2fee3e744e0a44f32c5038378d58a..a84850ccb01462c9cdb54aef35c9829eb3a7a28a
  • git diff --name-status b7c933e795f2fee3e744e0a44f32c5038378d58a..a84850ccb01462c9cdb54aef35c9829eb3a7a28a
  • git log --oneline --decorate --max-count=12
  • tests/fm-secondmate.test.sh 2>&1 | tee /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KVRF3YFM70QS6FYR19KAXZSN/fm-secondmate.test.log
  • tests/fm-spawn-batch.test.sh 2>&1 | tee /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KVRF3YFM70QS6FYR19KAXZSN/fm-spawn-batch.test.log
  • tests/fm-wake-queue.test.sh 2>&1 | tee /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KVRF3YFM70QS6FYR19KAXZSN/fm-wake-queue.test.log
  • tests/fm-afk-inject-e2e.test.sh 2>&1 | tee /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KVRF3YFM70QS6FYR19KAXZSN/fm-afk-inject-e2e.test.log
  • Manual CLI demo: seeded a secondmate route with fm-home-seed.sh, spawned it with fm-spawn.sh --secondmate through fake tmux, and captured registry, marker, meta, and launch transcript in secondmate-cli-demo.log.
  • git status --short
✅ **Document** - passed

✅ No issues found.

⚠️ **Lint** - 1 warning
  • ⚠️ .github/workflows/ci.yml:18 - Configured CI linter shellcheck bin/*.sh tests/*.sh could not be run because no shellcheck executable is available on PATH or in standard local tool paths.
✅ **Push** - passed

✅ No issues found.

@kunchenguid kunchenguid changed the title feat: support persistent sub-firstmates feat: support scoped persistent sub-firstmates Jun 22, 2026
@kunchenguid kunchenguid changed the title feat: support scoped persistent sub-firstmates feat: support persistent sub-firstmate routing Jun 22, 2026
iscooter added a commit to iscooter/firstmate that referenced this pull request Sep 21, 2026
…gates

Fourteen tasks, TDD throughout. Task 0 captures the real PRs kunchenguid#27, kunchenguid#32
and kunchenguid#37 as fixtures first, so every gate is written against genuine
GitHub payloads rather than imagined ones — those three give a full
pass, a classification rejection, and a non-bot rejection.

Task 1 proves the deploy gate by breaking the rules file on purpose and
watching the build fail, rather than asserting it works.

Glob matching gets its own task: only three pattern forms are used, so
a dependency is not worth it, but a subtly wrong inlined matcher fails
open on exactly the path rules that matter.

Rendering is split from the gate logic because PLAT-1190's readability
criterion is a human judgement and deserves its own review surface —
Task 8 ends by printing all three rationales to read as a stranger.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
NewAiCoder added a commit to NewAiCoder/firstmate that referenced this pull request Sep 26, 2026
…ror (kunchenguid#37)

* fix(nm-state-condition): treat no run yet as a clean false, not an error

fm-nm-state-condition.sh returned exit 2 (error) whenever the watched
clone or worktree had no no-mistakes run yet (repo not initialized
there), so a watch armed before the first run died with condition-error
after 3 polls. The pre-run state is now a sentinel projection distinct
from every real run state, so it reads as a clean false on every poll
and still fires the moment a real run appears.

* no-mistakes(document): docs(configuration): note no-run is a clean false, not error

* no-mistakes(lint): fix(test): quote printf format to satisfy shellcheck SC2016

---------

Co-authored-by: NewAiCoder <170579485+NewAiCoder@users.noreply.github.com>
NewAiCoder added a commit to NewAiCoder/firstmate that referenced this pull request Sep 26, 2026
…ror (kunchenguid#37)

* fix(nm-state-condition): treat no run yet as a clean false, not an error

fm-nm-state-condition.sh returned exit 2 (error) whenever the watched
clone or worktree had no no-mistakes run yet (repo not initialized
there), so a watch armed before the first run died with condition-error
after 3 polls. The pre-run state is now a sentinel projection distinct
from every real run state, so it reads as a clean false on every poll
and still fires the moment a real run appears.

* no-mistakes(document): docs(configuration): note no-run is a clean false, not error

* no-mistakes(lint): fix(test): quote printf format to satisfy shellcheck SC2016

---------

Co-authored-by: NewAiCoder <170579485+NewAiCoder@users.noreply.github.com>
NewAiCoder added a commit to NewAiCoder/firstmate that referenced this pull request Oct 1, 2026
…ror (kunchenguid#37)

* fix(nm-state-condition): treat no run yet as a clean false, not an error

fm-nm-state-condition.sh returned exit 2 (error) whenever the watched
clone or worktree had no no-mistakes run yet (repo not initialized
there), so a watch armed before the first run died with condition-error
after 3 polls. The pre-run state is now a sentinel projection distinct
from every real run state, so it reads as a clean false on every poll
and still fires the moment a real run appears.

* no-mistakes(document): docs(configuration): note no-run is a clean false, not error

* no-mistakes(lint): fix(test): quote printf format to satisfy shellcheck SC2016

---------

Co-authored-by: NewAiCoder <170579485+NewAiCoder@users.noreply.github.com>
fritznoff pushed a commit to fritznoff/starship that referenced this pull request Nov 2, 2026
* Add rival-model second-opinion convergent checker front-end.

Productize a bounded Pi/sol hostile-review wrapper and second-opinion-auto-fire
skill as the convergent counterpart to ADHD, including neutral-cwd enforcement
and a Codex quota floor.

* fix: mark fm-second-opinion.test.sh executable for CI.

CI runs tests/*.test.sh directly; without +x the suite exits 126.
fritznoff pushed a commit to fritznoff/starship that referenced this pull request Nov 18, 2026
…kunchenguid#37)

* fix(bin): name the no-mistakes handoff done and show each test lane's time against its limit

The no-mistakes definition of done said "The task is complete only when
committed on your branch" and asked for a plain `done:` at that point, the
designed handoff that lets firstmate send the pipeline trigger. Workers
followed it, and the current-state reader then reported the handoff as
`state: done` (READY in the fleet view), so a committed, unvalidated build
read as a finished one and was answered as a premature finish.

- Every no-mistakes DoD variant now says a commit finishes the
  implementation, not the task, and asks for
  `done: handoff, ready for no-mistakes - {summary}`, which never reports
  the task finished.
- fm_dod_nm_handoff_done names a mode=no-mistakes ship done that is not the
  ready report, and fm-crew-state.sh reads it blocked as a handoff waiting
  for the pipeline trigger instead of done.
- Each CI test lane records its own tripwire as --max-wall-ms, the timing
  JSON keeps it, and --aggregate-json prints every lane's duration against
  that limit, flagging and annotating any lane within 15 percent of it.

* fix(bin): keep a no-mistakes handoff off the parent channel and add the lane table to the run summary

The secondmate ledger path no longer reports a child's no-mistakes handoff
done upstream as a finished child; it owes nothing until the child reports
its PR. The timing aggregate also appends its per-lane table to
GITHUB_STEP_SUMMARY so each run's summary page shows every lane's time
against its limit.

* no-mistakes(review): Name unconfirmed PRs, assert no stray summary, merge guards

* no-mistakes(review): Read only PR-report notes as PRs; keep fixture tables off CI

* no-mistakes(test): Align secondmate ledger fixtures with the no-mistakes handoff rule

* no-mistakes(document): Document handoff coverage and hc lane timing upload

* no-mistakes(lint): Quote done literal in inactive-reconcile test for ShellCheck

* no-mistakes(ci): Fixed. The cause was two test fixtures, not a bug in the change. Both still modelled a finished no-mistakes ship as a bare `done: complete`. Under this PR's handoff contract (fm_dod_nm_handoff_done), that line is the pipeline handoff, so the reader correctly reports it `blocked`, never `done`. The tests expected `terminal_in_flight` with `<id>=done`, so they failed: - "ordinary terminal in-flight ship must still produce terminal_in_flight..." in tests/fm-fleet-snapshot-view.test.sh. This failed the Stock macOS Bash snapshot compatibility job and Behavior portable serial 11. - "terminal in-flight rows discarded the readable home" in tests/fm-bearings-snapshot.test.sh (test_nonprogressing_child_states_are_explicit). This also failed Behavior portable serial 11. - Full suite is only the aggregate gate, so it failed because those lanes did. Invariant: a no-mistakes ship counts as terminal-done only at its green-PR ready report, with the named head reachable outside the worker copy. Earlier commit 8ff478e6 already aligned the inactive-reconcile fixtures to this rule. These two were the only remaining no-mistakes ship fixtures that used a bare done. Other `done:` fixtures in these files have no mode or a different mode, so the handoff reading does not apply to them. Fix, tests only, no production code: each of the two fixtures now creates its worktree as a git copy (fm_git_init_commit), points `refs/remotes/origin/main` at HEAD, and writes `done: PR https://github.com/acme/<repo>/pull/7 checks green`. Each gets a short comment explaining why. Verification (all reproduced first, then re-run after the fix): - Both failures reproduced locally before the fix. - After the fix, tests/fm-fleet-snapshot-view.test.sh passed 18/18 three times in a row. - tests/fm-bearings-snapshot.test.sh: test_nonprogressing passes. Every other test passes too (24 in the full run plus the remaining 37 run separately), except the two that need tasks-axi, which is not on PATH here (CI has it). - ShellCheck is clean on both files. Unrelated flakes seen locally, not caused by this change and not touched: - tests/fm-bearings-snapshot.test.sh test_remote_ledgers_share_one_concurrent_budget... failed once in a full run, then passed alone. It passed in CI. - tests/fm-fleet-snapshot-view.test.sh test_completed_scout_report_is_pointer_not_pending failed once, then passed in the next three full runs. Its fixtures record no mode, so the handoff change cannot reach it
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