Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(mcp): inherit the caller's settings in a create_session work_dir
Jack Rudenkodf8e124dcd69
diff --git a/ai-docs/architecture/mcp-sessions.md b/ai-docs/architecture/mcp-sessions.mdindex bfbc808f..5cc80a5d 100644--- a/ai-docs/architecture/mcp-sessions.md+++ b/ai-docs/architecture/mcp-sessions.md@@ -188,7 +188,8 @@ every runtime file (`output.log`, `events.jsonl`, `tokens.json`, `waits.jsonl`,"startedAt": "2026-10-02T10:00:00.000Z","model": "<as the caller asked for it>","timeoutSeconds": 600, // effective: min(requested ?? 600, 3600)- "claudeSessionId": "<the child's uuid>"+ "claudeSessionId": "<the child's uuid>",+ "setupFrom": "/abs/caller/project" // OPTIONAL — present only when the child inherits a settings layer}```@@ -335,6 +336,48 @@ into one unattributable file. The capture **redacts at write time** now that itonly a path a user opted into: a 401/403 body routinely echoes the credential that failed,and `get_diagnostics` hands these records to an agent.+### A work_dir child inherits the caller's settings layer++Claude Code reads project-scope settings (`enabledPlugins`, hooks, permissions, `env`) only from+`<cwd>/.claude/settings{,.local}.json`; it does not walk up to the repository root. A+`create_session` child runs with `work_dir` as its cwd, so before MTL-185 every plugin the+caller's project enables was off in it and `--agent dev:qa-engineer` was refused+(`agent_rejected`). Measured on Claude Code 2.1.306 (session `dev-fix-20261022-023522-f75563b5`):++| Child cwd | Flags | Agents listed |+|---|---|---|+| caller project (E1) | none | the full list (24) |+| sandbox inside the repo (E2) | none | the 5 built-ins |+| sandbox inside the repo (E8, E16) | `--settings` = the caller's layer | identical to E1 |+| sandbox outside the repo (E5) | `--settings` = the caller's layer | user-scope installs only: `dev` at the user row's version (9.2.0, not 9.4.0); `designer`, `madbench`, `code-search`, `code-simplifier` absent |+| sandbox outside the repo (E13) | the layer + one `--plugin-dir` per install row | identical to E1 |++What `createSession` does now (`mcp-session/inherited-settings.ts`, `session-manager.ts`):++- `setup_from` defaults to the server's cwd (the caller's project) and is skipped when it resolves+ to the child's own cwd, whose files Claude Code already reads. `setup_from: null` opts out: the+ child's argv and files are byte-for-byte what they were.+- The layer is `settings.json`, then `settings.local.json`, then every caller `--settings` value+ (both `--settings v` and `--settings=v`), merged in that order: objects deep, arrays+ concatenated without duplicates, scalars later-wins.+- **Exactly one `--settings` reaches the child.** Claude Code keeps only the LAST one (E14: the+ root settings then `{}` lists the 5 built-ins; E15, reversed, the full list), and claudish's+ child runner merges only the first bare `--settings` into its own overlay (`claude-runner.ts`).+ A second token would replace either the inherited layer or claudish's overlay (statusLine,+ `forceLoginMethod`, `editorMode`), and losing the overlay fails the pane at boot. So the caller's+ `--settings` are folded into the file and removed from argv.+- `permissions.additionalDirectories` is removed: it is `--add-dir` in settings form, and the main+ checkout's `settings.local.json` carries one that would re-open reads outside `work_dir`.+- The layer is written to `<sessionDir>/inherited-settings.json`, mode 0600, because+ `settings.local.json` can carry `env` secrets. Nothing is written to `work_dir` or `setup_from`.+ `spawn.json` records `setupFrom`. A file that is not a JSON object fails the call as+ `invalid_args`, before any pane starts.++Known gaps, not carried: exact plugin versions outside the repo (needs per-row `--plugin-dir`,+E13, which depends on Claude Code's undocumented install-row keying); project `.claude/skills`,+`.claude/commands` and `.mcp.json`; project hooks with relative paths, which resolve against+`work_dir`. `team` needs none of this: its slots run in the server's cwd.+## MCP Tools (15 total)- **Low-level** (3): `run_prompt`, `list_models`, `search_models`diff --git a/docs/usage/mcp-server.md b/docs/usage/mcp-server.mdindex 7c64e82f..a83026b5 100644--- a/docs/usage/mcp-server.md+++ b/docs/usage/mcp-server.md@@ -340,6 +340,7 @@ is interactive and waits for `send_input`.- `agent` (optional) - Claude Code subagent the session runs as, e.g. `dev:reviewer`- `claude_flags` (optional) - Other Claude Code / claudish flags and their values, space-separated, never positional text (write `--allowedTools Read,Bash`; a value after a Claude Code switch, as in `--brief now`, would be the session's first prompt and is refused). Flags the pane owns (`-p`, `--resume`, `--model`, …) and print-mode-only flags (`--max-turns`, `--max-budget-usd`, …) are refused- `work_dir` (optional) - Working directory for the session (default: current directory)+- `setup_from` (optional) - Directory whose `.claude/settings.json` and `settings.local.json` the session inherits, so a session in another `work_dir` keeps your project's plugins and agents. Default: your project directory, when `work_dir` differs from it. `null` keeps the session on `work_dir`'s own settings only**Returns:** `{ session_id: "...", state: "STARTING" }` as soon as the pane exists; Claude Code then boots in it.diff --git a/packages/cli/src/mcp-server.ts b/packages/cli/src/mcp-server.tsindex ab23186d..c4fe6564 100644--- a/packages/cli/src/mcp-server.ts+++ b/packages/cli/src/mcp-server.ts@@ -24,6 +24,7 @@ import { loadHooksOnce } from "./hooks/index.js";import { type ProtocolStdout, isolateProtocolStdout } from "./hooks/output-capture.js";import { initLogger, log } from "./logger.js";import { SessionManager } from "./mcp-session/index.js";+import { resolveSetupFrom } from "./mcp-session/inherited-settings.js";import { parentSessionForCall } from "./mcp-session/parent-session.js";import { NESTED_INSTRUCTIONS, NESTED_MCP_TOOL_NAMES } from "./mcp/nested-mode.js";import {@@ -1985,6 +1986,14 @@ function defineTools(sessionManager: SessionManager, nested: boolean): ToolDefintype: "string",description: "Working directory for the session (default: current directory)",},+ setup_from: {+ type: ["string", "null"],+ description:+ "Directory whose .claude/settings.json and settings.local.json the session " ++ "inherits (enabled plugins, permissions, env), so a session in another work_dir " ++ "keeps the caller's plugins and agents. Default: the caller's project directory, " ++ "when work_dir differs from it. null keeps the session on work_dir's own settings only.",+ },},required: ["model"],},@@ -2034,6 +2043,8 @@ function defineTools(sessionManager: SessionManager, nested: boolean): ToolDefintimeoutSeconds: args.timeout_seconds as number | undefined,claudishFlags,cwd: workDir,+ // Claude Code reads project settings only from the child's own cwd.+ setupFrom: resolveSetupFrom(args.setup_from, workDir, process.cwd()),parentClaudeSessionId,});diff --git a/packages/cli/src/mcp-session/inherited-settings.test.ts b/packages/cli/src/mcp-session/inherited-settings.test.tsnew file mode 100644index 00000000..6ee702ef--- /dev/null+++ b/packages/cli/src/mcp-session/inherited-settings.test.ts@@ -0,0 +1,336 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";++import {+ buildInheritedSettingsLayer,+ mergeSettingsLayers,+ resolveSetupFrom,+} from "./inherited-settings.js";++const PROJECT_SETTINGS = {+ enabledPlugins: { "dev@magus": true, "claudish@magus": true },+ permissions: { allow: ["Read"] },+};+const LOCAL_SETTINGS = {+ enabledPlugins: { "mnemex@magus": true },+ permissions: { allow: ["Bash(ls)"], additionalDirectories: ["/secret"] },+ env: { X: "1" },+};++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "claudish-inherited-settings-"));+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function writeSetupFiles(+ project: Record<string, unknown> = PROJECT_SETTINGS,+ local: Record<string, unknown> = LOCAL_SETTINGS+): { setupFrom: string; projectFile: string; localFile: string } {+ const setupFrom = join(tmp, "caller");+ const settingsDir = join(setupFrom, ".claude");+ mkdirSync(settingsDir, { recursive: true });+ const projectFile = join(settingsDir, "settings.json");+ const localFile = join(settingsDir, "settings.local.json");+ writeFileSync(projectFile, `${JSON.stringify(project, null, 2)}\n`);+ writeFileSync(localFile, `${JSON.stringify(local, null, 2)}\n`);+ return { setupFrom, projectFile, localFile };+}++function expectInvalidArgs(action: () => unknown, source: string): void {+ let thrown: unknown;+ try {+ action();+ } catch (error) {+ thrown = error;+ }+ expect(thrown).toBeInstanceOf(Error);+ expect((thrown as Error).message).toMatch(/^invalid_args:/);+ expect((thrown as Error).message).toContain(source);+}++describe("mergeSettingsLayers", () => {+ test("merges nested objects and keeps enabledPlugins from both layers", () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ const base = {+ enabledPlugins: { "dev@magus": true },+ nested: { settings: { first: "a" } },+ };+ const over = {+ enabledPlugins: { "claudish@magus": true },+ nested: { settings: { second: "b" } },+ };++ expect(mergeSettingsLayers(base, over)).toEqual({+ enabledPlugins: { "dev@magus": true, "claudish@magus": true },+ nested: { settings: { first: "a", second: "b" } },+ });+ });++ test("concatenates arrays and keeps the first occurrence of each JSON value", () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ const base = {+ permissions: { allow: ["A", "B"] },+ values: [{ tool: "Read" }, ["x"]],+ };+ const over = {+ permissions: { allow: ["B", "C"] },+ values: [{ tool: "Read" }, ["x"], { tool: "Write" }],+ };++ expect(mergeSettingsLayers(base, over)).toEqual({+ permissions: { allow: ["A", "B", "C"] },+ values: [{ tool: "Read" }, ["x"], { tool: "Write" }],+ });+ });++ test("uses the overriding scalar or replacement value", () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ expect(+ mergeSettingsLayers(+ { model: "a", enabled: true, count: 1, nested: { value: "a" } },+ { model: "b", enabled: false, count: 0, nested: null }+ )+ ).toEqual({ model: "b", enabled: false, count: 0, nested: null });+ });++ test("does not mutate either input", () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ const base = {+ enabledPlugins: { "dev@magus": true },+ permissions: { allow: ["A", "B"] },+ model: "a",+ };+ const over = {+ enabledPlugins: { "claudish@magus": true },+ permissions: { allow: ["B", "C"] },+ model: "b",+ };+ const beforeBase = structuredClone(base);+ const beforeOver = structuredClone(over);++ mergeSettingsLayers(base, over);++ expect(base).toEqual(beforeBase);+ expect(over).toEqual(beforeOver);+ });+});++describe("buildInheritedSettingsLayer", () => {+ test("inherits project and local settings without additionalDirectories", () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ const { setupFrom } = writeSetupFiles();+ const { layer, restFlags } = buildInheritedSettingsLayer(setupFrom, []);++ expect(layer).toEqual({+ enabledPlugins: { "dev@magus": true, "claudish@magus": true, "mnemex@magus": true },+ permissions: { allow: ["Read", "Bash(ls)"] },+ env: { X: "1" },+ });+ expect(layer).not.toHaveProperty("permissions.additionalDirectories");+ expect(restFlags).toEqual([]);+ });++ test("lets a local scalar override the project scalar", () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ const { setupFrom } = writeSetupFiles(+ { ...PROJECT_SETTINGS, model: "a" },+ { ...LOCAL_SETTINGS, model: "b" }+ );++ expect(buildInheritedSettingsLayer(setupFrom, []).layer?.model).toBe("b");+ });++ test("folds separate and equals settings flags into the layer and removes both", () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ const { setupFrom } = writeSetupFiles(+ { ...PROJECT_SETTINGS, model: "a" },+ { ...LOCAL_SETTINGS, model: "b" }+ );+ const settingsFile = join(tmp, "caller-settings.json");+ writeFileSync(settingsFile, '{"outputStyle":"x"}');+ const flags = ["--effort", "high", "--settings", '{"model":"c"}', `--settings=${settingsFile}`];++ const { layer, restFlags } = buildInheritedSettingsLayer(setupFrom, flags);++ expect(layer?.model).toBe("c");+ expect(layer?.outputStyle).toBe("x");+ expect(layer).toHaveProperty("enabledPlugins.dev@magus", true);+ expect(restFlags).toEqual(["--effort", "high"]);+ });++ test("applies every caller settings value in order before removing additionalDirectories", () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ const { setupFrom } = writeSetupFiles();+ const settingsFile = join(tmp, "ordered-settings.json");+ writeFileSync(+ settingsFile,+ JSON.stringify({+ model: "d",+ permissions: { allow: ["Read", "Bash(pwd)"], additionalDirectories: ["/caller-only"] },+ })+ );+ const flags = [+ "--effort",+ "high",+ "--settings",+ ' {"model":"c"}',+ "--resume",+ "session-id",+ "--settings",+ settingsFile,+ '--settings={"model":"e"}',+ "--quiet",+ ];++ const { layer, restFlags } = buildInheritedSettingsLayer(setupFrom, flags);++ expect(layer?.model).toBe("e");+ expect(layer).toHaveProperty("permissions.allow", ["Read", "Bash(ls)", "Bash(pwd)"]);+ expect(layer).not.toHaveProperty("permissions.additionalDirectories");+ expect(restFlags).toEqual(["--effort", "high", "--resume", "session-id", "--quiet"]);+ });++ test("returns a null layer and unchanged flags when there are no settings sources", () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ const flags = ["--effort", "high"];++ expect(buildInheritedSettingsLayer(tmp, flags)).toEqual({ layer: null, restFlags: flags });+ });++ test("skips a missing project settings file and reads local settings", () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ const settingsDir = join(tmp, ".claude");+ mkdirSync(settingsDir);+ writeFileSync(join(settingsDir, "settings.local.json"), '{"model":"local"}');++ expect(buildInheritedSettingsLayer(tmp, [])).toEqual({+ layer: { model: "local" },+ restFlags: [],+ });+ });++ test("skips a missing local settings file and reads project settings", () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ const settingsDir = join(tmp, ".claude");+ mkdirSync(settingsDir);+ writeFileSync(join(settingsDir, "settings.json"), '{"model":"project"}');++ expect(buildInheritedSettingsLayer(tmp, [])).toEqual({+ layer: { model: "project" },+ restFlags: [],+ });+ });++ test("builds a caller-only layer even when setupFrom has no settings files", () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ expect(buildInheritedSettingsLayer(tmp, ["--settings", '{"model":"c"}'])).toEqual({+ layer: { model: "c" },+ restFlags: [],+ });+ });++ test("rejects malformed project JSON with invalid_args and the offending path", () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ const { setupFrom, projectFile } = writeSetupFiles();+ writeFileSync(projectFile, "{not json");++ expectInvalidArgs(() => buildInheritedSettingsLayer(setupFrom, []), projectFile);+ });++ test("rejects project JSON that is not an object", () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ const { setupFrom, projectFile } = writeSetupFiles();+ writeFileSync(projectFile, "[]");++ expectInvalidArgs(() => buildInheritedSettingsLayer(setupFrom, []), projectFile);+ });++ test("rejects malformed local JSON with invalid_args and the offending path", () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ const { setupFrom, localFile } = writeSetupFiles();+ writeFileSync(localFile, "{not json");++ expectInvalidArgs(() => buildInheritedSettingsLayer(setupFrom, []), localFile);+ });++ test("rejects malformed inline settings and names the offending value", () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ const { setupFrom } = writeSetupFiles();+ const value = "{not json";++ expectInvalidArgs(() => buildInheritedSettingsLayer(setupFrom, ["--settings", value]), value);+ });++ test("rejects a caller settings file whose JSON is not an object", () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ const { setupFrom } = writeSetupFiles();+ const settingsFile = join(tmp, "invalid-caller-settings.json");+ writeFileSync(settingsFile, "null");++ expectInvalidArgs(+ () => buildInheritedSettingsLayer(setupFrom, [`--settings=${settingsFile}`]),+ settingsFile+ );+ });++ test("leaves project, local, and caller settings files byte-identical", () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ const { setupFrom, projectFile, localFile } = writeSetupFiles();+ const settingsFile = join(tmp, "unchanged-caller-settings.json");+ writeFileSync(settingsFile, ' \n{"outputStyle": "x"}\n');+ const files = [projectFile, localFile, settingsFile];+ const before = files.map((file) => readFileSync(file));++ buildInheritedSettingsLayer(setupFrom, [+ "--settings",+ '{"model":"c"}',+ `--settings=${settingsFile}`,+ ]);++ expect(files.map((file) => readFileSync(file))).toEqual(before);+ });+});++describe("resolveSetupFrom", () => {+ test("treats null as an explicit opt-out", () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ expect(resolveSetupFrom(null, join(tmp, "work"), join(tmp, "caller"))).toBeUndefined();+ });++ test("defaults undefined to serverCwd when the work directory differs", () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ const serverCwd = join(tmp, "caller");++ expect(resolveSetupFrom(undefined, join(tmp, "work"), serverCwd)).toBe(serverCwd);+ });++ test("resolves a relative setup directory against the process cwd", () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ expect(resolveSetupFrom("rel/x", join(tmp, "work"), join(tmp, "server"))).toBe(+ resolve("rel/x")+ );+ });++ test("omits inheritance when work_dir is absent and setup resolves to serverCwd", () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ const serverCwd = join(tmp, "caller");++ expect(resolveSetupFrom(undefined, undefined, serverCwd)).toBeUndefined();+ expect(resolveSetupFrom(serverCwd, undefined, serverCwd)).toBeUndefined();+ });++ test("omits inheritance when the resolved setup directory equals work_dir", () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ const workDir = join(tmp, "caller");++ expect(resolveSetupFrom(`${workDir}/nested/..`, workDir, join(tmp, "server"))).toBeUndefined();+ expect(resolveSetupFrom(resolve("rel/x"), "rel/x", join(tmp, "server"))).toBeUndefined();+ });+});diff --git a/packages/cli/src/mcp-session/inherited-settings.ts b/packages/cli/src/mcp-session/inherited-settings.tsnew file mode 100644index 00000000..8f1c6848--- /dev/null+++ b/packages/cli/src/mcp-session/inherited-settings.ts@@ -0,0 +1,141 @@+/**+ * The caller's project settings, carried into a `create_session` child that runs+ * in another directory (MTL-185, claudish#284).+ *+ * Claude Code reads project-scope settings only from `<cwd>/.claude/`, and a child+ * started in `work_dir` has that as its cwd, so every plugin the caller's project+ * enables is off in the child. The layer built here is handed to the child as ONE+ * `--settings` value: Claude Code keeps only the LAST `--settings`, so a second one+ * would replace either this layer or claudish's own overlay. See+ * ai-docs/architecture/mcp-sessions.md § A work_dir child inherits the caller's+ * settings layer.+ */++import { existsSync, readFileSync } from "node:fs";+import { join, resolve } from "node:path";++type SettingsLayer = Record<string, unknown>;++function isPlainObject(value: unknown): value is SettingsLayer {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++/** `values` with repeats removed, the first occurrence kept, compared by JSON value. */+function uniqueByJson(values: unknown[]): unknown[] {+ const seen = new Set<string>();+ return values.filter((value) => {+ const key = JSON.stringify(value);+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+}++/**+ * Deep-merge two settings layers the way Claude Code merges settings sources:+ * plain objects merge recursively; arrays concatenate with duplicates removed+ * (first occurrence kept, compared by JSON value); any other value: `over` wins.+ * Neither input is mutated.+ */+export function mergeSettingsLayers(base: SettingsLayer, over: SettingsLayer): SettingsLayer {+ const merged: SettingsLayer = structuredClone(base);+ for (const [key, value] of Object.entries(over)) {+ const current = merged[key];+ if (isPlainObject(current) && isPlainObject(value)) {+ merged[key] = mergeSettingsLayers(current, value);+ } else if (Array.isArray(current) && Array.isArray(value)) {+ merged[key] = uniqueByJson([...current, ...structuredClone(value)]);+ } else {+ merged[key] = structuredClone(value);+ }+ }+ return merged;+}++/** One layer's JSON object; anything else is `invalid_args` naming `source`. */+function parseLayer(text: string, source: string): SettingsLayer {+ let parsed: unknown;+ try {+ parsed = JSON.parse(text);+ } catch (err) {+ throw new Error(+ `invalid_args: settings ${source} is not valid JSON (${(err as Error).message})`+ );+ }+ if (!isPlainObject(parsed)) {+ throw new Error(`invalid_args: settings ${source} is not a JSON object`);+ }+ return parsed;+}++/** A `--settings` value: inline JSON when it starts with `{`, else a file path. */+function readSettingsValue(value: string): SettingsLayer {+ if (value.trim().startsWith("{")) return parseLayer(value, value);+ let text: string;+ try {+ text = readFileSync(value, "utf-8");+ } catch (err) {+ throw new Error(`invalid_args: settings ${value} cannot be read (${(err as Error).message})`);+ }+ return parseLayer(text, value);+}++/**+ * The layer a child in another directory needs to see the caller's project setup.+ * Reads `<setupFrom>/.claude/settings.json` then `<setupFrom>/.claude/settings.local.json`+ * (a missing file is skipped), then folds EVERY `--settings` value found in `callerFlags`+ * on top, in order. Both forms count: `--settings <v>` and `--settings=<v>`.+ *+ * `permissions.additionalDirectories` is removed from the result: it is `--add-dir` in+ * settings form and would widen the child's file access beyond work_dir.+ *+ * `restFlags` is `callerFlags` with every `--settings` token (and its value) removed.+ * `layer` is null when no settings file exists in setupFrom and no `--settings` was given.+ * A source that is not a JSON object throws `invalid_args:` naming it. Never writes.+ */+export function buildInheritedSettingsLayer(+ setupFrom: string,+ callerFlags: readonly string[]+): { layer: SettingsLayer | null; restFlags: string[] } {+ const layers: SettingsLayer[] = [];+ for (const name of ["settings.json", "settings.local.json"]) {+ const file = join(setupFrom, ".claude", name);+ if (!existsSync(file)) continue;+ layers.push(parseLayer(readFileSync(file, "utf-8"), file));+ }++ const restFlags: string[] = [];+ for (let i = 0; i < callerFlags.length; i++) {+ const flag = callerFlags[i];+ if (flag === "--settings") {+ const value = callerFlags[i + 1];+ if (value === undefined) throw new Error("invalid_args: --settings needs a value");+ layers.push(readSettingsValue(value));+ i++;+ } else if (flag.startsWith("--settings=")) {+ layers.push(readSettingsValue(flag.slice("--settings=".length)));+ } else {+ restFlags.push(flag);+ }+ }++ if (layers.length === 0) return { layer: null, restFlags };+ const layer = layers.reduce((acc, next) => mergeSettingsLayers(acc, next), {});+ if (isPlainObject(layer.permissions)) delete layer.permissions.additionalDirectories;+ return { layer, restFlags };+}++/**+ * The setup directory a create_session call uses: `null` opts out, a string is+ * resolved, `undefined` is the server's cwd (the caller's project). Undefined when+ * that is the child's own directory, whose files Claude Code already reads natively.+ */+export function resolveSetupFrom(+ arg: unknown,+ workDir: string | undefined,+ serverCwd: string+): string | undefined {+ if (arg === null) return undefined;+ const setupFrom = typeof arg === "string" ? resolve(arg) : serverCwd;+ return setupFrom === resolve(workDir ?? serverCwd) ? undefined : setupFrom;+}diff --git a/packages/cli/src/mcp-session/session-manager.ts b/packages/cli/src/mcp-session/session-manager.tsindex c5e13845..346f9269 100644--- a/packages/cli/src/mcp-session/session-manager.ts+++ b/packages/cli/src/mcp-session/session-manager.ts@@ -100,6 +100,7 @@ import { projectsDir, transcriptPathFor } from "../session/session-discovery.js"import { TRUNCATION_NOTE, type TeamRunOutcome, classifyRunOutput } from "../team-orchestrator.js";import { readTokenStatsAt } from "../team-stats.js";import { sessionsDirFrom } from "./home-dir.js";+import { buildInheritedSettingsLayer } from "./inherited-settings.js";import { hostPidFrom } from "./parent-session.js";import { ScrollbackBuffer } from "./scrollback-buffer.js";import type {@@ -326,6 +327,9 @@ const UPSTREAM_ERROR_TAIL_BYTES = 64 * 1024;*/const SPAWN_RECORD_SCHEMA = 1;+/** The caller's settings layer, in the session dir (never in work_dir or setupFrom). */+const INHERITED_SETTINGS = "inherited-settings.json";+/** RUNNING activities that are not a tool name (§8 B). */// "hook": a settled turn held while session hooks run (§7.3); not a toolconst NON_TOOL_ACTIVITY = new Set(["thinking", "background", "finishing", "hook"]);@@ -841,6 +845,7 @@ export class SessionManager {claudeSessionId?: string;teamPath?: string;slots?: number;+ setupFrom?: string;}): void {const { kind, sessionId, parentClaudeSessionId, startedAt, ...rest } = record;@@ -875,9 +880,14 @@ export class SessionManager {if (opts.sessionId !== undefined && this.sessions.has(opts.sessionId)) {throw new Error(`Session id already in use: ${opts.sessionId}`);}- const flags = opts.claudishFlags ?? [];- const flagCheck = checkChildFlags(flags);+ const callerFlags = opts.claudishFlags ?? [];+ const flagCheck = checkChildFlags(callerFlags);if (!flagCheck.ok) throw new Error(`invalid_args: ${flagCheck.message}`);+ // Built before any pane, so a malformed settings file fails the call as invalid_args.+ const inherited = opts.setupFrom+ ? buildInheritedSettingsLayer(opts.setupFrom, callerFlags)+ : { layer: null, restFlags: callerFlags };+ let flags = callerFlags;const readAvailable = !flagsRemoveRead(flags);if (opts.prompt) {const refusal = deliveryRefusal(opts.prompt, readAvailable);@@ -898,11 +908,16 @@ export class SessionManager {reservePanes(1, sockRootFor(parentEnv));let entry: SessionEntry;try {- entry = this.recordSession(opts);+ entry = this.recordSession(opts, inherited.layer);} catch (err) {releasePaneReservations(1);throw err;}+ // The caller's `--settings` are inside the file: exactly one `--settings` reaches+ // the child, since Claude Code keeps only the last one.+ if (inherited.layer) {+ flags = [...inherited.restFlags, "--settings", join(entry.sessionDir, INHERITED_SETTINGS)];+ }this.sessions.set(entry.info.sessionId, entry);uncount();const started = this.startPane(entry, opts, { flags, readAvailable, parentEnv });@@ -919,8 +934,14 @@ export class SessionManager {}}- /** `prompt.md`, `spawn.json` and the in-memory entry (STARTING). Throws before any pane. */- private recordSession(opts: SessionCreateOptions): SessionEntry {+ /**+ * `prompt.md`, `spawn.json`, `inherited-settings.json` (when there is a layer) and the+ * in-memory entry (STARTING). Throws before any pane.+ */+ private recordSession(+ opts: SessionCreateOptions,+ inheritedLayer: Record<string, unknown> | null+ ): SessionEntry {const sessionId = opts.sessionId ?? randomUUID().slice(0, 8);// Minted here: it is the child's transcript basename, known BEFORE the pane starts.const claudeSessionId = randomUUID();@@ -942,7 +963,16 @@ export class SessionManager {model: opts.model,timeoutSeconds: timeout,claudeSessionId,+ ...(opts.setupFrom ? { setupFrom: opts.setupFrom } : {}),});+ // 0600: the caller's settings.local.json can carry `env` secrets.+ if (inheritedLayer) {+ writeFileSync(+ join(sessionDir, INHERITED_SETTINGS),+ `${JSON.stringify(inheritedLayer, null, 2)}\n`,+ { encoding: "utf-8", mode: 0o600 }+ );+ }const cwd = opts.cwd ?? process.cwd();const parentEnv = opts.parentEnv ?? this.parentEnv;diff --git a/packages/cli/src/mcp-session/session-setup-inherit.test.ts b/packages/cli/src/mcp-session/session-setup-inherit.test.tsnew file mode 100644index 00000000..cd25ba2d--- /dev/null+++ b/packages/cli/src/mcp-session/session-setup-inherit.test.ts@@ -0,0 +1,178 @@+/** Process-level coverage for caller setup inheritance in a real headless magmux pane. */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ existsSync,+ mkdirSync,+ readFileSync,+ readdirSync,+ realpathSync,+ statSync,+ writeFileSync,+} from "node:fs";+import { isAbsolute, join, sep } from "node:path";++import {+ MAGMUX,+ NO_MAGMUX_MESSAGE,+ type PaneTestEnv,+ killLeftovers,+ makePaneTestEnv,+ waitNoOrphans,+} from "../pane/test-helpers/hermetic-env.js";+import { SessionManager } from "./session-manager.js";++const T_PANE = 30_000;++type ChildProbe = { argv: string[]; env: Record<string, string>; cwd: string };+type InheritedSettings = { enabledPlugins: Record<string, boolean>; model?: string };++function waitUntil(predicate: () => boolean, timeoutMs = 10_000): Promise<void> {+ return new Promise((resolve, reject) => {+ const deadline = Date.now() + timeoutMs;+ const check = () => {+ if (predicate()) return resolve();+ if (Date.now() >= deadline) return reject(new Error("waitUntil timed out"));+ setTimeout(check, 20);+ };+ check();+ });+}++describe.skipIf(!MAGMUX)(+ `SessionCreateOptions setup inheritance (${MAGMUX ? "magmux" : NO_MAGMUX_MESSAGE})`,+ () => {+ let t: PaneTestEnv;+ let sessionsDir: string;+ let probe: string;+ let managers: SessionManager[];++ beforeEach(() => {+ t = makePaneTestEnv();+ sessionsDir = join(t.tmp, "sessions");+ probe = join(t.tmp, "probe-{session}.json");+ managers = [];+ });++ afterEach(async () => {+ for (const m of managers) await m.shutdownAll();+ const report = await waitNoOrphans({ sockRoot: t.sockRoot }, 10_000);+ killLeftovers({ sockRoot: t.sockRoot });+ t.cleanup();+ expect(report).toEqual({ processes: [], files: [] });+ });++ function makeManager(): SessionManager {+ const manager = new SessionManager({+ sessionsDir,+ hostPid: 1,+ parentEnv: { ...t.env, FAKE_PROBE_FILE: probe },+ paneTimings: { replStableMs: 200 },+ });+ managers.push(manager);+ return manager;+ }++ async function childProbe(manager: SessionManager, sessionId: string): Promise<ChildProbe> {+ const path = probe.replace("{session}", manager.getSession(sessionId).claudeSessionId);+ await waitUntil(() => existsSync(path));+ return JSON.parse(readFileSync(path, "utf-8")) as ChildProbe;+ }++ async function expectInheritedSession(claudishFlags: string[]): Promise<InheritedSettings> {+ const caller = join(t.tmp, "caller");+ const work = join(t.tmp, "work");+ mkdirSync(join(caller, ".claude"), { recursive: true });+ mkdirSync(work);+ const callerSettings = join(caller, ".claude", "settings.json");+ writeFileSync(callerSettings, '{"enabledPlugins":{"dev@magus":true}}\n');+ const before = readFileSync(callerSettings);+ const manager = makeManager();++ const sessionId = await manager.createSession({+ model: "fake-env_probe",+ cwd: work,+ setupFrom: caller,+ claudishFlags,+ });+ const child = await childProbe(manager, sessionId);+ const sessionDir = join(sessionsDir, sessionId);+ expect(manager.getDiagnostics(sessionId).sessionDir).toBe(sessionDir);+ expect(child.argv.filter((arg) => arg === "--settings")).toHaveLength(1);+ expect(child.argv.some((arg) => arg.startsWith("--settings="))).toBe(false);+ const settingsPath = child.argv[child.argv.indexOf("--settings") + 1];+ expect(isAbsolute(settingsPath)).toBe(true);+ expect(settingsPath).toBe(join(sessionDir, "inherited-settings.json"));+ expect(settingsPath.startsWith(`${sessionsDir}${sep}`)).toBe(true);+ expect(settingsPath.startsWith(`${work}${sep}`)).toBe(false);+ expect(settingsPath.startsWith(`${caller}${sep}`)).toBe(false);++ const settings = JSON.parse(readFileSync(settingsPath, "utf-8")) as InheritedSettings;+ expect(settings.enabledPlugins["dev@magus"]).toBe(true);+ expect(statSync(settingsPath).mode & 0o777).toBe(0o600);+ expect(child.cwd).toBe(realpathSync(work));+ const spawn = JSON.parse(readFileSync(join(sessionDir, "spawn.json"), "utf-8")) as Record<+ string,+ unknown+ >;+ expect(spawn.setupFrom).toBe(caller);++ await manager.shutdownAll();+ expect(readdirSync(work)).toEqual([]);+ expect(readFileSync(callerSettings)).toEqual(before);+ return settings;+ }++ test(+ "inherits caller plugins through one private settings file outside the work directory",+ async () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ await expectInheritedSession([]);+ },+ T_PANE+ );++ test(+ "merges a caller settings flag into the inherited file without adding another settings flag",+ async () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ const settings = await expectInheritedSession(["--settings", '{"model":"c"}']);+ expect(settings.model).toBe("c");+ },+ T_PANE+ );++ test(+ "omitting setupFrom adds no settings flag, inherited file, or spawn metadata",+ async () => {+ // REGRESSION: MTL-204/MTL-185 sandbox child lost the caller's plugins — /dev:fix session dev-fix-20261022-023522-f75563b5+ const work = join(t.tmp, "work");+ mkdirSync(work);+ const manager = makeManager();+ const sessionId = await manager.createSession({+ model: "fake-env_probe",+ cwd: work,+ claudishFlags: [],+ });+ const child = await childProbe(manager, sessionId);+ const sessionDir = join(sessionsDir, sessionId);++ expect(manager.getDiagnostics(sessionId).sessionDir).toBe(sessionDir);+ expect(+ child.argv.filter((arg) => arg === "--settings" || arg.startsWith("--settings="))+ ).toEqual([]);+ expect(existsSync(join(sessionDir, "inherited-settings.json"))).toBe(false);+ const spawn = JSON.parse(readFileSync(join(sessionDir, "spawn.json"), "utf-8")) as Record<+ string,+ unknown+ >;+ expect(spawn).not.toHaveProperty("setupFrom");+ expect(child.cwd).toBe(realpathSync(work));++ await manager.shutdownAll();+ expect(readdirSync(work)).toEqual([]);+ },+ T_PANE+ );+ }+);diff --git a/packages/cli/src/mcp-session/types.ts b/packages/cli/src/mcp-session/types.tsindex 1efd9b32..7b49808f 100644--- a/packages/cli/src/mcp-session/types.ts+++ b/packages/cli/src/mcp-session/types.ts@@ -145,6 +145,14 @@ export interface SessionCreateOptions {timeoutSeconds?: number;claudishFlags?: string[];cwd?: string;+ /**+ * The directory whose `.claude/settings{,.local}.json` the child inherits. Claude+ * Code reads project settings only from `<cwd>/.claude`, so a child in another+ * `cwd` would otherwise lose every plugin the caller's project enables. The layer+ * (with the caller's own `--settings` folded in) becomes the child's ONE+ * `--settings` file, `<sessionDir>/inherited-settings.json`. Absent → today's flags.+ */+ setupFrom?: string;/*** Use this id instead of minting a random one. Must be unique among live sessions;* a collision throws rather than silently adopting the existing session.