Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(cli): refuse --flag=value unless the command documents the flag as a value; own parsers refuse = on switches (#7619 review)
garrytan98dd756690fc
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.mdindex 40916e6931..c7010722b6 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 before the direct-pool profile, strict arguments, flag validation and dispatch (skipped when help is requested), so a handler that reads only `--flag value` never sees an `=` token it would drop. It refuses (`invalid_params`, exit 2, with the separate-token spelling) a curated switch or `--no-` negation given a value, an empty value or one starting with `--`, and a switch-like value (true/false/yes/no/on/off/0/1) on a flag whose arity is unknown. Commands with their own `=`-aware parser keep their argv: the validator's exemptions (call, config, jobs submit, eval brainbench), `migrate embeddings` / `retrieval-upgrade`, and every subcommand `src/cli/strict-args.ts` governs (`strictSpecFor`). `EQUALS_FORM_READERS` keeps the token for flags whose handler reads only the `=` form or gives it its own meaning (`doctor --scope`, `embed --pace`, `jobs --refresh-ms`, `models --skip`, `recall --budget-policy`). Pinned by `test/cli-flag-equals.test.ts` (a table over every registered CLI_ONLY flag) and `test/serve-flag-equals.test.ts` (real `gbrain serve` processes on PGLite).+- `src/cli/flag-equals.ts` — `--flag=value` on CLI_ONLY commands (#7619). `cliOnlyFlagArgs` in `src/cli/main.ts` runs `splitFlagEquals` once after routing and before the direct-pool profile, strict arguments, flag validation and dispatch (skipped when help is requested or no token has the `=` form), so no `=` token reaches a handler that would drop it. 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); an empty or flag-like value refuses; `EQUALS_FORM_READERS` keeps the token for the few handlers that read only the `=` form; the token splits into `--flag value` only when the command's own table declares a value; every other `=` form refuses with the separate-token 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 keeping a token whole on evidence from one module drops it in sibling subcommands (`extract links --source-id=x` walked every source), so both stay off. `--json=true` becomes `--json`. Refusals name `--flag=…`, never the value. `OWN_EQUALS_PARSERS` (own `=`-aware parsers that refuse `=` on their switches, `retrieval-upgrade` and `migrate embeddings` included), the validator's exemptions 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, stray-positional, dropped-scope and consent rows, own-parser switch refusals) and `test/serve-flag-equals.test.ts` (real CLI processes on PGLite, `--json` envelope 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/generate-flag-registry.ts b/scripts/generate-flag-registry.tsindex 717ff0ab0a..433030a091 100644--- a/scripts/generate-flag-registry.ts+++ b/scripts/generate-flag-registry.ts@@ -88,9 +88,10 @@ const DELEGATED_MODULES: Record<string, string[]> = {* declares both flags in its own source. strict-args.ts is the strict-argument* table for several commands' destructive subcommands (#6114): its literals* belong to pages, cache, schema, integrity and search, each of which reads- * its own flags in its own source.+ * its own flags in its own source. flag-equals.ts (#7619) names flags as+ * arity data for the `=` split; each handler reads its own flags.*/-const EXCLUDED_MODULES = ['thin-client-routing.ts', 'persistence-delegate.ts', 'job-isolation.ts', 'strict-args.ts'];+const EXCLUDED_MODULES = ['thin-client-routing.ts', 'persistence-delegate.ts', 'job-isolation.ts', 'strict-args.ts', 'flag-equals.ts'];function isExcludedModule(p: string): boolean {// Basename comparison is path-separator agnostic: on Windows p ends indiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex a892fe6295..9f054e1c42 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -42,7 +42,7 @@ src/core/bootstrap/harness.ts 2592 ratchet +29 live-PGLite-serve lane: LIVE_SERVsrc/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl optionsrc/core/ops/pages.ts 728 ratchet crossed the unlisted 1500 cap in the fix wave: pack-vocabulary enforcement on capture (#4721) + get_page alias follow (#4275) landed together; next growth should peel a pages-ops submodule; +3: alias hop reads the canonical in the owning source (ship-review); +5: explicit source_id liveness check in get_page/list_pages (#4620); +3: #4857 total-order slug sort + list_pages source_id parse; +5: #4620 explicit removed-source id fails loudly; master integration: +4: authenticated delegated private-write boundary and auto-link suppression; #5105: canonical page mutations peeled into persistence modules; +2 v0.50.5.0 purge parameter and shared preflight call; preparation composes through the persistence modules; +7: source-qualified deep-research fetch authorization and ambiguity refusal (codec lives in deep-research-id.ts); +1 #5567: remote get_page keeps materialized markers; +1 #5622: trusted local capture file parameter; +5 #5709: get_page include_timeline_entries (rows via get_timeline's read policy); +8 GBRA-36 security wave: required outputRedaction policy on each pages op; +1 #5154: list_pages passes listColumnsOnly; +17 #5641: list_pages exposes the updated_after_slug keyset cursor and updated_at_iso; +8 agent operator wave A2: every op declares mutating + idempotent (tags only); +7 F3b (#5954): list_pages pagination meta + listing_truncated notice for MCP callers (logic in ops/list-pages-pagination.ts); +4 #5988: get_page file_held (one indexed hold lookup; logic in persistence/held-reads.ts); +6 #6103: list_pages maps an unreadable updated_after (SQLSTATE 22007/22008) to invalid_params; wave 10 collector: #6103 (+6) and #4807 (+2) compose; +1 wave 11 W4.3 (#5969 D3): put_page drop_timeline param; +1 wave 11 security review: purge_deleted_pages yes param + trusted-CLI guard (consent logic in persistence/purge-deleted.ts); +1 Q2 parser gaps: get_page grammar_diagnostics param (report logic in core/line-grammar-report.ts); master v0.60.136.0 merge into #5575 memory trust (both sides kept); +21 large pages (Wave A): get_page body-mode dispatch, fetch window branch, put_page large-page admission and allow_shrink param, description text (logic in ops/get-page-body.ts and persistence/large-page-guard.ts); +1 D8 funnel: committed put_page records a save when the opt-in funnel is on; +1 #6609: restore_page detach param (logic in persistence/detached-pages.ts); +1 Wave B gem A: post-batch auto-link reads a segmented page materialized (helpers in persistence/segmented-apply.ts); merge v0.60.249.0: composes at 707; +4 Wave B PR 2: get_page refuses a segmented page whole and fetch windows one (logic in ops/get-page-body.ts and page-window/segmented.ts); +2 Wave B PR 2 lane F: get_page and fetch pin segmented reads to the authorized snapshot (pin logic in ops/get-page-body.ts authorizedReadPin); +3 W2 page-at-time: get_page known_as_of param and dispatch (logic in ops/known-as-of.ts and belief/page-at-time.ts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (721 measured); GBRA-151 #7147 follow-up re-summed at the v0.60.334.0 merge (727 measured); +1 #7305: capture dry run applies the hyphen-run slug admission (logic in persistence/suffixed-slug.ts)src/core/search/mode.ts 1704 ratchet +53 W3 confidence-gated reranking: reranker_gate / reranker_gate_min_gap bundle fields, overrides, config parse and KNOB_CONFIG_KEY rows, knobsHash v=31 rrg=/rrgg=/ecf= parts (parse contracts in crag.ts); +10 System One v1: decide.* snapshot subset in loadSearchModeConfig, append-only dec= knobsHash part; +5 #3617 follow-up: v27 same-knobs behavioral-change note (relaxed-row fusion demotion rides the bump); new row: crossed the 1500 unlisted cap in the 2026-08 eval fix wave — KNOBS_HASH v=27 adaptive-return fold (ar/arem/arom/armk/ari parts + KnobsHashContext.adaptiveReturn field + contamination rationale comments) | merged v0.48.1.0 (+#4787) true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: four knobs (expansion_variant_budget, relational_rerank_pin, keyword_arm_confidence_floor, metadata_boost_gate) + v29 hash parts + doc receipts (+218); #4781 loadSearchModeConfig reads the config table once via loadConfigSnapshot (+6); +4 #4359: update loadSearchModeConfig docstring — the cached path now reads config once (threaded snapshot), not twice; retired provider integration removed; +12 fw3-search: search.source_boosts + search.alias_token_hop read in the mode snapshot; +10 #5691: KnobsHashContext.queryPrefix and its append-only qp= part; P7 relational_planner / relational_orient_onehop knobs (interface docs, bundles, overrides, config parse, hash parts); +18 P7 relational_chain_slots knob (interface doc, bundles, override, config parse, rcs= hash part); +22 GBRA-60 S1 diverse_pool_depth knob (interface doc, bundles, overrides, pick, config parse, append-only dpd= hash part); +35 GBRA-154: collapse and rank_priors knobs (interface docs, bundles, overrides, pick, config parse, append-only col=/rpr= hash parts); GBRA-151 retrieval P0 x operability wave merge: both sides grew the file, re-summed (1704 measured)-src/commands/eval-longmemeval.ts 1544 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter)+src/commands/eval-longmemeval.ts 1545 ratchet new row: crossed the 1500 unlisted cap in fw3-search (#5092 benchmark-brain recycling: configureBrain split + recycler wiring + test seams; the recycler itself lives in src/eval/longmemeval/harness.ts); +1 P6: tokenmax synopsis-tier wiring (logic in eval/longmemeval/synopsis-tier.ts); +13 GBRA-81 lane A: --via-operation query|search (flags, per-call expansion pin, the run's expectExpansion, the op branch in runOneQuestion, row field, via_operation_summary and its FAIL line; logic in eval/longmemeval/via-operation.ts); +12 --call-plan FILE / --call-plan-gate CMD: two LME_FLAGS entries (CLI help lines), two ParsedArgs fields, the parseArgs pairing check and the header invariant (planner lives in eval/longmemeval/call-plan.ts; runEvalLongMemEval is one line shorter); +1 #7619: parseArgs refuses a value on a switch (--judge=false turned the paid judge on)src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: links_extraction_lag held bucket and its retry fix (logic in core/extraction-lag.ts heldExtractionReport); +1 undeclared_db_only_pages computes the source Git scope once per source (logic in core/markdown.ts sourceGitScope); new row: crossed the 1500 unlisted cap at the fix wave 9 merge: +7 lane W #5028 (extract_atoms freshness judged by the phase itself) and +3 lane F #5863 (extract_health dates a high halt rate by its last halt), each under the cap alone; +7 #5019: content_hash_duplicates fix pins the pairs' source (GBRAIN_SOURCE) and names a delete that runs; +1 fix wave 10 lane L1 #5556: links_extraction_lag denominator excludes quarantined pages (quarantineFilterFragment import); +11 fix wave 15 P2.8 (#5495): extract_health reads the 7-day halt reasons per kind (halt_reasons, top_halt_reason in details and the top reason in the warn line); the read, the unknown bucket and the ranking live in core/extract/rollup-writer.ts; +20 wave 18b lane 1: links_extraction_lag names the columns its pre-migration degrade reads (#6599 strict predicate), sync_freshness separates sync outcome from freshness for a source with no successful sync (#4960; verdict text, fixes and the attempt read live in doctor/sync-outcome.ts and core/sync-attempt.ts) and exempts read-only skill-pack catalogs (#6076; core/shared-skills/adopted-packs.ts); -51 #6803 (D1): links_extraction_lag reads its counts and verdict from core/extraction-lag.ts (shared with the sync nudge); +1 #7145: content_hash_duplicates reads one group past its list to report a floor ("at least 50")src/core/search/evidence-delivery.ts 1733 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move)src/commands/config.ts 1523 ratchet new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts)diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 8c1400538b..00ee2ac49b 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -76,6 +76,8 @@ test/claude-cli-recipe.test.ts claude-cli LanguageModel — output cap (#6424) 2test/claude-cli-recipe.test.ts claude-cli LanguageModel — text-only round trip 4 readFileSynctest/claude-cli-recipe.test.ts claude-cli LanguageModel — tool use 17 readFileSynctest/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 10 readFileSync+test/cli-flag-equals.test.ts #7619 split rules 10 readFileSynctest/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-helpertest/cli.test.ts BigInt-safe output normalization (#2450) 5 source-surface-helpertest/cli.test.ts CLI structure 2 source-surface-helperdiff --git a/src/cli/flag-equals.ts b/src/cli/flag-equals.tsindex 4c841e9ae6..01b7c223a7 100644--- a/src/cli/flag-equals.ts+++ b/src/cli/flag-equals.ts@@ -3,24 +3,37 @@* accepts the `=` form of every registered flag, but most handlers read only* `--flag value` (`args.includes`, `args[args.indexOf(flag) + 1]`), so the* value was dropped with no error: `serve --access=read-only` served every- * write tool. The CLI entry splits each token once, before validation and- * dispatch, so every handler sees the form it reads. Where splitting could- * change the meaning, the `=` form is refused (invalid_params, exit 2) with- * the separate-token spelling:- * - a switch (a curated boolean, or a `--no-` negation) takes no value;- * - a flag whose arity is unknown, given a switch-like value- * (true/false/yes/no/on/off/0/1): split, `--yes=false` would turn it on;- * - an empty value, or one starting with `--` (it would read as the next- * flag or as end-of-options).- * Flags in EQUALS_FORM_READERS keep the token: their handler reads the `=`- * form itself and gives it a meaning the bare form does not have. An unknown- * flag keeps the token too, so the validator names it. Everything after a- * bare `--` is passthrough.+ * write tool, `auth create --scopes=read` minted a full-access token. The+ * CLI entry never lets an `=` token reach a handler that would drop it:+ * - refuse (invalid_params, exit 2) a switch: a boolean in the command's own+ * table (curated help, the sync flag table), a `--no-` negation, the+ * command's COMMAND_SWITCHES, or a name whose shared-op parameter or+ * curated flag is boolean. Splitting turns the switch on and keeping drops+ * the value (`--dry-run=true` would write);+ * - 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+ * positional, which handlers that take the first numeric or non-flag token+ * as their target would act on (`forget --purge --reason=3 34` purging+ * fact 3). Keeping it whole is safe only where every path of the command+ * reads the `=` form, and evidence from one module does not show that for+ * its sibling subcommands (`extract links --source-id=x` walked every+ * source while `extract --stale` validated the same token).+ * `--json=true` becomes `--json` (the agent contract's JSON spelling, read+ * the same way by jsonRequested). Refusals name `--flag=…`, never the value,+ * which may be a credential. OWN_EQUALS_PARSERS pass their argv through,+ * EQUALS_FORM_READERS keep the token for the few handlers that read only the+ * `=` form, unregistered flags keep it for the validator to name, and+ * everything after a bare `--` is passthrough.*/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 type { CliHelpSpec } from './command-table.ts';+import { loadCuratedHelp } from './help/render.ts';+import { OPERATION_MANIFEST } from '../core/operation-manifest.generated.ts';+import { SYNC_FLAGS } from '../core/sync-flags.ts';export const EQUALS_FORM_READERS: Readonly<Record<string, readonly string[]>> = {// doctor.ts reads only `--scope=brain`.@@ -33,31 +46,65 @@ export const EQUALS_FORM_READERS: Readonly<Record<string, readonly string[]>> =models: ['--skip'],// recall parses both forms and refuses an empty `--budget-policy=` naming the policies.recall: ['--budget-policy'],+ // edge-proposals reads `--status=X` itself; `--status` is a switch on other commands.+ 'edge-proposals': ['--status'],};-const SWITCH_VALUE = /^(?:true|false|yes|no|on|off|0|1)$/i;+/**+ * Commands and subcommands whose handler parses `--flag value` and+ * `--flag=value` itself, refusing `=` on its own switches: cliOnlyFlagArgs in+ * src/cli/main.ts passes their argv through unchanged (pinned by+ * test/cli-flag-equals.test.ts against every `indexOf('=')` option parser).+ */+export const OWN_EQUALS_PARSERS: ReadonlySet<string> = new Set([+ 'append', 'auth local-writer', 'eval longmemeval', 'git', 'migrate embeddings', 'repair', 'retrieval-upgrade', 'schema add-type', 'skillpack remove',+ 'sources add', 'sources archive', 'sources connect', 'sources inspect', 'sources purge', 'sources reclone', 'sources reconcile',+ 'sources remove', 'sources reset-upstream', 'sources restore', 'sources set-path', 'sources writer',+ '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. */+export const COMMAND_SWITCHES: Readonly<Record<string, readonly string[]>> = {+ sync: ['--detail'],+ schema: ['--fields'],+};++/** Switch evidence by name: shared-op boolean parameters (handler-free manifest) and boolean flags in any command's curated help. Loaded only when an `=` token needs it. */+let switches: Promise<ReadonlySet<string>> | undefined;+export function knownSwitches(): Promise<ReadonlySet<string>> {+ return switches ??= (async () => {+ const out = new Set<string>();+ for (const op of OPERATION_MANIFEST) for (const [name, p] of Object.entries(op.params)) if (p.type === 'boolean') out.add(`--${name.replace(/_/g, '-')}`);+ for (const command of Object.keys(CLI_FLAG_REGISTRY)) for (const f of (await loadCuratedHelp(command))?.flags ?? []) if (f.type === 'boolean') out.add(f.name);+ return out;+ })();+}++export const EQUALS_TOKEN = /^(--[a-z0-9][a-z0-9-]*)=([\s\S]*)$/;-export function splitFlagEquals(command: string, args: readonly string[], curated: CliHelpSpec | null): { args: string[] } | { refusal: OperationError } {+export function splitFlagEquals(command: string, args: readonly string[], curated: CliHelpSpec | null, known: ReadonlySet<string>): { args: string[] } | { refusal: OperationError } {const legal = CLI_FLAG_REGISTRY[command];const types = new Map(curated?.flags.map(f => [f.name, f.type]));const out: string[] = [];for (let i = 0; i < args.length; i++) {const token = args[i]!;if (token === '--') return { args: [...out, ...args.slice(i)] };- const m = /^(--[a-z0-9][a-z0-9-]*)=([\s\S]*)$/.exec(token);+ const m = EQUALS_TOKEN.exec(token);const flag = m?.[1];- const known = flag !== undefined && (!legal || legal.includes(flag) || flag.startsWith('--no-') && legal.includes(`--${flag.slice(5)}`));- if (!m || !known || EQUALS_FORM_READERS[command]?.includes(flag)) { out.push(token); continue; }+ const registered = flag !== undefined && (!legal || legal.includes(flag) || flag.startsWith('--no-') && legal.includes(`--${flag.slice(5)}`));+ if (!m || !registered || EQUALS_FORM_READERS[command]?.includes(flag)) { out.push(token); continue; }const value = m[2]!;- const type = types.get(flag);- const refusal = type === 'boolean' || flag.startsWith('--no-')+ if (flag === '--json' && value === 'true') { out.push(flag); continue; }+ const own = types.get(flag) ?? (command === 'sync' ? (SYNC_FLAGS as Record<string, { arity: string }>)[flag]?.arity : undefined);+ const isSwitch = own !== undefined ? own === 'boolean' : flag.startsWith('--no-') || COMMAND_SWITCHES[command]?.includes(flag) || known.has(flag);+ const refusal = isSwitch? [`${flag} is a switch and takes no value`, `Write ${flag} on its own, or leave it out.`]- : value === '' || value.startsWith('--')- ? [`the value is empty or begins with --`, `Write ${flag} <value> with the value as the next argument.`]- : type === undefined && SWITCH_VALUE.test(value)- ? [`${flag} could be a switch or take a value, so the = form is ambiguous`, `Write ${flag} on its own to turn a switch on, or ${flag} ${value} to pass the value.`]+ : 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+ ? [`this command reads ${flag} only as a separate argument`, `Write ${flag} <value>, or ${flag} on its own if it is a switch.`]: null;- if (refusal) return { refusal: usageError(`gbrain ${command}: \`${token}\`: ${refusal[0]}.`, refusal[1]!) };+ if (refusal) return { refusal: usageError(`gbrain ${command}: \`${flag}=…\`: ${refusal[0]}.`, refusal[1]!) };out.push(flag, value);}return { args: out };diff --git a/src/cli/main.ts b/src/cli/main.tsindex ff6122f744..7012c8d2eb 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 { loadCuratedHelp, printCuratedHelp } from './help/render.ts';-import { splitFlagEquals } from './flag-equals.ts';+import { EQUALS_TOKEN, OWN_EQUALS_PARSERS, knownSwitches, 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';@@ -1324,10 +1324,10 @@ export function validateCommandFlags(command: string, subArgs: string[]): stringreturn null; // unknown command — the dispatcher's own error handles it}-/** #7619: the argv a CLI_ONLY handler receives, `--flag=value` split (cli/flag-equals.ts); commands with their own `=`-aware parser keep it. */+/** #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 }> {- if (!CLI_ONLY.has(command) || flagValidationExempt(command, subArgs) || command === 'retrieval-upgrade' || command === 'migrate' && subArgs[0] === 'embeddings' || strictSpecFor(command, subArgs)) return { args: subArgs };- return splitFlagEquals(command, subArgs, await loadCuratedHelp(command));+ if (!CLI_ONLY.has(command) || flagValidationExempt(command, subArgs) || strictSpecFor(command, subArgs) || OWN_EQUALS_PARSERS.has(command) || OWN_EQUALS_PARSERS.has(`${command} ${subArgs[0]}`) || !subArgs.some(a => EQUALS_TOKEN.test(a))) return { args: subArgs };+ return splitFlagEquals(command, subArgs, await loadCuratedHelp(command), await knownSwitches());}/** CLI_ONLY lane: token scan against the generated legal set. */diff --git a/src/commands/eval-longmemeval.ts b/src/commands/eval-longmemeval.tsindex afa32c8d3b..fc92f8b5bc 100644--- a/src/commands/eval-longmemeval.ts+++ b/src/commands/eval-longmemeval.ts@@ -438,6 +438,7 @@ function parseArgs(args: string[]): ParsedArgs {const name = eq >= 0 ? a.slice(0, eq) : a;const flag = byName.get(name);if (!flag) throw new Error(`unknown flag ${name} for 'gbrain eval longmemeval' (see --help)`);+ if (flag.arg === undefined && eq >= 0) throw new Error(`${name} is a switch and takes no value (write ${name} on its own)`);let value = '';if (flag.arg !== undefined) {value = eq >= 0 ? a.slice(eq + 1) : (args[++i] ?? '');diff --git a/src/commands/schema-add-type.ts b/src/commands/schema-add-type.tsindex 45c62b751a..17c4adecd9 100644--- a/src/commands/schema-add-type.ts+++ b/src/commands/schema-add-type.ts@@ -87,6 +87,7 @@ export function parseAddTypeArgs(args: string[]): AddTypeArgs {const flag = a.startsWith('--') && eq > 0 ? a.slice(0, eq) : a;if (!flag.startsWith('--')) { positional.push(a); continue; }seen.add(flag);+ if (!VALUE_FLAGS.has(flag) && flag !== a) throw usageError(`${flag} is a switch and takes no value.`, `Write ${flag} on its own.`);if (!VALUE_FLAGS.has(flag)) continue;const value = flag !== a ? a.slice(eq + 1) : args[++i];if (flag === '--alias') { if (value !== undefined) aliases.push(value); } else values[flag] = value;diff --git a/src/commands/sources-writer-movement.ts b/src/commands/sources-writer-movement.tsindex 29c09cf203..5daeaac25d 100644--- a/src/commands/sources-writer-movement.ts+++ b/src/commands/sources-writer-movement.ts@@ -76,6 +76,7 @@ export function parseMovementArgs(args: string[]): MovementArgs {const flag = token.startsWith('-') && equal > 0 ? token.slice(0, equal) : token;const value = () => { const v = equal > 0 && token.startsWith('-') ? token.slice(equal + 1) : args[++i]; if (v === undefined || v.startsWith('--')) throw usage(`${flag} requires a value.`, `Give ${flag} its value right after it, as ${flag} <value>.`); return v; };if (!token.startsWith('-')) { if (out.sourceId !== undefined) throw usage('Specify the source once.', `Name the source either as the argument or with --source, not both (here ${out.sourceId} and ${token}).`); out.sourceId = token; }+ else if ((flag === '--json' || flag === '--warn-only') && flag !== token) throw usage(`${flag} is a switch and takes no value.`, `Write ${flag} on its own.`);else if (flag === '--json') out.json = true;else if (flag === '--warn-only') out.warnOnly = true;else if (flag === '--source') { if (out.sourceId !== undefined) throw usage('Specify the source once.', 'Name the source either as the argument or with --source, not both.'); out.sourceId = value(); }diff --git a/test/cli-flag-equals.test.ts b/test/cli-flag-equals.test.tsindex 8cc5814049..9e63cb8a49 100644--- a/test/cli-flag-equals.test.ts+++ b/test/cli-flag-equals.test.ts@@ -1,19 +1,25 @@/*** #7619: `--flag=value` on CLI_ONLY commands must mean exactly what- * `--flag value` means, or refuse. The validator accepted the `=` form of- * every registered flag while most handlers read only the separate-token form,- * so the value was dropped with no error (`serve --access=read-only` served- * every write tool). cliOnlyFlagArgs is the argv every CLI_ONLY handler- * receives; this table runs it over every registered flag of every command.+ * `--flag value` means or refuse. The validator accepted the `=` form of+ * every registered flag while most handlers read only the separate-token+ * form, so the value was dropped with no error (`serve --access=read-only`+ * served every write tool). cliOnlyFlagArgs is the argv every CLI_ONLY+ * handler receives; these tables run it over every registered flag of every+ * command.*/import { describe, expect, test } from 'bun:test';+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 { EQUALS_FORM_READERS } from '../src/cli/flag-equals.ts';+import { EQUALS_FORM_READERS, OWN_EQUALS_PARSERS, knownSwitches } from '../src/cli/flag-equals.ts';+import { SYNC_FLAGS } from '../src/core/sync-flags.ts';import { loadCuratedHelp } from '../src/cli/help/render.ts';import { parseAccessFlag, parseSurfaceFlag } from '../src/mcp/surface.ts';+import { parseMovementArgs } from '../src/commands/sources-writer-movement.ts';+import { parseAddTypeArgs } from '../src/commands/schema-add-type.ts';-const PASSTHROUGH = new Set(['call', 'config', 'retrieval-upgrade', 'migrate']);+const PASSTHROUGH = new Set(['call', 'config', 'retrieval-upgrade']);async function argvFor(command: string, args: string[]): Promise<string[]> {const r = await cliOnlyFlagArgs(command, args);@@ -26,47 +32,61 @@ async function refusalFor(command: string, args: string[]): Promise<string | nulreturn 'refusal' in r ? r.refusal.message : null;}+async function ownTable(command: string): Promise<Map<string, string>> {+ const types = new Map((await loadCuratedHelp(command))?.flags.map(f => [f.name, f.type] as [string, string]));+ if (command === 'sync') for (const [flag, spec] of Object.entries(SYNC_FLAGS as Record<string, { arity: string }>)) if (!types.has(flag)) types.set(flag, spec.arity);+ return types;+}+describe('#7619 table: every registered CLI_ONLY flag', () => {- test('the = form reaches the handler as the bare form, is kept for an =-reading handler, or refuses', async () => {+ test('the = form splits only on the command\'s own value flags and otherwise refuses', async () => {+ const switches = await knownSwitches();const wrong: string[] = [];let checked = 0;+ const outcomes = { split: 0, kept: 0, refused: 0 };for (const command of CLI_ONLY) {const legal = CLI_FLAG_REGISTRY[command];- if (!legal || PASSTHROUGH.has(command)) continue;- const types = new Map((await loadCuratedHelp(command))?.flags.map(f => [f.name, f.type]));+ if (!legal || PASSTHROUGH.has(command) || OWN_EQUALS_PARSERS.has(command)) continue;+ const own = await ownTable(command);for (const flag of legal) {checked++;const value = 'alpha=beta,gamma';const r = await cliOnlyFlagArgs(command, [`${flag}=${value}`]);- const expected = EQUALS_FORM_READERS[command]?.includes(flag) ? 'kept'- : types.get(flag) === 'boolean' || flag.startsWith('--no-') ? 'refused' : 'split';- const args = 'refusal' in r ? null : r.args;- const bare = JSON.stringify(await argvFor(command, [flag, value]));- const got = args === null ? 'refused'- : args.length === 1 && args[0] === `${flag}=${value}` ? 'kept'- : JSON.stringify(args) === bare && args[0] === flag && args[1] === value ? 'split' : `other ${JSON.stringify(args)}`;- if (got !== expected) wrong.push(`${command} ${flag}: expected ${expected}, got ${got}`);- if (got === 'split' && validateCommandFlags(command, args!) !== null) wrong.push(`${command} ${flag}: split argv fails validation`);+ const got = 'refusal' in r ? 'refused'+ : r.args.length === 1 && r.args[0] === `${flag}=${value}` ? 'kept'+ : JSON.stringify(r.args) === JSON.stringify([flag, value]) ? 'split' : `other ${JSON.stringify(r.args)}`;+ if (got in outcomes) outcomes[got as keyof typeof outcomes]++;+ const listed = EQUALS_FORM_READERS[command]?.includes(flag);+ const isSwitch = own.has(flag) ? own.get(flag) === 'boolean' : flag.startsWith('--no-') || switches.has(flag);+ if (got === 'split' && (!own.has(flag) || own.get(flag) === 'boolean')) wrong.push(`${command} ${flag}: split without a value in the command's own table`);+ if (got === 'split' && validateCommandFlags(command, (r as { args: string[] }).args) !== null) wrong.push(`${command} ${flag}: split argv fails validation`);+ if (got === 'kept' && !listed) wrong.push(`${command} ${flag}: kept whole for a handler that may read only the separate form`);+ if (got !== 'refused' && isSwitch && !listed) wrong.push(`${command} ${flag}: a switch was not refused`);+ if (got === 'refused' && (listed || own.has(flag) && !isSwitch)) wrong.push(`${command} ${flag}: refused a form the handler reads`);+ if (got.startsWith('other')) wrong.push(`${command} ${flag}: ${got}`);}}expect(wrong).toEqual([]);expect(checked).toBeGreaterThan(1000);+ expect(outcomes.split).toBeGreaterThan(50);+ expect(outcomes.refused).toBeGreaterThan(1000);});- test('a switch-like value on a flag of unknown arity refuses for every split flag', async () => {- const accepted: string[] = [];+ test('an empty or flag-like value refuses on every flag, and no refusal echoes the value', async () => {+ const wrong: string[] = [];for (const command of CLI_ONLY) {const legal = CLI_FLAG_REGISTRY[command];- if (!legal || PASSTHROUGH.has(command)) continue;- const types = new Map((await loadCuratedHelp(command))?.flags.map(f => [f.name, f.type]));+ if (!legal || PASSTHROUGH.has(command) || OWN_EQUALS_PARSERS.has(command)) continue;for (const flag of legal) {- if (EQUALS_FORM_READERS[command]?.includes(flag) || types.has(flag)) continue;- for (const value of ['true', 'false', 'FALSE', 'yes', 'no', 'on', 'off', '0', '1', '', '--x']) {- if (await refusalFor(command, [`${flag}=${value}`]) === null) accepted.push(`${command} ${flag}=${value}`);+ if (EQUALS_FORM_READERS[command]?.includes(flag)) continue;+ for (const value of ['', '--x', '-y', '-h']) {+ if (await refusalFor(command, [`${flag}=${value}`]) === null) wrong.push(`${command} ${flag}=${value} accepted`);}+ const message = await refusalFor(command, [`${flag}=-SecretValue-alpha`]);+ if (message?.includes('SecretValue')) wrong.push(`${command} ${flag}: refusal echoes the value`);}}- expect(accepted).toEqual([]);+ expect(wrong).toEqual([]);});});@@ -89,26 +109,167 @@ describe('#7619 split rules', () => {expect(await argvFor('serve', ['--token-ttl=60'])).toEqual(['--token-ttl', '60']);});+ test('the sync flag table splits sync values', async () => {+ expect(await argvFor('sync', ['--source=source-a', '--interval=60'])).toEqual(['--source', 'source-a', '--interval', '60']);+ });+test('a curated switch refuses the = form with the bare spelling', async () => {for (const token of ['--source-guard=true', '--source-guard=false', '--http=1']) {const message = await refusalFor('serve', [token]);- expect(message).toContain(token);+ expect(message).toContain(`${token.split('=')[0]}=…`);expect(message).toContain('is a switch and takes no value');}});test('a negation refuses the = form', async () => {expect(await refusalFor('sync', ['--no-pull=true'])).toContain('--no-pull is a switch');+ expect(CLI_FLAG_REGISTRY.forget).not.toContain('--no-purge');+ expect(await refusalFor('forget', ['--no-purge=1'])).toContain('--no-purge is a switch');});- test('commands with their own =-aware parsers keep their argv', async () => {+ test('commands that read the = form themselves keep their argv', async () => {expect(await argvFor('config', ['set', 'k', '--x=true'])).toEqual(['set', 'k', '--x=true']);expect(await argvFor('jobs', ['submit', 'shell', '--params={"a":1}'])).toEqual(['submit', 'shell', '--params={"a":1}']);expect(await argvFor('pages', ['purge-deleted', '--older-than=72'])).toEqual(['purge-deleted', '--older-than=72']);expect(await argvFor('embed', ['--pace=gentle'])).toEqual(['--pace=gentle']);expect(await argvFor('doctor', ['--scope=brain'])).toEqual(['--scope=brain']);+ expect(await argvFor('search', ['--limit=5'])).toEqual(['--limit=5']);+ expect(await argvFor('retrieval-upgrade', ['--yes=true'])).toEqual(['--yes=true']);+ expect(await argvFor('migrate', ['embeddings', '--to=x'])).toEqual(['embeddings', '--to=x']);+ expect(await argvFor('eval', ['brainbench', '--x=1'])).toEqual(['brainbench', '--x=1']);+ expect(await argvFor('call', ['x', '--y=true'])).toEqual(['x', '--y=true']);+ expect(await argvFor('edge-proposals', ['list', '--status=all'])).toEqual(['list', '--status=all']);+ });++ test('a strict spec whose when is false falls through to the entry rule', async () => {+ expect(await refusalFor('skillpack', ['reference', '--harness=claude-code'])).toContain('reads --harness only as a separate argument');+ expect(await refusalFor('skillpack', ['reference', '--harness', 'claude-code', '--dry-run=true'])).toContain('--dry-run=…');+ });++ test('EQUALS_FORM_READERS matches the handlers that read only the = form', () => {+ const files = [...new Glob('src/{commands,cli}/**/*.ts').scanSync('.')].map(p => [p, readFileSync(p, 'utf8')] as const);+ const listed = new Set(Object.values(EQUALS_FORM_READERS).flat());+ const unlisted: string[] = [];+ for (const [path, src] of files) {+ for (const m of src.matchAll(/(?:startsWith|includes)\('(--[a-z0-9-]+)=/g)) {+ if (!new RegExp(`['"]${m[1]}['"]`).test(src) && !listed.has(m[1]!)) unlisted.push(`${path} ${m[1]}`);+ }+ }+ expect(unlisted).toEqual([]);+ for (const flag of listed) expect(files.some(([, src]) => src.includes(`'${flag}=`) || src.includes(`'${flag}'`) && /\$\{\w+\}=/.test(src))).toBe(true);+ });+});++describe('#7619 refusals that keep consent, scope and targets right', () => {+ test('a switch never splits into the switch plus a stray positional', async () => {+ for (const [command, args] of [+ ['reinit-pglite', ['--yes=n']], ['reinit-pglite', ['--yes=nope']], ['reinit-pglite', ['--yes=disabled']],+ ['forget', ['--purge=n']], ['embed', ['--stale=alice-example']], ['embed', ['--all=alice-example']], ['sync', ['--dry-run=alice-example']],+ ['forget', ['--purge', '--continue=12', '--yes', '--request-id', 'r1']],+ ['frontmatter', ['validate', 'x.md', '--fix', '--include-ambiguous=n']],+ ['init', ['--non-interactive=n']], ['init', ['--rebuild=n']], ['init', ['--supabase=on']], ['init', ['--pglite=1']],+ ['dream', ['--unsafe-bypass-dream-guard=never']], ['dream', ['--unsafe-bypass-dream-guard=1']],+ ['auth', ['--enable-dcr-insecure=disabled']], ['sync', ['--status=true']], ['forget', ['--status=yes']],+ ['setup', ['--remove=yes']], ['bootstrap', ['--remove=yes']], ['mcp', ['expose', '--remove=yes']], ['quarantine', ['--yes=n']],+ ['skillpack', ['scaffold', '--harness', 'claude-code', '--dry-run=true']],+ ] as const) {+ const token = args.find(a => a.includes('='))!;+ expect(CLI_FLAG_REGISTRY[command]).toContain(token.split('=')[0]!);+ const r = await cliOnlyFlagArgs(command, [...args]);+ expect('refusal' in r && r.refusal.code).toBe('invalid_params');+ }+ });++ test('a value flag the handler reads only as a separate argument refuses with that spelling instead of being dropped', async () => {+ for (const [command, args, flag] of [+ ['auth', ['create', 'bot-example', '--scopes=read'], '--scopes'], ['auth', ['create', 'bot-example', '--takes-holders=world'], '--takes-holders'],+ ['connect', ['https://a.example', '--scopes=read'], '--scopes'], ['takes', ['propose', '--accept=12'], '--accept'],+ ['reinit-pglite', ['--path=/tmp/brain-example'], '--path'], ['bootstrap', ['interview', '--confirm=abc123'], '--confirm'],+ ['extract', ['links', '--source', 'db', '--source-id=source-a'], '--source-id'], ['extract', ['--stale', '--source-id=source-a'], '--source-id'],+ ['trust', ['explain', 'ref-example', '--source=source-a'], '--source'], ['jobs', ['work', '--concurrency=4'], '--concurrency'],+ ['forget', ['34', '--reason=stale-example'], '--reason'], ['export', ['--dir=out-example'], '--dir'],+ ['beliefs', ['replay-purges', '--purge-mirror=/abs/mirror'], '--purge-mirror'], ['skillpack', ['scaffold', '--harness=claude-code'], '--harness'],+ ] as const) {+ const r = await cliOnlyFlagArgs(command, [...args]);+ expect('refusal' in r && r.refusal.message).toContain(`reads ${flag} only as a separate argument`);+ expect('refusal' in r && r.refusal.suggestion).toContain(`${flag} <value>`);+ }+ });++ test('a flag value never becomes the numeric or slug target of a mutating subcommand', async () => {+ for (const [command, args] of [+ ['forget', ['--purge', '--reason=3', '34', '--dry-run']], ['forget', ['--purge', '--source=7', '34', '--yes', '--request-id', 'r1']],+ ['edge-proposals', ['accept', '--limit=3', '7']], ['edge-proposals', ['accept', '--row=3', '7']],+ ['decide', ['proposals', 'accept', '--limit=3', '7']],+ ['loops', ['drop', '--note=7', '12']], ['pages', ['unpurge', '--source-id=people/alice-example', 'people/bob-example']],+ ] as const) expect(await refusalFor(command, [...args])).not.toBeNull();+ });++ test('subcommands with their own = parser get their argv unchanged', async () => {+ for (const [command, args] of [+ ['takes', ['resolve', 'people/alice-example', '--row=1', '--by=alice-example']],+ ['takes', ['add', 'people/alice-example', '--claim=x', '--by=1']],+ ['sources', ['reconcile', 'notes', '--apply=plan-example.json', '--remove-backup=id-example']],+ ['sources', ['add', 'source-a', '--history-days=1', '--token-env=TOKEN_EXAMPLE']],+ ['auth', ['local-writer', 'register', '--expected-epoch=1', '--scopes=read,write']],+ ['repair', ['file-drift', '--generation=1', '--keep=database']],+ ['eval', ['longmemeval', 'data.jsonl', '--top-k=1', '--autocut=on']],+ ['skillpack', ['remove', '--harness=claude-code', '--persona=alice-example']],+ ['schema', ['add-type', 'note', '--alias=n', '--primitive=entity']],+ ['git', ['commit-push', '--message=alpha', '--resolve=a.md=ours']],+ ] as const) expect(await argvFor(command, [...args])).toEqual([...args]);+ });++ test('own = parsers refuse a value on their own switches', () => {+ expect(() => parseMovementArgs(['source-a', '--warn-only=false'])).toThrow('--warn-only is a switch');+ expect(() => parseMovementArgs(['source-a', '--json=false'])).toThrow('--json is a switch');+ expect(parseMovementArgs(['source-a', '--warn-only', '--json'])).toMatchObject({ warnOnly: true, json: true });+ expect(() => parseAddTypeArgs(['note', '--primitive=entity', '--no-prefix=false'])).toThrow('--no-prefix is a switch');+ expect(() => parseAddTypeArgs(['note', '--primitive=entity', '--prefix=notes/', '--extractable=false'])).toThrow('--extractable is a switch');+ expect(parseAddTypeArgs(['note', '--primitive=entity', '--no-prefix'])).toMatchObject({ noPrefix: true });+ });++ test('every option parser in src/commands that splits = itself is an OWN_EQUALS_PARSERS entry', () => {+ const OWNERS: Record<string, string | null> = {+ 'src/commands/company-brain-connect.ts': 'sources connect', 'src/commands/company-brain-inspect.ts': 'sources inspect',+ 'src/commands/eval-longmemeval.ts': 'eval longmemeval', 'src/commands/git.ts': 'git', 'src/commands/persistence-admin.ts': 'auth local-writer',+ 'src/commands/repair.ts': 'repair', 'src/commands/schema-add-type.ts': 'schema add-type', 'src/commands/skillpack/harness.ts': 'skillpack remove',+ 'src/commands/source-reconcile.ts': 'sources reconcile', 'src/commands/sources-lifecycle-args.ts': 'sources add',+ 'src/commands/sources-reset-upstream.ts': 'sources reset-upstream', 'src/commands/sources-writer-movement.ts': 'sources writer',+ 'src/commands/takes-mutation.ts': 'takes add',+ // normalizeReindexArgs splits its own value flags; the entry refuses other = forms before it runs.+ 'src/commands/reindex.ts': null,+ };+ const found = [...new Glob('src/commands/**/*.ts').scanSync('.')].filter(p => /\b(?:eq|equal|equals) = \w+\.indexOf\('='\)/.test(readFileSync(p, 'utf8'))).sort();+ expect(found).toEqual(Object.keys(OWNERS).sort());+ for (const owner of Object.values(OWNERS)) if (owner) expect(OWN_EQUALS_PARSERS.has(owner)).toBe(true);});+ test("a command's own switch wins over a value of the same name elsewhere", async () => {+ expect(await refusalFor('sync', ['status', '--detail=high'])).toContain('--detail is a switch');+ expect(await refusalFor('schema', ['detect', '--fields=x'])).toContain('--fields is a switch');+ });++ test('--json=true is the JSON switch; other values refuse', async () => {+ expect(await argvFor('doctor', ['--json=true'])).toEqual(['--json']);+ expect(await argvFor('sync', ['--json=true'])).toEqual(['--json']);+ expect(await refusalFor('sync', ['--json=false'])).toContain('--json is a switch');+ });++ test('a refused credential value is never echoed', async () => {+ const r = await cliOnlyFlagArgs('auth', ['--token=-AbcSecretValue123']);+ expect('refusal' in r && r.refusal.code).toBe('invalid_params');+ expect(JSON.stringify(r)).not.toContain('AbcSecretValue123');+ const plain = await cliOnlyFlagArgs('auth', ['create', 'bot-example', '--scopes=AbcSecretValue123']);+ expect(JSON.stringify(plain)).not.toContain('AbcSecretValue123');+ });++ test('a curated value flag refuses an empty or flag-like value', async () => {+ for (const token of ['--access=', '--surface=--x', '--public-url=', '--token-ttl=', '--access=-y']) {+ const r = await cliOnlyFlagArgs('serve', [token]);+ expect('refusal' in r && r.refusal.code).toBe('invalid_params');+ }+ });});describe('#7619 serve: the dropped safety flags reach the handler', () => {diff --git a/test/serve-flag-equals.test.ts b/test/serve-flag-equals.test.tsindex 25a3dbac94..e35ca22094 100644--- a/test/serve-flag-equals.test.ts+++ b/test/serve-flag-equals.test.ts@@ -75,4 +75,25 @@ describe('serve --flag=value', () => {expect(r.status).toBe(2);expect(r.stderr).toContain('--source-guard is a switch and takes no value');});++ test('a refusal under --json prints one invalid_params envelope on stdout', () => {+ const r = cli(['serve', '--source-guard=true', '--json']);+ expect(r.status).toBe(2);+ const envelope = JSON.parse(r.stdout.trim());+ expect(envelope.code).toBe('invalid_params');+ expect(envelope.message).toContain('--source-guard is a switch and takes no value');+ });++ test('eval longmemeval refuses a value on its own switch instead of turning it on', () => {+ const r = cli(['eval', 'longmemeval', 'data-example.jsonl', '--retrieval-only', '--judge=false']);+ expect(r.status).not.toBe(0);+ expect(r.stderr).toContain('--judge is a switch and takes no value');+ expect(r.stderr).not.toContain('cannot be combined');+ });++ test('--help still answers when an = token would refuse', () => {+ const r = cli(['serve', '--source-guard=true', '--help']);+ expect(r.status).toBe(0);+ expect(r.stdout).toContain('gbrain serve');+ });});