Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(cli): D4 typed flag values for curated CLI-only commands

garrytand8da0335868b
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.md
index e5f2ab64af..e4cdf60c00 100644
--- a/docs/architecture/key-files/agent-contract.md
+++ b/docs/architecture/key-files/agent-contract.md
@@ -11,5 +11,6 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-
- `src/core/notice-ledger.ts` — notice dedupe/budget/mute. `NoticeLedger.admit(notices, {transport, principal, sessionId}, muted)`: stdio uses `processNoticeLedger()`; HTTP passes `ServeHttpContext.noticeLedger` (keyed by principal + transport-resolved session id, 10k keys, 24 h TTL). Per-call codes (`empty_retrieval`, `unknown_param`, `listing_truncated`) and, on HTTP, `degraded`/`safety` notices are never deduped; at most 2 coaching notices per session. Mute store `<GBRAIN_HOME>/notices/muted.json`: owner list (global) + per-client lists; `mute_notice` op (`src/core/ops/notices.ts`, write scope, per client) and `gbrain notices mute|unmute|list` (`src/cli/commands/notices.ts`, owner). Test: `test/notice-ledger.test.ts`.
- `src/core/ops/callable.ts` — `isCallable(op, {transport, surface, scopes, publishGates, allowedOps})`: the one predicate behind stdio `stdioVisibleTools`, serve-http `listMcpTools`, the legacy bearer transport's tools/list, and `dispatchRenderContext` (which tools a fix may name). `publishGatesFromDisabled` converts the gate resolver's disabled-op set. Test: `test/callable-predicate.test.ts` (list ⇔ pre-A2 filters; list ⇔ dispatch on surface/locality).
- `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). Test: `test/cli-error-render.serial.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.serial.test.ts`.
- `src/cli/json-guard.ts` — picks the `--json` guard mode for an invocation: on only when `jsonRequested(argv)` and the command-table record declares `json: 'document' | 'ndjson'`; wires the E11 `json_document_missing` hook. The guard itself is `installStdoutPipeDelivery({ json })` in `src/core/cli-force-exit.ts`: stdout writes and console.log/info/debug go to stderr, only `writeStdoutFinal`/`writeNdjsonLine` reach fd 1, a non-zero exit with no document writes the fallback document, `spawnCliChild` pipes child stdout to stderr. Test: `test/cli-json-guard.serial.test.ts`.
- `scripts/check-agent-contract.ts` — syntax-only AST scanner (≈2 s) in `bun run verify` and `guards-manifest.tsv` (fixtures `test/fixtures/guards/check-agent-contract.ts/`). Rules: suggestion-less `OperationError`, `throw new Error` in ops/mcp/handlers, hand-built `fix`/`next_action` command strings, legacy advice keys, raw interactive stdin/readline/raw-mode outside `interaction.ts`/`consent.ts`, raw "re-run with --yes" strings outside `consent.ts`, `stdio: 'inherit'` outside `spawnCliChild`, marker literals outside `agent-output.ts`/`agent-markers.ts`, `verify.argv` naming a non-read-only command (read_only command-table records + a static read-only list), plus unregistered codes and code naming (never baselined). Per-rule shrink-only baselines in `scripts/agent-contract-baselines/<rule>.tsv`; `--update` lowers them and refuses growth.
diff --git a/docs/architecture/key-files/entrypoints-and-docs.md b/docs/architecture/key-files/entrypoints-and-docs.md
index 10c9643be3..bde8bff719 100644
--- a/docs/architecture/key-files/entrypoints-and-docs.md
+++ b/docs/architecture/key-files/entrypoints-and-docs.md
@@ -121,7 +121,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers `handleCliOnly`'s explicit ordered pipeline (`@cliPipelineStage` functions: thin-client guard, deferred-persistence routing, subcommand and help routes, read-only timeout path, sync watchdog and delegation, connectEngine terminator with degraded-serve recovery, teardown), thin-client routing and refusal, help and self-help text, strict flag parsing and process-exit teardown. Per-command dispatch (pre- and post-connect) lives in the command table (entry below), not in `src/cli.ts`.
- `src/cli/remember-format.ts` — the `remember` human formatter (`formatRememberResult`: status, entity with `(inferred from mention)`, expiry, degraded dedup, `warnings` + `hint`), kept out of `src/cli.ts`; `--json` prints the raw envelope. Pinned by `test/remember-entity-inference.test.ts`.
-- `src/cli/command-table.ts` + `src/cli/commands/<name>.ts` — one record per CLI-only command (`name`, `phase`, `thinClient`, `selfHelp`, `skipStartupHooks`, `load: () => import('<literal>')`). The records derive `CLI_ONLY`, `CLI_ONLY_SELF_HELP`, `THIN_CLIENT_REFUSED_COMMANDS` and `STARTUP_HOOK_SKIP_COMMANDS` (re-exported from `src/cli.ts`); `cliAliases`' collision check runs over the derived `CLI_ONLY`. Each module holds the body its switch case or plain branch had, moved verbatim, and receives dispatcher-owned pieces through `CliDispatchContext`. Master's membership inconsistencies are preserved (the dead second `auth` branch, the unreachable `capture --help` branch, the `connectors` and `recall` refuse hints that only `connectEngine`'s thin-client backstop reaches (the static extractor reports them as never reached), `watch` refused without a hint, `eval whoknows` shadowed by the refusal) and pinned by `test/fixtures/goldens/cli/membership-sets.json`. Contract: `test/cli-command-table.test.ts`; engine lifecycle per path: `test/cli-dispatch-lifecycle.serial.test.ts`.
+- `src/cli/command-table.ts` + `src/cli/commands/<name>.ts` — one record per CLI-only command (`name`, `phase`, `thinClient`, `selfHelp`, `skipStartupHooks`, `load: () => import('<literal>')`, and the agent-contract fields `json`, `read_only`, `startup`, `end_of_options`, `help: () => import('./help/<name>.ts')` — see `src/cli/help/` in [agent contract](agent-contract.md)). A `selfHelp` record whose handler needs an engine answers `--help` brainless through `SELF_HELP_WITHOUT_ENGINE` in `src/cli.ts` (an explicit loader, or `true` to run the record's own module with a null engine). The records derive `CLI_ONLY`, `CLI_ONLY_SELF_HELP`, `THIN_CLIENT_REFUSED_COMMANDS` and `STARTUP_HOOK_SKIP_COMMANDS` (re-exported from `src/cli.ts`); `cliAliases`' collision check runs over the derived `CLI_ONLY`. Each module holds the body its switch case or plain branch had, moved verbatim, and receives dispatcher-owned pieces through `CliDispatchContext`. Master's membership inconsistencies are preserved (the dead second `auth` branch, the unreachable `capture --help` branch, the `connectors` and `recall` refuse hints that only `connectEngine`'s thin-client backstop reaches (the static extractor reports them as never reached), `watch` refused without a hint, `eval whoknows` shadowed by the refusal) and pinned by `test/fixtures/goldens/cli/membership-sets.json`. Contract: `test/cli-command-table.test.ts`; engine lifecycle per path: `test/cli-dispatch-lifecycle.serial.test.ts`.
- `scripts/lib/cli-pipeline.ts` — flattens `handleCliOnly` (inlining `@cliPipelineStage` functions) and reads the command table by AST, for the W0 dispatch-shape extractor (`test/helpers/cli-dispatch-extract.ts`) and `scripts/generate-flag-registry.ts`.
diff --git a/scripts/serial-weights.json b/scripts/serial-weights.json
index 843e308f57..378feb2c70 100644
--- a/scripts/serial-weights.json
+++ b/scripts/serial-weights.json
@@ -44,7 +44,8 @@
"test/check-update-refresh.serial.test.ts": 0,
"test/checkpoint-harvest.serial.test.ts": 9,
"test/cli-error-render.serial.test.ts": 3,
- "test/cli-help-without-brain.serial.test.ts": 16,
+ "test/cli-help-curated.serial.test.ts": 5,
+ "test/cli-help-without-brain.serial.test.ts": 21,
"test/cli-json-guard.serial.test.ts": 17,
"test/cli-util-prompt.serial.test.ts": 3,
"test/code-callers-pin.serial.test.ts": 11,
diff --git a/scripts/test-weights.json b/scripts/test-weights.json
index 97b187f6e2..905b5f26d3 100644
--- a/scripts/test-weights.json
+++ b/scripts/test-weights.json
@@ -279,6 +279,7 @@
"test/cli-format-history-json.test.ts": 84,
"test/cli-format-search-json.test.ts": 12,
"test/cli-format-volunteer.test.ts": 38,
+ "test/cli-help-curated.test.ts": 500,
"test/cli-help-discoverability.test.ts": 9632,
"test/cli-help-eval-storage-reindex.test.ts": 2595,
"test/cli-import-no-signal-handlers.test.ts": 285,
diff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.json
index 62575a8e64..9f93a10f47 100644
--- a/scripts/ubicloud/weights.json
+++ b/scripts/ubicloud/weights.json
@@ -319,7 +319,8 @@
"serial:test/check-update-refresh.serial.test.ts": 356,
"serial:test/checkpoint-harvest.serial.test.ts": 4977,
"serial:test/cli-error-render.serial.test.ts": 3000,
- "serial:test/cli-help-without-brain.serial.test.ts": 9329,
+ "serial:test/cli-help-curated.serial.test.ts": 5000,
+ "serial:test/cli-help-without-brain.serial.test.ts": 21000,
"serial:test/cli-json-guard.serial.test.ts": 17000,
"serial:test/cli-util-prompt.serial.test.ts": 2644,
"serial:test/code-callers-pin.serial.test.ts": 2975,
@@ -896,6 +897,7 @@
"unit:test/cli-format-history-json.test.ts": 376,
"unit:test/cli-format-search-json.test.ts": 430,
"unit:test/cli-format-volunteer.test.ts": 414,
+ "unit:test/cli-help-curated.test.ts": 500,
"unit:test/cli-help-discoverability.test.ts": 12942,
"unit:test/cli-help-eval-storage-reindex.test.ts": 3843,
"unit:test/cli-import-no-signal-handlers.test.ts": 582,
diff --git a/src/cli.ts b/src/cli.ts
index 0abe605059..5cb8b9e17e 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -38,6 +38,7 @@ 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 { printCuratedHelp } from './cli/help/render.ts';
+import { curatedFlagError } from './cli/help/validate.ts';
import { cliCommandOf, exitCliError, unknownFlagError, usageError, writeCliError, writeFatalCliError } from './cli/cli-error.ts';
import { opError } from './core/ops/contract.ts';
import { opParamValue } from './cli/op-param-values.ts';
@@ -473,6 +474,8 @@ async function main() {
const known = CLI_FLAG_REGISTRY[command] ?? Object.keys(flagOp?.params ?? {}).map(k => `--${k.replace(/_/g, '-')}`);
exitCliError(await unknownFlagError(command, unknown, message, known), command, { legacy: { status: 'error', reason: 'invalid_flag', message } });
}
+ const curated = await curatedFlagError(command, subArgs);
+ if (curated) exitCliError(curated, command);
}
// DB-free durability pull (v0.42.44 D2): the harden cron calls
diff --git a/src/cli/help/validate.ts b/src/cli/help/validate.ts
new file mode 100644
index 0000000000..cc2a967096
--- /dev/null
+++ b/src/cli/help/validate.ts
@@ -0,0 +1,50 @@
+/**
+ * Agent contract v1 (D4, CLI-only half): typed flag values from the curated
+ * help spec (D3). For a command with a help module, a `number` flag whose
+ * value is missing or not numeric, or an `enum` flag whose value is not one of
+ * its `values`, is a usage error (`invalid_params`, exit 2) naming the flag,
+ * the bad value and a valid example. Accepts `--flag value` and
+ * `--flag=value`; scanning stops at a bare `--`. Unknown flags stay the
+ * acceptance registry's job (src/core/cli-flag-registry.generated.ts).
+ */
+import type { OperationError } from '../../core/ops/contract.ts';
+import type { CliHelpFlag, CliHelpSpec } from '../command-table.ts';
+import { flagValueError } from '../flag-values.ts';
+import { loadCuratedHelp } from './render.ts';
+
+/** A value for `flag` taken from the spec's examples, else a placeholder. */
+function exampleValue(spec: CliHelpSpec, flag: CliHelpFlag): string {
+ if (flag.values?.length) return flag.values[0]!;
+ for (const example of spec.examples) {
+ const tokens = example.split(/\s+/);
+ const at = tokens.indexOf(flag.name);
+ if (at >= 0 && tokens[at + 1] && !tokens[at + 1]!.startsWith('-')) return tokens[at + 1]!;
+ const inline = tokens.find(t => t.startsWith(`${flag.name}=`));
+ if (inline) return inline.slice(flag.name.length + 1);
+ }
+ return '<n>';
+}
+
+function valueOk(flag: CliHelpFlag, raw: string): boolean {
+ if (flag.type === 'enum') return flag.values?.includes(raw) === true;
+ return raw.trim() !== '' && Number.isFinite(Number(raw));
+}
+
+export async function curatedFlagError(command: string, args: readonly string[]): Promise<OperationError | null> {
+ const spec = await loadCuratedHelp(command);
+ if (!spec) return null;
+ const typed = new Map(spec.flags.filter(f => f.type === 'number' || f.type === 'enum').map(f => [f.name, f]));
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i]!;
+ if (arg === '--') break;
+ const eq = arg.indexOf('=');
+ const flag = typed.get(eq > 0 ? arg.slice(0, eq) : arg);
+ if (!flag) continue;
+ const raw = eq > 0 ? arg.slice(eq + 1) : args[i + 1];
+ if (eq < 0 && raw !== undefined && !raw.startsWith('--')) i++;
+ if (raw !== undefined && !raw.startsWith('--') && valueOk(flag, raw)) continue;
+ const accepts = flag.type === 'enum' ? `one of ${flag.values!.join('|')}` : 'a number';
+ return flagValueError(flag.name, raw, accepts, exampleValue(spec, flag));
+ }
+ return null;
+}
diff --git a/test/cli-help-curated.serial.test.ts b/test/cli-help-curated.serial.test.ts
new file mode 100644
index 0000000000..47f843f1d4
--- /dev/null
+++ b/test/cli-help-curated.serial.test.ts
@@ -0,0 +1,84 @@
+/**
+ * Agent contract v1 D3/D4 through the real CLI, on a machine with no brain.
+ *
+ * Protects: `gbrain <cmd> --help` / `-h` for the 7 ops-critical commands
+ * prints the curated spec (usage, every curated flag, examples) engine-free,
+ * instead of the generic one-line stub or a "No brain configured" error;
+ * `--help --json` prints exactly that spec as one JSON document on stdout;
+ * a bad typed value exits 2 with `invalid_params` (one envelope under
+ * `--json`) before any engine work; an unknown flag on a curated command gets
+ * a did-you-mean drawn from the curated flags.
+ * Fails when: the --help short-circuit stops reaching the curated renderer,
+ * help opens an engine, the JSON document is mixed with other stdout, or the
+ * curated validation call in main() is dropped.
+ * Why new: the unit test (test/cli-help-curated.test.ts) covers the pure
+ * renderer/validator; only a subprocess proves dispatch order and exit codes.
+ * Seam: none (empty GBRAIN_HOME, database URLs stripped, --no-env-file).
+ */
+import { describe, expect, test } from 'bun:test';
+import { mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { loadCuratedHelp } from '../src/cli/help/render.ts';
+
+const REPO = new URL('..', import.meta.url).pathname;
+const CURATED = ['doctor', 'import', 'serve', 'apply-migrations', 'autopilot', 'status', 'onboard'];
+
+async function cli(args: string[]): Promise<{ code: number; stdout: string; stderr: string }> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-curated-help-'));
+ const env: Record<string, string | undefined> = { ...process.env, GBRAIN_HOME: home, HOME: home };
+ delete env.GBRAIN_DATABASE_URL;
+ delete env.DATABASE_URL;
+ const proc = Bun.spawn(['bun', '--no-env-file', 'run', 'src/cli.ts', ...args], { cwd: REPO, env, stdout: 'pipe', stderr: 'pipe' });
+ const [stdout, stderr] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()]);
+ return { code: await proc.exited, stdout, stderr };
+}
+
+describe('curated --help without a brain (D3)', () => {
+ test('--help and -h print the curated spec engine-free for every ops-critical command', async () => {
+ const runs = await Promise.all(CURATED.flatMap(c => [['--help'], ['-h']].map(async flag => ({ c, flag: flag[0], ...(await cli([c, ...flag])) }))));
+ for (const r of runs) {
+ const spec = (await loadCuratedHelp(r.c))!;
+ expect(r.code, `${r.c} ${r.flag}: ${r.stderr}`).toBe(0);
+ expect(r.stdout + r.stderr).not.toContain('No brain configured');
+ expect(r.stdout).not.toContain('run gbrain --help for the full command list');
+ expect(r.stdout).toContain(`Usage: gbrain ${r.c}`);
+ for (const f of spec.flags) expect(r.stdout, `${r.c} help lists ${f.name}`).toContain(f.name);
+ expect(r.stdout).toContain(spec.examples[0]!);
+ }
+ }, 90_000);
+
+ test('--help --json prints the spec as one JSON document', async () => {
+ const runs = await Promise.all(['doctor', 'serve'].map(async c => ({ c, ...(await cli([c, '--help', '--json'])) })));
+ for (const r of runs) {
+ expect(r.code).toBe(0);
+ const doc = JSON.parse(r.stdout);
+ expect(doc).toEqual({ command: r.c, ...(await loadCuratedHelp(r.c))!, contract_version: 1 });
+ }
+ }, 60_000);
+});
+
+describe('typed flag values from the curated spec (D4)', () => {
+ test('a non-numeric number flag exits 2 with invalid_params before any engine work', async () => {
+ const r = await cli(['doctor', '--remediate', '--max-usd', 'abc']);
+ expect(r.code).toBe(2);
+ expect(r.stderr).toContain("Error [invalid_params]: --max-usd must be a number; got 'abc'.");
+ expect(r.stderr).toContain('Pass a number, e.g. --max-usd 5.');
+ expect(r.stderr).not.toContain('No brain configured');
+ }, 30_000);
+
+ test('under --json the bad value is one envelope on stdout', async () => {
+ const r = await cli(['status', '--section', 'bogus', '--json']);
+ expect(r.code).toBe(2);
+ const env = JSON.parse(r.stdout);
+ expect(env.code).toBe('invalid_params');
+ expect(env.message).toContain("--section must be one of sync|cycle|locks|workers|queue|autopilot; got 'bogus'");
+ expect(env.suggestion).toContain('--section sync');
+ }, 30_000);
+
+ test('an unknown flag on a curated command suggests the curated flag', async () => {
+ const r = await cli(['doctor', '--remediat']);
+ expect(r.code).toBe(2);
+ expect(r.stderr).toContain('did you mean --remediate?');
+ }, 30_000);
+});
diff --git a/test/cli-help-curated.test.ts b/test/cli-help-curated.test.ts
new file mode 100644
index 0000000000..4091b41f51
--- /dev/null
+++ b/test/cli-help-curated.test.ts
@@ -0,0 +1,103 @@
+/**
+ * Agent contract v1 D3/D4 (CLI-only half): curated help specs, their renderer
+ * and the typed flag-value validator built from them.
+ *
+ * Protects: the 7 ops-critical commands carry a curated spec whose flags the
+ * acceptance registry accepts (so help never advertises a flag the CLI then
+ * rejects), `--yes` is listed wherever the handler parses it, the rendered
+ * help shows type/values/consent, `curatedFlagError` turns a NaN number or an
+ * out-of-set enum into `invalid_params` naming the flag, the value and an
+ * example (both `--flag value` and `--flag=value`, stopping at a bare `--`),
+ * and the unknown-flag did-you-mean draws on the curated flags.
+ * Fails when: a curated flag drifts from what the handler parses, a typed
+ * flag stops being validated, or a valid / string-typed value is refused
+ * (onboard's `--max-usd off`).
+ * Why new: D3/D4 add the specs and the validator; the subprocess journey is
+ * test/cli-help-curated.serial.test.ts. Seam: none (pure functions + lazy modules).
+ */
+import { describe, expect, test } from 'bun:test';
+import { CLI_COMMANDS } from '../src/cli/command-table.ts';
+import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';
+import { loadCuratedHelp, renderCuratedHelp } from '../src/cli/help/render.ts';
+import { curatedFlagError } from '../src/cli/help/validate.ts';
+import { unknownFlagError } from '../src/cli/cli-error.ts';
+
+const OPS_CRITICAL = ['apply-migrations', 'autopilot', 'doctor', 'import', 'onboard', 'serve', 'status'];
+/** Handlers that parse `--yes` (doctor --remediate, apply-migrations parseArgs, onboard --auto). */
+const PARSES_YES = ['apply-migrations', 'doctor', 'onboard'];
+
+describe('curated help specs (D3)', () => {
+ test('exactly the ops-critical commands carry a curated help module', () => {
+ expect(CLI_COMMANDS.filter(r => r.help).map(r => r.name).sort()).toEqual(OPS_CRITICAL);
+ });
+
+ for (const command of OPS_CRITICAL) {
+ test(`${command}: every curated flag is accepted by the generated registry and well-typed`, async () => {
+ const spec = (await loadCuratedHelp(command))!;
+ const accepted = new Set(CLI_FLAG_REGISTRY[command] ?? []);
+ expect(spec.usage).toContain(`gbrain ${command}`);
+ expect(spec.examples.length).toBeGreaterThanOrEqual(2);
+ expect(spec.examples.length).toBeLessThanOrEqual(4);
+ for (const e of spec.examples) expect(e.startsWith(`gbrain ${command}`)).toBe(true);
+ expect(new Set(spec.flags.map(f => f.name)).size).toBe(spec.flags.length);
+ for (const f of spec.flags) {
+ expect(accepted.has(f.name), `${command} ${f.name} is not in the acceptance registry`).toBe(true);
+ expect(f.desc.length).toBeGreaterThan(0);
+ expect(f.type === 'enum' ? (f.values?.length ?? 0) > 0 : f.values === undefined).toBe(true);
+ }
+ expect(spec.flags.some(f => f.name === '--yes')).toBe(PARSES_YES.includes(command));
+ });
+ }
+
+ test('the renderer prints usage, the typed flag table, enum values, consent effects and examples', async () => {
+ const spec = (await loadCuratedHelp('doctor'))!;
+ const text = renderCuratedHelp('doctor', spec);
+ expect(text).toContain('Usage: gbrain doctor');
+ expect(text).toMatch(/--max-usd <n>\s+number\s+.*\[consent: paid\]/);
+ expect(text).toMatch(/--include-repairs\s+boolean\s+.*\[consent: destructive\]/);
+ expect(text).toMatch(/--scope <choice>\s+enum\s+.*One of: all\|brain\./);
+ expect(text).toContain('Examples:\n gbrain doctor --json');
+ expect(text).toContain('gbrain doctor --help --json');
+ });
+});
+
+describe('curatedFlagError (D4, CLI-only commands)', () => {
+ test('a non-numeric number flag is invalid_params naming the flag, the value and an example', async () => {
+ const e = (await curatedFlagError('doctor', ['--remediate', '--max-usd', 'abc']))!;
+ expect(e.code).toBe('invalid_params');
+ expect(e.message).toBe("--max-usd must be a number; got 'abc'.");
+ expect(e.suggestion).toBe('Pass a number, e.g. --max-usd 5.');
+ });
+
+ test('--flag=value and a missing value are checked too', async () => {
+ expect((await curatedFlagError('doctor', ['--target-score=high']))?.message).toBe("--target-score must be a number; got 'high'.");
+ expect((await curatedFlagError('import', ['./notes', '--workers']))?.message).toBe('--workers requires a value: a number.');
+ expect((await curatedFlagError('import', ['./notes', '--workers', '--json']))?.message).toBe('--workers requires a value: a number.');
+ });
+
+ test('an enum value outside its set lists the valid choices', async () => {
+ const e = (await curatedFlagError('status', ['--section', 'bogus']))!;
+ expect(e.code).toBe('invalid_params');
+ expect(e.message).toBe("--section must be one of sync|cycle|locks|workers|queue|autopilot; got 'bogus'.");
+ expect(e.suggestion).toBe('Pass one of sync|cycle|locks|workers|queue|autopilot, e.g. --section sync.');
+ expect((await curatedFlagError('doctor', ['--scope=nope']))?.message).toContain('one of all|brain');
+ });
+
+ test('valid values, string flags, positionals after a bare -- and uncurated commands pass', async () => {
+ expect(await curatedFlagError('doctor', ['--remediate', '--yes', '--max-usd', '2.5', '--target-score=80', '--scope=brain'])).toBeNull();
+ expect(await curatedFlagError('serve', ['--surface', 'starter', '--access', 'read-only', '--port', '3131'])).toBeNull();
+ expect(await curatedFlagError('onboard', ['--auto', '--max-usd', 'off'])).toBeNull();
+ expect(await curatedFlagError('autopilot', ['--repo', './brain', '--', '--interval', 'soon'])).toBeNull();
+ expect(await curatedFlagError('doctor', ['--', '--max-usd', 'abc'])).toBeNull();
+ expect(await curatedFlagError('sync', ['--interval', 'abc'])).toBeNull();
+ });
+});
+
+describe('unknown-flag did-you-mean from curated flags (D3)', () => {
+ test('a typo on a curated command suggests the curated flag', async () => {
+ const e = await unknownFlagError('doctor', '--remediat', "unknown flag --remediat for 'gbrain doctor'");
+ expect(e.code).toBe('unknown_flag');
+ expect(e.message).toContain('did you mean --remediate?');
+ expect(e.suggestion).toContain('Did you mean --remediate?');
+ });
+});