Skip to content

feat(cmux): secondmate support with per-home workspaces and id-primary title-sync recovery - #22

Merged
egarlock merged 2 commits into
mainfrom
fm/fm-cmux-secondmate-v9
Jul 28, 2026
Merged

egarlock merged 2 commits into
mainfrom
fm/fm-cmux-secondmate-v9

Conversation

@egarlock

Copy link
Copy Markdown
Owner

Intent

Add cmux secondmate support to firstmate in one PR: lift bin/fm-spawn.sh's backend=cmux --secondmate refusal behind the captain-resolved per-home design (2026-07-27). Design as directed: (1) one dedicated cmux workspace per secondmate at the mate's home - never a tab in the primary's workspace in any container mode - with the mate's own crew tabs landing in ITS workspace; (2) workspace identity is ID-primary with synced-title recovery so the captain can freely retitle the mate's workspace: recorded workspace/surface UUIDs are the live handle, the meta records the last-synced title (cmux_workspace_title=), every liveness touch re-syncs it by id, relaunch recovery matches the recorded title then the scoped tab title then a passive home-cwd fingerprint (tty+ps+lsof, never the active typing probe), and any rung with multiple candidates refuses loudly with candidates rather than guessing or claiming another home's workspace; (3) a real cmux agent-liveness classifier for fm_backend_agent_alive so the session-start sweep respawns confidently; (4) a new config/secondmate-backend knob mirroring config/secondmate-harness (captain scope addition 2026-07-26); (5) docs replace the known-gap with the design and evidence. The task MANDATED re-verifying workspace-id persistence against the CURRENTLY INSTALLED cmux from shipped source only, never relaunching the captain's live app: done against 0.64.20 build 100 commit 14e3400b95 - socket-reported ids are still re-minted per launch (a new restart-stable stableId exists but the control API returns workspace.id, a let set once in the sole init), while workspace AND tab custom titles ARE restored - so the title-sync branch of the design was implemented as the task directed for that outcome. Deliberate decisions a diff-only reviewer might flag: the mate workspace's INITIAL title is the mate home's own fm- (fm-2ndmate--<8hex>), computed with FM_HOME and FM_ROOT both shadowed to the mate home so it is byte-identical to what the mate's own processes derive - it deliberately doubles as the mate home's tab-mode shared container; the mate's tab is renamed to the PRIMARY's scoped task title so existing target_ready label recovery serves send/peek/watch unchanged; agent_alive classifies EVERY process on the surface's tty (not the last foreground entry) so a live agent's tool child never misreads as a dead shell, counts cmux's resident /usr/bin/login wrapper as plumbing, and calls a down socket confidently dead because no cmux-hosted pty survives the app; the resolver's rc convention is 0 resolved / 2 definitively gone (the sweep's confident-dead reading) / 3 ambiguous (never acted on) / 1 uninspectable; orca stays refused via the new FM_BACKEND_SECONDMATE_SPAWN list which centralizes the per-backend secondmate capability; config/secondmate-backend deliberately outranks FM_BACKEND for secondmate spawns (it is the more specific knob, documented in docs/configuration.md) and a respawn reuses the mate's meta-recorded backend so a later config change never migrates an existing mate; the bootstrap sweep now resolves each mate's endpoint before probing (pass-through for non-cmux) and kills through a new fm_backend_secondmate_kill dispatcher whose default arm uses the teardown-shaped call (target + zellij tab + fm- label - strictly more scoped than the sweep's previous bare kill, byte-identical for tmux/herdr); teardown routes secondmate endpoint kills through that dispatcher and cmux joins zellij's FM_HOME/FM_ROOT-shadowed child-kill branch because cmux titles are home-scoped; .gitignore gains config/secondmate-backend and also fixes the pre-existing missing config/cmux-container entry; tests add a STATEFUL fake-cmux lib (tests/cmux-fake-lib.sh) because the multi-phase create-resolve-kill-respawn flows outgrow the ordered canned-response fake, and the cmux test-safety guards became window-agnostic plus gained a secondmate-shaped close after a live incident where the captain closed the macOS window holding fm-test workspaces mid-run; the smoke suite gained a real-app secondmate section using only test-marked scratch homes. Constraints honored: firstmate-coding-guidelines (one sentence per line, bin/fm-lint.sh shellcheck-clean at rc=0, colocated tests extending existing suites, one-owner cross-references), cmux live-testing safety (only fm-test-/fm-2ndmate-test- artifacts, no enumerate-and-close, the captain's app never quit/relaunched/reconfigured, zero residue verified), and no real secondmate homes against the captain's fleet - live verification used throwaway scratch homes, including a full real pass: spawn via the knob, alive against a real claude, /exit to dead, a real bootstrap sweep silently closing and respawning the mate with fresh ids re-recorded, and the meta-driven kill. Known pre-existing issue left untouched: tests/fm-bootstrap.test.sh's treehouse-lease case fails identically on base HEAD on machines running inside cmux (unpinned backend auto-detects cmux via ancestry); not introduced by this change. A prior pipeline run on this exact HEAD completed review with zero findings and tests with one info finding, then failed only because the machine lost network during the document step; this is the fresh rerun after connectivity returned.

What Changed

  • Lifted bin/fm-spawn.sh's backend=cmux --secondmate refusal and added a full cmux secondmate backend (bin/backends/cmux.sh, bin/fm-backend.sh): each secondmate gets one dedicated cmux workspace at the mate's own home (never a tab in the primary's workspace), with workspace identity kept as recorded ID-primary plus a synced cmux_workspace_title= — every liveness touch re-syncs the title by id, and relaunch recovery falls back from recorded title to scoped tab title to a passive tty/ps/lsof home-cwd fingerprint, refusing loudly with candidates on any ambiguous match.
  • Added a real cmux agent-liveness classifier for fm_backend_agent_alive (classifies every process on the surface's tty, treats cmux's /usr/bin/login wrapper as plumbing, and calls a down socket confidently dead) driving the bootstrap sweep (bin/fm-bootstrap.sh), plus a new fm_backend_secondmate_kill dispatcher wired through bin/fm-teardown.sh; introduced the config/secondmate-backend knob (outranking FM_BACKEND for secondmate spawns, respawns reuse the meta-recorded backend) with orca still refused via a centralized FM_BACKEND_SECONDMATE_SPAWN capability list, and added config/secondmate-backend and the missing config/cmux-container to .gitignore.
  • Added a stateful fake-cmux test lib (tests/cmux-fake-lib.sh) for the multi-phase create/resolve/kill/respawn flows, extended the cmux/backend/bootstrap/secondmate-liveness suites, added a real-app secondmate smoke section using only test-marked scratch homes, hardened the cmux test-safety guards to be window-agnostic, and updated the cmux/configuration/architecture docs to replace the known-gap note with the implemented design and installed-cmux (0.64.20) id-persistence evidence.

Risk Assessment

✅ Low: The change is large but well-bounded behind an experimental, opt-in cmux backend and --secondmate mode; all default-tmux and non-secondmate paths are byte-preserved, the new logic matches every required intent constraint, and tracing the resolver, teardown, sweep, and shared-helper interactions surfaced no reachable defect or invariant violation.

Testing

Baseline unit and e2e suites plus a real-app smoke run all pass on the secondmate intent. The strongest evidence is tests/fm-backend-cmux-smoke.test.sh, which drives the actual installed cmux app through the complete secondmate lifecycle (dedicated mate-home workspace, id-primary identity with synced-title/last-title/home-cwd-fingerprint recovery, real agent-liveness classification, and identity-checked idempotent kill) — 26/26 passing — and the liveness sweep, backend-dispatch, lifecycle, and bootstrap suites confirm the resolver rc convention, config/secondmate-backend precedence, and orca refusal. This is a CLI/backend change with no rendered UI surface, so the reviewer-visible artifacts are the real-cmux CLI transcript and test-name transcripts (saved to the evidence dir) rather than screenshots. The only failing check is a pre-existing, environment-locale-only glyph-strip quirk in bin/fm-composer-lib.sh that is byte-identical to base and passes under a UTF-8 locale; it is unrelated to this change and does not affect the secondmate feature. Worktree left clean.

Evidence: Real installed-cmux secondmate smoke transcript (26/26 pass)

ok - real cmux: create_secondmate makes a dedicated workspace at the mate home with the scoped tab title ok - real cmux: secondmate_resolve confirms a live recorded endpoint by id ok - real cmux: a captain retitle is synced into the durable record on the next supervision touch ok - real cmux: stale recorded ids recover by last-synced title and re-record the live ids ok - real cmux: agent_alive reads the surface tty's processes and calls a bare shell confidently dead ok - real cmux: the home-cwd fingerprint recovers a mate whose titles were all lost, without typing into any terminal ok - real cmux: secondmate kill closes the mate's whole workspace via identity checks and is idempotent

ok - real cmux: create_task creates a workspace/surface and refuses a duplicate title
ok - real cmux: expected task label verification accepts the matching workspace and rejects a mismatch
ok - real cmux: send_literal (unsubmitted) + send_key Enter submit as two steps and the output is capturable
ok - real cmux: send_text_line composes send+Enter and its output is capturable
ok - real cmux: current_path reads the surface's live cwd after a direct cd
ok - real cmux: current_path tracks a NESTED SUBSHELL's own cd (the treehouse-get-shaped case a bare cwd read cannot see)
ok - real cmux: send_key Escape (natively supported, unlike Orca) succeeds
ok - real cmux: send_key C-c (normalized to the verified 'ctrl-c' name) succeeds
ok - real cmux: fm_backend_busy_state reports unknown (watcher falls back to pane-regex, same as tmux/zellij/orca)
ok - real cmux: window_of_workspace locates a task workspace's window and counts its workspaces
ok - real cmux: kill removes the whole workspace and is idempotent/best-effort
ok - real cmux: list_live discovers a live task workspace by fm-<id> title
ok - real cmux: tab-mode create_task creates a focused tab in the container, restores focus, and returns '<ws> <surface>'
ok - real cmux: the task tab carries its scoped fm-<home>-<id> title (sticky rename)
ok - real cmux: tab-mode create_task refuses a duplicate scoped tab title
ok - real cmux: label-verified send and capture work against the task tab
ok - real cmux: current_path reports the task tab's own cwd (passive tiers), not the container's
ok - real cmux: list_live discovers a live task tab (tab arm) alongside task workspaces
ok - real cmux: tab-mode kill closes only the task's surface and leaves the container workspace alive
ok - real cmux: create_secondmate makes a dedicated workspace at the mate home with the scoped tab title
ok - real cmux: secondmate_resolve confirms a live recorded endpoint by id
ok - real cmux: a captain retitle is synced into the durable record on the next supervision touch
ok - real cmux: stale recorded ids recover by last-synced title and re-record the live ids
ok - real cmux: agent_alive reads the surface tty's processes and calls a bare shell confidently dead
ok - real cmux: the home-cwd fingerprint recovers a mate whose titles were all lost, without typing into any terminal
ok - real cmux: secondmate kill closes the mate's whole workspace via identity checks and is idempotent
Evidence: Secondmate liveness + sweep test names (15/15 pass)
ok - fm_backend_tmux_agent_alive: alive/dead/unknown classification
ok - fm_backend_herdr_agent_alive: dead/no-agent->dead, live->alive, unknown->unknown
ok - fm_backend_cmux_agent_alive: alive/dead/unknown classification (tool children never read as dead)
ok - fm_backend_agent_alive: routes tmux/herdr/cmux correctly, unknown for an unverified backend
ok - sweep: a confirmed-dead secondmate endpoint is killed and respawned
ok - sweep: an already-live secondmate is left untouched (no kill, no respawn)
ok - sweep: a transient/unknown probe reading is reported but never acted on
ok - sweep: an unverified harness makes a dead-looking probe inconclusive
ok - sweep: idempotent by construction - a live secondmate is never re-touched on a later run
ok - sweep: skipped entirely under FM_BOOTSTRAP_DETECT_ONLY=1, exactly like the other mutating sweeps
ok - sweep: a silent no-op with no kind=secondmate meta present (a secondmate home's own natural scoping)
ok - sweep: a dead cmux mate is title-synced, its workspace closed, and respawned into a fresh workspace
ok - sweep: an alive cmux mate is left running and its captain retitle is synced (freely retitlable)
ok - sweep: an ambiguous cmux endpoint refuses - no kill, no respawn, loud skip
ok - sweep: a definitively gone cmux endpoint is the confident dead reading and respawns
Evidence: config/secondmate-backend knob (docs) + .gitignore fixes
== config/secondmate-backend knob (docs + .gitignore) ==
+A `--secondmate` spawn resolves its backend separately: an explicit `--backend` still always wins, a respawn reuses the backend recorded in the mate's existing `state/<id>.meta` so a mate stays on its recorded backend across recovery and restarts, then the first non-empty line of local gitignored `config/secondmate-backend` applies when it is not `default`, and only then does the shared chain above take over (`fm_backend_secondmate_name` in `bin/fm-backend.sh`).
+`config/secondmate-backend` mirrors `config/secondmate-harness`: it is the primary's own setting, never inherited into secondmate homes, and when present it outranks `FM_BACKEND` and `config/backend` for secondmate spawns because it is the more specific knob.
+The `config/backend`, `config/secondmate-backend`, and `config/cmux-container` files are not inherited by secondmate homes.

== .gitignore additions ==
diff --git a/.gitignore b/.gitignore
index 5bf847c..ab227dd 100644
--- a/.gitignore
+++ b/.gitignore
@@ -11,8 +11,10 @@ __pycache__/
 config/crew-harness
 config/crew-dispatch.json
 config/secondmate-harness
+config/secondmate-backend
 config/backlog-backend
 config/backend
+config/cmux-container
 config/x-mode.env
 config/cmux-socket-password
 config/wedge-alarm
- Outcome: ⚠️ 1 info across 1 run (7m20s)

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
  • ℹ️ bin/fm-composer-lib.sh:215 - tests/fm-backend-cmux.test.sh's fm_backend_cmux_composer_state: the ghost placeholder text reads empty case fails under the harness's default empty/C locale (LANG/LC_ALL unset): ${content#??} in bin/fm-composer-lib.sh strips 2 bytes of the 3-byte '❯' glyph, leaving a stray byte so 'Type a message...' is misread as 'pending'. This is pre-existing and NOT introduced by this change (fm-composer-lib.sh, the cmux composer_state function, and this test case are all byte-identical to base 803fa7b), and it disappears when the suite runs under a UTF-8 locale (whole file passes, exit 0). Reported for transparency; unrelated to the secondmate intent.
  • bash tests/fm-backend-cmux-smoke.test.sh — 26/26 real-installed-cmux checks incl. the new secondmate section (create_secondmate, resolve-by-id, captain-retitle sync, stale-id title recovery, home-cwd fingerprint recovery, agent_alive, identity-checked kill)
  • bash tests/fm-secondmate-liveness.test.sh — 15/15 (cmux agent_alive classifier + sweep: dead→respawn, alive→untouched, ambiguous→loud refuse, definitively-gone→confident dead)
  • bash tests/fm-backend.test.sh — 31/31 (secondmate backend resolution, config/secondmate-backend precedence, validate_secondmate_spawn orca refusal, resolve/kill dispatcher)
  • bash tests/fm-secondmate-lifecycle-e2e.test.sh — 6/6
  • bash tests/fm-backend-cmux.test.sh — 42/43 under empty locale; 43/43 under LANG=en_US.UTF-8 (sole failure is the pre-existing locale glyph-strip quirk)
  • bash tests/fm-bootstrap.test.sh — 22/22 (not running inside cmux here, so the author's known cmux-ancestry case does not trigger)
  • bash tests/cmux-test-safety.sh — exit 0
  • Confirmed via git diff 803fa7b b766d2a that fm-composer-lib.sh and the failing composer test case are unchanged by this PR
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

egarlock and others added 2 commits July 27, 2026 16:50
Lifts the backend=cmux --secondmate refusal behind the captain-resolved
per-home design (2026-07-27): one dedicated workspace per mate, freely
retitlable by the captain without breaking supervision or recovery.

- bin/backends/cmux.sh: fm_backend_cmux_create_secondmate (dedicated
  workspace at the mate home, initial fm-2ndmate-<id>-<8hex> title that
  doubles as the mate home's tab-mode container, scoped tab rename),
  fm_backend_cmux_secondmate_resolve (id-primary handle; title sync on
  every liveness touch; relaunch recovery by last-synced title, then the
  scoped tab title, then a passive home-cwd fingerprint; ambiguity
  refuses loudly with candidates and never claims another home's
  workspace), fm_backend_cmux_secondmate_kill (whole-workspace close
  through those same identity checks), and fm_backend_cmux_agent_alive
  (a real tty-process classifier: harness names alive, shells-and-login
  only dead, everything else unknown; tool children never misread as a
  dead shell).
- bin/fm-backend.sh: FM_BACKEND_SECONDMATE_SPAWN + validate helper (orca
  keeps refusing), fm_backend_secondmate_name (config/secondmate-backend
  knob mirroring config/secondmate-harness), agent-alive cmux arm, and
  fm_backend_secondmate_resolve/kill dispatchers whose default arms keep
  every non-cmux backend byte-compatible.
- bin/fm-spawn.sh: secondmate backend resolution (explicit --backend,
  then the meta-recorded backend on a respawn, then the knob, then the
  shared chain), the cmux secondmate create arm, and the
  cmux_workspace_title= meta field.
- bin/fm-bootstrap.sh: the liveness sweep resolves each mate's endpoint
  first (cmux title sync + relaunch re-record), treats a definitively
  gone endpoint as the confident dead reading, skips ambiguous ones, and
  validates config/secondmate-backend (BACKEND_INVALID).
- bin/fm-teardown.sh: secondmate endpoints go through the meta-driven
  kill; cmux joins zellij's home-shadowed child-kill branch.
- Workspace-id persistence re-verified from the shipped 0.64.20 (build
  100) source: socket-reported ids are still re-minted per launch (the
  new restart-stable stableId is not what the control API returns), while
  workspace and tab custom titles ARE restored - docs/cmux-backend.md
  records the evidence, the design, and the full live pass against the
  real app (spawn, alive/dead probe, sweep kill+respawn, kill, zero
  residue).
- Tests: stateful fake-cmux lib (tests/cmux-fake-lib.sh), secondmate
  create/resolve/fingerprint/ambiguity/kill and fm-spawn e2e units,
  cmux agent-alive and sweep coverage, backend-knob and dispatcher units,
  bootstrap validation, real-app smoke section, and window-agnostic
  test-safety guards with a secondmate-shaped close.

Claude-Session: https://claude.ai/code/session_01XMXcwZi5RuChS7cAcVrprS
@egarlock
egarlock merged commit d17bf3c into main Jul 28, 2026
10 of 11 checks passed
egarlock added a commit that referenced this pull request Jul 28, 2026
…secondmate workspaces (#23)

A captain-renamed secondmate workspace broke every label-gated operation
(fm-send, fm-peek, fm-crew-state, and the bootstrap liveness sweep's
agent_alive probe): fm_backend_cmux_target_ready required the workspace or
surface title to equal the generated scoped title, but PR #22 made
secondmate workspace titles free-form, and the agent's own terminal-title
updates overwrite the scoped tab title too, so both title rungs missed even
though fm_backend_cmux_secondmate_resolve returned the correct endpoint.

target_ready now detects a kind=secondmate meta behind the expected label
and delegates identity to the resolver (recorded ids, synced recorded
title, scoped tab title, home-cwd fingerprint, loud ambiguity refusal),
adopting only the resolved endpoint - never the caller's unverified target.
Ordinary task targets keep the scoped-title gate unchanged.

Verified live 2026-07-28 against cmux 0.64.20 (build 100) and the fleet's
two renamed mates, read-only with scratch meta copies: unpatched
target_ready rc 1 / agent_alive unknown; patched target_ready resolves the
recorded endpoint, agent_alive reads alive, capture returns real pane
content. Full real-app smoke suite passes on the patched adapter.

Claude-Session: https://claude.ai/code/session_016YqtswHeV9YSLAJVLyk5gs

Co-authored-by: Eric Garlock <[email protected]>
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