Skip to content

feat(backends): improve cmux detection and socket-mode guidance - #259

Merged
kunchenguid merged 4 commits into
mainfrom
fm/cmux-backend-w3
Jul 4, 2026
Merged

kunchenguid merged 4 commits into
mainfrom
fm/cmux-backend-w3

Conversation

@kunchenguid

Copy link
Copy Markdown
Owner

Intent

Two related improvements to firstmate's experimental cmux backend, one branch, one PR, per the captain's direction. Workstream A: cmux's bundled claude wrapper (cmux-claude-wrapper, resolved via a PATH shim in cmux tabs) strips every CMUX_* env var on its passthrough path before exec'ing the real claude binary - verified live on this machine 2026-07-04 against cmux 0.64.17 (the wrapper's unauthenticated 0.75s socket ping always fails under password mode, forcing the stripping passthrough path; reproduced with a fake claude binary dumping its env). So a claude-harness firstmate launched inside cmux can never auto-detect cmux from CMUX_WORKSPACE_ID. Fix per the captain: fm_backend_detect keeps CMUX_WORKSPACE_ID as the primary marker and adds two macOS-only fallback signals consulted only when it is absent - (1) __CFBundleIdentifier == com.cmuxterm.app (survives the wrapper strip), (2) a process-ancestry walk reaching the running cmux app, resolved by bundle id via lsappinfo with a bundle-shaped ps comm match as fallback so the install path is never hardcoded. Innermost-first ordering (TMUX, then HERDR_ENV, then cmux) is deliberately preserved: a tmux server started from a cmux tab inherits the bundle id into every pane, so TMUX winning first absorbs that false positive (tested), and ancestry structurally cannot reach cmux from inside tmux because the tmux server reparents to launchd (verified live). The auto-detected-cmux stderr NOTICE now names the winning fallback signal. New globals FM_BACKEND_DETECTED/FM_BACKEND_DETECT_SIGNAL are set by fm_backend_detect for callers invoking it directly (fm_backend_name now calls it without command substitution to read them); the stdout contract is unchanged for existing callers. Workstream B: the captain finds the previously-required Password socket mode unnecessarily frictional and asked for the full five-mode Socket Control Mode matrix from cmux source plus a recommendation. Traced through github.com/manaflow-ai/cmux at commit 9c91710e3f58 (cloned read-only as scratch, never pushed): off = no listener; cmuxOnly (default) = connect-time peer-pid ancestry check, never admits external CLIs; automation = same-user external clients admitted with no secret (0600 socket file is the only gate, no verb restrictions); password = auth handshake; allowAll = 0666 world-open socket. Recommendation is Automation mode - same effective same-user boundary as password mode on a single-user machine without the shared-secret friction; password stays supported via config/cmux-socket-password/CMUX_SOCKET_PASSWORD; allowAll documented as an explicit not-recommended trade-off (upstream itself labels it unsafe). This matched the captain's stated hypothesis so no needs-decision escalation was warranted. Adapter changes are deliberately minimal: refusal messages factored into fm_backend_cmux_refuse_denied/unauth helpers naming all viable modes plus the recommended one, 'Invalid password' now classifies as unauth, and the launch-timeout message names the off-mode possibility; no probe of the running app was added for the off case because off is indistinguishable on the wire from app-not-running. Constraints honored: the captain's live cmux app (Password mode) was never reconfigured, ~/.config/cmux/cmux.json never written, live verification was read-only, and automation/allowAll/off semantics are labeled 'verified from source, not live' in docs/cmux-backend.md per that doc's existing posture. Docs: cmux-backend.md Setup rewritten around the matrix with the recommendation and rationale, a new wrapper-strip empirical record (date, version, exact commands, output) and fallback-contract subsections under Runtime auto-detection, and the socket section retitled/expanded with the source-traced enforcement points; configuration.md's stale password-mode sentence updated; AGENTS.md got exactly two one-line cross-reference fixes per the one-owner rule (the fm-spawn usage line's stale 'password-mode setup' and the section-7 marker enumeration pointing at the docs for the fallback). Tests extend the existing patterns: fm-backend.test.sh gains PATH-faked uname/lsappinfo/ps helpers so all fallback paths (bundle id, non-Darwin guard, tmux/herdr-nested false positive, ancestry pid match, ancestry comm match, launchd stop, fallback NOTICE wording) are deterministic on any host, and pre-existing no-detection assertions now also neutralize the new inputs; fm-backend-cmux.test.sh gains Invalid-password classification and denied/unauth refusal-wording tests. Repo style followed: firstmate-coding-guidelines loaded first, one sentence per line in Markdown, plain dashes, shellcheck bin/.sh bin/backends/.sh tests/*.sh passes, and the full 44-suite test run passes.

What Changed

  • Added cmux backend auto-detection fallbacks for macOS bundle ID and process ancestry while preserving tmux and herdr precedence and the existing stdout detection contract.
  • Refined cmux socket-mode handling with clearer denied, unauthenticated, invalid-password, and off-mode timeout guidance, including support for the Automation-mode recommendation.
  • Updated cmux/backend documentation and expanded backend tests to cover fallback signals, precedence, refusal wording, and cmux password classification.

Risk Assessment

✅ Low: Captain, the change is confined to the experimental cmux backend and its documentation/tests, and I found no material merge-blocking risks in the new fallback detection or socket-mode handling.

Testing

Captain, the pre-run full-suite baseline was already green, I reran the two focused backend suites successfully, then captured a CLI transcript showing the changed cmux detection and socket-mode user-facing behavior. No UI screenshot was captured because this change is backend/CLI-facing, and no transient working-tree artifacts were left behind.

Evidence: cmux backend CLI evidence

## cmux auto-detection fallback from __CFBundleIdentifier when CMUX_WORKSPACE_ID is absent
exit: 0
stdout:
  cmux
stderr:
  NOTICE: auto-detected cmux runtime (FALLBACK signal __CFBundleIdentifier=com.cmuxterm.app; CMUX_WORKSPACE_ID absent, stripped by cmux's bundled claude wrapper) - spawning into the EXPERIMENTAL cmux backend. Set config/backend or pass --backend tmux to opt out.

## tmux marker wins over inherited cmux bundle-id false positive
exit: 0
stdout:
  tmux
stderr:
  <empty>

## cmux auto-detection fallback from process ancestry when CMUX_WORKSPACE_ID and bundle id are absent
exit: 0
stdout:
  cmux
stderr:
  NOTICE: auto-detected cmux runtime (FALLBACK signal process-ancestry reaching the running cmux app; CMUX_WORKSPACE_ID absent, stripped by cmux's bundled claude wrapper) - spawning into the EXPERIMENTAL cmux backend. Set config/backend or pass --backend tmux to opt out.

## cmux Invalid password is classified as unauth and produces actionable Automation-mode guidance
exit: 1
stdout:
  ping-state=unauth
stderr:
  error: backend=cmux socket requires a password (automation.socketControlMode=password) but none is configured for this caller, or the configured one was rejected. Set config/cmux-socket-password or export CMUX_SOCKET_PASSWORD to the password from cmux Settings > Automation, or switch Socket Control Mode to 'Automation mode' (recommended - no password needed) - see docs/cmux-backend.md 'Setup' - or set config/backend to tmux (or pass --backend tmux) if you did not mean to use cmux.

## cmux launch timeout names Socket Control Mode Off as a likely cause
exit: 1
stdout:
  <empty>
stderr:
  error: cmux did not become reachable within 10s of launch. If the app is already running, its Socket Control Mode may be 'Off' (no control socket at all) - set it to 'Automation mode' (recommended) in Settings > Automation, see docs/cmux-backend.md 'Setup'.

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 1 issue found → auto-fixed (2) ✅
  • ℹ️ docs/configuration.md:24 - The runtime-backend overview is now incomplete: it still describes auto-detection as only $TMUX/HERDR_ENV=1/CMUX_WORKSPACE_ID, but this branch adds cmux fallback detection via __CFBundleIdentifier and process ancestry. Add a short cmux fallback cross-reference here so operators understand why cmux can be selected when CMUX_WORKSPACE_ID is absent.

🔧 Fix: Document cmux fallback detection
1 info still open:

  • ℹ️ docs/architecture.md:49 - The architecture overview still describes cmux auto-detection as only CMUX_WORKSPACE_ID and still calls the setup requirement password-mode, which now contradicts the new fallback detection path and Automation-mode recommendation. Update this summary to match docs/cmux-backend.md and docs/configuration.md so operators do not follow stale backend guidance.

🔧 Fix: Update cmux architecture docs
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • command -v tmux >/dev/null || { echo "tmux is required for e2e tests" >&2; exit 1; }; tmux -V; rc=0; for t in tests/*.test.sh; do echo "== $t =="; bash "$t" || rc=1; done; exit "$rc"
  • Baseline already reported successful before this validation: command -v tmux &gt;/dev/null || { echo &#34;tmux is required for e2e tests&#34; &gt;&amp;2; exit 1; }; tmux -V; rc=0; for t in tests/*.test.sh; do echo &#34;== $t ==&#34;; bash &#34;$t&#34; || rc=1; done; exit &#34;$rc&#34;
  • bash tests/fm-backend.test.sh
  • bash tests/fm-backend-cmux.test.sh
  • Created CLI evidence transcript at /var/folders/5x/4nqprlbx0518k3ybcb1sz6gr0000gn/T/no-mistakes-evidence/01KWQH57J46SVP6AH6PPDD69MG/cmux-backend-cli-evidence.txt covering cmux bundle-id fallback, process-ancestry fallback, tmux precedence, Invalid password classification, and off-mode timeout guidance.
  • git status --short
  • find . -maxdepth 2 \( -name '.pytest_cache' -o -name 'node_modules' -o -name 'coverage' -o -name 'dist' -o -name 'build' -o -name '*.tmp' \) -print
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

Workstream A: cmux's bundled claude wrapper strips every CMUX_* env var on
its passthrough path (reproduced live 2026-07-04, cmux 0.64.17), so a
claude-harness firstmate inside a cmux tab has no CMUX_WORKSPACE_ID.
fm_backend_detect now falls back - macOS-only, only when the primary marker
is absent - to __CFBundleIdentifier=com.cmuxterm.app and then a process
ancestry walk resolved by bundle id (lsappinfo) plus a bundle-shaped ps comm
match. Innermost-first ordering is unchanged and absorbs the
tmux-inside-cmux bundle-id false positive; the auto-detect NOTICE names the
winning fallback signal.

Workstream B: the five socketControlMode values were traced through cmux
source (commit 9c91710e3f58): off/cmuxOnly can never admit an external CLI,
automation admits same-user clients with no secret (0600 socket only),
password needs the auth handshake, allowAll opens the socket to every local
user (0666). Automation mode is now the documented recommendation; the
adapter's refusals name every viable mode, classify Invalid password as
unauth, and the launch-timeout message names the off-mode possibility.

Docs carry the wrapper-strip empirical record, the fallback contract and
authority split, and the full mode matrix with rationale; tests cover the
new detection paths, the nested false positive, and the refusal wording.
@kunchenguid
kunchenguid force-pushed the fm/cmux-backend-w3 branch from afebc59 to 0067a98 Compare July 4, 2026 22:20
@kunchenguid
kunchenguid merged commit aaf7de2 into main Jul 4, 2026
4 checks passed
@kunchenguid
kunchenguid deleted the fm/cmux-backend-w3 branch July 4, 2026 22:28
DQ4443 pushed a commit to DQ4443/firstmate that referenced this pull request Jul 6, 2026
…henguid#259)

* feat(backends): cmux detection fallbacks and socket-mode matrix

Workstream A: cmux's bundled claude wrapper strips every CMUX_* env var on
its passthrough path (reproduced live 2026-07-04, cmux 0.64.17), so a
claude-harness firstmate inside a cmux tab has no CMUX_WORKSPACE_ID.
fm_backend_detect now falls back - macOS-only, only when the primary marker
is absent - to __CFBundleIdentifier=com.cmuxterm.app and then a process
ancestry walk resolved by bundle id (lsappinfo) plus a bundle-shaped ps comm
match. Innermost-first ordering is unchanged and absorbs the
tmux-inside-cmux bundle-id false positive; the auto-detect NOTICE names the
winning fallback signal.

Workstream B: the five socketControlMode values were traced through cmux
source (commit 9c91710e3f58): off/cmuxOnly can never admit an external CLI,
automation admits same-user clients with no secret (0600 socket only),
password needs the auth handshake, allowAll opens the socket to every local
user (0666). Automation mode is now the documented recommendation; the
adapter's refusals name every viable mode, classify Invalid password as
unauth, and the launch-timeout message names the off-mode possibility.

Docs carry the wrapper-strip empirical record, the fallback contract and
authority split, and the full mode matrix with rationale; tests cover the
new detection paths, the nested false positive, and the refusal wording.

* no-mistakes(review): Document cmux fallback detection

* no-mistakes(review): Update cmux architecture docs

* no-mistakes(document): Align cmux backend docs
DQ4443 added a commit to DQ4443/firstmate that referenced this pull request Jul 6, 2026
* fix: anchor turn-end Stop hook to project root (kunchenguid#256)

* Fix turn-end Stop hook to use CLAUDE_PROJECT_DIR path

Claude Code runs hook commands via /bin/sh from the session cwd, so the
bare relative bin/fm-turnend-guard.sh path fails when cwd is not the repo
root. Anchor the command with "$CLAUDE_PROJECT_DIR"/bin/fm-turnend-guard.sh
instead; verified CLAUDE_PROJECT_DIR is set on Stop hooks in Claude Code
2.1.201. Document the cwd caveat and add a settings.json regression test.

* no-mistakes(document): Document Stop hook path anchoring

* docs: trim firstmate agent guidance duplication (kunchenguid#258)

* docs: trim AGENTS.md redundancy (diet PR 3/3)

Consolidates five duplicated passages to a single owner each, per
data/agentsmd-diet-s2/report.md redundancy items c3-c7:

- Inheritable-config propagation mechanism: owned by section 3 (where
  the sweep runs); sections 4 and 7 keep compact references. Section 4
  retains its one genuinely unique fact (crew-harness inherit-vs-fallback
  semantics), just no longer restates the propagation mechanism itself.
- Landed-work definition: owned by section 7's ship-teardown detail
  (PR-containment mechanics, pr= discovery fallback); section 1's hard
  rule #3 keeps the rule plus a three-case summary and a pointer.
- Backend meta-field enumeration: owned by docs/configuration.md
  ("Runtime backend", already comprehensive including cmux) and each
  backend's own doc; AGENTS.md keeps only the fields common to every
  task plus a pointer.
- Dropped one redundant restatement of "silence is correct while
  waiting" in section 8.
- Worktree-tangle guard explanation: owned by section 8 (already the
  fuller, cross-referenced version); section 3's TANGLE bullet keeps
  the remediation action and points at section 8 for the why.

Also adds two captain-requested single-sentence rules: invoke bin/
scripts by absolute $FM_ROOT path after any cd away from the home, and
a backend spawn refusal must be surfaced to the captain rather than
silently worked around by switching backends.

AGENTS.md: 901 -> 889 lines, 112355 -> 108560 bytes.

* no-mistakes(review): Clarify post-cd bin invocation guidance

* no-mistakes(document): Sync AGENTS trim docs

* no-mistakes(lint): Fix Markdown line style

* feat(backends): improve cmux detection and socket-mode guidance (kunchenguid#259)

* feat(backends): cmux detection fallbacks and socket-mode matrix

Workstream A: cmux's bundled claude wrapper strips every CMUX_* env var on
its passthrough path (reproduced live 2026-07-04, cmux 0.64.17), so a
claude-harness firstmate inside a cmux tab has no CMUX_WORKSPACE_ID.
fm_backend_detect now falls back - macOS-only, only when the primary marker
is absent - to __CFBundleIdentifier=com.cmuxterm.app and then a process
ancestry walk resolved by bundle id (lsappinfo) plus a bundle-shaped ps comm
match. Innermost-first ordering is unchanged and absorbs the
tmux-inside-cmux bundle-id false positive; the auto-detect NOTICE names the
winning fallback signal.

Workstream B: the five socketControlMode values were traced through cmux
source (commit 9c91710e3f58): off/cmuxOnly can never admit an external CLI,
automation admits same-user clients with no secret (0600 socket only),
password needs the auth handshake, allowAll opens the socket to every local
user (0666). Automation mode is now the documented recommendation; the
adapter's refusals name every viable mode, classify Invalid password as
unauth, and the launch-timeout message names the off-mode possibility.

Docs carry the wrapper-strip empirical record, the fallback contract and
authority split, and the full mode matrix with rationale; tests cover the
new detection paths, the nested false positive, and the refusal wording.

* no-mistakes(review): Document cmux fallback detection

* no-mistakes(review): Update cmux architecture docs

* no-mistakes(document): Align cmux backend docs

* fix(backends): scope zellij tabs by firstmate home (kunchenguid#252)

* fix(backends): home-scope zellij tab titles to close cross-home collision gap

Zellij's one shared "firstmate" session has no per-home split and enforces
no tab-name uniqueness, so two firstmate homes with colliding task ids could
send/peek/close each other's tabs - the same gap a no-mistakes review gate
caught for cmux (docs/cmux-backend.md). Ports that fix: every new tab is
created with a home-scoped title (fm-<home-label>-<id>), and every
list/find/recover/kill path scopes matches to this home's own tag. A tab
spawned before this change still matches via its old untagged bare title,
but only when unambiguous - two live tabs sharing a bare title refuse rather
than guessing which one is ours.

Factors the home-label/hash derivation shared with cmux into
bin/fm-backend-hometag-lib.sh so the two adapters can't drift.

* no-mistakes(review): Fix zellij child teardown home tag

* no-mistakes(review): Fix zellij teardown and selector scoping

* no-mistakes(document): Sync zellij home-scope docs

* Rewrite operating manual for the dynamic-workflow paradigm

Replace the crewmate/tmux-window dispatch model with in-session dynamic
workflows. Remove harness adapters, crew spawn/teardown/supervision, pane
peeking, stale-crew detection, and multi-backend machinery. Promote the
board-v2 interface and the design/red-team/merge gates to first-class
sections. Preserve firstmate persistence in tmux, the board pollers and
watcher for board input, delivery modes and the no-mistakes gate,
secondmates (flagged for David's confirmation), captain.md-at-startup,
bootstrap/recovery, backlog, self-update, and X mode.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* Finalize AGENTS.md for the dynamic-workflow paradigm

Reconcile the d3d3c7a rewrite down to the final workflow-era manual: the
finalA draft as the base, folding in the load-bearing board contract from
d3d3c7a (section semantics as whose-turn, one item one row, MVP-tracker
naming, scan-all-threads-before-seen) and applying the synthesis amendments
(Kronos tickets plus cite-repo-files-by-path in section 3, the built-in
verify then project-verify then no-mistakes done stack in section 5, the
transfer-file maintenance discipline in section 10, the reconciled
escape-hatch and skill dispositions in section 12).

Secondmates are dropped outright; the tmux-crewmate and watcher stack moves
to the documented escape hatch. CLAUDE.md is a symlink to this file.

* Add workflow-paradigm machinery: poller, write fence, board check-in

fm-poll.sh is the launchd-supervised (com.firstmate.poller, KeepAlive)
board/merge/stall poller that replaces the agent-armed watcher for daily
duty: it loops state/*.check.sh on the check contract, delivers wakes
through the durable queue in fm-wake-lib.sh, keeps its own
state/.last-poller-beat beacon and a home-scoped singleton guard, and
injects a synthetic startup check event so a wake confirms the delivery
path end to end.

fm-write-fence.sh is the broadened PreToolUse hook: it blocks writes under
~/dev/work except the agent-worktree allowlist
(~/dev/work/*/.claude/worktrees and ~/.treehouse), failing open on
unreadable payloads.

fm-board-checkin.sh writes a real per-item stamp into
state/board-checkins.json atomically at each phase boundary.

launchd/com.firstmate.poller.plist ships UNLOADED with a header comment:
loading it is the human-verified cutover step, with __FM_ROOT__/__FM_HOME__
placeholders substituted then.

* Deprecation headers on retired scripts (delete nothing)

Mark the retire-marked scripts from the disposition table with a DEPRECATED
header: the watcher/guard stack (fm-guard, fm-tangle-lib), the crewmate
scaffolding (fm-brief, fm-promote), the afk daemon (fm-supervise-daemon),
and the secondmate stack (fm-home-seed, fm-backlog-handoff, fm-config-push,
fm-config-inherit-lib, fm-marker-lib).

Each stays functional on disk and is removed only in the cleanup PR after
the Opus 4.8 transition settles, so rollback stays real.

* Regroup docs/scripts.md by workflow-paradigm disposition

Restructure the toolbelt reference into New, Kept, Escape hatch, Retired,
and Inert sections so each script's disposition is explicit, add the three
new scripts plus the launchd plist and the generated stall check, and note
that nothing is deleted until the cleanup PR.

* Salvage kronos-watch PR/CI awareness into section 5

* Write fence: cover projects/ clones and resolve new paths through symlinks

The projects/<name> entries are firstmate's own real clones, not symlinks into
~/dev/work, so the ~/dev/work rule never covered them. Add an explicit block on
<FM_ROOT>/projects/** (allowing only projects/<name>/.claude/worktrees/**), and
make resolve() walk up to the nearest existing ancestor so a new file created
under a symlinked directory still resolves into the real fenced tree instead of
slipping past as an unresolved literal. Add colocated behavior tests.

* Poller: identity-check the singleton pidfile and rate-limit the startup wake

A bare kill -0 on the pidfile trusted a recycled pid: after a kill -9 left a
stale pidfile whose pid got reused, the launchd instance read it as "already
running" and exited, and KeepAlive + the 10s throttle wedged the poller in a
silent respawn loop that never polled the board. Record the process identity
(start time + command) alongside the pid and honor the pidfile only when the
identity still matches, so a reused pid is treated as dead. Also rate-limit the
synthetic startup wake so a crash-respawn loop cannot flood the durable wake
queue; a genuine restart still emits it.

* Teardown: implement --worktree <path> mode for meta-less workflow worktrees

AGENTS.md sections 4 and 6 name bin/fm-teardown.sh --worktree <path> as the
sanctioned disposal for a changed worktree, but only the task-id path existed;
a workflow worktree has no state/<id>.meta, so the documented command errored.
Add a --worktree mode that runs the same landed check keyed on the worktree
path (refusing dirty or unlanded work, refusing a main checkout, removing only
on a pass or with --force), independent of any meta record. Add colocated tests.

* Docs: reconcile manual with the fence, poller, and cutover reality

- Rule 2 and section 3: projects/<name> are firstmate's own clones (real dirs),
  not symlinks into ~/dev/work; describe the write fence as wired at the poller
  cutover and best-effort behind isolation (fails open), not present-tense
  sole enforcement. Document the fence-wiring as a hard step of that cutover in
  the plist header, kept out of tracked settings for this shared-template repo.
- Rule 1: the tracker-sync merge authorization is gated on David's per-run
  okay of the change list; keep the standing merge authority the skill grants.
- Budgets and stall detection: mark data/budgets.md and
  state/workflow-runs.check.sh as built at the cutover, with an interim path.
- docs/scripts.md: fence covers projects/ clones; poller pidfile identity check
  and rate-limited startup wake.

* test: pass explicit identity to fm_git_identity (SC2119)

---------

Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
mielyemitchell added a commit to mielyemitchell/firstmate that referenced this pull request Jul 6, 2026