Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip: cli fast path + drain-aware exit

time-attack02ba4c9ac1d8
diff --git a/scripts/bench/efficiency/README.md b/scripts/bench/efficiency/README.md
new file mode 100644
index 0000000000..cfa2a106a8
--- /dev/null
+++ b/scripts/bench/efficiency/README.md
@@ -0,0 +1,49 @@
+# Efficiency bench harness
+
+Opt-in benchmark scripts for the Efficiency crew. Nothing here runs in CI or ships in the CLI.
+Brain data (pulled pages, synthetic brains, PGLite files, results) lives under
+`$BENCH_WORK` (default `~/.capy/work/brain`) and must never be committed. Result rows hold
+counts, sizes and timings only.
+
+Requires Bun >= 1.4 (the repo's `engines.bun`) and Docker for the Postgres engine.
+
+| File | What it does |
+|---|---|
+| `lib.ts` | Row schema (machine, engine, brain, pages, chunks, command, mode, N, p50, p95), percentiles, CLI runner, provider price table. |
+| `preload-instrument.ts` | `bun --preload` hook. `BENCH_USAGE_LOG` records every outbound HTTP call (host, path, ms, model, token usage; no bodies). `BENCH_ENGINE_TIMING` times every PGLite/Postgres engine method (outermost calls only) and process CPU. No product code changes. |
+| `materialize-pull.ts` | Pull directory -> importable markdown dir (`content` copied, field-only pages re-serialized, oversize pages replaced by size-matched synthetic stand-ins). |
+| `synth-brain.ts` | `shape` (manifest -> shape JSON, counts/sizes only), `full-shape` (~5,000 pages over 8 sources), `gen` (deterministic synthetic brain, `--scale`, `--seed`). |
+| `bench-import.ts` | Fresh isolated brain (GBRAIN_HOME) per engine; times init, per-source import, `extract all`, `embed --stale`; engine/HTTP/CPU split per phase; in-process parse and chunk probe; tokens and USD from provider usage. |
+| `bench-hot.ts` | Hot paths, cold (fresh CLI process per sample) and warm (one long-lived `gbrain serve` stdio MCP process): search, query with/without expansion, get_page, list_pages, recall, doctor, MCP stdio startup + call, HTTP serve startup + call, one-page sync. |
+| `probe-pg.ts` | Warm stdio MCP tool against a Postgres bench brain with `pg_stat_statements` reset around N calls: p50/p95, DB time per call, top statements (placeholders only). `--jit off` A/Bs Postgres JIT for the run. |
+| `probe-cold.ts` | Cold CLI start split: bun start, module graph, `--version`, real reads, each with stdout piped and with `GBRAIN_FLUSH_GRACE_MS=0` (the non-TTY exit-flush grace). |
+| `remote-rows.ts` | Rows for hosted-brain read latency recorded during a pull. |
+| `report.ts` | JSONL -> markdown tables (`results/report.md`). |
+| `run-all.sh` | Orchestrates data prep, both engines, all datasets, report. |
+
+## Run
+
+```bash
+export BENCH_WORK=~/.capy/work/brain # default
+scripts/bench/efficiency/run-all.sh default-pull synth-1x synth-full
+# one brain, one engine
+bun scripts/bench/efficiency/bench-import.ts --engine pglite --data $BENCH_WORK/import/synth-1x --label synth-1x --embed --max-usd 1
+bun scripts/bench/efficiency/bench-hot.ts --engine pglite --label synth-1x --n 20 --only search,query_expand
+bun scripts/bench/efficiency/report.ts
+# Postgres statement probe and cold-start split
+bun scripts/bench/efficiency/probe-pg.ts --label synth-full --tool list_pages --args '{"limit":50}' --jit off
+bun scripts/bench/efficiency/probe-cold.ts --label synth-full --engine postgres
+# CPU profile of one phase
+bun scripts/bench/efficiency/bench-import.ts ... --cpu-prof # writes .cpuprofile under engines/<engine>-<label>/bench-run/
+```
+
+Postgres uses a `pgvector/pgvector:pg16` container named `gbra66-bench-pg` on `127.0.0.1:5440`
+(`run-all.sh` starts it); each brain gets its own database `bench_<label>`.
+
+## Caveats
+
+- Cold CLI rows include Bun start, TypeScript load, config, engine connect and exit, the cost a
+ shell-out agent pays per call. Warm rows are what an MCP-connected agent pays.
+- Query, search and recall rows include provider round trips (query embedding, rerank, and for
+ `query` with expansion an LLM call), so they move with provider latency.
+- Embedding cost is the provider-reported token usage times `lib.ts` prices.
diff --git a/scripts/bench/efficiency/bench-hot.ts b/scripts/bench/efficiency/bench-hot.ts
new file mode 100755
index 0000000000..3c04edeb14
--- /dev/null
+++ b/scripts/bench/efficiency/bench-hot.ts
@@ -0,0 +1,256 @@
+#!/usr/bin/env bun
+/**
+ * Hot-path bench (GBRA-66). Opt-in, never run in CI.
+ *
+ * bun scripts/bench/efficiency/bench-hot.ts --engine pglite|postgres --label <name>
+ * [--n 20] [--warmup 3] [--only search,query_expand,...] [--sync-dir <dir>] [--out results/hot.jsonl]
+ *
+ * Runs against the brain bench-import.ts built at $BENCH_WORK/engines/<engine>-<label>.
+ * cold one fresh `gbrain <cmd>` process per sample (what a CLI user or a
+ * shell-out agent pays: bun start, config, engine connect, op, exit)
+ * warm one long-lived `gbrain serve` stdio MCP process, N tool calls after
+ * --warmup calls (what an MCP-connected agent pays per call)
+ * Also: MCP stdio startup + first tool call, HTTP serve startup + first tool
+ * call (fresh server per sample, bearer token), doctor, and a one-page sync.
+ *
+ * Query strings and slugs are sampled from the brain itself (three words of a
+ * random page's body) and never printed or written; rows carry counts only.
+ */
+import { appendFileSync, existsSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { CLI, REPO, WORK, appendRows, ensureDir, flag, has, lastJson, log, machine, readJsonl, rng, round, runCli, summarize, usageCost, type Row, type UsageRecord } from './lib.ts';
+
+const engine = flag('engine', 'pglite') as 'pglite' | 'postgres';
+const label = flag('label')!;
+const N = Number(flag('n', '20'));
+const WARMUP = Number(flag('warmup', '3'));
+const only = flag('only')?.split(',');
+const out = flag('out', join(WORK, 'results', 'hot.jsonl'))!;
+const home = join(WORK, 'engines', `${engine}-${label}`);
+if (!existsSync(home)) throw new Error(`no brain at ${home}; run bench-import.ts first`);
+const env: Record<string, string> = { GBRAIN_HOME: home, GBRAIN_ALLOW_DEFAULT_WRITE: '1' };
+const runDir = ensureDir(join(home, 'bench-run'));
+const usageFile = join(runDir, 'hot.usage.jsonl');
+rmSync(usageFile, { force: true });
+const M = machine();
+const want = (k: string) => !only || only.includes(k);
+
+/** Minimal newline-delimited JSON-RPC client for `gbrain serve` over stdio. */
+class StdioMcp {
+ proc: ReturnType<typeof Bun.spawn>;
+ private buf = '';
+ private waiters = new Map<number, (v: any) => void>();
+ private nextId = 1;
+ constructor(extraEnv: Record<string, string> = {}) {
+ this.proc = Bun.spawn([process.execPath, '--preload', join(import.meta.dir, 'preload-instrument.ts'), CLI, 'serve'], {
+ cwd: REPO, env: { ...process.env, ...env, ...extraEnv }, stdin: 'pipe', stdout: 'pipe', stderr: 'ignore',
+ });
+ void this.pump();
+ }
+ private async pump() {
+ const reader = (this.proc.stdout as ReadableStream<Uint8Array>).getReader();
+ const dec = new TextDecoder();
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ this.buf += dec.decode(value, { stream: true });
+ let i;
+ while ((i = this.buf.indexOf('\n')) >= 0) {
+ const line = this.buf.slice(0, i).trim();
+ this.buf = this.buf.slice(i + 1);
+ if (!line.startsWith('{')) continue;
+ try {
+ const msg = JSON.parse(line);
+ if (typeof msg.id === 'number' && this.waiters.has(msg.id)) {
+ this.waiters.get(msg.id)!(msg);
+ this.waiters.delete(msg.id);
+ }
+ } catch { /* partial or non-JSON line */ }
+ }
+ }
+ }
+ request(method: string, params: unknown, timeoutMs = 120_000): Promise<any> {
+ const id = this.nextId++;
+ const p = new Promise<any>((resolve, reject) => {
+ const t = setTimeout(() => { this.waiters.delete(id); reject(new Error(`timeout ${method}`)); }, timeoutMs);
+ this.waiters.set(id, (v) => { clearTimeout(t); resolve(v); });
+ });
+ (this.proc.stdin as any).write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');
+ (this.proc.stdin as any).flush?.();
+ return p;
+ }
+ notify(method: string, params: unknown = {}) {
+ (this.proc.stdin as any).write(JSON.stringify({ jsonrpc: '2.0', method, params }) + '\n');
+ }
+ async init() {
+ await this.request('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'gbra66-bench', version: '1' } });
+ this.notify('notifications/initialized');
+ }
+ async call(name: string, args: Record<string, unknown>) {
+ const r = await this.request('tools/call', { name, arguments: args });
+ if (r.error) throw new Error(`rpc error ${r.error.code}`);
+ if (r.result?.isError) throw new Error('tool error');
+ return r.result;
+ }
+ async close() {
+ try { (this.proc.stdin as any).end(); } catch { /* already closed */ }
+ const t = setTimeout(() => this.proc.kill(), 3000);
+ await this.proc.exited;
+ clearTimeout(t);
+ }
+}
+
+function toolJson(result: any): any {
+ const text = result?.content?.find((c: any) => c.type === 'text')?.text;
+ try { return JSON.parse(text); } catch { return null; }
+}
+
+async function sample<T>(n: number, fn: (i: number) => Promise<T>): Promise<{ ms: number[]; errors: number }> {
+ const ms: number[] = [];
+ let errors = 0;
+ for (let i = 0; i < n; i++) {
+ const t0 = performance.now();
+ try { await fn(i); ms.push(performance.now() - t0); } catch { errors++; }
+ }
+ return { ms, errors };
+}
+
+async function main() {
+ const stats = lastJson((await runCli(['stats', '--json'], env)).stdout) ?? {};
+ const pages = Number(stats.page_count ?? 0);
+ const chunks = Number(stats.chunk_count ?? 0);
+ const rows: Row[] = [];
+ const add = (command: string, mode: Row['mode'], s: { ms: number[]; errors: number }, extra?: Record<string, unknown>) => {
+ if (s.ms.length === 0) { log(`${command} [${mode}] all ${s.errors} samples failed`); }
+ const row: Row = { suite: 'hot', machine: M, engine, brain: label, pages, chunks, command, mode, ...summarize(s.ms.length ? s.ms : [NaN]), errors: s.errors, extra };
+ row.n = s.ms.length;
+ rows.push(row);
+ log(`${command} [${mode}] n=${row.n} p50=${row.p50_ms} p95=${row.p95_ms} err=${s.errors}`);
+ };
+
+ // Sample slugs and queries from the brain through a warm server; never printed.
+ const mcp = new StdioMcp({ BENCH_USAGE_LOG: usageFile });
+ await mcp.init();
+ const listed = toolJson(await mcp.call('list_pages', { limit: 500, sort: 'slug', source_id: '__all__' })) ?? [];
+ const all: { slug: string; source_id: string }[] = (Array.isArray(listed) ? listed : listed.pages ?? []).map((p: any) => ({ slug: p.slug, source_id: p.source_id }));
+ const r = rng(1234);
+ const picks = Array.from({ length: Math.max(N, 20) }, () => all[Math.floor(r() * all.length)]!).filter(Boolean);
+ const queries: string[] = [];
+ for (const p of picks) {
+ if (queries.length >= picks.length) break;
+ const page = toolJson(await mcp.call('get_page', { slug: p.slug, source_id: p.source_id }));
+ const words = String(page?.compiled_truth ?? '').replace(/[^\p{L}\p{N}\s]/gu, ' ').split(/\s+/).filter((w) => w.length > 3);
+ if (words.length < 3) continue;
+ const at = Math.floor(r() * (words.length - 3));
+ queries.push(words.slice(at, at + 3).join(' '));
+ }
+ log(`sampled ${picks.length} pages, ${queries.length} queries (not printed)`);
+ const q = (i: number) => queries[i % queries.length]!;
+ const pk = (i: number) => picks[i % picks.length]!;
+
+ const paths: { key: string; tool: string; args: (i: number) => Record<string, unknown>; cli: (i: number) => string[] }[] = [
+ { key: 'search', tool: 'search', args: (i) => ({ query: q(i), limit: 10 }), cli: (i) => ['search', q(i)] },
+ { key: 'query_expand', tool: 'query', args: (i) => ({ query: q(i), expand: true }), cli: (i) => ['query', q(i)] },
+ { key: 'query_noexpand', tool: 'query', args: (i) => ({ query: q(i), expand: false }), cli: (i) => ['query', q(i), '--no-expand'] },
+ { key: 'get_page', tool: 'get_page', args: (i) => ({ slug: pk(i).slug, source_id: pk(i).source_id }), cli: (i) => ['call', '--source', pk(i).source_id, 'get_page', JSON.stringify({ slug: pk(i).slug })] },
+ { key: 'list_pages', tool: 'list_pages', args: () => ({ limit: 50 }), cli: () => ['list', '--limit', '50'] },
+ { key: 'recall', tool: 'recall', args: (i) => ({ query: q(i), budget_tokens: 2000 }), cli: (i) => ['call', 'recall', JSON.stringify({ query: q(i), budget_tokens: 2000 })] },
+ ];
+
+ // Warm: the already-running stdio server.
+ for (const p of paths) {
+ if (!want(p.key)) continue;
+ await sample(WARMUP, (i) => mcp.call(p.tool, p.args(i + 1000)));
+ add(`mcp ${p.tool}${p.key.startsWith('query_') ? (p.key === 'query_expand' ? ' expand=true' : ' expand=false') : ''}`, 'warm', await sample(N, (i) => mcp.call(p.tool, p.args(i))));
+ }
+ await mcp.close();
+
+ // Cold: one fresh CLI process per sample.
+ for (const p of paths) {
+ if (!want(p.key)) continue;
+ add(`gbrain ${p.cli(0)[0]}${p.key === 'query_noexpand' ? ' --no-expand' : ''}${p.cli(0)[0] === 'call' ? ' ' + p.tool : ''}`, 'cold', await sample(N, async (i) => {
+ const res = await runCli(p.cli(i), { ...env, BENCH_USAGE_LOG: usageFile }, { preload: true, timeoutMs: 120_000 });
+ if (res.code !== 0) throw new Error(`exit ${res.code}`);
+ }));
+ }
+
+ if (want('doctor')) {
+ for (const args of [['doctor', '--json'], ['doctor', '--fast', '--json']]) {
+ add(`gbrain ${args.join(' ')}`, 'cold', await sample(Math.min(N, Number(flag('doctor-n', String(N)))), async () => {
+ const res = await runCli(args, env, { timeoutMs: 300_000 });
+ if (res.code !== 0 && res.code !== 1) throw new Error(`exit ${res.code}`);
+ }));
+ }
+ }
+
+ if (want('mcp_startup')) {
+ add('mcp stdio startup + get_page', 'cold', await sample(N, async (i) => {
+ const c = new StdioMcp();
+ try { await c.init(); await c.call('get_page', { slug: pk(i).slug, source_id: pk(i).source_id }); } finally { await c.close(); }
+ }));
+ }
+
+ if (want('http_startup')) {
+ const tokOut = await runCli(['auth', 'create', `bench-${Date.now()}`, '--scopes', 'read'], env);
+ const token = tokOut.stdout.match(/gbrain_[A-Za-z0-9_]+/)?.[0];
+ const port = 38100 + Math.floor(r() * 800);
+ add('http serve startup + get_page', 'cold', await sample(token ? N : 0, async (i) => {
+ const proc = Bun.spawn([process.execPath, CLI, 'serve', '--http', '--port', String(port), '--bind', '127.0.0.1'], { cwd: REPO, env: { ...process.env, ...env }, stdout: 'ignore', stderr: 'ignore' });
+ try {
+ const deadline = performance.now() + 60_000;
+ for (;;) {
+ try { if ((await fetch(`http://127.0.0.1:${port}/health`)).ok) break; } catch { /* not listening yet */ }
+ if (performance.now() > deadline) throw new Error('http startup timeout');
+ await Bun.sleep(20);
+ }
+ const res = await fetch(`http://127.0.0.1:${port}/mcp`, {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'get_page', arguments: { slug: pk(i).slug, source_id: pk(i).source_id } } }),
+ });
+ const body = await res.text();
+ if (!res.ok || body.includes('"isError":true')) throw new Error(`http ${res.status}`);
+ } finally {
+ proc.kill();
+ await proc.exited;
+ }
+ }));
+ }
+
+ const syncDir = flag('sync-dir');
+ if (want('sync') && syncDir) {
+ const git = async (...a: string[]) => {
+ const p = Bun.spawn(['git', '-C', syncDir, ...a], { stdout: 'ignore', stderr: 'pipe' });
+ if ((await p.exited) !== 0) throw new Error(`git ${a[0]} failed`);
+ };
+ if (!existsSync(join(syncDir, '.git'))) {
+ await git('init', '-q');
+ await git('add', '-A');
+ await git('commit', '-q', '-m', 'bench baseline');
+ }
+ const syncArgs = ['sync', '--source', 'syncbench', '--no-pull', '--no-embed', '--json'];
+ await runCli(['sources', 'add', 'syncbench', '--path', syncDir, '--no-federated'], env);
+ const first = await runCli(syncArgs, env, { timeoutMs: 900_000 });
+ add('gbrain sync --source (first sync of a git source, --no-embed)', 'once', { ms: first.code === 0 ? [first.ms] : [], errors: first.code === 0 ? 0 : 1 }, { source_pages: (await new Response(Bun.spawn(['git', '-C', syncDir, 'ls-files', '*.md'], { stdout: 'pipe' }).stdout).text()).split('\n').filter(Boolean).length });
+ const files = (await new Response(Bun.spawn(['git', '-C', syncDir, 'ls-files', '*.md'], { stdout: 'pipe' }).stdout).text()).split('\n').filter(Boolean);
+ add('gbrain sync (1-page change, --no-embed)', 'cold', await sample(N, async (i) => {
+ const f = join(syncDir, files[Math.floor(r() * files.length)]!);
+ appendFileSync(f, `\nBench edit ${i} ${Date.now()}.\n`);
+ await git('commit', '-q', '-am', `bench edit ${i}`);
+ const res = await runCli(syncArgs, env, { timeoutMs: 300_000 });
+ if (res.code !== 0) throw new Error(`exit ${res.code}`);
+ }));
+ add('gbrain sync (no change)', 'cold', await sample(Math.min(N, 10), async () => {
+ const res = await runCli(syncArgs, env, { timeoutMs: 300_000 });
+ if (res.code !== 0) throw new Error(`exit ${res.code}`);
+ }));
+ }
+
+ const usage = usageCost(readJsonl<UsageRecord>(usageFile));
+ for (const row of rows) row.extra = { ...(row.extra ?? {}) };
+ appendRows(out, rows);
+ writeFileSync(join(WORK, 'results', `hot-${engine}-${label}-usage.json`), JSON.stringify(usage, null, 1));
+ log(`done: ${rows.length} rows, provider spend so far for this brain $${usage.usd}`);
+}
+
+await main();
diff --git a/scripts/bench/efficiency/bench-import.ts b/scripts/bench/efficiency/bench-import.ts
new file mode 100755
index 0000000000..c9d1939324
--- /dev/null
+++ b/scripts/bench/efficiency/bench-import.ts
@@ -0,0 +1,165 @@
+#!/usr/bin/env bun
+/**
+ * Import-pipeline bench (GBRA-66). Opt-in, never run in CI.
+ *
+ * bun scripts/bench/efficiency/bench-import.ts --engine pglite|postgres --data <dir> --label <name>
+ * [--embed] [--max-usd 2] [--pg-url postgresql://postgres:[email protected]:5440/postgres]
+ * [--cpu-prof] [--out results/import.jsonl]
+ *
+ * <dir> holds one subdirectory per source (`default/`, `notes-main/`, ...). It is
+ * copied into the brain home first, because `sources add` writes ownership markers.
+ * Creates a fresh, isolated brain at $BENCH_WORK/engines/<engine>-<label>
+ * (GBRAIN_HOME), so ~/.gbrain is never touched. Postgres gets a fresh
+ * database `bench_<label>` on the --pg-url server.
+ *
+ * Phases, each a fresh `gbrain` process with preload-instrument.ts:
+ * init gbrain init (schema + migrations)
+ * import <source> gbrain import <dir> --no-embed --source-id <id> (parse + chunk + write)
+ * extract gbrain extract all --source db (links + timeline)
+ * embed gbrain embed --stale --max-usd N (provider calls; tokens + USD from usage)
+ * Per phase: wall ms, CPU ms, engine method time (outermost calls) and
+ * outbound HTTP time. A separate in-process probe times parseMarkdown and
+ * chunking alone over the same files, so CPU-side parse/chunk cost is
+ * separable from database writes.
+ */
+import { cpSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs';
+import { join, relative } from 'node:path';
+import { WORK, appendRows, ensureDir, flag, has, lastJson, log, machine, readJsonl, round, runCli, usageCost, writeJson, type Row, type UsageRecord } from './lib.ts';
+import { parseMarkdown } from '../../../src/core/markdown.ts';
+import { prepareMarkdownChunks } from '../../../src/core/markdown-chunks.ts';
+
+const engine = flag('engine', 'pglite') as 'pglite' | 'postgres';
+const srcData = flag('data')!;
+const label = flag('label')!;
+const pgAdmin = flag('pg-url', 'postgresql://postgres:[email protected]:5440/postgres')!;
+const out = flag('out', join(WORK, 'results', 'import.jsonl'))!;
+const maxUsd = flag('max-usd', '2')!;
+if (!srcData || !label) throw new Error('--data and --label are required');
+
+const home = join(WORK, 'engines', `${engine}-${label}`);
+const data = join(home, 'data');
+const runDir = ensureDir(join(home, 'bench-run'));
+const env: Record<string, string> = { GBRAIN_HOME: home, GBRAIN_ALLOW_DEFAULT_WRITE: '1' };
+const M = machine();
+
+function walk(dir: string): string[] {
+ const outFiles: string[] = [];
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
+ const p = join(dir, e.name);
+ if (e.isDirectory()) outFiles.push(...walk(p));
+ else if (e.name.endsWith('.md')) outFiles.push(p);
+ }
+ return outFiles;
+}
+
+async function pgExec(sql: string) {
+ const p = Bun.spawn(['docker', 'exec', 'gbra66-bench-pg', 'psql', '-U', 'postgres', '-v', 'ON_ERROR_STOP=1', '-c', sql], { stdout: 'pipe', stderr: 'pipe' });
+ const code = await p.exited;
+ if (code !== 0) throw new Error(`psql failed: ${await new Response(p.stderr).text()}`);
+}
+
+interface Phase { phase: string; wall_ms: number; code: number; cpu_user_ms?: number; engine_ms?: number; engine_top?: Record<string, { calls: number; ms: number }>; http_ms?: number; http_calls?: number; usage?: ReturnType<typeof usageCost>; json?: any }
+
+async function phase(name: string, args: string[], extraEnv: Record<string, string> = {}): Promise<Phase> {
+ const tag = name.replace(/[^a-z0-9]+/gi, '-');
+ const usageFile = join(runDir, `${tag}.usage.jsonl`);
+ const timingFile = join(runDir, `${tag}.timing.json`);
+ rmSync(usageFile, { force: true });
+ const cpuDir = has('cpu-prof') ? ensureDir(join(runDir, `cpuprof-${tag}`)) : undefined;
+ const r = await runCli(args, { ...env, ...extraEnv, BENCH_USAGE_LOG: usageFile, BENCH_ENGINE_TIMING: timingFile }, { preload: true, cpuProf: cpuDir });
+ if (r.code !== 0) log(`${name} exit ${r.code}: ${r.stderr.split('\n').filter((l) => /error|fail/i.test(l)).slice(0, 3).join(' | ').slice(0, 300)}`);
+ let timing: any = {};
+ try { timing = JSON.parse(readFileSync(timingFile, 'utf8')); } catch { /* process died early */ }
+ const usage = readJsonl<UsageRecord>(usageFile);
+ const engineMs = Object.values((timing.engine ?? {}) as Record<string, { ms: number }>).reduce((a, v) => a + v.ms, 0);
+ const top = Object.fromEntries(Object.entries(timing.engine ?? {}).slice(0, 8)) as Record<string, { calls: number; ms: number }>;
+ const p: Phase = {
+ phase: name, wall_ms: round(r.ms), code: r.code, cpu_user_ms: timing.cpu_user_ms, engine_ms: engineMs, engine_top: top,
+ http_ms: usage.reduce((a, u) => a + u.ms, 0), http_calls: usage.length, usage: usageCost(usage), json: lastJson(r.stdout),
+ };
+ log(`${name}: ${p.wall_ms}ms (engine ${engineMs}ms, http ${p.http_ms}ms/${p.http_calls} calls, cpu ${timing.cpu_user_ms}ms)`);
+ return p;
+}
+
+async function parseChunkProbe(files: string[], root: string) {
+ let parse = 0;
+ let chunk = 0;
+ let chunks = 0;
+ for (const f of files) {
+ const text = readFileSync(f, 'utf8');
+ const rel = relative(root, f);
+ const t0 = performance.now();
+ const parsed = parseMarkdown(text, rel, { validate: true });
+ const t1 = performance.now();
+ const c = await prepareMarkdownChunks({ compiled_truth: parsed.compiled_truth, timeline: parsed.timeline, frontmatter: parsed.frontmatter });
+ const t2 = performance.now();
+ parse += t1 - t0;
+ chunk += t2 - t1;
+ chunks += c.length;
+ }
+ return { parse_ms: round(parse), chunk_ms: round(chunk), chunks };
+}
+
+async function main() {
+ log(`engine=${engine} label=${label} home=${home}`);
+ rmSync(home, { recursive: true, force: true });
+ ensureDir(runDir);
+ // Each brain registers and owns its own copy: sources add writes ownership markers into the directory.
+ cpSync(srcData, data, { recursive: true });
+ const initArgs = ['init', '--non-interactive', '--json', '--skip-embed-check'];
+ if (engine === 'pglite') initArgs.push('--pglite');
+ else {
+ const db = `bench_${label.replace(/[^a-z0-9_]/gi, '_').toLowerCase()}`;
+ await pgExec(`DROP DATABASE IF EXISTS ${db} WITH (FORCE)`);
+ await pgExec(`CREATE DATABASE ${db}`);
+ initArgs.push('--url', pgAdmin.replace(/\/[^/]*$/, `/${db}`));
+ }
+ const phases: Phase[] = [await phase('init', initArgs)];
+
+ const sources = readdirSync(data).filter((d) => statSync(join(data, d)).isDirectory()).sort((a, b) => (a === 'default' ? -1 : b === 'default' ? 1 : a.localeCompare(b)));
+ let files = 0;
+ let bytes = 0;
+ const probe = { parse_ms: 0, chunk_ms: 0, chunks: 0 };
+ for (const src of sources) {
+ const dir = join(data, src);
+ const fl = walk(dir);
+ files += fl.length;
+ bytes += fl.reduce((a, f) => a + statSync(f).size, 0);
+ if (src !== 'default') phases.push(await phase(`sources add ${src}`, ['sources', 'add', src, '--path', dir, '--federated', '--force']));
+ const imp = await phase(`import ${src}`, ['import', dir, '--no-embed', '--json', '--source-id', src]);
+ if (imp.code !== 0) throw new Error(`import ${src} failed (exit ${imp.code})`);
+ phases.push(imp);
+ const pr = await parseChunkProbe(fl, dir);
+ probe.parse_ms += pr.parse_ms;
+ probe.chunk_ms += pr.chunk_ms;
+ probe.chunks += pr.chunks;
+ }
+ phases.push(await phase('extract all', ['extract', 'all', '--source', 'db', '--json']));
+ if (has('embed')) phases.push(await phase('embed --stale', ['embed', '--stale', '--json', '--max-usd', maxUsd]));
+ const stats = lastJson((await runCli(['stats', '--json'], env)).stdout) ?? {};
+ const pages = Number(stats.page_count ?? 0);
+ const chunks = Number(stats.chunk_count ?? 0);
+
+ const importPhases = phases.filter((p) => p.phase.startsWith('import '));
+ const sum = (ps: Phase[], k: keyof Phase) => ps.reduce((a, p) => a + Number(p[k] ?? 0), 0);
+ const rows: Row[] = [];
+ const base = { suite: 'import' as const, machine: M, engine, brain: label, pages, chunks, mode: 'once' as const, n: 1 };
+ for (const p of phases) {
+ rows.push({ ...base, command: `gbrain ${p.phase}`, p50_ms: p.wall_ms, p95_ms: p.wall_ms, errors: p.code === 0 ? 0 : 1, extra: { cpu_user_ms: p.cpu_user_ms, engine_ms: p.engine_ms, http_ms: p.http_ms, http_calls: p.http_calls, usd: p.usage?.usd, usage: p.usage?.byModel, engine_top: p.engine_top } });
+ }
+ const totalImport = sum(importPhases, 'wall_ms');
+ rows.push({
+ ...base, command: 'import pipeline total (all sources, --no-embed)', p50_ms: round(totalImport), p95_ms: round(totalImport),
+ extra: {
+ files, bytes, ms_per_page: round(totalImport / Math.max(1, files), 2), engine_ms: sum(importPhases, 'engine_ms'), cpu_user_ms: sum(importPhases, 'cpu_user_ms'), http_ms: sum(importPhases, 'http_ms'),
+ probe_parse_ms: round(probe.parse_ms), probe_chunk_ms: round(probe.chunk_ms), probe_chunks: probe.chunks,
+ extract_ms: phases.find((p) => p.phase === 'extract all')?.wall_ms, embed_ms: phases.find((p) => p.phase.startsWith('embed'))?.wall_ms,
+ embed_usd: phases.find((p) => p.phase.startsWith('embed'))?.usage?.usd ?? 0, stats: { links: stats.link_count, timeline: stats.timeline_entry_count, embedded: stats.embedded_count },
+ },
+ });
+ appendRows(out, rows);
+ writeJson(join(WORK, 'results', `import-${engine}-${label}.json`), { machine: M, engine, label, files, bytes, stats: { pages, chunks, links: stats.link_count, timeline: stats.timeline_entry_count, embedded: stats.embedded_count }, probe, phases: phases.map(({ json: _j, ...p }) => p) });
+ log(`done: pages=${pages} chunks=${chunks} import=${round(totalImport)}ms`);
+}
+
+await main();
diff --git a/scripts/bench/efficiency/cpuprof-top.ts b/scripts/bench/efficiency/cpuprof-top.ts
new file mode 100644
index 0000000000..794d31d1d3
--- /dev/null
+++ b/scripts/bench/efficiency/cpuprof-top.ts
@@ -0,0 +1,29 @@
+#!/usr/bin/env bun
+/**
+ * Summarize a Bun/V8 .cpuprofile: self time by function and by file (GBRA-66).
+ *
+ * bun scripts/bench/efficiency/cpuprof-top.ts <file.cpuprofile> [--top 25]
+ */
+import { readFileSync } from 'node:fs';
+import { REPO, flag } from './lib.ts';
+
+const file = process.argv[2]!;
+const top = Number(flag('top', '25'));
+const prof = JSON.parse(readFileSync(file, 'utf8'));
+const nodes = new Map<number, any>(prof.nodes.map((n: any) => [n.id, n]));
+const self = new Map<number, number>();
+const deltas: number[] = prof.timeDeltas ?? [];
+prof.samples.forEach((id: number, i: number) => self.set(id, (self.get(id) ?? 0) + (deltas[i] ?? 0)));
+const byFn = new Map<string, number>();
+const byFile = new Map<string, number>();
+let total = 0;
+for (const [id, us] of self) {
+ const cf = nodes.get(id).callFrame;
+ const url = String(cf.url || '(native)').replace(`file://${REPO}/`, '').replace(REPO + '/', '');
+ const fn = `${cf.functionName || '(anonymous)'} ${url}:${cf.lineNumber + 1}`;
+ byFn.set(fn, (byFn.get(fn) ?? 0) + us);
+ byFile.set(url, (byFile.get(url) ?? 0) + us);
+ total += us;
+}
+const show = (m: Map<string, number>) => [...m.entries()].sort((a, b) => b[1] - a[1]).slice(0, top).map(([k, us]) => `${(us / 1000).toFixed(1).padStart(9)} ms ${((us / total) * 100).toFixed(1).padStart(5)}% ${k}`).join('\n');
+console.log(`total sampled ${(total / 1000).toFixed(0)} ms\n\n== self time by function ==\n${show(byFn)}\n\n== self time by file ==\n${show(byFile)}`);
diff --git a/scripts/bench/efficiency/lib.ts b/scripts/bench/efficiency/lib.ts
new file mode 100755
index 0000000000..326f8dcfc3
--- /dev/null
+++ b/scripts/bench/efficiency/lib.ts
@@ -0,0 +1,174 @@
+/**
+ * Shared helpers for the efficiency bench harness (GBRA-66). Opt-in, never run in CI.
+ *
+ * Every result row carries the fields the Efficiency crew requires for a speed
+ * claim: machine, engine, brain size (pages/chunks), command, warm or cold, N,
+ * p50 and p95. Rows never carry page text, titles or slugs.
+ */
+import { cpus, totalmem, hostname, platform, release } from 'node:os';
+import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import { homedir } from 'node:os';
+
+export const REPO = resolve(import.meta.dir, '../../..');
+export const CLI = join(REPO, 'src/cli.ts');
+export const PRELOAD = join(import.meta.dir, 'preload-instrument.ts');
+export const WORK = process.env.BENCH_WORK ?? join(homedir(), '.capy/work/brain');
+
+export interface Row {
+ suite: 'import' | 'hot' | 'remote';
+ machine: string;
+ engine: 'pglite' | 'postgres' | 'hosted';
+ brain: string;
+ pages: number;
+ chunks: number;
+ command: string;
+ mode: 'cold' | 'warm' | 'once';
+ n: number;
+ p50_ms: number;
+ p95_ms: number;
+ mean_ms?: number;
+ min_ms?: number;
+ max_ms?: number;
+ errors?: number;
+ extra?: Record<string, unknown>;
+}
+
+export function flag(name: string, fallback?: string): string | undefined {
+ const i = process.argv.indexOf(`--${name}`);
+ if (i > 0 && process.argv[i + 1] && !process.argv[i + 1]!.startsWith('--')) return process.argv[i + 1];
+ return fallback;
+}
+export const has = (name: string) => process.argv.includes(`--${name}`);
+
+export function pct(values: number[], q: number): number {
+ if (values.length === 0) return NaN;
+ const s = [...values].sort((a, b) => a - b);
+ const idx = Math.min(s.length - 1, Math.max(0, Math.ceil(q * s.length) - 1));
+ return round(s[idx]!);
+}
+export const round = (x: number, d = 1) => Math.round(x * 10 ** d) / 10 ** d;
+
+export function summarize(samples: number[]): Pick<Row, 'n' | 'p50_ms' | 'p95_ms' | 'mean_ms' | 'min_ms' | 'max_ms'> {
+ return {
+ n: samples.length,
+ p50_ms: pct(samples, 0.5),
+ p95_ms: pct(samples, 0.95),
+ mean_ms: round(samples.reduce((a, b) => a + b, 0) / Math.max(1, samples.length)),
+ min_ms: round(Math.min(...samples)),
+ max_ms: round(Math.max(...samples)),
+ };
+}
+
+export function machine(): string {
+ const c = cpus();
+ return `${process.env.BENCH_MACHINE ?? hostname().slice(0, 12)} ${platform()}-${release().split('-')[0]} ${c.length}x${(c[0]?.model ?? 'cpu').replace(/\s+/g, ' ').slice(0, 40)} ${Math.round(totalmem() / 2 ** 30)}GiB bun-${Bun.version}`;
+}
+
+export const log = (m: string) => console.error(`[bench ${new Date().toISOString().slice(11, 19)}] ${m}`);
+
+export function ensureDir(p: string) {
+ mkdirSync(p, { recursive: true });
+ return p;
+}
+
+export function appendRows(file: string, rows: Row[]) {
+ ensureDir(dirname(file));
+ for (const r of rows) appendFileSync(file, JSON.stringify(r) + '\n');
+}
+
+export function readRows(file: string): Row[] {
+ if (!existsSync(file)) return [];
+ return readFileSync(file, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l) as Row);
+}
+
+export interface RunResult { ms: number; code: number; stdout: string; stderr: string }
+
+/** Run the gbrain CLI as a fresh process. `preload` adds the bench instrumentation. */
+export async function runCli(args: string[], env: Record<string, string>, opts: { preload?: boolean; cpuProf?: string; stdin?: string; timeoutMs?: number } = {}): Promise<RunResult> {
+ const bunArgs = [process.execPath];
+ if (opts.cpuProf) bunArgs.push('--cpu-prof', `--cpu-prof-dir=${opts.cpuProf}`);
+ if (opts.preload) bunArgs.push('--preload', PRELOAD);
+ bunArgs.push(CLI, ...args);
+ const t0 = performance.now();
+ const proc = Bun.spawn(bunArgs, {
+ cwd: REPO,
+ env: { ...process.env, ...env },
+ stdout: 'pipe',
+ stderr: 'pipe',
+ stdin: opts.stdin !== undefined ? new TextEncoder().encode(opts.stdin) : 'ignore',
+ });
+ const timer = opts.timeoutMs ? setTimeout(() => proc.kill(), opts.timeoutMs) : null;
+ const [stdout, stderr] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()]);
+ const code = await proc.exited;
+ if (timer) clearTimeout(timer);
+ return { ms: performance.now() - t0, code, stdout, stderr };
+}
+
+/** Last JSON object printed on stdout (gbrain --json prints one document). */
+export function lastJson(stdout: string): any {
+ const start = stdout.lastIndexOf('\n{');
+ const text = start >= 0 ? stdout.slice(start + 1) : stdout.trim().startsWith('{') ? stdout.trim() : '';
+ try { return JSON.parse(text); } catch { /* fall through */ }
+ for (let i = stdout.indexOf('{'); i >= 0; i = stdout.indexOf('{', i + 1)) {
+ try { return JSON.parse(stdout.slice(i)); } catch { /* keep scanning */ }
+ }
+ return null;
+}
+
+/** Embedding / LLM price table for the providers the bench may hit ($ per 1M tokens). */
+export const PRICE_PER_MTOK: Record<string, { in: number; out?: number }> = {
+ 'voyage-4': { in: 0.06 },
+ 'voyage-4-large': { in: 0.12 },
+ 'voyage-4-lite': { in: 0.02 },
+ 'rerank-2.5': { in: 0.05 },
+ 'rerank-2.5-lite': { in: 0.02 },
+ 'text-embedding-3-large': { in: 0.13 },
+ 'text-embedding-3-small': { in: 0.02 },
+};
+
+export interface UsageRecord { host: string; path: string; model?: string; status: number; ms: number; input_tokens?: number; output_tokens?: number; total_tokens?: number }
+
+/** Sum provider usage captured by preload-instrument.ts. Unknown models price at null. */
+export function usageCost(records: UsageRecord[]) {
+ const byModel: Record<string, { calls: number; input_tokens: number; output_tokens: number; usd: number | null; ms: number }> = {};
+ for (const r of records) {
+ const key = `${r.host}:${r.model ?? r.path}`;
+ const m = (byModel[key] ??= { calls: 0, input_tokens: 0, output_tokens: 0, usd: 0, ms: 0 });
+ m.calls++;
+ m.ms += r.ms;
+ const inTok = r.input_tokens ?? r.total_tokens ?? 0;
+ m.input_tokens += inTok;
+ m.output_tokens += r.output_tokens ?? 0;
+ const price = r.model ? PRICE_PER_MTOK[r.model.replace(/^.*\//, '')] : undefined;
+ if (r.host.includes('anthropic') && r.model) {
+ const p = r.model.includes('haiku') ? { in: 1, out: 5 } : r.model.includes('sonnet') ? { in: 3, out: 15 } : null;
+ m.usd = p && m.usd !== null ? m.usd + (inTok * p.in + (r.output_tokens ?? 0) * p.out) / 1e6 : null;
+ } else if (price && m.usd !== null) m.usd += (inTok * price.in + (r.output_tokens ?? 0) * (price.out ?? 0)) / 1e6;
+ else if (inTok > 0) m.usd = null;
+ }
+ const total = Object.values(byModel).reduce((a, m) => a + (m.usd ?? 0), 0);
+ return { byModel, usd: round(total, 4) };
+}
+
+export function readJsonl<T>(file: string): T[] {
+ if (!existsSync(file)) return [];
+ return readFileSync(file, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l) as T);
+}
+
+export function writeJson(file: string, data: unknown) {
+ ensureDir(dirname(file));
+ writeFileSync(file, JSON.stringify(data, null, 2) + '\n');
+}
+
+/** Mulberry32: tiny deterministic PRNG for the synthetic generator and query picks. */
+export function rng(seed: number) {
+ let a = seed >>> 0;
+ return () => {
+ a = (a + 0x6d2b79f5) >>> 0;
+ let t = a;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
diff --git a/scripts/bench/efficiency/materialize-pull.ts b/scripts/bench/efficiency/materialize-pull.ts
new file mode 100755
index 0000000000..5b2173aa9f
--- /dev/null
+++ b/scripts/bench/efficiency/materialize-pull.ts
@@ -0,0 +1,54 @@
+#!/usr/bin/env bun
+/**
+ * Turn a hosted-brain pull (~/.capy/work/brain/pull/<source>/) into an
+ * importable markdown directory. Opt-in, never run in CI; the output stays
+ * under ~/.capy/work/brain/ and must never be committed.
+ *
+ * bun scripts/bench/efficiency/materialize-pull.ts --source default [--out <dir>]
+ *
+ * Per page, in order of fidelity:
+ * <slug>.md get_page `content` (canonical markdown) -> copied as-is
+ * <slug>.page.json get_page fields without `content` -> serializeMarkdown()
+ * oversize response too large to read through the pull channel
+ * -> size- and type-matched synthetic stand-in (counted separately)
+ * Prints counts only.
+ */
+import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { serializeMarkdown } from '../../../src/core/markdown.ts';
+import { WORK, flag, writeJson } from './lib.ts';
+import { Gen, renderPage } from './synth-brain.ts';
+
+const source = flag('source', 'default')!;
+const pull = join(WORK, 'pull', source);
+const out = flag('out', join(WORK, 'import', `${source}-pull`, source))!;
+const manifest = JSON.parse(readFileSync(join(WORK, 'pull', `manifest-${source}.json`), 'utf8'));
+if (existsSync(out)) rmSync(out, { recursive: true, force: true });
+
+const g = new Gen(7);
+const counts = { content: 0, reconstructed: 0, standin: 0, missing: 0, bytes: 0 };
+for (const p of manifest.pages as any[]) {
+ const dest = join(out, `${p.slug}.md`);
+ mkdirSync(dirname(dest), { recursive: true });
+ const md = join(pull, `${p.slug}.md`);
+ const pj = join(pull, `${p.slug}.page.json`);
+ if (p.oversize) {
+ const bytes = Math.round(Number(p.approx_response_chars ?? 20000) * 0.9);
+ writeFileSync(dest, renderPage(g, { type: String(p.type ?? 'concept'), title: `${p.type} stand-in`, bytes, linkTargets: [], wikilinksPerKb: 0, timelineEntries: 0, tags: [] }));
+ counts.standin++;
+ } else if (!p.needs_reconstruct && existsSync(md)) {
+ copyFileSync(md, dest);
+ counts.content++;
+ } else if (existsSync(pj)) {
+ const f = JSON.parse(readFileSync(pj, 'utf8'));
+ const { type: _t, title: _ti, tags: _ta, ...fm } = (f.frontmatter ?? {}) as Record<string, unknown>;
+ writeFileSync(dest, serializeMarkdown(fm, f.compiled_truth ?? '', f.timeline ?? '', { type: f.type, title: f.title, tags: f.tags ?? [] }));
+ counts.reconstructed++;
+ } else {
+ counts.missing++;
+ continue;
+ }
+ counts.bytes += readFileSync(dest).length;
+}
+writeJson(join(dirname(out), 'materialize-stats.json'), { source, ...counts });
+console.log(JSON.stringify({ source, out_pages: counts.content + counts.reconstructed + counts.standin, ...counts }));
diff --git a/scripts/bench/efficiency/preload-instrument.ts b/scripts/bench/efficiency/preload-instrument.ts
new file mode 100755
index 0000000000..399749d77e
--- /dev/null
+++ b/scripts/bench/efficiency/preload-instrument.ts
@@ -0,0 +1,92 @@
+/**
+ * Bench-only instrumentation, loaded with `bun --preload` in front of src/cli.ts.
+ * Product code is untouched; everything here is opt-in through env vars.
+ *
+ * BENCH_USAGE_LOG=<file.jsonl> wrap globalThis.fetch: one line per outbound call
+ * (host, path, status, ms, model, token usage).
+ * Request and response bodies are never written.
+ * BENCH_ENGINE_TIMING=<file.json> wrap every PGLiteEngine / PostgresEngine prototype
+ * method; on exit write calls + wall ms per method for
+ * outermost calls only (nested engine calls are not
+ * double-counted), plus process CPU and wall time.
+ */
+import { appendFileSync, writeFileSync } from 'node:fs';
+import { AsyncLocalStorage } from 'node:async_hooks';
+
+const T0 = performance.now();
+const usageLog = process.env.BENCH_USAGE_LOG;
+const timingFile = process.env.BENCH_ENGINE_TIMING;
+
+if (usageLog) {
+ const realFetch = globalThis.fetch;
+ const wrapped = async function (input: any, init?: any): Promise<Response> {
+ const url = new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url);
+ let model: string | undefined;
+ try {
+ const body = init?.body;
+ if (typeof body === 'string' && body.length < 50_000_000) model = JSON.parse(body)?.model;
+ } catch { /* non-JSON body */ }
+ const t0 = performance.now();
+ let status = 0;
+ try {
+ const res = await realFetch(input, init);
+ status = res.status;
+ const rec: Record<string, unknown> = { host: url.host, path: url.pathname, model, status, ms: Math.round(performance.now() - t0) };
+ const ct = res.headers.get('content-type') ?? '';
+ if (ct.includes('application/json') && /voyageai|openai|anthropic|googleapis|typesafe/.test(url.host)) {
+ try {
+ const j: any = await res.clone().json();
+ const u = j?.usage ?? {};
+ rec.model = rec.model ?? j?.model;
+ rec.input_tokens = u.input_tokens ?? u.prompt_tokens;
+ rec.output_tokens = u.output_tokens ?? u.completion_tokens;
+ rec.total_tokens = u.total_tokens;
+ } catch { /* streamed or non-JSON */ }
+ }
+ appendFileSync(usageLog, JSON.stringify(rec) + '\n');
+ return res;
+ } catch (e) {
+ appendFileSync(usageLog, JSON.stringify({ host: url.host, path: url.pathname, model, status, ms: Math.round(performance.now() - t0), error: (e as Error)?.name }) + '\n');
+ throw e;
+ }
+ };
+ globalThis.fetch = Object.assign(wrapped, realFetch) as typeof fetch;
+}
+
+if (timingFile) {
+ const als = new AsyncLocalStorage<boolean>();
+ const stats: Record<string, { calls: number; ms: number }> = {};
+ const wrapClass = (label: string, proto: any) => {
+ for (const name of Object.getOwnPropertyNames(proto)) {
+ if (name === 'constructor') continue;
+ const desc = Object.getOwnPropertyDescriptor(proto, name);
+ if (!desc || typeof desc.value !== 'function') continue;
+ const orig = desc.value;
+ proto[name] = function (this: unknown, ...args: unknown[]) {
+ if (als.getStore()) return orig.apply(this, args);
+ const t0 = performance.now();
+ const done = () => {
+ const s = (stats[`${label}.${name}`] ??= { calls: 0, ms: 0 });
+ s.calls++;
+ s.ms += performance.now() - t0;
+ };
+ return als.run(true, () => {
+ let out: any;
+ try { out = orig.apply(this, args); } catch (e) { done(); throw e; }
+ if (out && typeof out.then === 'function') return out.finally(done);
+ done();
+ return out;
+ });
+ };
+ }
+ };
+ const { PGLiteEngine } = await import('../../../src/core/pglite-engine.ts');
+ const { PostgresEngine } = await import('../../../src/core/postgres-engine.ts');
+ wrapClass('pglite', PGLiteEngine.prototype);
+ wrapClass('postgres', PostgresEngine.prototype);
+ process.on('exit', () => {
+ const cpu = process.cpuUsage();
+ const rounded = Object.fromEntries(Object.entries(stats).sort((a, b) => b[1].ms - a[1].ms).map(([k, v]) => [k, { calls: v.calls, ms: Math.round(v.ms) }]));
+ writeFileSync(timingFile, JSON.stringify({ wall_ms: Math.round(performance.now() - T0), cpu_user_ms: Math.round(cpu.user / 1000), cpu_system_ms: Math.round(cpu.system / 1000), engine: rounded }, null, 1));
+ });
+}
diff --git a/scripts/bench/efficiency/probe-cold.ts b/scripts/bench/efficiency/probe-cold.ts
new file mode 100644
index 0000000000..e850d63068
--- /dev/null
+++ b/scripts/bench/efficiency/probe-cold.ts
@@ -0,0 +1,52 @@
+#!/usr/bin/env bun
+/**
+ * Cold CLI start breakdown (GBRA-66). Opt-in, never run in CI.
+ *
+ * bun scripts/bench/efficiency/probe-cold.ts [--label synth-full] [--engine postgres] [--n 20]
+ *
+ * Splits a fresh-process CLI call into: bun start (`bun -e 1`), module graph
+ * (`import('src/cli.ts')` timed in-process), `gbrain --version`, and real reads,
+ * each with stdout piped (what an agent shelling out sees) and with
+ * GBRAIN_FLUSH_GRACE_MS=0 (the exit-flush grace that cli-force-exit.ts holds when
+ * stdout is not a TTY). Prints a markdown table; with --label it also runs
+ * `list` and `call get_page` against engines/<engine>-<label>.
+ */
+import { existsSync } from 'node:fs';
+import { join } from 'node:path';
+import { CLI, REPO, WORK, flag, machine, pct } from './lib.ts';
+
+const N = Number(flag('n', '20'));
+const label = flag('label');
+const engine = flag('engine', 'postgres')!;
+const home = label ? join(WORK, 'engines', `${engine}-${label}`) : undefined;
+if (home && !existsSync(home)) throw new Error(`no brain at ${home}`);
+
+async function time(argv: string[], env: Record<string, string> = {}): Promise<number> {
+ const t = performance.now();
+ const p = Bun.spawn(argv, { cwd: REPO, stdout: 'pipe', stderr: 'pipe', env: { ...process.env, ...(home ? { GBRAIN_HOME: home } : {}), ...env } });
+ await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text()]);
+ await p.exited;
+ return performance.now() - t;
+}
+
+async function row(name: string, argv: string[], env: Record<string, string> = {}) {
+ await time(argv, env);
+ const ms: number[] = [];
+ for (let i = 0; i < N; i++) ms.push(await time(argv, env));
+ console.log(`| ${name} | ${N} | ${pct(ms, 50).toFixed(0)} | ${pct(ms, 95).toFixed(0)} |`);
+}
+
+const bun = process.execPath;
+const importProbe = `const t=performance.now(); await import(${JSON.stringify(CLI.replace(/cli\.ts$/, 'core/operations.ts'))}); console.log(performance.now()-t)`;
+console.log(`machine: ${machine()} engine: ${home ? engine : 'none'} brain: ${label ?? 'none'} mode: cold (fresh process, stdout piped)\n`);
+console.log('| step | N | p50 ms | p95 ms |\n|---|---|---|---|');
+await row('bun -e 1', [bun, '-e', '1']);
+await row('import src/core/operations.ts (module graph only)', [bun, '-e', importProbe]);
+await row('gbrain --version', [bun, CLI, '--version']);
+await row('gbrain --version, GBRAIN_FLUSH_GRACE_MS=0', [bun, CLI, '--version'], { GBRAIN_FLUSH_GRACE_MS: '0' });
+if (home) {
+ await row('gbrain list --limit 5', [bun, CLI, 'list', '--limit', '5']);
+ await row('gbrain list --limit 5, GBRAIN_FLUSH_GRACE_MS=0', [bun, CLI, 'list', '--limit', '5'], { GBRAIN_FLUSH_GRACE_MS: '0' });
+ await row('gbrain call get_page (missing slug)', [bun, CLI, 'call', 'get_page', '{"slug":"bench/missing"}']);
+ await row('gbrain call get_page, GBRAIN_FLUSH_GRACE_MS=0', [bun, CLI, 'call', 'get_page', '{"slug":"bench/missing"}'], { GBRAIN_FLUSH_GRACE_MS: '0' });
+}
diff --git a/scripts/bench/efficiency/probe-pg.ts b/scripts/bench/efficiency/probe-pg.ts
new file mode 100644
index 0000000000..aafefceb39
--- /dev/null
+++ b/scripts/bench/efficiency/probe-pg.ts
@@ -0,0 +1,88 @@
+#!/usr/bin/env bun
+/**
+ * Postgres statement probe for one warm MCP tool (GBRA-66). Opt-in, never run in CI.
+ *
+ * bun scripts/bench/efficiency/probe-pg.ts --label synth-full --tool list_pages --args '{"limit":50}' [--n 25] [--jit on|off|default]
+ *
+ * Starts one `gbrain serve` stdio process against engines/postgres-<label>, resets
+ * pg_stat_statements on that brain's database, runs the tool N times, and prints
+ * p50/p95 plus the statements that ran at least N times (calls, mean ms, share of
+ * DB time). `--jit off` sets `ALTER DATABASE ... SET jit = off` for the run and resets
+ * it afterwards, which is how the list_pages JIT finding was measured.
+ *
+ * Needs the bench container (gbra66-bench-pg) with pg_stat_statements preloaded:
+ * docker exec gbra66-bench-pg psql -U postgres -c "ALTER SYSTEM SET shared_preload_libraries='pg_stat_statements'"
+ * docker restart gbra66-bench-pg
+ * Prints statement text truncated to 140 chars; statements carry $n placeholders, never values.
+ */
+import { existsSync } from 'node:fs';
+import { join } from 'node:path';
+import { CLI, REPO, WORK, flag, machine, pct } from './lib.ts';
+
+const label = flag('label')!;
+const tool = flag('tool')!;
+const args = JSON.parse(flag('args', '{}')!);
+const N = Number(flag('n', '25'));
+const jit = flag('jit', 'default')!;
+const container = flag('container', 'gbra66-bench-pg')!;
+const home = join(WORK, 'engines', `postgres-${label}`);
+if (!existsSync(home)) throw new Error(`no brain at ${home}`);
+const db = `bench_${label.replace(/[^a-z0-9]/gi, '_')}`;
+
+async function psql(sql: string, dbName = db): Promise<string> {
+ const p = Bun.spawn(['docker', 'exec', container, 'psql', '-U', 'postgres', '-d', dbName, '-tAF', '\t', '-c', sql], { stdout: 'pipe', stderr: 'pipe' });
+ const [out, err] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text()]);
+ if ((await p.exited) !== 0) throw new Error(err.trim());
+ return out;
+}
+
+if (jit !== 'default') await psql(`ALTER DATABASE ${db} SET jit = ${jit === 'off' ? 'off' : 'on'}`, 'postgres');
+try {
+ await psql('CREATE EXTENSION IF NOT EXISTS pg_stat_statements');
+ const proc = Bun.spawn([process.execPath, CLI, 'serve'], { cwd: REPO, stdin: 'pipe', stdout: 'pipe', stderr: 'ignore', env: { ...process.env, GBRAIN_HOME: home } });
+ const pending = new Map<number, (m: any) => void>();
+ (async () => {
+ const reader = proc.stdout.getReader();
+ const dec = new TextDecoder();
+ let buf = '';
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) return;
+ buf += dec.decode(value);
+ for (let i = buf.indexOf('\n'); i >= 0; i = buf.indexOf('\n')) {
+ const line = buf.slice(0, i);
+ buf = buf.slice(i + 1);
+ try { const m = JSON.parse(line); pending.get(m.id)?.(m); } catch { /* log line */ }
+ }
+ }
+ })();
+ let id = 0;
+ const call = (method: string, params: unknown) => new Promise<any>((resolve) => {
+ const n = ++id;
+ pending.set(n, resolve);
+ proc.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: n, method, params }) + '\n');
+ proc.stdin.flush();
+ });
+ await call('initialize', { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 'probe-pg', version: '1' } });
+ await call('tools/call', { name: tool, arguments: args });
+ await psql('SELECT pg_stat_statements_reset()');
+ const ms: number[] = [];
+ let errors = 0;
+ for (let k = 0; k < N; k++) {
+ const t = performance.now();
+ const r = await call('tools/call', { name: tool, arguments: args });
+ ms.push(performance.now() - t);
+ if (r.error || r.result?.isError) errors++;
+ }
+ proc.kill();
+ const rows = (await psql(`SELECT calls, round(mean_exec_time::numeric, 2), round(total_exec_time::numeric, 1), left(regexp_replace(query, '\\s+', ' ', 'g'), 140)
+ FROM pg_stat_statements WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database()) AND calls >= ${N}
+ ORDER BY total_exec_time DESC LIMIT 12`)).trim().split('\n').filter(Boolean).map((l) => l.split('\t'));
+ const dbTotal = rows.reduce((s, r) => s + Number(r[2]), 0);
+ console.log(`machine: ${machine()}\nengine: postgres brain: ${label} tool: ${tool} mode: warm stdio jit: ${jit} N=${N} errors=${errors}`);
+ console.log(`wall p50 ${pct(ms, 50).toFixed(1)} ms p95 ${pct(ms, 95).toFixed(1)} ms db time/call ${(dbTotal / N).toFixed(2)} ms`);
+ console.log('calls\tmean_ms\tshare\tstatement');
+ for (const r of rows) console.log(`${r[0]}\t${r[1]}\t${((100 * Number(r[2])) / (dbTotal || 1)).toFixed(0)}%\t${r[3]}`);
+} finally {
+ if (jit !== 'default') await psql(`ALTER DATABASE ${db} RESET jit`, 'postgres');
+}
diff --git a/scripts/bench/efficiency/remote-rows.ts b/scripts/bench/efficiency/remote-rows.ts
new file mode 100755
index 0000000000..056b37881d
--- /dev/null
+++ b/scripts/bench/efficiency/remote-rows.ts
@@ -0,0 +1,29 @@
+#!/usr/bin/env bun
+/**
+ * Turn the latencies a hosted-brain pull recorded into bench rows (GBRA-66).
+ *
+ * bun scripts/bench/efficiency/remote-rows.ts --source default [--channel "capy codemode MCP relay"]
+ *
+ * The pull itself runs outside this repo (an MCP client paging list_pages
+ * with sort=updated_asc and calling get_page per slug); it writes
+ * $BENCH_WORK/pull/manifest-<source>.json with per-call ms. Latencies include
+ * whatever relay sits between the client and the hosted server, named by
+ * --channel. Counts and timings only.
+ */
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { WORK, appendRows, flag, machine, summarize, type Row } from './lib.ts';
+
+const source = flag('source', 'default')!;
+const channel = flag('channel', 'capy codemode -> hosted MCP')!;
+const m = JSON.parse(readFileSync(join(WORK, 'pull', `manifest-${source}.json`), 'utf8'));
+const pages = m.pages as any[];
+const base = { suite: 'remote' as const, machine: machine(), engine: 'hosted' as const, brain: `hosted:${source}`, pages: pages.length, chunks: 0, mode: 'warm' as const };
+const full = pages.filter((p) => !p.needs_reconstruct && !p.oversize && p.get_page_ms);
+const rows: Row[] = [
+ { ...base, command: 'list_pages limit=100', ...summarize(m.list_ms), extra: { note: channel } },
+ { ...base, command: 'get_page include_content+timeline_entries', ...summarize(full.map((p) => p.get_page_ms)), extra: { note: `${channel}; pages whose response fit the relay cap`, mean_response_kb: Math.round(full.reduce((a, p) => a + (p.response_bytes ?? 0), 0) / full.length / 102.4) / 10 } },
+ { ...base, command: 'get_page (all pages, any payload)', ...summarize(pages.filter((p) => p.get_page_ms).map((p) => p.get_page_ms)), extra: { note: channel } },
+];
+appendRows(join(WORK, 'results', 'remote.jsonl'), rows);
+console.log(JSON.stringify(rows.map((r) => ({ command: r.command, n: r.n, p50: r.p50_ms, p95: r.p95_ms }))));
diff --git a/scripts/bench/efficiency/report.ts b/scripts/bench/efficiency/report.ts
new file mode 100755
index 0000000000..a5f0116eb4
--- /dev/null
+++ b/scripts/bench/efficiency/report.ts
@@ -0,0 +1,67 @@
+#!/usr/bin/env bun
+/**
+ * Render bench JSONL rows as markdown tables (GBRA-66). Opt-in, never run in CI.
+ *
+ * bun scripts/bench/efficiency/report.ts [--results $BENCH_WORK/results] [--out report.md]
+ *
+ * Reads import.jsonl, hot.jsonl and remote.jsonl. Rows hold counts, sizes and
+ * timings only, so the rendered report is safe to share.
+ */
+import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { WORK, flag, readRows, type Row } from './lib.ts';
+
+const dir = flag('results', join(WORK, 'results'))!;
+const outFile = flag('out', join(dir, 'report.md'))!;
+const fmt = (x: number | undefined) => (x === undefined || Number.isNaN(x) ? '-' : x >= 100 ? String(Math.round(x)) : String(x));
+
+function table(rows: Row[], extraCols: [string, (r: Row) => string][] = []): string {
+ const head = ['engine', 'brain', 'pages', 'chunks', 'command', 'mode', 'N', 'p50 ms', 'p95 ms', ...extraCols.map((c) => c[0])];
+ const lines = [`| ${head.join(' | ')} |`, `|${head.map(() => '---').join('|')}|`];
+ for (const r of rows) lines.push(`| ${[r.engine, r.brain, r.pages, r.chunks, r.command, r.mode, r.n, fmt(r.p50_ms), fmt(r.p95_ms), ...extraCols.map((c) => c[1](r))].join(' | ')} |`);
+ return lines.join('\n');
+}
+
+/** Keep the newest row per (engine, brain, command, mode). */
+function latest(rows: Row[]): Row[] {
+ const m = new Map<string, Row>();
+ for (const r of rows) m.set(`${r.engine}|${r.brain}|${r.command}|${r.mode}`, r);
+ return [...m.values()];
+}
+
+const imp = latest(readRows(join(dir, 'import.jsonl')));
+const hot = latest(readRows(join(dir, 'hot.jsonl')));
+const remote = latest(readRows(join(dir, 'remote.jsonl')));
+const machines = [...new Set([...imp, ...hot, ...remote].map((r) => r.machine))];
+const parts: string[] = [`# gbrain efficiency bench`, '', `Machine(s): ${machines.map((m) => '`' + m + '`').join(', ')}`, ''];
+
+if (remote.length) parts.push('## Hosted brain remote reads', '', table(remote, [['note', (r) => String(r.extra?.note ?? '')]]), '');
+if (imp.length) {
+ const totals = imp.filter((r) => r.command.startsWith('import pipeline total'));
+ parts.push('## Import pipeline totals', '', table(totals, [
+ ['files', (r) => fmt(r.extra?.files as number)],
+ ['MB', (r) => fmt(Math.round(Number(r.extra?.bytes ?? 0) / 1e5) / 10)],
+ ['ms/page', (r) => fmt(r.extra?.ms_per_page as number)],
+ ['engine ms', (r) => fmt(r.extra?.engine_ms as number)],
+ ['cpu ms', (r) => fmt(r.extra?.cpu_user_ms as number)],
+ ['parse ms', (r) => fmt(r.extra?.probe_parse_ms as number)],
+ ['chunk ms', (r) => fmt(r.extra?.probe_chunk_ms as number)],
+ ['extract ms', (r) => fmt(r.extra?.extract_ms as number)],
+ ['embed ms', (r) => fmt(r.extra?.embed_ms as number)],
+ ['embed $', (r) => fmt(r.extra?.embed_usd as number)],
+ ]), '');
+ parts.push('## Import phases', '', table(imp.filter((r) => !r.command.startsWith('import pipeline total')), [
+ ['engine ms', (r) => fmt(r.extra?.engine_ms as number)],
+ ['http ms', (r) => fmt(r.extra?.http_ms as number)],
+ ['http calls', (r) => fmt(r.extra?.http_calls as number)],
+ ['$', (r) => fmt(r.extra?.usd as number)],
+ ]), '');
+}
+if (hot.length) {
+ const order = (r: Row) => `${r.command}|${r.mode}|${r.engine}|${String(r.pages).padStart(8, '0')}`;
+ parts.push('## Hot paths', '', table([...hot].sort((a, b) => order(a).localeCompare(order(b))), [['err', (r) => fmt(r.errors)]]), '');
+}
+const spendFile = join(dir, 'spend.json');
+if (existsSync(spendFile)) parts.push('## Spend', '', '```json', readFileSync(spendFile, 'utf8').trim(), '```', '');
+writeFileSync(outFile, parts.join('\n'));
+console.log(outFile);
diff --git a/scripts/bench/efficiency/run-all.sh b/scripts/bench/efficiency/run-all.sh
new file mode 100755
index 0000000000..f1f6773b02
--- /dev/null
+++ b/scripts/bench/efficiency/run-all.sh
@@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+# Efficiency bench orchestrator (GBRA-66). Opt-in, never run in CI.
+#
+# scripts/bench/efficiency/run-all.sh [datasets...] (default: default-pull synth-1x synth-full)
+#
+# Env:
+# BENCH_WORK work dir (default ~/.capy/work/brain); brain data never leaves it
+# BENCH_ENGINES "pglite postgres" (default)
+# BENCH_N samples per hot path (default 20)
+# BENCH_EMBED 1 = embed during import (default 1); BENCH_EMBED_SKIP="pglite:synth-full" skips pairs
+# BENCH_MAX_USD per-embed cap passed to gbrain embed --max-usd (default 2)
+# BENCH_PG_PORT host port of the pgvector container (default 5440)
+# BUN bun >= 1.4 binary (default: bun on PATH)
+set -euo pipefail
+HERE="$(cd "$(dirname "$0")" && pwd)"
+BUN="${BUN:-bun}"
+W="${BENCH_WORK:-$HOME/.capy/work/brain}"
+ENGINES="${BENCH_ENGINES:-pglite postgres}"
+N="${BENCH_N:-20}"
+PORT="${BENCH_PG_PORT:-5440}"
+DATASETS=("$@")
+[ ${#DATASETS[@]} -eq 0 ] && DATASETS=(default-pull synth-1x synth-full)
+
+if [[ " $ENGINES " == *" postgres "* ]] && ! docker inspect gbra66-bench-pg >/dev/null 2>&1; then
+ docker run -d --name gbra66-bench-pg -e POSTGRES_PASSWORD=postgres -p "127.0.0.1:${PORT}:5432" pgvector/pgvector:pg16 >/dev/null
+ until docker exec gbra66-bench-pg pg_isready -U postgres >/dev/null 2>&1; do sleep 1; done
+fi
+
+# Data prep: pull -> importable dir, shapes, synthetic brains.
+if [ -f "$W/pull/manifest-default.json" ]; then
+ [ -d "$W/import/default-pull" ] || "$BUN" "$HERE/materialize-pull.ts" --source default
+ [ -f "$W/shape-default.json" ] || "$BUN" "$HERE/synth-brain.ts" shape --manifest "$W/pull/manifest-default.json" --source default --pull-dir "$W/pull/default" --out "$W/shape-default.json"
+fi
+[ -f "$W/shape-full.json" ] || "$BUN" "$HERE/synth-brain.ts" full-shape --base "$W/shape-default.json" --out "$W/shape-full.json"
+[ -d "$W/import/synth-1x" ] || "$BUN" "$HERE/synth-brain.ts" gen --shape "$W/shape-default.json" --out "$W/import/synth-1x"
+[ -d "$W/import/synth-full" ] || "$BUN" "$HERE/synth-brain.ts" gen --shape "$W/shape-full.json" --out "$W/import/synth-full"
+
+for ds in "${DATASETS[@]}"; do
+ for eng in $ENGINES; do
+ embed=()
+ if [ "${BENCH_EMBED:-1}" = 1 ] && [[ " ${BENCH_EMBED_SKIP:-} " != *" $eng:$ds "* ]]; then embed=(--embed --max-usd "${BENCH_MAX_USD:-2}"); fi
+ "$BUN" "$HERE/bench-import.ts" --engine "$eng" --data "$W/import/$ds" --label "$ds" --pg-url "postgresql://postgres:[email protected]:${PORT}/postgres" "${embed[@]}"
+ home="$W/engines/$eng-$ds"
+ rm -rf "$home/sync-repo"
+ first_src="$(ls "$W/import/$ds" | grep -v '\.json$' | head -1)"
+ [ -d "$W/import/$ds/default" ] && first_src=default
+ cp -r "$W/import/$ds/$first_src" "$home/sync-repo"
+ "$BUN" "$HERE/bench-hot.ts" --engine "$eng" --label "$ds" --n "$N" --doctor-n "${BENCH_DOCTOR_N:-$N}" --sync-dir "$home/sync-repo"
+ done
+done
+"$BUN" "$HERE/report.ts"
diff --git a/scripts/bench/efficiency/synth-brain.ts b/scripts/bench/efficiency/synth-brain.ts
new file mode 100755
index 0000000000..4c8a014068
--- /dev/null
+++ b/scripts/bench/efficiency/synth-brain.ts
@@ -0,0 +1,248 @@
+#!/usr/bin/env bun
+/**
+ * Synthetic markdown brain generator for the efficiency bench (GBRA-66).
+ * Opt-in, never run in CI. Generates generated words and generic names only
+ * (alice-example style); no real page text, title or slug ever enters a shape
+ * file or the output.
+ *
+ * # 1) derive a shape (counts and sizes only) from a pull manifest
+ * bun scripts/bench/efficiency/synth-brain.ts shape --manifest <manifest.json> --source default --out shape.json
+ *
+ * # 2) generate a brain from a shape (one directory per source)
+ * bun scripts/bench/efficiency/synth-brain.ts gen --shape shape.json --out <dir> [--scale 1] [--seed 42]
+ *
+ * # 3) the built-in "full brain" shape (~5,000 pages over 8 sources), derived from a default-source shape
+ * bun scripts/bench/efficiency/synth-brain.ts full-shape --base shape.json --out shape-full.json
+ *
+ * Shape JSON:
+ * { "seed": 42, "sources": [ { "id": "default", "types": [
+ * { "type": "concept", "count": 14, "sizes": [bytes...], "timeline_per_page": 0.1,
+ * "wikilinks_per_kb": 0.4 } ] } ] }
+ * `sizes` is the empirical body-size sample (bytes); `gen` draws from it with
+ * +/-15% jitter, so `--scale 5` keeps the distribution while multiplying counts.
+ */
+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { flag, rng, writeJson } from './lib.ts';
+
+export interface TypeShape { type: string; count: number; sizes: number[]; timeline_per_page: number; wikilinks_per_kb: number }
+export interface SourceShape { id: string; types: TypeShape[] }
+export interface Shape { seed: number; note?: string; sources: SourceShape[] }
+
+const SYL = ['ka', 'lo', 'mi', 'ten', 'ra', 'vo', 'sil', 'den', 'ar', 'po', 'qui', 'nes', 'tor', 'bel', 'cas', 'ul', 'fin', 'gra', 'em', 'zo', 'pha', 'ret', 'lin', 'mo', 'sta', 'ber', 'ni', 'cor', 'tu', 'vex'];
+const COMMON = ['the', 'and', 'of', 'to', 'in', 'for', 'with', 'on', 'is', 'that', 'by', 'as', 'from', 'this', 'it', 'at', 'be', 'or', 'an', 'we'];
+const FIRST = ['alice', 'bob', 'carol', 'dave', 'erin', 'frank', 'grace', 'heidi', 'ivan', 'judy', 'mallory', 'niaj', 'olivia', 'peggy', 'rupert', 'sybil', 'trent', 'victor', 'walter', 'yolanda'];
+const ORG = ['acme', 'globex', 'initech', 'umbrella', 'hooli', 'vandelay', 'stark', 'wayne', 'tyrell', 'soylent'];
+
+function vocab(seed: number, n = 3000): string[] {
+ const r = rng(seed ^ 0x9e3779b9);
+ const words = new Set<string>();
+ while (words.size < n) {
+ const k = 1 + Math.floor(r() * 3);
+ let w = '';
+ for (let i = 0; i < k; i++) w += SYL[Math.floor(r() * SYL.length)];
+ words.add(w);
+ }
+ return [...words];
+}
+
+/** Generator state shared across one run so wikilinks point at pages that exist. */
+export class Gen {
+ private r: () => number;
+ private words: string[];
+ constructor(seed: number) {
+ this.r = rng(seed);
+ this.words = vocab(seed);
+ }
+ pick<T>(a: T[]): T { return a[Math.floor(this.r() * a.length)]!; }
+ rand() { return this.r(); }
+ word() { return this.r() < 0.35 ? this.pick(COMMON) : this.words[Math.floor(Math.pow(this.r(), 1.6) * this.words.length)]!; }
+ sentence(): string {
+ const n = 6 + Math.floor(this.r() * 16);
+ const w: string[] = [];
+ for (let i = 0; i < n; i++) w.push(this.word());
+ const s = w.join(' ');
+ return s[0]!.toUpperCase() + s.slice(1) + (this.r() < 0.1 ? '?' : '.');
+ }
+ person() { return `${this.pick(FIRST)}-example`; }
+ org() { return `${this.pick(ORG)}-example`; }
+ date(): string {
+ const d = new Date(Date.UTC(2024, 0, 1) + Math.floor(this.r() * 1000) * 86_400_000);
+ return d.toISOString().slice(0, 10);
+ }
+}
+
+export function pageSlug(sourceId: string, type: string, i: number) {
+ return `${type.replace(/[^a-z0-9-]/gi, '-').toLowerCase()}/${sourceId}-${type.replace(/[^a-z0-9-]/gi, '-').toLowerCase()}-${String(i).padStart(5, '0')}`;
+}
+
+/** One synthetic page body of ~`bytes` bytes with wikilinks and optional timeline. */
+export function renderPage(g: Gen, opts: { type: string; title: string; bytes: number; linkTargets: string[]; wikilinksPerKb: number; timelineEntries: number; tags: string[] }): string {
+ const fm = ['---', `type: ${opts.type}`, `title: "${opts.title}"`];
+ if (opts.tags.length) fm.push(`tags: [${opts.tags.join(', ')}]`);
+ fm.push(`created: ${g.date()}`, '---', '');
+ const parts: string[] = [`# ${opts.title}`, ''];
+ let size = fm.join('\n').length + parts.join('\n').length;
+ const wantLinks = Math.round((opts.bytes / 1024) * opts.wikilinksPerKb);
+ let links = 0;
+ let para = 0;
+ while (size < opts.bytes) {
+ if (para % 5 === 0) {
+ const h = `## ${g.sentence().split(' ').slice(0, 4).join(' ').replace(/[.?]$/, '')}`;
+ parts.push(h, '');
+ size += h.length + 2;
+ }
+ const sentences: string[] = [];
+ const ns = 2 + Math.floor(g.rand() * 5);
+ for (let i = 0; i < ns; i++) {
+ let s = g.sentence();
+ if (links < wantLinks && opts.linkTargets.length && g.rand() < 0.5) {
+ const target = g.pick(opts.linkTargets);
+ s = s.replace(/\.$/, '') + ` see [[${target}]].`;
+ links++;
+ } else if (g.rand() < 0.08) {
+ s = s.replace(/\.$/, '') + ` with ${g.person().replace('-example', '')} from ${g.org().replace('-example', '')}.`;
+ }
+ sentences.push(s);
+ }
+ const p = g.rand() < 0.25 ? sentences.map((s) => `- ${s}`).join('\n') : sentences.join(' ');
+ parts.push(p, '');
+ size += p.length + 1;
+ para++;
+ }
+ while (links < wantLinks && opts.linkTargets.length) {
+ parts.push(`- Related: [[${g.pick(opts.linkTargets)}]]`);
+ links++;
+ }
+ let out = fm.join('\n') + parts.join('\n').trimEnd() + '\n';
+ if (opts.timelineEntries > 0) {
+ const lines = ['', '<!-- timeline -->', ''];
+ for (let i = 0; i < opts.timelineEntries; i++) lines.push(`- **${g.date()}** | ${g.person()} — ${g.sentence()}`);
+ out += lines.join('\n') + '\n';
+ }
+ return out;
+}
+
+function jitter(g: Gen, sizes: number[]): number {
+ const base = sizes.length ? sizes[Math.floor(g.rand() * sizes.length)]! : 2000;
+ return Math.max(120, Math.round(base * (0.85 + g.rand() * 0.3)));
+}
+
+function poisson(g: Gen, mean: number): number {
+ if (mean <= 0) return 0;
+ const L = Math.exp(-mean);
+ let k = 0;
+ let p = 1;
+ do { k++; p *= g.rand(); } while (p > L && k < 1000);
+ return k - 1;
+}
+
+export function generate(shape: Shape, outDir: string, scale = 1, seed = shape.seed ?? 42) {
+ const g = new Gen(seed);
+ if (existsSync(outDir)) rmSync(outDir, { recursive: true, force: true });
+ const stats = { pages: 0, bytes: 0, timeline_entries: 0, sources: {} as Record<string, number> };
+ for (const src of shape.sources) {
+ const plan = src.types.map((t) => ({ ...t, n: Math.max(t.count > 0 ? 1 : 0, Math.round(t.count * scale)) }));
+ const slugs = plan.flatMap((t) => Array.from({ length: t.n }, (_, i) => pageSlug(src.id, t.type, i)));
+ let k = 0;
+ for (const t of plan) {
+ for (let i = 0; i < t.n; i++) {
+ const slug = slugs[k++]!;
+ const bytes = jitter(g, t.sizes);
+ const te = poisson(g, t.timeline_per_page);
+ const title = `${t.type} ${g.person()} ${i}`;
+ const md = renderPage(g, { type: t.type, title, bytes, linkTargets: slugs, wikilinksPerKb: t.wikilinks_per_kb, timelineEntries: te, tags: g.rand() < 0.4 ? [`tag-${Math.floor(g.rand() * 30)}`] : [] });
+ const file = join(outDir, src.id, `${slug}.md`);
+ mkdirSync(dirname(file), { recursive: true });
+ writeFileSync(file, md);
+ stats.pages++;
+ stats.bytes += md.length;
+ stats.timeline_entries += te;
+ stats.sources[src.id] = (stats.sources[src.id] ?? 0) + 1;
+ }
+ }
+ }
+ writeJson(join(outDir, 'synth-stats.json'), { scale, seed, ...stats });
+ return stats;
+}
+
+/** Counts + sizes only, from a pull manifest. */
+export function shapeFromManifest(manifestPath: string, sourceId: string, pullDir?: string): Shape {
+ const m = JSON.parse(readFileSync(manifestPath, 'utf8'));
+ const byType = new Map<string, { sizes: number[]; timeline: number; links: number; kb: number }>();
+ for (const p of m.pages as any[]) {
+ const type = String(p.type ?? 'concept');
+ const bytes = Number(p.bytes ?? Math.round((p.approx_response_chars ?? p.response_bytes ?? 2000) * 0.9));
+ const t = byType.get(type) ?? { sizes: [], timeline: 0, links: 0, kb: 0 };
+ t.sizes.push(bytes);
+ t.timeline += Number(p.timeline_count ?? 0);
+ if (pullDir) {
+ const f = join(pullDir, `${p.slug}.md`);
+ if (existsSync(f)) {
+ const text = readFileSync(f, 'utf8');
+ t.links += (text.match(/\[\[/g) ?? []).length;
+ t.kb += text.length / 1024;
+ }
+ }
+ byType.set(type, t);
+ }
+ const types: TypeShape[] = [...byType.entries()].map(([type, t]) => ({
+ type,
+ count: t.sizes.length,
+ sizes: t.sizes.sort((a, b) => a - b),
+ timeline_per_page: Math.round((t.timeline / t.sizes.length) * 100) / 100,
+ wikilinks_per_kb: t.kb > 0 ? Math.round((t.links / t.kb) * 100) / 100 : 0.3,
+ }));
+ return { seed: 42, note: `derived from ${sourceId} pull manifest: counts and sizes only`, sources: [{ id: sourceId, types }] };
+}
+
+/**
+ * Full-brain shape (~5,000 pages): the source page counts come from the
+ * hosted brain's list_pages totals; per-type size distributions reuse the
+ * default-source shape. Session-like sources draw from the session size sample.
+ */
+export function fullShape(base: Shape): Shape {
+ const types = base.sources[0]!.types;
+ const session = types.find((t) => t.type.endsWith('session')) ?? types[0]!;
+ const nonSession = types.filter((t) => t !== session);
+ const totalNon = nonSession.reduce((a, t) => a + t.count, 0) || 1;
+ const mixed = (id: string, n: number): SourceShape => ({ id, types: nonSession.map((t) => ({ ...t, count: Math.max(1, Math.round((t.count / totalNon) * n)) })) });
+ const sessions = (id: string, n: number, type = 'session'): SourceShape => ({ id, types: [{ ...session, type, count: n }] });
+ const notes = (id: string, n: number): SourceShape => ({ id, types: [{ ...(types.find((t) => t.type === 'concept') ?? types[0]!), type: 'note', count: n }] });
+ return {
+ seed: base.seed ?? 42,
+ note: 'synthetic full-brain shape: source counts from hosted list_pages totals, sizes from the default-source shape',
+ sources: [
+ mixed('notes-main', 3700),
+ sessions('sessions', 790),
+ notes('notes-b', 210),
+ notes('notes-c', 170),
+ mixed('default', 85),
+ notes('small-a', 25),
+ notes('small-b', 15),
+ notes('small-c', 5),
+ ],
+ };
+}
+
+if (import.meta.main) {
+ const cmd = process.argv[2];
+ if (cmd === 'shape') {
+ const manifest = flag('manifest')!;
+ const source = flag('source', 'default')!;
+ const shape = shapeFromManifest(manifest, source, flag('pull-dir'));
+ writeJson(flag('out')!, shape);
+ console.log(JSON.stringify({ types: shape.sources[0]!.types.map((t) => ({ type: t.type, count: t.count })) }));
+ } else if (cmd === 'full-shape') {
+ const shape = fullShape(JSON.parse(readFileSync(flag('base')!, 'utf8')));
+ writeJson(flag('out')!, shape);
+ console.log(JSON.stringify(shape.sources.map((s) => ({ id: s.id, pages: s.types.reduce((a, t) => a + t.count, 0) }))));
+ } else if (cmd === 'gen') {
+ const shape = JSON.parse(readFileSync(flag('shape')!, 'utf8')) as Shape;
+ const stats = generate(shape, flag('out')!, Number(flag('scale', '1')), Number(flag('seed', String(shape.seed ?? 42))));
+ console.log(JSON.stringify(stats));
+ } else {
+ console.error('usage: synth-brain.ts shape|full-shape|gen ... (see header)');
+ process.exit(2);
+ }
+}
diff --git a/scripts/check-skill-refs.mjs b/scripts/check-skill-refs.mjs
index 88055dcbd8..221128aec5 100755
--- a/scripts/check-skill-refs.mjs
+++ b/scripts/check-skill-refs.mjs
@@ -300,9 +300,9 @@ if (RUN_CLI_REFS) {
failures.push('[cli-refs] --tools-json parsed to an EMPTY command set, so no gbrain command in a skill was checked. Fix: make `bun src/cli.ts --tools-json` print the tool list, or pass --no-cli-refs to skip this lane deliberately');
}
if (known && known.size > 0) {
- // top-level commands defined directly in src/cli.ts (not ops): derive from source
+ // top-level commands defined directly in the dispatcher (src/cli/main.ts, not ops): derive from source
try {
- const cliSrc = readFileSync('src/cli.ts', 'utf8');
+ const cliSrc = readFileSync('src/cli/main.ts', 'utf8');
for (const m of cliSrc.matchAll(/(?:command === |case )'([a-z][a-z0-9-]*)'/g)) known.add(m[1]);
// Refactor wave 1: CLI-only commands are records in the command table.
const tableSrc = readFileSync('src/cli/command-table.ts', 'utf8');
diff --git a/scripts/coverage-diff-gate.ts b/scripts/coverage-diff-gate.ts
index 14d9a28657..6c61248141 100644
--- a/scripts/coverage-diff-gate.ts
+++ b/scripts/coverage-diff-gate.ts
@@ -294,8 +294,8 @@ function main(): void {
for (const file of scopedFiles) {
const addedLines = changed.get(file)!;
if (isExempt(file, exemptions)) {
- // Exempt: reported, never gated. src/cli.ts gets its own honest tag.
- const tag = file === "src/cli.ts" ? "[subprocess-undercount]" : "[e2e-exempt]";
+ // Exempt: reported, never gated. The CLI entry and dispatcher get their own honest tag.
+ const tag = file === "src/cli.ts" || file === "src/cli/main.ts" ? "[subprocess-undercount]" : "[e2e-exempt]";
rows.push({ file, added: addedLines.length, covered: null, uncovered: null, uncoveredLines: [], status: tag });
continue;
}
diff --git a/scripts/coverage-gate-exemptions.txt b/scripts/coverage-gate-exemptions.txt
index 08ea2c7d35..fb5517e90d 100644
--- a/scripts/coverage-gate-exemptions.txt
+++ b/scripts/coverage-gate-exemptions.txt
@@ -5,7 +5,7 @@
# They are still REPORTED in the gate's table, tagged:
# [e2e-exempt] coverage for these lives in DATABASE_URL-gated
# e2e lanes that the PR corpus may not run
-# [subprocess-undercount] src/cli.ts only: the CLI is exercised via child
+# [subprocess-undercount] src/cli.ts and src/cli/main.ts only: the CLI is exercised via child
# processes and bun coverage does not propagate
# into subprocesses, so its numbers undercount
#
@@ -23,3 +23,5 @@ src/core/migrate.ts
# Transferred with the MIGRATIONS array from migrate.ts (refactor wave 1, W3 split).
src/core/schema-migrations/
src/cli.ts
+# The dispatcher body moved here from src/cli.ts (cold-start fast path); same subprocess undercount.
+src/cli/main.ts
diff --git a/scripts/generate-flag-registry.ts b/scripts/generate-flag-registry.ts
index c99fefd886..2f0214a2c7 100644
--- a/scripts/generate-flag-registry.ts
+++ b/scripts/generate-flag-registry.ts
@@ -3,7 +3,7 @@
*
* gbrain's CLI_ONLY commands read flags ad hoc (`args.includes('--force')`,
* per-command parseFlags helpers), so there is no parser to make strict. The
- * pre-dispatch validator in src/cli.ts needs to know each command's legal
+ * pre-dispatch validator in src/cli/main.ts needs to know each command's legal
* flags; this script derives them from the source instead of a hand-typed
* list that would rot.
*
@@ -11,7 +11,7 @@
* its dispatch text: the record's module under src/cli/commands/ (the former
* `case 'X':` / plain `if (command === 'X')` body, moved verbatim in refactor
* wave 1) plus every block of the explicit handleCliOnly pipeline in
- * src/cli.ts (handleCliOnly and its @cliPipelineStage functions, see
+ * src/cli/main.ts (handleCliOnly and its @cliPipelineStage functions, see
* scripts/lib/cli-pipeline.ts) segmented on its dispatch markers — every
* `if (command === 'X' …)` head, plain or compound, and `case 'X':` labels (see
* segmentDispatchBlocks). Collect every `import('…/commands/Y.ts')` in that
@@ -373,7 +373,7 @@ function buildFlagArtifacts(root: string): { registry: Record<string, string[]>;
const commands = records.map(r => r.name);
// Dispatch text per command, from two sources (refactor wave 1, W4 cli):
- // 1. the explicit handleCliOnly pipeline in src/cli.ts: handleCliOnly and
+ // 1. the explicit handleCliOnly pipeline in src/cli/main.ts: handleCliOnly and
// every @cliPipelineStage function it calls, each segmented on its own
// (bounded at the function, so no function's tail bleeds into the next;
// unbounded, the LAST block once absorbed every --flag literal in the
@@ -383,10 +383,10 @@ function buildFlagArtifacts(root: string): { registry: Record<string, string[]>;
// Import specifiers resolve relative to the file the text came from.
const blocks = new Map<string, Array<{ text: string; dir: string }>>();
const addBlock = (label: string, text: string, dir: string) => blocks.set(label, [...(blocks.get(label) ?? []), { text, dir }]);
- const pipeline = flattenCliPipeline(parseSource(root, 'src/cli.ts'));
+ const pipeline = flattenCliPipeline(parseSource(root, 'src/cli/main.ts'));
for (const fn of [pipeline.entry, ...pipeline.stages]) {
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- build-time generator over this repository's own source tree; every joined segment is a constant module name or a path the generator itself discovered under ROOT
- for (const [label, text] of segmentDispatchBlocks(fn.getText())) addBlock(label, text, join(root, 'src'));
+ for (const [label, text] of segmentDispatchBlocks(fn.getText())) addBlock(label, text, join(root, 'src', 'cli'));
}
for (const record of records) {
const mod = record.loadSpecifier ? readCommandModule(root, record.loadSpecifier) : null;
diff --git a/src/cli.ts b/src/cli.ts
old mode 100755
new mode 100644
index 29a73431d7..21d1c729f9
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -1,3184 +1,45 @@
#!/usr/bin/env bun
-
-import { affectsRecall } from './core/types.ts';
-import { deliveryVersionSkewWarning } from './core/search/evidence-delivery.ts';
-import { installSigchldHandler } from './core/zombie-reap.ts';
-installSigchldHandler();
+/**
+ * gbrain CLI entry point (`bun src/cli.ts`, the `gbrain` bin, the compiled
+ * binary). Runs the process-level setup, then answers the engine-free fast
+ * paths (`--version`, `version`, bare `gbrain`, `--help`, `-h`) itself, or
+ * loads the dispatcher (src/cli/main.ts) with a dynamic import. The dispatcher
+ * pulls in every operation and command module, so the fast paths skip that
+ * import graph entirely. Every static import here is paid by every invocation:
+ * keep them light.
+ */
+import { VERSION } from './version.ts';
+import { exitOnUnsupportedBun } from './core/runtime-version.ts';
import { installCleanupSignalHandlers } from './core/serve-invocation.ts';
-
-import { readFileSync, existsSync, unlinkSync } from 'fs';
-import { readStdinBounded as readStdinPayload } from './core/interaction.ts';
-import { spawn } from 'child_process';
-import {
- readUpdateCache,
- isCacheFresh,
- pendingUpgradeVersion,
- readSnooze,
- isSnoozeActive,
- resolveSelfUpgradeMode,
- justUpgradedPath,
-} from './core/self-upgrade.ts';
-import { loadConfig, loadConfigFileOnly, loadConfigWithEngine, isThinClient, getDbUrlSource, envShadowDetected } from './core/config.ts';
-import {
- classifyPgAccessError as classifyDbAccessError,
- diagnoseDbConfig as diagnoseDbConfigForMarker,
- formatDbAccessMarker as formatDbMarker,
- shouldEmitDbAccessMarker,
-} from './core/pg-access-classify.ts';
-import { resolveBrainId as resolveBrainIdForDbMarker } from './core/brain-resolver.ts';
-import type { GBrainConfig } from './core/config.ts';
-import type { AIGatewayConfig } from './core/ai/types.ts';
-import type { BrainEngine } from './core/engine.ts';
-import { operations, OperationError } from './core/operations.ts';
-import { resolveSourceIdEngineFree } from './core/source-resolver.ts';
-import { installCliRoutingFor } from './cli/fix-routing-provider.ts';
-import { formatVolunteeredPage } from './core/context/volunteer.ts';
-import type { Operation, OperationContext } from './core/operations.ts';
-import { currentCliWriteWait } from './core/persistence/write-wait.ts';
-import { isScopeErrorCode } from './core/error-catalogue.ts';
-import { shouldForceExitAfterMain, finishCliTeardown, flushThenExit, currentExitCode, setCliExitVerdict, writeStdoutFinal, installStdoutPipeDelivery } from './core/cli-force-exit.ts';
+import { shouldForceExitAfterMain, flushThenExit, currentExitCode, installStdoutPipeDelivery } from './core/cli-force-exit.ts';
import { agentJsonGuardMode } from './cli/json-guard.ts';
-import { printCuratedHelp } from './cli/help/render.ts';
-import { curatedFlagError } from './cli/help/validate.ts';
-import { cliCommandOf, exitCliError, exitOnRepairFailed, unknownFlagError, usageError, writeCliError, writeCliNotice, writeFatalCliError } from './cli/cli-error.ts';
-import type { Notice } from './core/agent-output.ts';
-import { opError, opOwnsSource } from './core/ops/contract.ts';
-import { opParamValue } from './cli/op-param-values.ts';
-import { serializeMarkdown } from './core/markdown.ts';
-import { parseGlobalFlags, setCliOptions, getCliOptions } from './core/cli-options.ts';
+import { parseGlobalFlags } from './core/cli-options.ts';
import { runCliPreflight } from './core/cli-preflight.ts';
-import { isBooleanLiteral, isKnownOpFlag } from './core/op-flag-tokens.ts';
-import { conceptNudge } from './core/search/query-intent.ts';
-import { redactRetrievalOutput } from './core/search/output-redaction.ts';
-import type { CliOptions } from './core/cli-options.ts';
-import { callRemoteTool, RemoteMcpError, unpackToolResult, extractResponseMeta } from './core/mcp-client.ts';
-import { assertSingleSourceScopeFlag, checkHostHonoredParams, hintAmbientNarrowing, type AmbientSourceBinding } from './cli/source-scope.ts';
-import { maybePromptForUpgrade } from './core/thin-client-upgrade-prompt.ts';
-import { CLI_FLAG_REGISTRY } from './core/cli-flag-registry.generated.ts';
-import { cliHelpRequested } from './cli/subcommands.ts';
-import { printRouterHelp } from './cli/router-help.ts';
-import { strictArgsRefusal } from './cli/strict-args.ts';
-import { migrationCliArgumentError } from './core/embedding-migration-cli.ts';
-import { VERSION } from './version.ts';
-import { exitOnUnsupportedBun } from './core/runtime-version.ts';
-import { bigintToStringReplacer } from './core/utils.ts';
-import {
- CLI_ONLY,
- CLI_ONLY_SELF_HELP,
- STARTUP_HOOK_SKIP_COMMANDS,
- THIN_CLIENT_REFUSED_COMMANDS,
- findCliCommand,
- type CliDispatchContext,
-} from './cli/command-table.ts';
-import { formatRememberResult } from './cli/remember-format.ts';
-import { applyCliOpNotices, captureOpNotice } from './cli/op-notices.ts';
-
-// db-availability loop: best-effort brain-id for the GBRAIN_DB_ACCESS marker,
-// so a MOUNT's DB failure reads as `brain=<id>` instead of masquerading as a
-// host failure. Never throws (a malformed GBRAIN_BRAIN_ID must not break
-// error reporting — the marker just omits the suffix).
-function dbMarkerBrainId(): string | undefined {
- try {
- return resolveBrainIdForDbMarker(getCliOptions().brain ?? null);
- } catch {
- return undefined;
- }
-}
-
-// Build CLI name -> operation lookup
-const cliOps = new Map<string, Operation>();
-for (const op of operations) {
- const name = op.cliHints?.name;
- if (name && !op.cliHints?.hidden) {
- cliOps.set(name, op);
- }
-}
-
-// bigint → string JSON replacer: defined in core/utils.ts (commands must not
-// reach into the dispatcher for it); re-exported here so existing importers
-// and tests keep their surface. (#2450)
-export { bigintToStringReplacer };
-
-// Membership sets are derived from the command table (src/cli/command-table.ts);
-// re-exported so existing importers keep their surface (CLAUDE.md facade rule).
-export { CLI_ONLY, THIN_CLIENT_REFUSED_COMMANDS };
-
-// ENG-2 renderer parity: round-trip a local-engine op's return value so
-// renderers see the same shape the routed path produces. Bigint-safe via
-// bigintToStringReplacer. Exported for tests (same import-safety contract as
-// cliAliases/formatResult). (#2450)
-export function normalizeLocalResult(rawResult: unknown): unknown {
- return JSON.parse(JSON.stringify(rawResult, bigintToStringReplacer));
-}
-
-/**
- * Commands in CLI_ONLY_SELF_HELP whose handler honours `--help` as its first
- * action, before reading the engine. Dispatching them here keeps `--help`
- * answerable with no brain configured.
- *
- * Membership is behaviour, not taste: each entry is pinned by
- * test/cli-help-without-brain.test.ts, which runs the CLI with an empty
- * GBRAIN_HOME and requires exit 0 plus real help output.
- */
-const SELF_HELP_WITHOUT_ENGINE: Record<string, true | (() => Promise<(engine: never, args: string[]) => unknown>)> = {
- export: async () => (await import('./commands/export.ts')).runExport as never,
- models: async () => (await import('./commands/models.ts')).runModels as never,
- watch: async () => (await import('./commands/watch.ts')).runWatch as never,
- skillopt: async () => (await import('./commands/skillopt.ts')).runSkillOptCommand as never,
- maintain: async () => (await import('./commands/maintain.ts')).runMaintain as never,
- repair: async () => (await import('./commands/repair.ts')).runRepairCommand as never,
- 'extract-conversation-facts': async () =>
- (await import('./commands/extract-conversation-facts.ts')).runExtractConversationFacts as never,
- transcripts: async () => (await import('./commands/transcripts.ts')).runTranscripts as never,
- // runJobs accepts BrainEngine | null and its help guard returns before any
- // engine (or subcommand body) is touched.
- jobs: async () => (await import('./commands/jobs.ts')).runJobs as never,
- // runDream accepts BrainEngine | null; --help (and `retriage --help`) is
- // answered before any engine-bearing work per the dream.ts IRON RULE.
- dream: async () => (await import('./commands/dream.ts')).runDream as never,
- // runCompileContext accepts BrainEngine | null; the help guard runs first.
- 'compile-context': async () =>
- (await import('./commands/compile-context.ts')).runCompileContext as never,
- // runLoops / runWaiting answer --help before touching the engine.
- loops: async () => (await import('./commands/loops.ts')).runLoops as never,
- 'edge-proposals': async () => (await import('./commands/edge-proposals.ts')).runEdgeProposals as never,
- waiting: async () => (await import('./commands/loops.ts')).runWaiting as never,
- // runSources's `--help`/`-h`/undefined-subcommand branch calls printHelp()
- // without ever touching `engine` — safe to dispatch with no brain
- // configured, matching the reader who runs `sources --help` because they
- // have no brain yet.
- sources: async () => (await import('./commands/sources.ts')).runSources as never,
- // runConnectors's --help / no-subcommand / `providers` / `logout` branches
- // never touch `engine` — safe engine-free for the reader with no brain yet.
- connectors: async () => (await import('./commands/connectors/index.ts')).runConnectors as never,
- // runAgent accepts BrainEngine | null; help (incl. `register --help`) is
- // answered before any engine or job-queue work (cathedral-6).
- agent: async () => (await import('./commands/agent.ts')).runAgent as never,
- // D3: post-connect records whose handler answers --help before the engine; run through the table.
- advisor: true, anomalies: true, feedback: true, backfill: true, 'book-mirror': true, 'edges-backfill': true, embed: true, features: true,
- founder: true, 'graph-query': true, orphans: true, salience: true, think: true,
- brainstorm: true, lsd: true, migrate: true, pages: true, pricing: true, 'retrieval-upgrade': true, whoknows: true, core: true,
-};
-
-/** Returns true when the command's own help was printed. */
-async function printSelfHelpWithoutEngine(command: string, args: string[]): Promise<boolean> {
- const load = SELF_HELP_WITHOUT_ENGINE[command];
- if (!load) return false;
- if (load === true) return dispatchConnectedCommand(command, null as never, args).then(() => true);
- const run = await load();
- // The engine is never read on the help path; passing a placeholder keeps the
- // handler signatures untouched. skillopt already declares `BrainEngine | null`
- // for exactly this reason.
- await run(null as never, args);
- return true;
-}
-
-// v114 (#1941): alias -> operation lookup, kept separate from `cliOps` so
-// aliases don't double-list in printHelp's auto-generated section. Collisions
-// with a primary CLI name, a CLI_ONLY command, or another alias throw at module
-// load — a silent route-shadow is worse than a loud boot failure. CLI_ONLY is
-// derived from the command table (src/cli/command-table.ts), so the check runs
-// over every table record. Exported for the table test's collision case.
-export function buildCliAliases(
- ops: readonly Operation[],
- primary: ReadonlyMap<string, Operation>,
- cliOnly: ReadonlySet<string>,
-): Map<string, Operation> {
- const aliases = new Map<string, Operation>();
- for (const op of ops) {
- if (op.cliHints?.hidden) continue;
- for (const alias of op.cliHints?.aliases ?? []) {
- if (primary.has(alias) || cliOnly.has(alias) || aliases.has(alias)) {
- throw new Error(
- `CLI alias collision: '${alias}' (op '${op.name}') conflicts with an existing ` +
- `command or alias. Rename the alias in src/core/operations.ts.`,
- );
- }
- aliases.set(alias, op);
- }
- }
- return aliases;
-}
-
-export const cliAliases = buildCliAliases(operations, cliOps, CLI_ONLY);
+import { printHelp } from './cli/top-help.ts';
/**
- * Emit the self-upgrade marker on the hot path. CACHE-READ-ONLY: a statSync +
- * read, sub-ms. On a stale/missing cache it kicks a DETACHED, single-flighted
- * `gbrain check-update --refresh-cache` and emits nothing this run. NEVER
- * blocks a command and NEVER throws (the marker must not break any command).
- * Mode resolution is file-plane only (no DB; thin clients have no local DB).
+ * The fast path main() would take for `argv`, or null when the dispatcher must
+ * run. Mirrors main()'s first branches after global-flag parsing; a parse
+ * error falls through so the dispatcher reports it exactly as before.
*/
-function maybeEmitUpdateMarker(command: string): void {
+export function cliFastPath(argv: string[]): 'help' | 'version' | null {
+ let command: string | undefined;
try {
- if (process.env.GBRAIN_SKIP_STARTUP_HOOKS) return;
- // Never run during the test suite: tests spawn the CLI hundreds of times,
- // each with a fresh (stale-cache) GBRAIN_HOME, which would otherwise fire a
- // detached `gbrain check-update --refresh-cache` per invocation and saturate
- // the machine with real network calls. Bun sets NODE_ENV=test.
- if (process.env.NODE_ENV === 'test') return;
- if (STARTUP_HOOK_SKIP_COMMANDS.has(command)) {
- // We ARE the update path — skip self-check AND mark children so any
- // `gbrain post-upgrade` / `gbrain features` they spawn don't re-enter.
- process.env.GBRAIN_SKIP_STARTUP_HOOKS = '1';
- return;
- }
- if (getCliOptions().quiet) return;
-
- // JUST_UPGRADED: one-time confirmation after an upgrade (any mode).
- try {
- const jpath = justUpgradedPath();
- if (existsSync(jpath)) {
- const from = String(readFileSync(jpath, 'utf8')).trim();
- if (from) process.stderr.write(`JUST_UPGRADED ${from} ${VERSION}\n`);
- unlinkSync(jpath);
- }
- } catch {
- /* ignore */
- }
-
- const cfg = loadConfigFileOnly();
- const mode = resolveSelfUpgradeMode(cfg);
- if (mode === 'off') return;
-
- const now = Date.now();
- const entry = readUpdateCache();
- if (entry && isCacheFresh(entry, now)) {
- // Shared stale/foreign-cache guard (pendingUpgradeVersion): only nag when
- // the cached latest is strictly newer than the RUNNING binary, and print
- // the running version — the cache records whatever binary WROTE it.
- const latest = pendingUpgradeVersion(VERSION, now);
- if (latest) {
- // notify mode honors a per-version snooze; auto mode ignores it.
- if (mode === 'notify' && isSnoozeActive(readSnooze(), latest, now)) return;
- // The raw `UPGRADE_AVAILABLE <cur> <latest>` line is a MACHINE marker
- // (parsed by the self-upgrade skill / MCP via parseMarker). A human at
- // an interactive terminal should never see the token as the literal
- // first line of output — so emit it only when stderr is NOT a TTY
- // (agent harnesses capture stderr non-interactively and still get it).
- // GBRAIN_FORCE_UPGRADE_MARKER=1 forces it for the rarer agent harness
- // that allocates a PTY yet still parses the token. The human sentence
- // prints on both.
- if (!process.stderr.isTTY || process.env.GBRAIN_FORCE_UPGRADE_MARKER === '1') {
- process.stderr.write(`UPGRADE_AVAILABLE ${VERSION} ${latest}\n`);
- }
- process.stderr.write(
- `gbrain ${VERSION} -> ${latest} available. Run: gbrain self-upgrade\n`,
- );
- }
- return;
- }
-
- // Stale/missing cache → kick a detached, single-flighted refresh. The child
- // (`check-update --refresh-cache`) single-flights via the refresh lock and
- // writes the cache for the NEXT invocation. We never wait on it.
- // Spawn OURSELVES (hook.ts spawnDetachedPush pattern), not `gbrain` from
- // PATH — a different (older) binary on PATH would write ITS version into
- // the cache and make the marker lie about what is installed here.
- try {
- const exec = process.execPath ?? '';
- const refreshArgs = ['check-update', '--refresh-cache'];
- // Detect compiled-vs-dev by the RUNTIME's basename, not our own — a
- // published binary keeps its official name (`gbrain-darwin-arm64`, a
- // `gb` shim), so matching `/gbrain$/` on execPath would misfire and
- // prepend the `/$bunfs/root/...` virtual entrypoint (process.argv[1] in
- // a compiled Bun binary), producing an unknown-command child that never
- // refreshes. Dev mode runs under `bun`/`node`; anything else IS the
- // compiled binary and re-execs itself directly.
- const isDevRuntime = /[/\\](bun|node)(\.exe)?$/.test(exec);
- const argv = isDevRuntime ? [process.argv[1], ...refreshArgs] : refreshArgs;
- const child = spawn(exec, argv, {
- detached: true,
- stdio: 'ignore',
- env: { ...process.env, GBRAIN_SKIP_STARTUP_HOOKS: '1' },
- });
- // ChildProcess is an EventEmitter — an unhandled 'error' would throw
- // uncaught. Swallow it; the refresh is best-effort.
- child.on('error', () => {});
- child.unref();
- } catch {
- /* spawn failed — fail-open, no refresh this run */
- }
+ command = parseGlobalFlags(argv).rest[0];
} catch {
- /* the update marker must never break a command */
- }
-}
-
-async function main() {
- // cwd-.env quarantine → ~/.gbrain/.env → #3688 guardrails loader (fail-closed).
- await runCliPreflight();
-
- // Parse global flags (--quiet / --progress-json / --progress-interval)
- // BEFORE command dispatch, so `gbrain --progress-json doctor` works.
- // The stripped argv is what the command sees.
- const rawArgs = process.argv.slice(2);
- const { cliOpts, rest: args } = parseGlobalFlags(rawArgs);
- setCliOptions(cliOpts);
-
- let command = args[0];
- installCliRoutingFor(() => command, args);
-
- if (!command || command === '--help' || command === '-h') {
- printHelp();
- return;
- }
-
- if (command === '--version' || command === 'version') {
- console.log(`gbrain ${VERSION}`);
- return;
- }
-
- if (command === '--tools-json') {
- const { printToolsJson } = await import('./commands/tools-json.ts');
- await printToolsJson();
- return;
- }
-
- // #6114: decided once, before startup side effects; help never runs the command (grammar: cli/subcommands.ts).
- const helpRequested = cliHelpRequested(command, args.slice(1));
-
- if (command === 'extract' && !args.some(arg => arg === '--help' || arg === '-h')
- && args.some(arg => ['--repair-attendance', '--apply-preview', '--backup-verified', '--confirm', '--checkpoint'].includes(arg.split('=')[0]))) {
- const { runAttendanceRepairCli } = await import('./commands/extract-attendance-repair.ts');
- await runAttendanceRepairCli(args.slice(1), cliOpts.brain);
- return;
- }
-
- // v0.42 self-upgrade: ride this invocation as an update heartbeat. Cache-read-
- // only, fail-open, never blocks. Skips the update path's own commands + sets
- // GBRAIN_SKIP_STARTUP_HOOKS for their children. Runs for every real command.
- if (!helpRequested) {
- maybeEmitUpdateMarker(command);
-
- // Monthly backup-coverage nag (cache-read-only, bounded by the nag gate;
- // guards + skip set live inside the helper — one place, every call site).
- const { maybeEmitBackupNag } = await import('./core/backup/status-file.ts');
- maybeEmitBackupNag(command, { quiet: getCliOptions().quiet === true });
- // #5137: once per process, when an env key shadows a different config key; never from hook commands.
- if (command !== 'hook') (await import('./core/ai/key-warnings.ts')).warnShadowedProviderKeys();
- }
-
- const subArgs = args.slice(1);
-
- // DX alias: `ask` is a natural-language alias for `query`
- if (command === 'ask') {
- command = 'query';
- }
- dispatchedCommand = command;
-
- // Local patch 2026-06-11 — mark one-shot CLI processes so the facts
- // backstop routes absorb work to the durable jobs worker instead of the
- // in-process queue that the exit teardown drains-then-aborts after ~1-2s
- // (the `pipeline_error: [chat(...)] The operation was aborted.` class in
- // ingest_log). Daemons keep the in-process queue: their event loop
- // outlives the work. See src/core/facts/cli-process-mode.ts.
- if (!['serve', 'jobs', 'autopilot'].includes(command)) {
- const { markShortLivedCliProcess } = await import('./core/facts/cli-process-mode.ts');
- markShortLivedCliProcess();
- }
-
- // Per-command --help; the scan stops at `--` (`agent run -- --help` submits the prompt). Router
- // commands print usage here, so `<cmd> <sub> --help` never reaches the subcommand (#6114).
- if (helpRequested) {
- if (await printRouterHelp(command, subArgs)) return;
- if (await printCuratedHelp(command, subArgs)) return;
- // `eval brainbench` ships a published foreign-runner flag surface — its
- // own usage() must win over the generic eval stub (codex P3). Fall
- // through to handleCliOnly's no-DB brainbench route, which prints it.
- const selfHelpSub = command === 'eval' && subArgs[0] === 'brainbench';
- const op = cliOps.get(command) ?? cliAliases.get(command);
- if (op && !selfHelpSub) {
- printOpHelp(op, command);
- return;
- }
- if (!selfHelpSub && CLI_ONLY.has(command) && !CLI_ONLY_SELF_HELP.has(command)) {
- printCliOnlyHelp(command);
- return;
- }
- // Self-help members whose handler answers --help before it touches the
- // engine. Without this they fall through to the normal dispatch, which
- // connects first — so `gbrain models --help` on a machine with no brain
- // exits 1 with "No brain configured", and the handler's own help block is
- // unreachable. That is the state a reader is most likely to be in.
- if (await printSelfHelpWithoutEngine(command, subArgs)) return;
- }
-
- // #6114: destructive subcommands refuse a token they would ignore (exit 2) before dispatch.
- const strictRefusal = helpRequested ? null : strictArgsRefusal(command, subArgs);
- if (strictRefusal) exitCliError(strictRefusal, command);
-
- // T5 — `gbrain search modes|stats|tune` is the read-only config dashboard,
- // NOT a free-text search for the literal word "modes". Free-text
- // `gbrain search "<query>"` falls through to the cheap-hybrid `search` op
- // below (T4). Preserves the v0.41.6.0 read-only connect+dispatch timeout.
- if (command === 'search' && ['modes', 'stats', 'tune', 'diagnose'].includes(subArgs[0] ?? '')) {
- const { withTimeout, OperationTimeoutError } = await import('./core/timeout.ts');
- const isDiagnose = subArgs[0] === 'diagnose';
- // Gap-closure wave [OV6]: thin clients route the read-only dashboard
- // forms via search_modes/search_stats/search_tune instead of fabricating
- // a scratch PGLite; --reset/--apply/diagnose fall through to the refusal.
- const cfgSearch = loadConfig();
- if (isThinClient(cfgSearch)) {
- const { routeThinClientCommand } = await import('./commands/thin-client-routing.ts');
- if (await routeThinClientCommand(cfgSearch!, 'search', subArgs)) return;
- refuseThinClient('search', cfgSearch!.remote_mcp!.mcp_url);
- }
- const label = 'gbrain search';
- // diagnose runs real retrieval (keyword + vector + hybrid) so it gets a
- // longer deadline than the read-only dashboard.
- const timeoutMs = isDiagnose ? 60_000 : 10_000;
- let engine: BrainEngine;
- try {
- engine = await withTimeout(connectEngine(), timeoutMs, `${label}: connect`);
- } catch (e) {
- if (e instanceof OperationTimeoutError) { console.error(`${e.label} timed out.`); process.exit(124); }
- throw e;
- }
- try {
- if (isDiagnose) {
- const { runSearchDiagnose } = await import('./commands/search-diagnose.ts');
- await withTimeout(runSearchDiagnose(engine, subArgs), timeoutMs, label);
- } else {
- const { runSearch } = await import('./commands/search.ts');
- await withTimeout(runSearch(engine, subArgs), timeoutMs, label);
- }
- } finally {
- // #2084: `search diagnose` runs real hybrid retrieval (arms search-cache
- // writes) — route through the shared bounded teardown like every other
- // one-shot path. The connect-timeout process.exit(124) above is reviewed
- // and intentionally unchanged: no engine exists at that point.
- await finishCliTeardown({ engine });
- }
- return;
- }
-
- if (command === 'sources' && subArgs[0] === 'inspect') {
- const { runCompanyBrainInspection } = await import('./commands/company-brain-inspect.ts');
- await runCompanyBrainInspection(subArgs.slice(1));
- return;
- }
- if (command === 'sources' && subArgs[0] === 'connect') {
- const { runCompanyBrainConnect } = await import('./commands/company-brain-connect.ts');
- await runCompanyBrainConnect(subArgs.slice(1), () => connectEngine({ probeOnly: true }));
- return;
- }
- if (command === 'sources' && subArgs[0] === 'demo' && subArgs[1] === 'company-brain') {
- const { runCompanyBrainDemoCli } = await import('./commands/company-brain-demo.ts');
- await runCompanyBrainDemoCli(subArgs.slice(2));
- return;
- }
-
- // #2185: strict unknown-flag validation — pre-dispatch, pre-engine. A flag
- // no handler consults (the repro: `init --migrate-only --dry-run` applying
- // REAL migrations while the user asked for a rehearsal) fails loud here
- // instead of silently doing the destructive thing. Runs after the --help
- // short-circuit so `gbrain x --help` never errors; runs before any dispatch
- // or engine connect so the error is instant and side-effect-free.
- {
- const migrationError = migrationCliArgumentError(command, subArgs, rawArgs);
- const unknown = migrationError?.flag ?? validateCommandFlags(command, subArgs);
- if (unknown) {
- // Message contract shared with init.ts's in-handler check: lowercase
- // 'unknown flag' on stderr; --json gets one envelope whose legacy keys
- // (status, reason 'invalid_flag', message) are pinned by
- // test/init-migrate-only.test.ts. D1/D3: exit 2 + did-you-mean.
- const message = migrationError?.message ?? `unknown flag ${unknown} for 'gbrain ${command}'`;
- const flagOp = cliOps.get(command) ?? cliAliases.get(command);
- const curated = findCliCommand(command)?.help;
- const known = curated ? (await curated()).help.flags.map(f => f.name) : CLI_FLAG_REGISTRY[command] ?? Object.keys(flagOp?.params ?? {}).map(k => `--${k.replace(/_/g, '-')}`);
- exitCliError(unknownFlagError(command, unknown, message, known), command, { legacy: { status: 'error', reason: 'invalid_flag', message } });
- }
- const curated = await curatedFlagError(command, subArgs);
- if (curated) exitCliError(curated, command);
- }
-
- // DB-free durability pull (v0.42.44 D2): the harden cron calls
- // `gbrain sources pull --path <dir>` every ~30 min. It must NOT open PGLite
- // (a live long-lived session holds the single-writer lock), so handle it
- // BEFORE connectEngine. The `sources pull <id>` form (no --path) still routes
- // through handleCliOnly → runSources with an engine.
- if (command === 'sources' && subArgs[0] === 'pull' && subArgs.includes('--path')) {
- const { runPull } = await import('./commands/sources-harden.ts');
- await runPull(null, subArgs.slice(1));
- return;
- }
-
- // CLI-only commands
- if (CLI_ONLY.has(command)) {
- await handleCliOnly(command, subArgs);
- return;
- }
-
- await runSharedOperation(command, subArgs, cliOpts);
-}
-
-/**
- * Shared-operation dispatch (every non-CLI_ONLY command and alias): parse the
- * op's args, route thin clients over MCP, delegate to a live PGLite owner, or
- * connect and run the handler with the read wallclock bound and teardown.
- * Split out of main() (refactor wave 1, W4 cli); order and exits unchanged.
- */
-async function runSharedOperation(command: string, subArgs: string[], cliOpts: CliOptions): Promise<void> {
- // Shared operations (fall through to aliases, e.g. link-add -> add_link)
- const op = cliOps.get(command) ?? cliAliases.get(command);
- if (!op) exitCliError(usageError(`Unknown command: ${command}`, 'Run `gbrain --help` for available commands.', { code: 'unknown_command' }), command);
-
- // v0.31.1 (Issue #734, CDX-1): parse CLI args BEFORE engine connect so
- // the routing seam below can decide local-vs-remote without paying a
- // PGLite migration replay on thin-client installs. The arg parser, image
- // transform, and required-param check are all engine-free; refactoring
- // them out of the engine try/catch is safe and unlocks routing.
- const params = parseOpArgs(op, subArgs);
-
- // #3513: stdin fill moved out of parseOpArgs so a non-TTY stdin with no
- // piped input can't block the parse forever — the bounded read leaves the
- // param unset on timeout and the required-param check below fails fast.
- await applyStdinParam(op, params);
-
- // v0.27.1 (`gbrain query --image <path>`): swap the `image` param from
- // a filesystem path into base64 bytes + mime. The op accepts base64; the
- // CLI accepts a path. Helper is exported so tests can exercise the
- // transform without spawning a subprocess.
- if (op.name === 'query' && typeof params.image === 'string' && params.image.length > 0) {
- try {
- const { path, base64, mime } = resolveQueryImage(
- params.image as string,
- (params.image_mime as string) || undefined,
- );
- params.image = base64;
- params.image_mime = mime;
- void path;
- } catch (err) {
- exitCliError(usageError(err instanceof Error ? err.message : String(err), 'Pass --image a readable PNG/JPEG/WebP/GIF path.'), command);
- }
- }
-
- // Validate required params before calling handler. v0.27.1: the
- // `query` op's positional `query` is required only when --image is
- // NOT supplied. The runtime altRequired check below overrides the
- // generic required-flag check for that op.
- const queryHasAlt = op.name === 'query' && typeof params.image === 'string' && params.image.length > 0;
- for (const [key, def] of Object.entries(op.params)) {
- if (def.required && params[key] === undefined) {
- if (queryHasAlt && key === 'query') continue;
- const cliName = op.cliHints?.name || op.name;
- const positional = op.cliHints?.positional || [];
- const usage = positional.map(p => `<${p}>`).join(' ');
- exitCliError(usageError(`Missing required parameter '${key}' for 'gbrain ${cliName}'.`, `Usage: gbrain ${cliName} ${usage}`.trimEnd() + ` (see \`gbrain ${cliName} --help\`).`), command);
- }
- }
-
- // v0.31.1 (Issue #734, CDX-1 routing seam): on thin-client installs,
- // route every non-localOnly op through callRemoteTool instead of opening
- // the empty local PGLite. localOnly ops can't run on a thin client at all
- // (no local engine, server intentionally hides them) — refuse with hint.
- // Fix for the silent-empty-results bug class that motivated this whole release.
- const cfgPre = loadConfig();
- if (isThinClient(cfgPre)) {
- if (op.localOnly) {
- refuseThinClient(command, cfgPre!.remote_mcp!.mcp_url);
- }
- // A thin client has no local mounts — an explicit --brain cannot be
- // honored and must not be silently dropped (same loud-beats-silent rule
- // as applyThinClientSourceScope's --source refusal). Ambient tiers
- // (GBRAIN_BRAIN_ID / .gbrain-mount) are ignored here, matching the
- // source axis's ambient-with-nowhere-to-send behavior.
- if (cliOpts.brain) exitCliError(usageError(THIN_CLIENT_BRAIN_FLAG_MESSAGE, 'Remove --brain, or run from a machine with local mounts (`gbrain mounts list`).'), command);
- // #2098: the local path resolves --source / GBRAIN_SOURCE / .gbrain-source
- // inside makeContext (ctx.sourceId), which this route never reaches — so
- // scope must be mapped onto the op's source_id wire param before the call.
- let ambientScope: AmbientSourceBinding | null;
- try {
- ambientScope = applyThinClientSourceScope(op, params);
- } catch (e: unknown) {
- exitCliError(e, command);
- }
- await runThinClientRouted(op, params, cfgPre!, cliOpts, ambientScope);
- return;
- }
-
- // Locally --source reaches the op through makeContext (ctx.sourceId); a
- // per-call --source-id / --all-sources would silently win over it.
- try {
- assertSingleSourceScopeFlag(op, params);
- } catch (e: unknown) {
- exitCliError(e, command);
- }
-
- // The live PGLite owner exposes canonical operations over a dedicated
- // local socket. Delegate before opening a competing engine connection.
- {
- const { runDelegatedCliOperation } = await import('./commands/persistence-delegate.ts');
- if (await runDelegatedCliOperation(op.name, params, cfgPre, {
- brain: cliOpts.brain, timeoutMs: cliOpts.timeoutMs ?? undefined,
- }, formatResult)) return;
- }
-
- // No live serve owns the selected brain; connect through the normal lock path.
- const engine = await connectEngine();
- // #2084: the teardown contract (bounded drain of every background-work sink,
- // bounded disconnect, computed-deadline backstop) lives in finishCliTeardown
- // — see src/core/cli-force-exit.ts for the full design. The hard-deadline
- // timer arms at TEARDOWN start inside the helper, never before the handler:
- // the pre-#2084 placement here measured handler + teardown combined, so a
- // slow-but-healthy query burned the teardown budget (the flat-10s-banner
- // bug) and any >10s op was force-killed mid-run with exit 0. The explicit
- // process exit happens once, in the import.meta.main seam at the bottom of
- // this file — NOT here.
-
- // v0.42.41.0 (merged): wallclock bound for READ-scope op handlers. With the
- // teardown backstop correctly scoped to teardown, a genuinely WEDGED read
- // handler (hung pooler connection mid-query) would otherwise hang the CLI
- // forever — the #1633 zombie class the old pre-try timer accidentally
- // bounded at 10s. 180s sits far above any healthy slow-pooler run
- // (6-10s/connection); --timeout=Ns overrides. Writes/admin stay unbounded:
- // a long import/embed must never be killed by a default deadline. On
- // timeout the abandoned handler may hold ref'd sockets — harmless here,
- // because the import.meta.main seam exits explicitly on every one-shot path.
- const READ_OP_TIMEOUT_MS = 180_000;
-
- try {
- const { withTimeout, OperationTimeoutError } = await import('./core/timeout.ts');
- const wallclockMs = getCliOptions().timeoutMs ?? READ_OP_TIMEOUT_MS;
- const onWallclockTimeout = (e: InstanceType<typeof OperationTimeoutError>) => {
- const hint = getCliOptions().timeoutMs
- ? ''
- : ` (default ${e.ms}ms; pass --timeout=Ns to override)`;
- console.error(`${e.label} timed out${hint}.`);
- // 124 = timeout convention (matches the read-only dispatch path). Set
- // through the verdict channel — a raw process.exitCode write is invisible
- // to the exit seam and PGLite's WASM runtime can scribble over it.
- setCliExitVerdict(124);
- };
-
- // Context build does DB I/O (resolveSourceId) and runs for EVERY op —
- // a wedged pooler connection here would otherwise hang reads, writes,
- // and admin alike with no bound at all (adversarial review finding).
- let ctx: Awaited<ReturnType<typeof makeContext>>;
- try {
- ctx = await withTimeout(
- makeContext(engine, params, op),
- wallclockMs,
- `gbrain ${command}: context`,
- );
- } catch (e: unknown) {
- if (e instanceof OperationTimeoutError) {
- onWallclockTimeout(e);
- return; // the finally drains + disconnects; the import.meta.main seam exits
- }
- throw e;
- }
-
- let rawResult: unknown;
- if (op.scope === 'read') {
- try {
- rawResult = await withTimeout(
- op.handler(ctx, params),
- wallclockMs,
- `gbrain ${command}`,
- );
- } catch (e: unknown) {
- if (e instanceof OperationTimeoutError) {
- onWallclockTimeout(e);
- return; // the finally drains + disconnects; the import.meta.main seam exits
- }
- throw e;
- }
- } else {
- rawResult = await op.handler(ctx, params);
- }
- // ENG-2 (renderer parity by data shape): JSON-round-trip the local-engine
- // path's return value so renderers see the same shape they'd see on the
- // routed path. Date → ISO string; bigint → string (postgres.js shape);
- // Buffer → object. Microsecond-cost; eliminates a whole drift bug class.
- const { result, stderr: noticeText } = applyCliOpNotices(normalizeLocalResult(rawResult), params.json === true);
- const output = formatResult(op.name, result, params);
- // Awaited delivery (#3423): queued stdout writes past 64KiB lose their
- // tail to a slow pipe reader when the exit grace lapses — see
- // writeStdoutFinal.
- if (output) await writeStdoutFinal(output);
- if (noticeText) process.stderr.write(noticeText);
- // #4488: an op that reports failure IN-BAND (`{status: 'error'}` — e.g.
- // put_page over unparseable frontmatter) used to print the envelope and
- // exit 0, so scripts read a never-written page as success. Echo the error
- // to stderr and set the failure verdict. No-op statuses ('skipped',
- // 'unchanged', …) stay exit 0 — a no-op is not a failure.
- if (
- typeof result === 'object' && result !== null && !Array.isArray(result) &&
- (result as { status?: unknown }).status === 'error'
- ) {
- const detail = (result as { error?: unknown }).error;
- console.error(
- `gbrain ${command}: operation reported status 'error'` +
- (typeof detail === 'string' && detail ? ` — ${detail}` : '') + '.',
- );
- setCliExitVerdict(1);
- }
- maybePrintConceptNudge(op.name, params);
- } catch (e: unknown) {
- // v0.42.20.0 (codex D4): on error, set exitCode + return so the `finally`
- // STILL runs (drains every background-work sink + disconnects). A bare
- // process.exit(1) here would skip the finally → skip the drain + disconnect
- // (leaves facts/cache/eval-capture writes racing teardown). The finally's
- // drain bounds teardown; the hard-deadline timer armed at teardown entry
- // bounds a hung one.
- // #5232: the reporter owns the write verdict; never overwrite it.
- const { reportPersistenceCliError } = await import('./commands/persistence-delegate.ts');
- const receipt = !(e instanceof OperationError) || !!e.writeRequest;
- if (!receipt || !await reportPersistenceCliError(e, params.json === true || !!(e as OperationError)?.writeRequest)) {
- setCliExitVerdict(writeCliError(e, command));
- }
- } finally {
- // 1s per-sink drain budget: read paths with no pending work pay the ~0ms
- // fast path; capture/import that DO enqueue pay up to 1s (+ facts shutdown
- // grace) while in-flight Haiku finishes (#1762 drain-before-disconnect).
- await finishCliTeardown({ engine, drainTimeoutMs: 1000 });
- }
-}
-
-function hasHelpFlag(args: string[]): boolean {
- return args.includes('--help') || args.includes('-h');
-}
-
-function printCliOnlyHelp(command: string) {
- console.log(`Usage: gbrain ${command}`);
- console.log('');
- console.log(`gbrain ${command} - run gbrain --help for the full command list.`);
-}
-
-/**
- * v0.31.1 (Issue #734, CDX-1): route a shared op through the remote MCP
- * server instead of running it locally. Called from main() when
- * `isThinClient(cfg) && !op.localOnly`.
- *
- * Timeout policy (ENG-4): user override via --timeout=Ns wins; otherwise
- * 180s for `think` (LLM calls), 30s for everything else.
- *
- * Error policy: callRemoteTool normalizes every failure to RemoteMcpError;
- * the exhaustive switch requires a renderer for every reason variant.
- *
- * Renderer policy: unpackToolResult parses MCP text and shares formatResult
- * with the local-engine path, enforcing parity through the result shape.
- */
-async function runThinClientRouted(
- op: Operation,
- params: Record<string, unknown>,
- cfg: GBrainConfig,
- cliOpts: CliOptions,
- ambientScope: AmbientSourceBinding | null = null,
-): Promise<void> {
- // ENG-4: per-op timeout default; user override wins.
- const defaultTimeoutMs = op.name === 'think' ? 180_000 : 30_000;
- const timeoutMs = cliOpts.timeoutMs ?? defaultTimeoutMs;
-
- // SIGINT support: aborts in-flight HTTP cleanly (exit 130 is the standard
- // SIGINT exit code; our error switch maps `network/aborted` to that).
- const sigintController = new AbortController();
- const onSigint = () => {
- sigintController.abort(new Error('SIGINT'));
- };
- process.on('SIGINT', onSigint);
-
- // v0.31.1 (Issue #734, cherry-pick B): print identity banner to stderr
- // BEFORE the routed call. Banner failure suppresses the banner only —
- // never the underlying command. Suppression honors --quiet, non-TTY,
- // and GBRAIN_NO_BANNER=1.
- await printIdentityBannerBestEffort(cfg, cliOpts, sigintController.signal);
-
- try {
- const raw = await callRemoteTool(cfg, op.name, params, {
- timeoutMs,
- signal: sigintController.signal,
- ...(op.mutating ? { writeWaitMs: currentCliWriteWait().waitMs } : {}),
- });
- // T15/FOV-1: lift the server's retrieval meta off the envelope before
- // unpacking (old servers lack _meta — capture is simply skipped).
- const envelopeMeta = extractResponseMeta(raw);
- if (envelopeMeta?.retrieval) captureRetrievalMeta('retrieval', envelopeMeta.retrieval);
- checkHostHonoredParams(op, params, raw);
- const result = unpackToolResult(raw);
- hintAmbientNarrowing(op, params, result, ambientScope);
- const skew = deliveryVersionSkewWarning(op.name, params, envelopeMeta?.retrieval as Record<string, unknown> | undefined, result);
- if (skew) process.stderr.write(skew + '\n');
- const output = formatResult(op.name, result, params);
- // Awaited delivery (#3423) — same contract as the local-engine path.
- if (output) await writeStdoutFinal(output);
- maybePrintConceptNudge(op.name, params);
- } catch (e: unknown) {
- if (e instanceof RemoteMcpError) {
- const { reportPersistenceCliError } = await import('./commands/persistence-delegate.ts');
- if (await reportPersistenceCliError(e, params.json === true)) {
- process.off('SIGINT', onSigint);
- process.exit(sigintController.signal.aborted ? 130 : currentExitCode());
- }
- // D1: a server tool error renders its own code/fix; --json gets the one v1
- // envelope on stdout while transport failures keep their human text on stderr.
- const scopeDenied = isScopeErrorCode(e.detail?.code, e.detail?.canonical_code, e.detail?.reason);
- if ((e.reason === 'tool_error' && !scopeDenied) || e.detail?.code === 'serve_status_only') { process.off('SIGINT', onSigint); exitCliError(e, op.cliHints?.name ?? op.name); }
- const failExit = params.json === true ? writeCliError(e, op.cliHints?.name ?? op.name, { stderr: false }) : 1;
- const url = cfg.remote_mcp!.mcp_url;
- switch (e.reason) {
- case 'config':
- console.error(e.message);
- break;
- case 'discovery':
- console.error(`OAuth discovery failed at ${cfg.remote_mcp!.issuer_url}.`);
- console.error('Run `gbrain remote doctor` for details.');
- break;
- case 'auth':
- console.error('OAuth auth failed.');
- console.error('On the host, re-register your client:');
- console.error(' gbrain auth register-client <name> --grant-types client_credentials --scopes read,write,admin');
- break;
- case 'auth_after_refresh':
- console.error('OAuth auth failed after token refresh. Credentials may have been revoked.');
- console.error('Run `gbrain remote doctor` to confirm.');
- break;
- case 'rate_limited':
- console.error(`OAuth /token is rate-limited by the server (HTTP 429)${e.detail?.retry_after_s !== undefined ? `; retry in ${e.detail.retry_after_s}s` : ''}.`);
- console.error('This is the host\'s token-mint budget, not a connectivity problem; the host operator can raise GBRAIN_OAUTH_TOKEN_RATE_LIMIT_MAX.');
- break;
- case 'token':
- console.error(`${e.message} (issuer ${cfg.remote_mcp!.issuer_url}).`);
- console.error('Run `gbrain remote doctor` for details.');
- break;
- case 'network':
- if (e.detail?.kind === 'timeout') {
- const hint = cliOpts.timeoutMs ? '' : ` (default ${defaultTimeoutMs}ms; pass --timeout=Ns to override)`;
- console.error(`Request to ${url} timed out${hint}.`);
- } else if (e.detail?.kind === 'aborted') {
- console.error('Request aborted.');
- process.off('SIGINT', onSigint);
- process.exit(130);
- } else {
- console.error(`Cannot reach ${url}. Run \`gbrain remote doctor\` for details.`);
- }
- break;
- case 'tool_error':
- console.error('Missing OAuth scope on this client.');
- console.error('On the host, re-register the client with broader scopes:');
- console.error(' gbrain auth register-client <name> --grant-types client_credentials --scopes read,write,admin');
- break;
- case 'parse':
- console.error('Server response was malformed. Run `gbrain remote doctor`.');
- break;
- default: {
- // Exhaustive switch sentinel (TS `never` — fails to build if a
- // new RemoteMcpErrorReason variant is added without a case).
- const _exhaustive: never = e.reason;
- void _exhaustive;
- console.error(`Unhandled remote error: ${e.message}`);
- }
- }
- process.off('SIGINT', onSigint);
- process.exit(failExit);
- }
- // Defense in depth: callRemoteTool's contract is that everything is
- // RemoteMcpError. If a plain Error escapes, render it generically — but
- // this should never happen post-CDX-4.
- process.off('SIGINT', onSigint);
- exitCliError(e, op.cliHints?.name ?? op.name);
- } finally {
- process.off('SIGINT', onSigint);
- }
-}
-
-// ============================================================================
-// v0.31.1 (Issue #734, cherry-pick B): thin-client identity banner.
-//
-// Prints "[thin-client → <host> · brain: 102k pages, 265k chunks · vX.Y.Z]"
-// to stderr before each routed command, so users (and agents) know they're
-// talking to a real remote brain — not the empty local PGLite that motivated
-// this whole release.
-//
-// Cache: 60s TTL, in-memory Map keyed by mcp_url. Cross-process file cache
-// is deferred (marginal benefit; one mint per CLI process is fine).
-// Suppression: --quiet, non-TTY, GBRAIN_NO_BANNER=1.
-// Failure mode: any error in fetching identity → suppress banner; underlying
-// command runs normally. Banner is observability, not load-bearing.
-// ============================================================================
-
-export interface BrainIdentity {
- version: string;
- engine: 'postgres' | 'pglite';
- page_count: number;
- chunk_count: number;
- last_sync_iso: string | null;
-}
-
-interface CachedIdentity {
- identity: BrainIdentity;
- cached_at_ms: number;
-}
-
-const IDENTITY_TTL_MS = 60_000;
-const identityCache = new Map<string, CachedIdentity>();
-
-export function bannerSuppressed(cliOpts: CliOptions): boolean {
- if (cliOpts.quiet) return true;
- if (process.env.GBRAIN_NO_BANNER === '1') return true;
- // Non-TTY default is suppressed (clean pipes); explicit env-flag overrides.
- if (!process.stderr.isTTY && process.env.GBRAIN_BANNER !== '1') return true;
- return false;
-}
-
-function formatPageCount(n: number): string {
- if (n >= 1000) {
- const k = (n / 1000).toFixed(n >= 100_000 ? 0 : 1);
- return `${k}k`;
- }
- return String(n);
-}
-
-function formatBanner(mcpUrl: string, id: BrainIdentity): string {
- const host = mcpUrl.replace(/^https?:\/\//, '').split('/')[0];
- const counts = `brain: ${formatPageCount(id.page_count)} pages, ${formatPageCount(id.chunk_count)} chunks`;
- return `[thin-client → ${host} · ${counts} · v${id.version}]`;
-}
-
-async function fetchIdentity(
- cfg: GBrainConfig,
- signal: AbortSignal,
-): Promise<BrainIdentity> {
- // 2s timeout for the banner fetch — must not delay the underlying command.
- const raw = await callRemoteTool(cfg, 'get_brain_identity', {}, {
- timeoutMs: 2000,
- signal,
- });
- const id = unpackToolResult<BrainIdentity>(raw);
- return id;
-}
-
-async function printIdentityBannerBestEffort(
- cfg: GBrainConfig,
- cliOpts: CliOptions,
- signal: AbortSignal,
-): Promise<void> {
- if (bannerSuppressed(cliOpts)) return;
- const mcpUrl = cfg.remote_mcp?.mcp_url;
- if (!mcpUrl) return;
-
- // Cache lookup keyed by mcp_url so switching hosts via `gbrain init`
- // invalidates cleanly even within a long-lived process.
- const cached = identityCache.get(mcpUrl);
- if (cached && Date.now() - cached.cached_at_ms < IDENTITY_TTL_MS) {
- process.stderr.write(formatBanner(mcpUrl, cached.identity) + '\n');
- // v0.31.11: detect remote-version drift, prompt user to upgrade.
- // bannerIsSuppressed=false here — the early return above guaranteed it.
- await maybePromptForUpgrade(cfg, cached.identity, cliOpts, false);
- return;
- }
-
- // Cache miss — fetch. Failure is non-fatal: banner is observability,
- // never load-bearing for the underlying command.
- try {
- const id = await fetchIdentity(cfg, signal);
- identityCache.set(mcpUrl, { identity: id, cached_at_ms: Date.now() });
- process.stderr.write(formatBanner(mcpUrl, id) + '\n');
- // v0.31.11: detect remote-version drift, prompt user to upgrade.
- await maybePromptForUpgrade(cfg, id, cliOpts, false);
- } catch {
- // Swallow. Banner suppressed; main command continues. The CDX-4
- // hardened callRemoteTool will surface the same error class on the
- // actual command call if the host is genuinely unreachable.
- }
-}
-
-/**
- * v0.27.1: shared transform for `gbrain query --image <path>` (and any future
- * CLI surface that takes an image path). Reads the file, base64-encodes,
- * derives MIME from the extension, enforces the 20MB cap. Exported so tests
- * can verify the transform without spawning a subprocess.
- *
- * Throws Error on any failure (file missing, oversized, etc.). Caller is
- * responsible for routing to process.exit(1) with a user-facing message.
- */
-export function resolveQueryImage(
- imagePath: string,
- explicitMime?: string,
-): { path: string; base64: string; mime: string } {
- const bytes = readFileSync(imagePath);
- if (bytes.length > 20 * 1024 * 1024) {
- throw new Error(`Error: image too large (${bytes.length} bytes, max 20MB).`);
- }
- const base64 = bytes.toString('base64');
- let mime = explicitMime;
- if (!mime) {
- const lower = imagePath.toLowerCase();
- const mimeFromExt: Record<string, string> = {
- '.png': 'image/png',
- '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
- '.gif': 'image/gif',
- '.webp': 'image/webp',
- '.heic': 'image/heic', '.heif': 'image/heif',
- '.avif': 'image/avif',
- };
- const ext = Object.keys(mimeFromExt).find(e => lower.endsWith(e));
- mime = ext ? mimeFromExt[ext] : 'image/jpeg';
- }
- return { path: imagePath, base64, mime };
-}
-
-export function parseOpArgs(op: Operation, args: string[]): Record<string, unknown> {
- // `gbrain search --explain`: the CLI-local formatter flag also asks the op for score attribution.
- const params: Record<string, unknown> = op.name === 'search' && args.includes('--explain') ? { explain: true } : {};
- const positional = op.cliHints?.positional || [];
- let posIdx = 0;
-
- let endOfOptions = false; // D6: a bare `--` ends options (as in findUnknownOpFlag); later tokens are positionals
- for (let i = 0; i < args.length; i++) {
- const arg = args[i];
- if (arg === '--' && !endOfOptions) { endOfOptions = true; continue; }
- if (arg.startsWith('--') && !endOfOptions) {
- // #2185: `--key=value` inline form. Pre-fix this parsed as junk key
- // 'key=value' and consumed the NEXT token as its value, corrupting
- // positional parsing. Recognized here so the strict-flag validator and
- // the parser agree on the idiom.
- const eq = arg.indexOf('=');
- if (eq > 2) {
- const key = arg.slice(2, eq).replace(/-/g, '_');
- // CLI-local booleans: `--json=<v>` / `--dry-run=<v>` must parse as
- // booleans, not fall through to the junk-key path (which would
- // consume the NEXT token as a value and corrupt positional parsing).
- if (key === 'json' || key === 'dry_run') {
- params[key] = arg.slice(eq + 1) !== 'false';
- continue;
- }
- const def = op.params[key];
- if (def) {
- const raw = arg.slice(eq + 1);
- params[key] = def.type === 'boolean' ? raw !== 'false' : opParamValue(op, key, def, raw);
- continue;
- }
- }
- if (arg.startsWith('--no-')) {
- const positiveKey = arg.slice(5).replace(/-/g, '_');
- const positiveDef = op.params[positiveKey];
- if (positiveDef?.type === 'boolean') {
- params[positiveKey] = false;
- continue;
- }
- }
- const key = arg.slice(2).replace(/-/g, '_');
- const paramDef = op.params[key];
- if (paramDef?.type === 'boolean') {
- // #4602: a boolean flag followed by the word false used to set the
- // flag TRUE (silent intent inversion, exit 0) and leave the literal
- // 'false' to bind to the next unfilled positional slot (data
- // corruption on multi-positional ops). A LITERAL true/false following
- // a boolean flag is that flag's value — consume it, matching the
- // inline `=false` spelling that already worked. Any OTHER following
- // token keeps the old semantics (flag = true, token stays positional).
- params[key] = isBooleanLiteral(args[i + 1]) ? args[++i] === 'true' : true;
- } else if (key === 'json' || key === 'dry_run') {
- // CLI-local booleans, intentionally NOT on the operation contract
- // exposed over MCP/tools: json is the formatter flag; dry_run feeds
- // makeContext's ctx.dryRun. Neither consumes an ARBITRARY value token —
- // pre-fix, `gbrain delete x --dry-run` (trailing) set NOTHING, so
- // ctx.dryRun stayed false and the REAL delete ran despite the
- // rehearsal request (the resurrected #2185 class the red team caught).
- // #4602: a literal true/false is the one exception — it is this
- // flag's value (never a plausible positional), same as above.
- params[key] = isBooleanLiteral(args[i + 1]) ? args[++i] === 'true' : true;
- } else if (i + 1 < args.length) {
- // #5700: a known flag of this command in the value slot is a missing
- // argument, not a value (see op-flag-tokens.ts).
- if (isKnownOpFlag(op, args[i + 1])) {
- const flag = `--${key.replace(/_/g, '-')}`;
- const stdinHint = op.cliHints?.stdin === key ? `; omit ${flag} (or put it last) to read stdin` : '';
- throw usageError(`${flag} requires a value, but '${args[i + 1]}' is a flag${stdinHint}.`, `Pass ${flag} a value before the next flag (see \`gbrain ${op.cliHints?.name ?? op.name} --help\`).`);
- }
- // #2822: a flag silently overwriting an already-set positional is
- // almost always an argument-plumbing mistake (e.g. `gbrain put
- // notes.md --content "..."` — the file path landed in `content`
- // positionally, then --content clobbered it). Warn to stderr; when
- // the discarded value names an existing file, point at capture --file.
- const prevValue = params[key];
- params[key] = opParamValue(op, key, paramDef, args[++i]);
- if (prevValue !== undefined && prevValue !== params[key]) {
- let fileHint = '';
- try {
- if (typeof prevValue === 'string' && prevValue && existsSync(prevValue)) {
- fileHint = ` If '${prevValue}' is a file you meant to ingest, use: gbrain capture --file ${prevValue} --slug <slug>`; // nosemgrep: javascript.express.security.injection.raw-html-format.raw-html-format -- stderr text, never HTML
- }
- } catch { /* best-effort hint */ }
- process.stderr.write(
- `Warning: --${key.replace(/_/g, '-')} overwrites the positional value '${String(prevValue)}'.${fileHint}\n`,
- );
- }
- }
- } else if (posIdx < positional.length) {
- const key = positional[posIdx++];
- const paramDef = op.params[key];
- params[key] = opParamValue(op, key, paramDef, arg, true);
- }
- }
-
- for (const [key, def] of Object.entries(op.params)) {
- if ((def.type !== 'object' && def.type !== 'array') || typeof params[key] !== 'string') continue;
- let value: unknown;
- const jsonError = () => usageError(`--${key.replace(/_/g, '-')} requires a JSON ${def.type}.`, `Pass JSON, e.g. --${key.replace(/_/g, '-')} '${def.type === 'array' ? '["a","b"]' : '{"key":"value"}'}'.`);
- try { value = JSON.parse(params[key] as string); } catch { throw jsonError(); }
- if (def.type === 'array' ? !Array.isArray(value) : value === null || typeof value !== 'object' || Array.isArray(value)) throw jsonError();
- params[key] = value;
- }
- return params;
-}
-
-/**
- * #3513: read stdin into an op's stdin-capable param without ever blocking
- * forever. The old inline `readFileSync(0)` in parseOpArgs assumed non-TTY
- * implies piped content; a non-TTY stdin with NO input (CI step, cron job,
- * agent harness holding an unwritten pipe open) blocked the read until kill.
- *
- * Strategy by fd kind (fstat):
- * - TTY: skip, as before (interactive input is not an op-param source).
- * - regular file / /dev/null / anything not a pipe or socket: readFileSync
- * returns without blocking (`gbrain put x < file`, `< /dev/null` → '').
- * - FIFO/socket: stream-read with a deadline on the FIRST byte only. A real
- * pipe (`echo foo | gbrain put x`, heredocs) delivers its first byte
- * within milliseconds; once data flows only a 60s inactivity timeout
- * applies, reset on every chunk (slow producers stay supported).
- * An empty-but-closed pipe (`: | gbrain put x`) EOFs immediately → ''.
- * A pipe that never delivers a byte times out → param stays unset, so
- * the existing required-param usage error fires (fail fast, exit 1).
- *
- * GBRAIN_STDIN_TIMEOUT_MS overrides the first-byte deadline (default 30s,
- * stderr notice at 5s). The reader is interaction.ts readStdinBounded (A5).
- * Exported for tests; called by the op dispatch right after parseOpArgs.
- */
-export async function applyStdinParam(
- op: Operation,
- params: Record<string, unknown>,
-): Promise<void> {
- // Branch shape (stdin hint + missing param + `!process.stdin.isTTY` gate +
- // 5MB cap) is pinned by the R4 regression test for PR #1325's Windows fix
- // (test/cycle/regression-pr-wave-r1-r2-r4.test.ts) — keep the spelling.
- if (op.cliHints?.stdin && !params[op.cliHints.stdin] && !process.stdin.isTTY) {
- const content = await readStdinBounded();
- if (content === null) return; // no input arrived — let the required-param check fail fast
- // #2822: empty/whitespace-only stdin is NO input, not a real value. A CI
- // step's `< /dev/null`, an agent harness's empty pipe, or a botched
- // redirect used to land '' in the param and flow into a destructive
- // empty write; leaving the param unset makes the required-param usage
- // error fire instead (same fail-fast as the #3513 timeout path).
- if (content.trim() === '') return;
- const MAX_STDIN = 5_000_000; // 5MB
- if (Buffer.byteLength(content, 'utf-8') > MAX_STDIN) {
- exitCliError(opError('payload_too_large', `stdin content exceeds ${MAX_STDIN} bytes.`, 'Split the content into smaller inputs.'), op.cliHints?.name ?? op.name);
- }
- params[op.cliHints.stdin] = content;
- }
-}
-
-/**
- * Legacy-signature shim over interaction.ts readStdinBounded (A5): the full
- * stdin content, '' for a readable-but-empty stdin, or null for anything else
- * (first-byte or inactivity timeout, stream error, closed fd). No byte cap
- * here: applyStdinParam keeps its own 5MB check and message.
- */
-export async function readStdinBounded(): Promise<string | null> {
- const r = await readStdinPayload({ maxBytes: Infinity });
- return r.kind === 'data' ? r.text : r.kind === 'empty' ? '' : null;
-}
-
-/**
- * #2098: thin-client source scoping. Locally, --source / GBRAIN_SOURCE /
- * .gbrain-source resolve to ctx.sourceId in makeContext; the thin-client
- * route short-circuits before that, so `gbrain query --source X` against a
- * remote brain silently searched unscoped. This runs the engine-free tiers
- * (flag → env → dotfile; the DB-backed tiers can't run without an engine —
- * the server's grant scoping covers the rest) and maps the result onto the
- * op's `source_id` wire param.
- *
- * Ops that declare their OWN `source` param (facts add, etc.) are left
- * untouched — their --source is an op param, not scope. An explicit --source
- * on an op with no source_id wire param throws (loud beats silent drop);
- * ambient env/dotfile scope with nowhere to send it is ignored, matching the
- * pre-fix behavior for non-scopeable ops. Exported for tests.
- */
-// Ops whose `source_id` wire param is NOT read-scope semantics: get_skill's
-// source_id flips the lookup from host catalog to brain-resident-pack
-// (getResidentSkillDetail). Ambient env/dotfile scope must never leak into
-// these; an explicit --source-id still passes through untouched above.
-const NON_SCOPE_SOURCE_ID_OPS = new Set(['get_skill']);
-
-/**
- * Returns the ambient binding (GBRAIN_SOURCE / .gbrain-source) that was mapped
- * onto `source_id`, so an empty result can say what narrowed it; null when the
- * scope came from a flag or nothing was mapped.
- */
-export function applyThinClientSourceScope(
- op: Operation,
- params: Record<string, unknown>,
- cwd?: string,
-): AmbientSourceBinding | null {
- if (opOwnsSource(op)) return null;
- assertSingleSourceScopeFlag(op, params);
- const explicit = typeof params.source === 'string' && params.source.length > 0
- ? (params.source as string)
- : null;
- delete params.source; // never a wire param on these ops — don't leak it
- // Explicit per-call scope already on the wire wins over ambient tiers.
- if (params.source_id !== undefined || params.all_sources === true) return null;
- const resolved = resolveSourceIdEngineFree(explicit, cwd);
- if (!resolved) return null;
- if (!('source_id' in op.params) || NON_SCOPE_SOURCE_ID_OPS.has(op.name)) {
- if (explicit) {
- const hint = NON_SCOPE_SOURCE_ID_OPS.has(op.name)
- ? `(its source_id parameter is not a scope filter; pass --source-id explicitly if you mean it)`
- : `(the remote op has no source_id parameter; the server scopes it to your grant)`;
- throw new Error(
- `gbrain ${op.cliHints?.name || op.name} does not accept --source on a thin-client install ${hint}.`,
- );
- }
- return null; // ambient env/dotfile scope with nowhere to send it
- }
- params.source_id = resolved;
- if (explicit) return null;
- const env = process.env.GBRAIN_SOURCE;
- return { sourceId: resolved, via: env && env.length > 0 ? 'GBRAIN_SOURCE' : '.gbrain-source' };
-}
-
-// Exported for tests (same import-safety contract as applyThinClientSourceScope).
-// ─────────────────────────────────────────────────────────────────
-// #2185 — strict unknown-flag validation (pre-dispatch, pre-engine).
-// A flag no handler consults must fail loud instead of silently doing the
-// destructive thing (`init --migrate-only --dry-run` applied REAL migrations
-// while the user asked for a rehearsal). Two lanes:
-// - op commands: legal flags derive from the operation contract
-// (op.params) + the CLI-local formatter flags, mirroring parseOpArgs's
-// traversal so values that begin with '--' are never misread.
-// - CLI_ONLY commands: legal flags come from the generated
-// CLI_FLAG_REGISTRY (scripts/generate-flag-registry.ts scans each
-// command's source; freshness + coverage pinned by
-// test/cli-flag-validation.test.ts).
-// Everything after a literal `--` is passthrough and never validated.
-// ─────────────────────────────────────────────────────────────────
-
-// Exempt by contract, not oversight:
-// - call: the generic op invoker — arbitrary --param names are its interface.
-// - config: `config set <key> <value>` values are arbitrary strings.
-// - jobs submit: job payloads carry handler-defined params (shell lane incl.).
-// - eval brainbench: owns the 0/1/2 CI exit-code contract (0 pass · 1
-// regression · 2 error/inconclusive) via its own arg parser. The global
-// validator's exit(1) on an unknown flag would be read by a CI harness as a
-// memory REGRESSION rather than a typo; brainbench maps a bad flag to exit 2
-// (error) with its own usage. Its legal flags still land in the generated
-// registry (the generator scans eval's modules), so freshness/drift hold.
-function flagValidationExempt(command: string, subArgs: string[]): boolean {
- return command === 'call' || command === 'config'
- || (command === 'jobs' && subArgs[0] === 'submit')
- || (command === 'eval' && subArgs[0] === 'brainbench');
-}
-
-/** Returns the first unknown flag (e.g. '--dry-run') or null when clean. */
-export function validateCommandFlags(command: string, subArgs: string[]): string | null {
- if (flagValidationExempt(command, subArgs)) return null;
- if (command === 'retrieval-upgrade' || command === 'migrate' && subArgs[0] === 'embeddings') return migrationCliArgumentError(command, subArgs)?.flag ?? null;
- // Lane order MUST mirror dispatch order (CLI_ONLY first): commands that are
- // BOTH an op and a CLI_ONLY member (think, salience, anomalies) dispatch to
- // handleCliOnly, whose handlers parse flags the op contract doesn't declare
- // (`salience --kind`, `think --with-calibration`) — validating those
- // against op.params rejected documented invocations.
- if (CLI_ONLY.has(command)) {
- const legal = CLI_FLAG_REGISTRY[command];
- // Registry drift fails OPEN at runtime (never brick a command); the
- // drift-guard test fails the build instead.
- if (!legal) return null;
- return findUnknownFlag(subArgs, new Set(legal));
- }
- const op = cliOps.get(command) ?? cliAliases.get(command);
- if (op) return findUnknownOpFlag(op, subArgs);
- return null; // unknown command — the dispatcher's own error handles it
-}
-
-/** CLI_ONLY lane: token scan against the generated legal set. */
-export function findUnknownFlag(args: string[], legal: ReadonlySet<string>): string | null {
- for (const a of args) {
- if (a === '--') break;
- const m = /^--([a-z0-9][a-z0-9-]*)(?:=.*)?$/i.exec(a);
- if (!m) continue;
- // Casing typo = unknown flag: every handler in the repo is
- // case-sensitive-lowercase, so `--MIGRATE-ONLY` passing validation would
- // just be silently ignored downstream — the exact class this validator
- // exists to kill.
- if (/[A-Z]/.test(m[1])) return `--${m[1]}`;
- const name = `--${m[1]}`;
- if (legal.has(name)) continue;
- // --no-<flag> negation of a known flag is legal.
- if (name.startsWith('--no-') && legal.has(`--${name.slice(5)}`)) continue;
- return name;
- }
- return null;
-}
-
-/** Op lane: mirrors parseOpArgs so flag VALUES starting with '--' are skipped. */
-export function findUnknownOpFlag(op: Operation, args: string[]): string | null {
- for (let i = 0; i < args.length; i++) {
- const a = args[i];
- if (a === '--') break;
- const m = /^--([a-z0-9][a-z0-9-]*)(?:=(.*))?$/i.exec(a);
- if (!m) continue;
- // Casing typo = unknown flag (see findUnknownFlag).
- if (/[A-Z]/.test(m[1])) return `--${m[1]}`;
- const rawKey = m[1];
- // CLI-local flags consumed OUTSIDE the op contract (never wire params):
- // json/explain — formatter flags; help — short-circuits pre-dispatch;
- // source — makeContext's 6-tier source resolution (deleted before wire);
- // dry-run — makeContext's ctx.dryRun projection.
- // Pre-fix, rejecting these broke documented invocations
- // (`gbrain search "x" --source y`, `gbrain put x --dry-run`).
- if (rawKey === 'json') {
- // #4602: parseOpArgs consumes a literal true/false as this boolean's
- // value — mirror the traversal so the token counts as consumed here too.
- if (m[2] === undefined && isBooleanLiteral(args[i + 1])) i++;
- continue;
- }
- // Bare-only even where an op also declares `explain` (search/query): the `=` form is refused, never parsed as a value.
- if (rawKey === 'explain' || rawKey === 'help') { if (m[2] === undefined) continue; return `--${rawKey}`; }
- if (rawKey === 'source' || rawKey === 'dry-run') {
- // Non-boolean-style CLI-locals consume the next token as their value
- // in parseOpArgs (source does; dry-run is boolean-read) — mirror the
- // parser: source consumes a value when not inline-`=`; dry-run
- // consumes only a literal true/false (#4602).
- if (rawKey === 'source' && m[2] === undefined) i++;
- if (rawKey === 'dry-run' && m[2] === undefined && isBooleanLiteral(args[i + 1])) i++;
- continue;
- }
- if (rawKey.startsWith('no-')) {
- const positive = rawKey.slice(3).replace(/-/g, '_');
- if (op.params[positive]?.type === 'boolean') continue;
- }
- const key = rawKey.replace(/-/g, '_');
- const paramDef = op.params[key];
- if (paramDef) {
- // Non-boolean flags consume the next token as their value unless
- // provided inline via `=` — exactly like parseOpArgs. Boolean flags
- // consume only a literal true/false value token (#4602).
- if (paramDef.type !== 'boolean' && m[2] === undefined) i++;
- else if (paramDef.type === 'boolean' && m[2] === undefined && isBooleanLiteral(args[i + 1])) i++;
- continue;
- }
- return `--${rawKey}`;
- }
- return null;
-}
-
-/**
- * #1475 — the DB-plane merge `connectEngine` performs after connect, published
- * for `makeContext` so the operation context carries it too.
- *
- * Why a map rather than a module-level variable: a process can hold more than
- * one engine (`--brain <mount>` connects a second one), and the host brain's
- * merged config must never be served for a mounted brain's context. Weak so a
- * disconnected engine does not pin its config for the life of the process.
- */
-const MERGED_CONFIG_BY_ENGINE = new WeakMap<BrainEngine, GBrainConfig>();
-const SELECTED_CONFIG_BY_ENGINE = new WeakMap<BrainEngine, GBrainConfig>();
-
-/**
- * Adversarial-review fixup (PR #4186): which BrainEngine instances came from
- * connectMountEngine. Keyed on the engine object itself — same engine-keyed
- * weak-reference pattern as MERGED_CONFIG_BY_ENGINE above (a WeakMap; this is
- * a WeakSet since there's no payload to store, just membership), and for the
- * same reason that comment gives: a process can hold more than one engine,
- * so any guard that decides per-engine behavior must bind to the specific
- * engine instance, not to process-wide module state. (The prior version of
- * this fixup checked a module-level `activeBrainId` variable instead; that
- * drifts from the `engine` argument makeContext actually receives if a
- * process ever holds a host engine and a mount engine at once — the CLI
- * doesn't today, but nothing enforces that.) Weak so a disconnected mount
- * engine does not pin memory.
- */
-const MOUNT_ENGINES = new WeakSet<BrainEngine>();
-
-/**
- * @internal Exported for test/eval-capture-db-plane.test.ts.
- *
- * Publishing the merge is the whole point of the map — if the `set` in
- * connectEngine is ever dropped, makeContext silently falls back to
- * re-merging and every command pays the per-key reads twice with no test
- * going red. The seam lets a test prime the map the way connectEngine does
- * and observe that no further reads happen.
- */
-export const __testing = {
- publishMergedConfig(engine: BrainEngine, config: GBrainConfig): void {
- MERGED_CONFIG_BY_ENGINE.set(engine, config);
- },
- // Test-only seam for the mount-engine guard in makeContext's DB-plane
- // fallback (see the #1475 comment there). Mirrors the MOUNT_ENGINES.add
- // connectMountEngine makes on a real mount connect, without needing a live
- // BrainRegistry.
- markEngineAsMountForTests(engine: BrainEngine): void {
- MOUNT_ENGINES.add(engine);
- },
- // Test-only entry for test/cli-dispatch-lifecycle.serial.test.ts: the real
- // dispatcher, driven in-process with recorded engine lifecycle calls.
- main,
-};
-
-export async function makeContext(engine: BrainEngine, params: Record<string, unknown>, op?: Pick<Operation, 'params'>): Promise<OperationContext> {
- // v0.31.8 (D11): resolve sourceId via the canonical 6-tier chain. Honors
- // --source / GBRAIN_SOURCE / .gbrain-source / path-match / brain default /
- // 'default'. Wrapped in try/catch so a doctor / single-source brain that
- // never set up sources still returns 'default' silently.
- let sourceId: string | undefined;
- // #2561: when the source resolved via a NON-explicit tier (path-match /
- // brain default / sole-non-default / seed default), unqualified search-shaped
- // reads span every `config.federated = true` source. Computed here (the
- // trusted local boundary) and consumed by federatedSearchScope
- // (src/core/ops/context.ts), which widens only an unqualified read with no
- // OAuth grant; remote transports compute the same field for no-grant tokens.
- let localFederated: string[] | undefined;
- let sourceImplicit = true;
- // params.source is set when a CLI flag was parsed for the op (rare; most
- // CLI ops don't take --source). Falls through to env/dotfile/path-match.
- // An op that owns `source` (opOwnsSource) receives it as its own param.
- const explicit = op && opOwnsSource(op) ? null : (params.source as string | undefined) ?? null;
- const { resolveSourceWithTier, localFederatedSourceIds, SourceTargetError } = await import('./core/source-resolver.ts');
- try {
- const resolved = await resolveSourceWithTier(engine, explicit);
- sourceId = resolved.source_id;
- sourceImplicit = resolved.tier !== 'flag' && resolved.tier !== 'env' && resolved.tier !== 'dotfile';
- localFederated = await localFederatedSourceIds(engine, resolved.source_id, resolved.tier);
- } catch (err) {
- // #1712: an EXPLICIT --source that fails to resolve (invalid id, or a
- // source that doesn't exist) must error loudly — the blanket swallow
- // turned `--source __all__` and typos into a silent `default` scope,
- // which is how three bug reports became debugging sessions.
- // Ambient user-selected targets (GBRAIN_SOURCE / .gbrain-source /
- // sources.default) are just as authoritative as --source. Only structural
- // pre-init failures retain the legacy default fallback.
- if (explicit || err instanceof SourceTargetError) throw err;
- // Ambient resolution failed (e.g. sources table doesn't exist on a fresh
- // pre-init brain). Leave sourceId unset; engine read methods fall through
- // to the cross-source view (D16 back-compat path).
- sourceId = undefined;
- }
- // #1475 — the operation context must carry the DB plane, not just file/env.
- // `gbrain config set` writes DB-plane keys and `gbrain config get` reads
- // them back, but every op-side gate reads `ctx.config` — so building this
- // from the sync, file-only `loadConfig()` made those writes inert
- // (`eval.capture` was the reported case: set, echoed back, still off).
- //
- // connectEngine already performs exactly this merge after connect for the
- // HOST brain; it publishes the result, so the normal CLI path costs ZERO
- // additional config reads. The fallback merge below only runs when both
- // (a) the engine was never published (callers that reach makeContext with
- // an engine connectEngine never saw — tests with a stub engine) AND
- // (b) the engine is not a mount engine (MOUNT_ENGINES, set by
- // connectMountEngine). A mounted brain's engine never re-merges here.
- // connectMountEngine's own docstring only promises that a mount's DB-plane
- // model config is never merged into the caller's AI gateway; it says
- // nothing about ctx.config, and this fallback — added for #1475 after that
- // docstring was written — would otherwise happily merge a mount's DB-plane
- // config into the caller's context too, which is the same kind of leak the
- // gateway guarantee exists to prevent (a caller trusting a mount's config
- // as if it were its own). Skipping the merge for mount engines closes that
- // gap and, as a side effect, avoids adding a full per-key DB round-trip to
- // every mounted-brain command (the #3980 cost this whole publish/consume
- // split exists to avoid). Mounted brains keep the same file/env-only
- // config makeContext built before #1475.
- //
- // Fail-open, but not silent. The expected failure — a brain mid-migration
- // whose config table does not exist yet — is already absorbed per key inside
- // loadConfigWithEngine, so anything that escapes to here is unexpected (a
- // contract violation such as a malformed listConfigKeys result). Falling
- // back to the file plane keeps the command usable, but swallowing it without
- // a word would turn "the DB plane silently did nothing" back into a mystery —
- // which is the whole shape of #1475. Warn and continue.
- const fileConfig = loadConfig() || { engine: 'postgres' as const };
- let mergedConfig = MERGED_CONFIG_BY_ENGINE.get(engine) ?? fileConfig;
- if (!MERGED_CONFIG_BY_ENGINE.has(engine) && !MOUNT_ENGINES.has(engine)) {
- try {
- mergedConfig = (await loadConfigWithEngine(engine, fileConfig)) ?? fileConfig;
- } catch (err) {
- console.warn(
- `[config] DB-plane merge failed; using file/env config only. ` +
- `Values set via \`gbrain config set\` will not apply to this command: ` +
- `${(err as Error).message}`,
- );
- mergedConfig = fileConfig;
- }
- }
-
- return {
- engine,
- config: mergedConfig,
- logger: { info: console.log, warn: console.warn, error: console.error },
- dryRun: (params.dry_run as boolean) || false,
- // Local CLI invocation — the user owns the machine; do not apply remote-caller
- // confinement (e.g., cwd-locked file_upload).
- remote: false,
- cliOpts: getCliOptions(),
- writeWaitMs: currentCliWriteWait().waitMs, // #5232
- // v0.34 D4: sourceId is REQUIRED at the type level. Fall back to 'default'
- // when resolveSourceId returned undefined (fresh pre-init brain, no sources
- // table). Matches dispatch.ts's auto-fill so the contract holds across
- // every transport.
- sourceId: sourceId ?? 'default',
- // Brain axis: the id connectEngine resolved for this process. Module
- // state, NEVER params — caller-supplied params.brain must not select a
- // brain (that would be an untrusted-caller cross-brain hole over MCP).
- brainId: activeBrainId,
- ...(localFederated ? { localFederatedSourceIds: localFederated } : {}),
- ...(sourceImplicit ? { localSourceImplicit: true } : {}),
- // T15/FOV-1: capture the retrieval meta for formatResult's empty-result
- // render (the local-engine twin of the MCP _meta.retrieval channel).
- emitResponseMeta: captureRetrievalMeta,
- emitNotice: captureOpNotice, // A6/F8: rendered after the result by applyCliOpNotices
- };
-}
-
-/**
- * T15/FOV-1: the retrieval meta for the CURRENT CLI invocation, captured
- * from either result path — the local engine path via ctx.emitResponseMeta,
- * the thin-client routed path via the envelope's `_meta.retrieval`. Read by
- * formatResult's empty-result branch so `gbrain search`/`query` stop
- * printing a bare "No results." when the pipeline actually degraded.
- * Module state is safe here: one op per CLI process.
- */
-let lastRetrievalMeta: Record<string, unknown> | null = null;
-
-export function captureRetrievalMeta(key: string, value: unknown): void {
- if (key === 'retrieval' && value !== null && typeof value === 'object') {
- lastRetrievalMeta = value as Record<string, unknown>;
- }
-}
-
-// Exported for tests.
-export function resetRetrievalMetaForTests(): void {
- lastRetrievalMeta = null;
-}
-
-/** One-line parenthetical for the empty-result render. '' when no meta. */
-function describeEmptyRetrieval(): string {
- const m = lastRetrievalMeta;
- if (!m) return '';
- const parts: string[] = [];
- if (typeof m.retrieved_count === 'number' && m.retrieved_count > 0) {
- parts.push(`retrieved ${m.retrieved_count} before trimming`);
- }
- // Ranking-only stages (a skipped reranker) never cause a miss — keep the
- // "clean miss" verdict honest.
- const stages = Array.isArray(m.degraded)
- ? [...new Set((m.degraded as Array<{ stage?: string }>).filter(affectsRecall).map(d => d?.stage).filter(Boolean))]
- : [];
- parts.push(stages.length > 0
- ? `degraded: ${stages.join(', ')}`
- : 'clean miss — no retrieval degradation');
- return ` (${parts.join('; ')})`;
-}
-
-// Exported for tests (same import-safety contract as cliAliases/printOpHelp).
-/**
- * #2416: hint-only steering — a concept-shaped `search` gets a one-line
- * stderr nudge toward `query`. Never fires for other ops, never reroutes
- * (search stays the cheap hot path), and honors --quiet — the same silence
- * discipline as the identity banner. Called from BOTH result paths (local
- * engine + thin-client routed); formatResult can't host this because it
- * never sees the query text.
- */
-export function maybePrintConceptNudge(opName: string, params: Record<string, unknown>): void {
- if (opName !== 'search' || getCliOptions().quiet) return;
- const nudge = conceptNudge(String(params.query ?? ''));
- if (nudge) process.stderr.write(nudge + '\n');
-}
-
-/**
- * Characters of `compiled_truth` the human `history` table previews per
- * version row. `--json` returns the untruncated rows.
- */
-const VERSION_TRUTH_PREVIEW_CHARS = 60;
-
-export function formatResult(
- opName: string,
- result: unknown,
- params: Record<string, unknown> = {},
-): string {
- // D2: `--json` on the op lane is the result document for every op. Only
- // search/query render it themselves (retrieval redaction + stderr notice);
- // list/stats/health/tags/timeline used to print their human table instead.
- if (params.json === true && opName !== 'search' && opName !== 'query') {
- return JSON.stringify(result, bigintToStringReplacer, 2) + '\n';
- }
- switch (opName) {
- case 'volunteer_context': {
- const r = result as any;
- // Stats mode (the feedback loop).
- if (r && r.approximate === true && Array.isArray(r.by_arm)) {
- const lines = [
- `volunteered-context precision — last ${r.days} day(s) (${r.note})`,
- `total: ${r.total_volunteered} volunteered, ${r.total_used} used`,
- ];
- for (const a of r.by_arm) {
- lines.push(` ${a.match_arm}/${a.channel}: ${a.used}/${a.volunteered} used (precision ${a.precision})`);
- }
- if (!r.by_arm.length) lines.push(' (no volunteer events in the window)');
- return lines.join('\n') + '\n';
- }
- const pages = (r?.pages ?? []) as any[];
- if (!pages.length) return 'Nothing volunteered (no entity cleared the confidence gate).\n';
- return pages.map((p) => formatVolunteeredPage(p)).join('\n') + '\n';
- }
- case 'get_page': {
- const r = result as any;
- if (r.error === 'ambiguous_slug') {
- return `Ambiguous slug. Did you mean:\n${r.candidates.map((c: string) => ` ${c}`).join('\n')}\n`;
- }
- return serializeMarkdown(r.frontmatter || {}, r.compiled_truth || '', r.timeline || '', {
- type: r.type, title: r.title, tags: r.tags || [],
- });
- }
- case 'list_pages': {
- const pages = result as any[];
- if (pages.length === 0) return 'No pages found.\n';
- const cell = (v: unknown): string => {
- const s = v === null || v === undefined ? '' : String(v);
- return s.replace(/\\/g, '\\\\').replace(/\t/g, '\\t').replace(/\r/g, '\\r').replace(/\n/g, '\\n');
- };
- return pages.map(p =>
- `${cell(p.slug)}\t${cell(p.type)}\t${cell(p.updated_at?.toString().slice(0, 10) || '?')}\t${cell(p.title)}`,
- ).join('\n') + '\n';
- }
- case 'search':
- case 'query': {
- const { results, meta } = redactRetrievalOutput(result as any[], lastRetrievalMeta);
- const incompleteStages = Array.isArray(meta?.degraded)
- ? [...new Set((meta.degraded as Array<{ stage?: string }>).map(d => d.stage)
- .filter(stage => stage === 'vector_candidates_incomplete' || stage === 'projection_pending' || stage === 'projection_status_unknown'))]
- : [];
- const incompleteNotice = incompleteStages.length > 0
- ? `Retrieval incomplete: ${incompleteStages.join(', ')}.\n`
- : '';
- const answerId = typeof meta?.answer_id === 'string' ? meta.answer_id : undefined;
- if (answerId && results.length > 0) process.stderr.write(`answer: ${answerId} (rate with: gbrain rate ${answerId} 1-5)\n`);
- if (params.json === true) {
- if (incompleteNotice) process.stderr.write(incompleteNotice);
- // --explain --json: the same per-row score_details object MCP `explain: true` returns.
- if (getCliOptions().explain) for (const r of results) r.score_details ??= require('./core/search/explain-formatter.ts').buildScoreDetails(r);
- return JSON.stringify(answerId ? results.map(r => ({ ...r, answer_id: answerId })) : results, null, 2) + '\n';
- }
- // T15/FOV-1: an empty result names its cause when the pipeline told us
- // (degradation stages from _meta.retrieval / the local meta capture) —
- // a bare "No results." was indistinguishable from a degraded pipeline.
- if (results.length === 0) return `No results.${describeEmptyRetrieval()}\n`;
- // v0.40.4 — --explain switches to per-stage attribution formatter.
- // Reads CliOptions.explain via the module-level singleton.
- const cliOpts = getCliOptions();
- if (cliOpts.explain) {
- // Lazy import keeps formatResult's startup hot path narrow for
- // the common non-explain case.
- const { formatResultsExplain } = require('./core/search/explain-formatter.ts');
- // v0.48.2: thread the captured retrieval meta so the header lines
- // (autocut decision, `degraded: reranker_skipped (no_key)`) render.
- return formatResultsExplain(results, meta ?? undefined);
- }
- return incompleteNotice + results.map(r =>
- `[${r.score?.toFixed(4) || '?'}] ${r.slug} -- ${r.chunk_text?.slice(0, 100) || ''}${r.stale ? ' (stale)' : ''}`,
- ).join('\n') + '\n';
- }
- case 'get_tags': {
- const tags = result as string[];
- return tags.length > 0 ? tags.join(', ') + '\n' : 'No tags.\n';
- }
- case 'get_stats': {
- const s = result as any;
- const lines = [
- `Pages: ${s.page_count}`,
- `Chunks: ${s.chunk_count}`,
- `Embedded: ${s.embedded_count}`,
- `Links: ${s.link_count}`,
- `Tags: ${s.tag_count}`,
- `Timeline: ${s.timeline_entry_count}`,
- ];
- if (s.pages_by_type) {
- lines.push('', 'By type:');
- for (const [k, v] of Object.entries(s.pages_by_type)) {
- lines.push(` ${k}: ${v}`);
- }
- }
- return lines.join('\n') + '\n';
- }
- case 'get_health': {
- const h = result as any;
- // Health score weights: missing_embeddings is the heaviest (2 pts), other
- // graph quality issues are 1 pt each. link_coverage / timeline_coverage below
- // 50% on entity pages indicates the graph needs population.
- const score = Math.max(0, 10
- - (h.missing_embeddings > 0 ? 2 : 0)
- - (h.stale_pages > 0 ? 1 : 0)
- - (h.orphan_pages > 0 ? 1 : 0)
- - ((h.link_coverage ?? 1) < 0.5 ? 1 : 0)
- - ((h.timeline_coverage ?? 1) < 0.5 ? 1 : 0));
- const lines = [
- `Health score: ${score}/10`,
- `Embed coverage: ${(h.embed_coverage * 100).toFixed(1)}%`,
- `Missing embeddings: ${h.missing_embeddings}`,
- `Stale pages: ${h.stale_pages}`,
- `Orphan pages: ${h.orphan_pages}`,
- ];
- // gbrain#4147: null = below the small-N floor — say so instead of
- // rendering a misleading hard 0%/100%.
- if (h.link_coverage != null) {
- lines.push(`Link coverage (entities): ${(h.link_coverage * 100).toFixed(1)}%`);
- } else if (h.entity_page_count !== undefined) {
- lines.push(`Link coverage (entities): n/a (${h.entity_page_count} entity page(s) — too few to grade)`);
- }
- if (h.timeline_coverage != null) {
- lines.push(`Timeline coverage (entity pages): ${(h.timeline_coverage * 100).toFixed(1)}%`);
- } else if (h.entity_page_count !== undefined) {
- lines.push(`Timeline coverage (entity pages): n/a (${h.entity_page_count} entity page(s) — too few to grade)`);
- }
- if (h.timeline_coverage_score !== undefined) {
- lines.push(`Timeline density (entity and event pages): ${h.timeline_coverage_score}/15 (brain-score component)`);
- }
- if (Array.isArray(h.most_connected) && h.most_connected.length > 0) {
- lines.push('Most connected entities:');
- for (const e of h.most_connected) {
- lines.push(` ${e.slug}: ${e.link_count} links`);
- }
- }
- return lines.join('\n') + '\n';
- }
- case 'get_timeline': {
- const entries = result as any[];
- if (entries.length === 0) return 'No timeline entries.\n';
- return entries.map(e =>
- `${e.date} ${e.summary}${e.source ? ` [${e.source}]` : ''}`,
- ).join('\n') + '\n';
- }
- case 'get_versions': {
- const versions = result as any[];
- if (versions.length === 0) return 'No versions.\n';
- return versions.map(v => {
- // Only elide when something was actually dropped — an unconditional
- // ellipsis renders an 11-char body as `Short body....`.
- const truth = v.compiled_truth ?? '';
- const head = truth.slice(0, VERSION_TRUTH_PREVIEW_CHARS);
- const elided = truth.length > VERSION_TRUTH_PREVIEW_CHARS ? '...' : '';
- return `#${v.id} ${v.snapshot_at?.toString().slice(0, 19) || '?'} ${head}${elided}`;
- }).join('\n') + '\n';
- }
- // MEMORY_VERBS v1 [F-E]: human-readable by default; trailing `--json`
- // escapes to the raw envelope (parseOpArgs ignores an unmatched trailing
- // flag, so the argv probe is safe).
- case 'remember': {
- if (process.argv.includes('--json')) break;
- return formatRememberResult(result as Record<string, any>);
- }
- case 'entity': {
- if (process.argv.includes('--json')) break;
- const r = result as any;
- if (!r.found) {
- const lines = [`No entity found. (${r.latency_ms}ms)${r.coverage && r.coverage.state !== 'complete' ? ` Mention coverage: ${r.coverage.state}, ${r.coverage.pending_pages} page(s) pending.` : ''}`];
- if (Array.isArray(r.suggestions) && r.suggestions.length) {
- lines.push('Did you mean:');
- for (const s of r.suggestions) lines.push(` ${s.slug} — ${s.title} [${s.create_safety}]`);
- }
- return lines.join('\n') + '\n';
- }
- const c = r.card;
- const lines = [`${c.entity.title} (${c.entity.slug})${c.entity.type ? ` [${c.entity.type}]` : ''} (${r.latency_ms}ms)`];
- if (c.summary) lines.push(` ${c.summary}`);
- if (c.aka?.length) lines.push(` aka: ${c.aka.join(', ')}`);
- const lt = c.last_touched || {};
- const touched = lt.updated_at || lt.last_retrieved_at || lt.last_timeline_date;
- if (touched) lines.push(` last touched: ${String(touched).slice(0, 10)}`);
- if (c.open_threads?.length) {
- lines.push(' open threads:');
- for (const t of c.open_threads) lines.push(` [${t.kind}] ${t.text}${t.date ? ` (${String(t.date).slice(0, 10)})` : ''}`);
- }
- if (c.edges?.length) {
- lines.push(' edges:');
- for (const e of c.edges) lines.push(` ${e.direction === 'out' ? '→' : '←'} ${e.type} ${e.slug}`);
- }
- lines.push(` backlinks: ${c.backlink_count} | active facts: ${c.active_fact_count}`);
- if (c.referenced_by_count) lines.push(` referenced by ${c.referenced_by_count} page(s):`, ...c.referenced_by.map((g: any) => ` ${g.canonical_type} (${g.total}): ${g.rows.map((x: any) => x.slug).join(', ')}${g.next ? ', ...' : ''}`));
- if (c.coverage && c.coverage.state !== 'complete') lines.push(` mention coverage: ${c.coverage.state}, ${c.coverage.pending_pages} page(s) pending`);
- if (Array.isArray(r.suggestions) && r.suggestions.length) {
- lines.push(' other matches:');
- for (const s of r.suggestions) lines.push(` ${s.slug} — ${s.title}`);
- }
- return lines.join('\n') + '\n';
- }
- case 'synthesize': {
- if (process.argv.includes('--json')) break;
- const r = result as any;
- const lines = [r.answer || '(no answer)'];
- if (Array.isArray(r.sources) && r.sources.length) lines.push('', `sources: ${r.sources.join(', ')}`);
- if (Array.isArray(r.gaps) && r.gaps.length) lines.push(`gaps: ${r.gaps.join('; ')}`);
- const cost = r.cost || {};
- const tok = cost.input_tokens != null ? `${cost.input_tokens} in / ${cost.output_tokens} out` : 'tokens n/a';
- const usd = cost.usd_estimate != null ? ` (~$${Number(cost.usd_estimate).toFixed(4)})` : '';
- lines.push(`cost: ${cost.model} — ${tok}${usd}`);
- return lines.join('\n') + '\n';
- }
- default:
- // bigintToStringReplacer keeps this fallback renderer crash-proof even
- // if a future caller hands it a not-yet-normalized result. (#2450)
- return JSON.stringify(result, bigintToStringReplacer, 2) + '\n';
- }
- return JSON.stringify(result, null, 2) + '\n';
-}
-
-/**
- * Multi-topology v1: thin-client refusal set. These commands require a local
- * engine; if `~/.gbrain/config.json` has `remote_mcp` set, the dispatch guard
- * refuses them with a canonical error pointing at the remote host. The check
- * runs before per-command dispatch so the error message is consistent.
- *
- * `serve` is in this set because `gbrain serve` (stdio or http) requires a
- * local engine to expose. Thin clients don't have one to expose.
- *
- * `doctor` is intentionally NOT in this set — task 4 routes it to
- * `runRemoteDoctor` for thin-client installs.
- */
-/**
- * v0.31.1 (Issue #734, CDX-5 + cherry-pick A): pinpoint refusal hints for
- * local-only commands when running on a thin-client install. Each hint names
- * the closest path (remote MCP call, host-side workflow) so users aren't
- * stuck guessing what to do next.
- *
- * Source-of-truth lives here so adding a new local-only command means
- * adding both the THIN_CLIENT_REFUSED_COMMANDS member AND the hint in one
- * place during code review.
- */
-const THIN_CLIENT_REFUSE_HINTS: Record<string, string> = {
- call: '`call` dispatches against a local engine. Use the named CLI command or an authorized MCP tool through your agent, or run `gbrain call` on the host.',
- sync: 'sync runs on the host. Use the dedicated `sync_brain` MCP operation, or run `gbrain sync` on the host.',
- embed: 'embed runs on the host. Run `gbrain embed` or `gbrain cycle` on the host machine.',
- embeddings: 'embeddings enable changes the brain host config. Run `gbrain embeddings enable` (or the readiness fix) on the host machine.',
- extract: 'extract runs on the host. Run `gbrain extract` or `gbrain cycle` on the host machine.',
- 'extract-conversation-facts': 'extract-conversation-facts runs on the host (requires local engine + chat gateway). Run on the host machine.',
- enrich: 'enrich runs on the host (requires local engine + chat gateway for grounded synthesis). Run on the host machine.',
- migrate: "migrate runs on the host's local engine. Run on the host machine.",
- 'retrieval-upgrade': "retrieval-upgrade (embedding migration) rebuilds the host brain's schema + re-embeds. Run on the host machine.",
- 'apply-migrations': 'schema migrations run on the host. SSH and run there.',
- 'repair-jsonb': 'repair-jsonb operates on the local DB only.',
- integrity: 'integrity scans local files. Run on the host machine.',
- serve: 'serve starts a server. Run on the host, not the thin client.',
- dream: 'dream runs the autopilot cycle on the host. Run `gbrain dream` on the host machine.',
- orphans: "orphans needs the host's brain. Run on the host or use the `find_orphans` MCP tool from your agent.",
- transcripts: 'transcripts is server-private (raw chat exports stay on the host). Read transcripts on the host machine.',
- storage: 'storage operates on the local repo on disk. Run on the host.',
- takes: 'takes list/search/scorecard/calibration + add/update/resolve/supersede route to the brain host automatically (takes_* MCP ops). This subcommand (extract/revisit) is host-bound: run it on the host machine.',
- sources: 'sources commands manage local DB + config rows. Per-subcommand thin-client routing lands in v0.31.x. For now: use `sources_list` / `sources_status` MCP tools, or run on the host.',
- connectors: 'connectors manage provider session credentials in ~/.gbrain/connectors and sync your chat history on the host. Credentials never cross the wire — run on the host machine.',
- sweep: 'sweep runs the serve-resident maintenance passes against the LOCAL engine. Run it on the host (the serve process also runs it automatically).',
- 'compile-context': 'compile-context compiles from the local brain; run it on the host install.',
- decide: '`gbrain decide` runs on the brain host; run it there.',
- facts: '`gbrain facts relink` runs on the brain host (it writes the entity pages there): run `gbrain facts relink --source <id> --dry-run` on that machine.',
- // v0.32 audit additions
- pages: '`pages purge-deleted` is admin+localOnly (hard-deletes from the local DB). Run on the host.',
- files: '`files list` and `files url` MCP ops are localOnly (paths live on the host filesystem). Use `gbrain files` on the host machine.',
- eval: '`eval` export/prune/replay touch the local engine and have no MCP equivalents. Run `gbrain eval` on the host.',
- 'code-def': '`code-def` needs symbol-aware lookup that has no MCP op yet. Run on the host or use `search` from your agent with a symbol-shaped query.',
- 'code-refs': '`code-refs` has no MCP op yet. Run on the host.',
- 'code-callers': '`code-callers` has no MCP op yet. Run on the host.',
- 'code-callees': '`code-callees` has no MCP op yet. Run on the host.',
- // scratch-DB audit additions
- pricing: "pricing registers model prices in the host brain's config and is trusted-local only (a remote caller could void a cost cap). Ask the brain's operator to run `gbrain pricing set <model> ...` on the host.",
- config: "config reads/writes the host brain's config plane. Edit the host's .gbrain/config.json (file-plane keys) or run on the host with GBRAIN_HOME set. self_upgrade.* keys are machine-local and work here.",
- jobs: '`jobs list`, `jobs get <id>`, and `jobs stats` are thin-client routable; this subcommand runs against the host queue. Use the submit_job / list_jobs / get_job / get_job_stats MCP tools from your agent, or run on the host with GBRAIN_HOME set.',
- // Gap-closure wave [OV6]: routable subcommands are intercepted before this
- // hint fires — these fire only for the host-bound remainder.
- search: '`search modes|stats|tune` route to the brain host automatically (search_modes / search_stats / search_tune MCP ops). The modes reset form, modes with the source flag (the reset dry-run), and tune apply mutate or preview host config, and `diagnose` runs live retrieval — run those on the host.',
- cache: '`cache stats` routes to the brain host automatically (cache_stats MCP op). clear/prune mutate the host cache — run those on the host.',
- repair: 'repair runs on the brain host (it publishes coordinated page writes against the local engine). Run `gbrain repair` on the brain host.',
- projections: 'projections drain rebuilds text projections against the local engine. Run `gbrain projections drain` on the brain host.',
- quarantine: '`quarantine list` routes to the brain host automatically (quarantine_list MCP op). scan/clear are host-bound (bulk re-import; the clear trust decision) — run those on the host.',
- advisor: 'advisor ranks next actions from the host brain. Use the `advisor` MCP tool from your agent (when the host publishes it), or run `gbrain advisor` on the host.',
- export: 'export dumps the host brain to disk and has no MCP equivalent. Run `gbrain export` on the host, or read pages with the `get_page` MCP tool.',
- recall: '`recall --query`/`--budget-tokens` without `--budget-policy` runs the recall op locally. Add `--budget-policy facts_first` to send it to the brain host (`recall` MCP op).',
-};
-
-/**
- * v0.31.1: emit a pinpoint refusal hint for a thin-client-incompatible
- * command and exit 1. Falls back to the canonical generic message when no
- * specific hint is registered (defensive — every member of
- * THIN_CLIENT_REFUSED_COMMANDS should have a hint).
- */
-function refuseThinClient(command: string, mcpUrl: string): never {
- const hint = THIN_CLIENT_REFUSE_HINTS[command];
- const message = hint
- ? `\`gbrain ${command}\` is not routable (thin-client of ${mcpUrl}); run it on the brain host.`
- : `\`gbrain ${command}\` requires a local engine. This install is a thin client of ${mcpUrl}.`;
- exitCliError(opError('requires_local_engine', message,
- hint ?? `Run \`${command}\` on the remote host, or use the corresponding MCP tool from your agent.`, {
- ...(hint ? { why: hint } : {}),
- fix: { argv: ['gbrain', command, ...thinRefusalSubcommand(command)], consent: [], actor: 'host_admin', requires_exclusive: false,
- why: 'The brain database lives on the brain host; this machine only forwards MCP calls.' },
- }), command);
-}
-
-/** The refused invocation's subcommand word (id-shaped only, per A1 argv safety), for the host-side fix. */
-function thinRefusalSubcommand(command: string): string[] {
- const argv = process.argv.slice(2);
- const next = argv[argv.indexOf(command) + 1] ?? '';
- return argv.includes(command) && /^[a-z][a-z0-9-]*$/.test(next) ? [next] : [];
-}
-
-const THIN_CLIENT_BRAIN_FLAG_MESSAGE = '--brain is not supported on a thin-client install: the remote server is a single brain.';
-
-const ENGINE_CONNECT_HOOKS: EngineConnectHooks = { SELECTED_CONFIG_BY_ENGINE, completeStartup: completeEngineStartup };
-/** Dispatcher-owned pieces the command modules under src/cli/commands/ receive (see CliDispatchContext). */
-const CLI_DISPATCH_CONTEXT: CliDispatchContext = {
- connectEngine,
- completeStartup: completeEngineStartup,
- dbMarkerBrainId,
- SELECTED_CONFIG_BY_ENGINE,
- cliModuleUrl: import.meta.url,
- makeContext,
-};
-
-/**
- * Table step before the connectEngine() terminator: run a pre-connect record
- * (engine-free, or opening its own engine). Returns false for post-connect
- * records and for records an explicit pipeline step dispatches.
- */
-async function dispatchPreConnectCommand(command: string, args: string[]): Promise<boolean> {
- const record = findCliCommand(command);
- if (!record || record.phase === 'post-connect' || record.dispatchedBy) return false;
- await (await record.load()).run(args, CLI_DISPATCH_CONTEXT);
- return true;
-}
-
-/** Table step after the connectEngine() terminator: run a post-connect record with the connected engine. */
-async function dispatchConnectedCommand(command: string, engine: BrainEngine, args: string[]): Promise<void> {
- const record = findCliCommand(command);
- if (record?.phase !== 'post-connect') return;
- await (await record.load()).run(engine, args, CLI_DISPATCH_CONTEXT);
-}
-/**
- * CLI-only dispatch: the explicit ordered pipeline (refactor wave 1, W4 cli).
- * The command table (src/cli/command-table.ts) supplies each command's
- * module; everything that depends on arguments, config or install shape
- * stays explicit and in master's order:
- *
- * 1. thin-client guard, deferred-persistence routing, `agent register` guards
- * 2. table step: pre-connect records (engine-free or own-engine)
- * 3. engine-free subcommand routes, then engine-free `--help` routes
- * 4. read-only connect+dispatch timeout path (`sources list`)
- * 5. connected-dispatch preparation (sync watchdog, serve delegation, thin-client routes)
- * 6. connectEngine() terminator with degraded-serve recovery
- * 7. table step: post-connect records, then teardown/drain (never for `serve`)
- *
- * Functions tagged `@cliPipelineStage` are inlined in this order by the
- * dispatch-shape golden (test/helpers/cli-dispatch-extract.ts) and the flag
- * registry generator (scripts/generate-flag-registry.ts); keep new stages
- * tagged and called from here.
- */
-async function handleCliOnly(command: string, args: string[]) {
- if (await routeCliOnlyBeforeTable(command, args)) return;
- if (await dispatchPreConnectCommand(command, args)) return;
- if (await routeEngineFreeSubcommands(command, args)) return;
- if (await routeEngineFreeHelp(command, args)) return;
- if (await runReadOnlyTimeoutDispatch(command, args)) return;
- const prepared = await prepareConnectedDispatch(command, args);
- if (!prepared) return;
- const engine = await connectCliOnlyEngine(command, prepared.args);
- if (!engine) return;
- try {
- await dispatchConnectedCommand(command, engine, prepared.args);
- } finally {
- prepared.syncWatchdog?.dispose(); // #1633: tear down the hard-deadline watchdog on clean exit
- // #2084 — the CLI_ONLY fall-through teardown (drain every background-work
- // sink, THEN disconnect, under a computed-deadline backstop) lives in
- // finishCliTeardown. `gbrain capture`'s fire-and-forget facts:absorb job
- // gets its drain window before PGLite's db.close() can race it into the
- // re-pump busy-loop (#1762). #1471: this is also the fall-through
- // OWNER-disconnect — the owner is torn down LAST (after the drain), so
- // module-singleton borrowers never outlive it. `serve` skips teardown
- // entirely: the daemon owns its lifecycle.
- if (command !== 'serve') {
- await finishCliTeardown({ engine });
- }
- }
-}
-
-/**
- * Pipeline stage 1: thin-client guard, deferred-persistence routing and the
- * `agent register` pre-connect guards. Returns true when the command was handled.
- * @cliPipelineStage
- */
-async function routeCliOnlyBeforeTable(command: string, args: string[]): Promise<boolean> {
- // Thin-client guard: refuse DB-bound commands cleanly with a pinpoint
- // hint instead of letting them fail later inside connectEngine or
- // mid-handler. v0.31.1 routes through `refuseThinClient` so every
- // refusal carries an actionable next-step hint (CDX-5 cherry-pick A).
- // Gap-closure wave [OV6]: takes/cache/quarantine first try the
- // per-subcommand MCP routing (engine-free); unhandled subcommands fall
- // through to the refusal.
- if (THIN_CLIENT_REFUSED_COMMANDS.has(command) || command === 'cache' || command === 'quarantine') {
- const cfg = loadConfig();
- if (isThinClient(cfg)) {
- const { routeThinClientCommand } = await import('./commands/thin-client-routing.ts');
- if (await routeThinClientCommand(cfg!, command, args)) return true;
- refuseThinClient(command, cfg!.remote_mcp!.mcp_url);
- }
- }
-
- // Local deferred connections must not bypass the remote installation route.
- if (command === 'capture' || command === 'forget' || command === 'call' || command === 'sources' && ['writer', 'reconcile', 'add', 'remove', 'archive', 'restore', 'purge', 'set-path', 'reclone'].includes(args[0]) || command === 'takes' && ['add', 'update', 'supersede', 'resolve', 'remove', 'rebuild'].includes(args[0]) && !hasHelpFlag(args)) {
- const { runDeferredPersistenceCommand } = await import('./commands/persistence-delegate.ts');
- await runDeferredPersistenceCommand(command, args, connectEngine);
- return true;
- }
-
- // `transcripts recent` reads through a live PGLite serve that owns the brain.
- if (command === 'transcripts' && args[0] === 'recent' && !hasHelpFlag(args)
- && await (await import('./commands/transcripts.ts')).runDelegatedTranscriptsRecent(args.slice(1))) return true;
-
- // cathedral-6: `agent register` guards run PRE-connectEngine. A thin client
- // would otherwise build a scratch PGLite and mint dead credentials into it;
- // a live PGLite serve holds the single-writer lock, so connectEngine would
- // hang ~30s before any handler code could print guidance. (`agent` itself
- // stays out of THIN_CLIENT_REFUSED_COMMANDS — run/logs work elsewhere.)
- if (command === 'agent' && args[0] === 'register' && !hasHelpFlag(args)) {
- const cfg = loadConfig();
- const wantsJson = args.includes('--json');
- const refuse = (reason: string, message: string) => {
- if (wantsJson) {
- console.log(JSON.stringify({ ok: false, reason, message }));
- } else {
- console.error(`Error: ${message}`);
- }
- process.exit(1);
- };
- if (isThinClient(cfg)) {
- // Shared verbatim with the in-handler belt-and-braces re-check. Lazy
- // import: this guard runs pre-connect for `agent register` only, and a
- // top-level import would eager-load the register module on every CLI
- // start.
- const { THIN_CLIENT_REGISTER_MESSAGE } = await import('./commands/agent-register.ts');
- refuse('thin_client', THIN_CLIENT_REGISTER_MESSAGE);
- }
- if (cfg && !cfg.database_url && cfg.database_path) {
- const { probeLivePgliteHolder } = await import('./core/bootstrap/uninstall.ts');
- const holder = probeLivePgliteHolder(cfg.database_path);
- if (holder?.serve) {
- refuse('pglite_live_serve',
- `a live \`gbrain serve\` (pid ${holder.pid}) holds this PGLite brain's single-writer lock — stop the serve, run \`gbrain agent register\` again, then restart it. (Postgres brains register fine while the serve runs.)`);
- }
- }
- }
- return false;
-}
-
-/**
- * Pipeline stage 3a: engine-free subcommand routes (config / mcp pre-steps,
- * `eval <sub>` no-DB bypasses, thin-client `status` / `eval whoknows`).
- * @cliPipelineStage
- */
-async function routeEngineFreeSubcommands(command: string, args: string[]): Promise<boolean> {
- // db-availability loop (5c): the DB-connection config keys must be settable
- // with the DB DOWN — "fix your URL with config set database_url" is circular
- // if config needs the broken engine first. Other config keys fall through
- // to the engine path below unchanged.
- if (command === 'config') {
- const { tryRunConfigEngineFree } = await import('./commands/config.ts');
- if (await tryRunConfigEngineFree(args)) return true;
- }
- // Engine graduation owns its connections (routing rules: commands/migrate-graduation.ts routesToGraduation).
- if (command === 'migrate' && await (await import('./commands/migrate-graduation.ts')).tryRunMigrateGraduation(args)) return true;
- if (command === 'mcp') {
- const { runMcp, mcpNeedsEngine } = await import('./commands/mcp.ts');
- if (!mcpNeedsEngine(args)) { await runMcp(args); return true; }
- const cfg = loadConfig();
- if (isThinClient(cfg)) {
- console.log(JSON.stringify({ status: 'error', reason: 'host_administration_required', message: 'Provision on the brain host, or use --admin-token-file to authenticate to its running server.' }));
- setCliExitVerdict(1);
- return true;
- }
- if (cfg?.database_path && !cfg.database_url) {
- const { probeLivePgliteHolder } = await import('./core/bootstrap/uninstall.ts');
- if (probeLivePgliteHolder(cfg.database_path)?.serve) {
- console.log(JSON.stringify({ status: 'error', reason: 'pglite_live_serve', message: 'Use --admin-token-file with this running server’s admin credential; the command will provision through its existing engine.' }));
- setCliExitVerdict(1);
- return true;
- }
- }
- }
- if (command === 'sweep' && (args.includes('--help') || args.includes('-h'))) {
- // SWEEP_HELP is engine-independent and must print on a fresh install
- // (the sync/capture/enrich pre-engine-bind precedent). runSweep's --help
- // path returns before touching the engine argument.
- const { runSweep } = await import('./commands/sweep.ts');
- await runSweep(null as never, args);
- return true;
- }
- // Unreachable: the table step already ran `auth`. Master carried this
- // second `auth` branch too; it is kept so the W0 dispatch-shape golden
- // (branchesAfterTerminatingBranch) stays byte-identical. Removing it is a
- // deliberate golden regeneration, not part of refactor wave 1.
- if (command === 'auth') {
- const { runAuth } = await import('./commands/auth.ts');
- await runAuth(args);
- return true;
- }
-
- // `eval cross-modal` is a pure API-call command — no DB, no brain. Bypass
- // connectEngine entirely so first-run users (no `gbrain init` yet) can
- // run the quality gate. Mirrors the dream/doctor no-DB pattern but
- // doesn't even attempt the connect (T3=A in plans/radiant-napping-lerdorf.md).
- // The handler self-configures the AI gateway from loadConfig() + process.env.
- if (command === 'eval' && args[0] === 'cross-modal') {
- const { runEvalCrossModal } = await import('./commands/eval-cross-modal.ts');
- setCliExitVerdict(await runEvalCrossModal(args.slice(1)));
- return true;
- }
-
- // `eval run-all` is a pure orchestrator — its engine arg is unused
- // (`_engine`) and the brainbench suite it runs in-process is hermetic (brings
- // its own PGLite via createBenchmarkBrain). Bypass connectEngine so run-all
- // works with no brain configured — e.g. in CI. It returns its exit code
- // (1 when a suite failed).
- if (command === 'eval' && args[0] === 'run-all') {
- const { runEvalRunAll } = await import('./commands/eval-run-all.ts');
- setCliExitVerdict(await runEvalRunAll(null, args.slice(1)));
- return true;
- }
-
- // v0.32 EXP-5 (codex review #10): `eval takes-quality replay <receipt>`
- // is the ONLY sub-subcommand that doesn't need a brain — it reads a
- // receipt JSON file from disk and re-renders it. Bypass connectEngine
- // here so users can replay a receipt on a machine without DATABASE_URL.
- // run/trend/regress need the brain and fall through to the regular
- // engine-required path below.
- if (command === 'eval' && args[0] === 'takes-quality' && args[1] === 'replay') {
- const { runReplayNoBrain } = await import('./commands/eval-takes-quality.ts');
- setCliExitVerdict(await runReplayNoBrain(args.slice(2)));
- return true;
- }
-
- // BrainBench brings its own in-memory PGLite (longmemeval pattern) and is
- // hermetic by default — no gateway, no user brain, no config required. The
- // command owns its exit codes (0 pass / 1 regression / 2 error) and exits
- // explicitly via its grace-tick exit path (PGLite exitCode-hijack guard).
- if (command === 'eval' && args[0] === 'brainbench') {
- const { runEvalBrainBench } = await import('./commands/eval-brainbench.ts');
- if ((args.includes('--llm') || args.some((a) => a === '--decide' || a.startsWith('--decide='))) && !args.includes('--help') && !args.includes('-h')) {
- // --llm and --decide arms talk to a provider; mirror the longmemeval
- // gateway bootstrap so extraction and decide calls are keyed and priced.
- const config = loadConfig() ?? ({} as GBrainConfig);
- const { configureGateway } = await import('./core/ai/gateway.ts');
- configureGateway(buildGatewayConfig(config));
- }
- await runEvalBrainBench(args.slice(1));
- return true; // unreachable — runEvalBrainBench always exits — but keeps control flow explicit
- }
-
- // v0.28.8: longmemeval brings its own in-memory PGLite. Bypassing
- // connectEngine here keeps `gbrain eval longmemeval --help` and benchmark
- // runs working on machines that have no `~/.gbrain/config.json` configured.
- //
- // The in-memory brain's import + hybridSearch still embed through the
- // configured provider, so the shared eval gateway bootstrap runs first.
- if (command === 'eval' && args[0] === 'longmemeval') {
- const { runEvalLongMemEval } = await import('./commands/eval-longmemeval.ts');
- if (!(args.length > 1 && (args[1] === '--help' || args[1] === '-h'))) {
- const { configureEvalGateway } = await import('./eval/shared/gateway-bootstrap.ts');
- configureEvalGateway();
- }
- await runEvalLongMemEval(args.slice(1));
- return true;
- }
-
- // v0.42.x (#2390): `gbrain eval chronicle` is deterministic — brings its own
- // in-memory PGLite, no DB/gateway. CI fixture gate runs anywhere.
- if (command === 'eval' && args[0] === 'chronicle') {
- const { runEvalChronicle } = await import('./commands/eval-chronicle.ts');
- setCliExitVerdict(await runEvalChronicle(args.slice(1)));
- return true;
- }
-
- // #4198: `gbrain eval synthesize-concepts` gets a dedicated branch (mirror
- // of the chronicle branch above) so the generic qrels eval can't recapture
- // it — pre-fix it fell through to "Error: --qrels <path|json> is required".
- // The scaffold needs no DB and exits nonzero with an honest
- // {ok:false, status:'not_implemented'} envelope until the real evaluator
- // lands.
- if (command === 'eval' && args[0] === 'synthesize-concepts') {
- const { runEvalSynthesizeConceptsCli } = await import('./commands/eval-synthesize-concepts.ts');
- setCliExitVerdict(await runEvalSynthesizeConceptsCli(args.slice(1)));
- return true;
- }
-
- // v0.41.13.0: `gbrain eval conversation-parser` is pure-function
- // (parses fixture JSONL, runs parseConversation, scores results).
- // No DB access; bypass connectEngine entirely so the CI fixture
- // gate runs on machines with no `~/.gbrain/config.json`.
- if (command === 'eval' && args[0] === 'conversation-parser') {
- const { runEvalConversationParser } = await import('./commands/eval-conversation-parser.ts');
- setCliExitVerdict(await runEvalConversationParser(args.slice(1)));
- return true;
- }
-
- // v0.41.13.0: `gbrain conversation-parser list-builtins | validate
- // | --help` are pure (no DB access). Bypass connectEngine so the
- // operator can run them on machines with no brain configured.
- // `scan <slug>` needs a brain and falls through.
- if (
- command === 'conversation-parser' &&
- (args.length === 0 ||
- args[0] === '--help' ||
- args[0] === '-h' ||
- args[0] === 'list-builtins' ||
- args[0] === 'validate')
- ) {
- const { runConversationParser } = await import('./commands/conversation-parser.ts');
- await runConversationParser(null, args);
- return true;
- }
-
- // v0.33.1.3: `gbrain eval whoknows` on thin-client installs bypasses
- // connectEngine entirely — the eval routes per-query through the remote
- // `find_experts` MCP op (the v0.31.1 routing seam). Local mode falls
- // through to the engine-connected path below.
- if (command === 'eval' && args[0] === 'whoknows') {
- const cfgPre = loadConfig();
- if (isThinClient(cfgPre)) {
- const { runEvalWhoknows } = await import('./commands/eval-whoknows.ts');
- setCliExitVerdict(await runEvalWhoknows(null, args.slice(1)));
- return true;
- }
- }
-
- // v0.41.19.0: `gbrain status` on thin-client installs bypasses connectEngine
- // entirely — Sync + Cycle route through the `get_status_snapshot` MCP op,
- // and local-only sections render as "N/A on remote brain". Local mode falls
- // through to the engine-connected dispatch path below. (`args` here is the
- // subArgs slice already — no need to re-slice past the command.)
- if (command === 'status') {
- const cfgPre = loadConfig();
- if (cfgPre && isThinClient(cfgPre)) {
- const { runStatus } = await import('./commands/status.ts');
- const result = await runStatus(null, args);
- setCliExitVerdict(result.exitCode);
- return true;
- }
- }
- return false;
-}
-
-/**
- * Pipeline stage 3b: engine-free `--help` for self-help commands whose
- * handler needs an engine for everything else.
- * @cliPipelineStage
- */
-async function routeEngineFreeHelp(command: string, args: string[]): Promise<boolean> {
- // v0.37 fix wave (Lane D.4 + CDX2-12): short-circuit `gbrain sync --help`
- // BEFORE the engine bind. runSync has its own --help branch but can't
- // reach it without an engine — which means a user running `--help` from
- // a fresh tmpdir with no config gets a no-such-config error instead of
- // help text. Importing runSync without the engine + passing null works
- // because runSync's --help path doesn't touch the engine argument.
- if (command === 'sync' && (args.includes('--help') || args.includes('-h'))) {
- const { runSync } = await import('./commands/sync.ts');
- await runSync(null as any, args);
- return true;
- }
-
- // #3834: extract help is engine-independent and must work on a fresh
- // install before a brain has been configured.
- if (command === 'extract' && (args.includes('--help') || args.includes('-h'))) {
- const { runExtract } = await import('./commands/extract.ts');
- await runExtract(null as never, args);
- return true;
- }
-
- // v0.39.3.0 WARN-5: same pattern for `capture --help`. CLI_ONLY_SELF_HELP
- // now includes 'capture' so the generic short-circuit at :101 stays out
- // of the way, but the dispatch case at :1229 still needs an engine. The
- // pre-engine-bind branch here exposes the HELP constant without requiring
- // a configured brain (fresh-tmpdir parity with brainstorm/lsd/sync).
- if (command === 'capture' && (args.includes('--help') || args.includes('-h'))) {
- const { runCapture } = await import('./commands/capture.ts');
- await runCapture(null, args);
- return true;
- }
-
- // v0.41.39 (#1700): same pattern for `enrich --help`. enrich is in
- // CLI_ONLY_SELF_HELP so the generic stub stays out of the way; this
- // pre-engine-bind branch exposes the HELP constant without a configured
- // brain. runEnrich's --help path returns before touching the engine.
- if (command === 'enrich' && (args.includes('--help') || args.includes('-h'))) {
- const { runEnrich } = await import('./commands/enrich.ts');
- await runEnrich(null as never, args);
- return true;
- }
-
- // Same pattern for `takes --help`. 'takes' is now in CLI_ONLY_SELF_HELP so
- // the generic stub stays out of the way; this pre-engine-bind branch exposes
- // the subcommand usage block without a configured brain. runTakes' help path
- // returns before touching the engine.
- if (command === 'takes' && (args.includes('--help') || args.includes('-h'))) {
- const { runTakes } = await import('./commands/takes.ts');
- await runTakes(null as never, args);
- return true;
- }
-
- // #3686 (the #578 residue): `eval --help` reaches eval.ts's printHelp
- // engine-free. Placed AFTER the sub-owned no-DB routes above (brainbench /
- // longmemeval / run-all / cross-modal / chronicle / conversation-parser /
- // takes-quality replay / whoknows) so each sub's own usage keeps winning;
- // every remaining `eval … --help` form prints the full subcommand usage
- // instead of the old one-line stub (or a "No brain configured" error).
- // D-N1: a named subcommand (`eval replay --help`) gets its own usage. The
- // sub always sees `--help` as its first argument, the form every sub's
- // usage branch answers before it touches the engine.
- if (command === 'eval' && (args.includes('--help') || args.includes('-h'))) {
- const sub = args[0] !== undefined && !args[0].startsWith('-') ? args[0] : undefined;
- const { run } = await import('./cli/commands/eval.ts');
- await run(null as never, sub ? [sub, '--help'] : ['--help']);
- return true;
- }
-
- // #3686: `storage --help` — runStorage's help guard returns before the
- // engine argument is touched.
- if (command === 'storage' && (args.includes('--help') || args.includes('-h'))) {
- const { runStorage } = await import('./commands/storage.ts');
- await runStorage(null as never, args);
- return true;
- }
-
- // #3686: `reindex --help` — the usage block (incl. the --multimodal flags
- // the dispatcher parses) lives in reindex.ts; printing it needs no engine.
- if (command === 'reindex' && (args.includes('--help') || args.includes('-h'))) {
- const { printReindexHelp } = await import('./commands/reindex.ts');
- printReindexHelp();
- return true;
- }
- return false;
-}
-
-/**
- * Pipeline stage 4: the read-only connect+dispatch timeout path.
- * @cliPipelineStage
- */
-async function runReadOnlyTimeoutDispatch(command: string, args: string[]): Promise<boolean> {
- // v0.41.6.0 D3 (per outside-voice F1): connect-time + dispatch-time wallclock
- // timeouts for read-only commands whose hang would otherwise spin at 100% CPU
- // (the production "10-day zombie gbrain search ping" bug class). The wrap
- // covers connectEngine (so a hung schema probe / PgBouncer freeze actually
- // surfaces a timeout) AND the dispatch body (so a wedged runSearch /
- // runList honors the same deadline).
- // Per-command default: search 30s, sources list 10s. User --timeout=Ns wins.
- // Other commands (import, embed, doctor, etc.) keep their existing
- // unbounded connect — destructive / long-running commands shouldn't get
- // a default kill switch. The gate below is per-command (#3013): only the
- // commands dispatchReadOnlyCommand handles may enter this path — a
- // user-supplied --timeout on a write command must never reroute it here.
- const cliOptsResolved = getCliOptions();
- const userTimeoutMs = cliOptsResolved.timeoutMs;
- const readOnlyTimeoutMs = resolveReadOnlyDispatchTimeoutMs(command, args, userTimeoutMs);
-
- if (readOnlyTimeoutMs !== null) {
- const { withTimeout, OperationTimeoutError } = await import('./core/timeout.ts');
- const label = `gbrain ${command}`;
- let engine: BrainEngine;
- try {
- engine = await withTimeout(connectEngine(), readOnlyTimeoutMs, `${label}: connect`);
- } catch (e) {
- if (e instanceof OperationTimeoutError) {
- const hint = userTimeoutMs ? '' : ` (default ${e.ms}ms; pass --timeout=Ns to override)`;
- console.error(`${e.label} timed out${hint}.`);
- process.exit(124);
- }
- throw e;
- }
- try {
- await withTimeout(dispatchReadOnlyCommand(engine, command, args), readOnlyTimeoutMs, label);
- } catch (e) {
- if (e instanceof OperationTimeoutError) {
- const hint = userTimeoutMs ? '' : ` (default ${e.ms}ms; pass --timeout=Ns to override)`;
- console.error(`${e.label} timed out${hint}.`);
- process.exit(124);
- }
- throw e;
- } finally {
- await finishCliTeardown({ engine });
- }
- return true;
- }
- return false;
-}
-
-interface ConnectedDispatchPlan {
- /** Arguments the post-connect record receives (autopilot resolves positionals here). */
- args: string[];
- /** #1633 sync hard-deadline watchdog, disposed after the post-connect record returns. */
- syncWatchdog: { dispose(): void } | null;
-}
-
-/**
- * Pipeline stage 5: work that must happen before connectEngine() for the
- * remaining commands (sync watchdog, serve/persistence delegation, thin-client
- * routes). Returns null when the command was handled.
- * @cliPipelineStage
- */
-async function prepareConnectedDispatch(command: string, args: string[]): Promise<ConnectedDispatchPlan | null> {
- // #1633: out-of-band hard-deadline watchdog for `gbrain sync`. Installed
- // BEFORE connectEngine so a connect-phase hang (the reported zombie class) is
- // bounded too. A Bun Worker on its own OS thread SIGKILLs the process at the
- // deadline even when the main event loop is starved by a synchronous spin —
- // the only thing that stops the cron orphan-pileup. Disposed in the finally.
- let syncWatchdog: { dispose(): void } | null = null;
- // #6340: `sync status` / `sync unblock` read and schedule on the brain's own engine: no watchdog, no serve delegation (a delegate would refuse the subcommand).
- const syncOperator = command === 'sync' && (args[0] === 'status' || args[0] === 'unblock');
- if (command === 'sync' && !syncOperator) {
- try {
- const { resolveSyncHardDeadline } = await import('./commands/sync.ts');
- const res = resolveSyncHardDeadline(args, {
- isTty: Boolean(process.stdout.isTTY),
- env: process.env,
- });
- if (res) {
- const { installProcessWatchdog } = await import('./core/process-watchdog.ts');
- const { syncWatchdogPlan } = await import('./core/sync-reconcile.ts');
- const plan = syncWatchdogPlan(args, res);
- syncWatchdog = installProcessWatchdog(plan.watchdog);
- (await import('./core/forward-progress.ts')).registerRunDeadline({ atMs: Date.now() + res.deadlineMs, strict: !res.progressWindowMs });
- process.stderr.write(plan.armedLine);
- }
- } catch (e) {
- // A bad --hard-deadline value throws here (same posture as --timeout).
- exitCliError(usageError(e instanceof Error ? e.message : String(e), 'Pass --hard-deadline a duration such as 30m or 2h.'), command);
- }
- }
-
- // Serve-delegated sync preflight (PGLite host brains only): a live `gbrain
- // serve` owns the single-writer lock, so connectEngine below would throw
- // LiveServeLockError — instead the sync runs INSIDE the serve over its IPC
- // socket (commands/sync-delegate.ts). Handled === delegated or politely
- // refused (exit verdict set inside); false falls through unchanged.
- if (command === 'sync' && !syncOperator) {
- const cfgSync = loadConfig();
- if (await (await import('./commands/sync-persistence-delegate.ts')).maybeDelegateSyncToPersistence(cfgSync, args)) return null;
- if (cfgSync?.engine === 'pglite' && cfgSync.database_path && !cfgSync.database_url) {
- const { maybeDelegateSyncToServe } = await import('./commands/sync-delegate.ts');
- if (await maybeDelegateSyncToServe(cfgSync.database_path, args)) return null;
- }
- }
-
- if (command === 'sources' && args[0] === 'refresh' && !hasHelpFlag(args) && await (await import('./commands/sources-refresh-delegate.ts')).maybeDelegateSourcesRefresh(loadConfig(), args.slice(1))) return null;
- if (command === 'reindex-code') {
- if (await (await import('./commands/reindex-code-delegate.ts')).maybeDelegateReindexCode(loadConfig(), args)) return null;
- }
- if (command === 'extract' && args.includes('--stale') && !hasHelpFlag(args) && await (await import('./commands/extract-stale-delegate.ts')).maybeDelegateExtractStale(loadConfig(), args)) return null;
-
- if (command === 'embed' && args.includes('--facts')) {
- if (await (await import('./commands/embed-facts-delegate.ts')).maybeDelegateFactEmbed(loadConfig(), args)) return null;
- }
-
- // Serve-delegated sweep preflight (#677) — same shape as sync above: a live
- // `gbrain serve` owns the PGLite single-writer lock, so `sweep --once` used
- // to exit 1 with LiveServeLockError. The lock owner runs the sweep over its
- // IPC socket instead (commands/sweep-delegate.ts).
- if (command === 'sweep') {
- const cfgSweep = loadConfig();
- if (cfgSweep?.engine === 'pglite' && cfgSweep.database_path && !cfgSweep.database_url) {
- const { maybeDelegateSweepToServe } = await import('./commands/sweep-delegate.ts');
- if (await maybeDelegateSweepToServe(cfgSweep.database_path, args)) return null;
- }
- }
-
- // Thin-client `jobs` dispatch: `list` and `get` route over MCP (v0.32
- // routing branches in commands/jobs.ts) and never touch a local engine —
- // but falling through to connectEngine() below fabricates an empty
- // scratch PGLite in the thin-client GBRAIN_HOME and replays the entire
- // migration chain on every invocation before the remote call even runs.
- // Dispatch them engine-free here; every other jobs subcommand is
- // host-queue-bound, so refuse with a pinpoint hint instead of building
- // the scratch store.
- if (command === 'jobs') {
- const cfgJobs = loadConfig();
- if (isThinClient(cfgJobs)) {
- const jobsSub = args[0];
- if (jobsSub === 'list' || jobsSub === 'get') {
- const { runJobs } = await import('./commands/jobs.ts');
- await runJobs(null, args);
- return null;
- }
- if (jobsSub === 'stats') {
- // Gap-closure wave [OV6]: queue health routes via get_job_stats.
- const { routeThinClientCommand } = await import('./commands/thin-client-routing.ts');
- if (await routeThinClientCommand(cfgJobs!, 'jobs', args)) return null;
- }
- refuseThinClient('jobs', cfgJobs!.remote_mcp!.mcp_url);
- }
- if (args[0] === 'supervisor' && args[1] === 'status') {
- const { DEFAULT_PID_FILE } = await import('./core/minions/supervisor.ts');
- const { readSupervisorPid } = await import('./core/minions/supervisor-pid.ts');
- const pidFileIndex = args.indexOf('--pid-file');
- const pidFile = pidFileIndex >= 0 ? args[pidFileIndex + 1] ?? DEFAULT_PID_FILE : DEFAULT_PID_FILE;
- if (readSupervisorPid(pidFile).running) {
- const { runJobs } = await import('./commands/jobs.ts');
- await runJobs(null, args);
- return null;
- }
- }
- }
-
- // Autopilot status + uninstall are filesystem-only verdicts and MUST stay
- // engine-free: a running PGLite daemon holds the exclusive DB lock, so an
- // engine-bound status would fail to connect exactly when the exit-code
- // contract matters (live daemon, DB outage). #1525: positional spellings
- // resolve to flags (or exit 2 on an unknown word) BEFORE connectEngine.
- if (command === 'autopilot') {
- const { resolveAutopilotPositionals, runAutopilotStatus, uninstallDaemon } = await import('./commands/autopilot.ts');
- args = resolveAutopilotPositionals(args);
- if (args.includes('--uninstall')) { uninstallDaemon(); return null; }
- if (args.includes('--status')) { runAutopilotStatus(args); return null; }
- if (args.includes('--pause') || args.includes('--resume')) { (await import('./commands/autopilot-pause.ts')).runAutopilotPauseCommand(args); return null; }
- }
-
- // Thin-client `think` dispatch: runThinkCli already routes through
- // callRemoteTool when isThinClient(cfg) (v0.31.1). Falling through to
- // connectEngine() below fails with `database_url is missing` on
- // Topology-2 installs and never reaches that branch. Official invariant:
- // detect isThinClient BEFORE connectEngine (docs/architecture/thin-client.md).
- // --save/--take stay server-gated; runThinkCli already warns.
- if (command === 'think') {
- const cfgThink = loadConfig();
- if (cfgThink && isThinClient(cfgThink)) {
- const { runThinkCli } = await import('./commands/think.ts');
- await runThinkCli(null as never, args);
- return null;
- }
- }
-
- // These handlers already call their MCP twin on a thin client and never touch
- // the engine there; run them engine-free instead of opening one (#5102).
- if ((command === 'salience' || command === 'anomalies' || command === 'graph-query' || command === 'whoknows' || command === 'founder') &&
- isThinClient(loadConfig())) {
- await dispatchConnectedCommand(command, null as never, args);
- return null;
- }
-
- // Every recall form but an in-process --query/--budget-tokens call has a
- // thin-client path; that one reaches connectEngine, which refuses it.
- if (command === 'recall' && isThinClient(loadConfig())) {
- const { recallNeedsLocalEngine, runRecall } = await import('./commands/recall.ts');
- if (!recallNeedsLocalEngine(args)) {
- if (getCliOptions().brain) exitCliError(usageError(THIN_CLIENT_BRAIN_FLAG_MESSAGE, 'Remove --brain, or run from a machine with local mounts (`gbrain mounts list`).'), command);
- await runRecall(null as never, args);
- return null;
- }
- }
- return { args, syncWatchdog };
-}
-
-/**
- * Pipeline stage 6: the connectEngine() terminator, with jobs child-bootstrap
- * failure reporting and degraded-serve recovery. Returns null when `serve` ran
- * degraded (it owns its lifecycle).
- * @cliPipelineStage
- */
-async function connectCliOnlyEngine(command: string, args: string[]): Promise<BrainEngine | null> {
- // All remaining CLI-only commands need a DB connection.
- // db-availability loop (4c): `serve` alone survives a dead POSTGRES here —
- // degraded mode keeps the MCP server present in the harness (the classified
- // database_error envelope + GBRAIN_DB_ACCESS marker arrive in-band on every
- // tool call) and a repaired DB recovers on the next call without a harness
- // restart. PGLite keeps die-on-startup (its repair lane is pglite-repair;
- // the single-writer lock makes a lazy reconnect proxy wrong there). The
- // no-config path still exits inside connectEngine (keyless cold-home is
- // TODOS 1050, out of scope). Kill switch: GBRAIN_SERVE_DEGRADED=0.
- let engine: BrainEngine;
- // F4: a serve (stdio or --http) with no brain / a missing or repair-failed brain / unreadable config
- // answers in status-only mode instead of exiting; it re-probes through the throw-only connect.
- // Engine graduation (§6.4): a serve (re)launched while a run owns the host brain exits 75 with graduation_in_progress.
- if (command === 'serve' && (dbMarkerBrainId() ?? 'host') === 'host') (await import('./core/persistence/graduation-serve-guard.ts')).exitIfGraduationRunning();
- const serveStatus = command === 'serve' ? await import('./commands/serve-status.ts') : null;
- const serveStatusEligible = !!serveStatus?.statusModeEligible(args, (dbMarkerBrainId() ?? 'host') === 'host');
- const preConnectReason = serveStatusEligible ? serveStatus!.preConnectStatusReason() : null;
- if (preConnectReason) {
- await serveStatus!.runStatusModeServe(preConnectReason, null, args, () => connectEngineForServe(ENGINE_CONNECT_HOOKS));
return null;
}
- try {
- // A4: an observational command connects probe-only and completes startup only after consent.
- engine = await connectEngine({ probeOnly: findCliCommand(command)?.startup === 'observational' || (command === 'jobs' && args[0] === 'supervisor' && args[1] === 'status') });
- } catch (serveConnectError) {
- if (command === 'jobs' && args[0] === 'child-readiness') {
- const { writeChildReadinessFailure } = await import('./core/minions/child-readiness.ts');
- process.exit(writeChildReadinessFailure(serveConnectError));
- }
- if (command === 'jobs' && args[0] === 'run-child') {
- const { CHILD_ENV } = await import('./core/minions/job-isolation.ts');
- const resultPath = process.env[CHILD_ENV.resultPath];
- if (resultPath) {
- const { writeChildBootstrapError } = await import('./core/minions/run-child.ts');
- process.exit(writeChildBootstrapError(resultPath, serveConnectError));
- }
- }
- // Gate on the engine of the RESOLVED brain, not the host config —
- // connectEngine routes mounts FIRST, so a PGLite mount's failure on a
- // postgres host must NOT get a lazy reconnect proxy (the single-writer
- // data-dir lock makes that wrong), and an unknown engine (no config)
- // keeps die-on-startup rather than defaulting to postgres.
- const resolvedEngineKind = await (async () => {
- try {
- const id = dbMarkerBrainId();
- if (id && id !== 'host') {
- const { loadMounts } = await import('./core/brain-registry.ts');
- return loadMounts().find((m) => m.id === id)?.engine ?? null;
- }
- return loadConfig()?.engine ?? null;
- } catch {
- return null;
- }
- })();
- // C10: a supervisor asked for fail-fast — exit non-zero with the classified envelope on stderr.
- if (command === 'serve') {
- const failFast = await import('./core/serve-fail-fast.ts');
- if (failFast.serveFailFastRequested(args)) process.exit(failFast.writeServeFailFastEnvelope(serveConnectError));
- }
- const connectStatusReason = serveStatusEligible ? serveStatus!.statusReasonForError(serveConnectError) : null;
- if (connectStatusReason) {
- await serveStatus!.runStatusModeServe(connectStatusReason, serveConnectError, args, () => connectEngineForServe(ENGINE_CONNECT_HOOKS));
- return null;
- }
- if (command === 'serve' &&
- process.env.GBRAIN_SERVE_DEGRADED !== '0' &&
- process.env.GBRAIN_SERVE_DEGRADED !== 'false' &&
- resolvedEngineKind === 'postgres') {
- try {
- const d = classifyDbAccessError(serveConnectError, { url: loadConfig()?.database_url ?? null, brainId: dbMarkerBrainId() });
- console.error(`${formatDbMarker(d)}\n${d.message}\n${d.remediation} Run: gbrain db-repair`);
- } catch { /* marker is best-effort; degraded serve still starts */ }
- const { createDegradedEngine } = await import('./core/degraded-engine.ts');
- const graduationGate = (await import('./core/persistence/graduation-serve-guard.ts')).engineIdentityGate();
- const degraded = createDegradedEngine({
- initialError: serveConnectError,
- // Guarded reconnect: connectEngine's no-config path calls
- // process.exit(1) directly — if config.json disappears while serve is
- // degraded, the reconnect must THROW into the classified envelope, not
- // kill the live MCP server mid-RPC. HOST brains only: a mount routes
- // through connectMountEngine before loadConfig() and needs no host
- // config, so the guard must not brick a mount serve's recovery.
- reconnect: async () => {
- if ((dbMarkerBrainId() ?? 'host') === 'host') graduationGate();
- if ((dbMarkerBrainId() ?? 'host') === 'host' && !loadConfig()) {
- throw new Error('No brain configured (config.json missing or unreadable). Run: gbrain init');
- }
- return connectEngine();
- },
- });
- const { runServe } = await import('./commands/serve.ts');
- await runServe(degraded, args);
- return null; // serve doesn't disconnect
- }
- throw serveConnectError;
- }
- return engine;
-}
-
-
-/**
- * #3013: decide whether an invocation enters the read-only connect+dispatch
- * timeout path, and with what wallclock. Returns null for every command
- * dispatchReadOnlyCommand can't handle. The gate used to be "a timeout is
- * present" — so a user-supplied --timeout on a write command (`sync`,
- * `embed`, `import`, ...) hijacked dispatch into the read-only path, which
- * threw and exited 1 before any work ran. Pure; exported for the
- * regression test.
- */
-export function resolveReadOnlyDispatchTimeoutMs(
- command: string,
- subArgs: string[],
- userTimeoutMs: number | null,
-): number | null {
- if (command !== 'search' && command !== 'sources') return null;
- const defaultMs =
- command === 'search' ? 30_000 :
- (subArgs[0] === 'list' || subArgs[0] === undefined) ? 10_000 :
- null;
- return userTimeoutMs ?? defaultMs;
-}
-
-/**
- * v0.41.6.0 D3: dispatch helper for the read-only commands that take a
- * default wallclock timeout (`gbrain search`, `gbrain sources list`).
- * Keeps the timeout-wrap site in main() small and the per-command
- * dispatch logic colocated for easy extension. Pure dispatcher; no engine
- * lifecycle (caller owns connect/disconnect).
- */
-async function dispatchReadOnlyCommand(engine: BrainEngine, command: string, args: string[]): Promise<void> {
- switch (command) {
- case 'search': {
- const { runSearch } = await import('./commands/search.ts');
- await runSearch(engine, args);
- return;
- }
- case 'sources': {
- const { runSources } = await import('./commands/sources.ts');
- await runSources(engine, args);
- return;
- }
- default:
- throw new Error(`dispatchReadOnlyCommand: unsupported command "${command}"`);
- }
-}
-
-// Build the AIGatewayConfig payload from a GBrainConfig. Both configureGateway
-// sites in connectEngine() pass through this helper so adding a new field
-// touches one place.
-// v0.42 (#1780): moved to src/core/ai/build-gateway-config.ts so core modules
-// (init-embed-check) can reuse it without importing the CLI entrypoint. Still
-// re-exported here for back-compat with `test/ai/build-gateway-config.test.ts`
-// and other callers that import it from `../../src/cli.ts`. Imported (not just
-// re-exported) so cli.ts's own connectEngine() call sites bind it locally.
-import { buildGatewayConfig } from './core/ai/build-gateway-config.ts';
-export { buildGatewayConfig };
-import { connectEngineForServe, noBrainError, type EngineConnectHooks } from './core/engine-connect.ts';
-
-/**
- * Which brain this process's engine targets. Set by connectEngine after brain
- * resolution; read by makeContext so ctx.brainId carries the audit id. Never
- * derived from op params — an untrusted caller must not be able to name a
- * brain (same fail-closed shape as the #3524 remote source sentinel).
- */
-let activeBrainId: string = 'host';
-
-/** The command main() dispatched; connectEngine's thin-client refusal names it. */
-let dispatchedCommand = '';
-
-/**
- * Connect to a mounted brain (brain axis, non-host). Routes through
- * BrainRegistry so:
- * - an unknown/disabled mount id throws UnknownBrainError. Fail-closed:
- * the pre-fix CLI silently fell back to the host brain, returning
- * confident wrong answers (mirror of #3524's explicit --source decision);
- * - postgres mounts get a per-instance pool, never the db.ts singleton;
- * - NO migrations run against the mount — schema is the publisher's job
- * (same decision as BrainRegistry.initMountBrain). Write access control
- * is the mount's own DB credential grants: a read-only role rejects
- * writes at the database; gbrain does not re-implement that client-side.
- * The AI gateway still configures from the HOST config (the caller's API
- * keys + model tiers) — embedding/expansion spend stays the caller's, and
- * a mount's DB-plane model config is never merged into the caller's gateway.
- */
-async function connectMountEngine(brainId: string): Promise<BrainEngine> {
- const config = loadConfig();
- if (config) {
- const { configureGateway } = await import('./core/ai/gateway.ts');
- configureGateway(buildGatewayConfig(config));
- }
- const { loadRegistry } = await import('./core/brain-registry.ts');
- const handle = await loadRegistry().getBrain(brainId);
- activeBrainId = brainId;
- // Fixup (PR #4186): mark this specific engine as a mount engine so
- // makeContext's DB-plane fallback (see MOUNT_ENGINES above) never re-merges
- // a mount's config into the caller's context, regardless of what other
- // engine — host or another mount — this process may also be holding.
- MOUNT_ENGINES.add(handle.engine);
- SELECTED_CONFIG_BY_ENGINE.set(handle.engine, handle.config);
- return handle.engine;
-}
-
-async function connectEngine(opts?: { probeOnly?: boolean }): Promise<BrainEngine> {
- // Brain axis: resolve WHICH DATABASE this invocation targets before touching
- // the host engine. --brain (global flag) / GBRAIN_BRAIN_ID / .gbrain-mount /
- // mount-path-prefix resolve via the canonical 6-tier chain — the mirror of
- // the source axis in makeContext. connectEngine is the single choke point
- // every local CLI command routes through (shared ops, CLI-only commands,
- // and the search-dashboard path), so routing lands here once.
- const { resolveBrainId } = await import('./core/brain-resolver.ts');
- const brainId = resolveBrainId(getCliOptions().brain);
- if (brainId !== 'host') return exitOnRepairFailed(() => connectMountEngine(brainId));
-
- const config = loadConfig();
- if (!config) {
- // db-availability loop: this exit never reaches the bottom rejection
- // handler (direct process.exit), so the no_url marker is emitted HERE.
- // There is no error object on this path — diagnoseDbConfig is the
- // errorless config-plane entry point, never a faked Error.
- try {
- const d = diagnoseDbConfigForMarker({ source: getDbUrlSource(), envShadowed: envShadowDetected(), brainId });
- if (d && shouldEmitDbAccessMarker()) {
- console.error(formatDbMarker(d));
- }
- if (d?.reason === 'env_shadowed') console.error(d.remediation);
- } catch { /* marker is best-effort — the message below always prints */ }
- exitCliError(noBrainError(), cliCommandOf());
- }
-
- // A thin client has no local database. Every command that gets here would die
- // with "No database URL" (whose suggested init replaces remote_mcp) or answer
- // from an empty in-memory PGLite, so refuse with the routing hint (#5102).
- if (isThinClient(config) && !config.database_url) {
- refuseThinClient(dispatchedCommand, config.remote_mcp!.mcp_url);
- }
- // The throw-only connect (src/core/engine-connect.ts) behind the CLI's exits.
- return exitOnRepairFailed(() => connectEngineForServe(ENGINE_CONNECT_HOOKS, opts));
-}
-
-/** A6/D1: the pending-migrations warning as a notice whose fix applies them (stderr; stdout stays the command's). */
-function migrationsNotice(why: string): Notice {
- return { code: 'migrations_pending', kind: 'safety', why, fix: { argv: ['gbrain', 'apply-migrations', '--yes'], consent: [], actor: 'agent',
- requires_exclusive: true, why: 'Applies the pending schema migrations (the same ones every command applies on connect).', verify: { argv: ['gbrain', 'doctor', '--json'] } } };
-}
-
-/** Startup after the probe-only connect: migrations, retired-marker cleanup, DB-plane config merge. Mounts: none. */
-async function completeEngineStartup(engine: BrainEngine): Promise<void> {
- const config = SELECTED_CONFIG_BY_ENGINE.get(engine);
- if (!config || MOUNT_ENGINES.has(engine)) return;
-
- // v0.41.6.0 D4: race-tolerant CLI-side migration runner. Replaces the
- // pre-v0.41.6.0 `try { hasPendingMigrations && initSchema() } catch warn`
- // block that fired the alarming "Schema probe/migrate failed: deadlock
- // detected" warning on EVERY sync when two CLIs raced on schema probe.
- // The retry+poll loop quiets the warning when the race resolves
- // itself (the common case); the revised wording fires only when
- // migrations are genuinely stuck.
- try {
- const { tryRunPendingMigrations } = await import('./core/migrate.ts');
- const result = await tryRunPendingMigrations(engine);
- if (result.status === 'persistent') {
- writeCliNotice(migrationsNotice('Schema migrations are pending: another process attempted them but they did not complete within the retry window (usually transient). If it persists, check `gbrain doctor` for stale advisory locks and `gbrain jobs supervisor status` for crashed migration workers.'));
- } else if (result.status === 'error') {
- // Non-deadlock error during initSchema. Surface the message and continue;
- // subsequent operations will resurface the real schema error in context.
- writeCliNotice(migrationsNotice(`Schema probe failed: ${result.error.message}`));
- }
- // 'ok', 'not_needed', 'race_resolved' → silent (the common-case outcomes).
- } catch (err) {
- // Last-resort defense in case the helper itself throws unexpectedly.
- writeCliNotice(migrationsNotice(`Schema probe failed (unexpected): ${(err as Error).message}`));
- }
-
- // #5628: drop this host's markers of a retired managed epoch before any filesystem guard check.
- try { await (await import('./core/persistence/deactivation.ts')).cleanupRetiredManagedMarkers(engine); } catch { /* status reports pending markers */ }
-
- // v0.27.1 (F3 fix): re-merge DB-plane config now that the engine is up.
- // Flags like `embedding_multimodal` are user-mutable via `gbrain config set`
- // (DB plane) and need to flow into the gateway after connect. Schema-sizing
- // fields (embedding_dimensions etc.) keep their pre-connect file/env values
- // — those drove initSchema and the merged config respects file/env first.
- try {
- const merged = await loadConfigWithEngine(engine, config);
- if (merged) {
- // #1475 — hand the merged config to makeContext instead of letting it
- // re-derive one. See MERGED_CONFIG_BY_ENGINE: the op-side gates read
- // ctx.config, and re-running the merge there would double this
- // function's per-key config reads on every command (the cost #3980 is
- // about). Keyed on the engine so a mounted brain cannot be served the
- // host brain's merge.
- MERGED_CONFIG_BY_ENGINE.set(engine, merged);
- // Stash gate flags on process.env for downstream readers (import-file.ts
- // dispatches on GBRAIN_EMBEDDING_MULTIMODAL, gates OCR on GBRAIN_EMBEDDING_IMAGE_OCR).
- // The OCR *model* reaches the gateway via the re-configure below (#4107); its
- // env stash stays so subprocesses re-fold it through loadConfig's env merge.
- if (merged.embedding_multimodal !== undefined) {
- process.env.GBRAIN_EMBEDDING_MULTIMODAL = String(merged.embedding_multimodal);
- }
- if (merged.embedding_image_ocr !== undefined) {
- process.env.GBRAIN_EMBEDDING_IMAGE_OCR = String(merged.embedding_image_ocr);
- }
- if (merged.embedding_image_ocr_model !== undefined) {
- process.env.GBRAIN_EMBEDDING_IMAGE_OCR_MODEL = merged.embedding_image_ocr_model;
- }
- // Always re-configure with merged values when DB merge succeeded. The
- // trigger used to be field-name-gated (only when embedding_multimodal_model
- // was set); that coupled the gate to the field set and would silently
- // miss future DB-mutable gateway fields. One extra cache+shrinkState
- // clear per startup is microseconds, no hot path.
- (await import('./core/ai/gateway.ts')).configureGateway(buildGatewayConfig(merged));
- }
- // v0.31.12: re-resolve gateway defaults through resolveModel so
- // `models.tier.*` and `models.default` overrides apply to expansion +
- // chat. Per Codex F3 — configureGateway is sync; this is the async
- // re-stamp seam after engine.connect() makes config reads possible.
- const { reconfigureGatewayWithEngine } = await import('./core/ai/gateway.ts');
- await reconfigureGatewayWithEngine(engine);
- } catch {
- // Non-fatal. Pre-v39 brains may not have a usable config table yet.
- }
-
- // The one-time behavior-change disclosure on the CLI channel (stderr). `serve`
- // delivers it per MCP channel; `doctor` reads it without marking it shown.
- if (dispatchedCommand !== 'serve' && dispatchedCommand !== 'doctor') {
- try {
- const { takeLocalBehaviorNotice } = await import('./core/behavior-change-notice.ts');
- const notice = await takeLocalBehaviorNotice(engine, 'cli', { cfg: MERGED_CONFIG_BY_ENGINE.get(engine) ?? config });
- if (notice) writeCliNotice(notice);
- } catch { /* a disclosure never breaks a command */ }
- }
-}
-
-/** CLI-only usage examples appended to `gbrain <command> --help`. */
-const OP_HELP_EXAMPLES: Record<string, string[]> = {
- get_links: [
- 'gbrain links people/alice-example # resolved source (every federated source when unpinned)',
- 'gbrain links people/alice-example --source business # one source',
- 'gbrain links people/alice-example --all-sources # every source',
- ],
- get_backlinks: [
- 'gbrain backlinks companies/acme-example',
- 'gbrain backlinks companies/acme-example --source-id business',
- 'gbrain backlinks companies/acme-example --all-sources --json',
- ],
- // #6255: the receipt command's routing flags and states.
- get_write_request: ['gbrain write-request --brain host -- <request_id> [--json] # queued/running: pending, read again after retry_after_ms; committed/conflict/failed/cancelled: final'],
- traverse_graph: [
- 'gbrain graph people/alice-example --depth 2',
- 'gbrain graph people/alice-example --source business --direction both',
- 'gbrain graph people/alice-example --all-sources # same slug in two sources stays two nodes (source_id)',
- ],
-};
-
-export function printOpHelp(op: Operation, invokedName?: string) {
- const positional = (op.cliHints?.positional || []).map(p => `<${p}>`).join(' ');
- // v114 (#1941): when invoked via an alias (e.g. `gbrain link-add --help`),
- // show the alias the user typed, not the primary op name.
- const name = invokedName || op.cliHints?.name || op.name;
- const stdinKey = op.cliHints?.stdin;
- const stdinFlag = stdinKey ? `--${stdinKey.replace(/_/g, '-')}` : '';
- console.log(`Usage: gbrain ${name} ${positional} [options]`);
- if (stdinKey) console.log(` gbrain ${name} ${positional} [options] < file (${stdinFlag} read from stdin)`);
- console.log('\n' + op.description + '\n');
- const entries = Object.entries(op.params);
- if (entries.length > 0) {
- console.log('Options:');
- for (const [key, def] of entries) {
- const isPos = op.cliHints?.positional?.includes(key);
- const req = key === stdinKey
- ? ` (required: ${stdinFlag} needs a value; omit ${stdinFlag}, or put it last, to read stdin)`
- : def.required ? ' (required)' : '';
- const prefix = isPos ? ` <${key}>` : ` --${key.replace(/_/g, '-')}`;
- console.log(`${prefix.padEnd(28)} ${def.description || ''}${req}`);
- }
- }
- const examples = OP_HELP_EXAMPLES[op.name];
- if (examples) console.log(`\nExamples:\n${examples.map((line) => ` ${line}`).join('\n')}`);
+ if (!command || command === '--help' || command === '-h') return 'help';
+ if (command === '--version' || command === 'version') return 'version';
+ return null;
}
-function printHelp() {
- console.log(`gbrain ${VERSION} -- personal knowledge brain
-
-USAGE
- gbrain <command> [options]
-
-SETUP
- mcp grant <name> --help Grant hosted access; private credential handoff
- mcp verify --help Verify connection, permissions, and memory
- init [--pglite|--supabase|--url] Create brain (PGLite default, no server)
- init --prefer-postgres [--allow-docker]
- Postgres-first install ladder (env URL >
- Supabase token > local PG > docker > PGLite)
- engine status [--json] [--probe] Which engine + URL source, engine-free
- db-repair [--yes] [--json] Diagnose/fix Postgres access, engine-free
- (--yes --apply-rewrites for config rewrites)
- migrate --to <postgres|pglite> Move the brain between engines (PGLite -> Postgres graduates: plan, then --yes --expect)
- migrate embeddings --to <p:model> Re-embed onto another embedding provider
- embeddings enable --embedding-model <p:model> Turn on embeddings in place (keeps pages/facts)
- upgrade Self-update
- check-update [--json] Check for new versions
- repair [<kind>] [--apply] Preview/apply residual repairs (timeline, visibility, safe-chunks)
- projections drain [--limit n] Rebuild queued text projections now [--json]
- doctor [--json] [--fast] [--probe-pglite] Health check (resolver, skills, pgvector, RLS, embeddings; --probe-pglite runs the scratch-store probe)
- integrations [subcommand] Manage integration recipes (senses + reflexes)
-
-PAGES
- get <slug> Read a page
- put <slug> [< file.md] Write/update a page
- delete <slug> Delete a page
- list [--type T] [--tag T] [--limit N]
- List pages
-
-SEARCH
- search <query> Keyword search (tsvector)
- query <question> [--no-expand] Hybrid search (RRF + expansion)
- ask <question> [--no-expand] Alias for query
-
-IMPORT/EXPORT
- import <dir> [--no-embed] Import markdown directory
- sync [--repo <path>] [flags] Git-to-brain incremental sync
- sync --watch [--interval N] Continuous sync (loops until stopped)
- See also: autopilot --install (continuous daemon).
- sync --all --missing-path skip Classify sources whose local_path is absent
- on this machine as skipped, not failed
- export [--source <id>] [--dir <p>] Coherent Markdown snapshot; fresh output, no overwrite
- export --restore-only [--repo <p>] Restore missing db_only files; export --help for safe retry
- [--type T] [--slug-prefix S] With optional filters
-
-FILES
- files list [slug] List stored files
- files upload <file> --page <slug> Upload file to storage
- files upload-raw <file> --page <s> Smart upload (size routing + .redirect.yaml)
- files signed-url <path> Generate signed URL (1-hour)
- files sync <dir> Bulk upload directory
- files verify Verify all uploads
-
-EMBEDDINGS
- embed [<slug>|--all|--stale] Generate/refresh embeddings
-
-LINKS
- link <from> <to> Create typed link (alias: link-add)
- [--link-type T] [--link-source S] provenance defaults to 'manual'
- unlink <from> <to> Remove link (alias: link-rm)
- [--link-type T] [--link-source S] filter which edges to remove
- link-sources List provenances in use, with edge counts
- backlinks <slug> Incoming links
- graph <slug> [--depth N] Traverse link graph (nodes locally; remote MCP defaults to bidirectional edges)
- graph-query <slug> [--type T] Edge-based traversal with type/direction filters
- [--depth N] [--direction in|out|both]
-
-TAGS
- tags <slug> List tags
- tag <slug> <tag> Add tag
- untag <slug> <tag> Remove tag
-
-TIMELINE
- timeline [<slug>] View timeline
- timeline-add <slug> <date> <text> Add timeline entry
-
-TOOLS
- extract <links|timeline|all> Extract links/timeline (idempotent)
- [--source fs|db] [--source-id ID] [--dir <brain>]
- [--type T] [--since DATE] [--include-frontmatter]
- [--workers N|--concurrency N] [--dry-run] [--json]
- extract links --by-mention [--ner] --source db
- extract timeline --from-meetings [--infer-dates] --source db
- extract --stale [--source-id ID] [--catch-up] [--dry-run] [--json]
- extract links --source db --repair-attendance --source-id ID
- [--limit 250] [--after-slug SLUG] [--json]
- Apply: --apply-preview FILE --confirm DIGEST --yes --backup-verified --checkpoint FILE
- extract --explain <kind> [--json] Full details: gbrain extract --help
- publish <page.md> [--password] Shareable HTML (strips private data, optional AES-256)
- check-backlinks <check|fix> [dir] Find/fix missing back-links across brain
- lint <dir|file> [--fix] Catch LLM artifacts, placeholder dates, bad frontmatter
- backfill <kind|list> v0.30.1: run a registered backfill (effective-date, ...)
- orphans [--json] [--count] Find pages with no inbound wikilinks
- salience [--days N] [--kind P] v0.29: pages ranked by emotional + activity salience
- anomalies [--since D] [--sigma N] v0.29: cohort-based statistical anomalies (tag, type)
- feedback <status|reset> retrieval feedback: learned page weights; rate answers with gbrain rate
- transcripts <ingest|status|recent> v0.46: import agent session logs + chat exports (local-only)
- dream [--dry-run] [--json] Run the overnight maintenance cycle once (cron-friendly).
- See also: autopilot --install (continuous daemon).
- compile-context --target <t> Compile a deterministic, scanned, budgeted context
- [--budget N] [--check] file (claude-code | codex | openclaw)
- decide <status|probe|enable|...> System One decision support (Jev); every slot off by default
- facts relink [--dry-run] Link facts saved without an entity to the entity they name
- check-resolvable [--json] [--fix] Validate skill tree (reachability/MECE/DRY)
- report --type <name> --content ... Save timestamped report to brain/reports/
-
-OPEN LOOPS (Gmail/Calendar/Contacts connector — v0.47)
- google setup [--account <email>] One command: BYO OAuth → source → first sync → first digest
- google connect|status|disconnect Connect/inspect/remove a Google account (idempotent; --json)
- waiting [--top N] [--json] Who is waiting on you, what you promised, context to respond
- loops list|show|done|drop|mute Inspect and manage open loops (mute sender <email>)
- core list|show|status|add|remove Always-loaded core memory (also diff|ack|init|suggest)
- creds list|remove|export|import Generic credential vault (redacted output; encrypted bundles)
-
-BRAIN (capture / ideate / explore — v0.37/v0.38)
- capture [content] [--file PATH] Single entrypoint for getting content into the brain
- [--stdin] [--slug s] [--type t] Inline content / file / stdin; writes to inbox/ by default
- [--source ID] [--quiet|--json] Multi-source brains: route to a non-default source
- brainstorm <question> [--json] Bisociation idea generator (hybrid search + far-set + judge)
- [--save|--no-save] [--limit N]
- lsd <question> [--json] Lateral Synaptic Drift: inverted-judge brainstorm
- [--save|--no-save] [--limit N] rewarding far-from-obvious + axiomatic inversions
- think "<question>" [--anchor <s>] Multi-hop cited synthesis across pages + takes + graph
- [--save] [--source <id>] Full flags: gbrain think --help
-
-SOURCES (multi-repo / multi-brain)
- sources list Show registered sources
- sources add <id> --path <p> Register a source (id = short name, e.g. 'wiki')
- sources remove <id> Remove a source + its pages (--confirm-destructive)
- sources archive <id> Soft-delete: hide from search, recoverable for 72h
- sources restore <id> Un-archive a soft-deleted source
- sources archived List soft-deleted sources and their purge expiry
- sources purge [<id>] Permanently delete archived sources
- sources status Per-source dashboard (sync lag, embed coverage)
- sources --help Full subcommand list (rename, default, attach,
- current, federate, set-cr-mode, webhook, harden, ...)
- sync --all Sync all sources with a local_path
- sync --source <id> Sync one specific source
- repos ... DEPRECATED alias for 'sources' (v0.19.0)
-
-CODE INDEXING (v0.19.0 / v0.20.0 Cathedral II)
- code-def <symbol> [--lang l] Find the definition of a symbol across code pages
- code-refs <symbol> [--lang l] Find all references to a symbol (JSON-first)
- code-callers <symbol> Who calls this symbol? (v0.20.0 A1)
- code-callees <symbol> What does this symbol call? (v0.20.0 A1)
- query <q> --lang <l> Filter hybrid search to one language (v0.20.0)
- query <q> --symbol-kind <k> Filter to symbol type (function|class|method|...) (v0.20.0)
- reconcile-links [--dry-run] Batch-recompute doc↔impl edges (v0.20.0)
- reindex-code [--source id] [--yes] [--force] Explicit code-page reindex (v0.20.0; --force re-chunks unchanged pages)
- reindex-search-vector [--dry-run] [--yes] [--json]
- Recreate FTS triggers + backfill under
- $GBRAIN_FTS_LANGUAGE (default 'english')
- sync --strategy code Sync code files into the brain
-
-JOBS (Minions)
- jobs submit <name> [--params JSON] Submit background job [--follow] [--dry-run]
- jobs list [--status S] [--limit N] List jobs [--json]
- jobs get <id> [--json] Job details + history
- jobs cancel <id> Cancel job
- jobs retry <id> Re-queue failed/dead job
- jobs prune [--older-than 30d] Clean old jobs
- jobs stats [--json] Job health dashboard
- jobs watch [--follow] Live queue dashboard
- jobs work [--queue Q] Start worker daemon (Postgres only)
- jobs supervisor [start|status|stop] Auto-restarting worker wrapper
-
-ADMIN
- stats Brain statistics
- health Brain health dashboard
- history <slug> [--json] Page version history
- revert <slug> <version-id> Revert to version
- features [--json] [--auto-fix] Scan usage + recommend unused features
- autopilot [--repo] [--interval N] Self-maintaining brain daemon
- config [show|get|set] <key> [val] Brain config
- pricing [set|list|unset] <model> Register model prices for cost caps (host only)
- protocol [conformance|stats] MEMORY_VERBS v1: schemas, conformance
- certification, local usage stats + TTHW
- storage status [--repo <path>] Storage tier status and health
- [--json] (git-tracked vs supabase-only)
- serve MCP server (stdio)
- --surface verbs|starter|full Tool surface: the 7 memory verbs, the ~20-op
- starter set, or every op (default full).
- On --http this is the per-client CEILING.
- --access read-only|full stdio: list and dispatch only read operations
- serve --http [--port N] HTTP MCP server with OAuth 2.1
- --token-ttl N Access token TTL in seconds, 60-7776000 (default: 3600)
- --enable-dcr Enable Dynamic Client Registration (DCR clients default to authorization_code)
- --enable-dcr-insecure Also allow the consent-bypassing client_credentials grant on DCR (implies --enable-dcr)
- --public-url URL Public issuer URL (required behind proxy/tunnel)
- connect <mcp-url> --token <t> Wire Claude Code to a remote gbrain (bearer token)
- [--install] [--json] Print the paste-ready command, or --install to run it
- auth <create|list|revoke|...> Manage legacy tokens + OAuth 2.1 clients
- auth --help Full subcommand list (register-client,
- rescope, rescope-client, rescope-token, revoke-client, ...)
- watch [--json] Push-based context: pipe conversation turns in,
- volunteered brain pages stream out (#2095)
- call <tool> '<json>' Raw tool invocation
- version Version info
- --tools-json Tool discovery (JSON)
-
-Run gbrain <command> --help for command-specific help.
-`);
+async function runFastPath(path: 'help' | 'version'): Promise<void> {
+ await runCliPreflight();
+ if (path === 'help') printHelp();
+ else console.log(`gbrain ${VERSION}`);
}
-// Only auto-run when invoked as the entry point (the compiled binary or
-// `bun src/cli.ts`). Guarded so tests can import cliAliases / printOpHelp
-// without triggering argv parsing + main(). v114 (#1941).
-//
-// #2084 — the ONE process-exit seam for one-shot commands. Every teardown site
-// routes through finishCliTeardown (which returns); the exit itself happens
-// here, after main() settles, so the CLI never waits on Bun's event loop to
-// drain (stuck PgBouncer sockets kept it alive — endPoolBounded races PAST a
-// stuck pool.end() by design). flushThenExit fences stdout/stderr and holds a
-// short aliveness grace so piped output is delivered before exit (#1959).
-// Daemons (`serve`) are excluded by shouldForceExitAfterMain and keep the
-// pre-#2084 behavior: main() resolves and the server's own work keeps the
-// process alive. A fatal error still exits 1 for every command, daemons
-// included (matches the prior unconditional process.exit(1) on rejection).
if (import.meta.main) {
exitOnUnsupportedBun(process.argv[2], VERSION);
// v0.41.6.0 D5: cleanup registry + signal handlers for SIGTERM/SIGHUP/SIGPIPE/
@@ -3193,22 +54,13 @@ if (import.meta.main) {
// #4383: CLI_ONLY payloads (console.log / bare process.stdout.write) get
// delivery-exact serialized writes; `serve` keeps native streaming stdout.
if (shouldForceExitAfterMain()) installStdoutPipeDelivery(agentJsonGuardMode(process.argv.slice(2)));
- main().then(
- () => {
- if (shouldForceExitAfterMain()) flushThenExit(currentExitCode());
- },
- (e) => {
- // D1: the fatal seam renders through renderCliError (one --json
- // envelope on stdout; human `Error [code]` / `Fix:` on stderr), keeping
- // the pglite_busy keys and the GBRAIN_DB_ACCESS marker. A renderer
- // fault must never lose the error, so the raw message is the fallback.
- let exitCode = 1;
- try {
- exitCode = writeFatalCliError(e, { dbUrl: loadConfig()?.database_url ?? null, brainId: dbMarkerBrainId() });
- } catch {
- console.error(e?.message || e);
- }
- flushThenExit(exitCode);
- },
- );
+ const fastPath = cliFastPath(process.argv.slice(2));
+ if (fastPath) {
+ runFastPath(fastPath).then(
+ () => flushThenExit(currentExitCode()),
+ async (e) => (await import('./cli/main.ts')).exitOnFatalCliError(e),
+ );
+ } else {
+ void import('./cli/main.ts').then((m) => m.runCli());
+ }
}
diff --git a/src/cli/main.ts b/src/cli/main.ts
new file mode 100755
index 0000000000..dcc3be5501
--- /dev/null
+++ b/src/cli/main.ts
@@ -0,0 +1,3000 @@
+/**
+ * The CLI dispatcher: global-flag parsing, op routing, CLI_ONLY commands and the
+ * one-shot exit seam. src/cli.ts (the entry point) loads it with a dynamic
+ * import after answering its engine-free fast paths, so `gbrain --version` and
+ * top-level help never pay for this module's import graph. Tests import the
+ * helpers below from here.
+ */
+import { affectsRecall } from '../core/types.ts';
+import { deliveryVersionSkewWarning } from '../core/search/evidence-delivery.ts';
+import { installSigchldHandler } from '../core/zombie-reap.ts';
+installSigchldHandler();
+
+import { readFileSync, existsSync, unlinkSync } from 'fs';
+import { readStdinBounded as readStdinPayload } from '../core/interaction.ts';
+import { spawn } from 'child_process';
+import {
+ readUpdateCache,
+ isCacheFresh,
+ pendingUpgradeVersion,
+ readSnooze,
+ isSnoozeActive,
+ resolveSelfUpgradeMode,
+ justUpgradedPath,
+} from '../core/self-upgrade.ts';
+import { loadConfig, loadConfigFileOnly, loadConfigWithEngine, isThinClient, getDbUrlSource, envShadowDetected } from '../core/config.ts';
+import {
+ classifyPgAccessError as classifyDbAccessError,
+ diagnoseDbConfig as diagnoseDbConfigForMarker,
+ formatDbAccessMarker as formatDbMarker,
+ shouldEmitDbAccessMarker,
+} from '../core/pg-access-classify.ts';
+import { resolveBrainId as resolveBrainIdForDbMarker } from '../core/brain-resolver.ts';
+import type { GBrainConfig } from '../core/config.ts';
+import type { AIGatewayConfig } from '../core/ai/types.ts';
+import type { BrainEngine } from '../core/engine.ts';
+import { operations, OperationError } from '../core/operations.ts';
+import { resolveSourceIdEngineFree } from '../core/source-resolver.ts';
+import { installCliRoutingFor } from './fix-routing-provider.ts';
+import { formatVolunteeredPage } from '../core/context/volunteer.ts';
+import type { Operation, OperationContext } from '../core/operations.ts';
+import { currentCliWriteWait } from '../core/persistence/write-wait.ts';
+import { isScopeErrorCode } from '../core/error-catalogue.ts';
+import { shouldForceExitAfterMain, finishCliTeardown, flushThenExit, currentExitCode, setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';
+import { printCuratedHelp } from './help/render.ts';
+import { printHelp } from './top-help.ts';
+import { curatedFlagError } from './help/validate.ts';
+import { cliCommandOf, exitCliError, exitOnRepairFailed, unknownFlagError, usageError, writeCliError, writeCliNotice, writeFatalCliError } from './cli-error.ts';
+import type { Notice } from '../core/agent-output.ts';
+import { opError, opOwnsSource } from '../core/ops/contract.ts';
+import { opParamValue } from './op-param-values.ts';
+import { serializeMarkdown } from '../core/markdown.ts';
+import { parseGlobalFlags, setCliOptions, getCliOptions } from '../core/cli-options.ts';
+import { runCliPreflight } from '../core/cli-preflight.ts';
+import { isBooleanLiteral, isKnownOpFlag } from '../core/op-flag-tokens.ts';
+import { conceptNudge } from '../core/search/query-intent.ts';
+import { redactRetrievalOutput } from '../core/search/output-redaction.ts';
+import type { CliOptions } from '../core/cli-options.ts';
+import { callRemoteTool, RemoteMcpError, unpackToolResult, extractResponseMeta } from '../core/mcp-client.ts';
+import { assertSingleSourceScopeFlag, checkHostHonoredParams, hintAmbientNarrowing, type AmbientSourceBinding } from './source-scope.ts';
+import { maybePromptForUpgrade } from '../core/thin-client-upgrade-prompt.ts';
+import { CLI_FLAG_REGISTRY } from '../core/cli-flag-registry.generated.ts';
+import { cliHelpRequested } from './subcommands.ts';
+import { printRouterHelp } from './router-help.ts';
+import { strictArgsRefusal } from './strict-args.ts';
+import { migrationCliArgumentError } from '../core/embedding-migration-cli.ts';
+import { VERSION } from '../version.ts';
+import { bigintToStringReplacer } from '../core/utils.ts';
+import {
+ CLI_ONLY,
+ CLI_ONLY_SELF_HELP,
+ STARTUP_HOOK_SKIP_COMMANDS,
+ THIN_CLIENT_REFUSED_COMMANDS,
+ findCliCommand,
+ type CliDispatchContext,
+} from './command-table.ts';
+import { formatRememberResult } from './remember-format.ts';
+import { applyCliOpNotices, captureOpNotice } from './op-notices.ts';
+
+// db-availability loop: best-effort brain-id for the GBRAIN_DB_ACCESS marker,
+// so a MOUNT's DB failure reads as `brain=<id>` instead of masquerading as a
+// host failure. Never throws (a malformed GBRAIN_BRAIN_ID must not break
+// error reporting — the marker just omits the suffix).
+function dbMarkerBrainId(): string | undefined {
+ try {
+ return resolveBrainIdForDbMarker(getCliOptions().brain ?? null);
+ } catch {
+ return undefined;
+ }
+}
+
+// Build CLI name -> operation lookup
+const cliOps = new Map<string, Operation>();
+for (const op of operations) {
+ const name = op.cliHints?.name;
+ if (name && !op.cliHints?.hidden) {
+ cliOps.set(name, op);
+ }
+}
+
+// bigint → string JSON replacer: defined in core/utils.ts (commands must not
+// reach into the dispatcher for it); re-exported here so existing importers
+// and tests keep their surface. (#2450)
+export { bigintToStringReplacer };
+
+// Membership sets are derived from the command table (src/cli/command-table.ts);
+// re-exported so existing importers keep their surface (CLAUDE.md facade rule).
+export { CLI_ONLY, THIN_CLIENT_REFUSED_COMMANDS };
+
+// ENG-2 renderer parity: round-trip a local-engine op's return value so
+// renderers see the same shape the routed path produces. Bigint-safe via
+// bigintToStringReplacer. Exported for tests (same import-safety contract as
+// cliAliases/formatResult). (#2450)
+export function normalizeLocalResult(rawResult: unknown): unknown {
+ return JSON.parse(JSON.stringify(rawResult, bigintToStringReplacer));
+}
+
+/**
+ * Commands in CLI_ONLY_SELF_HELP whose handler honours `--help` as its first
+ * action, before reading the engine. Dispatching them here keeps `--help`
+ * answerable with no brain configured.
+ *
+ * Membership is behaviour, not taste: each entry is pinned by
+ * test/cli-help-without-brain.test.ts, which runs the CLI with an empty
+ * GBRAIN_HOME and requires exit 0 plus real help output.
+ */
+const SELF_HELP_WITHOUT_ENGINE: Record<string, true | (() => Promise<(engine: never, args: string[]) => unknown>)> = {
+ export: async () => (await import('../commands/export.ts')).runExport as never,
+ models: async () => (await import('../commands/models.ts')).runModels as never,
+ watch: async () => (await import('../commands/watch.ts')).runWatch as never,
+ skillopt: async () => (await import('../commands/skillopt.ts')).runSkillOptCommand as never,
+ maintain: async () => (await import('../commands/maintain.ts')).runMaintain as never,
+ repair: async () => (await import('../commands/repair.ts')).runRepairCommand as never,
+ 'extract-conversation-facts': async () =>
+ (await import('../commands/extract-conversation-facts.ts')).runExtractConversationFacts as never,
+ transcripts: async () => (await import('../commands/transcripts.ts')).runTranscripts as never,
+ // runJobs accepts BrainEngine | null and its help guard returns before any
+ // engine (or subcommand body) is touched.
+ jobs: async () => (await import('../commands/jobs.ts')).runJobs as never,
+ // runDream accepts BrainEngine | null; --help (and `retriage --help`) is
+ // answered before any engine-bearing work per the dream.ts IRON RULE.
+ dream: async () => (await import('../commands/dream.ts')).runDream as never,
+ // runCompileContext accepts BrainEngine | null; the help guard runs first.
+ 'compile-context': async () =>
+ (await import('../commands/compile-context.ts')).runCompileContext as never,
+ // runLoops / runWaiting answer --help before touching the engine.
+ loops: async () => (await import('../commands/loops.ts')).runLoops as never,
+ 'edge-proposals': async () => (await import('../commands/edge-proposals.ts')).runEdgeProposals as never,
+ waiting: async () => (await import('../commands/loops.ts')).runWaiting as never,
+ // runSources's `--help`/`-h`/undefined-subcommand branch calls printHelp()
+ // without ever touching `engine` — safe to dispatch with no brain
+ // configured, matching the reader who runs `sources --help` because they
+ // have no brain yet.
+ sources: async () => (await import('../commands/sources.ts')).runSources as never,
+ // runConnectors's --help / no-subcommand / `providers` / `logout` branches
+ // never touch `engine` — safe engine-free for the reader with no brain yet.
+ connectors: async () => (await import('../commands/connectors/index.ts')).runConnectors as never,
+ // runAgent accepts BrainEngine | null; help (incl. `register --help`) is
+ // answered before any engine or job-queue work (cathedral-6).
+ agent: async () => (await import('../commands/agent.ts')).runAgent as never,
+ // D3: post-connect records whose handler answers --help before the engine; run through the table.
+ advisor: true, anomalies: true, feedback: true, backfill: true, 'book-mirror': true, 'edges-backfill': true, embed: true, features: true,
+ founder: true, 'graph-query': true, orphans: true, salience: true, think: true,
+ brainstorm: true, lsd: true, migrate: true, pages: true, pricing: true, 'retrieval-upgrade': true, whoknows: true, core: true,
+};
+
+/** Returns true when the command's own help was printed. */
+async function printSelfHelpWithoutEngine(command: string, args: string[]): Promise<boolean> {
+ const load = SELF_HELP_WITHOUT_ENGINE[command];
+ if (!load) return false;
+ if (load === true) return dispatchConnectedCommand(command, null as never, args).then(() => true);
+ const run = await load();
+ // The engine is never read on the help path; passing a placeholder keeps the
+ // handler signatures untouched. skillopt already declares `BrainEngine | null`
+ // for exactly this reason.
+ await run(null as never, args);
+ return true;
+}
+
+// v114 (#1941): alias -> operation lookup, kept separate from `cliOps` so
+// aliases don't double-list in printHelp's auto-generated section. Collisions
+// with a primary CLI name, a CLI_ONLY command, or another alias throw at module
+// load — a silent route-shadow is worse than a loud boot failure. CLI_ONLY is
+// derived from the command table (src/cli/command-table.ts), so the check runs
+// over every table record. Exported for the table test's collision case.
+export function buildCliAliases(
+ ops: readonly Operation[],
+ primary: ReadonlyMap<string, Operation>,
+ cliOnly: ReadonlySet<string>,
+): Map<string, Operation> {
+ const aliases = new Map<string, Operation>();
+ for (const op of ops) {
+ if (op.cliHints?.hidden) continue;
+ for (const alias of op.cliHints?.aliases ?? []) {
+ if (primary.has(alias) || cliOnly.has(alias) || aliases.has(alias)) {
+ throw new Error(
+ `CLI alias collision: '${alias}' (op '${op.name}') conflicts with an existing ` +
+ `command or alias. Rename the alias in src/core/operations.ts.`,
+ );
+ }
+ aliases.set(alias, op);
+ }
+ }
+ return aliases;
+}
+
+export const cliAliases = buildCliAliases(operations, cliOps, CLI_ONLY);
+
+/**
+ * Emit the self-upgrade marker on the hot path. CACHE-READ-ONLY: a statSync +
+ * read, sub-ms. On a stale/missing cache it kicks a DETACHED, single-flighted
+ * `gbrain check-update --refresh-cache` and emits nothing this run. NEVER
+ * blocks a command and NEVER throws (the marker must not break any command).
+ * Mode resolution is file-plane only (no DB; thin clients have no local DB).
+ */
+function maybeEmitUpdateMarker(command: string): void {
+ try {
+ if (process.env.GBRAIN_SKIP_STARTUP_HOOKS) return;
+ // Never run during the test suite: tests spawn the CLI hundreds of times,
+ // each with a fresh (stale-cache) GBRAIN_HOME, which would otherwise fire a
+ // detached `gbrain check-update --refresh-cache` per invocation and saturate
+ // the machine with real network calls. Bun sets NODE_ENV=test.
+ if (process.env.NODE_ENV === 'test') return;
+ if (STARTUP_HOOK_SKIP_COMMANDS.has(command)) {
+ // We ARE the update path — skip self-check AND mark children so any
+ // `gbrain post-upgrade` / `gbrain features` they spawn don't re-enter.
+ process.env.GBRAIN_SKIP_STARTUP_HOOKS = '1';
+ return;
+ }
+ if (getCliOptions().quiet) return;
+
+ // JUST_UPGRADED: one-time confirmation after an upgrade (any mode).
+ try {
+ const jpath = justUpgradedPath();
+ if (existsSync(jpath)) {
+ const from = String(readFileSync(jpath, 'utf8')).trim();
+ if (from) process.stderr.write(`JUST_UPGRADED ${from} ${VERSION}\n`);
+ unlinkSync(jpath);
+ }
+ } catch {
+ /* ignore */
+ }
+
+ const cfg = loadConfigFileOnly();
+ const mode = resolveSelfUpgradeMode(cfg);
+ if (mode === 'off') return;
+
+ const now = Date.now();
+ const entry = readUpdateCache();
+ if (entry && isCacheFresh(entry, now)) {
+ // Shared stale/foreign-cache guard (pendingUpgradeVersion): only nag when
+ // the cached latest is strictly newer than the RUNNING binary, and print
+ // the running version — the cache records whatever binary WROTE it.
+ const latest = pendingUpgradeVersion(VERSION, now);
+ if (latest) {
+ // notify mode honors a per-version snooze; auto mode ignores it.
+ if (mode === 'notify' && isSnoozeActive(readSnooze(), latest, now)) return;
+ // The raw `UPGRADE_AVAILABLE <cur> <latest>` line is a MACHINE marker
+ // (parsed by the self-upgrade skill / MCP via parseMarker). A human at
+ // an interactive terminal should never see the token as the literal
+ // first line of output — so emit it only when stderr is NOT a TTY
+ // (agent harnesses capture stderr non-interactively and still get it).
+ // GBRAIN_FORCE_UPGRADE_MARKER=1 forces it for the rarer agent harness
+ // that allocates a PTY yet still parses the token. The human sentence
+ // prints on both.
+ if (!process.stderr.isTTY || process.env.GBRAIN_FORCE_UPGRADE_MARKER === '1') {
+ process.stderr.write(`UPGRADE_AVAILABLE ${VERSION} ${latest}\n`);
+ }
+ process.stderr.write(
+ `gbrain ${VERSION} -> ${latest} available. Run: gbrain self-upgrade\n`,
+ );
+ }
+ return;
+ }
+
+ // Stale/missing cache → kick a detached, single-flighted refresh. The child
+ // (`check-update --refresh-cache`) single-flights via the refresh lock and
+ // writes the cache for the NEXT invocation. We never wait on it.
+ // Spawn OURSELVES (hook.ts spawnDetachedPush pattern), not `gbrain` from
+ // PATH — a different (older) binary on PATH would write ITS version into
+ // the cache and make the marker lie about what is installed here.
+ try {
+ const exec = process.execPath ?? '';
+ const refreshArgs = ['check-update', '--refresh-cache'];
+ // Detect compiled-vs-dev by the RUNTIME's basename, not our own — a
+ // published binary keeps its official name (`gbrain-darwin-arm64`, a
+ // `gb` shim), so matching `/gbrain$/` on execPath would misfire and
+ // prepend the `/$bunfs/root/...` virtual entrypoint (process.argv[1] in
+ // a compiled Bun binary), producing an unknown-command child that never
+ // refreshes. Dev mode runs under `bun`/`node`; anything else IS the
+ // compiled binary and re-execs itself directly.
+ const isDevRuntime = /[/\\](bun|node)(\.exe)?$/.test(exec);
+ const argv = isDevRuntime ? [process.argv[1], ...refreshArgs] : refreshArgs;
+ const child = spawn(exec, argv, {
+ detached: true,
+ stdio: 'ignore',
+ env: { ...process.env, GBRAIN_SKIP_STARTUP_HOOKS: '1' },
+ });
+ // ChildProcess is an EventEmitter — an unhandled 'error' would throw
+ // uncaught. Swallow it; the refresh is best-effort.
+ child.on('error', () => {});
+ child.unref();
+ } catch {
+ /* spawn failed — fail-open, no refresh this run */
+ }
+ } catch {
+ /* the update marker must never break a command */
+ }
+}
+
+async function main() {
+ // cwd-.env quarantine → ~/.gbrain/.env → #3688 guardrails loader (fail-closed).
+ await runCliPreflight();
+
+ // Parse global flags (--quiet / --progress-json / --progress-interval)
+ // BEFORE command dispatch, so `gbrain --progress-json doctor` works.
+ // The stripped argv is what the command sees.
+ const rawArgs = process.argv.slice(2);
+ const { cliOpts, rest: args } = parseGlobalFlags(rawArgs);
+ setCliOptions(cliOpts);
+
+ let command = args[0];
+ installCliRoutingFor(() => command, args);
+
+ if (!command || command === '--help' || command === '-h') {
+ printHelp();
+ return;
+ }
+
+ if (command === '--version' || command === 'version') {
+ console.log(`gbrain ${VERSION}`);
+ return;
+ }
+
+ if (command === '--tools-json') {
+ const { printToolsJson } = await import('../commands/tools-json.ts');
+ await printToolsJson();
+ return;
+ }
+
+ // #6114: decided once, before startup side effects; help never runs the command (grammar: cli/subcommands.ts).
+ const helpRequested = cliHelpRequested(command, args.slice(1));
+
+ if (command === 'extract' && !args.some(arg => arg === '--help' || arg === '-h')
+ && args.some(arg => ['--repair-attendance', '--apply-preview', '--backup-verified', '--confirm', '--checkpoint'].includes(arg.split('=')[0]))) {
+ const { runAttendanceRepairCli } = await import('../commands/extract-attendance-repair.ts');
+ await runAttendanceRepairCli(args.slice(1), cliOpts.brain);
+ return;
+ }
+
+ // v0.42 self-upgrade: ride this invocation as an update heartbeat. Cache-read-
+ // only, fail-open, never blocks. Skips the update path's own commands + sets
+ // GBRAIN_SKIP_STARTUP_HOOKS for their children. Runs for every real command.
+ if (!helpRequested) {
+ maybeEmitUpdateMarker(command);
+
+ // Monthly backup-coverage nag (cache-read-only, bounded by the nag gate;
+ // guards + skip set live inside the helper — one place, every call site).
+ const { maybeEmitBackupNag } = await import('../core/backup/status-file.ts');
+ maybeEmitBackupNag(command, { quiet: getCliOptions().quiet === true });
+ // #5137: once per process, when an env key shadows a different config key; never from hook commands.
+ if (command !== 'hook') (await import('../core/ai/key-warnings.ts')).warnShadowedProviderKeys();
+ }
+
+ const subArgs = args.slice(1);
+
+ // DX alias: `ask` is a natural-language alias for `query`
+ if (command === 'ask') {
+ command = 'query';
+ }
+ dispatchedCommand = command;
+
+ // Local patch 2026-06-11 — mark one-shot CLI processes so the facts
+ // backstop routes absorb work to the durable jobs worker instead of the
+ // in-process queue that the exit teardown drains-then-aborts after ~1-2s
+ // (the `pipeline_error: [chat(...)] The operation was aborted.` class in
+ // ingest_log). Daemons keep the in-process queue: their event loop
+ // outlives the work. See src/core/facts/cli-process-mode.ts.
+ if (!['serve', 'jobs', 'autopilot'].includes(command)) {
+ const { markShortLivedCliProcess } = await import('../core/facts/cli-process-mode.ts');
+ markShortLivedCliProcess();
+ }
+
+ // Per-command --help; the scan stops at `--` (`agent run -- --help` submits the prompt). Router
+ // commands print usage here, so `<cmd> <sub> --help` never reaches the subcommand (#6114).
+ if (helpRequested) {
+ if (await printRouterHelp(command, subArgs)) return;
+ if (await printCuratedHelp(command, subArgs)) return;
+ // `eval brainbench` ships a published foreign-runner flag surface — its
+ // own usage() must win over the generic eval stub (codex P3). Fall
+ // through to handleCliOnly's no-DB brainbench route, which prints it.
+ const selfHelpSub = command === 'eval' && subArgs[0] === 'brainbench';
+ const op = cliOps.get(command) ?? cliAliases.get(command);
+ if (op && !selfHelpSub) {
+ printOpHelp(op, command);
+ return;
+ }
+ if (!selfHelpSub && CLI_ONLY.has(command) && !CLI_ONLY_SELF_HELP.has(command)) {
+ printCliOnlyHelp(command);
+ return;
+ }
+ // Self-help members whose handler answers --help before it touches the
+ // engine. Without this they fall through to the normal dispatch, which
+ // connects first — so `gbrain models --help` on a machine with no brain
+ // exits 1 with "No brain configured", and the handler's own help block is
+ // unreachable. That is the state a reader is most likely to be in.
+ if (await printSelfHelpWithoutEngine(command, subArgs)) return;
+ }
+
+ // #6114: destructive subcommands refuse a token they would ignore (exit 2) before dispatch.
+ const strictRefusal = helpRequested ? null : strictArgsRefusal(command, subArgs);
+ if (strictRefusal) exitCliError(strictRefusal, command);
+
+ // T5 — `gbrain search modes|stats|tune` is the read-only config dashboard,
+ // NOT a free-text search for the literal word "modes". Free-text
+ // `gbrain search "<query>"` falls through to the cheap-hybrid `search` op
+ // below (T4). Preserves the v0.41.6.0 read-only connect+dispatch timeout.
+ if (command === 'search' && ['modes', 'stats', 'tune', 'diagnose'].includes(subArgs[0] ?? '')) {
+ const { withTimeout, OperationTimeoutError } = await import('../core/timeout.ts');
+ const isDiagnose = subArgs[0] === 'diagnose';
+ // Gap-closure wave [OV6]: thin clients route the read-only dashboard
+ // forms via search_modes/search_stats/search_tune instead of fabricating
+ // a scratch PGLite; --reset/--apply/diagnose fall through to the refusal.
+ const cfgSearch = loadConfig();
+ if (isThinClient(cfgSearch)) {
+ const { routeThinClientCommand } = await import('../commands/thin-client-routing.ts');
+ if (await routeThinClientCommand(cfgSearch!, 'search', subArgs)) return;
+ refuseThinClient('search', cfgSearch!.remote_mcp!.mcp_url);
+ }
+ const label = 'gbrain search';
+ // diagnose runs real retrieval (keyword + vector + hybrid) so it gets a
+ // longer deadline than the read-only dashboard.
+ const timeoutMs = isDiagnose ? 60_000 : 10_000;
+ let engine: BrainEngine;
+ try {
+ engine = await withTimeout(connectEngine(), timeoutMs, `${label}: connect`);
+ } catch (e) {
+ if (e instanceof OperationTimeoutError) { console.error(`${e.label} timed out.`); process.exit(124); }
+ throw e;
+ }
+ try {
+ if (isDiagnose) {
+ const { runSearchDiagnose } = await import('../commands/search-diagnose.ts');
+ await withTimeout(runSearchDiagnose(engine, subArgs), timeoutMs, label);
+ } else {
+ const { runSearch } = await import('../commands/search.ts');
+ await withTimeout(runSearch(engine, subArgs), timeoutMs, label);
+ }
+ } finally {
+ // #2084: `search diagnose` runs real hybrid retrieval (arms search-cache
+ // writes) — route through the shared bounded teardown like every other
+ // one-shot path. The connect-timeout process.exit(124) above is reviewed
+ // and intentionally unchanged: no engine exists at that point.
+ await finishCliTeardown({ engine });
+ }
+ return;
+ }
+
+ if (command === 'sources' && subArgs[0] === 'inspect') {
+ const { runCompanyBrainInspection } = await import('../commands/company-brain-inspect.ts');
+ await runCompanyBrainInspection(subArgs.slice(1));
+ return;
+ }
+ if (command === 'sources' && subArgs[0] === 'connect') {
+ const { runCompanyBrainConnect } = await import('../commands/company-brain-connect.ts');
+ await runCompanyBrainConnect(subArgs.slice(1), () => connectEngine({ probeOnly: true }));
+ return;
+ }
+ if (command === 'sources' && subArgs[0] === 'demo' && subArgs[1] === 'company-brain') {
+ const { runCompanyBrainDemoCli } = await import('../commands/company-brain-demo.ts');
+ await runCompanyBrainDemoCli(subArgs.slice(2));
+ return;
+ }
+
+ // #2185: strict unknown-flag validation — pre-dispatch, pre-engine. A flag
+ // no handler consults (the repro: `init --migrate-only --dry-run` applying
+ // REAL migrations while the user asked for a rehearsal) fails loud here
+ // instead of silently doing the destructive thing. Runs after the --help
+ // short-circuit so `gbrain x --help` never errors; runs before any dispatch
+ // or engine connect so the error is instant and side-effect-free.
+ {
+ const migrationError = migrationCliArgumentError(command, subArgs, rawArgs);
+ const unknown = migrationError?.flag ?? validateCommandFlags(command, subArgs);
+ if (unknown) {
+ // Message contract shared with init.ts's in-handler check: lowercase
+ // 'unknown flag' on stderr; --json gets one envelope whose legacy keys
+ // (status, reason 'invalid_flag', message) are pinned by
+ // test/init-migrate-only.test.ts. D1/D3: exit 2 + did-you-mean.
+ const message = migrationError?.message ?? `unknown flag ${unknown} for 'gbrain ${command}'`;
+ const flagOp = cliOps.get(command) ?? cliAliases.get(command);
+ const curated = findCliCommand(command)?.help;
+ const known = curated ? (await curated()).help.flags.map(f => f.name) : CLI_FLAG_REGISTRY[command] ?? Object.keys(flagOp?.params ?? {}).map(k => `--${k.replace(/_/g, '-')}`);
+ exitCliError(unknownFlagError(command, unknown, message, known), command, { legacy: { status: 'error', reason: 'invalid_flag', message } });
+ }
+ const curated = await curatedFlagError(command, subArgs);
+ if (curated) exitCliError(curated, command);
+ }
+
+ // DB-free durability pull (v0.42.44 D2): the harden cron calls
+ // `gbrain sources pull --path <dir>` every ~30 min. It must NOT open PGLite
+ // (a live long-lived session holds the single-writer lock), so handle it
+ // BEFORE connectEngine. The `sources pull <id>` form (no --path) still routes
+ // through handleCliOnly → runSources with an engine.
+ if (command === 'sources' && subArgs[0] === 'pull' && subArgs.includes('--path')) {
+ const { runPull } = await import('../commands/sources-harden.ts');
+ await runPull(null, subArgs.slice(1));
+ return;
+ }
+
+ // CLI-only commands
+ if (CLI_ONLY.has(command)) {
+ await handleCliOnly(command, subArgs);
+ return;
+ }
+
+ await runSharedOperation(command, subArgs, cliOpts);
+}
+
+/**
+ * Shared-operation dispatch (every non-CLI_ONLY command and alias): parse the
+ * op's args, route thin clients over MCP, delegate to a live PGLite owner, or
+ * connect and run the handler with the read wallclock bound and teardown.
+ * Split out of main() (refactor wave 1, W4 cli); order and exits unchanged.
+ */
+async function runSharedOperation(command: string, subArgs: string[], cliOpts: CliOptions): Promise<void> {
+ // Shared operations (fall through to aliases, e.g. link-add -> add_link)
+ const op = cliOps.get(command) ?? cliAliases.get(command);
+ if (!op) exitCliError(usageError(`Unknown command: ${command}`, 'Run `gbrain --help` for available commands.', { code: 'unknown_command' }), command);
+
+ // v0.31.1 (Issue #734, CDX-1): parse CLI args BEFORE engine connect so
+ // the routing seam below can decide local-vs-remote without paying a
+ // PGLite migration replay on thin-client installs. The arg parser, image
+ // transform, and required-param check are all engine-free; refactoring
+ // them out of the engine try/catch is safe and unlocks routing.
+ const params = parseOpArgs(op, subArgs);
+
+ // #3513: stdin fill moved out of parseOpArgs so a non-TTY stdin with no
+ // piped input can't block the parse forever — the bounded read leaves the
+ // param unset on timeout and the required-param check below fails fast.
+ await applyStdinParam(op, params);
+
+ // v0.27.1 (`gbrain query --image <path>`): swap the `image` param from
+ // a filesystem path into base64 bytes + mime. The op accepts base64; the
+ // CLI accepts a path. Helper is exported so tests can exercise the
+ // transform without spawning a subprocess.
+ if (op.name === 'query' && typeof params.image === 'string' && params.image.length > 0) {
+ try {
+ const { path, base64, mime } = resolveQueryImage(
+ params.image as string,
+ (params.image_mime as string) || undefined,
+ );
+ params.image = base64;
+ params.image_mime = mime;
+ void path;
+ } catch (err) {
+ exitCliError(usageError(err instanceof Error ? err.message : String(err), 'Pass --image a readable PNG/JPEG/WebP/GIF path.'), command);
+ }
+ }
+
+ // Validate required params before calling handler. v0.27.1: the
+ // `query` op's positional `query` is required only when --image is
+ // NOT supplied. The runtime altRequired check below overrides the
+ // generic required-flag check for that op.
+ const queryHasAlt = op.name === 'query' && typeof params.image === 'string' && params.image.length > 0;
+ for (const [key, def] of Object.entries(op.params)) {
+ if (def.required && params[key] === undefined) {
+ if (queryHasAlt && key === 'query') continue;
+ const cliName = op.cliHints?.name || op.name;
+ const positional = op.cliHints?.positional || [];
+ const usage = positional.map(p => `<${p}>`).join(' ');
+ exitCliError(usageError(`Missing required parameter '${key}' for 'gbrain ${cliName}'.`, `Usage: gbrain ${cliName} ${usage}`.trimEnd() + ` (see \`gbrain ${cliName} --help\`).`), command);
+ }
+ }
+
+ // v0.31.1 (Issue #734, CDX-1 routing seam): on thin-client installs,
+ // route every non-localOnly op through callRemoteTool instead of opening
+ // the empty local PGLite. localOnly ops can't run on a thin client at all
+ // (no local engine, server intentionally hides them) — refuse with hint.
+ // Fix for the silent-empty-results bug class that motivated this whole release.
+ const cfgPre = loadConfig();
+ if (isThinClient(cfgPre)) {
+ if (op.localOnly) {
+ refuseThinClient(command, cfgPre!.remote_mcp!.mcp_url);
+ }
+ // A thin client has no local mounts — an explicit --brain cannot be
+ // honored and must not be silently dropped (same loud-beats-silent rule
+ // as applyThinClientSourceScope's --source refusal). Ambient tiers
+ // (GBRAIN_BRAIN_ID / .gbrain-mount) are ignored here, matching the
+ // source axis's ambient-with-nowhere-to-send behavior.
+ if (cliOpts.brain) exitCliError(usageError(THIN_CLIENT_BRAIN_FLAG_MESSAGE, 'Remove --brain, or run from a machine with local mounts (`gbrain mounts list`).'), command);
+ // #2098: the local path resolves --source / GBRAIN_SOURCE / .gbrain-source
+ // inside makeContext (ctx.sourceId), which this route never reaches — so
+ // scope must be mapped onto the op's source_id wire param before the call.
+ let ambientScope: AmbientSourceBinding | null;
+ try {
+ ambientScope = applyThinClientSourceScope(op, params);
+ } catch (e: unknown) {
+ exitCliError(e, command);
+ }
+ await runThinClientRouted(op, params, cfgPre!, cliOpts, ambientScope);
+ return;
+ }
+
+ // Locally --source reaches the op through makeContext (ctx.sourceId); a
+ // per-call --source-id / --all-sources would silently win over it.
+ try {
+ assertSingleSourceScopeFlag(op, params);
+ } catch (e: unknown) {
+ exitCliError(e, command);
+ }
+
+ // The live PGLite owner exposes canonical operations over a dedicated
+ // local socket. Delegate before opening a competing engine connection.
+ {
+ const { runDelegatedCliOperation } = await import('../commands/persistence-delegate.ts');
+ if (await runDelegatedCliOperation(op.name, params, cfgPre, {
+ brain: cliOpts.brain, timeoutMs: cliOpts.timeoutMs ?? undefined,
+ }, formatResult)) return;
+ }
+
+ // No live serve owns the selected brain; connect through the normal lock path.
+ const engine = await connectEngine();
+ // #2084: the teardown contract (bounded drain of every background-work sink,
+ // bounded disconnect, computed-deadline backstop) lives in finishCliTeardown
+ // — see src/core/cli-force-exit.ts for the full design. The hard-deadline
+ // timer arms at TEARDOWN start inside the helper, never before the handler:
+ // the pre-#2084 placement here measured handler + teardown combined, so a
+ // slow-but-healthy query burned the teardown budget (the flat-10s-banner
+ // bug) and any >10s op was force-killed mid-run with exit 0. The explicit
+ // process exit happens once, in the import.meta.main seam at the bottom of
+ // this file — NOT here.
+
+ // v0.42.41.0 (merged): wallclock bound for READ-scope op handlers. With the
+ // teardown backstop correctly scoped to teardown, a genuinely WEDGED read
+ // handler (hung pooler connection mid-query) would otherwise hang the CLI
+ // forever — the #1633 zombie class the old pre-try timer accidentally
+ // bounded at 10s. 180s sits far above any healthy slow-pooler run
+ // (6-10s/connection); --timeout=Ns overrides. Writes/admin stay unbounded:
+ // a long import/embed must never be killed by a default deadline. On
+ // timeout the abandoned handler may hold ref'd sockets — harmless here,
+ // because the import.meta.main seam exits explicitly on every one-shot path.
+ const READ_OP_TIMEOUT_MS = 180_000;
+
+ try {
+ const { withTimeout, OperationTimeoutError } = await import('../core/timeout.ts');
+ const wallclockMs = getCliOptions().timeoutMs ?? READ_OP_TIMEOUT_MS;
+ const onWallclockTimeout = (e: InstanceType<typeof OperationTimeoutError>) => {
+ const hint = getCliOptions().timeoutMs
+ ? ''
+ : ` (default ${e.ms}ms; pass --timeout=Ns to override)`;
+ console.error(`${e.label} timed out${hint}.`);
+ // 124 = timeout convention (matches the read-only dispatch path). Set
+ // through the verdict channel — a raw process.exitCode write is invisible
+ // to the exit seam and PGLite's WASM runtime can scribble over it.
+ setCliExitVerdict(124);
+ };
+
+ // Context build does DB I/O (resolveSourceId) and runs for EVERY op —
+ // a wedged pooler connection here would otherwise hang reads, writes,
+ // and admin alike with no bound at all (adversarial review finding).
+ let ctx: Awaited<ReturnType<typeof makeContext>>;
+ try {
+ ctx = await withTimeout(
+ makeContext(engine, params, op),
+ wallclockMs,
+ `gbrain ${command}: context`,
+ );
+ } catch (e: unknown) {
+ if (e instanceof OperationTimeoutError) {
+ onWallclockTimeout(e);
+ return; // the finally drains + disconnects; the import.meta.main seam exits
+ }
+ throw e;
+ }
+
+ let rawResult: unknown;
+ if (op.scope === 'read') {
+ try {
+ rawResult = await withTimeout(
+ op.handler(ctx, params),
+ wallclockMs,
+ `gbrain ${command}`,
+ );
+ } catch (e: unknown) {
+ if (e instanceof OperationTimeoutError) {
+ onWallclockTimeout(e);
+ return; // the finally drains + disconnects; the import.meta.main seam exits
+ }
+ throw e;
+ }
+ } else {
+ rawResult = await op.handler(ctx, params);
+ }
+ // ENG-2 (renderer parity by data shape): JSON-round-trip the local-engine
+ // path's return value so renderers see the same shape they'd see on the
+ // routed path. Date → ISO string; bigint → string (postgres.js shape);
+ // Buffer → object. Microsecond-cost; eliminates a whole drift bug class.
+ const { result, stderr: noticeText } = applyCliOpNotices(normalizeLocalResult(rawResult), params.json === true);
+ const output = formatResult(op.name, result, params);
+ // Awaited delivery (#3423): queued stdout writes past 64KiB lose their
+ // tail to a slow pipe reader when the exit grace lapses — see
+ // writeStdoutFinal.
+ if (output) await writeStdoutFinal(output);
+ if (noticeText) process.stderr.write(noticeText);
+ // #4488: an op that reports failure IN-BAND (`{status: 'error'}` — e.g.
+ // put_page over unparseable frontmatter) used to print the envelope and
+ // exit 0, so scripts read a never-written page as success. Echo the error
+ // to stderr and set the failure verdict. No-op statuses ('skipped',
+ // 'unchanged', …) stay exit 0 — a no-op is not a failure.
+ if (
+ typeof result === 'object' && result !== null && !Array.isArray(result) &&
+ (result as { status?: unknown }).status === 'error'
+ ) {
+ const detail = (result as { error?: unknown }).error;
+ console.error(
+ `gbrain ${command}: operation reported status 'error'` +
+ (typeof detail === 'string' && detail ? ` — ${detail}` : '') + '.',
+ );
+ setCliExitVerdict(1);
+ }
+ maybePrintConceptNudge(op.name, params);
+ } catch (e: unknown) {
+ // v0.42.20.0 (codex D4): on error, set exitCode + return so the `finally`
+ // STILL runs (drains every background-work sink + disconnects). A bare
+ // process.exit(1) here would skip the finally → skip the drain + disconnect
+ // (leaves facts/cache/eval-capture writes racing teardown). The finally's
+ // drain bounds teardown; the hard-deadline timer armed at teardown entry
+ // bounds a hung one.
+ // #5232: the reporter owns the write verdict; never overwrite it.
+ const { reportPersistenceCliError } = await import('../commands/persistence-delegate.ts');
+ const receipt = !(e instanceof OperationError) || !!e.writeRequest;
+ if (!receipt || !await reportPersistenceCliError(e, params.json === true || !!(e as OperationError)?.writeRequest)) {
+ setCliExitVerdict(writeCliError(e, command));
+ }
+ } finally {
+ // 1s per-sink drain budget: read paths with no pending work pay the ~0ms
+ // fast path; capture/import that DO enqueue pay up to 1s (+ facts shutdown
+ // grace) while in-flight Haiku finishes (#1762 drain-before-disconnect).
+ await finishCliTeardown({ engine, drainTimeoutMs: 1000 });
+ }
+}
+
+function hasHelpFlag(args: string[]): boolean {
+ return args.includes('--help') || args.includes('-h');
+}
+
+function printCliOnlyHelp(command: string) {
+ console.log(`Usage: gbrain ${command}`);
+ console.log('');
+ console.log(`gbrain ${command} - run gbrain --help for the full command list.`);
+}
+
+/**
+ * v0.31.1 (Issue #734, CDX-1): route a shared op through the remote MCP
+ * server instead of running it locally. Called from main() when
+ * `isThinClient(cfg) && !op.localOnly`.
+ *
+ * Timeout policy (ENG-4): user override via --timeout=Ns wins; otherwise
+ * 180s for `think` (LLM calls), 30s for everything else.
+ *
+ * Error policy: callRemoteTool normalizes every failure to RemoteMcpError;
+ * the exhaustive switch requires a renderer for every reason variant.
+ *
+ * Renderer policy: unpackToolResult parses MCP text and shares formatResult
+ * with the local-engine path, enforcing parity through the result shape.
+ */
+async function runThinClientRouted(
+ op: Operation,
+ params: Record<string, unknown>,
+ cfg: GBrainConfig,
+ cliOpts: CliOptions,
+ ambientScope: AmbientSourceBinding | null = null,
+): Promise<void> {
+ // ENG-4: per-op timeout default; user override wins.
+ const defaultTimeoutMs = op.name === 'think' ? 180_000 : 30_000;
+ const timeoutMs = cliOpts.timeoutMs ?? defaultTimeoutMs;
+
+ // SIGINT support: aborts in-flight HTTP cleanly (exit 130 is the standard
+ // SIGINT exit code; our error switch maps `network/aborted` to that).
+ const sigintController = new AbortController();
+ const onSigint = () => {
+ sigintController.abort(new Error('SIGINT'));
+ };
+ process.on('SIGINT', onSigint);
+
+ // v0.31.1 (Issue #734, cherry-pick B): print identity banner to stderr
+ // BEFORE the routed call. Banner failure suppresses the banner only —
+ // never the underlying command. Suppression honors --quiet, non-TTY,
+ // and GBRAIN_NO_BANNER=1.
+ await printIdentityBannerBestEffort(cfg, cliOpts, sigintController.signal);
+
+ try {
+ const raw = await callRemoteTool(cfg, op.name, params, {
+ timeoutMs,
+ signal: sigintController.signal,
+ ...(op.mutating ? { writeWaitMs: currentCliWriteWait().waitMs } : {}),
+ });
+ // T15/FOV-1: lift the server's retrieval meta off the envelope before
+ // unpacking (old servers lack _meta — capture is simply skipped).
+ const envelopeMeta = extractResponseMeta(raw);
+ if (envelopeMeta?.retrieval) captureRetrievalMeta('retrieval', envelopeMeta.retrieval);
+ checkHostHonoredParams(op, params, raw);
+ const result = unpackToolResult(raw);
+ hintAmbientNarrowing(op, params, result, ambientScope);
+ const skew = deliveryVersionSkewWarning(op.name, params, envelopeMeta?.retrieval as Record<string, unknown> | undefined, result);
+ if (skew) process.stderr.write(skew + '\n');
+ const output = formatResult(op.name, result, params);
+ // Awaited delivery (#3423) — same contract as the local-engine path.
+ if (output) await writeStdoutFinal(output);
+ maybePrintConceptNudge(op.name, params);
+ } catch (e: unknown) {
+ if (e instanceof RemoteMcpError) {
+ const { reportPersistenceCliError } = await import('../commands/persistence-delegate.ts');
+ if (await reportPersistenceCliError(e, params.json === true)) {
+ process.off('SIGINT', onSigint);
+ process.exit(sigintController.signal.aborted ? 130 : currentExitCode());
+ }
+ // D1: a server tool error renders its own code/fix; --json gets the one v1
+ // envelope on stdout while transport failures keep their human text on stderr.
+ const scopeDenied = isScopeErrorCode(e.detail?.code, e.detail?.canonical_code, e.detail?.reason);
+ if ((e.reason === 'tool_error' && !scopeDenied) || e.detail?.code === 'serve_status_only') { process.off('SIGINT', onSigint); exitCliError(e, op.cliHints?.name ?? op.name); }
+ const failExit = params.json === true ? writeCliError(e, op.cliHints?.name ?? op.name, { stderr: false }) : 1;
+ const url = cfg.remote_mcp!.mcp_url;
+ switch (e.reason) {
+ case 'config':
+ console.error(e.message);
+ break;
+ case 'discovery':
+ console.error(`OAuth discovery failed at ${cfg.remote_mcp!.issuer_url}.`);
+ console.error('Run `gbrain remote doctor` for details.');
+ break;
+ case 'auth':
+ console.error('OAuth auth failed.');
+ console.error('On the host, re-register your client:');
+ console.error(' gbrain auth register-client <name> --grant-types client_credentials --scopes read,write,admin');
+ break;
+ case 'auth_after_refresh':
+ console.error('OAuth auth failed after token refresh. Credentials may have been revoked.');
+ console.error('Run `gbrain remote doctor` to confirm.');
+ break;
+ case 'rate_limited':
+ console.error(`OAuth /token is rate-limited by the server (HTTP 429)${e.detail?.retry_after_s !== undefined ? `; retry in ${e.detail.retry_after_s}s` : ''}.`);
+ console.error('This is the host\'s token-mint budget, not a connectivity problem; the host operator can raise GBRAIN_OAUTH_TOKEN_RATE_LIMIT_MAX.');
+ break;
+ case 'token':
+ console.error(`${e.message} (issuer ${cfg.remote_mcp!.issuer_url}).`);
+ console.error('Run `gbrain remote doctor` for details.');
+ break;
+ case 'network':
+ if (e.detail?.kind === 'timeout') {
+ const hint = cliOpts.timeoutMs ? '' : ` (default ${defaultTimeoutMs}ms; pass --timeout=Ns to override)`;
+ console.error(`Request to ${url} timed out${hint}.`);
+ } else if (e.detail?.kind === 'aborted') {
+ console.error('Request aborted.');
+ process.off('SIGINT', onSigint);
+ process.exit(130);
+ } else {
+ console.error(`Cannot reach ${url}. Run \`gbrain remote doctor\` for details.`);
+ }
+ break;
+ case 'tool_error':
+ console.error('Missing OAuth scope on this client.');
+ console.error('On the host, re-register the client with broader scopes:');
+ console.error(' gbrain auth register-client <name> --grant-types client_credentials --scopes read,write,admin');
+ break;
+ case 'parse':
+ console.error('Server response was malformed. Run `gbrain remote doctor`.');
+ break;
+ default: {
+ // Exhaustive switch sentinel (TS `never` — fails to build if a
+ // new RemoteMcpErrorReason variant is added without a case).
+ const _exhaustive: never = e.reason;
+ void _exhaustive;
+ console.error(`Unhandled remote error: ${e.message}`);
+ }
+ }
+ process.off('SIGINT', onSigint);
+ process.exit(failExit);
+ }
+ // Defense in depth: callRemoteTool's contract is that everything is
+ // RemoteMcpError. If a plain Error escapes, render it generically — but
+ // this should never happen post-CDX-4.
+ process.off('SIGINT', onSigint);
+ exitCliError(e, op.cliHints?.name ?? op.name);
+ } finally {
+ process.off('SIGINT', onSigint);
+ }
+}
+
+// ============================================================================
+// v0.31.1 (Issue #734, cherry-pick B): thin-client identity banner.
+//
+// Prints "[thin-client → <host> · brain: 102k pages, 265k chunks · vX.Y.Z]"
+// to stderr before each routed command, so users (and agents) know they're
+// talking to a real remote brain — not the empty local PGLite that motivated
+// this whole release.
+//
+// Cache: 60s TTL, in-memory Map keyed by mcp_url. Cross-process file cache
+// is deferred (marginal benefit; one mint per CLI process is fine).
+// Suppression: --quiet, non-TTY, GBRAIN_NO_BANNER=1.
+// Failure mode: any error in fetching identity → suppress banner; underlying
+// command runs normally. Banner is observability, not load-bearing.
+// ============================================================================
+
+export interface BrainIdentity {
+ version: string;
+ engine: 'postgres' | 'pglite';
+ page_count: number;
+ chunk_count: number;
+ last_sync_iso: string | null;
+}
+
+interface CachedIdentity {
+ identity: BrainIdentity;
+ cached_at_ms: number;
+}
+
+const IDENTITY_TTL_MS = 60_000;
+const identityCache = new Map<string, CachedIdentity>();
+
+export function bannerSuppressed(cliOpts: CliOptions): boolean {
+ if (cliOpts.quiet) return true;
+ if (process.env.GBRAIN_NO_BANNER === '1') return true;
+ // Non-TTY default is suppressed (clean pipes); explicit env-flag overrides.
+ if (!process.stderr.isTTY && process.env.GBRAIN_BANNER !== '1') return true;
+ return false;
+}
+
+function formatPageCount(n: number): string {
+ if (n >= 1000) {
+ const k = (n / 1000).toFixed(n >= 100_000 ? 0 : 1);
+ return `${k}k`;
+ }
+ return String(n);
+}
+
+function formatBanner(mcpUrl: string, id: BrainIdentity): string {
+ const host = mcpUrl.replace(/^https?:\/\//, '').split('/')[0];
+ const counts = `brain: ${formatPageCount(id.page_count)} pages, ${formatPageCount(id.chunk_count)} chunks`;
+ return `[thin-client → ${host} · ${counts} · v${id.version}]`;
+}
+
+async function fetchIdentity(
+ cfg: GBrainConfig,
+ signal: AbortSignal,
+): Promise<BrainIdentity> {
+ // 2s timeout for the banner fetch — must not delay the underlying command.
+ const raw = await callRemoteTool(cfg, 'get_brain_identity', {}, {
+ timeoutMs: 2000,
+ signal,
+ });
+ const id = unpackToolResult<BrainIdentity>(raw);
+ return id;
+}
+
+async function printIdentityBannerBestEffort(
+ cfg: GBrainConfig,
+ cliOpts: CliOptions,
+ signal: AbortSignal,
+): Promise<void> {
+ if (bannerSuppressed(cliOpts)) return;
+ const mcpUrl = cfg.remote_mcp?.mcp_url;
+ if (!mcpUrl) return;
+
+ // Cache lookup keyed by mcp_url so switching hosts via `gbrain init`
+ // invalidates cleanly even within a long-lived process.
+ const cached = identityCache.get(mcpUrl);
+ if (cached && Date.now() - cached.cached_at_ms < IDENTITY_TTL_MS) {
+ process.stderr.write(formatBanner(mcpUrl, cached.identity) + '\n');
+ // v0.31.11: detect remote-version drift, prompt user to upgrade.
+ // bannerIsSuppressed=false here — the early return above guaranteed it.
+ await maybePromptForUpgrade(cfg, cached.identity, cliOpts, false);
+ return;
+ }
+
+ // Cache miss — fetch. Failure is non-fatal: banner is observability,
+ // never load-bearing for the underlying command.
+ try {
+ const id = await fetchIdentity(cfg, signal);
+ identityCache.set(mcpUrl, { identity: id, cached_at_ms: Date.now() });
+ process.stderr.write(formatBanner(mcpUrl, id) + '\n');
+ // v0.31.11: detect remote-version drift, prompt user to upgrade.
+ await maybePromptForUpgrade(cfg, id, cliOpts, false);
+ } catch {
+ // Swallow. Banner suppressed; main command continues. The CDX-4
+ // hardened callRemoteTool will surface the same error class on the
+ // actual command call if the host is genuinely unreachable.
+ }
+}
+
+/**
+ * v0.27.1: shared transform for `gbrain query --image <path>` (and any future
+ * CLI surface that takes an image path). Reads the file, base64-encodes,
+ * derives MIME from the extension, enforces the 20MB cap. Exported so tests
+ * can verify the transform without spawning a subprocess.
+ *
+ * Throws Error on any failure (file missing, oversized, etc.). Caller is
+ * responsible for routing to process.exit(1) with a user-facing message.
+ */
+export function resolveQueryImage(
+ imagePath: string,
+ explicitMime?: string,
+): { path: string; base64: string; mime: string } {
+ const bytes = readFileSync(imagePath);
+ if (bytes.length > 20 * 1024 * 1024) {
+ throw new Error(`Error: image too large (${bytes.length} bytes, max 20MB).`);
+ }
+ const base64 = bytes.toString('base64');
+ let mime = explicitMime;
+ if (!mime) {
+ const lower = imagePath.toLowerCase();
+ const mimeFromExt: Record<string, string> = {
+ '.png': 'image/png',
+ '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
+ '.gif': 'image/gif',
+ '.webp': 'image/webp',
+ '.heic': 'image/heic', '.heif': 'image/heif',
+ '.avif': 'image/avif',
+ };
+ const ext = Object.keys(mimeFromExt).find(e => lower.endsWith(e));
+ mime = ext ? mimeFromExt[ext] : 'image/jpeg';
+ }
+ return { path: imagePath, base64, mime };
+}
+
+export function parseOpArgs(op: Operation, args: string[]): Record<string, unknown> {
+ // `gbrain search --explain`: the CLI-local formatter flag also asks the op for score attribution.
+ const params: Record<string, unknown> = op.name === 'search' && args.includes('--explain') ? { explain: true } : {};
+ const positional = op.cliHints?.positional || [];
+ let posIdx = 0;
+
+ let endOfOptions = false; // D6: a bare `--` ends options (as in findUnknownOpFlag); later tokens are positionals
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i];
+ if (arg === '--' && !endOfOptions) { endOfOptions = true; continue; }
+ if (arg.startsWith('--') && !endOfOptions) {
+ // #2185: `--key=value` inline form. Pre-fix this parsed as junk key
+ // 'key=value' and consumed the NEXT token as its value, corrupting
+ // positional parsing. Recognized here so the strict-flag validator and
+ // the parser agree on the idiom.
+ const eq = arg.indexOf('=');
+ if (eq > 2) {
+ const key = arg.slice(2, eq).replace(/-/g, '_');
+ // CLI-local booleans: `--json=<v>` / `--dry-run=<v>` must parse as
+ // booleans, not fall through to the junk-key path (which would
+ // consume the NEXT token as a value and corrupt positional parsing).
+ if (key === 'json' || key === 'dry_run') {
+ params[key] = arg.slice(eq + 1) !== 'false';
+ continue;
+ }
+ const def = op.params[key];
+ if (def) {
+ const raw = arg.slice(eq + 1);
+ params[key] = def.type === 'boolean' ? raw !== 'false' : opParamValue(op, key, def, raw);
+ continue;
+ }
+ }
+ if (arg.startsWith('--no-')) {
+ const positiveKey = arg.slice(5).replace(/-/g, '_');
+ const positiveDef = op.params[positiveKey];
+ if (positiveDef?.type === 'boolean') {
+ params[positiveKey] = false;
+ continue;
+ }
+ }
+ const key = arg.slice(2).replace(/-/g, '_');
+ const paramDef = op.params[key];
+ if (paramDef?.type === 'boolean') {
+ // #4602: a boolean flag followed by the word false used to set the
+ // flag TRUE (silent intent inversion, exit 0) and leave the literal
+ // 'false' to bind to the next unfilled positional slot (data
+ // corruption on multi-positional ops). A LITERAL true/false following
+ // a boolean flag is that flag's value — consume it, matching the
+ // inline `=false` spelling that already worked. Any OTHER following
+ // token keeps the old semantics (flag = true, token stays positional).
+ params[key] = isBooleanLiteral(args[i + 1]) ? args[++i] === 'true' : true;
+ } else if (key === 'json' || key === 'dry_run') {
+ // CLI-local booleans, intentionally NOT on the operation contract
+ // exposed over MCP/tools: json is the formatter flag; dry_run feeds
+ // makeContext's ctx.dryRun. Neither consumes an ARBITRARY value token —
+ // pre-fix, `gbrain delete x --dry-run` (trailing) set NOTHING, so
+ // ctx.dryRun stayed false and the REAL delete ran despite the
+ // rehearsal request (the resurrected #2185 class the red team caught).
+ // #4602: a literal true/false is the one exception — it is this
+ // flag's value (never a plausible positional), same as above.
+ params[key] = isBooleanLiteral(args[i + 1]) ? args[++i] === 'true' : true;
+ } else if (i + 1 < args.length) {
+ // #5700: a known flag of this command in the value slot is a missing
+ // argument, not a value (see op-flag-tokens.ts).
+ if (isKnownOpFlag(op, args[i + 1])) {
+ const flag = `--${key.replace(/_/g, '-')}`;
+ const stdinHint = op.cliHints?.stdin === key ? `; omit ${flag} (or put it last) to read stdin` : '';
+ throw usageError(`${flag} requires a value, but '${args[i + 1]}' is a flag${stdinHint}.`, `Pass ${flag} a value before the next flag (see \`gbrain ${op.cliHints?.name ?? op.name} --help\`).`);
+ }
+ // #2822: a flag silently overwriting an already-set positional is
+ // almost always an argument-plumbing mistake (e.g. `gbrain put
+ // notes.md --content "..."` — the file path landed in `content`
+ // positionally, then --content clobbered it). Warn to stderr; when
+ // the discarded value names an existing file, point at capture --file.
+ const prevValue = params[key];
+ params[key] = opParamValue(op, key, paramDef, args[++i]);
+ if (prevValue !== undefined && prevValue !== params[key]) {
+ let fileHint = '';
+ try {
+ if (typeof prevValue === 'string' && prevValue && existsSync(prevValue)) {
+ fileHint = ` If '${prevValue}' is a file you meant to ingest, use: gbrain capture --file ${prevValue} --slug <slug>`; // nosemgrep: javascript.express.security.injection.raw-html-format.raw-html-format -- stderr text, never HTML
+ }
+ } catch { /* best-effort hint */ }
+ process.stderr.write(
+ `Warning: --${key.replace(/_/g, '-')} overwrites the positional value '${String(prevValue)}'.${fileHint}\n`,
+ );
+ }
+ }
+ } else if (posIdx < positional.length) {
+ const key = positional[posIdx++];
+ const paramDef = op.params[key];
+ params[key] = opParamValue(op, key, paramDef, arg, true);
+ }
+ }
+
+ for (const [key, def] of Object.entries(op.params)) {
+ if ((def.type !== 'object' && def.type !== 'array') || typeof params[key] !== 'string') continue;
+ let value: unknown;
+ const jsonError = () => usageError(`--${key.replace(/_/g, '-')} requires a JSON ${def.type}.`, `Pass JSON, e.g. --${key.replace(/_/g, '-')} '${def.type === 'array' ? '["a","b"]' : '{"key":"value"}'}'.`);
+ try { value = JSON.parse(params[key] as string); } catch { throw jsonError(); }
+ if (def.type === 'array' ? !Array.isArray(value) : value === null || typeof value !== 'object' || Array.isArray(value)) throw jsonError();
+ params[key] = value;
+ }
+ return params;
+}
+
+/**
+ * #3513: read stdin into an op's stdin-capable param without ever blocking
+ * forever. The old inline `readFileSync(0)` in parseOpArgs assumed non-TTY
+ * implies piped content; a non-TTY stdin with NO input (CI step, cron job,
+ * agent harness holding an unwritten pipe open) blocked the read until kill.
+ *
+ * Strategy by fd kind (fstat):
+ * - TTY: skip, as before (interactive input is not an op-param source).
+ * - regular file / /dev/null / anything not a pipe or socket: readFileSync
+ * returns without blocking (`gbrain put x < file`, `< /dev/null` → '').
+ * - FIFO/socket: stream-read with a deadline on the FIRST byte only. A real
+ * pipe (`echo foo | gbrain put x`, heredocs) delivers its first byte
+ * within milliseconds; once data flows only a 60s inactivity timeout
+ * applies, reset on every chunk (slow producers stay supported).
+ * An empty-but-closed pipe (`: | gbrain put x`) EOFs immediately → ''.
+ * A pipe that never delivers a byte times out → param stays unset, so
+ * the existing required-param usage error fires (fail fast, exit 1).
+ *
+ * GBRAIN_STDIN_TIMEOUT_MS overrides the first-byte deadline (default 30s,
+ * stderr notice at 5s). The reader is interaction.ts readStdinBounded (A5).
+ * Exported for tests; called by the op dispatch right after parseOpArgs.
+ */
+export async function applyStdinParam(
+ op: Operation,
+ params: Record<string, unknown>,
+): Promise<void> {
+ // Branch shape (stdin hint + missing param + `!process.stdin.isTTY` gate +
+ // 5MB cap) is pinned by the R4 regression test for PR #1325's Windows fix
+ // (test/cycle/regression-pr-wave-r1-r2-r4.test.ts) — keep the spelling.
+ if (op.cliHints?.stdin && !params[op.cliHints.stdin] && !process.stdin.isTTY) {
+ const content = await readStdinBounded();
+ if (content === null) return; // no input arrived — let the required-param check fail fast
+ // #2822: empty/whitespace-only stdin is NO input, not a real value. A CI
+ // step's `< /dev/null`, an agent harness's empty pipe, or a botched
+ // redirect used to land '' in the param and flow into a destructive
+ // empty write; leaving the param unset makes the required-param usage
+ // error fire instead (same fail-fast as the #3513 timeout path).
+ if (content.trim() === '') return;
+ const MAX_STDIN = 5_000_000; // 5MB
+ if (Buffer.byteLength(content, 'utf-8') > MAX_STDIN) {
+ exitCliError(opError('payload_too_large', `stdin content exceeds ${MAX_STDIN} bytes.`, 'Split the content into smaller inputs.'), op.cliHints?.name ?? op.name);
+ }
+ params[op.cliHints.stdin] = content;
+ }
+}
+
+/**
+ * Legacy-signature shim over interaction.ts readStdinBounded (A5): the full
+ * stdin content, '' for a readable-but-empty stdin, or null for anything else
+ * (first-byte or inactivity timeout, stream error, closed fd). No byte cap
+ * here: applyStdinParam keeps its own 5MB check and message.
+ */
+export async function readStdinBounded(): Promise<string | null> {
+ const r = await readStdinPayload({ maxBytes: Infinity });
+ return r.kind === 'data' ? r.text : r.kind === 'empty' ? '' : null;
+}
+
+/**
+ * #2098: thin-client source scoping. Locally, --source / GBRAIN_SOURCE /
+ * .gbrain-source resolve to ctx.sourceId in makeContext; the thin-client
+ * route short-circuits before that, so `gbrain query --source X` against a
+ * remote brain silently searched unscoped. This runs the engine-free tiers
+ * (flag → env → dotfile; the DB-backed tiers can't run without an engine —
+ * the server's grant scoping covers the rest) and maps the result onto the
+ * op's `source_id` wire param.
+ *
+ * Ops that declare their OWN `source` param (facts add, etc.) are left
+ * untouched — their --source is an op param, not scope. An explicit --source
+ * on an op with no source_id wire param throws (loud beats silent drop);
+ * ambient env/dotfile scope with nowhere to send it is ignored, matching the
+ * pre-fix behavior for non-scopeable ops. Exported for tests.
+ */
+// Ops whose `source_id` wire param is NOT read-scope semantics: get_skill's
+// source_id flips the lookup from host catalog to brain-resident-pack
+// (getResidentSkillDetail). Ambient env/dotfile scope must never leak into
+// these; an explicit --source-id still passes through untouched above.
+const NON_SCOPE_SOURCE_ID_OPS = new Set(['get_skill']);
+
+/**
+ * Returns the ambient binding (GBRAIN_SOURCE / .gbrain-source) that was mapped
+ * onto `source_id`, so an empty result can say what narrowed it; null when the
+ * scope came from a flag or nothing was mapped.
+ */
+export function applyThinClientSourceScope(
+ op: Operation,
+ params: Record<string, unknown>,
+ cwd?: string,
+): AmbientSourceBinding | null {
+ if (opOwnsSource(op)) return null;
+ assertSingleSourceScopeFlag(op, params);
+ const explicit = typeof params.source === 'string' && params.source.length > 0
+ ? (params.source as string)
+ : null;
+ delete params.source; // never a wire param on these ops — don't leak it
+ // Explicit per-call scope already on the wire wins over ambient tiers.
+ if (params.source_id !== undefined || params.all_sources === true) return null;
+ const resolved = resolveSourceIdEngineFree(explicit, cwd);
+ if (!resolved) return null;
+ if (!('source_id' in op.params) || NON_SCOPE_SOURCE_ID_OPS.has(op.name)) {
+ if (explicit) {
+ const hint = NON_SCOPE_SOURCE_ID_OPS.has(op.name)
+ ? `(its source_id parameter is not a scope filter; pass --source-id explicitly if you mean it)`
+ : `(the remote op has no source_id parameter; the server scopes it to your grant)`;
+ throw new Error(
+ `gbrain ${op.cliHints?.name || op.name} does not accept --source on a thin-client install ${hint}.`,
+ );
+ }
+ return null; // ambient env/dotfile scope with nowhere to send it
+ }
+ params.source_id = resolved;
+ if (explicit) return null;
+ const env = process.env.GBRAIN_SOURCE;
+ return { sourceId: resolved, via: env && env.length > 0 ? 'GBRAIN_SOURCE' : '.gbrain-source' };
+}
+
+// Exported for tests (same import-safety contract as applyThinClientSourceScope).
+// ─────────────────────────────────────────────────────────────────
+// #2185 — strict unknown-flag validation (pre-dispatch, pre-engine).
+// A flag no handler consults must fail loud instead of silently doing the
+// destructive thing (`init --migrate-only --dry-run` applied REAL migrations
+// while the user asked for a rehearsal). Two lanes:
+// - op commands: legal flags derive from the operation contract
+// (op.params) + the CLI-local formatter flags, mirroring parseOpArgs's
+// traversal so values that begin with '--' are never misread.
+// - CLI_ONLY commands: legal flags come from the generated
+// CLI_FLAG_REGISTRY (scripts/generate-flag-registry.ts scans each
+// command's source; freshness + coverage pinned by
+// test/cli-flag-validation.test.ts).
+// Everything after a literal `--` is passthrough and never validated.
+// ─────────────────────────────────────────────────────────────────
+
+// Exempt by contract, not oversight:
+// - call: the generic op invoker — arbitrary --param names are its interface.
+// - config: `config set <key> <value>` values are arbitrary strings.
+// - jobs submit: job payloads carry handler-defined params (shell lane incl.).
+// - eval brainbench: owns the 0/1/2 CI exit-code contract (0 pass · 1
+// regression · 2 error/inconclusive) via its own arg parser. The global
+// validator's exit(1) on an unknown flag would be read by a CI harness as a
+// memory REGRESSION rather than a typo; brainbench maps a bad flag to exit 2
+// (error) with its own usage. Its legal flags still land in the generated
+// registry (the generator scans eval's modules), so freshness/drift hold.
+function flagValidationExempt(command: string, subArgs: string[]): boolean {
+ return command === 'call' || command === 'config'
+ || (command === 'jobs' && subArgs[0] === 'submit')
+ || (command === 'eval' && subArgs[0] === 'brainbench');
+}
+
+/** Returns the first unknown flag (e.g. '--dry-run') or null when clean. */
+export function validateCommandFlags(command: string, subArgs: string[]): string | null {
+ if (flagValidationExempt(command, subArgs)) return null;
+ if (command === 'retrieval-upgrade' || command === 'migrate' && subArgs[0] === 'embeddings') return migrationCliArgumentError(command, subArgs)?.flag ?? null;
+ // Lane order MUST mirror dispatch order (CLI_ONLY first): commands that are
+ // BOTH an op and a CLI_ONLY member (think, salience, anomalies) dispatch to
+ // handleCliOnly, whose handlers parse flags the op contract doesn't declare
+ // (`salience --kind`, `think --with-calibration`) — validating those
+ // against op.params rejected documented invocations.
+ if (CLI_ONLY.has(command)) {
+ const legal = CLI_FLAG_REGISTRY[command];
+ // Registry drift fails OPEN at runtime (never brick a command); the
+ // drift-guard test fails the build instead.
+ if (!legal) return null;
+ return findUnknownFlag(subArgs, new Set(legal));
+ }
+ const op = cliOps.get(command) ?? cliAliases.get(command);
+ if (op) return findUnknownOpFlag(op, subArgs);
+ return null; // unknown command — the dispatcher's own error handles it
+}
+
+/** CLI_ONLY lane: token scan against the generated legal set. */
+export function findUnknownFlag(args: string[], legal: ReadonlySet<string>): string | null {
+ for (const a of args) {
+ if (a === '--') break;
+ const m = /^--([a-z0-9][a-z0-9-]*)(?:=.*)?$/i.exec(a);
+ if (!m) continue;
+ // Casing typo = unknown flag: every handler in the repo is
+ // case-sensitive-lowercase, so `--MIGRATE-ONLY` passing validation would
+ // just be silently ignored downstream — the exact class this validator
+ // exists to kill.
+ if (/[A-Z]/.test(m[1])) return `--${m[1]}`;
+ const name = `--${m[1]}`;
+ if (legal.has(name)) continue;
+ // --no-<flag> negation of a known flag is legal.
+ if (name.startsWith('--no-') && legal.has(`--${name.slice(5)}`)) continue;
+ return name;
+ }
+ return null;
+}
+
+/** Op lane: mirrors parseOpArgs so flag VALUES starting with '--' are skipped. */
+export function findUnknownOpFlag(op: Operation, args: string[]): string | null {
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i];
+ if (a === '--') break;
+ const m = /^--([a-z0-9][a-z0-9-]*)(?:=(.*))?$/i.exec(a);
+ if (!m) continue;
+ // Casing typo = unknown flag (see findUnknownFlag).
+ if (/[A-Z]/.test(m[1])) return `--${m[1]}`;
+ const rawKey = m[1];
+ // CLI-local flags consumed OUTSIDE the op contract (never wire params):
+ // json/explain — formatter flags; help — short-circuits pre-dispatch;
+ // source — makeContext's 6-tier source resolution (deleted before wire);
+ // dry-run — makeContext's ctx.dryRun projection.
+ // Pre-fix, rejecting these broke documented invocations
+ // (`gbrain search "x" --source y`, `gbrain put x --dry-run`).
+ if (rawKey === 'json') {
+ // #4602: parseOpArgs consumes a literal true/false as this boolean's
+ // value — mirror the traversal so the token counts as consumed here too.
+ if (m[2] === undefined && isBooleanLiteral(args[i + 1])) i++;
+ continue;
+ }
+ // Bare-only even where an op also declares `explain` (search/query): the `=` form is refused, never parsed as a value.
+ if (rawKey === 'explain' || rawKey === 'help') { if (m[2] === undefined) continue; return `--${rawKey}`; }
+ if (rawKey === 'source' || rawKey === 'dry-run') {
+ // Non-boolean-style CLI-locals consume the next token as their value
+ // in parseOpArgs (source does; dry-run is boolean-read) — mirror the
+ // parser: source consumes a value when not inline-`=`; dry-run
+ // consumes only a literal true/false (#4602).
+ if (rawKey === 'source' && m[2] === undefined) i++;
+ if (rawKey === 'dry-run' && m[2] === undefined && isBooleanLiteral(args[i + 1])) i++;
+ continue;
+ }
+ if (rawKey.startsWith('no-')) {
+ const positive = rawKey.slice(3).replace(/-/g, '_');
+ if (op.params[positive]?.type === 'boolean') continue;
+ }
+ const key = rawKey.replace(/-/g, '_');
+ const paramDef = op.params[key];
+ if (paramDef) {
+ // Non-boolean flags consume the next token as their value unless
+ // provided inline via `=` — exactly like parseOpArgs. Boolean flags
+ // consume only a literal true/false value token (#4602).
+ if (paramDef.type !== 'boolean' && m[2] === undefined) i++;
+ else if (paramDef.type === 'boolean' && m[2] === undefined && isBooleanLiteral(args[i + 1])) i++;
+ continue;
+ }
+ return `--${rawKey}`;
+ }
+ return null;
+}
+
+/**
+ * #1475 — the DB-plane merge `connectEngine` performs after connect, published
+ * for `makeContext` so the operation context carries it too.
+ *
+ * Why a map rather than a module-level variable: a process can hold more than
+ * one engine (`--brain <mount>` connects a second one), and the host brain's
+ * merged config must never be served for a mounted brain's context. Weak so a
+ * disconnected engine does not pin its config for the life of the process.
+ */
+const MERGED_CONFIG_BY_ENGINE = new WeakMap<BrainEngine, GBrainConfig>();
+const SELECTED_CONFIG_BY_ENGINE = new WeakMap<BrainEngine, GBrainConfig>();
+
+/**
+ * Adversarial-review fixup (PR #4186): which BrainEngine instances came from
+ * connectMountEngine. Keyed on the engine object itself — same engine-keyed
+ * weak-reference pattern as MERGED_CONFIG_BY_ENGINE above (a WeakMap; this is
+ * a WeakSet since there's no payload to store, just membership), and for the
+ * same reason that comment gives: a process can hold more than one engine,
+ * so any guard that decides per-engine behavior must bind to the specific
+ * engine instance, not to process-wide module state. (The prior version of
+ * this fixup checked a module-level `activeBrainId` variable instead; that
+ * drifts from the `engine` argument makeContext actually receives if a
+ * process ever holds a host engine and a mount engine at once — the CLI
+ * doesn't today, but nothing enforces that.) Weak so a disconnected mount
+ * engine does not pin memory.
+ */
+const MOUNT_ENGINES = new WeakSet<BrainEngine>();
+
+/**
+ * @internal Exported for test/eval-capture-db-plane.test.ts.
+ *
+ * Publishing the merge is the whole point of the map — if the `set` in
+ * connectEngine is ever dropped, makeContext silently falls back to
+ * re-merging and every command pays the per-key reads twice with no test
+ * going red. The seam lets a test prime the map the way connectEngine does
+ * and observe that no further reads happen.
+ */
+export const __testing = {
+ publishMergedConfig(engine: BrainEngine, config: GBrainConfig): void {
+ MERGED_CONFIG_BY_ENGINE.set(engine, config);
+ },
+ // Test-only seam for the mount-engine guard in makeContext's DB-plane
+ // fallback (see the #1475 comment there). Mirrors the MOUNT_ENGINES.add
+ // connectMountEngine makes on a real mount connect, without needing a live
+ // BrainRegistry.
+ markEngineAsMountForTests(engine: BrainEngine): void {
+ MOUNT_ENGINES.add(engine);
+ },
+ // Test-only entry for test/cli-dispatch-lifecycle.serial.test.ts: the real
+ // dispatcher, driven in-process with recorded engine lifecycle calls.
+ main,
+};
+
+export async function makeContext(engine: BrainEngine, params: Record<string, unknown>, op?: Pick<Operation, 'params'>): Promise<OperationContext> {
+ // v0.31.8 (D11): resolve sourceId via the canonical 6-tier chain. Honors
+ // --source / GBRAIN_SOURCE / .gbrain-source / path-match / brain default /
+ // 'default'. Wrapped in try/catch so a doctor / single-source brain that
+ // never set up sources still returns 'default' silently.
+ let sourceId: string | undefined;
+ // #2561: when the source resolved via a NON-explicit tier (path-match /
+ // brain default / sole-non-default / seed default), unqualified search-shaped
+ // reads span every `config.federated = true` source. Computed here (the
+ // trusted local boundary) and consumed by federatedSearchScope
+ // (src/core/ops/context.ts), which widens only an unqualified read with no
+ // OAuth grant; remote transports compute the same field for no-grant tokens.
+ let localFederated: string[] | undefined;
+ let sourceImplicit = true;
+ // params.source is set when a CLI flag was parsed for the op (rare; most
+ // CLI ops don't take --source). Falls through to env/dotfile/path-match.
+ // An op that owns `source` (opOwnsSource) receives it as its own param.
+ const explicit = op && opOwnsSource(op) ? null : (params.source as string | undefined) ?? null;
+ const { resolveSourceWithTier, localFederatedSourceIds, SourceTargetError } = await import('../core/source-resolver.ts');
+ try {
+ const resolved = await resolveSourceWithTier(engine, explicit);
+ sourceId = resolved.source_id;
+ sourceImplicit = resolved.tier !== 'flag' && resolved.tier !== 'env' && resolved.tier !== 'dotfile';
+ localFederated = await localFederatedSourceIds(engine, resolved.source_id, resolved.tier);
+ } catch (err) {
+ // #1712: an EXPLICIT --source that fails to resolve (invalid id, or a
+ // source that doesn't exist) must error loudly — the blanket swallow
+ // turned `--source __all__` and typos into a silent `default` scope,
+ // which is how three bug reports became debugging sessions.
+ // Ambient user-selected targets (GBRAIN_SOURCE / .gbrain-source /
+ // sources.default) are just as authoritative as --source. Only structural
+ // pre-init failures retain the legacy default fallback.
+ if (explicit || err instanceof SourceTargetError) throw err;
+ // Ambient resolution failed (e.g. sources table doesn't exist on a fresh
+ // pre-init brain). Leave sourceId unset; engine read methods fall through
+ // to the cross-source view (D16 back-compat path).
+ sourceId = undefined;
+ }
+ // #1475 — the operation context must carry the DB plane, not just file/env.
+ // `gbrain config set` writes DB-plane keys and `gbrain config get` reads
+ // them back, but every op-side gate reads `ctx.config` — so building this
+ // from the sync, file-only `loadConfig()` made those writes inert
+ // (`eval.capture` was the reported case: set, echoed back, still off).
+ //
+ // connectEngine already performs exactly this merge after connect for the
+ // HOST brain; it publishes the result, so the normal CLI path costs ZERO
+ // additional config reads. The fallback merge below only runs when both
+ // (a) the engine was never published (callers that reach makeContext with
+ // an engine connectEngine never saw — tests with a stub engine) AND
+ // (b) the engine is not a mount engine (MOUNT_ENGINES, set by
+ // connectMountEngine). A mounted brain's engine never re-merges here.
+ // connectMountEngine's own docstring only promises that a mount's DB-plane
+ // model config is never merged into the caller's AI gateway; it says
+ // nothing about ctx.config, and this fallback — added for #1475 after that
+ // docstring was written — would otherwise happily merge a mount's DB-plane
+ // config into the caller's context too, which is the same kind of leak the
+ // gateway guarantee exists to prevent (a caller trusting a mount's config
+ // as if it were its own). Skipping the merge for mount engines closes that
+ // gap and, as a side effect, avoids adding a full per-key DB round-trip to
+ // every mounted-brain command (the #3980 cost this whole publish/consume
+ // split exists to avoid). Mounted brains keep the same file/env-only
+ // config makeContext built before #1475.
+ //
+ // Fail-open, but not silent. The expected failure — a brain mid-migration
+ // whose config table does not exist yet — is already absorbed per key inside
+ // loadConfigWithEngine, so anything that escapes to here is unexpected (a
+ // contract violation such as a malformed listConfigKeys result). Falling
+ // back to the file plane keeps the command usable, but swallowing it without
+ // a word would turn "the DB plane silently did nothing" back into a mystery —
+ // which is the whole shape of #1475. Warn and continue.
+ const fileConfig = loadConfig() || { engine: 'postgres' as const };
+ let mergedConfig = MERGED_CONFIG_BY_ENGINE.get(engine) ?? fileConfig;
+ if (!MERGED_CONFIG_BY_ENGINE.has(engine) && !MOUNT_ENGINES.has(engine)) {
+ try {
+ mergedConfig = (await loadConfigWithEngine(engine, fileConfig)) ?? fileConfig;
+ } catch (err) {
+ console.warn(
+ `[config] DB-plane merge failed; using file/env config only. ` +
+ `Values set via \`gbrain config set\` will not apply to this command: ` +
+ `${(err as Error).message}`,
+ );
+ mergedConfig = fileConfig;
+ }
+ }
+
+ return {
+ engine,
+ config: mergedConfig,
+ logger: { info: console.log, warn: console.warn, error: console.error },
+ dryRun: (params.dry_run as boolean) || false,
+ // Local CLI invocation — the user owns the machine; do not apply remote-caller
+ // confinement (e.g., cwd-locked file_upload).
+ remote: false,
+ cliOpts: getCliOptions(),
+ writeWaitMs: currentCliWriteWait().waitMs, // #5232
+ // v0.34 D4: sourceId is REQUIRED at the type level. Fall back to 'default'
+ // when resolveSourceId returned undefined (fresh pre-init brain, no sources
+ // table). Matches dispatch.ts's auto-fill so the contract holds across
+ // every transport.
+ sourceId: sourceId ?? 'default',
+ // Brain axis: the id connectEngine resolved for this process. Module
+ // state, NEVER params — caller-supplied params.brain must not select a
+ // brain (that would be an untrusted-caller cross-brain hole over MCP).
+ brainId: activeBrainId,
+ ...(localFederated ? { localFederatedSourceIds: localFederated } : {}),
+ ...(sourceImplicit ? { localSourceImplicit: true } : {}),
+ // T15/FOV-1: capture the retrieval meta for formatResult's empty-result
+ // render (the local-engine twin of the MCP _meta.retrieval channel).
+ emitResponseMeta: captureRetrievalMeta,
+ emitNotice: captureOpNotice, // A6/F8: rendered after the result by applyCliOpNotices
+ };
+}
+
+/**
+ * T15/FOV-1: the retrieval meta for the CURRENT CLI invocation, captured
+ * from either result path — the local engine path via ctx.emitResponseMeta,
+ * the thin-client routed path via the envelope's `_meta.retrieval`. Read by
+ * formatResult's empty-result branch so `gbrain search`/`query` stop
+ * printing a bare "No results." when the pipeline actually degraded.
+ * Module state is safe here: one op per CLI process.
+ */
+let lastRetrievalMeta: Record<string, unknown> | null = null;
+
+export function captureRetrievalMeta(key: string, value: unknown): void {
+ if (key === 'retrieval' && value !== null && typeof value === 'object') {
+ lastRetrievalMeta = value as Record<string, unknown>;
+ }
+}
+
+// Exported for tests.
+export function resetRetrievalMetaForTests(): void {
+ lastRetrievalMeta = null;
+}
+
+/** One-line parenthetical for the empty-result render. '' when no meta. */
+function describeEmptyRetrieval(): string {
+ const m = lastRetrievalMeta;
+ if (!m) return '';
+ const parts: string[] = [];
+ if (typeof m.retrieved_count === 'number' && m.retrieved_count > 0) {
+ parts.push(`retrieved ${m.retrieved_count} before trimming`);
+ }
+ // Ranking-only stages (a skipped reranker) never cause a miss — keep the
+ // "clean miss" verdict honest.
+ const stages = Array.isArray(m.degraded)
+ ? [...new Set((m.degraded as Array<{ stage?: string }>).filter(affectsRecall).map(d => d?.stage).filter(Boolean))]
+ : [];
+ parts.push(stages.length > 0
+ ? `degraded: ${stages.join(', ')}`
+ : 'clean miss — no retrieval degradation');
+ return ` (${parts.join('; ')})`;
+}
+
+// Exported for tests (same import-safety contract as cliAliases/printOpHelp).
+/**
+ * #2416: hint-only steering — a concept-shaped `search` gets a one-line
+ * stderr nudge toward `query`. Never fires for other ops, never reroutes
+ * (search stays the cheap hot path), and honors --quiet — the same silence
+ * discipline as the identity banner. Called from BOTH result paths (local
+ * engine + thin-client routed); formatResult can't host this because it
+ * never sees the query text.
+ */
+export function maybePrintConceptNudge(opName: string, params: Record<string, unknown>): void {
+ if (opName !== 'search' || getCliOptions().quiet) return;
+ const nudge = conceptNudge(String(params.query ?? ''));
+ if (nudge) process.stderr.write(nudge + '\n');
+}
+
+/**
+ * Characters of `compiled_truth` the human `history` table previews per
+ * version row. `--json` returns the untruncated rows.
+ */
+const VERSION_TRUTH_PREVIEW_CHARS = 60;
+
+export function formatResult(
+ opName: string,
+ result: unknown,
+ params: Record<string, unknown> = {},
+): string {
+ // D2: `--json` on the op lane is the result document for every op. Only
+ // search/query render it themselves (retrieval redaction + stderr notice);
+ // list/stats/health/tags/timeline used to print their human table instead.
+ if (params.json === true && opName !== 'search' && opName !== 'query') {
+ return JSON.stringify(result, bigintToStringReplacer, 2) + '\n';
+ }
+ switch (opName) {
+ case 'volunteer_context': {
+ const r = result as any;
+ // Stats mode (the feedback loop).
+ if (r && r.approximate === true && Array.isArray(r.by_arm)) {
+ const lines = [
+ `volunteered-context precision — last ${r.days} day(s) (${r.note})`,
+ `total: ${r.total_volunteered} volunteered, ${r.total_used} used`,
+ ];
+ for (const a of r.by_arm) {
+ lines.push(` ${a.match_arm}/${a.channel}: ${a.used}/${a.volunteered} used (precision ${a.precision})`);
+ }
+ if (!r.by_arm.length) lines.push(' (no volunteer events in the window)');
+ return lines.join('\n') + '\n';
+ }
+ const pages = (r?.pages ?? []) as any[];
+ if (!pages.length) return 'Nothing volunteered (no entity cleared the confidence gate).\n';
+ return pages.map((p) => formatVolunteeredPage(p)).join('\n') + '\n';
+ }
+ case 'get_page': {
+ const r = result as any;
+ if (r.error === 'ambiguous_slug') {
+ return `Ambiguous slug. Did you mean:\n${r.candidates.map((c: string) => ` ${c}`).join('\n')}\n`;
+ }
+ return serializeMarkdown(r.frontmatter || {}, r.compiled_truth || '', r.timeline || '', {
+ type: r.type, title: r.title, tags: r.tags || [],
+ });
+ }
+ case 'list_pages': {
+ const pages = result as any[];
+ if (pages.length === 0) return 'No pages found.\n';
+ const cell = (v: unknown): string => {
+ const s = v === null || v === undefined ? '' : String(v);
+ return s.replace(/\\/g, '\\\\').replace(/\t/g, '\\t').replace(/\r/g, '\\r').replace(/\n/g, '\\n');
+ };
+ return pages.map(p =>
+ `${cell(p.slug)}\t${cell(p.type)}\t${cell(p.updated_at?.toString().slice(0, 10) || '?')}\t${cell(p.title)}`,
+ ).join('\n') + '\n';
+ }
+ case 'search':
+ case 'query': {
+ const { results, meta } = redactRetrievalOutput(result as any[], lastRetrievalMeta);
+ const incompleteStages = Array.isArray(meta?.degraded)
+ ? [...new Set((meta.degraded as Array<{ stage?: string }>).map(d => d.stage)
+ .filter(stage => stage === 'vector_candidates_incomplete' || stage === 'projection_pending' || stage === 'projection_status_unknown'))]
+ : [];
+ const incompleteNotice = incompleteStages.length > 0
+ ? `Retrieval incomplete: ${incompleteStages.join(', ')}.\n`
+ : '';
+ const answerId = typeof meta?.answer_id === 'string' ? meta.answer_id : undefined;
+ if (answerId && results.length > 0) process.stderr.write(`answer: ${answerId} (rate with: gbrain rate ${answerId} 1-5)\n`);
+ if (params.json === true) {
+ if (incompleteNotice) process.stderr.write(incompleteNotice);
+ // --explain --json: the same per-row score_details object MCP `explain: true` returns.
+ if (getCliOptions().explain) for (const r of results) r.score_details ??= require('../core/search/explain-formatter.ts').buildScoreDetails(r);
+ return JSON.stringify(answerId ? results.map(r => ({ ...r, answer_id: answerId })) : results, null, 2) + '\n';
+ }
+ // T15/FOV-1: an empty result names its cause when the pipeline told us
+ // (degradation stages from _meta.retrieval / the local meta capture) —
+ // a bare "No results." was indistinguishable from a degraded pipeline.
+ if (results.length === 0) return `No results.${describeEmptyRetrieval()}\n`;
+ // v0.40.4 — --explain switches to per-stage attribution formatter.
+ // Reads CliOptions.explain via the module-level singleton.
+ const cliOpts = getCliOptions();
+ if (cliOpts.explain) {
+ // Lazy import keeps formatResult's startup hot path narrow for
+ // the common non-explain case.
+ const { formatResultsExplain } = require('../core/search/explain-formatter.ts');
+ // v0.48.2: thread the captured retrieval meta so the header lines
+ // (autocut decision, `degraded: reranker_skipped (no_key)`) render.
+ return formatResultsExplain(results, meta ?? undefined);
+ }
+ return incompleteNotice + results.map(r =>
+ `[${r.score?.toFixed(4) || '?'}] ${r.slug} -- ${r.chunk_text?.slice(0, 100) || ''}${r.stale ? ' (stale)' : ''}`,
+ ).join('\n') + '\n';
+ }
+ case 'get_tags': {
+ const tags = result as string[];
+ return tags.length > 0 ? tags.join(', ') + '\n' : 'No tags.\n';
+ }
+ case 'get_stats': {
+ const s = result as any;
+ const lines = [
+ `Pages: ${s.page_count}`,
+ `Chunks: ${s.chunk_count}`,
+ `Embedded: ${s.embedded_count}`,
+ `Links: ${s.link_count}`,
+ `Tags: ${s.tag_count}`,
+ `Timeline: ${s.timeline_entry_count}`,
+ ];
+ if (s.pages_by_type) {
+ lines.push('', 'By type:');
+ for (const [k, v] of Object.entries(s.pages_by_type)) {
+ lines.push(` ${k}: ${v}`);
+ }
+ }
+ return lines.join('\n') + '\n';
+ }
+ case 'get_health': {
+ const h = result as any;
+ // Health score weights: missing_embeddings is the heaviest (2 pts), other
+ // graph quality issues are 1 pt each. link_coverage / timeline_coverage below
+ // 50% on entity pages indicates the graph needs population.
+ const score = Math.max(0, 10
+ - (h.missing_embeddings > 0 ? 2 : 0)
+ - (h.stale_pages > 0 ? 1 : 0)
+ - (h.orphan_pages > 0 ? 1 : 0)
+ - ((h.link_coverage ?? 1) < 0.5 ? 1 : 0)
+ - ((h.timeline_coverage ?? 1) < 0.5 ? 1 : 0));
+ const lines = [
+ `Health score: ${score}/10`,
+ `Embed coverage: ${(h.embed_coverage * 100).toFixed(1)}%`,
+ `Missing embeddings: ${h.missing_embeddings}`,
+ `Stale pages: ${h.stale_pages}`,
+ `Orphan pages: ${h.orphan_pages}`,
+ ];
+ // gbrain#4147: null = below the small-N floor — say so instead of
+ // rendering a misleading hard 0%/100%.
+ if (h.link_coverage != null) {
+ lines.push(`Link coverage (entities): ${(h.link_coverage * 100).toFixed(1)}%`);
+ } else if (h.entity_page_count !== undefined) {
+ lines.push(`Link coverage (entities): n/a (${h.entity_page_count} entity page(s) — too few to grade)`);
+ }
+ if (h.timeline_coverage != null) {
+ lines.push(`Timeline coverage (entity pages): ${(h.timeline_coverage * 100).toFixed(1)}%`);
+ } else if (h.entity_page_count !== undefined) {
+ lines.push(`Timeline coverage (entity pages): n/a (${h.entity_page_count} entity page(s) — too few to grade)`);
+ }
+ if (h.timeline_coverage_score !== undefined) {
+ lines.push(`Timeline density (entity and event pages): ${h.timeline_coverage_score}/15 (brain-score component)`);
+ }
+ if (Array.isArray(h.most_connected) && h.most_connected.length > 0) {
+ lines.push('Most connected entities:');
+ for (const e of h.most_connected) {
+ lines.push(` ${e.slug}: ${e.link_count} links`);
+ }
+ }
+ return lines.join('\n') + '\n';
+ }
+ case 'get_timeline': {
+ const entries = result as any[];
+ if (entries.length === 0) return 'No timeline entries.\n';
+ return entries.map(e =>
+ `${e.date} ${e.summary}${e.source ? ` [${e.source}]` : ''}`,
+ ).join('\n') + '\n';
+ }
+ case 'get_versions': {
+ const versions = result as any[];
+ if (versions.length === 0) return 'No versions.\n';
+ return versions.map(v => {
+ // Only elide when something was actually dropped — an unconditional
+ // ellipsis renders an 11-char body as `Short body....`.
+ const truth = v.compiled_truth ?? '';
+ const head = truth.slice(0, VERSION_TRUTH_PREVIEW_CHARS);
+ const elided = truth.length > VERSION_TRUTH_PREVIEW_CHARS ? '...' : '';
+ return `#${v.id} ${v.snapshot_at?.toString().slice(0, 19) || '?'} ${head}${elided}`;
+ }).join('\n') + '\n';
+ }
+ // MEMORY_VERBS v1 [F-E]: human-readable by default; trailing `--json`
+ // escapes to the raw envelope (parseOpArgs ignores an unmatched trailing
+ // flag, so the argv probe is safe).
+ case 'remember': {
+ if (process.argv.includes('--json')) break;
+ return formatRememberResult(result as Record<string, any>);
+ }
+ case 'entity': {
+ if (process.argv.includes('--json')) break;
+ const r = result as any;
+ if (!r.found) {
+ const lines = [`No entity found. (${r.latency_ms}ms)${r.coverage && r.coverage.state !== 'complete' ? ` Mention coverage: ${r.coverage.state}, ${r.coverage.pending_pages} page(s) pending.` : ''}`];
+ if (Array.isArray(r.suggestions) && r.suggestions.length) {
+ lines.push('Did you mean:');
+ for (const s of r.suggestions) lines.push(` ${s.slug} — ${s.title} [${s.create_safety}]`);
+ }
+ return lines.join('\n') + '\n';
+ }
+ const c = r.card;
+ const lines = [`${c.entity.title} (${c.entity.slug})${c.entity.type ? ` [${c.entity.type}]` : ''} (${r.latency_ms}ms)`];
+ if (c.summary) lines.push(` ${c.summary}`);
+ if (c.aka?.length) lines.push(` aka: ${c.aka.join(', ')}`);
+ const lt = c.last_touched || {};
+ const touched = lt.updated_at || lt.last_retrieved_at || lt.last_timeline_date;
+ if (touched) lines.push(` last touched: ${String(touched).slice(0, 10)}`);
+ if (c.open_threads?.length) {
+ lines.push(' open threads:');
+ for (const t of c.open_threads) lines.push(` [${t.kind}] ${t.text}${t.date ? ` (${String(t.date).slice(0, 10)})` : ''}`);
+ }
+ if (c.edges?.length) {
+ lines.push(' edges:');
+ for (const e of c.edges) lines.push(` ${e.direction === 'out' ? '→' : '←'} ${e.type} ${e.slug}`);
+ }
+ lines.push(` backlinks: ${c.backlink_count} | active facts: ${c.active_fact_count}`);
+ if (c.referenced_by_count) lines.push(` referenced by ${c.referenced_by_count} page(s):`, ...c.referenced_by.map((g: any) => ` ${g.canonical_type} (${g.total}): ${g.rows.map((x: any) => x.slug).join(', ')}${g.next ? ', ...' : ''}`));
+ if (c.coverage && c.coverage.state !== 'complete') lines.push(` mention coverage: ${c.coverage.state}, ${c.coverage.pending_pages} page(s) pending`);
+ if (Array.isArray(r.suggestions) && r.suggestions.length) {
+ lines.push(' other matches:');
+ for (const s of r.suggestions) lines.push(` ${s.slug} — ${s.title}`);
+ }
+ return lines.join('\n') + '\n';
+ }
+ case 'synthesize': {
+ if (process.argv.includes('--json')) break;
+ const r = result as any;
+ const lines = [r.answer || '(no answer)'];
+ if (Array.isArray(r.sources) && r.sources.length) lines.push('', `sources: ${r.sources.join(', ')}`);
+ if (Array.isArray(r.gaps) && r.gaps.length) lines.push(`gaps: ${r.gaps.join('; ')}`);
+ const cost = r.cost || {};
+ const tok = cost.input_tokens != null ? `${cost.input_tokens} in / ${cost.output_tokens} out` : 'tokens n/a';
+ const usd = cost.usd_estimate != null ? ` (~$${Number(cost.usd_estimate).toFixed(4)})` : '';
+ lines.push(`cost: ${cost.model} — ${tok}${usd}`);
+ return lines.join('\n') + '\n';
+ }
+ default:
+ // bigintToStringReplacer keeps this fallback renderer crash-proof even
+ // if a future caller hands it a not-yet-normalized result. (#2450)
+ return JSON.stringify(result, bigintToStringReplacer, 2) + '\n';
+ }
+ return JSON.stringify(result, null, 2) + '\n';
+}
+
+/**
+ * Multi-topology v1: thin-client refusal set. These commands require a local
+ * engine; if `~/.gbrain/config.json` has `remote_mcp` set, the dispatch guard
+ * refuses them with a canonical error pointing at the remote host. The check
+ * runs before per-command dispatch so the error message is consistent.
+ *
+ * `serve` is in this set because `gbrain serve` (stdio or http) requires a
+ * local engine to expose. Thin clients don't have one to expose.
+ *
+ * `doctor` is intentionally NOT in this set — task 4 routes it to
+ * `runRemoteDoctor` for thin-client installs.
+ */
+/**
+ * v0.31.1 (Issue #734, CDX-5 + cherry-pick A): pinpoint refusal hints for
+ * local-only commands when running on a thin-client install. Each hint names
+ * the closest path (remote MCP call, host-side workflow) so users aren't
+ * stuck guessing what to do next.
+ *
+ * Source-of-truth lives here so adding a new local-only command means
+ * adding both the THIN_CLIENT_REFUSED_COMMANDS member AND the hint in one
+ * place during code review.
+ */
+const THIN_CLIENT_REFUSE_HINTS: Record<string, string> = {
+ call: '`call` dispatches against a local engine. Use the named CLI command or an authorized MCP tool through your agent, or run `gbrain call` on the host.',
+ sync: 'sync runs on the host. Use the dedicated `sync_brain` MCP operation, or run `gbrain sync` on the host.',
+ embed: 'embed runs on the host. Run `gbrain embed` or `gbrain cycle` on the host machine.',
+ embeddings: 'embeddings enable changes the brain host config. Run `gbrain embeddings enable` (or the readiness fix) on the host machine.',
+ extract: 'extract runs on the host. Run `gbrain extract` or `gbrain cycle` on the host machine.',
+ 'extract-conversation-facts': 'extract-conversation-facts runs on the host (requires local engine + chat gateway). Run on the host machine.',
+ enrich: 'enrich runs on the host (requires local engine + chat gateway for grounded synthesis). Run on the host machine.',
+ migrate: "migrate runs on the host's local engine. Run on the host machine.",
+ 'retrieval-upgrade': "retrieval-upgrade (embedding migration) rebuilds the host brain's schema + re-embeds. Run on the host machine.",
+ 'apply-migrations': 'schema migrations run on the host. SSH and run there.',
+ 'repair-jsonb': 'repair-jsonb operates on the local DB only.',
+ integrity: 'integrity scans local files. Run on the host machine.',
+ serve: 'serve starts a server. Run on the host, not the thin client.',
+ dream: 'dream runs the autopilot cycle on the host. Run `gbrain dream` on the host machine.',
+ orphans: "orphans needs the host's brain. Run on the host or use the `find_orphans` MCP tool from your agent.",
+ transcripts: 'transcripts is server-private (raw chat exports stay on the host). Read transcripts on the host machine.',
+ storage: 'storage operates on the local repo on disk. Run on the host.',
+ takes: 'takes list/search/scorecard/calibration + add/update/resolve/supersede route to the brain host automatically (takes_* MCP ops). This subcommand (extract/revisit) is host-bound: run it on the host machine.',
+ sources: 'sources commands manage local DB + config rows. Per-subcommand thin-client routing lands in v0.31.x. For now: use `sources_list` / `sources_status` MCP tools, or run on the host.',
+ connectors: 'connectors manage provider session credentials in ~/.gbrain/connectors and sync your chat history on the host. Credentials never cross the wire — run on the host machine.',
+ sweep: 'sweep runs the serve-resident maintenance passes against the LOCAL engine. Run it on the host (the serve process also runs it automatically).',
+ 'compile-context': 'compile-context compiles from the local brain; run it on the host install.',
+ decide: '`gbrain decide` runs on the brain host; run it there.',
+ facts: '`gbrain facts relink` runs on the brain host (it writes the entity pages there): run `gbrain facts relink --source <id> --dry-run` on that machine.',
+ // v0.32 audit additions
+ pages: '`pages purge-deleted` is admin+localOnly (hard-deletes from the local DB). Run on the host.',
+ files: '`files list` and `files url` MCP ops are localOnly (paths live on the host filesystem). Use `gbrain files` on the host machine.',
+ eval: '`eval` export/prune/replay touch the local engine and have no MCP equivalents. Run `gbrain eval` on the host.',
+ 'code-def': '`code-def` needs symbol-aware lookup that has no MCP op yet. Run on the host or use `search` from your agent with a symbol-shaped query.',
+ 'code-refs': '`code-refs` has no MCP op yet. Run on the host.',
+ 'code-callers': '`code-callers` has no MCP op yet. Run on the host.',
+ 'code-callees': '`code-callees` has no MCP op yet. Run on the host.',
+ // scratch-DB audit additions
+ pricing: "pricing registers model prices in the host brain's config and is trusted-local only (a remote caller could void a cost cap). Ask the brain's operator to run `gbrain pricing set <model> ...` on the host.",
+ config: "config reads/writes the host brain's config plane. Edit the host's .gbrain/config.json (file-plane keys) or run on the host with GBRAIN_HOME set. self_upgrade.* keys are machine-local and work here.",
+ jobs: '`jobs list`, `jobs get <id>`, and `jobs stats` are thin-client routable; this subcommand runs against the host queue. Use the submit_job / list_jobs / get_job / get_job_stats MCP tools from your agent, or run on the host with GBRAIN_HOME set.',
+ // Gap-closure wave [OV6]: routable subcommands are intercepted before this
+ // hint fires — these fire only for the host-bound remainder.
+ search: '`search modes|stats|tune` route to the brain host automatically (search_modes / search_stats / search_tune MCP ops). The modes reset form, modes with the source flag (the reset dry-run), and tune apply mutate or preview host config, and `diagnose` runs live retrieval — run those on the host.',
+ cache: '`cache stats` routes to the brain host automatically (cache_stats MCP op). clear/prune mutate the host cache — run those on the host.',
+ repair: 'repair runs on the brain host (it publishes coordinated page writes against the local engine). Run `gbrain repair` on the brain host.',
+ projections: 'projections drain rebuilds text projections against the local engine. Run `gbrain projections drain` on the brain host.',
+ quarantine: '`quarantine list` routes to the brain host automatically (quarantine_list MCP op). scan/clear are host-bound (bulk re-import; the clear trust decision) — run those on the host.',
+ advisor: 'advisor ranks next actions from the host brain. Use the `advisor` MCP tool from your agent (when the host publishes it), or run `gbrain advisor` on the host.',
+ export: 'export dumps the host brain to disk and has no MCP equivalent. Run `gbrain export` on the host, or read pages with the `get_page` MCP tool.',
+ recall: '`recall --query`/`--budget-tokens` without `--budget-policy` runs the recall op locally. Add `--budget-policy facts_first` to send it to the brain host (`recall` MCP op).',
+};
+
+/**
+ * v0.31.1: emit a pinpoint refusal hint for a thin-client-incompatible
+ * command and exit 1. Falls back to the canonical generic message when no
+ * specific hint is registered (defensive — every member of
+ * THIN_CLIENT_REFUSED_COMMANDS should have a hint).
+ */
+function refuseThinClient(command: string, mcpUrl: string): never {
+ const hint = THIN_CLIENT_REFUSE_HINTS[command];
+ const message = hint
+ ? `\`gbrain ${command}\` is not routable (thin-client of ${mcpUrl}); run it on the brain host.`
+ : `\`gbrain ${command}\` requires a local engine. This install is a thin client of ${mcpUrl}.`;
+ exitCliError(opError('requires_local_engine', message,
+ hint ?? `Run \`${command}\` on the remote host, or use the corresponding MCP tool from your agent.`, {
+ ...(hint ? { why: hint } : {}),
+ fix: { argv: ['gbrain', command, ...thinRefusalSubcommand(command)], consent: [], actor: 'host_admin', requires_exclusive: false,
+ why: 'The brain database lives on the brain host; this machine only forwards MCP calls.' },
+ }), command);
+}
+
+/** The refused invocation's subcommand word (id-shaped only, per A1 argv safety), for the host-side fix. */
+function thinRefusalSubcommand(command: string): string[] {
+ const argv = process.argv.slice(2);
+ const next = argv[argv.indexOf(command) + 1] ?? '';
+ return argv.includes(command) && /^[a-z][a-z0-9-]*$/.test(next) ? [next] : [];
+}
+
+const THIN_CLIENT_BRAIN_FLAG_MESSAGE = '--brain is not supported on a thin-client install: the remote server is a single brain.';
+
+const ENGINE_CONNECT_HOOKS: EngineConnectHooks = { SELECTED_CONFIG_BY_ENGINE, completeStartup: completeEngineStartup };
+/** Dispatcher-owned pieces the command modules under src/cli/commands/ receive (see CliDispatchContext). */
+const CLI_DISPATCH_CONTEXT: CliDispatchContext = {
+ connectEngine,
+ completeStartup: completeEngineStartup,
+ dbMarkerBrainId,
+ SELECTED_CONFIG_BY_ENGINE,
+ cliModuleUrl: new URL('../cli.ts', import.meta.url).href,
+ makeContext,
+};
+
+/**
+ * Table step before the connectEngine() terminator: run a pre-connect record
+ * (engine-free, or opening its own engine). Returns false for post-connect
+ * records and for records an explicit pipeline step dispatches.
+ */
+async function dispatchPreConnectCommand(command: string, args: string[]): Promise<boolean> {
+ const record = findCliCommand(command);
+ if (!record || record.phase === 'post-connect' || record.dispatchedBy) return false;
+ await (await record.load()).run(args, CLI_DISPATCH_CONTEXT);
+ return true;
+}
+
+/** Table step after the connectEngine() terminator: run a post-connect record with the connected engine. */
+async function dispatchConnectedCommand(command: string, engine: BrainEngine, args: string[]): Promise<void> {
+ const record = findCliCommand(command);
+ if (record?.phase !== 'post-connect') return;
+ await (await record.load()).run(engine, args, CLI_DISPATCH_CONTEXT);
+}
+/**
+ * CLI-only dispatch: the explicit ordered pipeline (refactor wave 1, W4 cli).
+ * The command table (src/cli/command-table.ts) supplies each command's
+ * module; everything that depends on arguments, config or install shape
+ * stays explicit and in master's order:
+ *
+ * 1. thin-client guard, deferred-persistence routing, `agent register` guards
+ * 2. table step: pre-connect records (engine-free or own-engine)
+ * 3. engine-free subcommand routes, then engine-free `--help` routes
+ * 4. read-only connect+dispatch timeout path (`sources list`)
+ * 5. connected-dispatch preparation (sync watchdog, serve delegation, thin-client routes)
+ * 6. connectEngine() terminator with degraded-serve recovery
+ * 7. table step: post-connect records, then teardown/drain (never for `serve`)
+ *
+ * Functions tagged `@cliPipelineStage` are inlined in this order by the
+ * dispatch-shape golden (test/helpers/cli-dispatch-extract.ts) and the flag
+ * registry generator (scripts/generate-flag-registry.ts); keep new stages
+ * tagged and called from here.
+ */
+async function handleCliOnly(command: string, args: string[]) {
+ if (await routeCliOnlyBeforeTable(command, args)) return;
+ if (await dispatchPreConnectCommand(command, args)) return;
+ if (await routeEngineFreeSubcommands(command, args)) return;
+ if (await routeEngineFreeHelp(command, args)) return;
+ if (await runReadOnlyTimeoutDispatch(command, args)) return;
+ const prepared = await prepareConnectedDispatch(command, args);
+ if (!prepared) return;
+ const engine = await connectCliOnlyEngine(command, prepared.args);
+ if (!engine) return;
+ try {
+ await dispatchConnectedCommand(command, engine, prepared.args);
+ } finally {
+ prepared.syncWatchdog?.dispose(); // #1633: tear down the hard-deadline watchdog on clean exit
+ // #2084 — the CLI_ONLY fall-through teardown (drain every background-work
+ // sink, THEN disconnect, under a computed-deadline backstop) lives in
+ // finishCliTeardown. `gbrain capture`'s fire-and-forget facts:absorb job
+ // gets its drain window before PGLite's db.close() can race it into the
+ // re-pump busy-loop (#1762). #1471: this is also the fall-through
+ // OWNER-disconnect — the owner is torn down LAST (after the drain), so
+ // module-singleton borrowers never outlive it. `serve` skips teardown
+ // entirely: the daemon owns its lifecycle.
+ if (command !== 'serve') {
+ await finishCliTeardown({ engine });
+ }
+ }
+}
+
+/**
+ * Pipeline stage 1: thin-client guard, deferred-persistence routing and the
+ * `agent register` pre-connect guards. Returns true when the command was handled.
+ * @cliPipelineStage
+ */
+async function routeCliOnlyBeforeTable(command: string, args: string[]): Promise<boolean> {
+ // Thin-client guard: refuse DB-bound commands cleanly with a pinpoint
+ // hint instead of letting them fail later inside connectEngine or
+ // mid-handler. v0.31.1 routes through `refuseThinClient` so every
+ // refusal carries an actionable next-step hint (CDX-5 cherry-pick A).
+ // Gap-closure wave [OV6]: takes/cache/quarantine first try the
+ // per-subcommand MCP routing (engine-free); unhandled subcommands fall
+ // through to the refusal.
+ if (THIN_CLIENT_REFUSED_COMMANDS.has(command) || command === 'cache' || command === 'quarantine') {
+ const cfg = loadConfig();
+ if (isThinClient(cfg)) {
+ const { routeThinClientCommand } = await import('../commands/thin-client-routing.ts');
+ if (await routeThinClientCommand(cfg!, command, args)) return true;
+ refuseThinClient(command, cfg!.remote_mcp!.mcp_url);
+ }
+ }
+
+ // Local deferred connections must not bypass the remote installation route.
+ if (command === 'capture' || command === 'forget' || command === 'call' || command === 'sources' && ['writer', 'reconcile', 'add', 'remove', 'archive', 'restore', 'purge', 'set-path', 'reclone'].includes(args[0]) || command === 'takes' && ['add', 'update', 'supersede', 'resolve', 'remove', 'rebuild'].includes(args[0]) && !hasHelpFlag(args)) {
+ const { runDeferredPersistenceCommand } = await import('../commands/persistence-delegate.ts');
+ await runDeferredPersistenceCommand(command, args, connectEngine);
+ return true;
+ }
+
+ // `transcripts recent` reads through a live PGLite serve that owns the brain.
+ if (command === 'transcripts' && args[0] === 'recent' && !hasHelpFlag(args)
+ && await (await import('../commands/transcripts.ts')).runDelegatedTranscriptsRecent(args.slice(1))) return true;
+
+ // cathedral-6: `agent register` guards run PRE-connectEngine. A thin client
+ // would otherwise build a scratch PGLite and mint dead credentials into it;
+ // a live PGLite serve holds the single-writer lock, so connectEngine would
+ // hang ~30s before any handler code could print guidance. (`agent` itself
+ // stays out of THIN_CLIENT_REFUSED_COMMANDS — run/logs work elsewhere.)
+ if (command === 'agent' && args[0] === 'register' && !hasHelpFlag(args)) {
+ const cfg = loadConfig();
+ const wantsJson = args.includes('--json');
+ const refuse = (reason: string, message: string) => {
+ if (wantsJson) {
+ console.log(JSON.stringify({ ok: false, reason, message }));
+ } else {
+ console.error(`Error: ${message}`);
+ }
+ process.exit(1);
+ };
+ if (isThinClient(cfg)) {
+ // Shared verbatim with the in-handler belt-and-braces re-check. Lazy
+ // import: this guard runs pre-connect for `agent register` only, and a
+ // top-level import would eager-load the register module on every CLI
+ // start.
+ const { THIN_CLIENT_REGISTER_MESSAGE } = await import('../commands/agent-register.ts');
+ refuse('thin_client', THIN_CLIENT_REGISTER_MESSAGE);
+ }
+ if (cfg && !cfg.database_url && cfg.database_path) {
+ const { probeLivePgliteHolder } = await import('../core/bootstrap/uninstall.ts');
+ const holder = probeLivePgliteHolder(cfg.database_path);
+ if (holder?.serve) {
+ refuse('pglite_live_serve',
+ `a live \`gbrain serve\` (pid ${holder.pid}) holds this PGLite brain's single-writer lock — stop the serve, run \`gbrain agent register\` again, then restart it. (Postgres brains register fine while the serve runs.)`);
+ }
+ }
+ }
+ return false;
+}
+
+/**
+ * Pipeline stage 3a: engine-free subcommand routes (config / mcp pre-steps,
+ * `eval <sub>` no-DB bypasses, thin-client `status` / `eval whoknows`).
+ * @cliPipelineStage
+ */
+async function routeEngineFreeSubcommands(command: string, args: string[]): Promise<boolean> {
+ // db-availability loop (5c): the DB-connection config keys must be settable
+ // with the DB DOWN — "fix your URL with config set database_url" is circular
+ // if config needs the broken engine first. Other config keys fall through
+ // to the engine path below unchanged.
+ if (command === 'config') {
+ const { tryRunConfigEngineFree } = await import('../commands/config.ts');
+ if (await tryRunConfigEngineFree(args)) return true;
+ }
+ // Engine graduation owns its connections (routing rules: commands/migrate-graduation.ts routesToGraduation).
+ if (command === 'migrate' && await (await import('../commands/migrate-graduation.ts')).tryRunMigrateGraduation(args)) return true;
+ if (command === 'mcp') {
+ const { runMcp, mcpNeedsEngine } = await import('../commands/mcp.ts');
+ if (!mcpNeedsEngine(args)) { await runMcp(args); return true; }
+ const cfg = loadConfig();
+ if (isThinClient(cfg)) {
+ console.log(JSON.stringify({ status: 'error', reason: 'host_administration_required', message: 'Provision on the brain host, or use --admin-token-file to authenticate to its running server.' }));
+ setCliExitVerdict(1);
+ return true;
+ }
+ if (cfg?.database_path && !cfg.database_url) {
+ const { probeLivePgliteHolder } = await import('../core/bootstrap/uninstall.ts');
+ if (probeLivePgliteHolder(cfg.database_path)?.serve) {
+ console.log(JSON.stringify({ status: 'error', reason: 'pglite_live_serve', message: 'Use --admin-token-file with this running server’s admin credential; the command will provision through its existing engine.' }));
+ setCliExitVerdict(1);
+ return true;
+ }
+ }
+ }
+ if (command === 'sweep' && (args.includes('--help') || args.includes('-h'))) {
+ // SWEEP_HELP is engine-independent and must print on a fresh install
+ // (the sync/capture/enrich pre-engine-bind precedent). runSweep's --help
+ // path returns before touching the engine argument.
+ const { runSweep } = await import('../commands/sweep.ts');
+ await runSweep(null as never, args);
+ return true;
+ }
+ // Unreachable: the table step already ran `auth`. Master carried this
+ // second `auth` branch too; it is kept so the W0 dispatch-shape golden
+ // (branchesAfterTerminatingBranch) stays byte-identical. Removing it is a
+ // deliberate golden regeneration, not part of refactor wave 1.
+ if (command === 'auth') {
+ const { runAuth } = await import('../commands/auth.ts');
+ await runAuth(args);
+ return true;
+ }
+
+ // `eval cross-modal` is a pure API-call command — no DB, no brain. Bypass
+ // connectEngine entirely so first-run users (no `gbrain init` yet) can
+ // run the quality gate. Mirrors the dream/doctor no-DB pattern but
+ // doesn't even attempt the connect (T3=A in plans/radiant-napping-lerdorf.md).
+ // The handler self-configures the AI gateway from loadConfig() + process.env.
+ if (command === 'eval' && args[0] === 'cross-modal') {
+ const { runEvalCrossModal } = await import('../commands/eval-cross-modal.ts');
+ setCliExitVerdict(await runEvalCrossModal(args.slice(1)));
+ return true;
+ }
+
+ // `eval run-all` is a pure orchestrator — its engine arg is unused
+ // (`_engine`) and the brainbench suite it runs in-process is hermetic (brings
+ // its own PGLite via createBenchmarkBrain). Bypass connectEngine so run-all
+ // works with no brain configured — e.g. in CI. It returns its exit code
+ // (1 when a suite failed).
+ if (command === 'eval' && args[0] === 'run-all') {
+ const { runEvalRunAll } = await import('../commands/eval-run-all.ts');
+ setCliExitVerdict(await runEvalRunAll(null, args.slice(1)));
+ return true;
+ }
+
+ // v0.32 EXP-5 (codex review #10): `eval takes-quality replay <receipt>`
+ // is the ONLY sub-subcommand that doesn't need a brain — it reads a
+ // receipt JSON file from disk and re-renders it. Bypass connectEngine
+ // here so users can replay a receipt on a machine without DATABASE_URL.
+ // run/trend/regress need the brain and fall through to the regular
+ // engine-required path below.
+ if (command === 'eval' && args[0] === 'takes-quality' && args[1] === 'replay') {
+ const { runReplayNoBrain } = await import('../commands/eval-takes-quality.ts');
+ setCliExitVerdict(await runReplayNoBrain(args.slice(2)));
+ return true;
+ }
+
+ // BrainBench brings its own in-memory PGLite (longmemeval pattern) and is
+ // hermetic by default — no gateway, no user brain, no config required. The
+ // command owns its exit codes (0 pass / 1 regression / 2 error) and exits
+ // explicitly via its grace-tick exit path (PGLite exitCode-hijack guard).
+ if (command === 'eval' && args[0] === 'brainbench') {
+ const { runEvalBrainBench } = await import('../commands/eval-brainbench.ts');
+ if ((args.includes('--llm') || args.some((a) => a === '--decide' || a.startsWith('--decide='))) && !args.includes('--help') && !args.includes('-h')) {
+ // --llm and --decide arms talk to a provider; mirror the longmemeval
+ // gateway bootstrap so extraction and decide calls are keyed and priced.
+ const config = loadConfig() ?? ({} as GBrainConfig);
+ const { configureGateway } = await import('../core/ai/gateway.ts');
+ configureGateway(buildGatewayConfig(config));
+ }
+ await runEvalBrainBench(args.slice(1));
+ return true; // unreachable — runEvalBrainBench always exits — but keeps control flow explicit
+ }
+
+ // v0.28.8: longmemeval brings its own in-memory PGLite. Bypassing
+ // connectEngine here keeps `gbrain eval longmemeval --help` and benchmark
+ // runs working on machines that have no `~/.gbrain/config.json` configured.
+ //
+ // The in-memory brain's import + hybridSearch still embed through the
+ // configured provider, so the shared eval gateway bootstrap runs first.
+ if (command === 'eval' && args[0] === 'longmemeval') {
+ const { runEvalLongMemEval } = await import('../commands/eval-longmemeval.ts');
+ if (!(args.length > 1 && (args[1] === '--help' || args[1] === '-h'))) {
+ const { configureEvalGateway } = await import('../eval/shared/gateway-bootstrap.ts');
+ configureEvalGateway();
+ }
+ await runEvalLongMemEval(args.slice(1));
+ return true;
+ }
+
+ // v0.42.x (#2390): `gbrain eval chronicle` is deterministic — brings its own
+ // in-memory PGLite, no DB/gateway. CI fixture gate runs anywhere.
+ if (command === 'eval' && args[0] === 'chronicle') {
+ const { runEvalChronicle } = await import('../commands/eval-chronicle.ts');
+ setCliExitVerdict(await runEvalChronicle(args.slice(1)));
+ return true;
+ }
+
+ // #4198: `gbrain eval synthesize-concepts` gets a dedicated branch (mirror
+ // of the chronicle branch above) so the generic qrels eval can't recapture
+ // it — pre-fix it fell through to "Error: --qrels <path|json> is required".
+ // The scaffold needs no DB and exits nonzero with an honest
+ // {ok:false, status:'not_implemented'} envelope until the real evaluator
+ // lands.
+ if (command === 'eval' && args[0] === 'synthesize-concepts') {
+ const { runEvalSynthesizeConceptsCli } = await import('../commands/eval-synthesize-concepts.ts');
+ setCliExitVerdict(await runEvalSynthesizeConceptsCli(args.slice(1)));
+ return true;
+ }
+
+ // v0.41.13.0: `gbrain eval conversation-parser` is pure-function
+ // (parses fixture JSONL, runs parseConversation, scores results).
+ // No DB access; bypass connectEngine entirely so the CI fixture
+ // gate runs on machines with no `~/.gbrain/config.json`.
+ if (command === 'eval' && args[0] === 'conversation-parser') {
+ const { runEvalConversationParser } = await import('../commands/eval-conversation-parser.ts');
+ setCliExitVerdict(await runEvalConversationParser(args.slice(1)));
+ return true;
+ }
+
+ // v0.41.13.0: `gbrain conversation-parser list-builtins | validate
+ // | --help` are pure (no DB access). Bypass connectEngine so the
+ // operator can run them on machines with no brain configured.
+ // `scan <slug>` needs a brain and falls through.
+ if (
+ command === 'conversation-parser' &&
+ (args.length === 0 ||
+ args[0] === '--help' ||
+ args[0] === '-h' ||
+ args[0] === 'list-builtins' ||
+ args[0] === 'validate')
+ ) {
+ const { runConversationParser } = await import('../commands/conversation-parser.ts');
+ await runConversationParser(null, args);
+ return true;
+ }
+
+ // v0.33.1.3: `gbrain eval whoknows` on thin-client installs bypasses
+ // connectEngine entirely — the eval routes per-query through the remote
+ // `find_experts` MCP op (the v0.31.1 routing seam). Local mode falls
+ // through to the engine-connected path below.
+ if (command === 'eval' && args[0] === 'whoknows') {
+ const cfgPre = loadConfig();
+ if (isThinClient(cfgPre)) {
+ const { runEvalWhoknows } = await import('../commands/eval-whoknows.ts');
+ setCliExitVerdict(await runEvalWhoknows(null, args.slice(1)));
+ return true;
+ }
+ }
+
+ // v0.41.19.0: `gbrain status` on thin-client installs bypasses connectEngine
+ // entirely — Sync + Cycle route through the `get_status_snapshot` MCP op,
+ // and local-only sections render as "N/A on remote brain". Local mode falls
+ // through to the engine-connected dispatch path below. (`args` here is the
+ // subArgs slice already — no need to re-slice past the command.)
+ if (command === 'status') {
+ const cfgPre = loadConfig();
+ if (cfgPre && isThinClient(cfgPre)) {
+ const { runStatus } = await import('../commands/status.ts');
+ const result = await runStatus(null, args);
+ setCliExitVerdict(result.exitCode);
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * Pipeline stage 3b: engine-free `--help` for self-help commands whose
+ * handler needs an engine for everything else.
+ * @cliPipelineStage
+ */
+async function routeEngineFreeHelp(command: string, args: string[]): Promise<boolean> {
+ // v0.37 fix wave (Lane D.4 + CDX2-12): short-circuit `gbrain sync --help`
+ // BEFORE the engine bind. runSync has its own --help branch but can't
+ // reach it without an engine — which means a user running `--help` from
+ // a fresh tmpdir with no config gets a no-such-config error instead of
+ // help text. Importing runSync without the engine + passing null works
+ // because runSync's --help path doesn't touch the engine argument.
+ if (command === 'sync' && (args.includes('--help') || args.includes('-h'))) {
+ const { runSync } = await import('../commands/sync.ts');
+ await runSync(null as any, args);
+ return true;
+ }
+
+ // #3834: extract help is engine-independent and must work on a fresh
+ // install before a brain has been configured.
+ if (command === 'extract' && (args.includes('--help') || args.includes('-h'))) {
+ const { runExtract } = await import('../commands/extract.ts');
+ await runExtract(null as never, args);
+ return true;
+ }
+
+ // v0.39.3.0 WARN-5: same pattern for `capture --help`. CLI_ONLY_SELF_HELP
+ // now includes 'capture' so the generic short-circuit at :101 stays out
+ // of the way, but the dispatch case at :1229 still needs an engine. The
+ // pre-engine-bind branch here exposes the HELP constant without requiring
+ // a configured brain (fresh-tmpdir parity with brainstorm/lsd/sync).
+ if (command === 'capture' && (args.includes('--help') || args.includes('-h'))) {
+ const { runCapture } = await import('../commands/capture.ts');
+ await runCapture(null, args);
+ return true;
+ }
+
+ // v0.41.39 (#1700): same pattern for `enrich --help`. enrich is in
+ // CLI_ONLY_SELF_HELP so the generic stub stays out of the way; this
+ // pre-engine-bind branch exposes the HELP constant without a configured
+ // brain. runEnrich's --help path returns before touching the engine.
+ if (command === 'enrich' && (args.includes('--help') || args.includes('-h'))) {
+ const { runEnrich } = await import('../commands/enrich.ts');
+ await runEnrich(null as never, args);
+ return true;
+ }
+
+ // Same pattern for `takes --help`. 'takes' is now in CLI_ONLY_SELF_HELP so
+ // the generic stub stays out of the way; this pre-engine-bind branch exposes
+ // the subcommand usage block without a configured brain. runTakes' help path
+ // returns before touching the engine.
+ if (command === 'takes' && (args.includes('--help') || args.includes('-h'))) {
+ const { runTakes } = await import('../commands/takes.ts');
+ await runTakes(null as never, args);
+ return true;
+ }
+
+ // #3686 (the #578 residue): `eval --help` reaches eval.ts's printHelp
+ // engine-free. Placed AFTER the sub-owned no-DB routes above (brainbench /
+ // longmemeval / run-all / cross-modal / chronicle / conversation-parser /
+ // takes-quality replay / whoknows) so each sub's own usage keeps winning;
+ // every remaining `eval … --help` form prints the full subcommand usage
+ // instead of the old one-line stub (or a "No brain configured" error).
+ // D-N1: a named subcommand (`eval replay --help`) gets its own usage. The
+ // sub always sees `--help` as its first argument, the form every sub's
+ // usage branch answers before it touches the engine.
+ if (command === 'eval' && (args.includes('--help') || args.includes('-h'))) {
+ const sub = args[0] !== undefined && !args[0].startsWith('-') ? args[0] : undefined;
+ const { run } = await import('./commands/eval.ts');
+ await run(null as never, sub ? [sub, '--help'] : ['--help']);
+ return true;
+ }
+
+ // #3686: `storage --help` — runStorage's help guard returns before the
+ // engine argument is touched.
+ if (command === 'storage' && (args.includes('--help') || args.includes('-h'))) {
+ const { runStorage } = await import('../commands/storage.ts');
+ await runStorage(null as never, args);
+ return true;
+ }
+
+ // #3686: `reindex --help` — the usage block (incl. the --multimodal flags
+ // the dispatcher parses) lives in reindex.ts; printing it needs no engine.
+ if (command === 'reindex' && (args.includes('--help') || args.includes('-h'))) {
+ const { printReindexHelp } = await import('../commands/reindex.ts');
+ printReindexHelp();
+ return true;
+ }
+ return false;
+}
+
+/**
+ * Pipeline stage 4: the read-only connect+dispatch timeout path.
+ * @cliPipelineStage
+ */
+async function runReadOnlyTimeoutDispatch(command: string, args: string[]): Promise<boolean> {
+ // v0.41.6.0 D3 (per outside-voice F1): connect-time + dispatch-time wallclock
+ // timeouts for read-only commands whose hang would otherwise spin at 100% CPU
+ // (the production "10-day zombie gbrain search ping" bug class). The wrap
+ // covers connectEngine (so a hung schema probe / PgBouncer freeze actually
+ // surfaces a timeout) AND the dispatch body (so a wedged runSearch /
+ // runList honors the same deadline).
+ // Per-command default: search 30s, sources list 10s. User --timeout=Ns wins.
+ // Other commands (import, embed, doctor, etc.) keep their existing
+ // unbounded connect — destructive / long-running commands shouldn't get
+ // a default kill switch. The gate below is per-command (#3013): only the
+ // commands dispatchReadOnlyCommand handles may enter this path — a
+ // user-supplied --timeout on a write command must never reroute it here.
+ const cliOptsResolved = getCliOptions();
+ const userTimeoutMs = cliOptsResolved.timeoutMs;
+ const readOnlyTimeoutMs = resolveReadOnlyDispatchTimeoutMs(command, args, userTimeoutMs);
+
+ if (readOnlyTimeoutMs !== null) {
+ const { withTimeout, OperationTimeoutError } = await import('../core/timeout.ts');
+ const label = `gbrain ${command}`;
+ let engine: BrainEngine;
+ try {
+ engine = await withTimeout(connectEngine(), readOnlyTimeoutMs, `${label}: connect`);
+ } catch (e) {
+ if (e instanceof OperationTimeoutError) {
+ const hint = userTimeoutMs ? '' : ` (default ${e.ms}ms; pass --timeout=Ns to override)`;
+ console.error(`${e.label} timed out${hint}.`);
+ process.exit(124);
+ }
+ throw e;
+ }
+ try {
+ await withTimeout(dispatchReadOnlyCommand(engine, command, args), readOnlyTimeoutMs, label);
+ } catch (e) {
+ if (e instanceof OperationTimeoutError) {
+ const hint = userTimeoutMs ? '' : ` (default ${e.ms}ms; pass --timeout=Ns to override)`;
+ console.error(`${e.label} timed out${hint}.`);
+ process.exit(124);
+ }
+ throw e;
+ } finally {
+ await finishCliTeardown({ engine });
+ }
+ return true;
+ }
+ return false;
+}
+
+interface ConnectedDispatchPlan {
+ /** Arguments the post-connect record receives (autopilot resolves positionals here). */
+ args: string[];
+ /** #1633 sync hard-deadline watchdog, disposed after the post-connect record returns. */
+ syncWatchdog: { dispose(): void } | null;
+}
+
+/**
+ * Pipeline stage 5: work that must happen before connectEngine() for the
+ * remaining commands (sync watchdog, serve/persistence delegation, thin-client
+ * routes). Returns null when the command was handled.
+ * @cliPipelineStage
+ */
+async function prepareConnectedDispatch(command: string, args: string[]): Promise<ConnectedDispatchPlan | null> {
+ // #1633: out-of-band hard-deadline watchdog for `gbrain sync`. Installed
+ // BEFORE connectEngine so a connect-phase hang (the reported zombie class) is
+ // bounded too. A Bun Worker on its own OS thread SIGKILLs the process at the
+ // deadline even when the main event loop is starved by a synchronous spin —
+ // the only thing that stops the cron orphan-pileup. Disposed in the finally.
+ let syncWatchdog: { dispose(): void } | null = null;
+ // #6340: `sync status` / `sync unblock` read and schedule on the brain's own engine: no watchdog, no serve delegation (a delegate would refuse the subcommand).
+ const syncOperator = command === 'sync' && (args[0] === 'status' || args[0] === 'unblock');
+ if (command === 'sync' && !syncOperator) {
+ try {
+ const { resolveSyncHardDeadline } = await import('../commands/sync.ts');
+ const res = resolveSyncHardDeadline(args, {
+ isTty: Boolean(process.stdout.isTTY),
+ env: process.env,
+ });
+ if (res) {
+ const { installProcessWatchdog } = await import('../core/process-watchdog.ts');
+ const { syncWatchdogPlan } = await import('../core/sync-reconcile.ts');
+ const plan = syncWatchdogPlan(args, res);
+ syncWatchdog = installProcessWatchdog(plan.watchdog);
+ (await import('../core/forward-progress.ts')).registerRunDeadline({ atMs: Date.now() + res.deadlineMs, strict: !res.progressWindowMs });
+ process.stderr.write(plan.armedLine);
+ }
+ } catch (e) {
+ // A bad --hard-deadline value throws here (same posture as --timeout).
+ exitCliError(usageError(e instanceof Error ? e.message : String(e), 'Pass --hard-deadline a duration such as 30m or 2h.'), command);
+ }
+ }
+
+ // Serve-delegated sync preflight (PGLite host brains only): a live `gbrain
+ // serve` owns the single-writer lock, so connectEngine below would throw
+ // LiveServeLockError — instead the sync runs INSIDE the serve over its IPC
+ // socket (commands/sync-delegate.ts). Handled === delegated or politely
+ // refused (exit verdict set inside); false falls through unchanged.
+ if (command === 'sync' && !syncOperator) {
+ const cfgSync = loadConfig();
+ if (await (await import('../commands/sync-persistence-delegate.ts')).maybeDelegateSyncToPersistence(cfgSync, args)) return null;
+ if (cfgSync?.engine === 'pglite' && cfgSync.database_path && !cfgSync.database_url) {
+ const { maybeDelegateSyncToServe } = await import('../commands/sync-delegate.ts');
+ if (await maybeDelegateSyncToServe(cfgSync.database_path, args)) return null;
+ }
+ }
+
+ if (command === 'sources' && args[0] === 'refresh' && !hasHelpFlag(args) && await (await import('../commands/sources-refresh-delegate.ts')).maybeDelegateSourcesRefresh(loadConfig(), args.slice(1))) return null;
+ if (command === 'reindex-code') {
+ if (await (await import('../commands/reindex-code-delegate.ts')).maybeDelegateReindexCode(loadConfig(), args)) return null;
+ }
+ if (command === 'extract' && args.includes('--stale') && !hasHelpFlag(args) && await (await import('../commands/extract-stale-delegate.ts')).maybeDelegateExtractStale(loadConfig(), args)) return null;
+
+ if (command === 'embed' && args.includes('--facts')) {
+ if (await (await import('../commands/embed-facts-delegate.ts')).maybeDelegateFactEmbed(loadConfig(), args)) return null;
+ }
+
+ // Serve-delegated sweep preflight (#677) — same shape as sync above: a live
+ // `gbrain serve` owns the PGLite single-writer lock, so `sweep --once` used
+ // to exit 1 with LiveServeLockError. The lock owner runs the sweep over its
+ // IPC socket instead (commands/sweep-delegate.ts).
+ if (command === 'sweep') {
+ const cfgSweep = loadConfig();
+ if (cfgSweep?.engine === 'pglite' && cfgSweep.database_path && !cfgSweep.database_url) {
+ const { maybeDelegateSweepToServe } = await import('../commands/sweep-delegate.ts');
+ if (await maybeDelegateSweepToServe(cfgSweep.database_path, args)) return null;
+ }
+ }
+
+ // Thin-client `jobs` dispatch: `list` and `get` route over MCP (v0.32
+ // routing branches in commands/jobs.ts) and never touch a local engine —
+ // but falling through to connectEngine() below fabricates an empty
+ // scratch PGLite in the thin-client GBRAIN_HOME and replays the entire
+ // migration chain on every invocation before the remote call even runs.
+ // Dispatch them engine-free here; every other jobs subcommand is
+ // host-queue-bound, so refuse with a pinpoint hint instead of building
+ // the scratch store.
+ if (command === 'jobs') {
+ const cfgJobs = loadConfig();
+ if (isThinClient(cfgJobs)) {
+ const jobsSub = args[0];
+ if (jobsSub === 'list' || jobsSub === 'get') {
+ const { runJobs } = await import('../commands/jobs.ts');
+ await runJobs(null, args);
+ return null;
+ }
+ if (jobsSub === 'stats') {
+ // Gap-closure wave [OV6]: queue health routes via get_job_stats.
+ const { routeThinClientCommand } = await import('../commands/thin-client-routing.ts');
+ if (await routeThinClientCommand(cfgJobs!, 'jobs', args)) return null;
+ }
+ refuseThinClient('jobs', cfgJobs!.remote_mcp!.mcp_url);
+ }
+ if (args[0] === 'supervisor' && args[1] === 'status') {
+ const { DEFAULT_PID_FILE } = await import('../core/minions/supervisor.ts');
+ const { readSupervisorPid } = await import('../core/minions/supervisor-pid.ts');
+ const pidFileIndex = args.indexOf('--pid-file');
+ const pidFile = pidFileIndex >= 0 ? args[pidFileIndex + 1] ?? DEFAULT_PID_FILE : DEFAULT_PID_FILE;
+ if (readSupervisorPid(pidFile).running) {
+ const { runJobs } = await import('../commands/jobs.ts');
+ await runJobs(null, args);
+ return null;
+ }
+ }
+ }
+
+ // Autopilot status + uninstall are filesystem-only verdicts and MUST stay
+ // engine-free: a running PGLite daemon holds the exclusive DB lock, so an
+ // engine-bound status would fail to connect exactly when the exit-code
+ // contract matters (live daemon, DB outage). #1525: positional spellings
+ // resolve to flags (or exit 2 on an unknown word) BEFORE connectEngine.
+ if (command === 'autopilot') {
+ const { resolveAutopilotPositionals, runAutopilotStatus, uninstallDaemon } = await import('../commands/autopilot.ts');
+ args = resolveAutopilotPositionals(args);
+ if (args.includes('--uninstall')) { uninstallDaemon(); return null; }
+ if (args.includes('--status')) { runAutopilotStatus(args); return null; }
+ if (args.includes('--pause') || args.includes('--resume')) { (await import('../commands/autopilot-pause.ts')).runAutopilotPauseCommand(args); return null; }
+ }
+
+ // Thin-client `think` dispatch: runThinkCli already routes through
+ // callRemoteTool when isThinClient(cfg) (v0.31.1). Falling through to
+ // connectEngine() below fails with `database_url is missing` on
+ // Topology-2 installs and never reaches that branch. Official invariant:
+ // detect isThinClient BEFORE connectEngine (docs/architecture/thin-client.md).
+ // --save/--take stay server-gated; runThinkCli already warns.
+ if (command === 'think') {
+ const cfgThink = loadConfig();
+ if (cfgThink && isThinClient(cfgThink)) {
+ const { runThinkCli } = await import('../commands/think.ts');
+ await runThinkCli(null as never, args);
+ return null;
+ }
+ }
+
+ // These handlers already call their MCP twin on a thin client and never touch
+ // the engine there; run them engine-free instead of opening one (#5102).
+ if ((command === 'salience' || command === 'anomalies' || command === 'graph-query' || command === 'whoknows' || command === 'founder') &&
+ isThinClient(loadConfig())) {
+ await dispatchConnectedCommand(command, null as never, args);
+ return null;
+ }
+
+ // Every recall form but an in-process --query/--budget-tokens call has a
+ // thin-client path; that one reaches connectEngine, which refuses it.
+ if (command === 'recall' && isThinClient(loadConfig())) {
+ const { recallNeedsLocalEngine, runRecall } = await import('../commands/recall.ts');
+ if (!recallNeedsLocalEngine(args)) {
+ if (getCliOptions().brain) exitCliError(usageError(THIN_CLIENT_BRAIN_FLAG_MESSAGE, 'Remove --brain, or run from a machine with local mounts (`gbrain mounts list`).'), command);
+ await runRecall(null as never, args);
+ return null;
+ }
+ }
+ return { args, syncWatchdog };
+}
+
+/**
+ * Pipeline stage 6: the connectEngine() terminator, with jobs child-bootstrap
+ * failure reporting and degraded-serve recovery. Returns null when `serve` ran
+ * degraded (it owns its lifecycle).
+ * @cliPipelineStage
+ */
+async function connectCliOnlyEngine(command: string, args: string[]): Promise<BrainEngine | null> {
+ // All remaining CLI-only commands need a DB connection.
+ // db-availability loop (4c): `serve` alone survives a dead POSTGRES here —
+ // degraded mode keeps the MCP server present in the harness (the classified
+ // database_error envelope + GBRAIN_DB_ACCESS marker arrive in-band on every
+ // tool call) and a repaired DB recovers on the next call without a harness
+ // restart. PGLite keeps die-on-startup (its repair lane is pglite-repair;
+ // the single-writer lock makes a lazy reconnect proxy wrong there). The
+ // no-config path still exits inside connectEngine (keyless cold-home is
+ // TODOS 1050, out of scope). Kill switch: GBRAIN_SERVE_DEGRADED=0.
+ let engine: BrainEngine;
+ // F4: a serve (stdio or --http) with no brain / a missing or repair-failed brain / unreadable config
+ // answers in status-only mode instead of exiting; it re-probes through the throw-only connect.
+ // Engine graduation (§6.4): a serve (re)launched while a run owns the host brain exits 75 with graduation_in_progress.
+ if (command === 'serve' && (dbMarkerBrainId() ?? 'host') === 'host') (await import('../core/persistence/graduation-serve-guard.ts')).exitIfGraduationRunning();
+ const serveStatus = command === 'serve' ? await import('../commands/serve-status.ts') : null;
+ const serveStatusEligible = !!serveStatus?.statusModeEligible(args, (dbMarkerBrainId() ?? 'host') === 'host');
+ const preConnectReason = serveStatusEligible ? serveStatus!.preConnectStatusReason() : null;
+ if (preConnectReason) {
+ await serveStatus!.runStatusModeServe(preConnectReason, null, args, () => connectEngineForServe(ENGINE_CONNECT_HOOKS));
+ return null;
+ }
+ try {
+ // A4: an observational command connects probe-only and completes startup only after consent.
+ engine = await connectEngine({ probeOnly: findCliCommand(command)?.startup === 'observational' || (command === 'jobs' && args[0] === 'supervisor' && args[1] === 'status') });
+ } catch (serveConnectError) {
+ if (command === 'jobs' && args[0] === 'child-readiness') {
+ const { writeChildReadinessFailure } = await import('../core/minions/child-readiness.ts');
+ process.exit(writeChildReadinessFailure(serveConnectError));
+ }
+ if (command === 'jobs' && args[0] === 'run-child') {
+ const { CHILD_ENV } = await import('../core/minions/job-isolation.ts');
+ const resultPath = process.env[CHILD_ENV.resultPath];
+ if (resultPath) {
+ const { writeChildBootstrapError } = await import('../core/minions/run-child.ts');
+ process.exit(writeChildBootstrapError(resultPath, serveConnectError));
+ }
+ }
+ // Gate on the engine of the RESOLVED brain, not the host config —
+ // connectEngine routes mounts FIRST, so a PGLite mount's failure on a
+ // postgres host must NOT get a lazy reconnect proxy (the single-writer
+ // data-dir lock makes that wrong), and an unknown engine (no config)
+ // keeps die-on-startup rather than defaulting to postgres.
+ const resolvedEngineKind = await (async () => {
+ try {
+ const id = dbMarkerBrainId();
+ if (id && id !== 'host') {
+ const { loadMounts } = await import('../core/brain-registry.ts');
+ return loadMounts().find((m) => m.id === id)?.engine ?? null;
+ }
+ return loadConfig()?.engine ?? null;
+ } catch {
+ return null;
+ }
+ })();
+ // C10: a supervisor asked for fail-fast — exit non-zero with the classified envelope on stderr.
+ if (command === 'serve') {
+ const failFast = await import('../core/serve-fail-fast.ts');
+ if (failFast.serveFailFastRequested(args)) process.exit(failFast.writeServeFailFastEnvelope(serveConnectError));
+ }
+ const connectStatusReason = serveStatusEligible ? serveStatus!.statusReasonForError(serveConnectError) : null;
+ if (connectStatusReason) {
+ await serveStatus!.runStatusModeServe(connectStatusReason, serveConnectError, args, () => connectEngineForServe(ENGINE_CONNECT_HOOKS));
+ return null;
+ }
+ if (command === 'serve' &&
+ process.env.GBRAIN_SERVE_DEGRADED !== '0' &&
+ process.env.GBRAIN_SERVE_DEGRADED !== 'false' &&
+ resolvedEngineKind === 'postgres') {
+ try {
+ const d = classifyDbAccessError(serveConnectError, { url: loadConfig()?.database_url ?? null, brainId: dbMarkerBrainId() });
+ console.error(`${formatDbMarker(d)}\n${d.message}\n${d.remediation} Run: gbrain db-repair`);
+ } catch { /* marker is best-effort; degraded serve still starts */ }
+ const { createDegradedEngine } = await import('../core/degraded-engine.ts');
+ const graduationGate = (await import('../core/persistence/graduation-serve-guard.ts')).engineIdentityGate();
+ const degraded = createDegradedEngine({
+ initialError: serveConnectError,
+ // Guarded reconnect: connectEngine's no-config path calls
+ // process.exit(1) directly — if config.json disappears while serve is
+ // degraded, the reconnect must THROW into the classified envelope, not
+ // kill the live MCP server mid-RPC. HOST brains only: a mount routes
+ // through connectMountEngine before loadConfig() and needs no host
+ // config, so the guard must not brick a mount serve's recovery.
+ reconnect: async () => {
+ if ((dbMarkerBrainId() ?? 'host') === 'host') graduationGate();
+ if ((dbMarkerBrainId() ?? 'host') === 'host' && !loadConfig()) {
+ throw new Error('No brain configured (config.json missing or unreadable). Run: gbrain init');
+ }
+ return connectEngine();
+ },
+ });
+ const { runServe } = await import('../commands/serve.ts');
+ await runServe(degraded, args);
+ return null; // serve doesn't disconnect
+ }
+ throw serveConnectError;
+ }
+ return engine;
+}
+
+
+/**
+ * #3013: decide whether an invocation enters the read-only connect+dispatch
+ * timeout path, and with what wallclock. Returns null for every command
+ * dispatchReadOnlyCommand can't handle. The gate used to be "a timeout is
+ * present" — so a user-supplied --timeout on a write command (`sync`,
+ * `embed`, `import`, ...) hijacked dispatch into the read-only path, which
+ * threw and exited 1 before any work ran. Pure; exported for the
+ * regression test.
+ */
+export function resolveReadOnlyDispatchTimeoutMs(
+ command: string,
+ subArgs: string[],
+ userTimeoutMs: number | null,
+): number | null {
+ if (command !== 'search' && command !== 'sources') return null;
+ const defaultMs =
+ command === 'search' ? 30_000 :
+ (subArgs[0] === 'list' || subArgs[0] === undefined) ? 10_000 :
+ null;
+ return userTimeoutMs ?? defaultMs;
+}
+
+/**
+ * v0.41.6.0 D3: dispatch helper for the read-only commands that take a
+ * default wallclock timeout (`gbrain search`, `gbrain sources list`).
+ * Keeps the timeout-wrap site in main() small and the per-command
+ * dispatch logic colocated for easy extension. Pure dispatcher; no engine
+ * lifecycle (caller owns connect/disconnect).
+ */
+async function dispatchReadOnlyCommand(engine: BrainEngine, command: string, args: string[]): Promise<void> {
+ switch (command) {
+ case 'search': {
+ const { runSearch } = await import('../commands/search.ts');
+ await runSearch(engine, args);
+ return;
+ }
+ case 'sources': {
+ const { runSources } = await import('../commands/sources.ts');
+ await runSources(engine, args);
+ return;
+ }
+ default:
+ throw new Error(`dispatchReadOnlyCommand: unsupported command "${command}"`);
+ }
+}
+
+// Build the AIGatewayConfig payload from a GBrainConfig. Both configureGateway
+// sites in connectEngine() pass through this helper so adding a new field
+// touches one place.
+// v0.42 (#1780): moved to src/core/ai/build-gateway-config.ts so core modules
+// (init-embed-check) can reuse it without importing the CLI entrypoint. Still
+// re-exported here for back-compat with `test/ai/build-gateway-config.test.ts`
+// and other callers that import it from `../../src/cli.ts`. Imported (not just
+// re-exported) so cli.ts's own connectEngine() call sites bind it locally.
+import { buildGatewayConfig } from '../core/ai/build-gateway-config.ts';
+export { buildGatewayConfig };
+import { connectEngineForServe, noBrainError, type EngineConnectHooks } from '../core/engine-connect.ts';
+
+/**
+ * Which brain this process's engine targets. Set by connectEngine after brain
+ * resolution; read by makeContext so ctx.brainId carries the audit id. Never
+ * derived from op params — an untrusted caller must not be able to name a
+ * brain (same fail-closed shape as the #3524 remote source sentinel).
+ */
+let activeBrainId: string = 'host';
+
+/** The command main() dispatched; connectEngine's thin-client refusal names it. */
+let dispatchedCommand = '';
+
+/**
+ * Connect to a mounted brain (brain axis, non-host). Routes through
+ * BrainRegistry so:
+ * - an unknown/disabled mount id throws UnknownBrainError. Fail-closed:
+ * the pre-fix CLI silently fell back to the host brain, returning
+ * confident wrong answers (mirror of #3524's explicit --source decision);
+ * - postgres mounts get a per-instance pool, never the db.ts singleton;
+ * - NO migrations run against the mount — schema is the publisher's job
+ * (same decision as BrainRegistry.initMountBrain). Write access control
+ * is the mount's own DB credential grants: a read-only role rejects
+ * writes at the database; gbrain does not re-implement that client-side.
+ * The AI gateway still configures from the HOST config (the caller's API
+ * keys + model tiers) — embedding/expansion spend stays the caller's, and
+ * a mount's DB-plane model config is never merged into the caller's gateway.
+ */
+async function connectMountEngine(brainId: string): Promise<BrainEngine> {
+ const config = loadConfig();
+ if (config) {
+ const { configureGateway } = await import('../core/ai/gateway.ts');
+ configureGateway(buildGatewayConfig(config));
+ }
+ const { loadRegistry } = await import('../core/brain-registry.ts');
+ const handle = await loadRegistry().getBrain(brainId);
+ activeBrainId = brainId;
+ // Fixup (PR #4186): mark this specific engine as a mount engine so
+ // makeContext's DB-plane fallback (see MOUNT_ENGINES above) never re-merges
+ // a mount's config into the caller's context, regardless of what other
+ // engine — host or another mount — this process may also be holding.
+ MOUNT_ENGINES.add(handle.engine);
+ SELECTED_CONFIG_BY_ENGINE.set(handle.engine, handle.config);
+ return handle.engine;
+}
+
+async function connectEngine(opts?: { probeOnly?: boolean }): Promise<BrainEngine> {
+ // Brain axis: resolve WHICH DATABASE this invocation targets before touching
+ // the host engine. --brain (global flag) / GBRAIN_BRAIN_ID / .gbrain-mount /
+ // mount-path-prefix resolve via the canonical 6-tier chain — the mirror of
+ // the source axis in makeContext. connectEngine is the single choke point
+ // every local CLI command routes through (shared ops, CLI-only commands,
+ // and the search-dashboard path), so routing lands here once.
+ const { resolveBrainId } = await import('../core/brain-resolver.ts');
+ const brainId = resolveBrainId(getCliOptions().brain);
+ if (brainId !== 'host') return exitOnRepairFailed(() => connectMountEngine(brainId));
+
+ const config = loadConfig();
+ if (!config) {
+ // db-availability loop: this exit never reaches the bottom rejection
+ // handler (direct process.exit), so the no_url marker is emitted HERE.
+ // There is no error object on this path — diagnoseDbConfig is the
+ // errorless config-plane entry point, never a faked Error.
+ try {
+ const d = diagnoseDbConfigForMarker({ source: getDbUrlSource(), envShadowed: envShadowDetected(), brainId });
+ if (d && shouldEmitDbAccessMarker()) {
+ console.error(formatDbMarker(d));
+ }
+ if (d?.reason === 'env_shadowed') console.error(d.remediation);
+ } catch { /* marker is best-effort — the message below always prints */ }
+ exitCliError(noBrainError(), cliCommandOf());
+ }
+
+ // A thin client has no local database. Every command that gets here would die
+ // with "No database URL" (whose suggested init replaces remote_mcp) or answer
+ // from an empty in-memory PGLite, so refuse with the routing hint (#5102).
+ if (isThinClient(config) && !config.database_url) {
+ refuseThinClient(dispatchedCommand, config.remote_mcp!.mcp_url);
+ }
+ // The throw-only connect (src/core/engine-connect.ts) behind the CLI's exits.
+ return exitOnRepairFailed(() => connectEngineForServe(ENGINE_CONNECT_HOOKS, opts));
+}
+
+/** A6/D1: the pending-migrations warning as a notice whose fix applies them (stderr; stdout stays the command's). */
+function migrationsNotice(why: string): Notice {
+ return { code: 'migrations_pending', kind: 'safety', why, fix: { argv: ['gbrain', 'apply-migrations', '--yes'], consent: [], actor: 'agent',
+ requires_exclusive: true, why: 'Applies the pending schema migrations (the same ones every command applies on connect).', verify: { argv: ['gbrain', 'doctor', '--json'] } } };
+}
+
+/** Startup after the probe-only connect: migrations, retired-marker cleanup, DB-plane config merge. Mounts: none. */
+async function completeEngineStartup(engine: BrainEngine): Promise<void> {
+ const config = SELECTED_CONFIG_BY_ENGINE.get(engine);
+ if (!config || MOUNT_ENGINES.has(engine)) return;
+
+ // v0.41.6.0 D4: race-tolerant CLI-side migration runner. Replaces the
+ // pre-v0.41.6.0 `try { hasPendingMigrations && initSchema() } catch warn`
+ // block that fired the alarming "Schema probe/migrate failed: deadlock
+ // detected" warning on EVERY sync when two CLIs raced on schema probe.
+ // The retry+poll loop quiets the warning when the race resolves
+ // itself (the common case); the revised wording fires only when
+ // migrations are genuinely stuck.
+ try {
+ const { tryRunPendingMigrations } = await import('../core/migrate.ts');
+ const result = await tryRunPendingMigrations(engine);
+ if (result.status === 'persistent') {
+ writeCliNotice(migrationsNotice('Schema migrations are pending: another process attempted them but they did not complete within the retry window (usually transient). If it persists, check `gbrain doctor` for stale advisory locks and `gbrain jobs supervisor status` for crashed migration workers.'));
+ } else if (result.status === 'error') {
+ // Non-deadlock error during initSchema. Surface the message and continue;
+ // subsequent operations will resurface the real schema error in context.
+ writeCliNotice(migrationsNotice(`Schema probe failed: ${result.error.message}`));
+ }
+ // 'ok', 'not_needed', 'race_resolved' → silent (the common-case outcomes).
+ } catch (err) {
+ // Last-resort defense in case the helper itself throws unexpectedly.
+ writeCliNotice(migrationsNotice(`Schema probe failed (unexpected): ${(err as Error).message}`));
+ }
+
+ // #5628: drop this host's markers of a retired managed epoch before any filesystem guard check.
+ try { await (await import('../core/persistence/deactivation.ts')).cleanupRetiredManagedMarkers(engine); } catch { /* status reports pending markers */ }
+
+ // v0.27.1 (F3 fix): re-merge DB-plane config now that the engine is up.
+ // Flags like `embedding_multimodal` are user-mutable via `gbrain config set`
+ // (DB plane) and need to flow into the gateway after connect. Schema-sizing
+ // fields (embedding_dimensions etc.) keep their pre-connect file/env values
+ // — those drove initSchema and the merged config respects file/env first.
+ try {
+ const merged = await loadConfigWithEngine(engine, config);
+ if (merged) {
+ // #1475 — hand the merged config to makeContext instead of letting it
+ // re-derive one. See MERGED_CONFIG_BY_ENGINE: the op-side gates read
+ // ctx.config, and re-running the merge there would double this
+ // function's per-key config reads on every command (the cost #3980 is
+ // about). Keyed on the engine so a mounted brain cannot be served the
+ // host brain's merge.
+ MERGED_CONFIG_BY_ENGINE.set(engine, merged);
+ // Stash gate flags on process.env for downstream readers (import-file.ts
+ // dispatches on GBRAIN_EMBEDDING_MULTIMODAL, gates OCR on GBRAIN_EMBEDDING_IMAGE_OCR).
+ // The OCR *model* reaches the gateway via the re-configure below (#4107); its
+ // env stash stays so subprocesses re-fold it through loadConfig's env merge.
+ if (merged.embedding_multimodal !== undefined) {
+ process.env.GBRAIN_EMBEDDING_MULTIMODAL = String(merged.embedding_multimodal);
+ }
+ if (merged.embedding_image_ocr !== undefined) {
+ process.env.GBRAIN_EMBEDDING_IMAGE_OCR = String(merged.embedding_image_ocr);
+ }
+ if (merged.embedding_image_ocr_model !== undefined) {
+ process.env.GBRAIN_EMBEDDING_IMAGE_OCR_MODEL = merged.embedding_image_ocr_model;
+ }
+ // Always re-configure with merged values when DB merge succeeded. The
+ // trigger used to be field-name-gated (only when embedding_multimodal_model
+ // was set); that coupled the gate to the field set and would silently
+ // miss future DB-mutable gateway fields. One extra cache+shrinkState
+ // clear per startup is microseconds, no hot path.
+ (await import('../core/ai/gateway.ts')).configureGateway(buildGatewayConfig(merged));
+ }
+ // v0.31.12: re-resolve gateway defaults through resolveModel so
+ // `models.tier.*` and `models.default` overrides apply to expansion +
+ // chat. Per Codex F3 — configureGateway is sync; this is the async
+ // re-stamp seam after engine.connect() makes config reads possible.
+ const { reconfigureGatewayWithEngine } = await import('../core/ai/gateway.ts');
+ await reconfigureGatewayWithEngine(engine);
+ } catch {
+ // Non-fatal. Pre-v39 brains may not have a usable config table yet.
+ }
+
+ // The one-time behavior-change disclosure on the CLI channel (stderr). `serve`
+ // delivers it per MCP channel; `doctor` reads it without marking it shown.
+ if (dispatchedCommand !== 'serve' && dispatchedCommand !== 'doctor') {
+ try {
+ const { takeLocalBehaviorNotice } = await import('../core/behavior-change-notice.ts');
+ const notice = await takeLocalBehaviorNotice(engine, 'cli', { cfg: MERGED_CONFIG_BY_ENGINE.get(engine) ?? config });
+ if (notice) writeCliNotice(notice);
+ } catch { /* a disclosure never breaks a command */ }
+ }
+}
+
+/** CLI-only usage examples appended to `gbrain <command> --help`. */
+const OP_HELP_EXAMPLES: Record<string, string[]> = {
+ get_links: [
+ 'gbrain links people/alice-example # resolved source (every federated source when unpinned)',
+ 'gbrain links people/alice-example --source business # one source',
+ 'gbrain links people/alice-example --all-sources # every source',
+ ],
+ get_backlinks: [
+ 'gbrain backlinks companies/acme-example',
+ 'gbrain backlinks companies/acme-example --source-id business',
+ 'gbrain backlinks companies/acme-example --all-sources --json',
+ ],
+ // #6255: the receipt command's routing flags and states.
+ get_write_request: ['gbrain write-request --brain host -- <request_id> [--json] # queued/running: pending, read again after retry_after_ms; committed/conflict/failed/cancelled: final'],
+ traverse_graph: [
+ 'gbrain graph people/alice-example --depth 2',
+ 'gbrain graph people/alice-example --source business --direction both',
+ 'gbrain graph people/alice-example --all-sources # same slug in two sources stays two nodes (source_id)',
+ ],
+};
+
+export function printOpHelp(op: Operation, invokedName?: string) {
+ const positional = (op.cliHints?.positional || []).map(p => `<${p}>`).join(' ');
+ // v114 (#1941): when invoked via an alias (e.g. `gbrain link-add --help`),
+ // show the alias the user typed, not the primary op name.
+ const name = invokedName || op.cliHints?.name || op.name;
+ const stdinKey = op.cliHints?.stdin;
+ const stdinFlag = stdinKey ? `--${stdinKey.replace(/_/g, '-')}` : '';
+ console.log(`Usage: gbrain ${name} ${positional} [options]`);
+ if (stdinKey) console.log(` gbrain ${name} ${positional} [options] < file (${stdinFlag} read from stdin)`);
+ console.log('\n' + op.description + '\n');
+ const entries = Object.entries(op.params);
+ if (entries.length > 0) {
+ console.log('Options:');
+ for (const [key, def] of entries) {
+ const isPos = op.cliHints?.positional?.includes(key);
+ const req = key === stdinKey
+ ? ` (required: ${stdinFlag} needs a value; omit ${stdinFlag}, or put it last, to read stdin)`
+ : def.required ? ' (required)' : '';
+ const prefix = isPos ? ` <${key}>` : ` --${key.replace(/_/g, '-')}`;
+ console.log(`${prefix.padEnd(28)} ${def.description || ''}${req}`);
+ }
+ }
+ const examples = OP_HELP_EXAMPLES[op.name];
+ if (examples) console.log(`\nExamples:\n${examples.map((line) => ` ${line}`).join('\n')}`);
+}
+
+/**
+ * #2084 — the ONE process-exit seam for one-shot commands. Every teardown site
+ * routes through finishCliTeardown (which returns); the exit itself happens
+ * here, after main() settles, so the CLI never waits on Bun's event loop to
+ * drain (stuck PgBouncer sockets kept it alive — endPoolBounded races PAST a
+ * stuck pool.end() by design). flushThenExit fences stdout/stderr and waits
+ * for queued pipe output before exit (#1959).
+ * Daemons (`serve`) are excluded by shouldForceExitAfterMain and keep the
+ * pre-#2084 behavior: main() resolves and the server's own work keeps the
+ * process alive. A fatal error still exits 1 for every command, daemons
+ * included (matches the prior unconditional process.exit(1) on rejection).
+ * src/cli.ts runs the process-level setup (Bun floor, signal handlers, stdout
+ * delivery) before calling this.
+ */
+export function runCli(): void {
+ main().then(
+ () => {
+ if (shouldForceExitAfterMain()) flushThenExit(currentExitCode());
+ },
+ exitOnFatalCliError,
+ );
+}
+
+/**
+ * D1: the fatal seam renders through renderCliError (one --json envelope on
+ * stdout; human `Error [code]` / `Fix:` on stderr), keeping the pglite_busy
+ * keys and the GBRAIN_DB_ACCESS marker. A renderer fault must never lose the
+ * error, so the raw message is the fallback.
+ */
+export function exitOnFatalCliError(e: any): void {
+ let exitCode = 1;
+ try {
+ exitCode = writeFatalCliError(e, { dbUrl: loadConfig()?.database_url ?? null, brainId: dbMarkerBrainId() });
+ } catch {
+ console.error(e?.message || e);
+ }
+ flushThenExit(exitCode);
+}
diff --git a/src/cli/top-help.ts b/src/cli/top-help.ts
new file mode 100644
index 0000000000..8729af9b85
--- /dev/null
+++ b/src/cli/top-help.ts
@@ -0,0 +1,214 @@
+/**
+ * Top-level `gbrain` / `gbrain --help` usage text. Engine-free and import-light
+ * so src/cli.ts can answer it on the fast path without loading the dispatcher
+ * (src/cli/main.ts), which prints the same text on its own `--help` route.
+ */
+import { VERSION } from '../version.ts';
+
+export function printHelp() {
+ console.log(`gbrain ${VERSION} -- personal knowledge brain
+
+USAGE
+ gbrain <command> [options]
+
+SETUP
+ mcp grant <name> --help Grant hosted access; private credential handoff
+ mcp verify --help Verify connection, permissions, and memory
+ init [--pglite|--supabase|--url] Create brain (PGLite default, no server)
+ init --prefer-postgres [--allow-docker]
+ Postgres-first install ladder (env URL >
+ Supabase token > local PG > docker > PGLite)
+ engine status [--json] [--probe] Which engine + URL source, engine-free
+ db-repair [--yes] [--json] Diagnose/fix Postgres access, engine-free
+ (--yes --apply-rewrites for config rewrites)
+ migrate --to <postgres|pglite> Move the brain between engines (PGLite -> Postgres graduates: plan, then --yes --expect)
+ migrate embeddings --to <p:model> Re-embed onto another embedding provider
+ embeddings enable --embedding-model <p:model> Turn on embeddings in place (keeps pages/facts)
+ upgrade Self-update
+ check-update [--json] Check for new versions
+ repair [<kind>] [--apply] Preview/apply residual repairs (timeline, visibility, safe-chunks)
+ projections drain [--limit n] Rebuild queued text projections now [--json]
+ doctor [--json] [--fast] [--probe-pglite] Health check (resolver, skills, pgvector, RLS, embeddings; --probe-pglite runs the scratch-store probe)
+ integrations [subcommand] Manage integration recipes (senses + reflexes)
+
+PAGES
+ get <slug> Read a page
+ put <slug> [< file.md] Write/update a page
+ delete <slug> Delete a page
+ list [--type T] [--tag T] [--limit N]
+ List pages
+
+SEARCH
+ search <query> Keyword search (tsvector)
+ query <question> [--no-expand] Hybrid search (RRF + expansion)
+ ask <question> [--no-expand] Alias for query
+
+IMPORT/EXPORT
+ import <dir> [--no-embed] Import markdown directory
+ sync [--repo <path>] [flags] Git-to-brain incremental sync
+ sync --watch [--interval N] Continuous sync (loops until stopped)
+ See also: autopilot --install (continuous daemon).
+ sync --all --missing-path skip Classify sources whose local_path is absent
+ on this machine as skipped, not failed
+ export [--source <id>] [--dir <p>] Coherent Markdown snapshot; fresh output, no overwrite
+ export --restore-only [--repo <p>] Restore missing db_only files; export --help for safe retry
+ [--type T] [--slug-prefix S] With optional filters
+
+FILES
+ files list [slug] List stored files
+ files upload <file> --page <slug> Upload file to storage
+ files upload-raw <file> --page <s> Smart upload (size routing + .redirect.yaml)
+ files signed-url <path> Generate signed URL (1-hour)
+ files sync <dir> Bulk upload directory
+ files verify Verify all uploads
+
+EMBEDDINGS
+ embed [<slug>|--all|--stale] Generate/refresh embeddings
+
+LINKS
+ link <from> <to> Create typed link (alias: link-add)
+ [--link-type T] [--link-source S] provenance defaults to 'manual'
+ unlink <from> <to> Remove link (alias: link-rm)
+ [--link-type T] [--link-source S] filter which edges to remove
+ link-sources List provenances in use, with edge counts
+ backlinks <slug> Incoming links
+ graph <slug> [--depth N] Traverse link graph (nodes locally; remote MCP defaults to bidirectional edges)
+ graph-query <slug> [--type T] Edge-based traversal with type/direction filters
+ [--depth N] [--direction in|out|both]
+
+TAGS
+ tags <slug> List tags
+ tag <slug> <tag> Add tag
+ untag <slug> <tag> Remove tag
+
+TIMELINE
+ timeline [<slug>] View timeline
+ timeline-add <slug> <date> <text> Add timeline entry
+
+TOOLS
+ extract <links|timeline|all> Extract links/timeline (idempotent)
+ [--source fs|db] [--source-id ID] [--dir <brain>]
+ [--type T] [--since DATE] [--include-frontmatter]
+ [--workers N|--concurrency N] [--dry-run] [--json]
+ extract links --by-mention [--ner] --source db
+ extract timeline --from-meetings [--infer-dates] --source db
+ extract --stale [--source-id ID] [--catch-up] [--dry-run] [--json]
+ extract links --source db --repair-attendance --source-id ID
+ [--limit 250] [--after-slug SLUG] [--json]
+ Apply: --apply-preview FILE --confirm DIGEST --yes --backup-verified --checkpoint FILE
+ extract --explain <kind> [--json] Full details: gbrain extract --help
+ publish <page.md> [--password] Shareable HTML (strips private data, optional AES-256)
+ check-backlinks <check|fix> [dir] Find/fix missing back-links across brain
+ lint <dir|file> [--fix] Catch LLM artifacts, placeholder dates, bad frontmatter
+ backfill <kind|list> v0.30.1: run a registered backfill (effective-date, ...)
+ orphans [--json] [--count] Find pages with no inbound wikilinks
+ salience [--days N] [--kind P] v0.29: pages ranked by emotional + activity salience
+ anomalies [--since D] [--sigma N] v0.29: cohort-based statistical anomalies (tag, type)
+ feedback <status|reset> retrieval feedback: learned page weights; rate answers with gbrain rate
+ transcripts <ingest|status|recent> v0.46: import agent session logs + chat exports (local-only)
+ dream [--dry-run] [--json] Run the overnight maintenance cycle once (cron-friendly).
+ See also: autopilot --install (continuous daemon).
+ compile-context --target <t> Compile a deterministic, scanned, budgeted context
+ [--budget N] [--check] file (claude-code | codex | openclaw)
+ decide <status|probe|enable|...> System One decision support (Jev); every slot off by default
+ facts relink [--dry-run] Link facts saved without an entity to the entity they name
+ check-resolvable [--json] [--fix] Validate skill tree (reachability/MECE/DRY)
+ report --type <name> --content ... Save timestamped report to brain/reports/
+
+OPEN LOOPS (Gmail/Calendar/Contacts connector — v0.47)
+ google setup [--account <email>] One command: BYO OAuth → source → first sync → first digest
+ google connect|status|disconnect Connect/inspect/remove a Google account (idempotent; --json)
+ waiting [--top N] [--json] Who is waiting on you, what you promised, context to respond
+ loops list|show|done|drop|mute Inspect and manage open loops (mute sender <email>)
+ core list|show|status|add|remove Always-loaded core memory (also diff|ack|init|suggest)
+ creds list|remove|export|import Generic credential vault (redacted output; encrypted bundles)
+
+BRAIN (capture / ideate / explore — v0.37/v0.38)
+ capture [content] [--file PATH] Single entrypoint for getting content into the brain
+ [--stdin] [--slug s] [--type t] Inline content / file / stdin; writes to inbox/ by default
+ [--source ID] [--quiet|--json] Multi-source brains: route to a non-default source
+ brainstorm <question> [--json] Bisociation idea generator (hybrid search + far-set + judge)
+ [--save|--no-save] [--limit N]
+ lsd <question> [--json] Lateral Synaptic Drift: inverted-judge brainstorm
+ [--save|--no-save] [--limit N] rewarding far-from-obvious + axiomatic inversions
+ think "<question>" [--anchor <s>] Multi-hop cited synthesis across pages + takes + graph
+ [--save] [--source <id>] Full flags: gbrain think --help
+
+SOURCES (multi-repo / multi-brain)
+ sources list Show registered sources
+ sources add <id> --path <p> Register a source (id = short name, e.g. 'wiki')
+ sources remove <id> Remove a source + its pages (--confirm-destructive)
+ sources archive <id> Soft-delete: hide from search, recoverable for 72h
+ sources restore <id> Un-archive a soft-deleted source
+ sources archived List soft-deleted sources and their purge expiry
+ sources purge [<id>] Permanently delete archived sources
+ sources status Per-source dashboard (sync lag, embed coverage)
+ sources --help Full subcommand list (rename, default, attach,
+ current, federate, set-cr-mode, webhook, harden, ...)
+ sync --all Sync all sources with a local_path
+ sync --source <id> Sync one specific source
+ repos ... DEPRECATED alias for 'sources' (v0.19.0)
+
+CODE INDEXING (v0.19.0 / v0.20.0 Cathedral II)
+ code-def <symbol> [--lang l] Find the definition of a symbol across code pages
+ code-refs <symbol> [--lang l] Find all references to a symbol (JSON-first)
+ code-callers <symbol> Who calls this symbol? (v0.20.0 A1)
+ code-callees <symbol> What does this symbol call? (v0.20.0 A1)
+ query <q> --lang <l> Filter hybrid search to one language (v0.20.0)
+ query <q> --symbol-kind <k> Filter to symbol type (function|class|method|...) (v0.20.0)
+ reconcile-links [--dry-run] Batch-recompute doc↔impl edges (v0.20.0)
+ reindex-code [--source id] [--yes] [--force] Explicit code-page reindex (v0.20.0; --force re-chunks unchanged pages)
+ reindex-search-vector [--dry-run] [--yes] [--json]
+ Recreate FTS triggers + backfill under
+ $GBRAIN_FTS_LANGUAGE (default 'english')
+ sync --strategy code Sync code files into the brain
+
+JOBS (Minions)
+ jobs submit <name> [--params JSON] Submit background job [--follow] [--dry-run]
+ jobs list [--status S] [--limit N] List jobs [--json]
+ jobs get <id> [--json] Job details + history
+ jobs cancel <id> Cancel job
+ jobs retry <id> Re-queue failed/dead job
+ jobs prune [--older-than 30d] Clean old jobs
+ jobs stats [--json] Job health dashboard
+ jobs watch [--follow] Live queue dashboard
+ jobs work [--queue Q] Start worker daemon (Postgres only)
+ jobs supervisor [start|status|stop] Auto-restarting worker wrapper
+
+ADMIN
+ stats Brain statistics
+ health Brain health dashboard
+ history <slug> [--json] Page version history
+ revert <slug> <version-id> Revert to version
+ features [--json] [--auto-fix] Scan usage + recommend unused features
+ autopilot [--repo] [--interval N] Self-maintaining brain daemon
+ config [show|get|set] <key> [val] Brain config
+ pricing [set|list|unset] <model> Register model prices for cost caps (host only)
+ protocol [conformance|stats] MEMORY_VERBS v1: schemas, conformance
+ certification, local usage stats + TTHW
+ storage status [--repo <path>] Storage tier status and health
+ [--json] (git-tracked vs supabase-only)
+ serve MCP server (stdio)
+ --surface verbs|starter|full Tool surface: the 7 memory verbs, the ~20-op
+ starter set, or every op (default full).
+ On --http this is the per-client CEILING.
+ --access read-only|full stdio: list and dispatch only read operations
+ serve --http [--port N] HTTP MCP server with OAuth 2.1
+ --token-ttl N Access token TTL in seconds, 60-7776000 (default: 3600)
+ --enable-dcr Enable Dynamic Client Registration (DCR clients default to authorization_code)
+ --enable-dcr-insecure Also allow the consent-bypassing client_credentials grant on DCR (implies --enable-dcr)
+ --public-url URL Public issuer URL (required behind proxy/tunnel)
+ connect <mcp-url> --token <t> Wire Claude Code to a remote gbrain (bearer token)
+ [--install] [--json] Print the paste-ready command, or --install to run it
+ auth <create|list|revoke|...> Manage legacy tokens + OAuth 2.1 clients
+ auth --help Full subcommand list (register-client,
+ rescope, rescope-client, rescope-token, revoke-client, ...)
+ watch [--json] Push-based context: pipe conversation turns in,
+ volunteered brain pages stream out (#2095)
+ call <tool> '<json>' Raw tool invocation
+ version Version info
+ --tools-json Tool discovery (JSON)
+
+Run gbrain <command> --help for command-specific help.
+`);
+}
diff --git a/src/core/cli-force-exit.ts b/src/core/cli-force-exit.ts
index d612500380..6a829844c0 100644
--- a/src/core/cli-force-exit.ts
+++ b/src/core/cli-force-exit.ts
@@ -34,9 +34,11 @@
* shouldForceExitAfterMain() && flushThenExit(currentExitCode())
* — drain the serialized stdout tail if any interposed write is still in
* flight (#4383, ref'd keepalive), then fence stdout+stderr (write-fence
- * raced with an unref'd guard, EPIPE-safe), hold a short REF'D aliveness
- * grace for non-TTY stdio (Bun only delivers queued pipe writes while
- * alive), then process.exit. Stuck sockets become irrelevant.
+ * raced with an unref'd guard, EPIPE-safe), then process.exit as soon as
+ * no non-TTY stream has queued bytes: a REF'D aliveness grace bounds the
+ * wait for a stream still draining (Bun only delivers queued pipe writes
+ * while alive) and stays a fixed sleep only for a stream whose queue
+ * this module cannot see. Stuck sockets become irrelevant.
*
* The hard-deadline timer is armed at TEARDOWN start, never before the op
* handler — a slow-but-healthy handler must not erode the teardown budget
@@ -95,15 +97,19 @@ const TEARDOWN_SLACK_MS = 2_000;
/** Max wait for the stdio flush fence before exiting anyway (blocked pipe). */
const FLUSH_GUARD_MS = 2_000;
/**
- * Aliveness grace between the fence and process.exit when stdio is NOT a TTY.
- * Empirically verified (#2084 probes): Bun's process.stdout queues pipe writes
- * in a native writer that only pushes to the fd on event-loop turns WHILE THE
- * PROCESS IS ALIVE — process.exit discards the queue, natural event-loop exit
- * discards it too, and no API reaches it (write callbacks fire on accept, not
- * delivery; writableLength/bytesWritten read 0 throughout;
- * Bun.stdout.writer().flush() is a different writer; fs.writeSync(1) is also
- * queued). Staying alive briefly is the ONLY flush. TTY writes are synchronous
- * — no grace needed there.
+ * Upper bound on the aliveness grace between the fence and process.exit when
+ * stdio is NOT a TTY. Empirically verified (#2084 probes): Bun's
+ * process.stdout/stderr queue pipe writes in a native writer that only pushes
+ * to the fd on event-loop turns WHILE THE PROCESS IS ALIVE — process.exit
+ * discards the queue, natural event-loop exit discards it too (write callbacks
+ * fire on accept, not delivery; writableLength/bytesWritten read 0 throughout).
+ * What Bun 1.4 does expose: write() returns false exactly when bytes stayed
+ * queued (a write the fd took whole returns true), and 'drain' fires once the
+ * queue is empty again. trackNativeBacklog reads that signal on process.stderr,
+ * and process.stdout's one-shot writes go through the fd-1 write chain, so the
+ * exit seam knows when nothing is queued and exits without waiting. The grace
+ * only runs while a tracked stream is still draining (ending at its 'drain')
+ * or for a stream nothing tracks. TTY writes are synchronous — no grace there.
*/
const FLUSH_GRACE_PIPE_MS = 250;
@@ -246,10 +252,12 @@ export interface FlushThenExitOpts {
stderr?: MinimalWritable;
guardMs?: number;
/**
- * Aliveness window between the fence and exit. Default: 0 when BOTH stdio
- * streams are TTYs (synchronous writes), FLUSH_GRACE_PIPE_MS otherwise.
- * The grace timer is deliberately ref'd — keeping the loop alive is the
- * only thing that delivers Bun's queued pipe writes (see module constant).
+ * Longest aliveness window between the fence and exit. Default: 0 when BOTH
+ * stdio streams are TTYs (synchronous writes), FLUSH_GRACE_PIPE_MS otherwise.
+ * It ends early once every non-TTY stream is known to hold no queued bytes
+ * (streamQueueState). The grace timer is deliberately ref'd — keeping the
+ * loop alive is the only thing that delivers Bun's queued pipe writes (see
+ * module constant).
*/
graceMs?: number;
}
@@ -262,9 +270,12 @@ export interface FlushThenExitOpts {
* queue; an unref'd guard bounds a stream whose callback never fires.
* (In Bun the callback fires on ACCEPT, not delivery — the fence alone is
* NOT sufficient; verified in the #2084 probes.)
- * 2. Aliveness grace: a REF'D timer keeps the process alive `graceMs` so
- * Bun's native writer can push the queued bytes to the fd / a consuming
- * reader (#1959 truncation class). TTY stdio skips this (sync writes).
+ * 2. Aliveness grace: a REF'D timer keeps the process alive up to `graceMs`
+ * so Bun's native writer can push the queued bytes to the fd / a
+ * consuming reader (#1959 truncation class). It is skipped when every
+ * non-TTY stream is known to be empty, and ends at the 'drain' of the
+ * tracked streams still holding bytes; a stream nothing tracks gets the
+ * full grace. TTY stdio skips this (sync writes).
*
* A reader that consumes nothing for longer than guard+grace loses the tail —
* unavoidable without waiting forever; strictly better than the pre-#2084
@@ -299,12 +310,31 @@ export function flushThenExit(code: number, opts: FlushThenExitOpts = {}): void
if (fenced) return;
fenced = true;
if (guard) clearTimeout(guard);
- if (graceMs <= 0) {
+ const states = streams
+ .filter((s) => (s as { isTTY?: boolean }).isTTY !== true)
+ .map((s) => ({ s, state: streamQueueState(s) }))
+ .filter(({ state }) => state !== 'empty');
+ if (graceMs <= 0 || states.length === 0) {
exit(code);
return;
}
+ let exited = false;
+ const exitOnce = () => {
+ if (exited) return;
+ exited = true;
+ clearTimeout(grace);
+ exit(code);
+ };
// Ref'd on purpose: aliveness IS the flush (Bun pipe-write semantics).
- setTimeout(() => exit(code), graceMs);
+ const grace = setTimeout(exitOnce, graceMs);
+ if (states.some(({ state }) => state === 'unknown')) return;
+ let draining = states.length;
+ for (const { s } of states) {
+ s.once?.('drain', () => {
+ draining -= 1;
+ if (draining === 0) exitOnce();
+ });
+ }
};
let pending = streams.length;
const done = () => {
@@ -433,6 +463,46 @@ interface StdoutQueueEntry {
settle: () => void;
}
+/** Native-writer queue state of the streams trackNativeBacklog wrapped. */
+const nativeBacklog = new WeakMap<object, { queued: boolean }>();
+
+/**
+ * Record when Bun's native writer is holding queued bytes for `stream`:
+ * write() returns false exactly when part of the chunk stayed queued, and
+ * 'drain' fires once the queue is empty (Bun 1.4 pipe semantics, pinned by
+ * test/cli-exit-drain.test.ts). Lets the exit seam skip the aliveness grace
+ * when nothing is queued instead of sleeping on every exit.
+ */
+function trackNativeBacklog(stream: NodeJS.WriteStream): void {
+ if (nativeBacklog.has(stream)) return;
+ const state = { queued: false };
+ nativeBacklog.set(stream, state);
+ const write = stream.write.bind(stream) as (...args: unknown[]) => boolean;
+ stream.write = function (...args: unknown[]): boolean {
+ const accepted = write(...args);
+ if (!accepted && !state.queued) {
+ state.queued = true;
+ stream.once('drain', () => {
+ state.queued = false;
+ });
+ }
+ return accepted;
+ } as typeof stream.write;
+}
+
+/**
+ * Whether `stream` may still hold bytes the process must stay alive to
+ * deliver: 'empty' (process.stdout behind the fd-1 write chain, or a tracked
+ * stream with nothing queued), 'queued' (a tracked stream waiting for its
+ * 'drain'), or 'unknown' (anything nothing tracks — the fixed grace applies).
+ */
+function streamQueueState(stream: MinimalWritable): 'empty' | 'queued' | 'unknown' {
+ if (stream === process.stdout && stdoutInterposed) return 'empty';
+ const state = nativeBacklog.get(stream);
+ if (!state) return 'unknown';
+ return state.queued ? 'queued' : 'empty';
+}
+
/** FIFO of deferred payloads: every routed stdout write settles in order. */
const stdoutQueue: StdoutQueueEntry[] = [];
/** Writes on the queue that have not yet settled (0 ⇒ safe to start eagerly). */
@@ -683,6 +753,7 @@ function chainStdoutWrite(data: string | Uint8Array, encoding?: BufferEncoding):
*/
export function installStdoutPipeDelivery(opts: { json?: 'document' | 'ndjson' } = {}): void {
if (stdoutInterposed) return;
+ if (!process.stderr.isTTY) trackNativeBacklog(process.stderr);
// Agent contract v1 (D2 guard mode): under `--json` the guard installs even
// on a TTY, because the contract is "fd 1 carries exactly the document".
if (process.stdout.isTTY && !opts.json) return;
diff --git a/src/core/thin-client-upgrade-prompt.ts b/src/core/thin-client-upgrade-prompt.ts
index 33174e5503..ced55b9b2a 100644
--- a/src/core/thin-client-upgrade-prompt.ts
+++ b/src/core/thin-client-upgrade-prompt.ts
@@ -22,7 +22,7 @@
import { existsSync, readFileSync, writeFileSync, renameSync, openSync, closeSync, unlinkSync, statSync, mkdirSync } from 'fs';
import { dirname } from 'path';
import { execSync, execFileSync } from 'child_process';
-import { compareVersions } from '../commands/migrations/index.ts';
+import { compareVersions } from './migration-ledger.ts';
import { gbrainPath } from './config.ts';
import type { GBrainConfig } from './config.ts';
import { promptLineStderr } from './cli-util.ts';
diff --git a/test/ai/build-gateway-config.test.ts b/test/ai/build-gateway-config.test.ts
index 4006944d9a..b3cb39b7d5 100644
--- a/test/ai/build-gateway-config.test.ts
+++ b/test/ai/build-gateway-config.test.ts
@@ -19,7 +19,7 @@
*/
import { describe, expect, test } from 'bun:test';
-import { buildGatewayConfig } from '../../src/cli.ts';
+import { buildGatewayConfig } from '../../src/cli/main.ts';
import { KNOWN_CONFIG_KEYS, type GBrainConfig } from '../../src/core/config.ts';
import { withEnv } from '../helpers/with-env.ts';
@@ -385,7 +385,7 @@ describe('buildGatewayConfig import side effect guard', () => {
// already ran by the time describe() executes. Re-importing here is
// belt-and-suspenders: any future test that splits the suite would still
// exercise the side-effect contract from a fresh module record.
- const mod = await import('../../src/cli.ts');
+ const mod = await import('../../src/cli/main.ts');
expect(typeof mod.buildGatewayConfig).toBe('function');
// Build a synthetic config and call it. Pre-fix behavior: importing the
@@ -406,7 +406,7 @@ describe('buildGatewayConfig import side effect guard', () => {
// Post-fix: stdout is empty; only the bun runtime header / warnings may
// appear on stderr.
const inline = `
- import { buildGatewayConfig } from './src/cli.ts';
+ import { buildGatewayConfig } from './src/cli/main.ts';
const cfg = buildGatewayConfig({});
// Touch the result so the engine does not dead-code-eliminate the call.
if (!cfg) process.exit(2);
diff --git a/test/all-sources-sentinel.test.ts b/test/all-sources-sentinel.test.ts
index 0e5c707fcc..3df5076ccc 100644
--- a/test/all-sources-sentinel.test.ts
+++ b/test/all-sources-sentinel.test.ts
@@ -198,14 +198,14 @@ describe('__all__ is never narrower than an unqualified read', () => {
describe('cli makeContext — no silent default fallback for explicit --source', () => {
test('--source __all__ produces ctx.sourceId __all__ (was: silent default)', async () => {
- const { makeContext } = await import('../src/cli.ts');
+ const { makeContext } = await import('../src/cli/main.ts');
const ctx = await makeContext(makeStub(['default']), { source: '__all__' });
expect(ctx.sourceId).toBe('__all__');
expect(ctx.remote).toBe(false);
});
test('an explicit --source that fails to resolve throws instead of becoming default', async () => {
- const { makeContext } = await import('../src/cli.ts');
+ const { makeContext } = await import('../src/cli/main.ts');
await expect(makeContext(makeStub(['default']), { source: 'ghost' }))
.rejects.toThrow(/not found/);
await expect(makeContext(makeStub(['default']), { source: 'my_source' }))
@@ -213,7 +213,7 @@ describe('cli makeContext — no silent default fallback for explicit --source',
});
test('ambient resolution failure still falls back silently (pre-init brains)', async () => {
- const { makeContext } = await import('../src/cli.ts');
+ const { makeContext } = await import('../src/cli/main.ts');
const broken = {
kind: 'pglite',
executeRaw: async () => { throw new Error('relation "sources" does not exist'); },
diff --git a/test/auth-local-writer-dry-run.test.ts b/test/auth-local-writer-dry-run.test.ts
index 22b1db1e2e..07714f0afc 100644
--- a/test/auth-local-writer-dry-run.test.ts
+++ b/test/auth-local-writer-dry-run.test.ts
@@ -11,7 +11,7 @@ import { spawnSync } from 'node:child_process';
import { mkdtempSync, realpathSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { validateCommandFlags } from '../src/cli.ts';
+import { validateCommandFlags } from '../src/cli/main.ts';
const home = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-local-writer-dry-run-')));
afterAll(() => rmSync(home, { recursive: true, force: true }));
diff --git a/test/bootstrap-status.serial.test.ts b/test/bootstrap-status.serial.test.ts
index 6ba6dff3d4..7fddcd34fb 100644
--- a/test/bootstrap-status.serial.test.ts
+++ b/test/bootstrap-status.serial.test.ts
@@ -11,7 +11,7 @@ import { join } from 'node:path';
import { runBootstrap } from '../src/commands/bootstrap.ts';
-import { CLI_ONLY, THIN_CLIENT_REFUSED_COMMANDS } from '../src/cli.ts';
+import { CLI_ONLY, THIN_CLIENT_REFUSED_COMMANDS } from '../src/cli/main.ts';
import { VERSION } from '../src/version.ts';
import {
BOOTSTRAP_PHASE_IDS,
diff --git a/test/brain-flag-routing.serial.test.ts b/test/brain-flag-routing.serial.test.ts
index d86b7652c0..d39c6e3a60 100644
--- a/test/brain-flag-routing.serial.test.ts
+++ b/test/brain-flag-routing.serial.test.ts
@@ -175,7 +175,7 @@ describe('untrusted callers cannot cross brains', () => {
});
test('makeContext ignores caller-supplied params.brain (stays on the connected engine)', async () => {
- const { makeContext } = await import('../src/cli.ts');
+ const { makeContext } = await import('../src/cli/main.ts');
const stub = {
kind: 'pglite',
executeRaw: async () => [],
diff --git a/test/cli-ambient-source-fail-closed.test.ts b/test/cli-ambient-source-fail-closed.test.ts
index 68e57f5207..ba63d64603 100644
--- a/test/cli-ambient-source-fail-closed.test.ts
+++ b/test/cli-ambient-source-fail-closed.test.ts
@@ -10,7 +10,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:tes
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { makeContext } from '../src/cli.ts';
+import { makeContext } from '../src/cli/main.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { resolveSourceWithTier } from '../src/core/source-resolver.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
diff --git a/test/cli-args.test.ts b/test/cli-args.test.ts
index 0ae4fb7dbf..c258fc2ea7 100644
--- a/test/cli-args.test.ts
+++ b/test/cli-args.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, test } from 'bun:test';
-import { findUnknownOpFlag, parseOpArgs } from '../src/cli.ts';
+import { findUnknownOpFlag, parseOpArgs } from '../src/cli/main.ts';
import { operations, operationsByName } from '../src/core/operations.ts';
describe('parseOpArgs', () => {
diff --git a/test/cli-bigint-normalize.test.ts b/test/cli-bigint-normalize.test.ts
index cb0d9d0529..56400949fe 100644
--- a/test/cli-bigint-normalize.test.ts
+++ b/test/cli-bigint-normalize.test.ts
@@ -13,7 +13,7 @@
* doesn't crash the serializer the moment a query matches. (#2450 comments)
*/
import { describe, test, expect } from 'bun:test';
-import { bigintToStringReplacer, CLI_ONLY } from '../src/cli.ts';
+import { bigintToStringReplacer, CLI_ONLY } from '../src/cli/main.ts';
import { takeHitRowToHit } from '../src/core/utils.ts';
import { runCall } from '../src/commands/call.ts';
import type { BrainEngine } from '../src/core/engine.ts';
diff --git a/test/cli-command-table.test.ts b/test/cli-command-table.test.ts
index aa0f249178..5b181dbb6c 100644
--- a/test/cli-command-table.test.ts
+++ b/test/cli-command-table.test.ts
@@ -27,7 +27,7 @@ import {
THIN_CLIENT_REFUSED_COMMANDS,
findCliCommand,
} from '../src/cli/command-table.ts';
-import { buildCliAliases } from '../src/cli.ts';
+import { buildCliAliases } from '../src/cli/main.ts';
import type { Operation } from '../src/core/operations.ts';
import { COMMAND_TABLE_PATH, parseSource, readCommandModule, readTableRecords } from '../scripts/lib/cli-pipeline.ts';
import { extractCliDispatch } from './helpers/cli-dispatch-extract.ts';
diff --git a/test/cli-concept-nudge.test.ts b/test/cli-concept-nudge.test.ts
index e0f6c46e72..a43686a5d3 100644
--- a/test/cli-concept-nudge.test.ts
+++ b/test/cli-concept-nudge.test.ts
@@ -6,7 +6,7 @@
// sites are two-liners.
import { describe, expect, test, beforeEach, afterEach } from 'bun:test';
-import { maybePrintConceptNudge } from '../src/cli.ts';
+import { maybePrintConceptNudge } from '../src/cli/main.ts';
import {
DEFAULT_CLI_OPTIONS,
setCliOptions,
diff --git a/test/cli-dispatch-lifecycle.serial.test.ts b/test/cli-dispatch-lifecycle.serial.test.ts
index 7ef47c5450..9eb2a2e6dc 100644
--- a/test/cli-dispatch-lifecycle.serial.test.ts
+++ b/test/cli-dispatch-lifecycle.serial.test.ts
@@ -113,7 +113,7 @@ beforeAll(async () => {
order: 99,
drain: async () => { events.push('drain'); return { unfinished: 0 }; },
});
- main = (await import('../src/cli.ts')).__testing.main;
+ main = (await import('../src/cli/main.ts')).__testing.main;
});
afterAll(() => {
diff --git a/test/cli-dispatch-phase.test.ts b/test/cli-dispatch-phase.test.ts
index 2415f2ca3c..e88023f68a 100644
--- a/test/cli-dispatch-phase.test.ts
+++ b/test/cli-dispatch-phase.test.ts
@@ -22,7 +22,7 @@
* by extracting twice. Regenerate: GBRAIN_TEST_UPDATE_GOLDENS=1.
*/
import { describe, expect, test } from 'bun:test';
-import { CLI_ONLY, THIN_CLIENT_REFUSED_COMMANDS, cliAliases } from '../src/cli.ts';
+import { CLI_ONLY, THIN_CLIENT_REFUSED_COMMANDS, cliAliases } from '../src/cli/main.ts';
import { operations } from '../src/core/operations.ts';
import { extractCliDispatch, thinClientRoutes, type CliDispatchShape } from './helpers/cli-dispatch-extract.ts';
import { defineNormalizer, expectGolden, expectNormalizerStable } from './helpers/golden.ts';
diff --git a/test/cli-empty-retrieval-render.test.ts b/test/cli-empty-retrieval-render.test.ts
index 4bc2f7cb36..9c5186a2e6 100644
--- a/test/cli-empty-retrieval-render.test.ts
+++ b/test/cli-empty-retrieval-render.test.ts
@@ -9,7 +9,7 @@
*/
import { afterEach, describe, expect, test } from 'bun:test';
-import { formatResult, captureRetrievalMeta, resetRetrievalMetaForTests } from '../src/cli.ts';
+import { formatResult, captureRetrievalMeta, resetRetrievalMetaForTests } from '../src/cli/main.ts';
import { unpackToolResult, extractResponseMeta } from '../src/core/mcp-client.ts';
afterEach(() => resetRetrievalMetaForTests());
diff --git a/test/cli-exit-drain.test.ts b/test/cli-exit-drain.test.ts
new file mode 100644
index 0000000000..b42e3cc955
--- /dev/null
+++ b/test/cli-exit-drain.test.ts
@@ -0,0 +1,79 @@
+/**
+ * The exit seam ends as soon as piped output is delivered (real Bun pipes).
+ *
+ * flushThenExit used to sleep the full non-TTY grace (250ms) on every exit.
+ * Now process.stdout's one-shot writes go through the fd-1 write chain and
+ * process.stderr's native-writer queue is tracked (Bun 1.4: write() returns
+ * false exactly when bytes stayed queued, 'drain' fires when the queue empties),
+ * so the process exits right after the fence when nothing is queued and at the
+ * stream's 'drain' when something is. The grace is set to 5s here: a run that
+ * still slept it would take 5s or more, so the duration bounds below separate
+ * the two behaviors by a wide margin, and every case also checks that no byte
+ * was lost.
+ */
+
+import { describe, expect, test } from 'bun:test';
+import { spawn } from 'child_process';
+import { resolve } from 'path';
+
+const HARNESS = resolve(import.meta.dir, 'fixtures', 'exit-drain-harness.ts');
+const GRACE_MS = 5_000;
+
+function runHarness(env: Record<string, string>, readerDelayMs: number): Promise<{
+ stdout: number;
+ stderr: number;
+ code: number | null;
+ durationMs: number;
+}> {
+ return new Promise((resolveOut, reject) => {
+ const t0 = Date.now();
+ const child = spawn(process.execPath, [HARNESS], {
+ env: { ...process.env, GBRAIN_FLUSH_GRACE_MS: String(GRACE_MS), ...env },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ let stdout = 0;
+ let stderr = 0;
+ child.stdout.pause();
+ child.stderr.pause();
+ setTimeout(() => {
+ child.stdout.on('data', (d: Buffer) => (stdout += d.length));
+ child.stderr.on('data', (d: Buffer) => (stderr += d.length));
+ child.stdout.resume();
+ child.stderr.resume();
+ }, readerDelayMs);
+ const killer = setTimeout(() => {
+ child.kill('SIGKILL');
+ reject(new Error(`harness did not exit (stdout ${stdout}, stderr ${stderr})`));
+ }, 30_000);
+ child.on('close', (code) => {
+ clearTimeout(killer);
+ resolveOut({ stdout, stderr, code, durationMs: Date.now() - t0 });
+ });
+ });
+}
+
+describe('exit seam waits for delivery, not a fixed grace (real Bun pipes)', () => {
+ test('nothing queued: exits right after the fence, output complete', async () => {
+ const run = await runHarness({ HARNESS_STDOUT_BYTES: '100', HARNESS_STDERR_BYTES: '100', HARNESS_EXIT_CODE: '3' }, 0);
+ expect(run.code).toBe(3);
+ expect(run.stdout).toBe(100);
+ expect(run.stderr).toBe(100);
+ expect(run.durationMs).toBeLessThan(GRACE_MS / 2);
+ }, 40_000);
+
+ test('stderr past the pipe buffer with a late reader: waits for drain, then exits', async () => {
+ const size = 1_000_000;
+ const run = await runHarness({ HARNESS_STDERR_BYTES: String(size), HARNESS_EXIT_CODE: '0' }, 300);
+ expect(run.code).toBe(0);
+ expect(run.stderr).toBe(size);
+ expect(run.durationMs).toBeLessThan(GRACE_MS / 2 + 300);
+ }, 40_000);
+
+ test('stdout past the pipe buffer with a late reader: the write chain delivers it, then exits', async () => {
+ const size = 1_000_000;
+ const run = await runHarness({ HARNESS_STDOUT_BYTES: String(size), HARNESS_EXIT_CODE: '0' }, 300);
+ expect(run.code).toBe(0);
+ expect(run.stdout).toBe(size);
+ expect(run.durationMs).toBeLessThan(GRACE_MS / 2 + 300);
+ }, 40_000);
+});
diff --git a/test/cli-explain-degraded-render.test.ts b/test/cli-explain-degraded-render.test.ts
index fe35511a5b..e97917de13 100644
--- a/test/cli-explain-degraded-render.test.ts
+++ b/test/cli-explain-degraded-render.test.ts
@@ -6,7 +6,7 @@
* unreachable from the CLI (the formatter was only ever tested directly).
*/
import { afterEach, describe, expect, test } from 'bun:test';
-import { formatResult, captureRetrievalMeta, resetRetrievalMetaForTests } from '../src/cli.ts';
+import { formatResult, captureRetrievalMeta, resetRetrievalMetaForTests } from '../src/cli/main.ts';
import { getCliOptions, setCliOptions, _resetCliOptionsForTest } from '../src/core/cli-options.ts';
import type { SearchResult } from '../src/core/types.ts';
diff --git a/test/cli-flag-validation.test.ts b/test/cli-flag-validation.test.ts
index 3f24b41ea3..c4f9f25368 100644
--- a/test/cli-flag-validation.test.ts
+++ b/test/cli-flag-validation.test.ts
@@ -22,7 +22,7 @@ import {
findUnknownFlag,
findUnknownOpFlag,
CLI_ONLY,
-} from '../src/cli.ts';
+} from '../src/cli/main.ts';
import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';
import { operations, operationsByName } from '../src/core/operations.ts';
import { buildFlagRegistry } from '../scripts/generate-flag-registry.ts';
@@ -137,7 +137,7 @@ describe('#2185 acceptance — real usage stays legal', () => {
});
test('--json=<v> is coherent between validator and parser (no positional corruption)', async () => {
- const { parseOpArgs } = await import('../src/cli.ts');
+ const { parseOpArgs } = await import('../src/cli/main.ts');
const search = operationsByName.search;
// Validator accepts any --json form.
expect(findUnknownOpFlag(search, ['--json=true', 'needle'])).toBeNull();
@@ -155,7 +155,7 @@ describe('#2185 acceptance — real usage stays legal', () => {
describe('#2185 parseOpArgs inline = form (regression rule: changed token consumption)', () => {
test('string and number params via =, positional untouched', async () => {
- const { parseOpArgs } = await import('../src/cli.ts');
+ const { parseOpArgs } = await import('../src/cli/main.ts');
const search = operationsByName.search;
const p = parseOpArgs(search, ['needle', '--limit=5']);
expect(p.query).toBe('needle');
@@ -163,7 +163,7 @@ describe('#2185 parseOpArgs inline = form (regression rule: changed token consum
});
test('boolean =false negates; =0 keeps the raw!==false rule (pinned semantics)', async () => {
- const { parseOpArgs } = await import('../src/cli.ts');
+ const { parseOpArgs } = await import('../src/cli/main.ts');
const withBool = operations.find(o =>
o.cliHints && Object.values(o.params).some(pp => pp.type === 'boolean'))!;
const key = Object.entries(withBool.params).find(([, pp]) => pp.type === 'boolean')![0];
@@ -173,7 +173,7 @@ describe('#2185 parseOpArgs inline = form (regression rule: changed token consum
});
test('undeclared =-form key keeps the historical junk-fallthrough (validator rejects it first)', async () => {
- const { parseOpArgs } = await import('../src/cli.ts');
+ const { parseOpArgs } = await import('../src/cli/main.ts');
const search = operationsByName.search;
// The validator is the strict gate; the parser's legacy behavior for
// undeclared keys is unchanged — pinned so a refactor can't silently
@@ -196,7 +196,7 @@ describe('#2185 red-team regressions', () => {
});
test('--dry-run is a real CLI-local boolean on op commands (trailing position sets it)', async () => {
- const { parseOpArgs } = await import('../src/cli.ts');
+ const { parseOpArgs } = await import('../src/cli/main.ts');
// An op WITHOUT a declared dry_run param — pre-fix, trailing --dry-run
// set NOTHING (ctx.dryRun stayed false → the REAL destructive action
// ran despite the rehearsal request), and leading --dry-run consumed
@@ -319,7 +319,7 @@ describe('#2185 subprocess smokes — end-to-end error surface', () => {
describe('#5700 parseOpArgs refuses to swallow a known flag as a value', () => {
test('a non-boolean flag followed by a known flag of the same command is an argument error', async () => {
- const { parseOpArgs } = await import('../src/cli.ts');
+ const { parseOpArgs } = await import('../src/cli/main.ts');
const put = operations.find(o => o.cliHints?.name === 'put')!;
// The reported shape: `gbrain put x --content --source default` with the
// body on stdin used to store the literal "--source" as the page body,
@@ -342,7 +342,7 @@ describe('#5700 parseOpArgs refuses to swallow a known flag as a value', () => {
});
test('the stdin-capable flag names the stdin recovery; other flags do not', async () => {
- const { parseOpArgs } = await import('../src/cli.ts');
+ const { parseOpArgs } = await import('../src/cli/main.ts');
const put = operations.find(o => o.cliHints?.name === 'put')!;
expect(() => parseOpArgs(put, ['repro', '--content', '--source', 'default'])).toThrow(
"--content requires a value, but '--source' is a flag; omit --content (or put it last) to read stdin.",
@@ -353,7 +353,7 @@ describe('#5700 parseOpArgs refuses to swallow a known flag as a value', () => {
});
test('flag order alone still decides nothing: both orders reach the same params', async () => {
- const { parseOpArgs } = await import('../src/cli.ts');
+ const { parseOpArgs } = await import('../src/cli/main.ts');
const put = operations.find(o => o.cliHints?.name === 'put')!;
// Working order — --content last, body from stdin (unit test: no pipe, so
// content stays unset and applyStdinParam would fill it).
@@ -364,7 +364,7 @@ describe('#5700 parseOpArgs refuses to swallow a known flag as a value', () => {
});
test('a value that merely starts with -- is still a value', async () => {
- const { parseOpArgs } = await import('../src/cli.ts');
+ const { parseOpArgs } = await import('../src/cli/main.ts');
const put = operations.find(o => o.cliHints?.name === 'put')!;
// Markdown bodies legitimately start with "--" (an em-dash list, a YAML
// comment). Only a token this command knows as a flag is refused.
diff --git a/test/cli-force-exit-teardown-arming.test.ts b/test/cli-force-exit-teardown-arming.test.ts
index 46516f3a31..e3f499cc27 100644
--- a/test/cli-force-exit-teardown-arming.test.ts
+++ b/test/cli-force-exit-teardown-arming.test.ts
@@ -22,7 +22,7 @@ import { surfaceFileSource } from './helpers/source-surface.ts';
describe('cli.ts — disconnect hard-deadline armed at teardown entry, not before the op body', () => {
test('no timer arming exists between op-dispatch setup and the try; the deadline arms inside finishCliTeardown before the drain', () => {
- const cli = surfaceFileSource('cli', 'src/cli.ts');
+ const cli = surfaceFileSource('cli', 'src/cli/main.ts');
// The old pre-try arming constant must stay gone (its return is the
// kill-slow-ops-with-exit-0 regression).
diff --git a/test/cli-format-get-page-json.test.ts b/test/cli-format-get-page-json.test.ts
index 1d22e64af3..1382abf7b7 100644
--- a/test/cli-format-get-page-json.test.ts
+++ b/test/cli-format-get-page-json.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, test } from 'bun:test';
-import { formatResult } from '../src/cli.ts';
+import { formatResult } from '../src/cli/main.ts';
/**
* `gbrain get <slug> --json` accepted `--json` and silently printed the
diff --git a/test/cli-format-history-json.test.ts b/test/cli-format-history-json.test.ts
index 3f06ba8952..216c8da75c 100644
--- a/test/cli-format-history-json.test.ts
+++ b/test/cli-format-history-json.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, test } from 'bun:test';
-import { formatResult } from '../src/cli.ts';
+import { formatResult } from '../src/cli/main.ts';
/**
* `gbrain history <slug> --json` accepted `--json` and silently printed the
diff --git a/test/cli-format-search-json.test.ts b/test/cli-format-search-json.test.ts
index 0bdbf88e26..f189211aae 100644
--- a/test/cli-format-search-json.test.ts
+++ b/test/cli-format-search-json.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, test } from 'bun:test';
-import { formatResult } from '../src/cli.ts';
+import { formatResult } from '../src/cli/main.ts';
describe('formatResult - search/query --json', () => {
test('search --json renders the raw result array as parseable JSON', () => {
diff --git a/test/cli-format-volunteer.test.ts b/test/cli-format-volunteer.test.ts
index 3e7f242269..4163832c3f 100644
--- a/test/cli-format-volunteer.test.ts
+++ b/test/cli-format-volunteer.test.ts
@@ -4,7 +4,7 @@
* the empty-result message, and the approximate stats summary.
*/
import { describe, test, expect } from 'bun:test';
-import { formatResult } from '../src/cli.ts';
+import { formatResult } from '../src/cli/main.ts';
describe('formatResult — volunteer_context', () => {
test('renders pointer lines with confidence, arm, rationale, and synopsis', () => {
diff --git a/test/cli-incomplete-retrieval-render.test.ts b/test/cli-incomplete-retrieval-render.test.ts
index 3b1fab2d87..b2089d75aa 100644
--- a/test/cli-incomplete-retrieval-render.test.ts
+++ b/test/cli-incomplete-retrieval-render.test.ts
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, spyOn, test } from 'bun:test';
-import { captureRetrievalMeta, formatResult, resetRetrievalMetaForTests } from '../src/cli.ts';
+import { captureRetrievalMeta, formatResult, resetRetrievalMetaForTests } from '../src/cli/main.ts';
afterEach(() => resetRetrievalMetaForTests());
diff --git a/test/cli-input-plumbing-2822.test.ts b/test/cli-input-plumbing-2822.test.ts
index 9d2625d35a..844a6d62c1 100644
--- a/test/cli-input-plumbing-2822.test.ts
+++ b/test/cli-input-plumbing-2822.test.ts
@@ -16,7 +16,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, setDefaultTimeout, t
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
-import { parseOpArgs } from '../src/cli.ts';
+import { parseOpArgs } from '../src/cli/main.ts';
import { operations, operationsByName } from '../src/core/operations.ts';
import type { OperationContext } from '../src/core/operations.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
diff --git a/test/cli-op-owned-source.test.ts b/test/cli-op-owned-source.test.ts
index af62c8d740..0280152285 100644
--- a/test/cli-op-owned-source.test.ts
+++ b/test/cli-op-owned-source.test.ts
@@ -19,7 +19,7 @@ import { acquireLock, releaseLock } from '../src/core/pglite-lock.ts';
import { maybeDelegateLocalOperation } from '../src/core/persistence/local-client.ts';
import { startPersistenceIpcServer, persistenceSocketPathForConfig, type PersistenceIpcRequest } from '../src/core/persistence/ipc.ts';
import { operations } from '../src/core/operations.ts';
-import { applyThinClientSourceScope } from '../src/cli.ts';
+import { applyThinClientSourceScope } from '../src/cli/main.ts';
import { withEnv } from './helpers/with-env.ts';
const CLI = join(import.meta.dir, '../src/cli.ts');
diff --git a/test/cli-op-typed-args.test.ts b/test/cli-op-typed-args.test.ts
index 605c492ad0..e966850e04 100644
--- a/test/cli-op-typed-args.test.ts
+++ b/test/cli-op-typed-args.test.ts
@@ -3,7 +3,7 @@
* ends options in parseOpArgs, matching findUnknownOpFlag).
*/
import { describe, expect, test } from 'bun:test';
-import { parseOpArgs, findUnknownOpFlag } from '../src/cli.ts';
+import { parseOpArgs, findUnknownOpFlag } from '../src/cli/main.ts';
import { operations, OperationError } from '../src/core/operations.ts';
import { runCli } from './helpers/cli-spawn.ts';
import { mkdtempSync } from 'node:fs';
diff --git a/test/cli-query-image.test.ts b/test/cli-query-image.test.ts
index 8e5f382006..c5839b86ba 100644
--- a/test/cli-query-image.test.ts
+++ b/test/cli-query-image.test.ts
@@ -6,7 +6,7 @@ import { describe, expect, test, beforeAll, afterAll } from 'bun:test';
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
-import { resolveQueryImage } from '../src/cli.ts';
+import { resolveQueryImage } from '../src/cli/main.ts';
let tmp: string;
diff --git a/test/cli-recall-flag-ownership.test.ts b/test/cli-recall-flag-ownership.test.ts
index 27764ccb04..9df334ab36 100644
--- a/test/cli-recall-flag-ownership.test.ts
+++ b/test/cli-recall-flag-ownership.test.ts
@@ -3,7 +3,7 @@ import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { buildFlagRegistry } from '../scripts/generate-flag-registry.ts';
-import { validateCommandFlags } from '../src/cli.ts';
+import { validateCommandFlags } from '../src/cli/main.ts';
import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';
import { runCli } from './helpers/cli-spawn.ts';
diff --git a/test/cli-stdin-hang.test.ts b/test/cli-stdin-hang.test.ts
index 792fa8f581..c26f8ece23 100644
--- a/test/cli-stdin-hang.test.ts
+++ b/test/cli-stdin-hang.test.ts
@@ -18,6 +18,7 @@ import { dirname, join } from 'path';
const REPO = dirname(import.meta.dir);
const CLI = join(REPO, 'src', 'cli.ts');
+const CLI_MODULE = join(REPO, 'src', 'cli', 'main.ts');
interface CliRun {
exited: boolean;
@@ -109,7 +110,7 @@ describe('#3513 — applyStdinParam content preservation (subprocess driver)', (
// Drive the exported helper in a child process so we control the child's
// real fd 0 — bun test's own stdin is not a reliable fixture.
const DRIVER = `
- const { applyStdinParam } = await import(${JSON.stringify(CLI)});
+ const { applyStdinParam } = await import(${JSON.stringify(CLI_MODULE)});
const op = { name: 'put', params: { content: { type: 'string', required: true } }, cliHints: { stdin: 'content' } };
const params = {};
await applyStdinParam(op, params);
diff --git a/test/cli-synthetic-command.test.ts b/test/cli-synthetic-command.test.ts
index 0467a7da42..b0543fb850 100644
--- a/test/cli-synthetic-command.test.ts
+++ b/test/cli-synthetic-command.test.ts
@@ -19,10 +19,10 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { dirname, join } from 'path';
import { buildFlagRegistry } from '../scripts/generate-flag-registry.ts';
-import { findUnknownFlag } from '../src/cli.ts';
+import { findUnknownFlag } from '../src/cli/main.ts';
const FILES: Record<string, string> = {
- 'src/cli.ts': [
+ 'src/cli/main.ts': [
'async function handleCliOnly(command: string, args: string[]) {',
' if (await routeSyntheticBeforeTable(command, args)) return;',
' if (await dispatchPreConnectCommand(command, args)) return;',
diff --git a/test/cli.test.ts b/test/cli.test.ts
index d7511ff7fb..3dfbb644de 100644
--- a/test/cli.test.ts
+++ b/test/cli.test.ts
@@ -5,7 +5,7 @@ import { join } from 'path';
import { surfaceFileSource } from './helpers/source-surface.ts';
// test-reads-source-ok[structural]: two kept pins need the dispatcher's text: the handleCliOnly case-label census (switch labels cannot be enumerated at runtime) and the local-op normalize call site (bigints only reach it from Postgres, never PGLite).
-const cliSource = surfaceFileSource('cli', 'src/cli.ts');
+const cliSource = surfaceFileSource('cli', 'src/cli/main.ts');
const repoRoot = new URL('..', import.meta.url).pathname;
function isolatedEnv(home: string): Record<string, string> {
@@ -55,7 +55,7 @@ describe('CLI structure', () => {
// Structural, self-updating: a new handler module without a CLI_ONLY entry
// fails here at PR time.
test('every handleCliOnly top-level case label is reachable via CLI_ONLY', async () => {
- const { CLI_ONLY } = await import('../src/cli.ts');
+ const { CLI_ONLY } = await import('../src/cli/main.ts');
const members = new Set<string>(CLI_ONLY);
const caseLabels = readdirSync(join(repoRoot, 'src', 'cli', 'commands'))
@@ -94,7 +94,7 @@ describe('BigInt-safe output normalization (#2450)', () => {
});
test('normalizeLocalResult serializes bigint → string without throwing', async () => {
- const { normalizeLocalResult } = await import('../src/cli.ts');
+ const { normalizeLocalResult } = await import('../src/cli/main.ts');
const out = normalizeLocalResult({
id: 42n,
nested: { count: 7n },
@@ -110,14 +110,14 @@ describe('BigInt-safe output normalization (#2450)', () => {
});
test('bigint past Number.MAX_SAFE_INTEGER keeps full precision as a string', async () => {
- const { normalizeLocalResult } = await import('../src/cli.ts');
+ const { normalizeLocalResult } = await import('../src/cli/main.ts');
const big = 9007199254740993n; // MAX_SAFE_INTEGER + 2
const out = normalizeLocalResult({ id: big }) as Record<string, unknown>;
expect(out.id).toBe('9007199254740993');
});
test("formatResult's default renderer is bigint-safe", async () => {
- const { formatResult } = await import('../src/cli.ts');
+ const { formatResult } = await import('../src/cli/main.ts');
expect(() => formatResult('__no_such_op__', { id: 5n })).not.toThrow();
expect(formatResult('__no_such_op__', { id: 5n })).toContain('"5"');
});
@@ -137,7 +137,7 @@ describe('BigInt-safe output normalization (#2450)', () => {
// untouched (the JSON path carries the raw characters).
describe("list_pages TSV escaping (#5433)", () => {
async function render(pages: unknown[]): Promise<string> {
- const { formatResult } = await import('../src/cli.ts');
+ const { formatResult } = await import('../src/cli/main.ts');
return formatResult('list_pages', pages, {});
}
diff --git a/test/docs-cli-commands.test.ts b/test/docs-cli-commands.test.ts
index 388b55b29d..61e7fec217 100644
--- a/test/docs-cli-commands.test.ts
+++ b/test/docs-cli-commands.test.ts
@@ -34,7 +34,7 @@
import { describe, expect, test } from 'bun:test';
import { readdirSync, readFileSync, statSync } from 'fs';
import { dirname, join, relative } from 'path';
-import { CLI_ONLY } from '../src/cli.ts';
+import { CLI_ONLY } from '../src/cli/main.ts';
import {
codeRegions, flagRejection, gbrainInvocations, HISTORICAL_MARKER, liveCliVerbs,
} from './helpers/cli-command-surface.ts';
diff --git a/test/doctor-timeline-metric-labels-2298.test.ts b/test/doctor-timeline-metric-labels-2298.test.ts
index e9fb89dda3..33fb9149cd 100644
--- a/test/doctor-timeline-metric-labels-2298.test.ts
+++ b/test/doctor-timeline-metric-labels-2298.test.ts
@@ -28,7 +28,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { sqlQueryForEngine } from '../src/core/sql-query.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { buildChecks } from '../src/commands/doctor.ts';
-import { formatResult } from '../src/cli.ts';
+import { formatResult } from '../src/cli/main.ts';
let engine: PGLiteEngine;
diff --git a/test/eval-capture-db-plane.test.ts b/test/eval-capture-db-plane.test.ts
index 48265dec95..ebc8b1379e 100644
--- a/test/eval-capture-db-plane.test.ts
+++ b/test/eval-capture-db-plane.test.ts
@@ -26,7 +26,7 @@ import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { withEnv } from './helpers/with-env.ts';
-import { makeContext } from '../src/cli.ts';
+import { makeContext } from '../src/cli/main.ts';
import { isEvalCaptureEnabled, isEvalScrubEnabled } from '../src/core/eval-capture.ts';
import type { BrainEngine } from '../src/core/engine.ts';
import { surfaceSource } from './helpers/source-surface.ts';
@@ -109,7 +109,7 @@ describe('eval.capture set on the DB plane reaches the runtime gate (#1475)', ()
// that lacks the export, which would collapse the other cases' signal to a
// single load error. Deferring it keeps each case independently
// meaningful when someone reverts half the fix to see what breaks.
- const { __testing } = await import('../src/cli.ts');
+ const { __testing } = await import('../src/cli/main.ts');
let keysRead: string[] = [];
const counting = {
@@ -162,7 +162,7 @@ describe('eval.capture set on the DB plane reaches the runtime gate (#1475)', ()
// state) — the same provenance-follows-the-engine binding
// MERGED_CONFIG_BY_ENGINE already uses, so this stays correct even if a
// process ever holds a host engine and a mount engine at once.
- const { __testing } = await import('../src/cli.ts');
+ const { __testing } = await import('../src/cli/main.ts');
let keysRead: string[] = [];
const counting = {
kind: 'pglite',
diff --git a/test/federated-link-reads-5827.test.ts b/test/federated-link-reads-5827.test.ts
index 60eeb27dd1..30fcc92bde 100644
--- a/test/federated-link-reads-5827.test.ts
+++ b/test/federated-link-reads-5827.test.ts
@@ -21,7 +21,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { operationsByName, type AuthInfo, type OperationContext } from '../src/core/operations.ts';
import { noGrantFederatedScope } from '../src/core/source-resolver.ts';
import { dispatchToolCall, type DispatchOpts } from '../src/mcp/dispatch.ts';
-import { makeContext } from '../src/cli.ts';
+import { makeContext } from '../src/cli/main.ts';
import { withEnv } from './helpers/with-env.ts';
import { FEDERATED_SET, edgeKeys, seedAliceIdentity, seedFederatedLinkFixture } from './helpers/federated-link-fixture.ts';
import { ENTITY_IDENTITY_UNION_CONFIG_KEY } from '../src/core/entity-identity.ts';
diff --git a/test/find-contradictions-cli-source.test.ts b/test/find-contradictions-cli-source.test.ts
index bfa1b5c7cc..9262aeaf24 100644
--- a/test/find-contradictions-cli-source.test.ts
+++ b/test/find-contradictions-cli-source.test.ts
@@ -9,7 +9,7 @@
* sources (--source, GBRAIN_SOURCE) still get the unavailable note.
*/
import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
-import { makeContext } from '../src/cli.ts';
+import { makeContext } from '../src/cli/main.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { operationsByName } from '../src/core/operations.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
diff --git a/test/fixtures/exit-drain-harness.ts b/test/fixtures/exit-drain-harness.ts
new file mode 100644
index 0000000000..637ffd4d5f
--- /dev/null
+++ b/test/fixtures/exit-drain-harness.ts
@@ -0,0 +1,16 @@
+/**
+ * Spawned harness for test/cli-exit-drain.test.ts: the one-shot CLI's stdio
+ * setup (installStdoutPipeDelivery), HARNESS_STDOUT_BYTES of 'o' on stdout and
+ * HARNESS_STDERR_BYTES of 'e' on stderr, then the exit seam (flushThenExit).
+ * The parent pipes both streams, attaches its readers late on demand and
+ * checks byte-complete delivery plus how long the exit waited.
+ */
+
+import { flushThenExit, installStdoutPipeDelivery } from '../../src/core/cli-force-exit.ts';
+
+installStdoutPipeDelivery();
+const outBytes = Number(process.env.HARNESS_STDOUT_BYTES ?? 0);
+const errBytes = Number(process.env.HARNESS_STDERR_BYTES ?? 0);
+if (outBytes > 0) process.stdout.write('o'.repeat(outBytes));
+if (errBytes > 0) process.stderr.write('e'.repeat(errBytes));
+flushThenExit(Number(process.env.HARNESS_EXIT_CODE ?? 0));
diff --git a/test/fixtures/goldens/cli/dispatch-phase.json b/test/fixtures/goldens/cli/dispatch-phase.json
index 0af851ca4c..08ec5b1d30 100644
--- a/test/fixtures/goldens/cli/dispatch-phase.json
+++ b/test/fixtures/goldens/cli/dispatch-phase.json
@@ -781,7 +781,7 @@
"unconditionalFor": []
},
{
- "condition": "command === 'extract' && args.includes('--stale') && !hasHelpFlag(args) && await (await import('./commands/extract-stale-delegate.ts')).maybeDelegateExtractStale(loadConfig(), args)",
+ "condition": "command === 'extract' && args.includes('--stale') && !hasHelpFlag(args) && await (await import('../commands/extract-stale-delegate.ts')).maybeDelegateExtractStale(loadConfig(), args)",
"connectsEngine": false,
"refusesThinClient": false,
"routesThinClient": false,
@@ -1122,7 +1122,7 @@
"phase": "post-connect",
"preConnectRules": [
{
- "condition": "command === 'migrate' && await (await import('./commands/migrate-graduation.ts')).tryRunMigrateGraduation(args)",
+ "condition": "command === 'migrate' && await (await import('../commands/migrate-graduation.ts')).tryRunMigrateGraduation(args)",
"connectsEngine": false,
"refusesThinClient": false,
"routesThinClient": false,
@@ -1719,7 +1719,7 @@
]
},
{
- "condition": "command === 'sources' && args[0] === 'refresh' && !hasHelpFlag(args) && await (await import('./commands/sources-refresh-delegate.ts')).maybeDelegateSourcesRefresh(loadConfig(), args.slice(1))",
+ "condition": "command === 'sources' && args[0] === 'refresh' && !hasHelpFlag(args) && await (await import('../commands/sources-refresh-delegate.ts')).maybeDelegateSourcesRefresh(loadConfig(), args.slice(1))",
"connectsEngine": false,
"refusesThinClient": false,
"routesThinClient": false,
@@ -1895,7 +1895,7 @@
"phase": "post-connect",
"preConnectRules": [
{
- "condition": "command === 'transcripts' && args[0] === 'recent' && !hasHelpFlag(args) && await (await import('./commands/transcripts.ts')).runDelegatedTranscriptsRecent(args.slice(1))",
+ "condition": "command === 'transcripts' && args[0] === 'recent' && !hasHelpFlag(args) && await (await import('../commands/transcripts.ts')).runDelegatedTranscriptsRecent(args.slice(1))",
"connectsEngine": false,
"refusesThinClient": false,
"routesThinClient": false,
diff --git a/test/generate-flag-registry.test.ts b/test/generate-flag-registry.test.ts
index 7a6aef6e8f..adf4ff17c0 100644
--- a/test/generate-flag-registry.test.ts
+++ b/test/generate-flag-registry.test.ts
@@ -20,7 +20,7 @@
import { describe, test, expect } from 'bun:test';
import { segmentDispatchBlocks, buildFlagRegistry, isValueOnlyImport, stripComments } from '../scripts/generate-flag-registry.ts';
import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';
-import { validateCommandFlags } from '../src/cli.ts';
+import { validateCommandFlags } from '../src/cli/main.ts';
/**
* The flags the plan names for `gbrain eval longmemeval`, plus a sample of
diff --git a/test/helpers/cli-command-surface.ts b/test/helpers/cli-command-surface.ts
index 8fe3838968..274586a67b 100644
--- a/test/helpers/cli-command-surface.ts
+++ b/test/helpers/cli-command-surface.ts
@@ -15,7 +15,7 @@
*
* Plain helper: no env mutation, no engine, no network.
*/
-import { CLI_ONLY, cliAliases, validateCommandFlags } from '../../src/cli.ts';
+import { CLI_ONLY, cliAliases, validateCommandFlags } from '../../src/cli/main.ts';
import { parseGlobalFlags } from '../../src/core/cli-options.ts';
import { migrationCliArgumentError } from '../../src/core/embedding-migration-cli.ts';
import { operations } from '../../src/core/operations.ts';
diff --git a/test/helpers/cli-dispatch-extract.ts b/test/helpers/cli-dispatch-extract.ts
index c4a186909b..735b09ee8c 100644
--- a/test/helpers/cli-dispatch-extract.ts
+++ b/test/helpers/cli-dispatch-extract.ts
@@ -322,7 +322,7 @@ function tableRule(name: string, run: ts.FunctionDeclaration): BranchRule {
}
export function extractCliDispatch(): CliDispatchShape {
- const sf = parseTs('src/cli.ts');
+ const sf = parseTs('src/cli/main.ts');
const cliOnly = [...TABLE_CLI_ONLY];
const refused = [...TABLE_REFUSED];
const setsByName: Record<string, string[]> = {
diff --git a/test/integrations.test.ts b/test/integrations.test.ts
index a637298498..af896f89b8 100644
--- a/test/integrations.test.ts
+++ b/test/integrations.test.ts
@@ -175,7 +175,7 @@ describe('CLI integration', () => {
let tableSource: string;
beforeAll(() => {
- cliSource = surfaceFileSource('cli', 'src/cli.ts');
+ cliSource = surfaceFileSource('cli', 'src/cli/main.ts');
// Refactor wave 1 (W4 cli): CLI_ONLY membership and dispatch phase live in
// the command table; containment reads the whole cli surface.
cliSurface = surfaceSource('cli');
@@ -198,7 +198,7 @@ describe('CLI integration', () => {
});
test('help text mentions integrations', () => {
- expect(cliSource).toContain('integrations');
+ expect(surfaceFileSource('cli', 'src/cli/top-help.ts')).toContain('integrations');
});
});
diff --git a/test/jobs-list-get-json.serial.test.ts b/test/jobs-list-get-json.serial.test.ts
index 9eb96b1295..7038615c0b 100644
--- a/test/jobs-list-get-json.serial.test.ts
+++ b/test/jobs-list-get-json.serial.test.ts
@@ -143,7 +143,7 @@ describe('help advertises --json on list/get/stats (#3685)', () => {
});
test('cli.ts JOBS summary lines carry [--json] (source audit)', () => {
- const src = surfaceFileSource('cli', 'src/cli.ts');
+ const src = surfaceFileSource('cli', 'src/cli/top-help.ts');
const jobsListLine = src.split('\n').find((l) => /^\s*jobs list /.test(l));
const jobsGetLine = src.split('\n').find((l) => /^\s*jobs get /.test(l));
const jobsStatsLine = src.split('\n').find((l) => /^\s*jobs stats/.test(l));
diff --git a/test/link-reads-thin-client-5827.serial.test.ts b/test/link-reads-thin-client-5827.serial.test.ts
index f8da0f9ec2..a6a76dc4ec 100644
--- a/test/link-reads-thin-client-5827.serial.test.ts
+++ b/test/link-reads-thin-client-5827.serial.test.ts
@@ -47,7 +47,7 @@ mock.module('../src/core/mcp-client.ts', () => ({
},
}));
-const { __testing } = await import('../src/cli.ts');
+const { __testing } = await import('../src/cli/main.ts');
class ExitSignal extends Error {
constructor(readonly code: number) { super(`process.exit(${code})`); }
diff --git a/test/link-source-namespaced-regex.test.ts b/test/link-source-namespaced-regex.test.ts
index 0609b84356..b34f02332c 100644
--- a/test/link-source-namespaced-regex.test.ts
+++ b/test/link-source-namespaced-regex.test.ts
@@ -25,7 +25,7 @@ import {
MANAGED_LINK_SOURCES,
} from '../src/core/operations.ts';
import type { OperationContext } from '../src/core/operations.ts';
-import { cliAliases, printOpHelp } from '../src/cli.ts';
+import { cliAliases, printOpHelp } from '../src/cli/main.ts';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
diff --git a/test/mcp-result-rows-skew.test.ts b/test/mcp-result-rows-skew.test.ts
index 7a8a1f76da..8b8334a56a 100644
--- a/test/mcp-result-rows-skew.test.ts
+++ b/test/mcp-result-rows-skew.test.ts
@@ -35,7 +35,7 @@ import { serializeMarkdown } from '../src/core/markdown.ts';
import { mintLegacyToken } from '../src/core/token-mint.ts';
import { callRemoteTool, unpackToolResult, _clearMcpClientTokenCache } from '../src/core/mcp-client.ts';
import { resetStrictParamsModeCache } from '../src/mcp/validate-params.ts';
-import { formatResult } from '../src/cli.ts';
+import { formatResult } from '../src/cli/main.ts';
import { keylessBrainEnv } from './helpers/provider-env.ts';
import { withEnv } from './helpers/with-env.ts';
diff --git a/test/observational-startup.serial.test.ts b/test/observational-startup.serial.test.ts
index 070a45a0fe..41e7a596e2 100644
--- a/test/observational-startup.serial.test.ts
+++ b/test/observational-startup.serial.test.ts
@@ -90,7 +90,7 @@ beforeAll(async () => {
mkdirSync(join(home, '.gbrain'), { recursive: true });
writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: brainPath }, null, 2));
await withBrain(engine => engine.initSchema());
- main = (await import('../src/cli.ts')).__testing.main;
+ main = (await import('../src/cli/main.ts')).__testing.main;
});
afterAll(() => {
diff --git a/test/reconcile-links-cli-reachability.test.ts b/test/reconcile-links-cli-reachability.test.ts
index 08d6140061..b149ee4cd6 100644
--- a/test/reconcile-links-cli-reachability.test.ts
+++ b/test/reconcile-links-cli-reachability.test.ts
@@ -12,7 +12,7 @@
*/
import { describe, test, expect } from 'bun:test';
-import { CLI_ONLY } from '../src/cli.ts';
+import { CLI_ONLY } from '../src/cli/main.ts';
describe('CLI_ONLY command reachability (#2900)', () => {
test('`reconcile-links` is in CLI_ONLY so dispatch reaches its handler', () => {
diff --git a/test/search/output-redaction.serial.test.ts b/test/search/output-redaction.serial.test.ts
index 741e7d330e..4b61a6d99d 100644
--- a/test/search/output-redaction.serial.test.ts
+++ b/test/search/output-redaction.serial.test.ts
@@ -38,7 +38,7 @@ mock.module('../../src/core/think/index.ts', () => ({
const { PGLiteEngine } = await import('../../src/core/pglite-engine.ts');
const { operationsByName } = await import('../../src/core/operations.ts');
-const { formatResult, captureRetrievalMeta, resetRetrievalMetaForTests } = await import('../../src/cli.ts');
+const { formatResult, captureRetrievalMeta, resetRetrievalMetaForTests } = await import('../../src/cli/main.ts');
const { getCliOptions, setCliOptions, _resetCliOptionsForTest } = await import('../../src/core/cli-options.ts');
const { resetPgliteState } = await import('../helpers/reset-pglite.ts');
const { installFixtureChunks } = await import('../helpers/page-projection.ts');
diff --git a/test/shared-skills-operation-contract.test.ts b/test/shared-skills-operation-contract.test.ts
index 38a03e1309..5bdc21ff23 100644
--- a/test/shared-skills-operation-contract.test.ts
+++ b/test/shared-skills-operation-contract.test.ts
@@ -1,7 +1,7 @@
import { expect, test } from 'bun:test';
import { operations, operationsByName } from '../src/core/operations.ts';
import { brainMembershipOperations } from '../src/core/ops/brain-membership.ts';
-import { parseOpArgs } from '../src/cli.ts';
+import { parseOpArgs } from '../src/cli/main.ts';
test('shared skill synchronization does not replace the existing local administrator sync API', () => {
const legacy = operationsByName.sync_brain;
diff --git a/test/sync-timeout-cli-dispatch.test.ts b/test/sync-timeout-cli-dispatch.test.ts
index 335e2d67d2..c279686c89 100644
--- a/test/sync-timeout-cli-dispatch.test.ts
+++ b/test/sync-timeout-cli-dispatch.test.ts
@@ -3,7 +3,7 @@ import { spawnSync } from 'node:child_process';
import { join } from 'node:path';
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
-import { resolveReadOnlyDispatchTimeoutMs } from '../src/cli.ts';
+import { resolveReadOnlyDispatchTimeoutMs } from '../src/cli/main.ts';
import { parseGlobalFlags } from '../src/core/cli-options.ts';
// #3013 — `gbrain sync --timeout <s>` was unreachable: the global option
diff --git a/test/thin-client-source-scope.test.ts b/test/thin-client-source-scope.test.ts
index d366f319dc..593ca827d7 100644
--- a/test/thin-client-source-scope.test.ts
+++ b/test/thin-client-source-scope.test.ts
@@ -15,7 +15,7 @@ import { describe, test, expect } from 'bun:test';
import { mkdtempSync, rmSync, writeFileSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
-import { applyThinClientSourceScope, parseOpArgs } from '../src/cli.ts';
+import { applyThinClientSourceScope, parseOpArgs } from '../src/cli/main.ts';
import { operationsByName } from '../src/core/operations.ts';
import { withEnv } from './helpers/with-env.ts';
diff --git a/test/transcripts-managed-ingest.test.ts b/test/transcripts-managed-ingest.test.ts
index 8fd693c9a2..da2bc0b37e 100644
--- a/test/transcripts-managed-ingest.test.ts
+++ b/test/transcripts-managed-ingest.test.ts
@@ -15,7 +15,7 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
-import { makeContext } from '../src/cli.ts';
+import { makeContext } from '../src/cli/main.ts';
import { runTranscriptsIngest } from '../src/core/transcripts/ingest.ts';
import { runTranscripts } from '../src/commands/transcripts.ts';
import { disposePersistenceConsumer, stopPersistenceConsumer } from '../src/core/persistence/service.ts';
diff --git a/test/v0_37_fix_wave.serial.test.ts b/test/v0_37_fix_wave.serial.test.ts
index 00be94f5a4..d80ae402ac 100644
--- a/test/v0_37_fix_wave.serial.test.ts
+++ b/test/v0_37_fix_wave.serial.test.ts
@@ -211,7 +211,7 @@ describe('v0.37 Lane C.3 — Voyage key reaches buildGatewayConfig', () => {
delete process.env.ANTHROPIC_API_KEY;
delete process.env.OPENROUTER_API_KEY;
try {
- const { buildGatewayConfig } = await import('../src/cli.ts');
+ const { buildGatewayConfig } = await import('../src/cli/main.ts');
const cfg = {
engine: 'pglite' as const,
voyage_api_key: 'test-voyage-key',
@@ -237,7 +237,7 @@ describe('v0.37 Lane C.3 — Voyage key reaches buildGatewayConfig', () => {
const saved = process.env.VOYAGE_API_KEY;
process.env.VOYAGE_API_KEY = 'env-wins-key';
try {
- const { buildGatewayConfig } = await import('../src/cli.ts');
+ const { buildGatewayConfig } = await import('../src/cli/main.ts');
const cfg = { engine: 'pglite' as const, voyage_api_key: 'file-key' };
const gwCfg = buildGatewayConfig(cfg as any);
expect(gwCfg.env?.VOYAGE_API_KEY).toBe('env-wins-key');
diff --git a/test/write-request-help.test.ts b/test/write-request-help.test.ts
index 2404f7586f..fe74144b7f 100644
--- a/test/write-request-help.test.ts
+++ b/test/write-request-help.test.ts
@@ -1,6 +1,6 @@
/** #6255 (fix wave 12, W1.4): `gbrain write-request --help` names its routing flags and the receipt states. */
import { expect, test } from 'bun:test';
-import { printOpHelp } from '../src/cli.ts';
+import { printOpHelp } from '../src/cli/main.ts';
import { operationsByName } from '../src/core/operations.ts';
test('write-request help shows --brain, --json and the pending versus final states', () => {