Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(cli): #7619 ship review: google attachments own parser, --json=true in own parsers, dream/embed switches, neutral search-dashboard refusal, direct auth entry renders global-flag errors
garrytanf72f9a2d3035
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex c79cc79a31..222117d3a9 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -76,7 +76,7 @@ test/claude-cli-recipe.test.ts claude-cli LanguageModel — output cap (#6424) 2test/claude-cli-recipe.test.ts claude-cli LanguageModel — text-only round trip 4 readFileSynctest/claude-cli-recipe.test.ts claude-cli LanguageModel — tool use 17 readFileSynctest/claude-cli-recipe.test.ts claude-cli recipe registration 2 readFileSync-test/cli-flag-equals.test.ts #7619 refusals that keep consent, scope and targets right 13 readFileSync,source-surface-helper+test/cli-flag-equals.test.ts #7619 refusals that keep consent, scope and targets right 15 readFileSync,source-surface-helpertest/cli-flag-equals.test.ts #7619 split rules 21 readFileSync,source-surface-helpertest/cli-force-exit-teardown-arming.test.ts cli.ts — disconnect hard-deadline armed at teardown entry, not before the op body 1 readFileSync,source-surface-helpertest/cli.test.ts BigInt-safe output normalization (#2450) 5 source-surface-helperdiff --git a/src/cli/flag-equals.ts b/src/cli/flag-equals.tsindex ab41e59f8b..fd89fb5c18 100644--- a/src/cli/flag-equals.ts+++ b/src/cli/flag-equals.ts@@ -81,7 +81,7 @@ export const EQUALS_READERS: Readonly<Record<string, readonly string[]>> = {'edge-proposals list': ['--status', '--limit'],// embed.ts:841 parsePaceArgs (--pace bare or =mode); core/consent.ts:126 via embed-consent.ts:129 and held-embedding.ts:234.embed: ['--pace', '--pace-max-concurrency', '--max-usd', '--max-cost'],- // eval-conversation-parser.ts:48-53 (main.ts:2216 and eval.ts:106 both reach it).+ // eval-conversation-parser.ts:48-53 (main.ts handleCliOnly's eval conversation-parser branch and eval.ts:106 both reach it).'eval conversation-parser': ['--fixtures', '--min-recall'],// eval/decide-eval-flags.ts:124 extractDecideEvalFlags via eval-retrieval-quality.ts:38.'eval retrieval-quality': ['--decide', '--decide-provider', '--decide-calibration', '--decide-threshold', '--decide-force-on', '--decide-dataset'],@@ -194,7 +194,7 @@ export const EQUALS_READERS: Readonly<Record<string, readonly string[]>> = {* exact tokens.*/export const OWN_EQUALS_PARSERS: ReadonlySet<string> = new Set([- 'append', 'auth local-writer', 'eval longmemeval', 'git', 'migrate embeddings', 'repair', 'retrieval-upgrade', 'schema add-type', 'skillpack remove',+ 'append', 'auth local-writer', 'eval longmemeval', 'git', 'google attachments', 'migrate embeddings', 'repair', 'retrieval-upgrade', 'schema add-type', 'skillpack remove','sources connect', 'sources inspect', 'sources reconcile', 'sources reset-upstream', 'sources writer','takes add', 'takes remove', 'takes resolve', 'takes supersede', 'takes update',]);@@ -203,6 +203,8 @@ export const OWN_EQUALS_PARSERS: ReadonlySet<string> = new Set([export const COMMAND_SWITCHES: Readonly<Record<string, readonly string[]>> = {sync: ['--detail'],schema: ['--fields'],+ dream: ['--unsafe-bypass-dream-guard'],+ embed: ['--stale'],};/** Paths (`command sub`) whose handler treats a bare `--` as the end of its options; everywhere else the scan continues past it. */@@ -252,6 +254,8 @@ export async function splitFlagEquals(command: string, args: readonly string[]):? [`the value is empty or looks like a flag`, `Write ${flag} <value> with the value as the next argument.`]: own === undefined && /^(true|false|yes|no|y|n|on|off|0|1)$/i.test(value)? [`write ${flag} on its own if it is a switch, or with its value as the next argument`, `If ${flag} is a switch, write it on its own to turn it on, or leave it out to turn it off: a value never turns it off. If it takes a value, put the value in the next argument.`]+ : !legal+ ? [`gbrain ${command} ${args[0]} reads no = form`, `Check the flag in gbrain ${command} ${args[0]} --help, then write its value as the next argument.`]: own === undefined? [`this command takes ${flag} <value> as two arguments`, `Write ${flag} <value>, or ${flag} on its own if it is a switch.`]: null;diff --git a/src/commands/auth.ts b/src/commands/auth.tsindex c3182c9ec9..49b2d8a4a3 100644--- a/src/commands/auth.ts+++ b/src/commands/auth.ts@@ -1403,11 +1403,8 @@ export async function runAuth(args: string[]): Promise<void> {// (e.g. `bun run src/commands/auth.ts ...`). When imported by cli.ts, this block is skipped.if (import.meta.main) {const { directEntryArgs } = await import('../cli/flag-equals.ts');- const argv = await directEntryArgs('auth', process.argv.slice(2));- if ('refusal' in argv) {- const { exitCliError } = await import('../cli/cli-error.ts');- exitCliError(argv.refusal, 'auth', { legacy: argv.legacy });- } else {- await runAuth(argv.args);- }+ const { exitCliError } = await import('../cli/cli-error.ts');+ const argv = await directEntryArgs('auth', process.argv.slice(2)).catch((e: unknown) => exitCliError(e, 'auth'));+ if ('refusal' in argv) exitCliError(argv.refusal, 'auth', { legacy: argv.legacy });+ else await runAuth(argv.args);}diff --git a/src/commands/schema-add-type.ts b/src/commands/schema-add-type.tsindex 17c4adecd9..98371467d8 100644--- a/src/commands/schema-add-type.ts+++ b/src/commands/schema-add-type.ts@@ -87,7 +87,7 @@ export function parseAddTypeArgs(args: string[]): AddTypeArgs {const flag = a.startsWith('--') && eq > 0 ? a.slice(0, eq) : a;if (!flag.startsWith('--')) { positional.push(a); continue; }seen.add(flag);- if (!VALUE_FLAGS.has(flag) && flag !== a) throw usageError(`${flag} is a switch and takes no value.`, `Write ${flag} on its own.`);+ if (!VALUE_FLAGS.has(flag) && flag !== a && a !== '--json=true') throw usageError(`${flag} is a switch and takes no value.`, `Write ${flag} on its own.`);if (!VALUE_FLAGS.has(flag)) continue;const value = flag !== a ? a.slice(eq + 1) : args[++i];if (flag === '--alias') { if (value !== undefined) aliases.push(value); } else values[flag] = value;diff --git a/src/commands/sources-writer-movement.ts b/src/commands/sources-writer-movement.tsindex 5daeaac25d..f9db94f16e 100644--- a/src/commands/sources-writer-movement.ts+++ b/src/commands/sources-writer-movement.ts@@ -76,7 +76,7 @@ export function parseMovementArgs(args: string[]): MovementArgs {const flag = token.startsWith('-') && equal > 0 ? token.slice(0, equal) : token;const value = () => { const v = equal > 0 && token.startsWith('-') ? token.slice(equal + 1) : args[++i]; if (v === undefined || v.startsWith('--')) throw usage(`${flag} requires a value.`, `Give ${flag} its value right after it, as ${flag} <value>.`); return v; };if (!token.startsWith('-')) { if (out.sourceId !== undefined) throw usage('Specify the source once.', `Name the source either as the argument or with --source, not both (here ${out.sourceId} and ${token}).`); out.sourceId = token; }- else if ((flag === '--json' || flag === '--warn-only') && flag !== token) throw usage(`${flag} is a switch and takes no value.`, `Write ${flag} on its own.`);+ else if ((flag === '--json' || flag === '--warn-only') && flag !== token && token !== '--json=true') throw usage(`${flag} is a switch and takes no value.`, `Write ${flag} on its own.`);else if (flag === '--json') out.json = true;else if (flag === '--warn-only') out.warnOnly = true;else if (flag === '--source') { if (out.sourceId !== undefined) throw usage('Specify the source once.', 'Name the source either as the argument or with --source, not both.'); out.sourceId = value(); }diff --git a/test/cli-flag-equals.test.ts b/test/cli-flag-equals.test.tsindex 91e32c382a..403bb48bc1 100644--- a/test/cli-flag-equals.test.ts+++ b/test/cli-flag-equals.test.ts@@ -7,7 +7,7 @@* handler receives; these tables run it over every registered flag of every* command.*/-import { describe, expect, test } from 'bun:test';+import { afterEach, describe, expect, test } from 'bun:test';import { readFileSync } from 'node:fs';import { Glob } from 'bun';import { CLI_ONLY, cliOnlyFlagArgs, validateCommandFlags } from '../src/cli/main.ts';@@ -15,6 +15,7 @@ import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';import { END_OF_OPTIONS, EQUALS_READERS, OWN_EQUALS_PARSERS, directEntryArgs, knownSwitches } from '../src/cli/flag-equals.ts';import { SEARCH_SUBCOMMANDS } from '../src/cli/subcommands.ts';import { SYNC_FLAGS } from '../src/core/sync-flags.ts';+import { _resetCliOptionsForTest, getCliOptions } from '../src/core/cli-options.ts';import { strictSpecFor } from '../src/cli/strict-args.ts';import { surfaceFileSource } from './helpers/source-surface.ts';import { loadCuratedHelp } from '../src/cli/help/render.ts';@@ -95,6 +96,8 @@ describe('#7619 table: every registered CLI_ONLY flag', () => {});describe('#7619 split rules', () => {+ afterEach(() => _resetCliOptionsForTest());+test('a value containing = splits at the first =', async () => {expect(await argvFor('serve', ['--public-url=https://brain.example.com/?a=b'])).toEqual(['--public-url', 'https://brain.example.com/?a=b']);});@@ -124,7 +127,7 @@ describe('#7619 split rules', () => {});test('a true/false word on a switch with no table entry never suggests the value form', async () => {- for (const [command, args] of [['transcripts', ['recover', 'codex', '--apply=false']], ['trust', ['claim-sources', '--accept-all=no']], ['dream', ['--unsafe-bypass-dream-guard=off']]] as const) {+ for (const [command, args] of [['transcripts', ['recover', 'codex', '--apply=false']], ['trust', ['claim-sources', '--accept-all=no']], ['maintain', ['--apply=off']]] as const) {const r = await cliOnlyFlagArgs(command, [...args]);const text = 'refusal' in r ? `${r.refusal.message} ${r.refusal.suggestion}` : '';expect(text).toContain('a value never turns it off');@@ -165,8 +168,11 @@ describe('#7619 split rules', () => {test('the direct entry strips global flags and validates local-writer the way main does', async () => {expect(await directEntryArgs('auth', ['list', '--quiet', '--timeout', '5s'])).toEqual({ args: ['list'] });+ expect(getCliOptions().quiet).toBe(true);const r = await directEntryArgs('auth', ['local-writer', 'list', '--bogus']);expect('refusal' in r && r.refusal.code).toBe('unknown_flag');+ const own = ['local-writer', 'register', '--expected-epoch=1', '--scopes=read,write'];+ expect(await directEntryArgs('auth', own)).toEqual({ args: own });});test('the direct entry refuses an unknown flag with the envelope main uses', async () => {@@ -229,6 +235,7 @@ describe('#7619 split rules', () => {expect(await argvFor('call', ['x', '--y=true'])).toEqual(['x', '--y=true']);expect(await argvFor('edge-proposals', ['list', '--status=all', '--limit=5'])).toEqual(['list', '--status=all', '--limit=5']);expect(await argvFor('recall', ['--source-id=peer', '--json'])).toEqual(['--source-id=peer', '--json']);+ expect(await argvFor('recall', ['--budget-policy='])).toEqual(['--budget-policy=']);expect(await argvFor('export', ['--source=default', '--dir=out-example'])).toEqual(['--source=default', '--dir=out-example']);expect(await argvFor('skillpack', ['reference', '--harness=claude-code'])).toEqual(['reference', '--harness=claude-code']);expect(await argvFor('sources', ['status', '--limit=5'])).toEqual(['status', '--limit=5']);@@ -433,6 +440,7 @@ describe('#7619 refusals that keep consent, scope and targets right', () => {expect(CLI_FLAG_REGISTRY[command]).toContain(token.split('=')[0]!);const r = await cliOnlyFlagArgs(command, [...args]);expect('refusal' in r && r.refusal.code).toBe('invalid_params');+ expect('refusal' in r && `${r.refusal.message} ${r.refusal.suggestion}`).not.toContain('<value>');}});@@ -445,7 +453,6 @@ describe('#7619 refusals that keep consent, scope and targets right', () => {['trust', ['explain', 'ref-example', '--source=source-a'], '--source'], ['jobs', ['work', '--concurrency=4'], '--concurrency'],['forget', ['34', '--reason=stale-example'], '--reason'], ['migrate', ['--to=pglite'], '--to'],['jobs', ['submit', 'shell', '--params={"a":1}'], '--params'], ['jobs', ['submit', 'sync', '--max-usd=5'], '--max-usd'],- ['search', ['diagnose', 'q', '--target', 'x', '--source=source-a'], '--source'],] as const) {const r = await cliOnlyFlagArgs(command, [...args]);expect('refusal' in r && r.refusal.message).toContain(`takes ${flag} <value> as two arguments`);@@ -481,6 +488,19 @@ describe('#7619 refusals that keep consent, scope and targets right', () => {}});+ test('the hand-parsed search subcommands refuse an = form without vouching for the flag', async () => {+ for (const [args, flag] of [[['modes', '--mdoe=balanced'], '--mdoe'], [['diagnose', 'q', '--target', 'x', '--source=source-a'], '--source']] as const) {+ const r = await cliOnlyFlagArgs('search', [...args]);+ expect('refusal' in r && r.refusal.message).toContain(`${flag}=…`);+ expect('refusal' in r && r.refusal.message).not.toContain(`takes ${flag}`);+ expect('refusal' in r && r.refusal.suggestion).toContain(`gbrain search ${args[0]} --help`);+ }+ });++ test('google attachments hands its = forms to its own parser', async () => {+ expect(await argvFor('google', ['attachments', 'backfill', '--source=default', '--limit=5'])).toEqual(['attachments', 'backfill', '--source=default', '--limit=5']);+ });+test('validation-exempt paths that read exact tokens refuse the = form', async () => {for (const [command, args, flag] of [['jobs', ['submit', 'sync', '--dry-run=true', '--queue-only'], '--dry-run'], ['jobs', ['submit', 'shell', '--follow=1'], '--follow'],@@ -521,6 +541,9 @@ describe('#7619 refusals that keep consent, scope and targets right', () => {expect(() => parseAddTypeArgs(['note', '--primitive=entity', '--no-prefix=false'])).toThrow('--no-prefix is a switch');expect(() => parseAddTypeArgs(['note', '--primitive=entity', '--prefix=notes/', '--extractable=false'])).toThrow('--extractable is a switch');expect(parseAddTypeArgs(['note', '--primitive=entity', '--no-prefix'])).toMatchObject({ noPrefix: true });+ expect(parseMovementArgs(['source-a', '--json=true'])).toMatchObject({ json: true });+ expect(() => parseAddTypeArgs(['note', '--primitive=entity', '--no-prefix', '--json=true'])).not.toThrow();+ expect(() => parseMovementArgs(['source-a', '--json=false'])).toThrow('--json is a switch');});test('OWN_EQUALS_PARSERS and the = option parsers match in both directions', () => {@@ -529,7 +552,7 @@ describe('#7619 refusals that keep consent, scope and targets right', () => {'src/commands/eval-longmemeval.ts': 'eval longmemeval', 'src/commands/git.ts': 'git', 'src/commands/persistence-admin.ts': 'auth local-writer','src/commands/repair.ts': 'repair', 'src/commands/schema-add-type.ts': 'schema add-type', 'src/commands/skillpack/harness.ts': 'skillpack remove','src/commands/source-reconcile.ts': 'sources reconcile', 'src/commands/sources-reset-upstream.ts': 'sources reset-upstream',- 'src/commands/sources-writer-movement.ts': 'sources writer', 'src/commands/takes-mutation.ts': 'takes add',+ 'src/commands/sources-writer-movement.ts': 'sources writer', 'src/commands/takes-mutation.ts': 'takes add', 'src/commands/google-attachments.ts': 'google attachments',// normalizeReindexArgs splits its own value flags; the entry refuses other = forms before it runs.'src/commands/reindex.ts': null,// Governs managed brains only: an unmanaged brain falls back to runSources, which reads exact tokens, so the entry rule applies.@@ -537,18 +560,18 @@ describe('#7619 refusals that keep consent, scope and targets right', () => {};const PARSER_OF: Record<string, string> = {append: 'src/cli/commands/append.ts', 'auth local-writer': 'src/commands/persistence-admin.ts', 'eval longmemeval': 'src/commands/eval-longmemeval.ts',- git: 'src/commands/git.ts', 'migrate embeddings': 'src/core/embedding-migration-cli.ts', 'retrieval-upgrade': 'src/core/embedding-migration-cli.ts',+ git: 'src/commands/git.ts', 'google attachments': 'src/commands/google-attachments.ts', 'migrate embeddings': 'src/core/embedding-migration-cli.ts', 'retrieval-upgrade': 'src/core/embedding-migration-cli.ts',repair: 'src/commands/repair.ts', 'schema add-type': 'src/commands/schema-add-type.ts', 'skillpack remove': 'src/commands/skillpack/harness.ts','sources connect': 'src/commands/company-brain-connect.ts', 'sources inspect': 'src/commands/company-brain-inspect.ts','sources reconcile': 'src/commands/source-reconcile.ts', 'sources reset-upstream': 'src/commands/sources-reset-upstream.ts','sources writer': 'src/commands/sources-writer-movement.ts', 'takes add': 'src/commands/takes-mutation.ts', 'takes remove': 'src/commands/takes-mutation.ts','takes resolve': 'src/commands/takes-mutation.ts', 'takes supersede': 'src/commands/takes-mutation.ts', 'takes update': 'src/commands/takes-mutation.ts',};- const found = [...new Glob('src/commands/**/*.ts').scanSync('.')].filter(p => /\b(?:eq|equal|equals) = \w+\.indexOf\('='\)/.test(readFileSync(p, 'utf8'))).sort();+ const found = [...new Glob('src/commands/**/*.ts').scanSync('.')].filter(p => /\b(?:eq|equal|equals) = \w+\.indexOf\('='\)|\.split\(\/=\(\.\*\)\/s\)/.test(readFileSync(p, 'utf8'))).sort();expect(found).toEqual(Object.keys(OWNERS).sort());for (const owner of Object.values(OWNERS)) if (owner) expect(OWN_EQUALS_PARSERS.has(owner)).toBe(true);expect([...OWN_EQUALS_PARSERS].sort()).toEqual(Object.keys(PARSER_OF).sort());- for (const path of Object.values(PARSER_OF)) expect(readFileSync(path, 'utf8')).toMatch(/indexOf\('='\)|\(\?:=\(\.\*\)\)/);+ for (const path of Object.values(PARSER_OF)) expect(readFileSync(path, 'utf8')).toMatch(/indexOf\('='\)|\(\?:=\(\.\*\)\)|split\(\/=\(\.\*\)\/s\)/);});test("a command's own switch wins over a value of the same name elsewhere", async () => {diff --git a/test/generate-flag-registry.test.ts b/test/generate-flag-registry.test.tsindex adf4ff17c0..0108591adb 100644--- a/test/generate-flag-registry.test.ts+++ b/test/generate-flag-registry.test.ts@@ -183,6 +183,12 @@ describe('segmentDispatchBlocks — every if/case shape is a marker for its commexpect(CLI_FLAG_REGISTRY.reindex).toContain('--multimodal');});+ test('flag-equals.ts stays out of the scan, so auth does not borrow its table literals (#7619)', () => {+ for (const registry of [CLI_FLAG_REGISTRY, buildFlagRegistry()]) {+ for (const flag of ['--purge', '--pace', '--archived-at']) expect(registry.auth).not.toContain(flag);+ }+ });+test('committed registry: brainstorm/lsd do not carry the phantom --retry-judge (#4766)', () => {// The flag had no parser branch; it registered only because the judge-failed// advice strings in the brainstorm orchestrator mentioned it. The advice nowdiff --git a/test/serve-flag-equals.test.ts b/test/serve-flag-equals.test.tsindex aee0f10d60..02cae1f1c9 100644--- a/test/serve-flag-equals.test.ts+++ b/test/serve-flag-equals.test.ts@@ -158,6 +158,15 @@ describe('serve --flag=value', () => {expect(cli(['auth', 'list']).stdout).not.toContain('bot-typo-example');});+ test('the direct auth.ts entry renders a bad global flag as an envelope, not a stack trace', () => {+ for (const [args, code] of [[['list', '--wait=abc', '--json'], 2], [['list', '--brain'], 1]] as const) {+ const direct = spawnSync('bun', ['--no-env-file', 'run', 'src/commands/auth.ts', ...args], { cwd: process.cwd(), env, encoding: 'utf8', input: '', timeout: 30_000 });+ expect(direct.status).toBe(code);+ expect(direct.stderr).toMatch(/^Error \[/m);+ expect(direct.stderr).not.toMatch(/^\s+at /m);+ }+ });+test('a self-help handler never runs on the help path with an = token the gate refuses', () => {const r = cli(['connectors', 'auth', 'chatgpt', '--token=placeholder-example', '--help']);expect(r.status).toBe(2);