Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(cli): agent run refuses a value flag after the prompt; edge-proposals = advice says drop it (#7672)
garrytan8311822d11ef
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.mdindex 0d5527639a..8f39419a91 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 (`jobs submit`, whose consent check reads the `=` spending cap, and `config` except `set`) and the direct `bun run src/commands/auth.ts` entry (which strips and applies the global flags, hands `auth local-writer` to its own parser and runs the unknown-flag validator, `findUnknownFlag` with the same `unknown_flag` envelope and legacy keys, all as main does). 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` (the `sync --status` alias reads as `sync status`, `forget --purge` is its own path, and `repos` reads the `sources` keys through `READER_ALIASES`), 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 or 0/1 on a flag with no table entry (`--apply=false`, `--expect=on`) refuses naming both readings, never `--apply <value>`, and says a value never turns a switch off. `sources pull --path=` refuses, because main's database-free route matches only the exact token. On the hand-parsed `search` subcommands, which have no registry row, every `=` token but `--json=true` refuses with a neutral message that names the subcommand, echoes no value and vouches for no switch. `--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 (`jobs submit`, whose consent check reads the `=` spending cap, and `config` except `set`) and the direct `bun run src/commands/auth.ts` entry (which strips and applies the global flags, hands `auth local-writer` to its own parser and runs the unknown-flag validator, `findUnknownFlag` with the same `unknown_flag` envelope and legacy keys, all as main does). 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` (also the switches no shared evidence covers, such as `agent --detach`), 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` (the `sync --status` alias reads as `sync status`, `forget --purge` is its own path, and `repos` reads the `sources` keys through `READER_ALIASES`), 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). `NO_VALUE_FLAG_PATHS` (the `edge-proposals` subcommands but `list`, which take the first numeric token as the id) refuse a value flag's `=` form with advice to leave it out, never `--flag <value>`. `agent run` is scanned only where `parseRunFlags` reads flags: the leading zone through `RUN_VALUE_FLAGS` (each value passes untouched) and `BOOLEAN_TAIL_FLAGS` from `src/commands/agent.ts`, plus flag-shaped `--x=` tokens, then, when the prompt holds no bare `--`, the trailing switches it hoists; one of its flags written with `=` inside the prompt, up to its first bare `--`, refuses with advice to write it before the prompt or put `--` before the prompt, and `parseRunFlags` itself throws on a value flag written as two arguments there (#7672). 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 or 0/1 on a flag with no table entry (`--apply=false`, `--expect=on`) refuses naming both readings, never `--apply <value>`, and says a value never turns a switch off. `sources pull --path=` refuses, because main's database-free route matches only the exact token. On the hand-parsed `search` subcommands, which have no registry row, every `=` token but `--json=true` refuses with a neutral message that names the subcommand, echoes no value and vouches for no switch. `--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/docs/guides/plugin-authors.md b/docs/guides/plugin-authors.mdindex 4444b27722..5f8fde7d13 100644--- a/docs/guides/plugin-authors.md+++ b/docs/guides/plugin-authors.md@@ -51,7 +51,7 @@ a 3-sentence summary.```bashexport GBRAIN_PLUGIN_PATH="/path/to/my-plugin"gbrain jobs work # worker startup prints the plugin load line-gbrain agent run "summarize meetings/2026-04-20" --subagent-def my-summarizer+gbrain agent run --subagent-def my-summarizer "summarize meetings/2026-04-20"```Multiple plugins: colon-separated, just like `$PATH`.diff --git a/plugin/skills/minion-orchestrator/SKILL.md b/plugin/skills/minion-orchestrator/SKILL.mdindex 9b4c897e86..73a012352a 100644--- a/plugin/skills/minion-orchestrator/SKILL.md+++ b/plugin/skills/minion-orchestrator/SKILL.md@@ -206,7 +206,7 @@ slug binding; generic `submit_job` does not accept these job names.## Phase 1: Submit```-gbrain agent run "Research Acme Corp revenue" --tools "search,query"+gbrain agent run --tools "search,query" "Research Acme Corp revenue"````--tools` accepts a comma-separated subset of `BRAIN_TOOL_ALLOWLIST` (seediff --git a/skills/minion-orchestrator/SKILL.md b/skills/minion-orchestrator/SKILL.mdindex 0b81c26495..2fd84a6718 100644--- a/skills/minion-orchestrator/SKILL.md+++ b/skills/minion-orchestrator/SKILL.md@@ -205,7 +205,7 @@ slug binding; generic `submit_job` does not accept these job names.## Phase 1: Submit```-gbrain agent run "Research Acme Corp revenue" --tools "search,query"+gbrain agent run --tools "search,query" "Research Acme Corp revenue"````--tools` accepts a comma-separated subset of `BRAIN_TOOL_ALLOWLIST` (seediff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex ad82dfcdd5..d4847e6e3d 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -189,7 +189,7 @@"migrations/v0.8.1.md": "fad7341cfb5e02545fb8a23221d12ab395fc3d8db15d1d8ee8a18844aea6563a","migrations/v0.9.0.md": "773fab0a8d7f330576265a3f510c1f318f47789b6136c46d43e08121acbc20eb","migrations/v0.9.1.md": "75761bad6c0ad37b69ec8197c6a678bb6a1484f9a76e4b70f2d1e86dc80102b3",- "minion-orchestrator/SKILL.md": "c6b2dcdb88b31d10242d4d05298d23adbf559bd2c463bbefd9c5a1c87ef928a5",+ "minion-orchestrator/SKILL.md": "9522cf2a740ab92f58a46dc054703649724f97dd080c699310cadcf4307d8e54","minion-orchestrator/routing-eval.jsonl": "501ed2e19cb16847ff8425219d246b7a774de1accd42cb28fd44edbb64204992","perplexity-research/SKILL.md": "1d6cf9f752b4a1618a04789a2f24a7f18d6feaa4ada578515842860bd5869997","perplexity-research/routing-eval.jsonl": "f1a40d87e710d5d2acd602a372d83f46c95da022b6e635228fffeaacb3bb2b27",diff --git a/src/cli/flag-equals.ts b/src/cli/flag-equals.tsindex 5bc6513770..d1dfbaa3b4 100644--- a/src/cli/flag-equals.ts+++ b/src/cli/flag-equals.ts@@ -21,6 +21,8 @@* - keep the token where the handler on this path reads the `=` form* (EQUALS_READERS, keyed by command or `command sub`), empty values* included: that handler owns refusing them;+ * - on a path that reads no value flag (NO_VALUE_FLAG_PATHS), refuse a+ * value flag with advice to leave it out;* - 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@@ -225,13 +227,19 @@ export const OWN_EQUALS_PARSERS: ReadonlySet<string> = new Set(['takes add', 'takes remove', 'takes resolve', 'takes supersede', 'takes update',]);-/** Switches a command reads with `args.includes` whose name takes a value elsewhere; the command's own reading wins. */+/**+ * Switches a command reads with `args.includes` whose name takes a value+ * elsewhere, or that no shared switch evidence (curated help, the operation+ * manifest) covers: `agent` has no curated help, so its `--follow` and+ * `--detach` need an entry here. The command's own reading wins.+ */export const COMMAND_SWITCHES: Readonly<Record<string, readonly string[]>> = {sync: ['--detail'],schema: ['--fields'],agent: ['--follow', '--detach'],dream: ['--unsafe-bypass-dream-guard'],embed: ['--stale'],+ 'edge-proposals': ['--all-held', '--all-applied'],};/** Value flags of a command with no curated help that every path reads as `--flag <value>` (migrate-engine.ts parseArgs, migrate-graduation.ts flagValue and routesToGraduation); their `=` form splits. */@@ -239,6 +247,17 @@ export const COMMAND_VALUES: Readonly<Record<string, readonly string[]>> = {migrate: ['--to', '--url'],};+/**+ * Paths (`command sub`) whose handler reads no value flag, only switches and+ * positionals: an `=` value flag there refuses with advice to drop it, never+ * `--flag <value>`, because the separate value would become the target+ * (edge-proposals.ts takes the first numeric token as the proposal id, so+ * `accept --limit 5 12` acts on proposal 5).+ */+export const NO_VALUE_FLAG_PATHS: ReadonlySet<string> = new Set([+ 'edge-proposals show', 'edge-proposals accept', 'edge-proposals reject', 'edge-proposals undo', 'edge-proposals date', 'edge-proposals retry',+]);+/** Paths (`command sub`) whose handler treats a bare `--` as the end of its options; everywhere else the scan continues past it. */export const END_OF_OPTIONS: ReadonlySet<string> = new Set(['agent run', 'frontmatter validate']);@@ -304,6 +323,8 @@ export async function splitFlagEquals(command: string, args: readonly string[]):? [`${where} reads no = form`, `Check the flag in ${where} --help: write a switch on its own (a value never turns it off), or a value as the next argument.`]: isSwitch? [`${flag} is a switch and takes no value`, `Write ${flag} on its own, or leave it out.`]+ : NO_VALUE_FLAG_PATHS.has(`${keyed} ${sub}`)+ ? [`${where} does not read ${flag}`, `Leave ${flag} out: written as ${flag} <value>, the value would be read as a positional argument (such as an id).`]: value === '' || /^-[-A-Za-z]/.test(value)? [`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|0|1)$/i.test(value)diff --git a/src/commands/agent.ts b/src/commands/agent.tsindex e6cc60a931..238e024faa 100644--- a/src/commands/agent.ts+++ b/src/commands/agent.ts@@ -2,7 +2,7 @@* `gbrain agent` CLI: the user-facing entry point for the v0.15 subagent* runtime.*- * gbrain agent run <prompt> [flags]+ * gbrain agent run [flags] <prompt>* gbrain agent logs <job_id> [--follow] [--since <spec>]** `run` submits a subagent job (or fan-out of N subagents + aggregator)@@ -84,7 +84,7 @@ function printHelp(): void {console.log(`gbrain agent — durable LLM agent runs (v0.15)USAGE- gbrain agent run <prompt> [flags]+ gbrain agent run [flags] <prompt>gbrain agent logs <job_id> [--follow] [--since <spec>]gbrain agent register <name> --harness <h> [flags] (see: gbrain agent register --help)@@ -107,8 +107,9 @@ SUBMITTINGFlags before the prompt are parsed normally. The no-value switches--detach, --follow and --no-follow are ALSO recognized when they trail- the prompt, so \`gbrain agent run "do X" --detach\` detaches. Any other- --word is treated as prompt text (no error). Use \`--\` to end flag+ the prompt, so \`gbrain agent run "do X" --detach\` detaches. A value+ flag above written after the prompt refuses (write it before the prompt);+ any other --word is treated as prompt text (no error). Use \`--\` to end flagparsing and pass the rest verbatim:gbrain agent run -- "literally --detach this, with --flags"@@ -196,7 +197,9 @@ function parseIntFlagValue(v: string, flag: string): number {* Prompt zone: a trailing run of the no-value switches (--detach/--follow/* --no-follow) is hoisted out so `agent run "do X" --detach` detaches. Only* trailing switches are hoisted; a `--word` elsewhere in the prompt stays- * verbatim. After an explicit `--`, nothing is hoisted.+ * verbatim. After an explicit `--`, nothing is hoisted. One of the value+ * flags in the prompt, up to its first bare `--`, throws (#7672): `agent run+ * "do X" --tools read` would otherwise run with every tool.*/function parseRunFlags(args: string[]): { flags: RunFlags; rest: string[] } {const flags: RunFlags = {@@ -226,6 +229,13 @@ function parseRunFlags(args: string[]): { flags: RunFlags; rest: string[] } {if (!known) break; // unknown --flag → first token of the (freeform) prompt}const rest = args.slice(i);+ if (!escaped) {+ const end = rest.indexOf('--');+ const stray = (end < 0 ? rest : rest.slice(0, end)).find(a => RUN_VALUE_FLAGS.has(a));+ if (stray) {+ throw new Error(`gbrain agent run: ${stray} is in the prompt, so it and its value would be prompt text. Write ${stray} <value> before the prompt and ahead of any word agent run does not read (such as --json or --yes), or put -- before the prompt to keep it as text.`);+ }+ }// An explicit `--` terminates flag parsing wherever it appears — leading// zone (escaped) OR after a positional (the leading loop breaks before it,// so `escaped` stays false). Honor both: when the prompt carries a literaldiff --git a/test/agent-cli.test.ts b/test/agent-cli.test.tsindex 1e7122e2a2..24483257cf 100644--- a/test/agent-cli.test.ts+++ b/test/agent-cli.test.ts@@ -90,6 +90,23 @@ describe('parseRunFlags', () => {expect(rest).toEqual(['summarize']);});+ // Value: protects=a value flag written after the prompt (or after a word parseRunFlags does not read, such as --json) refuses instead of becoming prompt text; fails_when=agent run "do X" --tools read submits a job with every tool; why_new=only the = spelling refused at the CLI entry (#7672 items 1 and 2); seam=none; no_claim=the job submit path+ test('#7672: a value flag in the prompt throws with both escapes', () => {+ for (const args of [['summarize X', '--tools', 'read'], ['fix', 'the', '--model', 'opus', 'bug'], ['--json', '--tools', 'read', 'go'], ['--model', 'm', 'go', '--source', 'source-a', '--detach'], ['go', '--max-turns', '2', '--', 'more']]) {+ expect(() => agentTesting.parseRunFlags(args)).toThrow(/is in the prompt, so it and its value would be prompt text.*before the prompt.*or put -- before the prompt/);+ }+ expect(agentTesting.parseRunFlags(['--', 'explain', '--tools', 'read']).rest).toEqual(['explain', '--tools', 'read']);+ expect(agentTesting.parseRunFlags(['explain', '--', '--tools', 'read']).rest).toEqual(['explain', '--', '--tools', 'read']);+ expect(agentTesting.parseRunFlags(['explain the --tools read flag']).rest).toEqual(['explain the --tools read flag']);+ });++ test('#7672: --json=true ahead of a value flag refuses instead of dropping it', async () => {+ const { cliOnlyFlagArgs } = await import('../src/cli/main.ts');+ const r = await cliOnlyFlagArgs('agent', ['run', '--json=true', '--tools', 'read', 'go']);+ if ('refusal' in r) throw new Error(r.refusal.message);+ expect(() => agentTesting.parseRunFlags(r.args.slice(1))).toThrow(/--tools is in the prompt/);+ });+test('#1738: a --switch mid-prompt (not trailing) stays verbatim', () => {const { flags, rest } = agentTesting.parseRunFlags(['summarize', '--detach', 'the', 'doc']);expect(flags.detach).toBe(false);diff --git a/test/cli-flag-equals.test.ts b/test/cli-flag-equals.test.tsindex e724f22d34..f092a1efb6 100644--- a/test/cli-flag-equals.test.ts+++ b/test/cli-flag-equals.test.ts@@ -12,7 +12,7 @@ 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 { COMMAND_VALUES, END_OF_OPTIONS, EQUALS_READERS, OWN_EQUALS_PARSERS, directEntryArgs, findUnknownFlag, knownSwitches, splitFlagEquals } from '../src/cli/flag-equals.ts';+import { COMMAND_VALUES, END_OF_OPTIONS, EQUALS_READERS, NO_VALUE_FLAG_PATHS, OWN_EQUALS_PARSERS, directEntryArgs, findUnknownFlag, knownSwitches, splitFlagEquals } from '../src/cli/flag-equals.ts';import { CLI_COMMANDS } from '../src/cli/command-table.ts';import { SEARCH_SUBCOMMANDS } from '../src/cli/subcommands.ts';import { SYNC_FLAGS } from '../src/core/sync-flags.ts';@@ -571,6 +571,34 @@ describe('#7619 refusals that keep consent, scope and targets right', () => {}});+ // Value: protects=the agent run leading zone skips a value flag's value, so an = flag after it is read as a leading flag and gets the two-argument advice; fails_when=the value-skip is removed and the value ends the zone, so the = flag is read as prompt text with advice to move it before the prompt it already precedes; why_new=no row put an = flag after a value flag and its value (#7672 item 6); seam=none; no_claim=agent run's own parse after the gate+ test('agent run reads an = flag after a value flag and its value as a leading flag', async () => {+ for (const [args, flag] of [[['run', '--model', 'opus', '--tools=read', 'go'], '--tools'], [['run', '--source', 'source-a', '--detach', '--max-turns=2', 'go'], '--max-turns']] as const) {+ const r = await cliOnlyFlagArgs('agent', [...args]);+ expect('refusal' in r && r.refusal.message).toContain(`${flag}=…`);+ expect('refusal' in r && r.refusal.message).toContain('as two arguments');+ expect('refusal' in r && r.refusal.message).not.toContain('before the prompt');+ }+ });++ // Value: protects=an = value flag on an edge-proposals path that reads no value flag refuses with advice to drop it; fails_when=the refusal advises --limit <value>, and the handler then takes that value as the proposal id (accept --limit 5 12 acts on proposal 5); why_new=the generic two-argument advice assumed every path reads the flag (#7672 item 4); seam=none; no_claim=the list path, which reads --limit= itself+ test('edge-proposals paths that read no value flag say to drop an = value flag', async () => {+ const { EDGE_PROPOSALS_SUBCOMMANDS } = await import('../src/cli/subcommands.ts');+ expect([...NO_VALUE_FLAG_PATHS].sort()).toEqual(EDGE_PROPOSALS_SUBCOMMANDS.filter(s => s !== 'list').map(s => `edge-proposals ${s}`).sort());+ for (const sub of ['show', 'accept', 'reject', 'undo', 'date', 'retry']) {+ for (const flag of ['--limit', '--source']) {+ const r = await cliOnlyFlagArgs('edge-proposals', [sub, `${flag}=5`, '12']);+ expect('refusal' in r && r.refusal.code).toBe('invalid_params');+ expect('refusal' in r && r.refusal.message).toContain(`gbrain edge-proposals ${sub} does not read ${flag}`);+ expect('refusal' in r && r.refusal.suggestion).toContain(`Leave ${flag} out`);+ expect('refusal' in r && r.refusal.suggestion).not.toContain(`Write ${flag} <value>`);+ }+ }+ expect(await refusalFor('edge-proposals', ['retry', '--all-held=1'])).toContain('--all-held is a switch');+ expect(await refusalFor('edge-proposals', ['undo', '--all-applied=true'])).toContain('--all-applied is a switch');+ expect(await argvFor('edge-proposals', ['list', '--limit=5', '--status=all'])).toEqual(['list', '--limit=5', '--status=all']);+ });+test('the hand-parsed search subcommands refuse an = form without vouching for the flag', async () => {for (const [args, flag] of [[['modes', '--mdoe=balanced'], '--mdoe'], [['diagnose', 'q', '--target', 'x', '--source=source-a'], '--source'], [['stats', '--yes=n'], '--yes'], [['modes', '--dry-run=x'], '--dry-run'], [['stats', '--no-thing=x'], '--no-thing']] as const) {const r = await cliOnlyFlagArgs('search', [...args]);