Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(search): search modes previews a reset with --mode; --source stays a deprecated alias (W4.13)
time-attackb340accfd1dc
diff --git a/docs/architecture/key-files/entrypoints-and-docs.md b/docs/architecture/key-files/entrypoints-and-docs.mdindex 7520b7c6a9..aa20b194c1 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 CHANGELSize 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/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): 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). 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.+- `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). 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.- `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/strict-args.ts b/src/cli/strict-args.tsindex f31c28b4b9..9f4b325b27 100644--- a/src/cli/strict-args.ts+++ b/src/cli/strict-args.ts@@ -74,10 +74,10 @@ export const STRICT_SUBCOMMANDS: Readonly<Record<string, StrictSpec>> = {},'search modes': {flags: ['--reset', '--json'],- values: { '--source': null },+ values: { '--mode': null, '--source': null },separateValues: true,maxPositionals: 0,- when: args => args.includes('--reset'),+ when: args => args.includes('--reset') || args.includes('--mode') || args.includes('--source'),fix: { argv: ['search', 'modes'], why: 'Shows every search.* override and its value; changes nothing.' },},};diff --git a/src/commands/search.ts b/src/commands/search.tsindex 5780473a21..e137529d1d 100644--- a/src/commands/search.ts+++ b/src/commands/search.ts@@ -9,7 +9,7 @@* active mode, the source of every resolved knob (mode default vs* config override vs per-call), and a one-liner per knob.*- * gbrain search modes --reset [--source <mode>]+ * gbrain search modes --reset [--mode <mode>] (--source <mode>: deprecated alias)* Clears every search.* override key (per CDX-8). --source acts as* a dry-run that lists what would change without writing.*@@ -98,18 +98,54 @@ function formatModesText(report: SearchModesReport): string {return lines.join('\n');}+/**+ * W4.13: the dry-run mode of `search modes --reset --mode <mode>`. `--source`+ * is the deprecated spelling (it means a brain source everywhere else) and+ * prints a notice. A flag without a value, or `--mode` and `--source` naming+ * different modes, refuses with exit 2 before anything is read or deleted.+ */+async function modesDryRunMode(args: string[]): Promise<{ mode: string | null } | { refused: true }> {+ const read = (flag: string): string | null | undefined => {+ const at = args.indexOf(flag);+ if (at === -1) return null;+ const value = args[at + 1];+ return value === undefined || value.startsWith('--') ? undefined : value;+ };+ const refuse = async (message: string, why: string): Promise<{ refused: true }> => {+ const { usageError, writeCliError } = await import('../cli/cli-error.ts');+ const { setCliExitVerdict } = await import('../core/cli-force-exit.ts');+ setCliExitVerdict(writeCliError(usageError(message,+ `Preview with gbrain search modes --reset --mode <${SEARCH_MODES.join('|')}>, or clear the overrides with gbrain search modes --reset.`,+ { why, fix: { argv: ['gbrain', 'search', 'modes'], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'Shows every search.* override and its value; changes nothing.' } }), 'search', { json: args.includes('--json') }));+ return { refused: true };+ };+ const mode = read('--mode');+ const source = read('--source');+ if (mode === undefined || source === undefined) {+ return refuse(`${mode === undefined ? '--mode' : '--source'} needs a search mode value; nothing was changed.`,+ 'Without its value the command would reset every override instead of previewing.');+ }+ if (mode !== null && source !== null && mode !== source) {+ return refuse(`--mode ${mode} and --source ${source} name different modes; nothing was changed.`, 'Only one preview mode can run.');+ }+ if (source !== null) process.stderr.write('[search modes] --source <mode> is deprecated here (--source names a brain source everywhere else); use --mode <mode>.\n');+ return { mode: mode ?? source };+}+async function runModesSubcommand(engine: BrainEngine, args: string[]): Promise<void> {const json = args.includes('--json');const reset = args.includes('--reset');- const sourceIdx = args.indexOf('--source');- const dryRunSource = sourceIdx !== -1 ? args[sourceIdx + 1] : null;+ const parsed = await modesDryRunMode(args);+ if ('refused' in parsed) return;+ const dryRunSource = parsed.mode;// --reset path: clear every search.* OVERRIDE key (not search.mode itself).- // --source <mode> is a dry-run that prints what would change.+ // --mode <mode> (alias --source) is a dry-run that prints what would change.if (reset || dryRunSource) {const dryRun = Boolean(dryRunSource);if (dryRunSource && !isSearchMode(dryRunSource)) {- console.error(`Invalid --source value: ${dryRunSource}. Expected one of: ${SEARCH_MODES.join(', ')}`);+ console.error(`Invalid --mode value: ${dryRunSource}. Expected one of: ${SEARCH_MODES.join(', ')}`);process.exit(1);}const overrides = await engine.listConfigKeys('search.');@@ -119,7 +155,7 @@ async function runModesSubcommand(engine: BrainEngine, args: string[]): Promise<return;}if (dryRun) {- console.log(`--source ${dryRunSource} (dry run). Would unset ${toRemove.length} key(s):`);+ console.log(`--mode ${dryRunSource} (dry run). Would unset ${toRemove.length} key(s):`);for (const k of toRemove) console.log(` - ${k}`);console.log(`No changes written. Re-run with --reset to apply.`);return;@@ -359,7 +395,8 @@ const USAGE = `Usage: gbrain search <modes|stats|tune|diagnose> [flags]Subcommands:modes [--json] Show active mode, bundles, and per-knob source.modes --reset Clear all search.* overrides (mode bundle wins).- modes --source <mode> Dry-run: list what --reset would change.+ modes --reset --mode <mode> Dry-run: list what --reset would change+ (--source <mode> is a deprecated alias).stats [--days N] [--json] Cache hit rate, intent mix, budget pressure.tune [--apply] [--json] Print recommendations; --apply mutates config.diagnose "<query>" --target <slug> [--json] [--source <id>]diff --git a/src/commands/thin-client-routing.ts b/src/commands/thin-client-routing.tsindex bdcdc33888..c12329be48 100644--- a/src/commands/thin-client-routing.ts+++ b/src/commands/thin-client-routing.ts@@ -120,7 +120,7 @@ export async function routeThinClientCommand(}if (command === 'search') {- if (sub === 'modes' && !rest.includes('--reset') && !rest.includes('--source')) {+ if (sub === 'modes' && !rest.includes('--reset') && !rest.includes('--source') && !rest.includes('--mode')) {printJson(await call(cfg, 'search_modes', {}));return true;}@@ -132,7 +132,7 @@ export async function routeThinClientCommand(printJson(await call(cfg, 'search_tune', {}));return true;}- return false; // modes --reset / modes --source (the reset dry-run) / tune --apply / diagnose — host-side config or live probe+ return false; // modes --reset / modes --mode|--source (the reset dry-run) / tune --apply / diagnose — host-side config or live probe}if (command === 'jobs' && sub === 'stats') {diff --git a/test/search-modes-mode-w413.test.ts b/test/search-modes-mode-w413.test.tsnew file mode 100644index 0000000000..4ce554aa74--- /dev/null+++ b/test/search-modes-mode-w413.test.ts@@ -0,0 +1,77 @@+/**+ * Wave 12 W4.13: `search modes --reset --mode <mode>` previews the reset;+ * `--source <mode>` (which names a brain source everywhere else) still works+ * with a deprecation notice. A missing value or conflicting `--mode` and+ * `--source` refuse (exit 2) and never fall through to deleting the overrides.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runSearch } from '../src/commands/search.ts';+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';+import { strictArgsProblem, STRICT_SUBCOMMANDS } from '../src/cli/strict-args.ts';++let engine: PGLiteEngine;+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); });+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => {+ _resetCliExitVerdictForTests();+ await engine.setConfig('search.cache_enabled', 'false');+});++async function run(...args: string[]): Promise<{ stdout: string; stderr: string }> {+ const out = process.stdout.write.bind(process.stdout);+ const err = process.stderr.write.bind(process.stderr);+ const log = console.log;+ let stdout = '';+ let stderr = '';+ (process.stdout.write as unknown as (c: unknown) => boolean) = (c: unknown) => { stdout += String(c); return true; };+ (process.stderr.write as unknown as (c: unknown) => boolean) = (c: unknown) => { stderr += String(c); return true; };+ console.log = (...a: unknown[]) => { stdout += a.join(' ') + '\n'; };+ try { await runSearch(engine, ['modes', ...args]); } finally { process.stdout.write = out; process.stderr.write = err; console.log = log; }+ return { stdout, stderr };+}+const overrideKept = async () => (await engine.getConfig('search.cache_enabled')) === 'false';++describe('W4.13: search modes --reset --mode', () => {+ test('--mode previews and changes nothing', async () => {+ const r = await run('--reset', '--mode', 'tokenmax');+ expect(r.stdout).toContain('--mode tokenmax (dry run)');+ expect(currentExitCode()).toBe(0);+ expect(await overrideKept()).toBe(true);+ });++ test('--source still previews, with a deprecation notice', async () => {+ const r = await run('--reset', '--source', 'tokenmax');+ expect(r.stdout).toContain('(dry run)');+ expect(r.stderr).toContain('use --mode <mode>');+ expect(await overrideKept()).toBe(true);+ });++ test('a missing value refuses with exit 2 and never deletes the overrides', async () => {+ await run('--reset', '--mode');+ expect(currentExitCode()).toBe(2);+ expect(await overrideKept()).toBe(true);+ _resetCliExitVerdictForTests();+ await run('--reset', '--source', '--json');+ expect(currentExitCode()).toBe(2);+ expect(await overrideKept()).toBe(true);+ });++ test('conflicting --mode and --source refuse with exit 2', async () => {+ await run('--reset', '--mode', 'tokenmax', '--source', 'balanced');+ expect(currentExitCode()).toBe(2);+ expect(await overrideKept()).toBe(true);+ });++ test('plain --reset still clears the overrides', async () => {+ await run('--reset');+ expect(await overrideKept()).toBe(false);+ });++ test('the strict-args table accepts --mode and refuses its = form', () => {+ const spec = STRICT_SUBCOMMANDS['search modes']!;+ expect(strictArgsProblem(spec, ['--reset', '--mode', 'tokenmax'])).toBeNull();+ expect(strictArgsProblem(spec, ['--reset', '--mode=tokenmax'])).not.toBeNull();+ expect(spec.when?.(['--mode', 'tokenmax'])).toBe(true);+ });+});