Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(launcher): wrap claudish -i in magmux when session hooks are loaded
Jack Rudenkoa026b5e0c627
diff --git a/packages/cli/src/claude-runner.ts b/packages/cli/src/claude-runner.tsindex c79418ee..a13abe63 100644--- a/packages/cli/src/claude-runner.ts+++ b/packages/cli/src/claude-runner.ts@@ -1,12 +1,16 @@import type { ChildProcess } from "node:child_process";import { spawn, spawnSync } from "node:child_process";+import { randomUUID } from "node:crypto";import {+ chmodSync,closeSync,existsSync,mkdirSync,+ mkdtempSync,openSync,readFileSync,readdirSync,+ rmSync,statSync,unlinkSync,writeFileSync,@@ -17,6 +21,16 @@ import { isatty } from "node:tty";import { lookupModelForProvider } from "./adapters/model-catalog.js";import { classifierPassthroughEnabled } from "./classifier-passthrough.js";import { ENV } from "./config.js";+import { getHookEngine } from "./hooks/index.js";+import { InProcessSink, setProcessSink } from "./hooks/injection/sinks.js";+import { sessionHooksNeedBinding } from "./hooks/session/binding.js";+import { InteractiveDriver } from "./hooks/session/interactive-driver.js";+import {+ driverLeadingArgs,+ planInteractiveSurfaces,+ sessionFlagsOf,+} from "./hooks/session/interactive-launch.js";+import { type NoSurfaceSession, startNoSurfaceSession } from "./hooks/session/no-surface.js";import {STRIPPED_CHILD_VARS,magmuxPaneCapability,@@ -26,13 +40,19 @@ import {// console printer), and an unaliased import would be shadowed inside it.import { log as debugLog, logStderr } from "./logger.js";import { PANE_LAUNCH_VARS, isPaneChild } from "./pane/child-env.js";+import { flagsRemoveRead } from "./pane/pane-launch.js";import { loadConfig } from "./profile-config.js";import { discoverContextWindow } from "./providers/model-discovery.js";import { parseModelSpec } from "./providers/model-parser.js";import { getProviderByName } from "./providers/provider-definitions.js";import { route } from "./providers/routing-rules.js";-import { installRecoveryUi, shutdownRecoveryUi } from "./recovery/magmux-ui.js";+import {+ installRecoveryUi,+ recoveryOverlayHeld,+ shutdownRecoveryUi,+} from "./recovery/magmux-ui.js";import { applyRetryWatchdog, recoverySurfaceAllowed } from "./recovery/settings.js";+import { projectsDir } from "./session/session-discovery.js";import { assignedTokenFile, resolveTokenFilePath } from "./session/token-file.js";import { setClaudeCodeRunning } from "./telemetry.js";import { beginTerminalIsolation } from "./terminal-isolation.js";@@ -2087,8 +2107,40 @@ export async function runClaudeWithProxy(// `paneCapability` was resolved before the environment was finalised, and is// re-used rather than re-derived: the watchdog above is exported on exactly// the launches that reach `planMagmuxWrap` or the ambient branch below.+ //+ // SESSION HOOKS are the wrap's SECOND reason (hook-system §7.5). A loaded hook that+ // declares `responseEnd` or a session event needs the `InteractiveDriver`, which+ // needs a pane, so `--no-recovery` no longer removes the surface such a hook needs.+ // That reason plans the wrap and starts the driver and NOTHING else: the recovery UI+ // and the retry watchdog (exported above by `applyRetryWatchdog`, which asks+ // `recoverySurfaceAllowed()` itself) stay gated on the recovery switches alone. The+ // hook engine is the proxy's, already loaded by `createProxyServer`; null when the+ // proxy runs no hooks (monitor mode).+ const hookEngine = getHookEngine();+ const surfaces = planInteractiveSurfaces({+ capability: paneCapability,+ recoveryAllowed: recoverySurfaceAllowed(),+ sessionHooksNeedDriver: hookEngine !== null && sessionHooksNeedBinding(hookEngine),+ });+ const sessionFlags = sessionFlagsOf(config.claudeArgs);+ let driverLaunch: { sink: InProcessSink; turnDir: string; sessionId: string | null } | null =+ null;+ if (surfaces.driver) {+ // The transcript path must be known from boot, so claudish mints the session id+ // unless the user named one or asked Claude Code to resume. Long injections go to a+ // turn file the model Reads from the `--add-dir` directory (no prompt there: S2b).+ const minted = sessionFlags.sessionId || sessionFlags.resumes ? null : randomUUID();+ const turnDir = mkdtempSync(join(tmpdir(), "claudish-turns-"));+ chmodSync(turnDir, 0o700);+ claudeArgs.unshift(...driverLeadingArgs({ mintedSessionId: minted, turnDir }));+ const sink = new InProcessSink();+ // Installed before Claude Code starts, so its first request already reports here.+ setProcessSink(sink);+ driverLaunch = { sink, turnDir, sessionId: minted ?? sessionFlags.sessionId };+ }+const wrap =- recoverySurfaceAllowed() && paneCapability.kind === "wrap"+ surfaces.wrap && paneCapability.kind === "wrap"? planMagmuxWrap({claudeBinary,claudeArgs,@@ -2110,6 +2162,8 @@ export async function runClaudeWithProxy(if (wrap) {wrap.watch(proc);+ }+ if (wrap && surfaces.recoveryUi === "wrap") {// Hand the control socket to the proxy as an EXPLICIT input. It cannot be// discovered: claudish is magmux's parent and `MAGMUX_SOCK` is exported// downward only, so the `--id` path — fixed before magmux starts — is the@@ -2122,7 +2176,7 @@ export async function runClaudeWithProxy(// after the user had already quit.void shutdownRecoveryUi();});- } else if (recoverySurfaceAllowed() && paneCapability.kind === "ambient") {+ } else if (surfaces.recoveryUi === "ambient") {// Already inside someone else's magmux — `team --grid --mode interactive`,// or a user who launched claudish in a pane by hand. There is nothing to// wrap, but there IS a multiplexer to ask for a pane, so the recovery UI@@ -2139,6 +2193,56 @@ export async function runClaudeWithProxy(installRecoveryUi(null);}+ // The session-hook host of this launch: the driver on a pane, or the lifecycle-only+ // session when there is no pane (`sessionStart` now, `sessionEnd` at exit).+ let driver: InteractiveDriver | null = null;+ let noSurfaceSession: NoSurfaceSession | null = null;+ const sessionModel = modelDisplayName;+ if (driverLaunch && hookEngine && surfaces.driver) {+ const sockPath =+ surfaces.driver === "wrap" && wrap+ ? wrap.controlSocket+ : paneCapability.kind === "ambient"+ ? paneCapability.sock+ : null;+ if (sockPath) {+ const d = new InteractiveDriver({+ mode: surfaces.driver,+ sockPath,+ // A wrap has exactly one `-e` pane, so Claude Code is pane 0; an ambient+ // pane is found by ancestry.+ ...(surfaces.driver === "wrap" ? { pane: 0 } : {}),+ cwd: process.cwd(),+ sessionId: driverLaunch.sessionId,+ projectsRoot: projectsDir(env),+ turnDir: driverLaunch.turnDir,+ readAvailable: !flagsRemoveRead(config.claudeArgs),+ model: sessionModel,+ sink: driverLaunch.sink,+ engine: hookEngine,+ overlayHeld: recoveryOverlayHeld,+ });+ driver = d;+ void d.start();+ wrap?.onClaudeExit((code) => {+ void d.stop(sessionOutcomeOf(code));+ });+ } else {+ // No socket to drive after all: nothing would ever drain the sink.+ driverLaunch.sink.markUnavailable();+ }+ } else if (surfaces.noSurfaceSession && hookEngine) {+ noSurfaceSession = startNoSurfaceSession(hookEngine, {+ kind: "interactive",+ role: null,+ id: sessionFlags.sessionId ?? "",+ claudeSessionId: sessionFlags.sessionId,+ model: sessionModel,+ cwd: process.cwd(),+ shape: config.interactive ? "interactive" : "one-shot",+ });+ }+if (filterChildStderr && proc.stderr) {relayChildStderr(proc.stderr);}@@ -2209,6 +2313,19 @@ export async function runClaudeWithProxy(});wrap?.cleanup();+ // `sessionEnd`, awaited at most 1.5 s before the caller shuts the proxy down (§4.4).+ // The driver's stop is idempotent: in a wrap it began at the pane's exit announcement.+ if (driver) await driver.stop(sessionOutcomeOf(exitCode));+ if (noSurfaceSession) await noSurfaceSession.end(sessionOutcomeOf(exitCode));+ if (driverLaunch) {+ setProcessSink(null);+ try {+ rmSync(driverLaunch.turnDir, { recursive: true, force: true });+ } catch {+ // a leftover 0700 temp dir of turn files is harmless+ }+ }+// The only durable record of WHY the run ended. The always-on session log// carries proxy traffic, so a session that died before its first request left// nothing but "[Proxy] Server started" behind, and the caller's error notice@@ -2237,6 +2354,17 @@ export async function runClaudeWithProxy(return exitCode;}+/** `sessionEnd`'s outcome for the interactive launcher: Claude Code's exit. */+function sessionOutcomeOf(exitCode: number | null): {+ state: string;+ reason: string | null;+ exitCode: number | null;+} {+ return exitCode === 0+ ? { state: "COMPLETED", reason: null, exitCode }+ : { state: "FAILED", reason: "child_exited", exitCode };+}+/*** Signal numbers, for the `128 + signum` exit convention.*diff --git a/packages/cli/src/hooks/session/interactive-launch.test.ts b/packages/cli/src/hooks/session/interactive-launch.test.tsnew file mode 100644index 00000000..5ef7b4f7--- /dev/null+++ b/packages/cli/src/hooks/session/interactive-launch.test.ts@@ -0,0 +1,215 @@+/**+ * The interactive launcher's plan when session hooks are loaded (hook-system §3.2, §7.5,+ * §12 P7): the wrap's second reason, the recovery gate it must NOT open, the session-id+ * mint and the `--add-dir` turn directory.+ */++import { afterEach, describe, expect, test } from "bun:test";+import type { MagmuxPaneCapability } from "../../launcher/magmux-wrapper.js";+import {+ RETRY_WATCHDOG_OWNER_ENV,+ applyRetryWatchdog,+ recoverySurfaceAllowed,+ resetRecoveryFlagOverrides,+ setRecoveryFlagOverrides,+} from "../../recovery/settings.js";+import {+ driverLeadingArgs,+ planInteractiveSurfaces,+ sessionFlagsOf,+} from "./interactive-launch.js";++const WRAP: MagmuxPaneCapability = { kind: "wrap", magmux: "/usr/local/bin/magmux" };+const AMBIENT: MagmuxPaneCapability = { kind: "ambient", sock: "/tmp/magmux-1.sock" };+const NO_TTY: MagmuxPaneCapability = { kind: "none", reason: "no-tty" };+const PRINT: MagmuxPaneCapability = { kind: "none", reason: "not-interactive" };+const PANE_CHILD: MagmuxPaneCapability = { kind: "none", reason: "pane-child" };++afterEach(() => resetRecoveryFlagOverrides());++describe("planInteractiveSurfaces", () => {+ test("no session hooks: today's plan exactly (the wrap is the recovery surface's alone)", () => {+ expect(+ planInteractiveSurfaces({+ capability: WRAP,+ recoveryAllowed: true,+ sessionHooksNeedDriver: false,+ })+ ).toEqual({ wrap: true, recoveryUi: "wrap", driver: null, noSurfaceSession: false });+ expect(+ planInteractiveSurfaces({+ capability: WRAP,+ recoveryAllowed: false,+ sessionHooksNeedDriver: false,+ })+ ).toEqual({ wrap: false, recoveryUi: null, driver: null, noSurfaceSession: false });+ expect(+ planInteractiveSurfaces({+ capability: AMBIENT,+ recoveryAllowed: true,+ sessionHooksNeedDriver: false,+ })+ ).toEqual({ wrap: false, recoveryUi: "ambient", driver: null, noSurfaceSession: false });+ });++ test("session hooks with recovery on: one wrap, both the banner and the driver on it", () => {+ expect(+ planInteractiveSurfaces({+ capability: WRAP,+ recoveryAllowed: true,+ sessionHooksNeedDriver: true,+ })+ ).toEqual({ wrap: true, recoveryUi: "wrap", driver: "wrap", noSurfaceSession: false });+ });++ test("--no-recovery + session hooks: the wrap is planned for the driver, the banner is not", () => {+ expect(+ planInteractiveSurfaces({+ capability: WRAP,+ recoveryAllowed: false,+ sessionHooksNeedDriver: true,+ })+ ).toEqual({ wrap: true, recoveryUi: null, driver: "wrap", noSurfaceSession: false });+ });++ test("ambient: the driver runs on the ambient pane whatever the recovery switches say", () => {+ for (const recoveryAllowed of [true, false])+ expect(+ planInteractiveSurfaces({+ capability: AMBIENT,+ recoveryAllowed,+ sessionHooksNeedDriver: true,+ })+ ).toEqual({+ wrap: false,+ recoveryUi: recoveryAllowed ? "ambient" : null,+ driver: "ambient",+ noSurfaceSession: false,+ });+ });++ test("no pane (no TTY, -p): lifecycle-only session hooks; a pane child: none at all", () => {+ for (const capability of [NO_TTY, PRINT])+ expect(+ planInteractiveSurfaces({ capability, recoveryAllowed: true, sessionHooksNeedDriver: true })+ ).toEqual({ wrap: false, recoveryUi: null, driver: null, noSurfaceSession: true });+ expect(+ planInteractiveSurfaces({+ capability: PANE_CHILD,+ recoveryAllowed: true,+ sessionHooksNeedDriver: true,+ })+ ).toEqual({ wrap: false, recoveryUi: null, driver: null, noSurfaceSession: false });+ });+});++/**+ * The recovery gate, as `claude-runner.ts` asks it: the watchdog is applied with+ * `paneEligible: capability.kind !== "none"` and its own `recoverySurfaceAllowed()`,+ * and the wrap is planned from the same capability plus the session-hook reason.+ */+describe("recovery gate: --no-recovery + session hooks wraps WITHOUT exporting the watchdog", () => {+ function launch(sessionHooksNeedDriver: boolean) {+ const env: Record<string, string | undefined> = {};+ applyRetryWatchdog(env, { paneEligible: WRAP.kind !== "none" });+ const plan = planInteractiveSurfaces({+ capability: WRAP,+ recoveryAllowed: recoverySurfaceAllowed(),+ sessionHooksNeedDriver,+ });+ return { env, plan };+ }++ test("--no-recovery + hooks: wrapped, driver on, no recovery UI, no CLAUDE_CODE_RETRY_WATCHDOG", () => {+ setRecoveryFlagOverrides({ recovery: false });+ const { env, plan } = launch(true);+ expect(plan.wrap).toBe(true);+ expect(plan.driver).toBe("wrap");+ expect(plan.recoveryUi).toBeNull();+ expect(env.CLAUDE_CODE_RETRY_WATCHDOG).toBeUndefined();+ expect(env[RETRY_WATCHDOG_OWNER_ENV]).toBeUndefined();+ });++ test("--no-recovery-ui + hooks: the same", () => {+ setRecoveryFlagOverrides({ recoveryUi: false });+ const { env, plan } = launch(true);+ expect(plan.wrap).toBe(true);+ expect(plan.recoveryUi).toBeNull();+ expect(env.CLAUDE_CODE_RETRY_WATCHDOG).toBeUndefined();+ });++ test("an inherited claudish watchdog is still REMOVED when the recovery gate fails", () => {+ setRecoveryFlagOverrides({ recovery: false });+ const env: Record<string, string | undefined> = {+ CLAUDE_CODE_RETRY_WATCHDOG: "1",+ [RETRY_WATCHDOG_OWNER_ENV]: "1",+ };+ applyRetryWatchdog(env, { paneEligible: true });+ expect(env.CLAUDE_CODE_RETRY_WATCHDOG).toBeUndefined();+ });++ test("positive control: recovery on + hooks exports the watchdog and installs the banner", () => {+ setRecoveryFlagOverrides({ recovery: true, recoveryUi: true });+ const { env, plan } = launch(true);+ expect(plan.wrap).toBe(true);+ expect(plan.recoveryUi).toBe("wrap");+ expect(env.CLAUDE_CODE_RETRY_WATCHDOG).toBe("1");+ });++ test("negative control: --no-recovery without hooks does not wrap (the shipped fix stays)", () => {+ setRecoveryFlagOverrides({ recovery: false });+ const { env, plan } = launch(false);+ expect(plan.wrap).toBe(false);+ expect(env.CLAUDE_CODE_RETRY_WATCHDOG).toBeUndefined();+ });+});++describe("sessionFlagsOf", () => {+ test("nothing given: claudish mints", () => {+ expect(sessionFlagsOf(["--permission-mode", "plan", "hello"])).toEqual({+ sessionId: null,+ resumes: false,+ });+ });++ test("an explicit --session-id is the session from boot, in both spellings", () => {+ expect(sessionFlagsOf(["--session-id", "abc"])).toEqual({ sessionId: "abc", resumes: false });+ expect(sessionFlagsOf(["--session-id=abc"])).toEqual({ sessionId: "abc", resumes: false });+ });++ test("every resume flag means Claude Code decides: no id known, no mint", () => {+ for (const args of [+ ["--resume"],+ ["--resume", "x"],+ ["-r"],+ ["--continue"],+ ["-c"],+ ["--fork-session", "--resume", "x"],+ ["--session-id", "abc", "--fork-session"],+ ])+ expect(sessionFlagsOf(args)).toEqual({ sessionId: null, resumes: true });+ });++ test("arguments after -- are the prompt, not flags", () => {+ expect(sessionFlagsOf(["--", "-c is not a flag here"])).toEqual({+ sessionId: null,+ resumes: false,+ });+ });+});++describe("driverLeadingArgs", () => {+ test("--add-dir is never the last of the leading args a positional could follow", () => {+ const minted = driverLeadingArgs({ mintedSessionId: "u-1", turnDir: "/t" });+ expect(minted).toEqual(["--session-id", "u-1", "--add-dir", "/t"]);+ expect(driverLeadingArgs({ mintedSessionId: null, turnDir: "/t" })).toEqual([+ "--add-dir",+ "/t",+ ]);+ // claude-runner puts these ahead of its own `--settings <file>`, which ends the+ // variadic list: a prompt after it can never be read as a directory.+ const argv = [...minted, "--settings", "/s.json", "hello"];+ const at = argv.indexOf("--add-dir");+ expect(argv[at + 2]?.startsWith("-")).toBe(true);+ });+});diff --git a/packages/cli/src/hooks/session/interactive-launch.ts b/packages/cli/src/hooks/session/interactive-launch.tsnew file mode 100644index 00000000..b0fa9a97--- /dev/null+++ b/packages/cli/src/hooks/session/interactive-launch.ts@@ -0,0 +1,117 @@+/**+ * What the interactive launcher plans before it spawns Claude Code, when session hooks+ * are loaded (hook-system architecture §2.1, §3.2, §7.5). Pure, so `claude-runner.ts`+ * and its tests ask the same functions.+ *+ * Two reasons now plan the magmux wrap, and they are kept apart on purpose:+ *+ * 1. the recovery surface (`recoverySurfaceAllowed()`), as before: the banner and,+ * through `applyRetryWatchdog`, the client's retry watchdog;+ * 2. `sessionHooksNeedDriver`: a loaded hook declares `responseEnd` or a session+ * event, so the `InteractiveDriver` needs a pane to read and type into.+ *+ * Reason 2 alone wraps the launch and starts the driver. It never installs the recovery+ * UI and never exports the watchdog: those stay gated on reason 1 alone, so+ * `--no-recovery` keeps its "pre-recovery behaviour, byte for byte" promise for the+ * RESPONSE even when a hook needs the pane.+ */++import type { MagmuxPaneCapability } from "../../launcher/magmux-wrapper.js";++export interface SurfacePlan {+ /** spawn Claude Code inside a visible `-w` magmux claudish launches */+ wrap: boolean;+ /** where the recovery banner installs: the wrap's socket, the ambient one, or nowhere */+ recoveryUi: "wrap" | "ambient" | null;+ /** where the interactive driver runs, or null when it does not */+ driver: "wrap" | "ambient" | null;+ /**+ * Session hooks are loaded but no pane can carry them (`no-tty`, `no-magmux`, `-p`):+ * `sessionStart` fires at spawn and `sessionEnd` at exit, and every injection is+ * dropped `unavailable` (§2.1, §4.7 rule 8). Never for a pane child, whose owner fires+ * its session events.+ */+ noSurfaceSession: boolean;+}++export function planInteractiveSurfaces(input: {+ capability: MagmuxPaneCapability;+ /** `recoverySurfaceAllowed()`: both recovery switches on */+ recoveryAllowed: boolean;+ /** a loaded hook declares `responseEnd` or a session event (`sessionHooksNeedBinding`) */+ sessionHooksNeedDriver: boolean;+}): SurfacePlan {+ const { capability, recoveryAllowed, sessionHooksNeedDriver } = input;+ const wrap = capability.kind === "wrap" && (recoveryAllowed || sessionHooksNeedDriver);+ const recoveryUi = !recoveryAllowed+ ? null+ : capability.kind === "wrap"+ ? "wrap"+ : capability.kind === "ambient"+ ? "ambient"+ : null;+ const driver = !sessionHooksNeedDriver+ ? null+ : wrap+ ? "wrap"+ : capability.kind === "ambient"+ ? "ambient"+ : null;+ const paneChild = capability.kind === "none" && capability.reason === "pane-child";+ return {+ wrap,+ recoveryUi,+ driver,+ noSurfaceSession: sessionHooksNeedDriver && driver === null && !paneChild,+ };+}++/** Flags after which Claude Code picks the session itself, so claudish mints none. */+const RESUME_FLAGS = new Set(["--resume", "-r", "--continue", "-c", "--fork-session"]);++/**+ * What the user's own arguments say about the session id: an explicit `--session-id`+ * (then the driver knows it from boot), or a resume (`--resume`/`-r`, `--continue`/`-c`,+ * `--fork-session`: Claude Code decides, and the driver learns it from the first proxy+ * request that names it). Neither → claudish mints one.+ */+export function sessionFlagsOf(args: ReadonlyArray<string>): {+ sessionId: string | null;+ resumes: boolean;+} {+ let sessionId: string | null = null;+ let resumes = false;+ for (let i = 0; i < args.length; i++) {+ const a = args[i] as string;+ if (a === "--") break;+ const eq = a.startsWith("--") ? a.indexOf("=") : -1;+ const name = eq > 0 ? a.slice(0, eq) : a;+ if (RESUME_FLAGS.has(name)) resumes = true;+ else if (name === "--session-id") {+ const v = eq > 0 ? a.slice(eq + 1) : args[i + 1];+ if (v && !v.startsWith("-")) sessionId = v;+ }+ }+ return { sessionId: resumes ? null : sessionId, resumes };+}++/**+ * The arguments the driver adds IN FRONT of Claude Code's argv: `--session-id <minted>`+ * when one was minted, and `--add-dir <turn dir>` so the model may Read a long+ * injection's turn file without a permission prompt (S2b, measured: no prompt in default+ * mode, including for a file written after launch).+ *+ * Front, because `--add-dir` takes a VARIADIC list: placed before the user's arguments+ * it would swallow a positional prompt as a second directory. `claude-runner` puts+ * these ahead of its own `--settings <file>`, which ends the list.+ */+export function driverLeadingArgs(input: {+ mintedSessionId: string | null;+ turnDir: string;+}): string[] {+ return [+ ...(input.mintedSessionId ? ["--session-id", input.mintedSessionId] : []),+ "--add-dir",+ input.turnDir,+ ];+}diff --git a/packages/cli/src/recovery/settings.test.ts b/packages/cli/src/recovery/settings.test.tsindex 25da7b26..4dddd6e0 100644--- a/packages/cli/src/recovery/settings.test.ts+++ b/packages/cli/src/recovery/settings.test.ts@@ -406,26 +406,39 @@ describe("claude-runner asks that gate, and not the UI switch alone", () => {// not enough, so a guard that did not strip them would pass on reverted code.const code = source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, "");- test("the magmux wrap ternary consults recoverySurfaceAllowed()", () => {- const gate = /const wrap =\s*([\s\S]{0,160}?)\?\s*\n?\s*planMagmuxWrap/.exec(code)?.[1];- expect(gate, "could not find the wrap ternary in claude-runner.ts").toBeTruthy();- expect(gate).toContain("recoverySurfaceAllowed()");- expect(gate).toContain('paneCapability.kind === "wrap"');+ // Since the hook system (architecture §3.2, §7.5) the gate is planned in ONE call,+ // `planInteractiveSurfaces({capability, recoveryAllowed, sessionHooksNeedDriver})`,+ // whose rules `hooks/session/interactive-launch.test.ts` pins. These guards check that+ // claude-runner feeds it the two-switch predicate and uses its answer at both sites.+ const plan = /planInteractiveSurfaces\(\{([\s\S]{0,400}?)\}\)/.exec(code)?.[1];++ test("the surface plan is asked with recoverySurfaceAllowed(), and the wrap ternary obeys it", () => {+ expect(+ plan,+ "could not find the planInteractiveSurfaces call in claude-runner.ts"+ ).toBeTruthy();+ expect(plan).toContain("recoveryAllowed: recoverySurfaceAllowed()");+ expect(plan).toContain("capability: paneCapability");// The reverted form, named explicitly so the failure says what went wrong// rather than which substring is missing.expect(- /\bresolveRecoveryUi\(\)/.test(gate as string)- ? "the wrap gate asks resolveRecoveryUi() — --no-recovery will still wrap the session in magmux"+ /\bresolveRecoveryUi\(\)/.test(plan as string)+ ? "the surface plan asks resolveRecoveryUi() — --no-recovery will still wrap the session in magmux": null).toBeNull();+ const gate = /const wrap =\s*([\s\S]{0,160}?)\?\s*\n?\s*planMagmuxWrap/.exec(code)?.[1];+ expect(gate, "could not find the wrap ternary in claude-runner.ts").toBeTruthy();+ expect(gate).toContain("surfaces.wrap");+ expect(gate).toContain('paneCapability.kind === "wrap"');+ expect(/\bresolveRecoveryUi\(\)/.test(gate as string)).toBe(false);});- test("the ambient-magmux branch consults it too", () => {+ test("the ambient-magmux branch installs the recovery UI from that plan", () => {const branch = code.split("\n").find((l) => l.includes("else if") && /ambient|MAGMUX_SOCK/.test(l));expect(branch, "could not find the ambient branch in claude-runner.ts").toBeTruthy();- expect(branch).toContain("recoverySurfaceAllowed()");+ expect(branch).toContain('surfaces.recoveryUi === "ambient"');expect(/\bresolveRecoveryUi\(\)/.test(branch as string)? "the ambient branch asks resolveRecoveryUi() — --no-recovery still installs the recovery UI in a grid pane"@@ -437,12 +450,13 @@ describe("claude-runner asks that gate, and not the UI switch alone", () => {// `network-recovery.md`: one predicate decides the surface. The ambient branch// used to restate it as `config.interactive && process.env.MAGMUX_SOCK`, so a// case added to `magmuxPaneCapability()` (the pane child, D22) would still- // install the recovery UI here.+ // install the recovery UI here. The plan takes `paneCapability` whole.const branch = code.split("\n").find((l) => l.includes("else if") && /ambient|MAGMUX_SOCK/.test(l));expect(branch, "could not find the ambient branch in claude-runner.ts").toBeTruthy();- expect(branch).toContain('paneCapability.kind === "ambient"');expect(branch).not.toContain("MAGMUX_SOCK");+ expect(plan).toContain("capability: paneCapability");+ expect(plan).not.toContain("MAGMUX_SOCK");});});