Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(closeout): usage mistakes in sources harden, migrate, mcp grant and backup exit 2 as invalid_params with usage and example

garrytand496697da6d6
diff --git a/scripts/serial-weights.json b/scripts/serial-weights.json
index 956313d0b9..9a06628206 100644
--- a/scripts/serial-weights.json
+++ b/scripts/serial-weights.json
@@ -56,6 +56,7 @@
"test/cli-help-without-brain.serial.test.ts": 21,
"test/cli-json-commands.serial.test.ts": 37,
"test/cli-json-guard.serial.test.ts": 17,
+ "test/cli-usage-errors.serial.test.ts": 10,
"test/cli-util-prompt.serial.test.ts": 3,
"test/code-callers-pin.serial.test.ts": 11,
"test/code-def-refs-pin.serial.test.ts": 12,
diff --git a/src/commands/backup.ts b/src/commands/backup.ts
index 1a1207ffbe..1af5fe9ce9 100644
--- a/src/commands/backup.ts
+++ b/src/commands/backup.ts
@@ -15,6 +15,7 @@
* back to the cached verdict + age (cache-derived exit code), never a crash;
*/
+import { OperationError, opError } from '../core/ops/contract.ts';
import type { BrainEngine } from '../core/engine.ts';
import { getCliOptions } from '../core/cli-options.ts';
import { getBackupStatus } from '../core/backup/coverage.ts';
@@ -30,6 +31,19 @@ import {
type BackupStatus,
} from '../core/backup/status-file.ts';
+const BACKUP_USAGE: Record<string, { usage: string; example: string }> = {
+ create: { usage: 'gbrain backup create --output /absolute/private/path/archive.gbrain-backup [--json]',
+ example: 'gbrain backup create --output /srv/private/brain-2026-10-03.gbrain-backup' },
+ restore: { usage: 'gbrain backup restore ARCHIVE --into /absolute/new-root [--mode new-brain|recovery] [--confirm-quiesced] [--confirm-backup-compatible] [--confirm-authority-reviewed] [--json]',
+ example: 'gbrain backup restore /srv/private/brain-2026-10-03.gbrain-backup --into /srv/gbrain-restored' },
+};
+
+/** A3/D4: a malformed `backup create|restore` invocation is a caller mistake (exit 2) with the usage and an example. */
+function backupUsageError(sub: string, message: string): OperationError {
+ const u = BACKUP_USAGE[sub] ?? BACKUP_USAGE.create!;
+ return opError('invalid_params', message, `Usage: ${u.usage}. Example: ${u.example}`);
+}
+
export interface BackupCliResult {
exitCode: 0 | 1 | 2;
}
@@ -128,20 +142,20 @@ export async function runBackupCli(
const arg = args[i];
if (arg === '--json') continue;
if (arg === '--output' || arg === '--into' || arg === '--mode') {
- if (!args[i + 1] || args[i + 1].startsWith('--')) throw new Error(`Missing value for ${arg}`);
+ if (!args[i + 1] || args[i + 1].startsWith('--')) throw backupUsageError(sub, `Missing value for ${arg}.`);
values[arg] = args[++i];
} else if (['--confirm-quiesced', '--confirm-backup-compatible', '--confirm-authority-reviewed'].includes(arg)) confirmations.add(arg);
- else if (arg.startsWith('-')) throw new Error(`Unknown backup option: ${arg}`);
+ else if (arg.startsWith('-')) throw backupUsageError(sub, `Unknown backup option: ${arg}.`);
else positional.push(arg);
}
const { createPgliteBackup, restorePgliteBackup } = await import('../core/backup/snapshot.ts');
if (sub === 'create') {
- if (!values['--output'] || values['--into'] || values['--mode'] || confirmations.size || positional.length) throw new Error('Usage: gbrain backup create --output /absolute/private/path/archive.gbrain-backup');
+ if (!values['--output'] || values['--into'] || values['--mode'] || confirmations.size || positional.length) throw backupUsageError(sub, 'gbrain backup create takes exactly --output <absolute archive path>.');
const result = await createPgliteBackup({ output: values['--output'] });
if (json) console.log(JSON.stringify({ ok: true, ...result }));
else console.log(`Backup created: ${result.archive}\nSensitive full database state; protect any off-VM copy.\nExcluded assets: ${(result.manifest.omitted as string[]).join('; ')}`);
} else {
- if (!values['--into'] || values['--output'] || positional.length !== 1) throw new Error('Usage: gbrain backup restore ARCHIVE --into /absolute/new-root');
+ if (!values['--into'] || values['--output'] || positional.length !== 1) throw backupUsageError(sub, 'gbrain backup restore takes one ARCHIVE and --into <absolute new root>.');
if (values['--mode'] !== undefined && !['new-brain', 'recovery'].includes(values['--mode'])) throw new Error('Restore --mode must be new-brain or recovery.');
const result = await restorePgliteBackup({ archive: positional[0], into: values['--into'], mode: values['--mode'] === 'recovery' ? 'recovery' : 'new_brain',
confirmQuiesced: confirmations.has('--confirm-quiesced'), confirmBackupCompatible: confirmations.has('--confirm-backup-compatible'),
@@ -151,6 +165,11 @@ export async function runBackupCli(
}
return { exitCode: 0 };
} catch (error) {
+ if (error instanceof OperationError && error.code === 'invalid_params') {
+ const { writeCliError } = await import('../cli/cli-error.ts');
+ writeCliError(error, 'backup', { json, legacy: { ok: false, reason: 'invalid_params', message: error.message } });
+ return { exitCode: 2 };
+ }
const detail = error as Error & { code?: string; retryable?: boolean };
if (json) console.log(JSON.stringify({ ok: false, reason: detail.code ?? 'backup_failed', message: detail.message, ...(detail.retryable ? { retryable: true } : {}) }));
else console.error(detail.message);
diff --git a/src/commands/mcp.ts b/src/commands/mcp.ts
index 167367844f..1a84e6b512 100644
--- a/src/commands/mcp.ts
+++ b/src/commands/mcp.ts
@@ -1,4 +1,5 @@
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
+import { OperationError, opError } from '../core/ops/contract.ts';
import { statSync } from 'node:fs';
import type { BrainEngine } from '../core/engine.ts';
import { GRANT_PROFILES, type GrantPatch, type GrantProfileId } from '../core/grants/model.ts';
@@ -55,7 +56,12 @@ export function mcpNeedsEngine(args: string[], envToken = process.env.GBRAIN_ADM
}
export function parseMcpGrant(args: string[]): ProvisionGrantInput {
- if (args[0] !== 'grant' || !args[1] || args[1].startsWith('-')) throw new Error('Usage: gbrain mcp grant NAME [options]');
+ if (args[0] !== 'grant' || !args[1] || args[1].startsWith('-')) {
+ throw opError('invalid_params', 'gbrain mcp grant needs a client NAME.',
+ 'Usage: gbrain mcp grant NAME --harness ID --profile PROFILE --source SOURCE --url URL --credentials-out FILE. '
+ + 'Example: gbrain mcp grant laptop-agent --harness claude-code --profile memory-writer --source default --url https://brain.example.ts.net/mcp --credentials-out ~/laptop-agent.json --dry-run '
+ + '(`gbrain mcp adapters` and `gbrain mcp profiles` list the ids; `gbrain mcp --help` lists every option).');
+ }
validateHarnessArguments(args.slice(2), MCP_GRANT_ARGUMENTS);
const value = (flag: string) => { const i = args.indexOf(flag); if (i < 0) return undefined; const v = args[i + 1]; if (!v || v.startsWith('--')) throw new Error(`${flag} requires a value`); return v; };
const list = (flag: string) => value(flag)?.split(',').map(v => v.trim()).filter(Boolean);
@@ -145,6 +151,13 @@ export async function runMcp(args: string[], engine?: BrainEngine): Promise<void
? 'Install the private handoff inside the intended harness with gbrain connect, then run gbrain mcp verify.'
: 'Grant updated; inspect effective access with gbrain mcp admin client. Restrictions apply immediately. Newly added scopes require fresh authorization in the native client or a new machine token; existing credentials are preserved.' }, null, args.includes('--json') ? undefined : 2));
} catch (error) {
+ if (error instanceof OperationError && error.code === 'invalid_params') {
+ // A3/D4: a malformed invocation exits 2 with the usage and an example; the legacy keys lead the document.
+ const { writeCliError } = await import('../cli/cli-error.ts');
+ writeCliError(error, 'mcp', { json: true, legacy: { status: 'error', reason: 'invalid_params', message: error.message } });
+ setCliExitVerdict(2);
+ return;
+ }
console.log(JSON.stringify({ status: 'error', reason: error instanceof McpAdminError ? error.code : 'mcp_setup_failed',
message: redactAdminValue(error instanceof Error ? error.message : 'MCP setup failed', [process.env.GBRAIN_ADMIN_BOOTSTRAP_TOKEN ?? '']),
...(error instanceof McpAdminError && error.outcome ? { outcome: error.outcome } : {}),
diff --git a/src/commands/migrate-engine.ts b/src/commands/migrate-engine.ts
index 383c28dfab..1166d64828 100644
--- a/src/commands/migrate-engine.ts
+++ b/src/commands/migrate-engine.ts
@@ -8,6 +8,7 @@ import { assertLegacyEngineMigration, assertUnmanagedCanonicalWriter } from '../
* gbrain migrate --to <engine> --force (overwrite non-empty target)
*/
+import { opError } from '../core/ops/contract.ts';
import { createEngine } from '../core/engine-factory.ts';
import { loadConfig, saveConfig, toEngineConfig, gbrainPath, effectiveEnvDatabaseUrl, type GBrainConfig } from '../core/config.ts';
import type { BrainEngine } from '../core/engine.ts';
@@ -37,7 +38,8 @@ interface MigrateOpts {
function parseArgs(args: string[]): MigrateOpts {
const toIdx = args.indexOf('--to');
if (toIdx === -1 || !args[toIdx + 1]) {
- throw new Error('Usage: gbrain migrate --to <supabase|pglite> [--url <url>] [--path <path>] [--force]');
+ throw opError('invalid_params', 'gbrain migrate needs --to <supabase|pglite>.',
+ 'Usage: gbrain migrate --to <supabase|pglite> [--url <url>] [--path <path>] [--force]. Example: gbrain migrate --to pglite --path ~/.gbrain/brain.pglite');
}
const targetRaw = args[toIdx + 1];
@@ -825,9 +827,9 @@ export async function quiesceAutopilot(engine?: BrainEngine): Promise<(() => voi
}
export async function runMigrateEngine(sourceEngine: BrainEngine, args: string[]): Promise<void> {
+ const opts = parseArgs(args);
await assertUnmanagedCanonicalWriter(sourceEngine, 'engine migration');
await assertLegacyEngineMigration(sourceEngine);
- const opts = parseArgs(args);
const config = loadConfig();
if (!config) {
console.error('No brain configured. Run: gbrain init');
diff --git a/src/commands/sources-harden.ts b/src/commands/sources-harden.ts
index d5cce39cbe..baddcd5240 100644
--- a/src/commands/sources-harden.ts
+++ b/src/commands/sources-harden.ts
@@ -23,6 +23,7 @@ import { invalidateBackupStatus } from '../core/backup/status-file.ts';
import { existsSync } from 'fs';
import { join } from 'path';
import { FAILED_EXIT_CODE } from '../core/exit-codes.ts';
+import { opError, type OperationError } from '../core/ops/contract.ts';
interface SourceRow { id: string; local_path: string | null; config: unknown; }
@@ -42,6 +43,14 @@ function configHost(config: unknown): string | null {
return null;
}
+const HARDEN_USAGE = 'gbrain sources harden <id|--all> [--pat-file <p>] [--branch <b>] [--no-cron] [--no-verify] [--dry-run] [--json]';
+
+/** A3/D4: a missing source id is a caller mistake (exit 2): the usage, an example, and where the ids come from. */
+function hardenUsageError(): OperationError {
+ return opError('invalid_params', 'gbrain sources harden needs a source id or --all.',
+ `Usage: ${HARDEN_USAGE}. Example: gbrain sources harden wiki --pat-file ~/.config/gbrain/pat --dry-run (\`gbrain sources list\` shows the ids).`);
+}
+
async function loadSourceRows(engine: BrainEngine, id: string | undefined, all: boolean): Promise<SourceRow[]> {
if (all) {
// #3880: `--all` skips archived sources (v34 legacy fallback, house
@@ -55,7 +64,7 @@ async function loadSourceRows(engine: BrainEngine, id: string | undefined, all:
return engine.executeRaw<SourceRow>(`SELECT id, local_path, config FROM sources WHERE local_path IS NOT NULL ORDER BY id`);
}
}
- if (!id) throw new Error('Usage: gbrain sources harden <id|--all> [--pat-file <p>] [--branch <b>] [--no-cron] [--no-verify] [--dry-run] [--json]');
+ if (!id) throw hardenUsageError();
return engine.executeRaw<SourceRow>(`SELECT id, local_path, config FROM sources WHERE id = $1`, [id]);
}
@@ -65,6 +74,7 @@ export async function runHarden(engine: BrainEngine, args: string[]): Promise<vo
const all = args.includes('--all');
const id = all ? undefined : args.find(a => !a.startsWith('--')
&& a !== flagVal(args, '--pat-file') && a !== flagVal(args, '--branch'));
+ if (!all && !id) throw hardenUsageError();
const json = args.includes('--json');
const dryRun = args.includes('--dry-run');
const installCron = !args.includes('--no-cron');
diff --git a/test/cli-usage-errors.serial.test.ts b/test/cli-usage-errors.serial.test.ts
new file mode 100644
index 0000000000..ebf1d198f9
--- /dev/null
+++ b/test/cli-usage-errors.serial.test.ts
@@ -0,0 +1,54 @@
+/**
+ * A3/D4 closeout: invocations that used to `throw new Error('Usage: …')` (and
+ * `sources harden` with no id, which surfaced as internal_error) are
+ * invalid_params caller mistakes: exit 2, the usage and an example in the
+ * suggestion, legacy JSON keys kept where the command had a JSON shape.
+ *
+ * Serial: real CLI subprocesses against one temp PGLite brain.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { gb } from './helpers/agent-journey.ts';
+
+function lastJson(stdout: string): Record<string, any> {
+ const t = stdout.trim();
+ try { return JSON.parse(t); } catch { return JSON.parse(t.split('\n').filter(Boolean).at(-1)!); }
+}
+
+describe('usage mistakes exit 2 with the usage and an example', () => {
+ let home = '';
+ beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-usage-errors-'));
+ expect((await gb(home, ['init', '--pglite', '--no-embedding', '--json'], { timeoutMs: 120_000 })).exitCode).toBe(0);
+ }, 150_000);
+ afterAll(() => { rmSync(home, { recursive: true, force: true }); });
+
+ const rows: Array<{ args: string[]; legacy?: Record<string, unknown> }> = [
+ { args: ['sources', 'harden', '--json'] },
+ { args: ['migrate', '--json'] },
+ { args: ['mcp', 'grant'], legacy: { status: 'error', reason: 'invalid_params' } },
+ { args: ['backup', 'create', '--json'], legacy: { ok: false, reason: 'invalid_params' } },
+ { args: ['backup', 'restore', '--json'], legacy: { ok: false, reason: 'invalid_params' } },
+ ];
+
+ for (const row of rows) {
+ test(`gbrain ${row.args.join(' ')}`, async () => {
+ const r = await gb(home, row.args);
+ expect(r.exitCode, r.stderr.slice(-1500)).toBe(2);
+ const doc = lastJson(r.stdout);
+ expect(doc).toMatchObject({ error: 'invalid_params', code: 'invalid_params', class: 'caller', contract_version: 1, ...(row.legacy ?? {}) });
+ expect(doc.suggestion).toContain('Usage: gbrain ');
+ expect(doc.suggestion).toContain('Example: gbrain ');
+ expect(r.stderr).toContain('Error [invalid_params]');
+ expect(r.stderr).not.toContain('internal_error');
+ }, 60_000);
+ }
+
+ test('human sources harden prints the usage on the Fix line', async () => {
+ const r = await gb(home, ['sources', 'harden']);
+ expect(r.exitCode).toBe(2);
+ expect(r.stderr).toContain('Fix: Usage: gbrain sources harden <id|--all>');
+ }, 60_000);
+});