Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
W-C1: connectors sync and recall --limit usage errors are invalid_params envelopes (exit 2)
garrytan973ce36b3564
diff --git a/src/commands/connectors/sync.ts b/src/commands/connectors/sync.tsindex 2d5498f333..c1e70e239d 100644--- a/src/commands/connectors/sync.ts+++ b/src/commands/connectors/sync.ts@@ -16,7 +16,8 @@ import { connectorProviderNames, isConnectorProviderName } from '../../core/connimport { loadCredential } from '../../core/connectors/credentials.ts';import { sourceIdKey } from '../../core/connectors/config-keys.ts';import type { ConnectorProviderName } from '../../core/connectors/types.ts';-import { intFlagValue } from '../../cli/flag-values.ts';+import { flagValueError, intFlagValue } from '../../cli/flag-values.ts';+import { usageError } from '../../cli/cli-error.ts';interface SyncFlags {full: boolean;@@ -30,9 +31,10 @@ interface SyncFlags {all: boolean;}-function parseFlags(args: string[]): { provider: string; flags: SyncFlags } {+function parseFlags(args: string[]): { provider: string; providerIndex: number; flags: SyncFlags } {const flags: SyncFlags = { full: false, dryRun: false, embed: false, background: false, json: false, all: false };let provider = '';+ let providerIndex = -1;for (let i = 0; i < args.length; i++) {const a = args[i];if (a === '--all') flags.all = true;@@ -45,19 +47,35 @@ function parseFlags(args: string[]): { provider: string; flags: SyncFlags } {else if (a === '--limit') flags.limit = intFlagValue(args[++i], '--limit', { min: 1, example: 50 });else if (a === '--window-days') flags.windowDays = intFlagValue(args[++i], '--window-days', { min: 0, example: 30 });else if (a === '--source') flags.source = args[++i];- else if (!a.startsWith('-')) provider = a;+ else if (!a.startsWith('-')) { provider = a; providerIndex = i; }}- return { provider, flags };+ return { provider, providerIndex, flags };+}++const SYNC_USAGE = 'gbrain connectors sync <chatgpt|claude>|--all [--full] [--dry-run] [--limit N] [--window-days N] [--source id] [--embed] [--background] [--json]';++/** Agent contract v1: usage errors are `invalid_params` (exit 2, one `--json` envelope) naming the usage and the fix. */+function syncUsageError(message: string, fix: { argv: string[]; inputs: Array<{ name: string; how: string }> }) {+ return usageError(message, `Usage: ${SYNC_USAGE}`, {+ why: 'gbrain connectors sync needs one provider (or --all) and a value after every value flag.',+ fix: { ...fix, consent: [], actor: 'agent', why: 'A corrected command line runs the sync.', requires_exclusive: false },+ });}export async function runConnectorSyncCmd(engine: BrainEngine, args: string[]): Promise<void> {- if (args.some((arg, i) => arg === '--source' && (!args[i + 1] || args[i + 1].startsWith('-')))) {- console.error('Usage: gbrain connectors sync <chatgpt|claude>|--all [--full] [--dry-run] [--limit N] [--source id]');- setCliExitVerdict(1);+ if (args.includes('--help') || args.includes('-h')) {+ console.log(`Usage: ${SYNC_USAGE}`);return;}+ const badSource = args.findIndex((arg, i) => arg === '--source' && (!args[i + 1] || args[i + 1].startsWith('-')));+ if (badSource !== -1) {+ const argv = ['gbrain', 'connectors', 'sync', ...args.slice(0, badSource + 1), '<SOURCE_ID>', ...args.slice(badSource + 1)];+ throw syncUsageError(flagValueError('--source', args[badSource + 1], 'a source id', 'default').message, {+ argv, inputs: [{ name: 'SOURCE_ID', how: 'The id of the source the imported conversations belong to (gbrain sources list), or drop --source to use the configured connector source.' }],+ });+ }- const { provider, flags } = parseFlags(args);+ const { provider, providerIndex, flags } = parseFlags(args);// Resolve the target provider set.let providers: ConnectorProviderName[];@@ -72,9 +90,11 @@ export async function runConnectorSyncCmd(engine: BrainEngine, args: string[]):} else if (isConnectorProviderName(provider)) {providers = [provider];} else {- console.error('Usage: gbrain connectors sync <chatgpt|claude>|--all [--full] [--dry-run] [--limit N]');- setCliExitVerdict(1);- return;+ const names = connectorProviderNames();+ throw syncUsageError(provider ? `Unknown connector provider '${provider}'; expected ${names.join(', ')} or --all.` : `Name a connector provider (${names.join(', ')}) or pass --all.`, {+ argv: ['gbrain', 'connectors', 'sync', '<PROVIDER>', ...args.filter((_, i) => i !== providerIndex)],+ inputs: [{ name: 'PROVIDER', how: `One of ${names.join(', ')}, or --all for every provider with a credential (gbrain connectors providers lists them).` }],+ });}const sourceId = flags.source ?? (await engine.getConfig(sourceIdKey())) ?? 'default';diff --git a/src/commands/recall.ts b/src/commands/recall.tsindex 621fba81f8..d8b8e2ba1c 100644--- a/src/commands/recall.ts+++ b/src/commands/recall.ts@@ -37,6 +37,7 @@ import { loadConfig, isThinClient } from '../core/config.ts';import { callRemoteTool, RemoteMcpError, unpackToolResult } from '../core/mcp-client.ts';import { readCursor, writeCursor } from '../core/recall-cursor-state.ts';import { resolveSourceId, resolveSourceIdEngineFree, SourceTargetError } from '../core/source-resolver.ts';+import { usageError } from '../cli/cli-error.ts';// Same kebab-case shape gate the source-resolver applies. v0.32: applied// locally on thin-client where the canonical resolver's assertSourceExists@@ -128,8 +129,14 @@ function parseFlags(args: string[]): ParsedFlags {if (a === '--limit') {const raw = args[++i] ?? '';if (!/^\d+$/.test(raw) || !Number.isSafeInteger(Number(raw)) || Number(raw) < 1) {- process.stderr.write(`Error: --limit must be a positive safe integer (got "${raw}").\n`);- process.exit(2);+ const message = `--limit must be a positive safe integer (got "${raw}").`;+ // Agent contract v1: invalid_params (exit 2 through renderCliError, the envelope under --json).+ const valueGiven = i < args.length && !raw.startsWith('--');+ const argv = ['gbrain', 'recall', ...args.slice(0, i), '50', ...args.slice(valueGiven ? i + 1 : i)];+ throw usageError(message, 'Pass a positive integer, e.g. --limit 50.', {+ why: '--limit caps how many facts recall returns, so it must be a whole number of at least 1.',+ fix: { argv, consent: [], actor: 'agent', why: 'The same recall with a valid --limit.', requires_exclusive: false },+ });}out.limit = Number(raw); continue;}diff --git a/test/connectors-sync-cli.test.ts b/test/connectors-sync-cli.test.tsindex ba59f6cc35..ad3af767ee 100644--- a/test/connectors-sync-cli.test.ts+++ b/test/connectors-sync-cli.test.ts@@ -5,6 +5,8 @@ import { join } from 'node:path';import { runConnectorSyncCmd } from '../src/commands/connectors/sync.ts';import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';import { withEnv } from './helpers/with-env.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { renderCliError } from '../src/core/agent-output.ts';const tempHomes: string[] = [];@@ -27,18 +29,48 @@ describe('connectors sync --source CLI validation', () => {GBRAIN_CONNECTOR_CLAUDE_COOKIE: undefined,GBRAIN_CONNECTOR_CLAUDE_TOKEN: undefined,}, async () => {- const errors: string[] = [];- const originalError = console.error;- console.error = (...values: unknown[]) => errors.push(values.join(' '));- try {- await runConnectorSyncCmd({ getConfig: async () => 'configured-source' } as never, args);- } finally {- console.error = originalError;- }-- expect(errors.join('\n')).toContain('Usage: gbrain connectors sync');- expect(currentExitCode()).toBe(1);+ const error = await runConnectorSyncCmd({ getConfig: async () => 'configured-source' } as never, args).then(() => null, (e: unknown) => e);+ // Agent contract v1: invalid_params (exit 2 through renderCliError) with a fix that names the missing input.+ expect(error).toBeInstanceOf(OperationError);+ const e = error as OperationError;+ expect(e.code).toBe('invalid_params');+ expect(e.message).toContain('--source requires a value');+ expect(e.suggestion).toContain('Usage: gbrain connectors sync');+ expect(e.why).toBeTruthy();+ expect(e.fix?.argv).toEqual(['gbrain', 'connectors', 'sync', 'claude', '--source', '<SOURCE_ID>', ...args.slice(2)]);+ expect(e.fix?.inputs?.[0]?.name).toBe('SOURCE_ID');+ const rendered = renderCliError(e, { json: true, command: 'connectors', tty: false });+ expect(rendered.exitCode).toBe(2);+ expect(JSON.parse(rendered.stdout!)).toMatchObject({ code: 'invalid_params', fix: { next: 'run' } });+ expect(currentExitCode()).toBe(0);});});}});++describe('connectors sync provider usage errors', () => {+ for (const [args, message] of [+ [[], 'Name a connector provider'],+ [['bogus', '--full'], "Unknown connector provider 'bogus'"],+ ] as const) {+ test(`exit 2 invalid_params: ${args.join(' ') || '(no provider)'}`, async () => {+ const error = await runConnectorSyncCmd({ getConfig: async () => null } as never, [...args]).then(() => null, (e: unknown) => e);+ expect(error).toBeInstanceOf(OperationError);+ const e = error as OperationError;+ expect(e.code).toBe('invalid_params');+ expect(e.message).toContain(message);+ expect(e.fix?.argv).toEqual(['gbrain', 'connectors', 'sync', '<PROVIDER>', ...args.filter(a => a !== 'bogus')]);+ expect(renderCliError(e, { json: false, command: 'connectors', tty: false }).exitCode).toBe(2);+ expect(currentExitCode()).toBe(0);+ });+ }++ test('--help prints the usage and succeeds', async () => {+ const lines: string[] = [];+ const log = console.log;+ console.log = (...values: unknown[]) => lines.push(values.join(' '));+ try { await runConnectorSyncCmd({ getConfig: async () => null } as never, ['--help']); } finally { console.log = log; }+ expect(lines.join('\n')).toContain('Usage: gbrain connectors sync');+ expect(currentExitCode()).toBe(0);+ });+});diff --git a/test/recall-grep-local-cli.test.ts b/test/recall-grep-local-cli.test.tsindex 16f9a963f7..d0c1cfbca9 100644--- a/test/recall-grep-local-cli.test.ts+++ b/test/recall-grep-local-cli.test.ts@@ -15,6 +15,7 @@import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { runRecall } from '../src/commands/recall.ts';+import { OperationError } from '../src/core/ops/contract.ts';let engine: PGLiteEngine;const origWrite = process.stdout.write.bind(process.stdout);@@ -66,23 +67,12 @@ beforeEach(() => {describe('gbrain#5607 — local recall --grep filters in SQL before LIMIT', () => {test('rejects malformed --limit values and accepts a positive integer', async () => {- const originalExit = process.exit;- const originalStderr = process.stderr.write;- const refused: string[] = [];- process.exit = ((code?: number) => { refused.push(String(code)); throw new Error('exit intercepted'); }) as typeof process.exit;- process.stderr.write = ((chunk: string | Uint8Array) => { captured += typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString(); return true; }) as typeof process.stderr.write;- try {- for (const value of ['3x', 'abc', '0']) {- let exited = false;- try { await runRecall(engine, ['--limit', value]); } catch (error) { exited = (error as Error).message === 'exit intercepted'; }- expect(exited).toBe(true);- expect(refused.at(-1)).toBe('2');- expect(captured).toContain(`got "${value}"`);- captured = '';- }- } finally {- process.exit = originalExit;- process.stderr.write = originalStderr;+ // Agent contract v1: an invalid_params usage error (exit 2 through renderCliError).+ for (const value of ['3x', 'abc', '0']) {+ const error = await runRecall(engine, ['--limit', value]).then(() => null, (e: unknown) => e);+ expect(error).toBeInstanceOf(OperationError);+ expect((error as OperationError).code).toBe('invalid_params');+ expect((error as OperationError).message).toContain(`got "${value}"`);}const needle = await seed({ entity: 'g5607-limit-valid' });const out = await recallJson(['--grep', needle, '--limit', '3']);diff --git a/test/recall-limit-envelope.test.ts b/test/recall-limit-envelope.test.tsnew file mode 100644index 0000000000..06e640e3ae--- /dev/null+++ b/test/recall-limit-envelope.test.ts@@ -0,0 +1,52 @@+/**+ * Agent contract v1: `gbrain recall --limit` usage errors are invalid_params+ * (exit 2 through renderCliError): under `--json` one envelope carrying+ * `code`, `why` and a runnable `fix`; on a terminal the Error/Fix/Why lines.+ * The flag is parsed before any engine call, so no brain is opened.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { runRecall, recallNeedsLocalEngine } from '../src/commands/recall.ts';+import { renderCliError } from '../src/core/agent-output.ts';+import { OperationError } from '../src/core/ops/contract.ts';++const originalExit = process.exit;+afterEach(() => { process.exit = originalExit; });++/** The refusal recall throws; a pre-contract `process.exit` fails the test instead of killing the runner. */+async function refusal(args: string[]): Promise<OperationError> {+ process.exit = ((code?: number) => { throw new Error(`process.exit(${code}) instead of an invalid_params error`); }) as typeof process.exit;+ const error = await runRecall({} as never, args).then(() => null, (e: unknown) => e);+ expect(error).toBeInstanceOf(OperationError);+ return error as OperationError;+}++describe('recall --limit invalid-input envelope', () => {+ test('--json renders one invalid_params envelope (exit 2) with why and a corrected command', async () => {+ const e = await refusal(['--limit', '0', '--json']);+ const r = renderCliError(e, { json: true, command: 'recall', tty: false });+ expect(r.exitCode).toBe(2);+ const env = JSON.parse(r.stdout!);+ expect(env.code).toBe('invalid_params');+ expect(env.message).toContain('got "0"');+ expect(env.why).toContain('--limit');+ expect(env.fix.argv.slice(0, 5)).toEqual(['gbrain', 'recall', '--limit', '50', '--json']);+ expect(env.fix.next).toBe('run');+ });++ test('a missing value inserts the example instead of dropping the next flag', async () => {+ const e = await refusal(['--json', '--limit', '--today']);+ expect(e.fix?.argv).toEqual(['gbrain', 'recall', '--json', '--limit', '50', '--today']);+ });++ test('human output names the bad value and the fix on stderr', async () => {+ const r = renderCliError(await refusal(['--limit', '3x']), { json: false, command: 'recall', tty: false });+ expect(r.exitCode).toBe(2);+ expect(r.stderr).toContain('got "3x"');+ expect(r.stderr).toContain('Fix: gbrain recall --limit 50');+ });++ test('the thin-client dispatch probe refuses the same way', () => {+ process.exit = ((code?: number) => { throw new Error(`process.exit(${code})`); }) as typeof process.exit;+ expect(() => recallNeedsLocalEngine(['--limit', 'x'])).toThrow(OperationError);+ });+});