Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/masked-brain-cli-fallback.md
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 2 additions & 2 deletions docs/decisions/claude-code-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/runtime-requirements.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
2 changes: 1 addition & 1 deletion docs/plans/storage-lifecycle.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/process/evidence/test-wait-review-partition.json
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 18 additions & 1 deletion packages/ui-server/src/brain/client.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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"];
Expand Down
22 changes: 18 additions & 4 deletions packages/ui-server/src/brain/private-index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand All @@ -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]) } : {}) }) };
Expand All @@ -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) };
Expand All @@ -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 }
Expand Down
Loading
Loading