Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(cli): core and loops are routers, so their subcommand help answers before any engine access
garrytanfd7def2f4824
diff --git a/docs/architecture/key-files/entrypoints-and-docs.md b/docs/architecture/key-files/entrypoints-and-docs.mdindex b4e7828e9b..10ea46bfef 100644--- a/docs/architecture/key-files/entrypoints-and-docs.md+++ b/docs/architecture/key-files/entrypoints-and-docs.md@@ -122,7 +122,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGELSize ceiling (`src/cli/main.ts`): `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/main.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/subcommands.ts` + `src/cli/router-help.ts` + `src/cli/strict-args.ts` — help never acts (#6114). `subcommands.ts` holds each router command's inventory (`ROUTERS`: pages, cache, integrity, hook, search, edge-proposals, schema, config; each router re-exports its list as `SUBCOMMANDS` and types its dispatch over it, so an unlisted subcommand fails typecheck) and the help grammar: `--help`/`-h` anywhere before `--` (a flag-value slot included) and a bare `help` only as the first token after a router command or one of its subcommands (`search help` stays a query). `cli.ts` decides `cliHelpRequested` once, before the update marker, backup nag and key warnings; on help it calls `printRouterHelp`, which loads only the router's `printUsage`, before any subcommand, thin-client route or engine. `strict-args.ts` is the per-subcommand table for destructive subcommands (pages purge-deleted, cache clear/prune, schema use/downgrade/init/remove-*, integrity auto/reset-progress, search modes --reset and its `--mode <mode>` preview, W4.13: `--source <mode>` is the deprecated alias, and the handler refuses a missing value or conflicting `--mode`/`--source` with exit 2 instead of resetting): an argument the handler would ignore refuses with `invalid_params` (exit 2) after help and before dispatch, with a read-only fix that itself parses under the table (`ask_user` for integrity reset-progress). `STRICT_SELF_HELP_SUBCOMMANDS` is the same table for a self-help command that prints its own per-subcommand help instead of a router inventory: `skillpack reference` (#5491) accepts `<name>` or `--all`, `--workspace`, `--since`, `--apply-clean-hunks`, `--dry-run` and `--json`, so a `--dry-run=true`, a typo or an unknown flag refuses before the apply instead of running it with the flag ignored (the `--harness` lane keeps its own parser; `src/commands/skillpack/reference.ts` re-checks on entry so an in-process caller gets the same refusal). The flag-registry generator skips `strict-args.ts` (its literals belong to the commands it lists). Pinned by `test/cli-help-grammar.test.ts` and the four-part subprocess gate `test/cli-help-no-side-effects*.serial.test.ts` (harness `test/helpers/cli-help-gate.ts`, child probe `test/helpers/cli-side-effect-probe.ts`): every self-help command's `--help`/`-h` and every router subcommand's `--help`/`-h`/`help` on a copy of a seeded PGLite brain, asserting exit 0 with usage, unchanged table rows and HOME/cwd files, and no fetch or spawn. `quarantine` (list, clear, scan) is a router since #6259.+- `src/cli/subcommands.ts` + `src/cli/router-help.ts` + `src/cli/strict-args.ts` — help never acts (#6114). `subcommands.ts` holds each router command's inventory (`ROUTERS`: pages, cache, integrity, hook, search, edge-proposals, schema, config, quarantine, core, loops; each router re-exports its list as `SUBCOMMANDS` and types its dispatch over it, so an unlisted subcommand fails typecheck) and the help grammar: `--help`/`-h` anywhere before `--` (a flag-value slot included) and a bare `help` only as the first token after a router command or one of its subcommands (`search help` stays a query). `cli.ts` decides `cliHelpRequested` once, before the update marker, backup nag and key warnings; on help it calls `printRouterHelp`, which loads only the router's `printUsage`, before any subcommand, thin-client route or engine. `strict-args.ts` is the per-subcommand table for destructive subcommands (pages purge-deleted, cache clear/prune, schema use/downgrade/init/remove-*, integrity auto/reset-progress, search modes --reset and its `--mode <mode>` preview, W4.13: `--source <mode>` is the deprecated alias, and the handler refuses a missing value or conflicting `--mode`/`--source` with exit 2 instead of resetting): an argument the handler would ignore refuses with `invalid_params` (exit 2) after help and before dispatch, with a read-only fix that itself parses under the table (`ask_user` for integrity reset-progress). `STRICT_SELF_HELP_SUBCOMMANDS` is the same table for a self-help command that prints its own per-subcommand help instead of a router inventory: `skillpack reference` (#5491) accepts `<name>` or `--all`, `--workspace`, `--since`, `--apply-clean-hunks`, `--dry-run` and `--json`, so a `--dry-run=true`, a typo or an unknown flag refuses before the apply instead of running it with the flag ignored (the `--harness` lane keeps its own parser; `src/commands/skillpack/reference.ts` re-checks on entry so an in-process caller gets the same refusal). The flag-registry generator skips `strict-args.ts` (its literals belong to the commands it lists). Pinned by `test/cli-help-grammar.test.ts` and the four-part subprocess gate `test/cli-help-no-side-effects*.serial.test.ts` (harness `test/helpers/cli-help-gate.ts`, child probe `test/helpers/cli-side-effect-probe.ts`): every self-help command's `--help`/`-h` and every router subcommand's `--help`/`-h`/`help` on a copy of a seeded PGLite brain, asserting exit 0 with usage, unchanged table rows and HOME/cwd files, and no fetch or spawn. `quarantine` (list, clear, scan) is a router since #6259. `core` and `loops` are routers since #6521: as SELF_HELP_WITHOUT_ENGINE entries their handlers answered help only as the first token, so `core list --help` ran `list` against the null engine (`internal_error: null is not an object`) and `loops show --help` exited 2; `transcripts` keeps its per-subcommand help (`recover --help` prints a dedicated usage) and its handler answers the flag for `status` itself. `test/cli-help-without-brain.test.ts` runs an explicit brainless table of these invocations next to the gate's router walk.- `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`. `json` / `jsonSubcommands` declare the D2 `--json` contract (record-wide / per subcommand).- `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/src/cli/router-help.ts b/src/cli/router-help.tsindex 12348382c2..56aee3a762 100644--- a/src/cli/router-help.ts+++ b/src/cli/router-help.ts@@ -21,6 +21,8 @@ export const ROUTER_MODULES: Readonly<Record<string, () => Promise<RouterModule>schema: () => import('../commands/schema.ts'),config: () => import('../commands/config.ts'),quarantine: () => import('../commands/quarantine.ts'),+ core: () => import('../commands/core.ts'),+ loops: () => import('../commands/loops.ts'),};/**diff --git a/src/cli/subcommands.ts b/src/cli/subcommands.tsindex bf440905f5..3fce5f15da 100644--- a/src/cli/subcommands.ts+++ b/src/cli/subcommands.ts@@ -25,6 +25,8 @@ export const SEARCH_SUBCOMMANDS = ['modes', 'stats', 'tune', 'diagnose'] as consexport const EDGE_PROPOSALS_SUBCOMMANDS = ['list', 'show', 'accept', 'reject', 'undo', 'date', 'retry'] as const;export const CONFIG_SUBCOMMANDS = ['show', 'get', 'set', 'unset'] as const;export const QUARANTINE_SUBCOMMANDS = ['list', 'clear', 'scan', 'release', 'drop'] as const;+export const CORE_SUBCOMMANDS = ['list', 'show', 'status', 'add', 'remove', 'diff', 'ack', 'init', 'suggest'] as const;+export const LOOPS_SUBCOMMANDS = ['list', 'show', 'done', 'drop', 'mute', 'unmute'] as const;export const SCHEMA_SUBCOMMANDS = ['active', 'list', 'show', 'validate', 'use', 'detect', 'suggest', 'review-candidates', 'init', 'fork', 'edit','diff', 'graph', 'lint', 'explain', 'review-orphans', 'downgrade', 'usage', 'stats', 'cardinality-preview',@@ -52,6 +54,10 @@ export const ROUTERS: Readonly<Record<string, RouterInventory>> = {schema: { subcommands: SCHEMA_SUBCOMMANDS, bareHelpFirst: true },config: { subcommands: CONFIG_SUBCOMMANDS, bareHelpFirst: true },quarantine: { subcommands: QUARANTINE_SUBCOMMANDS, bareHelpFirst: true },+ // #6521: these two were SELF_HELP_WITHOUT_ENGINE entries whose handlers answered help only as the first token,+ // so `core list --help` ran `list` against a null engine and `loops show --help` exited 2 "needs a loop id".+ core: { subcommands: CORE_SUBCOMMANDS, bareHelpFirst: true },+ loops: { subcommands: LOOPS_SUBCOMMANDS, bareHelpFirst: true },};/** `--help` / `-h` before any `--` terminator. */diff --git a/src/commands/core.ts b/src/commands/core.tsindex d647102629..da1c225034 100644--- a/src/commands/core.ts+++ b/src/commands/core.ts@@ -22,6 +22,9 @@ import {} from '../core/core-memory.ts';import { serializePageToMarkdown } from '../core/markdown.ts';import { setCliExitVerdict } from '../core/cli-force-exit.ts';+import { CORE_SUBCOMMANDS, ROUTERS, subcommandHelpRequested } from '../cli/subcommands.ts';++export { CORE_SUBCOMMANDS as SUBCOMMANDS } from '../cli/subcommands.ts';/** Core is opt-in: marking a page does nothing for sessions until the owner turns delivery on. */const CORE_OFF_HINT = 'Core memory is off (the default), so sessions do not load it yet. If the user wants it always loaded: gbrain config set memory.core.enabled true';@@ -38,6 +41,10 @@ const USAGE = `Usage: gbrain core <list|show|status|add|remove|diff|ack|init|sugsuggest [--source <id>] [--apply] [--json]Docs: ${CORE_DOCS}`;+export function printUsage(): void {+ console.log(USAGE);+}+function flag(args: string[], name: string): string | undefined {const i = args.indexOf(name);return i !== -1 ? args[i + 1] : undefined;@@ -125,7 +132,9 @@ function lineDiff(before: string, after: string): string {}export async function runCore(engine: BrainEngine, args: string[]): Promise<void> {- const sub = args[0];+ // cli.ts answers help before dispatch (#6114 router); this covers direct callers.+ if (subcommandHelpRequested(args, ROUTERS.core)) { printUsage(); return; }+ const sub = args[0] as (typeof CORE_SUBCOMMANDS)[number] | undefined;const json = args.includes('--json');const sourceId = flag(args, '--source') ?? 'default';const slug = positional(args);@@ -253,8 +262,8 @@ export async function runCore(engine: BrainEngine, args: string[]): Promise<voidreturn;}default:- console.log(USAGE);- if (sub && sub !== '--help' && sub !== '-h' && sub !== 'help') setCliExitVerdict(1);+ printUsage();+ if (sub) setCliExitVerdict(1);}}diff --git a/src/commands/loops.ts b/src/commands/loops.tsindex d612ae435f..5a6a317149 100644--- a/src/commands/loops.ts+++ b/src/commands/loops.ts@@ -27,6 +27,25 @@ import { setCliExitVerdict } from '../core/cli-force-exit.ts';import { ALL_SOURCES } from '../core/source-id.ts';import { exitCliError, usageError, writeCliError } from '../cli/cli-error.ts';import { opError } from '../core/ops/contract.ts';+import { LOOPS_SUBCOMMANDS, ROUTERS, subcommandHelpRequested } from '../cli/subcommands.ts';++export { LOOPS_SUBCOMMANDS as SUBCOMMANDS } from '../cli/subcommands.ts';++export function printUsage(): void {+ process.stdout.write(+ [+ 'gbrain loops — inspect and manage open loops',+ ' list [--status open|done|dropped|stale] [--type <loop_type>] [--source <id>] [--json]',+ ' show <id> [--json]',+ ' done <id> [--note <text>] mark handled',+ ' drop <id> [--note <text>] not going to do it',+ ' mute sender <email> | thread <thread-id> [--source <id>]',+ ' unmute sender <email> | thread <thread-id> [--source <id>] undo a mute',+ '',+ 'The ranked digest lives at: gbrain waiting',+ ].join('\n') + '\n',+ );+}function sourceFlag(args: string[]): string | undefined {const i = args.indexOf('--source');@@ -189,23 +208,13 @@ async function showLoop(}export async function runLoops(engine: BrainEngine, args: string[]): Promise<void> {- const [sub, ...rest] = args;+ const [first, ...rest] = args;+ const sub = first as (typeof LOOPS_SUBCOMMANDS)[number] | undefined;const json = rest.includes('--json') || args.includes('--json');- if (!sub || sub === '--help' || sub === '-h' || sub === 'help') {- process.stdout.write(- [- 'gbrain loops — inspect and manage open loops',- ' list [--status open|done|dropped|stale] [--type <loop_type>] [--source <id>] [--json]',- ' show <id> [--json]',- ' done <id> [--note <text>] mark handled',- ' drop <id> [--note <text>] not going to do it',- ' mute sender <email> | thread <thread-id> [--source <id>]',- ' unmute sender <email> | thread <thread-id> [--source <id>] undo a mute',- '',- 'The ranked digest lives at: gbrain waiting',- ].join('\n') + '\n',- );+ // cli.ts answers help before dispatch (#6114 router, #6521: `loops show --help` used to exit 2 "needs a loop id").+ if (!sub || subcommandHelpRequested(args, ROUTERS.loops)) {+ printUsage();return;}diff --git a/src/commands/transcripts.ts b/src/commands/transcripts.tsindex 5d94284e14..6b8f9cdb4b 100644--- a/src/commands/transcripts.ts+++ b/src/commands/transcripts.ts@@ -17,6 +17,7 @@import { homedir } from 'node:os';import type { BrainEngine } from '../core/engine.ts';+import { helpFlagRequested } from '../cli/subcommands.ts';import type { CliDispatchContext } from '../cli/command-table.ts';import type { RecentTranscript } from '../core/transcripts.ts';import { setCliExitVerdict } from '../core/cli-force-exit.ts';@@ -605,6 +606,8 @@ export async function runTranscripts(engine: BrainEngine, args: string[], dispatreturn;}if (sub === 'status') {+ // #6521: `status` has no parser of its own, so its help flag reached runStatus and the (null) engine.+ if (helpFlagRequested(args.slice(1))) { console.log(HELP); return; }await runStatus(engine, args.slice(1));return;}diff --git a/test/cli-help-without-brain.test.ts b/test/cli-help-without-brain.test.tsindex f5918d1d75..c323bf7e4f 100644--- a/test/cli-help-without-brain.test.ts+++ b/test/cli-help-without-brain.test.ts@@ -67,6 +67,10 @@ const HELP_WITHOUT_BRAIN = [const STILL_NEEDS_A_BRAIN: string[] = [];async function runHelp(command: string): Promise<{ code: number; out: string }> {+ return runCli([command, '--help']);+}++async function runCli(argv: string[]): Promise<{ code: number; out: string }> {const home = mkdtempSync(join(tmpdir(), 'gbrain-nobrain-'));// An empty GBRAIN_HOME is not enough: loadConfig also honours// GBRAIN_DATABASE_URL and DATABASE_URL (config.ts:550-551), so a developer@@ -78,7 +82,7 @@ async function runHelp(command: string): Promise<{ code: number; out: string }>// --no-env-file: bun auto-loads .env from cwd, and GBRAIN_DATABASE_URL is// honored unconditionally, so a developer's local .env would put back// exactly what the deletes above removed.- const proc = Bun.spawn(['bun', '--no-env-file', 'run', 'src/cli.ts', command, '--help'], {+ const proc = Bun.spawn(['bun', '--no-env-file', 'run', 'src/cli.ts', ...argv], {cwd: REPO,env,stdout: 'pipe',@@ -147,6 +151,41 @@ describe('--help without a configured brain', () => {}, 30_000);}+ // #6521: a subcommand's help must answer brainless too. SELF_HELP_WITHOUT_ENGINE dispatches the handler with a+ // null engine and trusts it to answer help first; `core list --help` ran `list` against null ("null is not an+ // object (evaluating 'exec.executeRaw')", exit 1) and `loops show --help` exited 2 ("needs a loop id"). `core`+ // and `loops` are routers now (cli.ts prints their usage before dispatch, src/cli/router-help.ts); `transcripts`+ // keeps per-subcommand help, so its handler answers the flag for `status`/`audit-secrets`. The explicit table+ // is the fail-first; the ROUTERS walk in test/helpers/cli-help-gate.ts is the ratchet afterwards.+ const SUBCOMMAND_HELP_WITHOUT_BRAIN: Array<{ argv: string[]; usage: string }> = [+ { argv: ['core', 'list', '--help'], usage: 'Usage: gbrain core' },+ { argv: ['core', 'status', '--help'], usage: 'Usage: gbrain core' },+ { argv: ['core', 'init', '--help'], usage: 'Usage: gbrain core' },+ { argv: ['core', 'suggest', '-h'], usage: 'Usage: gbrain core' },+ { argv: ['core', 'add', 'x', '--help'], usage: 'Usage: gbrain core' },+ { argv: ['core', 'add', 'help'], usage: 'Usage: gbrain core' },+ { argv: ['loops', 'list', '--help'], usage: 'gbrain loops —' },+ { argv: ['loops', 'show', '--help'], usage: 'gbrain loops —' },+ { argv: ['loops', 'done', '--help'], usage: 'gbrain loops —' },+ { argv: ['loops', 'drop', '-h'], usage: 'gbrain loops —' },+ { argv: ['loops', 'mute', '--help'], usage: 'gbrain loops —' },+ { argv: ['loops', 'unmute', 'help'], usage: 'gbrain loops —' },+ { argv: ['transcripts', 'status', '--help'], usage: 'gbrain transcripts' },+ { argv: ['transcripts', 'audit-secrets', '--help'], usage: 'gbrain transcripts' },+ ];+ test('subcommand help answers brainless (#6521: core, loops, transcripts status)', async () => {+ const results = await Promise.all(SUBCOMMAND_HELP_WITHOUT_BRAIN.map(async c => ({ ...c, ...(await runCli(c.argv)) })));+ for (const r of results) {+ const label = r.argv.join(' ');+ expect(r.out, label).not.toContain('No brain configured');+ expect(r.out, label).not.toContain('internal_error');+ expect(r.out, label).not.toContain('null is not an object');+ expect(r.out, label).not.toContain('needs a loop id');+ expect(r.out, label).toContain(r.usage);+ expect(r.code, label).toBe(0);+ }+ }, 120_000);+test('the known-unfixed set is exactly what it claims', async () => {// Concurrently: seven sequential CLI spawns is most of this file's wall// clock, and each one is independent (its own temp GBRAIN_HOME).diff --git a/test/helpers/cli-help-gate.ts b/test/helpers/cli-help-gate.tsindex a43007dd6b..3261fc2a12 100644--- a/test/helpers/cli-help-gate.ts+++ b/test/helpers/cli-help-gate.ts@@ -45,7 +45,7 @@ export interface GateCase {const ROUTER_USAGE: Record<string, string> = {pages: 'gbrain pages —', cache: 'gbrain cache —', integrity: 'Usage: gbrain integrity', hook: 'Usage: gbrain hook',search: 'Usage: gbrain search <modes', 'edge-proposals': 'Usage: gbrain edge-proposals', schema: 'gbrain schema —',- config: 'Usage: gbrain config',+ config: 'Usage: gbrain config', core: 'Usage: gbrain core', loops: 'gbrain loops —',};/** Every case, in a stable order. */