Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(cli): #7619 cycle-3 review fixes: 0/1 switch values, direct-entry unknown_flag envelope, shared search subcommand list, disclosure of = values that now apply

garrytan9e3ba6d1e36c
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.md
index 18b14f700e..c1fa0e50cb 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/flag-equals.ts` — `--flag=value` on CLI_ONLY commands (#7619). `cliOnlyFlagArgs` in `src/cli/main.ts` runs `splitFlagEquals` once after routing and the help printers that run no handler, before the self-help handlers' help path, strict arguments, flag validation and dispatch, so no `=` token reaches a handler that would drop it. It also covers the hand-parsed `search modes|stats|tune|diagnose` subcommands, the validation-exempt paths that read exact tokens (`jobs submit`, `config` except `set`) and the direct `bun run src/commands/auth.ts` entry (which hands `auth local-writer` to its own parser, as main does, and runs the unknown-flag validator main runs). Per registered `--flag=value` token: a switch refuses (`invalid_params`, exit 2: a boolean in the command's own table, curated help or `SYNC_FLAGS` for sync, a `--no-` negation, the command's `COMMAND_SWITCHES`, or a name `knownSwitches()` finds boolean in the handler-free `OPERATION_MANIFEST` or any curated help, so `--yes=n` is never answered with `--yes <value>`); an empty or flag-like value refuses; `EQUALS_READERS`, keyed by command or `command sub`, keeps the token where the handler on that path reads the `=` form itself; the token splits into `--flag value` only when the command's own table declares a value; every other `=` form refuses with the two-argument spelling. Splitting a flag the subcommand never reads leaves its value as a stray positional that handlers taking the first numeric or non-flag token act on (`forget --purge --reason=3 34` purging fact 3), and a reader key wider than its path drops the token in sibling subcommands (`extract links --source-id=x` walked every source), so keys name the narrowest path. A short flag never takes `=` (`-y=n` refuses). A bare `--` ends the scan only on `END_OF_OPTIONS` paths (`agent run`, `frontmatter validate`), whose handler stops there; `serve`, `auth`, `frontmatter generate`, `questions` and `agent logs` read flags after it, so past `--` an `=` token that is not a registered flag refuses (the unknown-flag validator stops at `--`). A true/false word on a switch with no table entry (`--apply=false`) refuses with the bare-switch fix, never `--apply <value>`. `sources pull --path=` refuses, because main's database-free route matches only the exact token. `--json=true` becomes `--json`. Refusals name `--flag=…`, never the value. `OWN_EQUALS_PARSERS` (own `=`-aware parsers on every path that refuse `=` on their switches, `retrieval-upgrade` and `migrate embeddings` included; not the sources lifecycle subcommands, whose unmanaged fallback reads exact tokens), `call`, `config set`, `eval brainbench` and every subcommand `src/cli/strict-args.ts` governs (`strictSpecFor`) keep their argv. `scripts/generate-flag-registry.ts` skips this module. Pinned by `test/cli-flag-equals.test.ts` (a table over every registered CLI_ONLY flag, both-direction pins of `EQUALS_READERS` against every `=` reader in `src` and of `OWN_EQUALS_PARSERS` against every `=` option parser, stray-positional, dropped-scope, consent and `--` rows, own-parser switch refusals) and `test/serve-flag-equals.test.ts` (real CLI processes on PGLite, `--json` envelope, the direct `auth.ts` entry, `serve -- --access=` and `frontmatter generate` behind `--help` or `--` included).
+- `src/cli/flag-equals.ts` — `--flag=value` on CLI_ONLY commands (#7619). `cliOnlyFlagArgs` in `src/cli/main.ts` runs `splitFlagEquals` once after routing and the help printers that run no handler, before the self-help handlers' help path, strict arguments, flag validation and dispatch, so no `=` token reaches a handler that would drop it. It also covers the hand-parsed `search modes|stats|tune|diagnose` subcommands, the validation-exempt paths that read exact tokens (`jobs submit`, `config` except `set`) and the direct `bun run src/commands/auth.ts` entry (which hands `auth local-writer` to its own parser, as main does, and runs the unknown-flag validator main runs, `findUnknownFlag` with the same `unknown_flag` envelope and legacy keys). Per registered `--flag=value` token: a switch refuses (`invalid_params`, exit 2: a boolean in the command's own table, curated help or `SYNC_FLAGS` for sync, a `--no-` negation, the command's `COMMAND_SWITCHES`, or a name `knownSwitches()` finds boolean in the handler-free `OPERATION_MANIFEST` or any curated help, so `--yes=n` is never answered with `--yes <value>`); `EQUALS_READERS`, keyed by command or `command sub`, keeps the token where the handler on that path reads the `=` form itself, empty values included (that handler owns refusing them); elsewhere an empty or flag-like value refuses; the token splits into `--flag value` only when the command's own table declares a value; every other `=` form refuses with the two-argument spelling. Splitting a flag the subcommand never reads leaves its value as a stray positional that handlers taking the first numeric or non-flag token act on (`forget --purge --reason=3 34` purging fact 3), and a reader key wider than its path drops the token in sibling subcommands (`extract links --source-id=x` walked every source), so keys name the narrowest path. A short flag never takes `=` (`-y=n` refuses). A bare `--` ends the scan only on `END_OF_OPTIONS` paths (`agent run`, `frontmatter validate`), whose handler stops there; `serve`, `auth`, `frontmatter generate`, `questions` and `agent logs` read flags after it, so past `--` an `=` token that is not a registered flag refuses (the unknown-flag validator stops at `--`). A true/false word on a switch with no table entry (`--apply=false`) refuses with the bare-switch fix, never `--apply <value>`; a 0 or 1 there names both readings and says a value never turns a switch off. `sources pull --path=` refuses, because main's database-free route matches only the exact token. `--json=true` becomes `--json`. Refusals name `--flag=…`, never the value. `OWN_EQUALS_PARSERS` (own `=`-aware parsers on every path that refuse `=` on their switches, `retrieval-upgrade` and `migrate embeddings` included; not the sources lifecycle subcommands, whose unmanaged fallback reads exact tokens), `call`, `config set`, `eval brainbench` and every subcommand `src/cli/strict-args.ts` governs (`strictSpecFor`) keep their argv. `scripts/generate-flag-registry.ts` skips this module. Pinned by `test/cli-flag-equals.test.ts` (a table over every registered CLI_ONLY flag, both-direction pins of `EQUALS_READERS` against every `=` reader in `src` and of `OWN_EQUALS_PARSERS` against every `=` option parser, stray-positional, dropped-scope, consent and `--` rows, own-parser switch refusals) and `test/serve-flag-equals.test.ts` (real CLI processes on PGLite, `--json` envelope, the direct `auth.ts` entry, `serve -- --access=` and `frontmatter generate` behind `--help` or `--` included).
- `src/cli/search-timings.ts` — `gbrain search|query --timings` (#7158; global flag claimed by search/query/ask in `cli-options.ts`): `timeCliPhase` books `connect`, `context` and `remote` in `runSharedOperation`/`runThinClientRouted`; `searchTimingsDocument` makes `--json` print `{results, timings_ms, cost}` (bare array without the flag) and `searchTimingsLine` the stderr line. Absent phase = did not run. Guide: `docs/guides/search-explain.md`. Test: `test/cli-search-timings.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`.
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index f999032e3e..564e660be5 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -77,7 +77,7 @@ test/claude-cli-recipe.test.ts claude-cli LanguageModel — text-only round trip
test/claude-cli-recipe.test.ts claude-cli LanguageModel — tool use 17 readFileSync
test/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 split rules 16 readFileSync,source-surface-helper
+test/cli-flag-equals.test.ts #7619 split rules 19 readFileSync,source-surface-helper
test/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-helper
test/cli.test.ts BigInt-safe output normalization (#2450) 5 source-surface-helper
test/cli.test.ts CLI structure 2 source-surface-helper
diff --git a/src/cli/flag-equals.ts b/src/cli/flag-equals.ts
index c6935ce71c..3b5ae9aa6b 100644
--- a/src/cli/flag-equals.ts
+++ b/src/cli/flag-equals.ts
@@ -14,12 +14,14 @@
* `--yes=n` is never answered with `--yes <value>`;
* - refuse a true/false word (`--apply=false`) with the bare-switch fix
* even without the command's own table, so it never suggests
- * `--apply false`, which turns the switch on;
+ * `--apply false`, which turns the switch on; a 0 or 1 there names both
+ * readings and says a value never turns a switch off;
* - after a bare `--` the handler reads past, refuse an `=` token that is
* not a registered flag: the unknown-flag validator stops at `--`;
- * - refuse an empty value or one that looks like a flag (`-y`, `--x`);
* - keep the token where the handler on this path reads the `=` form
- * (EQUALS_READERS, keyed by command or `command sub`);
+ * (EQUALS_READERS, keyed by command or `command sub`), empty values
+ * included: that handler owns refusing them;
+ * - elsewhere, refuse an empty value or one that looks like a flag (`-y`, `--x`);
* - split `--flag value` when the command's own table declares a value;
* - refuse every other `=` form with the separate-token spelling. Splitting
* a flag the subcommand never reads would leave its value as a stray
@@ -40,7 +42,7 @@
*/
import type { OperationError } from '../core/ops/contract.ts';
import { CLI_FLAG_REGISTRY } from '../core/cli-flag-registry.generated.ts';
-import { usageError } from './cli-error.ts';
+import { unknownFlagError, usageError } from './cli-error.ts';
import { loadCuratedHelp } from './help/render.ts';
import { OPERATION_MANIFEST } from '../core/operation-manifest.generated.ts';
import { SYNC_FLAGS } from '../core/sync-flags.ts';
@@ -249,6 +251,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)$/i.test(value)
? [`${flag} takes no true/false value`, `Write ${flag} on its own to turn it on, or leave it out to turn it off.`]
+ : own === undefined && /^[01]$/.test(value)
+ ? [`${flag} takes no 0/1 value after =`, `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 number, write ${flag} <number>.`]
: own === undefined
? [`this command takes ${flag} <value> as two arguments`, `Write ${flag} <value>, or ${flag} on its own if it is a switch.`]
: null;
@@ -258,13 +262,34 @@ export async function splitFlagEquals(command: string, args: readonly string[]):
return { args: out };
}
-/** A command module's direct `bun run` entry: main's pass-through for own `=` parsers, the `=` rule, and main's unknown-flag check (which stops at `--`). */
-export async function directEntryArgs(command: string, raw: string[]): Promise<{ args: string[] } | { refusal: OperationError }> {
+/** CLI_ONLY lane: token scan against the generated legal set. */
+export function findUnknownFlag(args: string[], legal: ReadonlySet<string>): string | null {
+ for (const a of args) {
+ if (a === '--') break;
+ const m = /^--([a-z0-9][a-z0-9-]*)(?:=.*)?$/i.exec(a);
+ if (!m) continue;
+ // Casing typo = unknown flag: every handler in the repo is
+ // case-sensitive-lowercase, so `--MIGRATE-ONLY` passing validation would
+ // just be silently ignored downstream — the exact class this validator
+ // exists to kill.
+ if (/[A-Z]/.test(m[1])) return `--${m[1]}`;
+ const name = `--${m[1]}`;
+ if (legal.has(name)) continue;
+ // --no-<flag> negation of a known flag is legal.
+ if (name.startsWith('--no-') && legal.has(`--${name.slice(5)}`)) continue;
+ return name;
+ }
+ return null;
+}
+
+/** A command module's direct `bun run` entry: main's pass-through for own `=` parsers, the `=` rule, and main's unknown-flag check with its envelope (legacy keys included). */
+export async function directEntryArgs(command: string, raw: string[]): Promise<{ args: string[] } | { refusal: OperationError; legacy?: Record<string, string> }> {
if (OWN_EQUALS_PARSERS.has(`${command} ${raw[0]}`)) return { args: raw };
const split = await splitFlagEquals(command, raw);
if ('refusal' in split) return split;
- const legal = new Set(CLI_FLAG_REGISTRY[command]);
- const end = split.args.indexOf('--');
- const unknown = split.args.slice(0, end < 0 ? undefined : end).map(a => /^--[^=\s]+/.exec(a)?.[0]).find(f => f && !legal.has(f) && !(f.startsWith('--no-') && legal.has(`--${f.slice(5)}`)));
- return unknown ? { refusal: usageError(`gbrain ${command}: unknown flag ${unknown}.`, `Run gbrain ${command} --help for the flags it takes.`) } : split;
+ const unknown = findUnknownFlag(split.args, new Set(CLI_FLAG_REGISTRY[command]));
+ if (!unknown) return split;
+ const message = `unknown flag ${unknown} for 'gbrain ${command}'`;
+ const known = (await loadCuratedHelp(command))?.flags.map(f => f.name) ?? CLI_FLAG_REGISTRY[command] ?? [];
+ return { refusal: unknownFlagError(command, unknown, message, known), legacy: { status: 'error', reason: 'invalid_flag', message } };
}
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 02aab03861..247f7e97d1 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -42,7 +42,7 @@ import { currentCliWriteWait } from '../core/persistence/write-wait.ts';
import { isScopeErrorCode } from '../core/error-catalogue.ts';
import { shouldForceExitAfterMain, finishCliTeardown, flushThenExit, currentExitCode, setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';
import { printCuratedHelp } from './help/render.ts';
-import { OWN_EQUALS_PARSERS, splitFlagEquals } from './flag-equals.ts';
+import { OWN_EQUALS_PARSERS, findUnknownFlag, splitFlagEquals } from './flag-equals.ts';
import { printHelp } from './top-help.ts';
import { curatedFlagError } from './help/validate.ts';
import { cliCommandOf, exitCliError, exitOnRepairFailed, unknownFlagError, usageError, writeCliError, writeCliNotice, writeFatalCliError } from './cli-error.ts';
@@ -62,7 +62,7 @@ import { RemoteMcpError, extractResponseMeta } from '../core/remote-mcp-error.ts
import { assertSingleSourceScopeFlag, checkHostHonoredParams, hintAmbientNarrowing, type AmbientSourceBinding } from './source-scope.ts';
import { maybePromptForUpgrade } from '../core/thin-client-upgrade-prompt.ts';
import { CLI_FLAG_REGISTRY } from '../core/cli-flag-registry.generated.ts';
-import { cliHelpRequested } from './subcommands.ts';
+import { SEARCH_SUBCOMMANDS, cliHelpRequested } from './subcommands.ts';
import { printRouterHelp } from './router-help.ts';
import { strictArgsRefusal, strictSpecFor } from './strict-args.ts';
import { migrationCliArgumentError } from '../core/embedding-migration-cli.ts';
@@ -1328,12 +1328,9 @@ export function validateCommandFlags(command: string, subArgs: string[]): string
return null; // unknown command — the dispatcher's own error handles it
}
-/** The `search` subcommands main() dispatches by hand before the op lane (the dashboard branch); they read their flags as exact tokens. */
-const SEARCH_DASHBOARD_SUBCOMMANDS = ['modes', 'stats', 'tune', 'diagnose'];
-
/** #7619: the argv a CLI_ONLY handler receives, `--flag=value` split or refused (cli/flag-equals.ts); commands with their own `=`-aware parser keep it. */
export async function cliOnlyFlagArgs(command: string, subArgs: string[]): Promise<{ args: string[] } | { refusal: OperationError }> {
- const handParsedSearch = command === 'search' && SEARCH_DASHBOARD_SUBCOMMANDS.includes(subArgs[0] ?? '');
+ const handParsedSearch = command === 'search' && (SEARCH_SUBCOMMANDS as readonly string[]).includes(subArgs[0] ?? '');
if (!CLI_ONLY.has(command) && !handParsedSearch || equalsExempt(command, subArgs) || strictSpecFor(command, subArgs) || OWN_EQUALS_PARSERS.has(command) || OWN_EQUALS_PARSERS.has(`${command} ${subArgs[0]}`)) return { args: subArgs };
return splitFlagEquals(command, subArgs);
}
@@ -1343,25 +1340,7 @@ function equalsExempt(command: string, subArgs: string[]): boolean {
return command === 'call' || command === 'config' && subArgs[0] === 'set' || command === 'eval' && subArgs[0] === 'brainbench';
}
-/** CLI_ONLY lane: token scan against the generated legal set. */
-export function findUnknownFlag(args: string[], legal: ReadonlySet<string>): string | null {
- for (const a of args) {
- if (a === '--') break;
- const m = /^--([a-z0-9][a-z0-9-]*)(?:=.*)?$/i.exec(a);
- if (!m) continue;
- // Casing typo = unknown flag: every handler in the repo is
- // case-sensitive-lowercase, so `--MIGRATE-ONLY` passing validation would
- // just be silently ignored downstream — the exact class this validator
- // exists to kill.
- if (/[A-Z]/.test(m[1])) return `--${m[1]}`;
- const name = `--${m[1]}`;
- if (legal.has(name)) continue;
- // --no-<flag> negation of a known flag is legal.
- if (name.startsWith('--no-') && legal.has(`--${name.slice(5)}`)) continue;
- return name;
- }
- return null;
-}
+export { findUnknownFlag };
/** Op lane: mirrors parseOpArgs so flag VALUES starting with '--' are skipped. */
export function findUnknownOpFlag(op: OperationMeta, args: string[]): string | null {
diff --git a/src/commands/auth.ts b/src/commands/auth.ts
index 6291a37ae0..c3182c9ec9 100644
--- a/src/commands/auth.ts
+++ b/src/commands/auth.ts
@@ -1406,7 +1406,7 @@ if (import.meta.main) {
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');
+ exitCliError(argv.refusal, 'auth', { legacy: argv.legacy });
} else {
await runAuth(argv.args);
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 3fa41a5253..abfed37387 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1307,7 +1307,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.464.0', text: 'On Postgres, `gbrain serve --access read-only` (stdio) no longer acts as a resident owner: it holds no session-lane (direct pool) connection, starts no persistence consumer, takes no on-commit notifier lease, runs no startup or idle sweep or facts drain, and refuses delegated sync and sweep requests (the CLI then runs them itself). Resolve, turn_context and context_pack still answer. A read-write serve, `gbrain jobs work` or the autopilot owns those duties; `gbrain doctor` reports when no process on the host holds the notifier (`commit_notifier`) or a consumer (`two_consumers_on_host`). Read-write and HTTP serves, and any serve on PGLite (the process that owns the database file), are unchanged.' },
{ since: '0.60.464.0', text: 'Security: `gbrain serve --access=read-only` (the `=` form) now sets the read-only ceiling. It passed flag validation before but started the serve with full write access, because only `--access read-only` was read. A config that used the `=` form now gets the read-only tool set and refused mutations it asked for; a repeated `--access` never widens a read-only value, and an invalid value in either form refuses. `--surface=<v>` likewise now sets the serve surface (it was ignored, leaving the full surface), and a repeated `--surface` takes the narrowest value.' },
{ since: '0.60.464.0', text: 'A managed sync pass whose process was killed or crashed now reads `resumable` / `pass_interrupted` in `gbrain sync status` (with an `interrupted` block naming the pass and the dead holder) instead of `pass_unfinished`, and a second killed pass reads `blocked` / `pass_abandoned` at once. `gbrain doctor` `managed_sync_blocked` lists both (warn, fail after an hour). A live pass still committing is no longer counted abandoned because its row is old.' },
- { since: 'TBD', id: 'cli_flag_equals', text: 'A CLI flag value written with `=` that a command used to ignore now exits 2 (`invalid_params`) and names the two-argument spelling the command reads: `gbrain auth create --scopes=read` minted a full-access token. A switch never takes a value (`--yes=n`, `--dry-run=true`, `--apply=false` and `-y=n` exit 2 instead of being ignored), and the `=` spellings a command already read keep working. A script that passes a value with `=` to a command that does not read that form now stops with the fix instead of running without the value.' },
+ { since: 'TBD', id: 'cli_flag_equals', text: 'A CLI flag value written with `=` that a command used to ignore now exits 2 (`invalid_params`) and names the two-argument spelling the command reads: `gbrain auth create --scopes=read` minted a full-access token. A switch never takes a value (`--yes=n`, `--dry-run=true`, `--apply=false` and `-y=n` exit 2 instead of being ignored), and the `=` spellings a command already read keep working. A value written with `=` on a flag that the help of the command declares used to be ignored and now applies: an all-interfaces bind address given to `gbrain serve` that way bound loopback and now listens on every interface, and the serve port and token lifetime, the sync interval and the import worker count take effect the same way. A script that passes a value with `=` to a command that does not read that form now stops with the fix instead of running without the value.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/test/cli-flag-equals.test.ts b/test/cli-flag-equals.test.ts
index f118a42b9d..b4fd74771b 100644
--- a/test/cli-flag-equals.test.ts
+++ b/test/cli-flag-equals.test.ts
@@ -12,7 +12,8 @@ import { readFileSync } from 'node:fs';
import { Glob } from 'bun';
import { CLI_ONLY, cliOnlyFlagArgs, validateCommandFlags } from '../src/cli/main.ts';
import { CLI_FLAG_REGISTRY } from '../src/core/cli-flag-registry.generated.ts';
-import { END_OF_OPTIONS, EQUALS_READERS, OWN_EQUALS_PARSERS, knownSwitches } from '../src/cli/flag-equals.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 { strictSpecFor } from '../src/cli/strict-args.ts';
import { surfaceFileSource } from './helpers/source-surface.ts';
@@ -75,7 +76,7 @@ describe('#7619 table: every registered CLI_ONLY flag', () => {
expect(outcomes.refused).toBeGreaterThan(1000);
});
- test('an empty or flag-like value refuses on every flag, and no refusal echoes the value', async () => {
+ test('an empty or flag-like value refuses on every flag outside EQUALS_READERS, and no refusal echoes the value', async () => {
const wrong: string[] = [];
for (const command of CLI_ONLY) {
const legal = CLI_FLAG_REGISTRY[command];
@@ -130,6 +131,39 @@ describe('#7619 split rules', () => {
}
});
+ test('a 0/1 value on a switch with no table entry says a value never turns it off', async () => {
+ for (const [command, args] of [['maintain', ['--apply=0']], ['trust', ['claim-sources', '--accept-all=0']], ['quarantine', ['--accept-all=1']], ['status', ['--force-break-lock=1']], ['transcripts', ['recover', 'codex', '--apply=0']]] 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');
+ expect(text).not.toContain('<value>');
+ }
+ });
+
+ test('consent and mutation switches never get the value-form fix for a true/false or 0/1 value', async () => {
+ const consent: [string, string[], string][] = [
+ ['maintain', [], '--apply'], ['reindex', [], '--apply'], ['quarantine', [], '--accept-all'], ['trust', ['claim-sources'], '--accept-all'],
+ ['status', [], '--force-break-lock'], ['transcripts', ['recover', 'codex'], '--apply'], ['reinit-pglite', [], '--yes'], ['dream', [], '--unsafe-bypass-dream-guard'],
+ ];
+ for (const [command, pre, flag] of consent) {
+ for (const value of ['0', '1', 'false', 'true', 'no', 'off']) {
+ const r = await cliOnlyFlagArgs(command, [...pre, `${flag}=${value}`]);
+ const text = 'refusal' in r ? `${r.refusal.message} ${r.refusal.suggestion}` : '';
+ expect(text).toContain(`${flag}=…`);
+ expect(text).not.toContain('<value>');
+ }
+ }
+ });
+
+ test('the direct entry refuses an unknown flag with the envelope main uses', async () => {
+ const r = await directEntryArgs('auth', ['create', 'agent-a', '--bogus', 'x']);
+ expect('refusal' in r && r.refusal.code).toBe('unknown_flag');
+ expect('refusal' in r && r.refusal.fix?.argv).toEqual(['gbrain', 'auth', '--help']);
+ expect('refusal' in r && r.legacy).toEqual({ status: 'error', reason: 'invalid_flag', message: "unknown flag --bogus for 'gbrain auth'" });
+ expect('refusal' in await directEntryArgs('auth', ['create', 'agent-a', '--Scopes', 'read'])).toBe(true);
+ expect(await directEntryArgs('auth', ['create', 'agent-a', '--scopes', 'read'])).toEqual({ args: ['create', 'agent-a', '--scopes', 'read'] });
+ });
+
test('sources pull --path= refuses instead of falling through to the engine route', async () => {
expect(await refusalFor('sources', ['pull', '--path=/repo-example'])).toContain('takes --path <value> as two arguments');
});
@@ -137,9 +171,8 @@ describe('#7619 split rules', () => {
test('the = gate list matches the hand-dispatched search dashboard subcommands', () => {
const src = surfaceFileSource('cli', 'src/cli/main.ts');
const dispatch = /command === 'search' && (\[[^\]]+\])\.includes\(subArgs\[0\] \?\? ''\)/.exec(src)?.[1];
- const gate = /const SEARCH_DASHBOARD_SUBCOMMANDS = (\[[^\]]+\]);/.exec(src)?.[1];
expect(dispatch).toBeDefined();
- expect(gate).toBe(dispatch);
+ expect(JSON.parse(dispatch!.replace(/'/g, '"'))).toEqual([...SEARCH_SUBCOMMANDS]);
});
test('an unknown flag keeps its token so the validator names it', async () => {