Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(pane): bind each pane to its transcript in magmux's input gate
Jack Rudenkoea1b99280c83
diff --git a/.github/magmux.env b/.github/magmux.envindex fbb9d9e4..f32ba219 100644--- a/.github/magmux.env+++ b/.github/magmux.env@@ -3,8 +3,8 @@# Bump the tag and all four checksums together, deliberately, after the pane suites# pass against the new release. The sums are copied from the release's checksums.txt# and verified independently of it: a replaced asset or a moved tag fails the download.-MAGMUX_TAG=v0.15.1-MAGMUX_SHA256_darwin_amd64=a3eaa190fc13700cdd62d58a22cfa5211fa42cc8332fd69fb49b3f99ff667604-MAGMUX_SHA256_darwin_arm64=bc1ad66b09f7344d725dc010240bcdc868cfa361e0555ffdd2287c9fb9be7e3a-MAGMUX_SHA256_linux_amd64=e3e8c16d50e7978cc27a1bd75293c785dd081f607778af3a3e67ffec387d2f83-MAGMUX_SHA256_linux_arm64=c0076445e1b0a8c982c680e8a421309518343b16b0d0fbf8d5b8bee09c98d372+MAGMUX_TAG=v0.17.0+MAGMUX_SHA256_darwin_amd64=51b5160f41b3d0f0babb26bd2fb3e71abbae2b78709ee51d6a60ac80d51f224e+MAGMUX_SHA256_darwin_arm64=16d3fe7402a0d7535f1663c56d15b368fcb9bcb5a25957683532cc74399f8a14+MAGMUX_SHA256_linux_amd64=48b3144ca5919e3d4836dfc74223975a61f9bbf23ebe424bcf90a6c201e7f177+MAGMUX_SHA256_linux_arm64=c30b092e582ec50cd06923c8109a023ff37a658cfe72d842942607d9289ed0fbdiff --git a/packages/cli/src/pane/gate-binding.ts b/packages/cli/src/pane/gate-binding.tsnew file mode 100644index 00000000..e27b0c44--- /dev/null+++ b/packages/cli/src/pane/gate-binding.ts@@ -0,0 +1,74 @@+/**+ * The binding check (architecture-v2 R1.0): claudish trusts magmux's input gate for a pane+ * only when magmux bound that pane to claudish's OWN transcript.+ *+ * A pane is launched declared (`--controller claude-code --session-id <uuid> --transcript+ * <path>`, magmux >= 0.17.0), so magmux claims exactly that file and never runs its mtime+ * discovery, which could otherwise lock onto the parent's or a sibling's session. This+ * module reads one `list` reply and says whether pane 0 is gated and bound by name to the+ * same session id and the same path claudish's transcript follower reads.+ *+ * `transcriptSeen: false` is normal before the first prompt (Claude Code writes no+ * transcript until then) and is not read here.+ *+ * Pure apart from `realpathSync` on the path's existing ancestors.+ */++import { realpathSync } from "node:fs";+import { basename, dirname, join, resolve } from "node:path";+import { gateBasisOf, parseGateBinding, parseGateInput } from "./input-gate.js";++export type GateBindingCheck = { ok: true } | { ok: false; detail: string };++/**+ * `p` made absolute, with its deepest EXISTING ancestor realpath-resolved and the rest+ * appended as written: the transcript file, and often its `projects/<slug>` directory, do+ * not exist before the first prompt, and `/var` vs `/private/var` must still compare equal.+ */+export function normaliseTranscriptPath(p: string): string {+ const abs = resolve(p);+ const tail: string[] = [];+ let cur = abs;+ for (;;) {+ try {+ return tail.length ? join(realpathSync(cur), ...tail.reverse()) : realpathSync(cur);+ } catch {+ const parent = dirname(cur);+ if (parent === cur) return abs;+ tail.push(basename(cur));+ cur = parent;+ }+ }+}++/**+ * One `list` result → whether pane 0's gate may be trusted for this session. Fails with+ * `input_gate_unavailable` when pane 0 is not gated as a declared pane, and with+ * `input_gate_unbound` when the binding is not by name, or names another session or path.+ */+export function checkGateBinding(+ listResult: unknown,+ expected: { sessionUuid: string; transcriptPath: string; magmuxVersion: string }+): GateBindingCheck {+ const v = expected.magmuxVersion || "?";+ const basis = gateBasisOf(listResult);+ if (basis !== "declared" || !parseGateInput(listResult, 0)) {+ return {+ ok: false,+ detail: `input_gate_unavailable: magmux ${v} did not gate pane 0 (gateBasis ${basis ?? "none"})`,+ };+ }+ const b = parseGateBinding(listResult);+ const ours = normaliseTranscriptPath(expected.transcriptPath);+ const theirs = b?.transcriptPath ? normaliseTranscriptPath(b.transcriptPath) : null;+ const differs: string[] = [];+ if (b?.bound !== "named") differs.push(`bound ${b?.boundRaw ?? "none"}`);+ if (b?.sessionId !== expected.sessionUuid)+ differs.push(`sessionId ${b?.sessionId ?? "none"}, not ${expected.sessionUuid}`);+ if (theirs !== ours) differs.push(`transcriptPath ${theirs ?? "none"}, not ${ours}`);+ if (differs.length === 0) return { ok: true };+ return {+ ok: false,+ detail: `input_gate_unbound: magmux ${v} bound pane 0 to ${theirs ?? "none"} (${b?.boundRaw ?? "none"}), not ${ours}: ${differs.join("; ")}`,+ };+}diff --git a/packages/cli/src/pane/pane-launch.ts b/packages/cli/src/pane/pane-launch.tsindex 5698da9d..42b8aa1e 100644--- a/packages/cli/src/pane/pane-launch.ts+++ b/packages/cli/src/pane/pane-launch.ts@@ -10,9 +10,14 @@* child re-applies (`child-env.ts`), and `$SHELL` is a generated shim that drops `-l`, so* no profile runs at all (X-M15).*- * The pane command must never name `claude`: magmux attaches its ClaudeCodeController- * to such a pane, and that controller's mtime-based transcript discovery can lock onto- * the parent's or a sibling's transcript (research-magmux §3).+ * magmux runs a pane DECLARED: `--controller claude-code --session-id <uuid> --transcript+ * <path>` before `-e` names the session and the transcript claudish already gives Claude+ * Code and its own transcript follower, so magmux's input gate reads exactly that file+ * and never its mtime-based discovery, which can lock onto the parent's or a sibling's+ * transcript (research-magmux §3; architecture-v2 R1.0). `PaneSession` verifies the+ * binding from `list` on every attach (`gate-binding.ts`). The pane command itself still+ * never names `claude`: a direct `claude` launch would be gated with basis `direct`, by+ * discovery, and have its `--settings` rewritten.*/import { type ChildProcess, execFile, spawn } from "node:child_process";@@ -484,7 +489,12 @@ export const KNOWN_CLAUDISH_FLAGS: readonly string[] = Object.keys(CLAUDISH_FLAG/* ───────────────────────────── magmux binary ───────────────────────────── */-export const MIN_MAGMUX_VERSION = "0.15.1";+/**+ * 0.17.0: the Claude Code input gate with a declared transcript (`--session-id`,+ * `--transcript`, and `list`'s `bound`/`sessionId`/`transcriptPath`). A pre-release such as+ * `0.17.0-rc1` passes: `versionAtLeast` compares the numeric triple only.+ */+export const MIN_MAGMUX_VERSION = "0.17.0";export class MagmuxUnavailableError extends Error {readonly code = "magmux_unavailable";@@ -505,7 +515,7 @@ export function versionAtLeast(v: string, min: string): boolean {const magmuxCache = new Map<string, { binary: string; version: string }>();const execFileAsync = promisify(execFile);-/** The magmux binary and its version (≥ 0.15.1), cached per process. Never a `-p` fallback. */+/** The magmux binary and its version (≥ MIN_MAGMUX_VERSION), cached per process. Never a `-p` fallback. */export async function assertMagmuxAvailable(binary?: string): Promise<{ binary: string; version: string }> {@@ -529,7 +539,7 @@ export async function assertMagmuxAvailable(const version = out.match(/(\d+\.\d+\.\d+)/)?.[1] ?? "";if (!version || !versionAtLeast(version, MIN_MAGMUX_VERSION))throw new MagmuxUnavailableError(- `magmux_unavailable: ${found} is version ${version || "unknown"}; panes need >= ${MIN_MAGMUX_VERSION}`+ `magmux_unavailable: ${found} is version ${version || "unknown"}; panes need >= ${MIN_MAGMUX_VERSION} (the Claude Code input gate bound to a named transcript); upgrade: brew upgrade MadAppGang/tap/magmux`);const result = { binary: found, version };magmuxCache.set(binary ?? "", result);@@ -571,7 +581,7 @@ export function launcherScript(cwd: string, launch: ClaudishLaunch, argv: stringexport const SHELL_SHIM = '#!/bin/sh\n[ "$1" = -l ] && shift\nexec /bin/sh "$@"\n';-/** The `-e` value. It never names `claude` (research-magmux §3). */+/** The `-e` value. It never names `claude`: the pane is declared, not a direct launch. */export function paneCommand(ctlDir: string): string {const cmd = `. ${shq(join(ctlDir, "pane-launch.sh"))}`;if (/claude /.test(cmd) || /claude$/.test(cmd) || /(^|\/)claude['"]?$/.test(cmd))@@ -629,24 +639,49 @@ export interface MagmuxSpawnInput {sockRoot: string;ctlDir: string;cwd: string;+ /**+ * magmux's environment (`buildPaneEnv`). It is built from the same parent environment+ * the transcript path is derived from, so a `CLAUDE_CONFIG_DIR` the session uses is in+ * magmux's own environment too, where magmux resolves the session registry.+ */env: Record<string, string>;+ /** the `--session-id` claudish passes Claude Code */+ sessionUuid: string;+ /** the transcript claudish's follower reads; made absolute here (magmux requires it) */+ transcriptPath: string;+}++/**+ * magmux's argv. The declaration comes before `-e`, which it binds; `--id <paneId>+ * --sock-dir` stays adjacent, because that pair is how the reap, the sweep and the pane+ * watcher recognise this pane's magmux (`magmuxNeedle`).+ */+export function paneMagmuxArgv(input: Omit<MagmuxSpawnInput, "binary" | "cwd" | "env">): string[] {+ return [+ "--headless",+ "--no-status",+ "--controller",+ "claude-code",+ "--session-id",+ input.sessionUuid,+ "--transcript",+ resolve(input.transcriptPath),+ "--id",+ input.paneId,+ "--sock-dir",+ input.sockRoot,+ "-e",+ paneCommand(input.ctlDir),+ ];}export function spawnPaneMagmux(input: MagmuxSpawnInput): ChildProcess {- const proc = spawn(- input.binary,- [- "--headless",- "--no-status",- "--id",- input.paneId,- "--sock-dir",- input.sockRoot,- "-e",- paneCommand(input.ctlDir),- ],- { cwd: input.cwd, env: input.env, stdio: ["ignore", "ignore", "pipe"], detached: true }- );+ const proc = spawn(input.binary, paneMagmuxArgv(input), {+ cwd: input.cwd,+ env: input.env,+ stdio: ["ignore", "ignore", "pipe"],+ detached: true,+ });proc.on("error", () => {});return proc;}diff --git a/packages/cli/src/pane/pane-session.ts b/packages/cli/src/pane/pane-session.tsindex 3449e97f..21b70315 100644--- a/packages/cli/src/pane/pane-session.ts+++ b/packages/cli/src/pane/pane-session.ts@@ -30,7 +30,8 @@ import {type FailureReason,type SlotState,} from "./contract.js";-import { MagmuxClient, type MagmuxConnectError } from "./magmux-client.js";+import { checkGateBinding } from "./gate-binding.js";+import { MagmuxClient, type MagmuxConnectError, type MagmuxReply } from "./magmux-client.js";import {type ClaudishLaunch,FATAL_MAGMUX_STDERR,@@ -174,6 +175,12 @@ const REGISTRY_DISAGREE_MS = 2_000;/** No live registry record this long after boot was ready: `registry_record_missing`. */const REGISTRY_MISSING_MS = 5_000;const MAX_ANOMALY_KEYS = 64;+/**+ * A declared pane gates every `send` with text or an Enter (magmux README "the input+ * gate"). Until delivery moves to one gated send (architecture-v2 R1.10 commit 5), every+ * send claudish makes stays the ungated send it always was, byte for byte.+ */+const UNGATED_SENDS = true;/** Settled answers kept for `turnAnswer` (owners read the current or the last one). */const KEPT_ANSWERS = 4;@@ -522,6 +529,8 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {ctlDir: this.ctlDir,cwd: input.cwd,env: input.env,+ sessionUuid: this.o.sessionUuid,+ transcriptPath: this.o.transcriptPath,});} catch (e) {return this.spawnFailed(e);@@ -598,8 +607,9 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {// dropped while asking: `disconnected` has already started the redialif (client.isClosed) return;this.client = client;+ const magmuxVersion = caps.ok ? String(caps.result.version ?? "") : "";if (caps.ok) {- const v = String(caps.result.version ?? "");+ const v = magmuxVersion;if (caps.result.protocol !== 1 || !versionAtLeast(v, MIN_MAGMUX_VERSION)) {this.step(() =>this.fire("pane_lost", {@@ -621,7 +631,40 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {if (p0?.dead === true && !this.paneExited) {if (!reconnect) await this.nextFrame(500); // let the keyframe land: the final screen decides agent_rejectedvoid this.onPaneExit({ exitCode: p0.exitCode ?? null, lastLine: "" });+ return;}+ this.verifyGateBinding(client, list, magmuxVersion);+ }++ /**+ * The binding check (architecture-v2 R1.0), on every attach: magmux's input gate is+ * trusted only for a pane it bound BY NAME to this session's id and transcript. Anything+ * else fails the pane; claudish never falls back to magmux's transcript discovery.+ * Nothing reads the gate yet: this only proves the declared launch took.+ */+ private verifyGateBinding(+ client: MagmuxClient,+ list: MagmuxReply<{ panes?: Array<Record<string, unknown>> }>,+ magmuxVersion: string+ ): void {+ // dropped while asking: the redial attaches again and re-checks+ if (client.isClosed || isTerminalPhase(this.phase)) return;+ if (!list.ok) {+ this.step(() =>+ this.fire("pane_lost", {+ detail: `input_gate_unbound: magmux ${magmuxVersion || "?"} list failed (${list.code}: ${list.error}), so the binding of pane 0 is unknown`,+ })+ );+ return;+ }+ // no pane 0: it is gone, and the exit path owns that+ if (!list.result.panes?.some((p) => p.pane === 0)) return;+ const check = checkGateBinding(list.result, {+ sessionUuid: this.o.sessionUuid,+ transcriptPath: this.o.transcriptPath,+ magmuxVersion,+ });+ if (!check.ok) this.step(() => this.fire("pane_lost", { detail: check.detail }));}/* ───────────────────────────── magmux events ───────────────────────────── */@@ -1081,7 +1124,10 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {for (let attempt = 0; attempt < 2; attempt++) {const c = this.client;if (c) {- const r = await c.request({ type: "send", pane: 0, text, typed: true, enter }, 10_000);+ const r = await c.request(+ { type: "send", pane: 0, text, typed: true, enter, noGate: UNGATED_SENDS },+ 10_000+ );if (r.ok) return true;why = r.code;if (r.code === "client_timeout" || r.code === "client_lost") {@@ -1115,7 +1161,10 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {private async key(k: string): Promise<boolean> {const c = this.client;if (!c) return false;- const r = await c.request({ type: "send", pane: 0, keys: [k], enter: false }, 10_000);+ const r = await c.request(+ { type: "send", pane: 0, keys: [k], enter: false, noGate: UNGATED_SENDS },+ 10_000+ );return r.ok;}