Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(cli): CI round 1 + scanner burn-down in Lane D's files

garrytan064f030015ef
diff --git a/scripts/agent-contract-baselines/interactive-io.tsv b/scripts/agent-contract-baselines/interactive-io.tsv
index e0f98c8bed..034967bee6 100644
--- a/scripts/agent-contract-baselines/interactive-io.tsv
+++ b/scripts/agent-contract-baselines/interactive-io.tsv
@@ -1,6 +1,5 @@
# shrink-only baseline for scripts/check-agent-contract.ts rule interactive-io: path<TAB>count
src/commands/hook.ts 3
-src/commands/init.ts 4
src/commands/jobs-watch.ts 2
src/commands/upgrade.ts 1
src/commands/watch.ts 1
diff --git a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
index 7210721e2a..1ecce3e5bc 100644
--- a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
+++ b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
@@ -1,5 +1,4 @@
# shrink-only baseline for scripts/check-agent-contract.ts rule suggestionless-operation-error: path<TAB>count
-src/cli.ts 3
src/commands/book-mirror.ts 1
src/commands/capture.ts 4
src/commands/company-brain-connect.ts 15
diff --git a/scripts/agent-contract-baselines/yes-rerun-string.tsv b/scripts/agent-contract-baselines/yes-rerun-string.tsv
index 75c3531f97..e7e0387673 100644
--- a/scripts/agent-contract-baselines/yes-rerun-string.tsv
+++ b/scripts/agent-contract-baselines/yes-rerun-string.tsv
@@ -1,5 +1,4 @@
# shrink-only baseline for scripts/check-agent-contract.ts rule yes-rerun-string: path<TAB>count
-src/cli.ts 3
src/commands/apply-migrations.ts 3
src/commands/config.ts 1
src/commands/db-repair.ts 1
diff --git a/src/cli.ts b/src/cli.ts
index 7e57c12240..90ce532381 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -37,7 +37,8 @@ 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 { agentJsonGuardMode } from './cli/json-guard.ts';
-import { cliCommandOf, exitCliError, unknownFlagError, usageError, writeCliError, writeFatalCliError } from './cli/cli-error.ts';
+import { cliCommandOf, exitCliError, unknownFlagError, usageError, writeCliError, writeCliNotice, writeFatalCliError } from './cli/cli-error.ts';
+import type { Notice } from './core/agent-output.ts';
import { opError } from './core/ops/contract.ts';
import { opParamValue } from './cli/op-param-values.ts';
import { serializeMarkdown } from './core/markdown.ts';
@@ -787,13 +788,11 @@ async function runThinClientRouted(
process.off('SIGINT', onSigint);
process.exit(sigintController.signal.aborted ? 130 : currentExitCode());
}
- // D1: --json gets the one v1 envelope; a server tool error renders its
- // own code/fix. Transport failures keep their specific human text.
+ // 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 (params.json === true || (e.reason === 'tool_error' && !scopeDenied)) {
- process.off('SIGINT', onSigint);
- exitCliError(e, op.cliHints?.name ?? op.name);
- }
+ if (e.reason === 'tool_error' && !scopeDenied) { 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':
@@ -841,7 +840,7 @@ async function runThinClientRouted(
}
}
process.off('SIGINT', onSigint);
- process.exit(1);
+ process.exit(failExit);
}
// Defense in depth: callRemoteTool's contract is that everything is
// RemoteMcpError. If a plain Error escapes, render it generically — but
@@ -1055,7 +1054,7 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
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 new OperationError('invalid_params', `${flag} requires a value, but '${args[i + 1]}' is a flag${stdinHint}.`);
+ 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
@@ -1086,11 +1085,9 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
for (const [key, def] of Object.entries(op.params)) {
if ((def.type !== 'object' && def.type !== 'array') || typeof params[key] !== 'string') continue;
let value: unknown;
- try { value = JSON.parse(params[key] as string); }
- catch { throw new OperationError('invalid_params', `--${key.replace(/_/g, '-')} requires a JSON ${def.type}.`); }
- if (def.type === 'array' ? !Array.isArray(value) : value === null || typeof value !== 'object' || Array.isArray(value)) {
- throw new OperationError('invalid_params', `--${key.replace(/_/g, '-')} requires a JSON ${def.type}.`);
- }
+ 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;
@@ -2781,6 +2778,12 @@ async function connectEngine(opts?: { probeOnly?: boolean }): Promise<BrainEngin
return engine;
}
+/** 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);
@@ -2797,25 +2800,16 @@ async function completeEngineStartup(engine: BrainEngine): Promise<void> {
const { tryRunPendingMigrations } = await import('./core/migrate.ts');
const result = await tryRunPendingMigrations(engine);
if (result.status === 'persistent') {
- console.warn(
- ' Schema migrations are pending. Another process attempted to apply them ' +
- 'but the migration didn\'t complete within the retry window. This is usually transient.',
- );
- console.warn(' If it persists:');
- console.warn(' 1. Check `gbrain doctor` for stale locks or stuck advisory locks.');
- console.warn(' 2. Check `gbrain jobs supervisor status` for crashed migration workers.');
- console.warn(' 3. Re-run: `gbrain apply-migrations --yes`');
+ 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.
- console.warn(` Schema probe failed: ${result.error.message}`);
- console.warn(' Re-run: `gbrain apply-migrations --yes`');
+ 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.
- console.warn(` Schema probe failed (unexpected): ${(err as Error).message}`);
- console.warn(' Re-run: `gbrain apply-migrations --yes`');
+ 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.
diff --git a/src/cli/cli-error.ts b/src/cli/cli-error.ts
index 0c28b03182..6e64272c0a 100644
--- a/src/cli/cli-error.ts
+++ b/src/cli/cli-error.ts
@@ -8,7 +8,8 @@
* idle and the patched `process.exit` drains anything queued, so callers may
* exit right after.
*/
-import { renderCliError, type AgentEnvelope } from '../core/agent-output.ts';
+import { cliRenderContext, renderCliError, renderNotice, type AgentEnvelope, type Notice } from '../core/agent-output.ts';
+import { renderCliNotices } from '../core/agent-markers.ts';
import { jsonRequested, noteRenderedErrorCode, writeStdoutFinal } from '../core/cli-force-exit.ts';
import { opError, type OpErrorOpts, type OperationError } from '../core/ops/contract.ts';
import type { RegistryCode } from '../core/error-registry.ts';
@@ -28,6 +29,8 @@ export interface CliErrorWriteOpts {
argv?: readonly string[];
/** Overrides the argv `--json` probe (in-process callers that parsed their own flags). */
json?: boolean;
+ /** false: the caller prints its own human lines (stdout document only). */
+ stderr?: boolean;
/**
* A pre-v1 JSON shape this site printed: its keys lead and keep their
* values, the envelope adds the rest, and the document stays one line
@@ -56,7 +59,7 @@ export function writeCliError(e: unknown, command: string, opts: CliErrorWriteOp
stderr = [`Error [${env.code}]: ${env.message}`, `Fix: ${env.fix?.command ?? env.suggestion}`,
...(env.why ? [`Why: ${env.why}`] : [])].join('\n') + '\n';
}
- try { process.stderr.write(stderr ?? ''); } catch { /* stderr gone */ }
+ if (opts.stderr !== false) try { process.stderr.write(stderr ?? ''); } catch { /* stderr gone */ }
return r.exitCode;
}
@@ -69,6 +72,15 @@ export function exitCliError(e: unknown, command: string, opts: CliErrorWriteOpt
process.exit(writeCliError(e, command, opts));
}
+/**
+ * A warning-class notice from the CLI's own plumbing (not a command result):
+ * stderr, as `Note [code]` lines on a TTY or an `[AGENT]` block otherwise.
+ */
+export function writeCliNotice(n: Notice): void {
+ const out = renderCliNotices([renderNotice(n, cliRenderContext())], { json: false, tty: process.stderr.isTTY === true, stdoutIsData: true });
+ try { if (out.stderr) process.stderr.write(out.stderr); } catch { /* stderr gone */ }
+}
+
/**
* A usage / invalid-input error (exit 2 via the registry): `invalid_params`
* by default, `unknown_flag` / `unknown_command` for those cases.
diff --git a/src/commands/extract-attendance-repair.ts b/src/commands/extract-attendance-repair.ts
index 0a5dd7b398..8062fbce49 100644
--- a/src/commands/extract-attendance-repair.ts
+++ b/src/commands/extract-attendance-repair.ts
@@ -13,6 +13,7 @@ import { readRepairSidecar } from '../core/pglite-repair.ts';
import { applyAttendanceRepair, previewAttendanceRepair, attendanceRepairHash, assertAttendanceRepairAuthority,
validateAttendanceRepairScope, ATTENDANCE_REPAIR_LIMIT, type AttendanceRepairPreview,
type AttendanceRepairAuthority } from '../core/attendance-repair.ts';
+import { usageError } from '../cli/cli-error.ts';
export const ATTENDANCE_REPAIR_HELP = ` gbrain extract links --source db --repair-attendance --source-id ID
[--limit 250] [--after-slug SLUG] [--json]
@@ -154,7 +155,11 @@ export async function runAttendanceRepair(engine: BrainEngine, args: string[], a
}
export async function runAttendanceRepairCli(args: string[], brainFlag: string | null) {
- parseAttendanceRepairArgs(args, { remote: false });
+ // D1/D4: an invalid invocation is a usage error (invalid_params, exit 2), not an internal fault.
+ try { parseAttendanceRepairArgs(args, { remote: false }); } catch (e) {
+ throw usageError(e instanceof Error && e.message ? e.message : 'Invalid attendance repair invocation.',
+ 'Run `gbrain extract --help` for the attendance repair flags: extract links --source db --repair-attendance --source-id ID [--dry-run].');
+ }
const config = loadConfig();
if (isThinClient(config)) throw new Error('Attendance repair is unavailable to remote or thin clients');
const brainId = resolveBrainId(brainFlag);
diff --git a/src/commands/init.ts b/src/commands/init.ts
index dbcee0859d..5a794a5bac 100644
--- a/src/commands/init.ts
+++ b/src/commands/init.ts
@@ -20,6 +20,7 @@ import { deferInitJsonError, flushInitJsonResult, initJsonError, setInitJsonResu
import { buildInitFirstRunNotices } from './init-first-run.ts';
import { renderNotice, cliRenderContext } from '../core/agent-output.ts';
import { exitCodeForCode } from '../core/error-catalogue.ts';
+import { promptLineStderr } from '../core/interaction.ts';
import type { SearchMode as SearchModeName } from '../core/search/mode.ts';
/** D2: `--json` writes exactly one document, after whichever branch ran (see init-json.ts). */
@@ -1687,7 +1688,7 @@ async function supabaseWizard(): Promise<string> {
console.log(' Format: postgresql://postgres.[ref]:[password]@aws-0-[region].pooler.supabase.com:6543/postgres'); /* allow-pg-url-literal */
console.log(' Find it: Supabase Dashboard > Connect (top bar) > Connection String > Transaction pooler\n');
- const url = await readLine('Connection URL: ');
+ const url = (await promptLineStderr('Connection URL: ')) ?? '';
if (!url) {
console.error('No URL provided.');
process.exit(1);
@@ -1695,28 +1696,6 @@ async function supabaseWizard(): Promise<string> {
return url;
}
-function readLine(prompt: string): Promise<string> {
- return new Promise((resolve) => {
- process.stdout.write(prompt);
- let data = '';
- let settled = false;
- const settle = (value: string) => {
- if (settled) return;
- settled = true;
- process.stdin.pause();
- resolve(value);
- };
- process.stdin.setEncoding('utf-8');
- process.stdin.once('data', (chunk) => {
- data = chunk.toString().trim();
- settle(data);
- });
- // EOF (Ctrl-D mid-prompt) resolves empty instead of hanging — the caller's
- // "No URL provided." guard then fails loud.
- process.stdin.once('end', () => settle(''));
- process.stdin.resume();
- });
-}
/**
* v0.32.3 [CDX-9]: readLine + EOF detection + default fallback + timeout.
@@ -1737,47 +1716,17 @@ function readLine(prompt: string): Promise<string> {
* Non-TTY stdin (pipe, scripted init) returns defaultValue immediately
* without printing the prompt, so e2e tests don't hang.
*/
-export function readLineSafe(
+export async function readLineSafe(
prompt: string,
defaultValue: string,
timeoutMs: number = 60_000,
): Promise<string> {
- return new Promise((resolve) => {
- // Non-TTY (pipe, redirect, scripted init) → no prompt, no wait.
- if (!process.stdin.isTTY) {
- resolve(defaultValue);
- return;
- }
-
- process.stdout.write(prompt);
- process.stdin.setEncoding('utf-8');
-
- let settled = false;
- const finish = (value: string) => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- process.stdin.removeListener('data', onData);
- process.stdin.removeListener('end', onEnd);
- try { process.stdin.pause(); } catch { /* swallow */ }
- resolve(value);
- };
-
- const onData = (chunk: Buffer | string) => {
- const raw = chunk.toString().trim();
- finish(raw.length === 0 ? defaultValue : raw);
- };
- const onEnd = () => finish(defaultValue);
-
- const timer = setTimeout(() => {
- process.stdout.write(`\n[timeout after ${Math.round(timeoutMs / 1000)}s, using default: ${defaultValue}]\n`);
- finish(defaultValue);
- }, timeoutMs);
-
- process.stdin.once('data', onData);
- process.stdin.once('end', onEnd);
- process.stdin.resume();
- });
+ // Non-TTY (pipe, redirect, scripted init) → no prompt, no wait.
+ if (!process.stdin.isTTY) return defaultValue;
+ // A5: the shared bounded reader (EOF / timeout → null → the default).
+ const answer = await promptLineStderr(prompt, { timeoutMs });
+ if (answer === null) process.stderr.write(`\n[no answer, using default: ${defaultValue}]\n`);
+ return answer ? answer : defaultValue;
}
/**
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 8be33a73a5..2273cfcf4f 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -289,5 +289,6 @@ export const NOTICE_CODES = {
backup_coverage: { kind: 'coaching', summary: 'Some knowledge assets have no off-machine backup.' },
empty_retrieval: { kind: 'info', summary: 'A retrieval returned no results; the notice says whether recall was degraded.' },
first_run_decisions: { kind: 'ask', summary: 'init finished; the first-run decisions (search mode, harness wiring, …) carry defaults the user may change.' },
+ migrations_pending: { kind: 'safety', summary: 'Schema migrations are pending or failed to apply on this brain.' },
unknown_param: { kind: 'info', summary: 'The call passed a parameter the tool does not declare; it was ignored.' },
} as const satisfies Record<string, NoticeEntry>;
diff --git a/test/ambient-recall-cli.test.ts b/test/ambient-recall-cli.test.ts
index db6c7f77a7..5413668c08 100644
--- a/test/ambient-recall-cli.test.ts
+++ b/test/ambient-recall-cli.test.ts
@@ -6,7 +6,7 @@
* later spawns reuse the persisted brain). Pins:
* - exit 0 + parseable JSON envelope with protocol_version 1 on both verbs
* - `since` echoed NORMALIZED to ISO (never the raw string)
- * - unparseable --since → exit 1 + the verbError rendering on stderr
+ * - unparseable --since → exit 2 (usage) + the verbError rendering on stderr
* (`Error [invalid_params]: …` + the `Fix:` suggestion line)
*/
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
@@ -80,9 +80,9 @@ describe('gbrain delta (CLI)', () => {
expect(env.next_cursor).toEqual({ since: '1970-01-01T00:00:00.000Z', slug: '' });
}, 60_000);
- test('unparseable --since: exit 1, invalid_params rendering on stderr', () => {
+ test('unparseable --since: exit 2 (usage), invalid_params rendering on stderr', () => {
const { stdout, stderr, status } = run(['delta', '--since', 'not-a-date', '--json']);
- expect(status).toBe(1);
+ expect(status).toBe(2); // agent contract v1 A3: invalid_params exits 2
// verbError CLI rendering: `Error [code]: message` + the Fix line (stderr).
expect(stderr).toContain('Error [invalid_params]:');
expect(stderr).toContain('not a parseable timestamp');
diff --git a/test/attendance-repair-cli.serial.test.ts b/test/attendance-repair-cli.serial.test.ts
index fb7075e49a..3abffbf9e0 100644
--- a/test/attendance-repair-cli.serial.test.ts
+++ b/test/attendance-repair-cli.serial.test.ts
@@ -59,7 +59,10 @@ describe('attendance repair CLI authority and private receipts', () => {
].map(args => [args]))('invalid command refuses before creating a brain: %j', async args => {
const before = readdirSync(home);
const result = await runCli(['extract', ...args], { home, cwd: home, env, timeoutMs: 20_000 });
- expect(result.exitCode).toBe(1);
+ // Agent contract v1 A3/D1: an invocation the parser rejects is a usage error (exit 2); later refusals exit 1.
+ let parseRejects = false;
+ try { parseAttendanceRepairArgs(args, { remote: false }); } catch { parseRejects = true; }
+ expect(result.exitCode).toBe(parseRejects ? 2 : 1);
expect(result.stderr).not.toContain('Setting up brain schema');
expect(readdirSync(home)).toEqual(before);
}, 30_000);
diff --git a/test/e2e/thin-client.test.ts b/test/e2e/thin-client.test.ts
index c1bdedc715..bca1b217d5 100644
--- a/test/e2e/thin-client.test.ts
+++ b/test/e2e/thin-client.test.ts
@@ -420,8 +420,8 @@ describeWhen('thin-client end-to-end (requires DATABASE_URL)', () => {
GBRAIN_REMOTE_CLIENT_SECRET: 'gbrain_cs_definitely_not_the_real_secret',
});
expect(r.exitCode, cliDiagnostic("thin-client CLI", r)).toBe(1);
- // No fabricated results — stdout stays empty on the error path.
- expect(r.stdout.trim()).toBe('');
+ // No fabricated results: under --json stdout carries only the v1 error envelope (agent contract D1).
+ expect(JSON.parse(r.stdout)).toMatchObject({ code: expect.any(String), suggestion: expect.any(String), contract_version: 1 });
// Canonical RemoteMcpError surface. mcp-client maps the non-401 /token
// HTTP failure to reason 'discovery' today ("OAuth discovery failed at
// <issuer>."); allow the 'auth' spelling too so a future 401
@@ -448,10 +448,10 @@ describeWhen('thin-client end-to-end (requires DATABASE_URL)', () => {
// the hang this test exists to forbid.
expect(Date.now() - t0).toBeLessThan(60_000);
expect(search.exitCode, cliDiagnostic("thin-client CLI", search)).toBe(1);
- expect(search.stdout.trim()).toBe('');
+ expect(JSON.parse(search.stdout)).toMatchObject({ code: expect.any(String), contract_version: 1 }); // D1: the error envelope, no results
expect(search.stderr).toContain(`Cannot reach http://127.0.0.1:${serverPort}/mcp`);
expect(recall.exitCode, cliDiagnostic("thin-client CLI", recall)).toBe(1);
- expect(recall.stdout.trim()).toBe('');
+ expect(JSON.parse(recall.stdout)).toMatchObject({ code: expect.any(String), contract_version: 1 }); // D1: the error envelope, no results
expect(recall.stderr).toMatch(/OAuth discovery failed/);
});
});
diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.json
index 61f9371020..2bfda2bb90 100644
--- a/test/fixtures/goldens/cli/help-and-errors.json
+++ b/test/fixtures/goldens/cli/help-and-errors.json
@@ -648,19 +648,21 @@
},
{
"argv": "definitely-not-a-command",
- "exitCode": 1,
+ "exitCode": 2,
"stderr": [
- "Unknown command: definitely-not-a-command",
- "Run gbrain --help for available commands."
+ "Error [unknown_command]: Unknown command: definitely-not-a-command",
+ "Fix: Run `gbrain --help` for available commands.",
+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#unknown_command"
],
"stdout": []
},
{
"argv": "definitely-not-a-command --help",
- "exitCode": 1,
+ "exitCode": 2,
"stderr": [
- "Unknown command: definitely-not-a-command",
- "Run gbrain --help for available commands."
+ "Error [unknown_command]: Unknown command: definitely-not-a-command",
+ "Fix: Run `gbrain --help` for available commands.",
+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#unknown_command"
],
"stdout": []
},
@@ -756,18 +758,21 @@
},
{
"argv": "lint --definitely-not-a-flag",
- "exitCode": 1,
+ "exitCode": 2,
"stderr": [
- "gbrain lint: unknown flag --definitely-not-a-flag for 'gbrain lint'",
- "Run: gbrain lint --help"
+ "Error [unknown_flag]: unknown flag --definitely-not-a-flag for 'gbrain lint'",
+ "Fix: gbrain lint --help",
+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#unknown_flag"
],
"stdout": []
},
{
"argv": "get",
- "exitCode": 1,
+ "exitCode": 2,
"stderr": [
- "Usage: gbrain get <slug>"
+ "Error [invalid_params]: Missing required parameter 'slug' for 'gbrain get'.",
+ "Fix: Usage: gbrain get <slug> (see `gbrain get --help`).",
+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#invalid_params"
],
"stdout": []
}
diff --git a/test/fixtures/goldens/cli/thin-client-routing.json b/test/fixtures/goldens/cli/thin-client-routing.json
index 22c5e53b37..6f0949c753 100644
--- a/test/fixtures/goldens/cli/thin-client-routing.json
+++ b/test/fixtures/goldens/cli/thin-client-routing.json
@@ -15,7 +15,7 @@
"exitCode": 1,
"stderr": [
"Error [requires_local_engine]: `gbrain takes` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",
- "Fix: gbrain takes",
+ "Fix: gbrain takes extract",
"Why: 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.",
"Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"
],
@@ -44,7 +44,7 @@
"exitCode": 1,
"stderr": [
"Error [requires_local_engine]: `gbrain cache` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",
- "Fix: gbrain cache",
+ "Fix: gbrain cache clear",
"Why: `cache stats` routes to the brain host automatically (cache_stats MCP op). clear/prune mutate the host cache — run those on the host.",
"Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"
],
@@ -65,7 +65,7 @@
"exitCode": 1,
"stderr": [
"Error [requires_local_engine]: `gbrain quarantine` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",
- "Fix: gbrain quarantine",
+ "Fix: gbrain quarantine scan",
"Why: `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.",
"Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"
],
@@ -106,7 +106,7 @@
"exitCode": 1,
"stderr": [
"Error [requires_local_engine]: `gbrain jobs` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",
- "Fix: gbrain jobs",
+ "Fix: gbrain jobs work",
"Why: `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.",
"Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"
],
@@ -127,7 +127,7 @@
"exitCode": 1,
"stderr": [
"Error [requires_local_engine]: `gbrain search` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",
- "Fix: gbrain search",
+ "Fix: gbrain search diagnose",
"Why: `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.",
"Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"
],
@@ -138,7 +138,7 @@
"exitCode": 1,
"stderr": [
"Error [requires_local_engine]: `gbrain sources` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",
- "Fix: gbrain sources",
+ "Fix: gbrain sources list",
"Why: 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.",
"Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"
],
@@ -149,7 +149,7 @@
"exitCode": 1,
"stderr": [
"Error [requires_local_engine]: `gbrain sources` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",
- "Fix: gbrain sources",
+ "Fix: gbrain sources add",
"Why: 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.",
"Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"
],
@@ -197,7 +197,7 @@
"exitCode": 1,
"stderr": [
"Error [requires_local_engine]: `gbrain eval` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",
- "Fix: gbrain eval",
+ "Fix: gbrain eval whoknows",
"Why: `eval` export/prune/replay touch the local engine and have no MCP equivalents. Run `gbrain eval` on the host.",
"Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"
],
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index ca12d551f7..f9b2b77186 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -5454,7 +5454,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"projection_pending\" | \"timeout\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambiguous_id\" | \"ambiguous_skill\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"catalog_unavailable\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"consent_timeout\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"d_sel_too_small\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_disabled\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_payload_expired\" | \"fetch_failed\" | \"full_resync_required\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graph_incomplete\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_client\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"managed_pull_skipped\" | \"method_not_allowed\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_pricing\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"overlapping_path\" | \"parse_error\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pending_writes\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"redirect_uri_mismatch\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"request_already_submitted\" | \"requirements_changed\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"state_mismatch\" | \"sync_in_progress\" | \"target_escape\" | \"topology_change_required\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined",
+ "canonical?: \"unknown\" | \"projection_pending\" | \"timeout\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambiguous_id\" | \"ambiguous_skill\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"catalog_unavailable\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"consent_timeout\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"d_sel_too_small\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_disabled\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_payload_expired\" | \"fetch_failed\" | \"full_resync_required\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graph_incomplete\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_client\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"managed_pull_skipped\" | \"method_not_allowed\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_pricing\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"parse_error\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pending_writes\" | \"pglite_busy\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"redirect_uri_mismatch\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"state_mismatch\" | \"sync_in_progress\" | \"target_escape\" | \"topology_change_required\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",