diff --git a/.changeset/masked-brain-cli-fallback.md b/.changeset/masked-brain-cli-fallback.md new file mode 100644 index 0000000000..70b82e59e4 --- /dev/null +++ b/.changeset/masked-brain-cli-fallback.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": patch +--- + +A brain without a packaged CLI (`node_modules/.bin/brain`) whose `scripts/brain-cli.ts` fallback is protected now reads its taxonomy and builds a provider-restricted turn's private index in the masked worker (#2865). The worker launcher admits only an absolute executable, so the fallback's `bun` used to be refused as an unavailable worker boundary; every `types:` provider selector then refused and the private index stayed incomplete. The masked worker now runs the fallback on the server's own Bun, the runtime it already admits, and the script still resolves inside the turn's immutable startup view with no added mount. Host CLI calls and packaged CLI selection are unchanged. A configured command whose executable is another relative name refuses by name before anything launches, and a failed run's detail no longer ends on Bun's version banner instead of the error. diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index d90ec9cdfc..c5b90d6335 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -63,7 +63,7 @@ next to it. - **Updated.** Nothing in the tree installs, updates, pins or reads the version of this binary. The only version probe in the server is for the `brain` CLI (`Probe the selected content CLI`, - `packages/ui-server/src/brain/client.ts:163-231`, called at + `packages/ui-server/src/brain/client.ts:180-248`, called at `probeBrainCliVersion(config.brainPath`, `packages/ui-server/src/app.ts:451`). `brain doctor` runs `claude mcp list` from `PATH` (`which("claude")`, `packages/core/src/cli/commands/doctor.ts:503-507`) — the user's own Claude @@ -243,7 +243,7 @@ than refuses on a mismatch.** pair is one nobody measured. - **At boot, from the binary a turn would spawn.** The same shape as the `brain` CLI probe (`Probe the selected content CLI`, - `packages/ui-server/src/brain/client.ts:163`). The SDK's + `packages/ui-server/src/brain/client.ts:180`). The SDK's resolver is not exported, so the probe must not re-implement it. The SDK resolves the binary when a query is built, and fails there if none is found (`node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs:228`); it then hands diff --git a/docs/decisions/runtime-requirements.md b/docs/decisions/runtime-requirements.md index 070413274d..4b662ba027 100644 --- a/docs/decisions/runtime-requirements.md +++ b/docs/decisions/runtime-requirements.md @@ -275,7 +275,7 @@ reciprocal host-version negotiation is involved. | Existing boundary | How this design uses it | | --- | --- | -| `probeBrainCliVersion` / `brainCliCommand` (`export async function probeBrainCliVersion`, `packages/ui-server/src/brain/client.ts:164-231`) | Reuse executable selection, wrapper, deadline and cleanup; add host floor composition, strict comparison and invocation verification without duplicating the 0.33.0 constant. | +| `probeBrainCliVersion` / `brainCliCommand` (`export async function probeBrainCliVersion`, `packages/ui-server/src/brain/client.ts:181-248`) | Reuse executable selection, wrapper, deadline and cleanup; add host floor composition, strict comparison and invocation verification without duplicating the 0.33.0 constant. | | `installedAgentSdkVersion` (`export function installedAgentSdkVersion`, `packages/ui-backend-claude/src/runtime-probe.ts:55-61`) | Retain importer-relative resolution; validate package name/version and the owner's manifest range. | | `selectedSpawn` / `probeClaudeRuntime` (`export function selectedSpawn`, `packages/ui-backend-claude/src/runtime-probe.ts:69-96`; `export async function probeClaudeRuntime`, `packages/ui-backend-claude/src/runtime-probe.ts:127-147`) | Keep SDK-selected command capture, native/JS override argv, environment, timeout and group cleanup; add strict identity validation and composed runtime floors. | | `probeBackendRuntimes` (`export async function probeBackendRuntimes`, `packages/ui-server/src/agent/backend.ts:394-444`) | Forward validated host requirements; retain active-backend selection and separate unmeasured-pair logging. | diff --git a/docs/plans/storage-lifecycle.md b/docs/plans/storage-lifecycle.md index f7e5e64786..72ec665cfd 100644 --- a/docs/plans/storage-lifecycle.md +++ b/docs/plans/storage-lifecycle.md @@ -31,7 +31,7 @@ Use maintenance workers for repository code, the CLI and Git. Host routes may perform narrowly validated descriptor operations, as the journal/revert do; they must not evaluate brain configuration, hooks, filters or executables. The existing brain client supplies boundary execution -(`async function execBrain`, `packages/ui-server/src/brain/client.ts:285-340`). +(`async function execBrain`, `packages/ui-server/src/brain/client.ts:302-357`). Do not turn the new surface into a host command runner or an extension seam. Reuse existing authorization. A requested reversible, fully journaled edit diff --git a/docs/process/evidence/test-wait-review-partition.json b/docs/process/evidence/test-wait-review-partition.json index c36eccc100..c149022253 100644 --- a/docs/process/evidence/test-wait-review-partition.json +++ b/docs/process/evidence/test-wait-review-partition.json @@ -1999,7 +1999,7 @@ "basis": "Embedded `brain` CLI body written by brainWithCli or an inline fake bin; the test spawns it through the brain client and never waits for the literal. The hold exists so the cancellation path has a live child to kill. No completed elapsed minimum is implied by the literal.", "noElapsedMinimumImplied": true, "raceWinner": "controller.abort() after the host PID is seen wins; the 60000 ms sleep never completes in a passing run", - "holdEnd": "SIGKILL: the client's execBrain passes killSignal SIGKILL with the abort signal (packages/ui-server/src/brain/client.ts:274-276). The test asserts the rejection arrives only after the child stops answering signal 0." + "holdEnd": "SIGKILL: the client's execBrain passes killSignal SIGKILL with the abort signal (packages/ui-server/src/brain/client.ts:339). The test asserts the rejection arrives only after the child stops answering signal 0." }, "observation": null, "followUp": null diff --git a/packages/ui-server/src/brain/client.ts b/packages/ui-server/src/brain/client.ts index c317efb22a..eb97f70846 100644 --- a/packages/ui-server/src/brain/client.ts +++ b/packages/ui-server/src/brain/client.ts @@ -1,5 +1,5 @@ import { existsSync } from "fs"; -import { join } from "path"; +import { isAbsolute, join } from "path"; import type { Logger } from "@opentelemetry/api-logs"; import { ambientExecConfig, subprocessEnv } from "../config/env.js"; import { MaintenanceTempBusyError, VERSION_PROBE_TIMEOUT_MS } from "@schlessera/brain-ui-sdk/internal"; @@ -150,6 +150,23 @@ export function brainCliCommand(brainPath: string): string[] { return ["bun", "scripts/brain-cli.ts"]; } +/** + * The CLI argv a masked worker runs (#2865). The worker launcher admits only + * an absolute executable, so the `scripts/brain-cli.ts` fallback's bare `bun` + * becomes the server's own Bun, the runtime every worker envelope already + * admits. The script stays relative: the worker starts in the brain's + * immutable startup view, so it resolves there, never against the live brain, + * and adds no mount. Any other relative executable has no admitted path and + * refuses by name. {@link brainCliCommand} and host calls are unchanged. + */ +export function workerBrainCliCommand(command: readonly string[]): { ok: true; command: string[] } | { ok: false; detail: string } { + const [executable, ...rest] = command; + if (!executable) return { ok: false, detail: "no CLI command was given" }; + if (isAbsolute(executable)) return { ok: true, command: [...command] }; + if (executable === "bun") return { ok: true, command: [process.execPath, ...rest] }; + return { ok: false, detail: `its executable, ${executable}, is not an absolute path, and only the brain-cli fallback's bun is resolved, to the server's own runtime` }; +} + /** The keyword index pass that builds a provider-restricted turn's private index (#1668). */ export function privateIndexArgv(brainPath: string, command: readonly string[] = brainCliCommand(brainPath)): string[] { return [...command, "index", "--json"]; diff --git a/packages/ui-server/src/brain/private-index.ts b/packages/ui-server/src/brain/private-index.ts index 69c08f8e43..bdfb76664c 100644 --- a/packages/ui-server/src/brain/private-index.ts +++ b/packages/ui-server/src/brain/private-index.ts @@ -22,7 +22,7 @@ import { chmodSync, chownSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { launchAgentWorker, prepareWorkerSandbox, retainWorkerStartupView, workerIdentityHelper, type WorkerStartupView } from "@schlessera/brain-ui-sdk/internal"; -import { privateIndexArgv } from "./client.js"; +import { privateIndexArgv, workerBrainCliCommand } from "./client.js"; /** How long admission waits for the private index; a slower build leaves a partial index. */ export const PRIVATE_INDEX_BUILD_MS = 120_000; @@ -58,10 +58,21 @@ async function bounded(stream: unknown, bytes: number): Promise<{ text: string; return { text: new TextDecoder().decode(Buffer.concat(kept)), whole }; } +/** + * The last line of a failed run's stderr that says why. Bun ends an uncaught + * error, such as a CLI script it cannot find, with its own version banner, + * which names nothing (#2865). + */ +function exitReason(stderr: string): string { + return stderr.split("\n").map(line => line.trim()).filter(line => line && !/^Bun v\d\S* \(/u.test(line)).at(-1) ?? ""; +} + /** * Run the brain's own CLI in a credential-free strict worker on the immutable * startup view, with `folders` masked, `.git` hidden and only the private - * index directory writable. Repository code never runs on the host. + * index directory writable. Repository code never runs on the host. The + * `scripts/brain-cli.ts` fallback runs on the server's own Bun + * (`workerBrainCliCommand`). */ export async function runMaskedBrainCli(options: { brainPath: string; startupView: WorkerStartupView; folders: readonly string[]; index: string; @@ -72,6 +83,9 @@ export async function runMaskedBrainCli(options: { visible?: readonly string[]; }): Promise<{ ok: true; stdout: string } | { ok: false; detail: string; stdout?: string }> { options.signal.throwIfAborted(); + // Refused before anything launches: the host never runs the command. + const command = workerBrainCliCommand(options.command); + if (!command.ok) return { ok: false, detail: `${options.label} cannot run in a masked worker: ${command.detail}` }; const sandbox = { ...prepareWorkerSandbox(options.brainPath, { profile: "strict", areas: [], maskPaths: options.maskPaths }), providerMasks: Object.freeze({ folders: Object.freeze([...options.folders]), index: options.index, indexWritable: true, ...(options.visible ? { visible: Object.freeze([...options.visible]) } : {}) }) }; @@ -80,7 +94,7 @@ export async function runMaskedBrainCli(options: { try { worker = launchAgentWorker({ brainPath: options.brainPath, startupView: view, sandbox, env: { PATH: [dirname(process.execPath), "/usr/local/bin", "/usr/bin", "/bin"].join(":"), BRAIN_ROOT: options.brainPath, HOME: "/tmp", NO_COLOR: "1" }, - command: [...options.command] }); + command: command.command }); } catch (error) { await view.cleanup(); return { ok: false, detail: error instanceof Error ? error.message : String(error) }; @@ -93,7 +107,7 @@ export async function runMaskedBrainCli(options: { const [stdout, stderr, exit] = await Promise.all([bounded(worker.stdout, options.outputBytes ?? OUTPUT_BYTES), bounded(worker.stderr, OUTPUT_BYTES), worker.exited]); options.signal.throwIfAborted(); if (timedOut) return { ok: false, detail: `${options.label} did not finish within ${options.timeoutMs / 1000} s` }; - if (exit !== 0) return { ok: false, detail: `${options.label} exited ${exit}: ${stderr.text.trim().split("\n").at(-1) ?? ""}`, + if (exit !== 0) return { ok: false, detail: `${options.label} exited ${exit}: ${exitReason(stderr.text)}`, ...(options.outputBytes !== undefined && stdout.whole ? { stdout: stdout.text } : {}) }; // Output is read only when it is wanted, and then only whole. return options.outputBytes === undefined || stdout.whole ? { ok: true, stdout: stdout.text } diff --git a/packages/ui-server/tests/private-index.test.ts b/packages/ui-server/tests/private-index.test.ts index a9c4dd2446..1095bc77cc 100644 --- a/packages/ui-server/tests/private-index.test.ts +++ b/packages/ui-server/tests/private-index.test.ts @@ -7,13 +7,15 @@ import { installFixtureNativeStartupViews } from "./helpers/fixture-native-startup.js"; installFixtureNativeStartupViews(); import { expectRejection } from "./helpers/expect-rejection.js"; -import { afterEach, expect, spyOn, test, type Mock } from "bun:test"; +import { afterAll, afterEach, expect, spyOn, test, type Mock } from "bun:test"; +import { Database } from "bun:sqlite"; import { cpSync, existsSync, linkSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; -import { join, resolve } from "node:path"; +import { dirname, join, resolve } from "node:path"; import { launchAgentWorker, workerCommand } from "../../ui-sdk/src/server/worker-launcher"; import * as startup from "../../ui-sdk/src/server/worker-startup-view"; import { createFixtureWorkerStartupView } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture"; import { createUiDb } from "../src/db/client"; +import { brainCliCommand, workerBrainCliCommand } from "../src/brain/client"; import { createHostExecution } from "../src/brain/host-execution"; import { createGovernedTurns } from "../src/brain/governed-turn"; import { createNativeJournalFixture } from "./helpers/native-journal-fixture.js"; @@ -554,6 +556,107 @@ test("the scripts/brain-cli.ts fallback refuses type translation unless it is pr try { expect(hold.sandbox.providerMasks?.folders, "PROTECTED_CLI_SCRIPT_TRANSLATES").toEqual(["me"]); } finally { await hold.end(); } }); +/** + * The legacy layout: a vendored `scripts/brain-cli.ts` that needs nothing + * outside the brain, as the strict worker hides the workspace. It runs a + * bundle of the workspace CLI, built once per file, and first leaves `marker` + * if it can write the host. The brain is configured by `brain.config.json`, + * whose taxonomy imports no package. + */ +let bundledCli: string | undefined; +afterAll(() => { if (bundledCli) rmSync(dirname(bundledCli), { recursive: true, force: true }); }); +async function vendoredCli(): Promise { + if (bundledCli) return bundledCli; + const out = mkdtempSync(join(REPO, "tmp", "odysseus-vendored-cli-")); + bundledCli = join(out, "brain.js"); + const built = await Bun.build({ entrypoints: [join(REPO, "packages/core/src/cli/brain.ts")], target: "bun", outdir: out }); + expect(built.success, `VENDORED_CLI_BUILT: ${built.logs.join("; ")}`).toBe(true); + return bundledCli; +} +function vendoredFallback(cli: string, marker: string) { + return (brain: string) => { + rmSync(join(brain, "brain.config.ts")); + writeFileSync(join(brain, "brain.config.json"), "{}\n"); + mkdirSync(join(brain, "scripts/vendor"), { recursive: true }); + cpSync(cli, join(brain, "scripts/vendor/brain.js")); + writeFileSync(join(brain, "scripts/brain-cli.ts"), `import { writeFileSync } from "node:fs";\n` + + `try { writeFileSync(${JSON.stringify(marker)}, "ran"); } catch { /* the worker cannot reach the host */ }\n` + + `await import("./vendor/brain.js");\n`); + }; +} + +test("a protected scripts/brain-cli.ts fallback reads the taxonomy and builds the private index in the masked worker (#2865)", async () => { + const marker = join(REPO, "tmp", `odysseus-fallback-host-run-${process.pid}`); + cleanup.push(() => rmSync(marker, { force: true })); + const cli = await vendoredCli(); + // No packaged CLI and no configured command: the brain's own fallback script runs, protected. + const f = fixture("[{ types: [identity], allow: [anthropic] }]", "governed", brain => { + vendoredFallback(cli, marker)(brain); + setPolicy(brain, "[{ types: [identity], allow: [anthropic] }]", "protect: [scripts]"); + }, null); + expect(existsSync(join(f.brain, "node_modules/.bin/brain")), "NO_PACKAGED_CLI").toBe(false); + const hold = await f.turns.begin("fallback-protected", new AbortController().signal).catch((error: Error) => error); + if (hold instanceof Error) throw new Error(`PROTECTED_FALLBACK_LAUNCHES: ${hold.message}`); + try { + expect(hold.sandbox.providerMasks?.folders, "PROTECTED_FALLBACK_TRANSLATES_IDENTITY").toEqual(["me"]); + expect(f.reports.filter(report => report.includes("private search index")), `FALLBACK_PRIVATE_INDEX_BUILT: ${f.reports.join("; ")}`).toEqual([]); + expect(existsSync(join(hold.sandbox.providerMasks!.index!, "brain.db")), "FALLBACK_PRIVATE_INDEX_WRITTEN").toBe(true); + const db = new Database(join(hold.sandbox.providerMasks!.index!, "brain.db"), { readonly: true }); + let paths: string[]; + try { paths = db.query<{ path: string }, []>("SELECT path FROM documents").all().map(row => row.path); } finally { db.close(); } + expect(paths.filter(path => path.startsWith("me/")), "FALLBACK_PRIVATE_INDEX_LACKS_MASKED_DOCUMENTS").toEqual([]); + expect(paths, "FALLBACK_PRIVATE_INDEX_KEEPS_PERMITTED_DOCUMENTS").toContain("notes/quick-note-eagle.md"); + } finally { await hold.end(); } + expect(existsSync(marker), "FALLBACK_NEVER_RAN_ON_THE_HOST").toBe(false); +}); + +test("a protected fallback whose script is absent, or a relative executable other than bun, refuses by name without running on the host (#2865)", async () => { + // The fallback is selected by the missing packaged CLI alone; its script is not in the view. + const missing = fixture("[{ types: [identity], allow: [anthropic] }]", "governed", brain => { + mkdirSync(join(brain, "scripts")); writeFileSync(join(brain, "scripts/.keep"), ""); + setPolicy(brain, "[{ types: [identity], allow: [anthropic] }]", "protect: [scripts]"); + }, null); + const absent = await refusalOf(missing.turns.begin("fallback-absent", new AbortController().signal)); + expect(absent?.name, `ABSENT_FALLBACK_REFUSED: ${String(absent)}`).toBe("ProviderPolicyRefusedError"); + expect(absent!.message, "ABSENT_FALLBACK_NAMES_THE_SCRIPT").toContain("scripts/brain-cli.ts"); + expect(absent!.message, "ABSENT_FALLBACK_IS_NOT_A_BOUNDARY_FAILURE").not.toContain("worker boundary unavailable"); + // A script present but whose vendored CLI is absent: Bun ends that error with its version banner. + const unvendored = fixture("[{ types: [identity], allow: [anthropic] }]", "governed", brain => { + mkdirSync(join(brain, "scripts")); writeFileSync(join(brain, "scripts/brain-cli.ts"), `await import("./vendor/brain.js");\n`); + setPolicy(brain, "[{ types: [identity], allow: [anthropic] }]", "protect: [scripts]"); + }, null); + const unloaded = await refusalOf(unvendored.turns.begin("fallback-unvendored", new AbortController().signal)); + expect(unloaded?.name, `UNVENDORED_FALLBACK_REFUSED: ${String(unloaded)}`).toBe("ProviderPolicyRefusedError"); + expect(unloaded!.message, "UNVENDORED_FALLBACK_NAMES_WHAT_IT_COULD_NOT_LOAD").toContain("vendor/brain.js"); + const marker = join(REPO, "tmp", `odysseus-relative-host-run-${process.pid}`); + cleanup.push(() => rmSync(marker, { force: true })); + const cli = await vendoredCli(); + const relative = fixture("[{ types: [identity], allow: [anthropic] }]", "governed", brain => { + vendoredFallback(cli, marker)(brain); + setPolicy(brain, "[{ types: [identity], allow: [anthropic] }]", "protect: [scripts]"); + }, ["node", "scripts/brain-cli.ts"]); + const named = await refusalOf(relative.turns.begin("relative-runtime", new AbortController().signal)); + expect(named?.name, `RELATIVE_RUNTIME_REFUSED: ${String(named)}`).toBe("ProviderPolicyRefusedError"); + expect(named!.message, "RELATIVE_RUNTIME_NAMED").toContain("its executable, node, is not an absolute path"); + expect(existsSync(marker), "RELATIVE_RUNTIME_NEVER_RAN_ON_THE_HOST").toBe(false); +}); + +test("the masked worker resolves only the fallback's bun to the server's runtime; packaged and host argv are unchanged (#2865)", () => { + const root = mkdtempSync(join(REPO, "tmp", "odysseus-cli-selection-")); + cleanup.push(() => rmSync(root, { recursive: true, force: true })); + expect(brainCliCommand(root), "HOST_FALLBACK_UNCHANGED").toEqual(["bun", "scripts/brain-cli.ts"]); + // The script stays relative: the worker starts in the immutable startup view, which resolves it. + expect(workerBrainCliCommand(brainCliCommand(root)), "WORKER_FALLBACK_RUNTIME_ABSOLUTE").toEqual({ ok: true, command: [process.execPath, "scripts/brain-cli.ts"] }); + mkdirSync(join(root, "node_modules/.bin"), { recursive: true }); + writeFileSync(join(root, "node_modules/.bin/brain"), "#!/usr/bin/env bun\n"); + const packaged = join(root, "node_modules/.bin/brain"); + expect(brainCliCommand(root), "PACKAGED_CLI_PREFERRED").toEqual([packaged]); + expect(workerBrainCliCommand(brainCliCommand(root)), "PACKAGED_CLI_UNCHANGED_IN_THE_WORKER").toEqual({ ok: true, command: [packaged] }); + expect(workerBrainCliCommand(CLI), "CONFIGURED_ABSOLUTE_UNCHANGED").toEqual({ ok: true, command: CLI }); + expect(workerBrainCliCommand(["./bun", "scripts/brain-cli.ts"]).ok, "ONLY_A_BARE_BUN_IS_RESOLVED").toBe(false); + expect(workerBrainCliCommand([]).ok, "EMPTY_COMMAND_REFUSED").toBe(false); +}); + test("a protected name a governed turn created refuses type translation until that turn is reconciled (#2699)", async () => { // The brain is configured by brain.config.json; brain.config.ts is a protected name that is absent. const f = fixture("[{ types: [identity], allow: [anthropic] }]", "governed", brain => {