Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(cli): --types takes a bare value or comma list (#7173)
garrytanc90a856ae827
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.mdindex ceb2fe01e2..4411a372f9 100644--- a/docs/architecture/key-files/agent-contract.md+++ b/docs/architecture/key-files/agent-contract.md@@ -14,7 +14,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-- `src/cli/cli-error.ts` — the CLI's one error writer (D1): `writeCliError`/`exitCliError` render through `renderCliError` (human `Error [code]` / `Fix:` / `Why:` / `Docs:` on stderr; under `--json` one envelope on stdout plus the human lines on stderr) and record the code for the guard's fallback document; a `legacy` shape (unknown flag's `{status, reason:'invalid_flag', message}`, `pglite_busy`'s `next_action`) leads, keeps its values and stays one line. `usageError` (`invalid_params` / `unknown_flag` / `unknown_command`, exit 2), `unknownFlagError` (did-you-mean from the command's curated help flags, else the acceptance registry), `writeFatalCliError` (the `import.meta.main` seam; keeps the `GBRAIN_DB_ACCESS` marker + remediation on human output; a `pglite_busy` with reason `legacy_owner_unverified` renders its own ask_user fix, `retryable: false`, exit 3). Test: `test/cli-error-render.test.ts`.- `src/cli/help/<command>.ts` + `src/cli/help/render.ts` + `src/cli/help/validate.ts` — D3/D4 curated CLI help. Each spec module exports `help: CliHelpSpec` (`summary`, `usage`, `flags: [{name, type: boolean|string|number|enum, values?, desc, consent?}]`, 2–4 `examples`, `end_of_options?`) and is loaded lazily through its command-table record's `help: () => import('./help/<name>.ts')` (literal, so `bun build --compile` bundles it and `gbrain --version` loads none; pinned by `test/cli-command-table.test.ts` and `scripts/check-compile-autoload.sh`). Curated today: doctor, import, serve, apply-migrations, autopilot, status, onboard; every curated flag must be in the generated acceptance registry and `--yes` is listed wherever the handler parses it. `printCuratedHelp` answers `gbrain <cmd> --help`/`-h` first in main()'s help short-circuit, engine-free (human table with type/values/consent; `--help --json` one document `{command, …spec, contract_version}`). `curatedFlagError(command, args)` (called in main() after the unknown-flag check) refuses a missing/non-numeric `number` value or an out-of-set `enum` value with `invalid_params` (exit 2) via `flagValueError`, example value drawn from the spec's examples; `--flag=value` and `--flag value`, stops at a bare `--`; `string` flags (e.g. onboard's `--max-usd off`) are not checked. `unknownFlagError` draws did-you-mean candidates from the curated flags. Tests: `test/cli-help-curated.test.ts`, `test/cli-help-curated-cli.test.ts`.- `src/cli/flag-values.ts` — strict numeric values for CLI-only flags (D4): `intFlagValue` / `numberFlagValue` (digits only, safe integer, `[min, max]`) and `flagValueError` raise `invalid_params` usage errors (exit 2) naming the flag, what it accepts and an example. Used by jobs submit, extract-conversation-facts, eval run-all, sync `--interval`, connectors sync, book-mirror (the absorbed community fixes #5936 #5934 #5933 #5931 #5930 #5909). Tests: each command's `*-numeric-flags`/`*-flags` test.-- `src/cli/op-param-values.ts` — `opParamValue`: typed values for shared ops from `ParamDef` inside `parseOpArgs` (number → finite, string enum → declared values), `invalid_params` with an example otherwise; mirrors MCP `validateParams`. `parseOpArgs` also honours a bare `--` (D6). Test: `test/cli-op-typed-args.test.ts`.+- `src/cli/op-param-values.ts` — `opParamValue`: typed values for shared ops from `ParamDef` inside `parseOpArgs` (number → finite, string enum → declared values), `invalid_params` with an example otherwise; mirrors MCP `validateParams`. `opStructuredValue` turns object/array flag text into its value: JSON, or for a string-item array a bare value or comma list (`--types company`, `--types person,company`, #7173); `test/cli-types-param.test.ts`. `parseOpArgs` also honours a bare `--` (D6). Test: `test/cli-op-typed-args.test.ts`.- `src/commands/init-json.ts` + `src/commands/init-first-run.ts` — `init --json` (D2): the success document accumulates across init's branches and is written once when `runInit` returns; failures keep their legacy one-line keys plus the envelope (Postgres-core failures are held until the direct wrapper writes them, so the `--prefer-postgres` ladder still prints only its envelope). `buildInitFirstRunNotices` is the G5 seam: one `first_run_decisions` ask notice with `decisions[]` (`search_mode`, `writeback`, `harness_wiring`, `skills_scaffold`); the stdio onboarding cache reuses it with writeback and skills only, and `setupFirstRunNotices` is `gbrain setup`'s form (from `init --json`: `harness_wiring` dropped, `why`/`user_message` framed as settings in effect that the agent relays in the install reply instead of a reply-to-continue question; Cat 41 wave 2, pinned by `test/init-first-run.test.ts`). `firstRunBundle`/`harnessRegistrationCommand` take `gbrain init --surface`. Tests: `test/cli-json-guard.test.ts`.- `src/core/onboard/hosted-option.ts` — the `hosted_option` coaching notice (gbrain.io, hosted GBrain): the one home of its URL, copy and `?ref=` tags. `gbrain setup` appends it when it created the brain, `printInAgentReady` prints it after the in-agent ready text when init created the brain (its mute hint names that install's own launcher), and `gbrain mcp expose`'s `Session.finish` adds it (JSON `notices`, one human line) on the run that wrote the first receipt and at Tailscale/service friction exits (`EXPOSE_FRICTION_REASONS`), never on the consent-pending document, `--dry-run`, `--status` or `--remove`. Bare `gbrain init` never shows it. Refs split publish (`cli-mcp-expose`) from friction exits (`cli-mcp-expose-friction`). Muted by the owner list or the `stdio` audience (`hostedOptionMuted`, i.e. `mutedNoticeCodes('stdio')`); `writeHostedOption` prints one plain line on a TTY and the notice block otherwise. No network call. Tests: `test/hosted-option.test.ts`, `test/setup.test.ts`, `test/mcp-expose.test.ts`.- `src/core/onboard/mcp-onboarding.ts` — onboarding coaching for the owner's stdio pipe. `collectOnboardOpportunities(engine, signal, between?)` is the one home of init's six counts (parallel for `runInitNudge`, sequential with yields for the background refresh; the stale-chunk count uses `countStaleChunks`' predicate, so soft-deleted and `embed_skip` pages are not backlog); a failed count is `null` and never reads as a gap, and `onboardGaps` applies init's thresholds (link < 0.7, timeline < 0.9; an empty brain has none). The per-brain cache (6 h TTL, `GBRAIN_HOME/onboard-counts-<brain>.json`, atomic write, partial runs not persisted) is loaded by `startOnboardingRefresher` and refreshed in the background only while the idle gate reports no request in flight (3 s budget); it also holds the pitchable `gbrain features` recommendations (`pitchableFeatures`, offer state read-only) and the stale-chunk backfill estimate. `mcpOnboardingNotices` is dispatch's one producer on the stdio success path: `first_run_decisions` (writeback + skills via `mcpFirstRunNotices`, from the second successful call, nothing persisted) and one coaching notice per class (`onboard_stale_chunks`, `onboard_link_coverage`, `onboard_timeline_coverage`, `onboard_no_takes`) when `ONBOARD_CALL_AFFINITY` names the call and the class's result predicate holds, plus `features_auto_fix` on `get_backlinks`/`traverse_graph`; fixes are the read-only `get_health` / `gbrain onboard --check` preview, the dismissal line names `mute_notice` only where it is callable. `mutedFirstRunDecisionsNotice` feeds doctor (`memory_writeback`) and `gbrain onboard --check`. HTTP never calls it. Test seams `__warmOnboardingCacheForTests`, `__awaitOnboardingRefreshForTests`, `__resetMcpOnboardingForTests`. Tests: `test/mcp-onboarding.test.ts`, `test/init-nudge.test.ts`, `test/mcp-notice-channels.test.ts`.diff --git a/src/cli/main.ts b/src/cli/main.tsindex 4e5c06ecab..b689fbfad0 100755--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -49,7 +49,7 @@ import { cliCommandOf, exitCliError, exitOnRepairFailed, unknownFlagError, usageimport type { Notice } from '../core/agent-output.ts';import { opError, opOwnsSource } from '../core/ops/contract.ts';import { PAGE_MAX_BYTES } from '../core/page-size-policy.ts';-import { opParamValue } from './op-param-values.ts';+import { opParamValue, opStructuredValue } from './op-param-values.ts';import { SEGMENTED_STREAMED, formatGetPage, printPagedPage, remoteErrorCode, streamSegmentedGet, wantsWholePage } from './page-render.ts';import { parseGlobalFlags, setCliOptions, getCliOptions } from '../core/cli-options.ts';import { runCliPreflight } from '../core/cli-preflight.ts';@@ -1131,12 +1131,7 @@ 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;- 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;+ if (params[key] !== undefined) params[key] = opStructuredValue(key, def, params[key]);}return params;}diff --git a/src/cli/op-param-values.ts b/src/cli/op-param-values.tsindex 2fd652bbb0..d22af6f71d 100644--- a/src/cli/op-param-values.ts+++ b/src/cli/op-param-values.ts@@ -28,3 +28,19 @@ export function opParamValue(op: Operation, key: string, def: ParamDef | undefin}return raw;}++/**+ * An object/array param from its CLI text: JSON, or for a string-item array+ * a bare value or comma list (`--types company`, `--types person,company`,+ * the form the op's own errors suggest). Other values pass through.+ */+export function opStructuredValue(key: string, def: ParamDef, value: unknown): unknown {+ const flag = `--${key.replace(/_/g, '-')}`;+ if ((def.type !== 'object' && def.type !== 'array') || typeof value !== 'string') return value;+ if (def.type === 'array' && def.items?.type === 'string' && !value.trimStart().startsWith('[')) return value.split(',').map(v => v.trim()).filter(Boolean);+ const jsonError = () => usageError(`${flag} requires a JSON ${def.type}.`, `Pass JSON, e.g. ${flag} '${def.type === 'array' ? '["a","b"]' : '{"key":"value"}'}'.`);+ let parsed: unknown;+ try { parsed = JSON.parse(value); } catch { throw jsonError(); }+ if (def.type === 'array' ? !Array.isArray(parsed) : parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) throw jsonError();+ return parsed;+}diff --git a/test/cli-types-param.test.ts b/test/cli-types-param.test.tsnew file mode 100644index 0000000000..09b0f4803e--- /dev/null+++ b/test/cli-types-param.test.ts@@ -0,0 +1,28 @@+/**+ * #7173: `--types` takes the bare and comma forms its help and the op's own+ * errors suggest (`--types company`, `--types person,company`), as well as+ * a JSON array. Before the fix the generic CLI parser JSON-parsed every+ * array param and refused both with `--types requires a JSON array`.+ */+import { describe, expect, test } from 'bun:test';+import { operations } from '../src/core/operations.ts';+import { parseOpArgs } from '../src/cli/main.ts';++const op = (name: string) => operations.find(o => o.name === name)! as never;++describe('--types on search and query (#7173)', () => {+ test('a bare value is a one-type list', () => {+ expect(parseOpArgs(op('search'), ['q', '--types', 'company']).types).toEqual(['company']);+ expect(parseOpArgs(op('query'), ['q', '--types', 'interview-transcript']).types).toEqual(['interview-transcript']);+ });++ test('a comma list splits, with spaces trimmed', () => {+ expect(parseOpArgs(op('search'), ['q', '--types', 'person,company']).types).toEqual(['person', 'company']);+ expect(parseOpArgs(op('search'), ['q', '--types=person, company']).types).toEqual(['person', 'company']);+ });++ test('a JSON array still works, and malformed JSON is still a usage error', () => {+ expect(parseOpArgs(op('query'), ['q', '--types', '["person"]']).types).toEqual(['person']);+ expect(() => parseOpArgs(op('query'), ['q', '--types', '["person"'])).toThrow('--types requires a JSON array');+ });+});