Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Lazy OpenAI model discovery: run before the first OpenAI-routed call, not on connect (#6607); keep setup's Memory line out of the flag registry

garrytanddbd4f6e6f0f
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.md
index 95f75efda1..eef7dffaa6 100644
--- a/docs/architecture/key-files/core-ai.md
+++ b/docs/architecture/key-files/core-ai.md
@@ -28,7 +28,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ai/model-resolver.ts` — Recipe-touchpoint validator. `assertTouchpoint(recipe, touchpoint, modelId)` checks the PROVIDER's capability only (anthropic has no embedding touchpoint; voyage/ollama have no chat) and never gates on the model id. Recipe `models:` arrays are informational — default-model selection (`models[0]` for `--model <provider>` shorthand and env-ready pickers), guard-test fixtures for the repo's own hardcoded defaults, and `gbrain providers list` display — NOT a runtime allowlist, so frontier models newer than a recipe work without a recipe PR. A nonexistent id surfaces as the provider's own `model_not_found` at call time; `gbrain models doctor` live-probes the configured models for a pre-flight check. Exception: `gateway.rerank()` keeps its own model-list check because each listed reranker id maps to a known request/response wire shape. `embeddingDimsForModel` matches recipe `model_dims` keys exactly first, then case-insensitively with BOTH sides folded (configured ids arrive cased, and user-editable recipe tables can carry cased keys; without the fold a cased id would fall through to `default_dims` and `gbrain init` would build a wrong-width column), before falling back to `default_dims`.
-- `src/core/ai/openai-latest.ts` — latest-model discovery: OpenAI defaults are NEVER pinned. `refreshLatestOpenAIModels()` (called from `reconfigureGatewayWithEngine`, TTL 24h, 3s-bounded, fail-open, `GBRAIN_MODEL_DISCOVERY=off|0` kill switch — the test preload sets it; skipped, even forced, when a `gbrain setup` receipt for this install recorded provider use as declined — `providerDeclineRecord` in `src/core/setup/local-receipts.ts`, an unreadable record fails closed) fetches the account's own `GET /v1/models`, ranks ids through a conservative grammar (`parseOpenAIChatId`: bare family aliases `gpt-N.M` + known tier suffixes sol/pro/terra/luna/nano/mini; dated snapshots, `-chat` Instant-class, realtime/image and UNKNOWN future suffixes are ignored — rot degrades to newest-known-shape, never a wrong pick), and maps the newest family onto the tier ladder (utility→cheap, reasoning/subagent→mid, deep→top). ONLY ids with a canonical pricing row are eligible (`rankOpenAIChatModels`'s priced filter): BudgetTracker fails closed (`no_pricing`) under a cost cap, so an unpriced discovered default would brick budget-capped backfills — a newer-unpriced family warns once naming the missing `model-pricing.ts` row. Result lands in `<configDir()>/model-cache.json` (atomic tmp+rename); `latestOpenAITiers()` is the SYNC read (stale cache beats static fallback — TTL gates refresh, never use) consumed by `resolveTierDefault`'s openai entry and the dynamic `gpt` alias. Pinned by `test/openai-latest.serial.test.ts`.
+- `src/core/ai/openai-latest.ts` — latest-model discovery: OpenAI defaults are NEVER pinned. `refreshLatestOpenAIModels()` (called lazily from the gateway's `discoverBeforeOpenAICall`, once per `reconfigureGatewayWithEngine`, just before an OpenAI-routed chat, expansion or embedding call, never on engine connect (#6607: a brain that never calls OpenAI sends nothing even with `OPENAI_API_KEY` set; when the refresh changes the discovered tiers the gateway re-resolves its models before the call reads them), TTL 24h, 3s-bounded, fail-open, `GBRAIN_MODEL_DISCOVERY=off|0` kill switch — the test preload sets it; skipped, even forced, when a `gbrain setup` receipt for this install recorded provider use as declined — `providerDeclineRecord` in `src/core/setup/local-receipts.ts`, an unreadable record fails closed) fetches the account's own `GET /v1/models`, ranks ids through a conservative grammar (`parseOpenAIChatId`: bare family aliases `gpt-N.M` + known tier suffixes sol/pro/terra/luna/nano/mini; dated snapshots, `-chat` Instant-class, realtime/image and UNKNOWN future suffixes are ignored — rot degrades to newest-known-shape, never a wrong pick), and maps the newest family onto the tier ladder (utility→cheap, reasoning/subagent→mid, deep→top). ONLY ids with a canonical pricing row are eligible (`rankOpenAIChatModels`'s priced filter): BudgetTracker fails closed (`no_pricing`) under a cost cap, so an unpriced discovered default would brick budget-capped backfills — a newer-unpriced family warns once naming the missing `model-pricing.ts` row. Result lands in `<configDir()>/model-cache.json` (atomic tmp+rename); `latestOpenAITiers()` is the SYNC read (stale cache beats static fallback — TTL gates refresh, never use) consumed by `resolveTierDefault`'s openai entry and the dynamic `gpt` alias. Pinned by `test/openai-latest.serial.test.ts`.
- `src/core/ai/openrouter-families.ts` — single source of truth for which OpenRouter model families may drive the subagent (tool) loop: `OPENROUTER_SUBAGENT_FAMILIES` (currently `anthropic/` + `deepseek/`, each backed by a live abort/retry replay pin under `test/e2e/`) + `openrouterModelSupportsSubagentLoop(modelId)` (takes the bare OpenRouter id, no `openrouter:` prefix). Shared by the openrouter recipe's predicate and the subagent handler's auto-route so the two can never disagree; a new family gets its own live pin before joining the list.
diff --git a/docs/guides/setup.md b/docs/guides/setup.md
index d3891a4b1e..407a5644c6 100644
--- a/docs/guides/setup.md
+++ b/docs/guides/setup.md
@@ -53,7 +53,8 @@ Provider keys in the environment do not change these defaults.
A declined provider decision holds even when provider keys sit in the
environment: gbrain sends no request to a model provider it was not asked to
-use. OpenAI model discovery (`GET /v1/models` on engine connect) is skipped,
+use. OpenAI model discovery (`GET /v1/models`, which otherwise runs only before
+the first OpenAI-routed call) is skipped,
and `gbrain doctor --probe` does not probe the embedding provider. `gbrain
doctor` reports the decision as `provider_consent` ("skipped by consent").
Only the user changes it: `gbrain setup claude-code --providers` records
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index f7f8230d4a..4067ab06e8 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -11,7 +11,7 @@ src/commands/extract-conversation-facts.ts 2075 ratchet grown v0.46.x per-provid
src/commands/extract.ts 2637 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page; +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale; +25 GBRA-69: extract --source db reads snapshots and publishes derived links BATCH_SIZE pages at a time (readPageSnapshotsBatch in core/page-snapshot-batch.ts, replay in derived-links.ts replaceDerivedLinksBatchOrReplay); +2 GBRA-75 w7: the --source db links walk refreshes planner statistics (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 13 P2.16 (#6272): both unmanaged DB link drains defer and count a page a concurrent writer moved (skipped_concurrent_write) instead of aborting the run (classifier and skip line in core/derived-links.ts); +3 fix wave 13 P2.18 (S4): extract all --source db stamps the pages both phases completed at one revision, in a finally (stampCompletedIntersection), instead of every links-phase page; +1 fix wave 13 P2.15 (#6273): --from-meetings exits non-zero while managed entity pages are still pending; +7 fix wave 13 PR2: extractFromDB split out of runExtract so runExtract stays under its function-size baseline
src/commands/jobs.ts 666 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codes
src/commands/serve-http.ts 931 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts)
-src/core/ai/gateway.ts 4511 ratchet +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base)
+src/core/ai/gateway.ts 4528 ratchet +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base)
src/commands/sync.ts 519 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts)
src/core/cycle.ts 3303 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts)
src/core/cycle/synthesize.ts 3228 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import)
diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsv
index c8d6319c12..bd6cc934fc 100644
--- a/scripts/serial-files.tsv
+++ b/scripts/serial-files.tsv
@@ -274,6 +274,7 @@ test/native-base-url-fold.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME
test/nightly-probe-compiled-binary.serial.test.ts global-state global-state: compiles a probe harness with bun build --compile and runs it plus a source-mode copy as subprocesses
test/oauth-client-setup.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnect
test/observational-startup.serial.test.ts R2 R2: mock.module(../src/cli/commands/repair.ts) replaces modules for every file in the process
+test/openai-discovery-lazy.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, OPENAI_API_KEY, GBRAIN_MODEL_DISCOVERY); binds a local server
test/openai-latest.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_MODEL_DISCOVERY)
test/openclaw-compact-transcript-runtime.serial.test.ts global-state global-state: swaps the context engine's module-level transcript-runtime loader and SDK load state
test/openclaw-context-engine-native.serial.test.ts global-state global-state: binds local servers/ports
diff --git a/src/commands/setup.ts b/src/commands/setup.ts
index 75a73cebdb..3ba6e0414e 100644
--- a/src/commands/setup.ts
+++ b/src/commands/setup.ts
@@ -610,8 +610,8 @@ async function finish(out: Out, doc: {
if (state && !doc.remove) say(out, harness === 'codex'
? 'Next: start a new Codex session (config and hooks are read at session start) and check that /mcp lists gbrain.'
: 'Next: open a new Claude Code session (config is read at session start) and check that /mcp lists gbrain.');
- if (state && !doc.remove) say(out, 'Memory: save what the user asks you to remember as a fact: gbrain remember "<fact>" --entity <slug> --provenance "<where>" (MCP tool: remember). '
- + 'World-visible facts (the default) are pushed into new sessions; --visibility private keeps a fact out of them (local CLI recall only). capture writes a page, not a fact.');
+ if (state && !doc.remove) say(out, 'Memory: save what the user asks you to remember as a fact with gbrain remember "<fact>", naming its entity and provenance (MCP tool: remember). '
+ + 'World-visible facts (the default) are pushed into new sessions; a private fact is not (local CLI recall only). capture writes a page, not a fact.');
writeCliNotices(doc.notices);
return 0;
}
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index e841fd5f8d..74d5845506 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -535,31 +535,47 @@ export function refreshGatewayEnvFromFilePlane(): void {
* config for callers who want to inspect what landed.
*/
export async function reconfigureGatewayWithEngine(engine: BrainEngine): Promise<AIGatewayConfig> {
+ _discoveryEngine = engine;
+ _discovery = null;
+ return resolveGatewayModels(engine);
+}
+
+let _discoveryEngine: BrainEngine | null = null;
+let _discovery: Promise<void> | null = null;
+
+/**
+ * #6607: OpenAI model discovery runs once per reconfigure, just before an
+ * OpenAI-routed call, never on connect (a brain that never calls OpenAI sends
+ * nothing). TTL, backoff, decline and kill switch live in openai-latest.ts.
+ * Changed tiers re-resolve the models first. Endpoint: OPENAI_BASE_URL (env
+ * plane), never DB-mergeable base_urls, so a shared brain cannot redirect the
+ * key. Fail-open.
+ */
+async function discoverBeforeOpenAICall(modelStr: string | undefined): Promise<void> {
+ if (!modelStr) return;
+ try { if (resolveRecipe(modelStr).recipe.id !== 'openai') return; } catch { return; }
+ _discovery ??= (async () => {
+ try {
+ const cfg = requireConfig();
+ const { refreshLatestOpenAIModels, latestOpenAITiers } = await import('./openai-latest.ts');
+ const before = JSON.stringify(latestOpenAITiers());
+ await refreshLatestOpenAIModels({ env: cfg.env ?? process.env, baseUrl: resolveNativeBaseUrl('openai', cfg) });
+ if (_discoveryEngine && JSON.stringify(latestOpenAITiers()) !== before) await resolveGatewayModels(_discoveryEngine);
+ } catch {
+ // Fail-open: the call proceeds on the models already resolved.
+ }
+ })();
+ await _discovery;
+}
+
+async function resolveGatewayModels(engine: BrainEngine): Promise<AIGatewayConfig> {
const cfg = requireConfig();
- // Refresh the OpenAI latest-model discovery cache BEFORE resolution so the
- // key-aware tier defaults below see it. TTL-throttled (one fetch/24h),
- // 3s-bounded, fail-open, disabled in test lanes via GBRAIN_MODEL_DISCOVERY
- // — a connect never blocks on or breaks from discovery.
- const { refreshLatestOpenAIModels } = await import('./openai-latest.ts');
- // Discovery hits the same endpoint real native-openai calls use:
- // OPENAI_BASE_URL via resolveNativeBaseUrl — the ENV PLANE, deliberately
- // NOT cfg.base_urls.openai. Two reasons: (1) defaulting to api.openai.com
- // when a custom endpoint is configured would send that endpoint's key to
- // the official host; (2) base_urls can be DB-plane-merged from a mounted
- // brain, and discovery fires automatically on connect — a hostile shared
- // brain must never be able to point this process's bearer key at an
- // attacker URL (native chat calls ignore base_urls for the same reason).
- await refreshLatestOpenAIModels({
- env: cfg.env ?? process.env,
- baseUrl: resolveNativeBaseUrl('openai', cfg),
- });
// The two resolutions below each walk a 5-tier precedence chain that reads
// up to 4 config keys, plus alias expansion. Against the engine that is
// many sequential round trips before the CLI does any work — seconds of
// `gbrain stats`'s wall clock on a hosted brain, for reads the server
- // answered in microseconds. Take one snapshot of the config table (AFTER
- // the discovery refresh above, so tier defaults see fresh discovery) and
+ // answered in microseconds. Take one snapshot of the config table and
// resolve every model against it. Same keys, same precedence, one round
// trip.
const reader = await snapshotConfigReader(engine);
@@ -693,6 +709,8 @@ export function __setGatewayResetBaselineForTests(
/** Clear every piece of module state. Shared by both reset flavors. */
function clearGatewayState(): void {
_config = null;
+ _discoveryEngine = null;
+ _discovery = null;
clearGatewayModelSources();
stashGatewayAnthropicKeyFromEnv(undefined); // gateway-owned snapshot dies with the config
_modelCache.clear();
@@ -1406,6 +1424,7 @@ function noKeyOnce(modelStr: string, keyName: string, query: string, docCount: n
}
async function resolveEmbeddingProvider(modelStr: string): Promise<{ model: any; recipe: Recipe; modelId: string }> {
+ await discoverBeforeOpenAICall(modelStr);
const { parsed, recipe } = resolveRecipe(modelStr);
assertTouchpoint(recipe, 'embedding', parsed.modelId);
const cfg = requireConfig();
@@ -2343,6 +2362,7 @@ export async function embedMultimodalSafe(
// ---- Expansion ----
async function resolveExpansionProvider(modelStr: string): Promise<{ model: any; recipe: Recipe; modelId: string }> {
+ await discoverBeforeOpenAICall(modelStr);
const { parsed, recipe } = resolveRecipe(modelStr);
assertTouchpoint(recipe, 'expansion', parsed.modelId);
const cfg = requireConfig();
@@ -2500,6 +2520,7 @@ export async function expand(query: string): Promise<string[]> {
});
try {
+ await discoverBeforeOpenAICall(_config?.expansion_model);
const requestedModelId = getExpansionModel();
const { model, recipe, modelId } = await resolveExpansionProvider(requestedModelId);
const modelLabel = `${recipe.id}:${modelId}`;
@@ -3265,6 +3286,7 @@ function chatSupportsPromptCache(recipe: Recipe, modelId: string): boolean {
}
async function resolveChatProvider(modelStr: string): Promise<{ model: any; recipe: Recipe; modelId: string }> {
+ await discoverBeforeOpenAICall(modelStr);
const { parsed, recipe } = resolveRecipe(modelStr);
assertTouchpoint(recipe, 'chat', parsed.modelId);
const cfg = requireConfig();
@@ -3514,6 +3536,7 @@ export function toAISDKTools(tools: ChatToolDef[] | undefined): Record<string, a
}
export async function chat(opts: ChatOpts): Promise<ChatResult> {
+ await discoverBeforeOpenAICall(opts.model ?? _config?.chat_model);
const fallbackChain = opts.allowFallback === false ? undefined : _config?.chat_fallback_chain;
if (fallbackChain?.length) return chatWithFallback(opts, opts.model ?? getChatModel(), fallbackChain, chat, { onRefusal: _config?.chat_fallback_on_refusal !== false });
const tracker = __budgetStore.getStore() ?? null;
diff --git a/src/core/ai/openai-latest.ts b/src/core/ai/openai-latest.ts
index e85926fcfe..75ddbea52e 100644
--- a/src/core/ai/openai-latest.ts
+++ b/src/core/ai/openai-latest.ts
@@ -325,8 +325,9 @@ export interface RefreshOpts {
* Best-effort by contract: never throws, never blocks longer than
* FETCH_TIMEOUT_MS, no-ops without a key, with GBRAIN_MODEL_DISCOVERY=off, or
* when a `gbrain setup` receipt recorded provider use as declined.
- * Call sites: reconfigureGatewayWithEngine (engine connect) and — through
- * it — the jobs worker's per-job gateway refresh.
+ * Call site: the gateway's discoverBeforeOpenAICall, once per reconfigure,
+ * when an OpenAI-routed call is about to go out (#6607: never on engine
+ * connect, so a brain that never calls OpenAI sends nothing).
*/
export async function refreshLatestOpenAIModels(opts: RefreshOpts = {}): Promise<void> {
const disc = process.env.GBRAIN_MODEL_DISCOVERY;
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 746f3d696b..e2cb669f02 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -535,7 +535,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
// GBRA-81 item 5 (per-stage search timings). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
{ since: '0.60.205.0', text: 'Every `search` and `query` response now carries `_meta.retrieval.timings` (integer milliseconds per stage, `other_ms` and the operation total), and the CLI explain view of `gbrain search` and `gbrain query` prints them as a `timings:` line; results are unchanged and the timings never appear in result text.' },
// Cat 41 first push (#6606, GBRA-60). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
- { since: '0.60.205.0', text: '`gbrain remember --visibility private` from the local CLI now says the fact is recall-only: a `note: private` line and a `private_fact_not_pushed` agent notice naming the world re-save, because session hooks push world-visible facts only. `gbrain --help` lists `remember`, `recall` and `forget` in a MEMORY section, and `gbrain setup` prints a `Memory:` line after `Next:` naming `remember`. What is saved and what is pushed are unchanged.' },
+ { since: '0.60.205.0', text: 'A `gbrain remember` call with visibility private from the local CLI now says the fact is recall-only: a `note: private` line and a `private_fact_not_pushed` agent notice naming the world re-save, because session hooks push world-visible facts only. `gbrain --help` lists `remember`, `recall` and `forget` in a MEMORY section, and `gbrain setup` prints a `Memory:` line after `Next:` naming `remember`. What is saved and what is pushed are unchanged.' },
+ // Cat 41 consent (#6607, GBRA-60). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
+ { since: '0.60.205.0', text: 'OpenAI model discovery (the unbilled `GET /v1/models` request that picks the newest OpenAI model for each tier) no longer runs on every engine connect when `OPENAI_API_KEY` is set. It runs just before the first OpenAI-routed chat, expansion or embedding call in a process, with the same 24-hour cache, so a brain that never calls OpenAI (a keyless brain running `gbrain doctor` or `gbrain search`) sends nothing. An install that uses OpenAI gets the same discovered models; the call that triggers discovery already runs on them. A recorded provider decline still stops it.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 7adbe31964..bd69138a31 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -47,7 +47,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--autostash', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--visibility', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-pending', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--autostash', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--expand', '--expect', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--get', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--providers', '--prune-orphans', '--pull', '--pure', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@ -61,7 +61,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply', '--apply-preview', '--background', '--backup-verified', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--client', '--concurrency', '--confirm', '--confirm-relocated-root', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--from-meetings', '--help', '--http', '--id', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--page', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--wait', '--workers', '--yes'],
'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--brain', '--concurrency', '--confirm-destructive', '--confirm-relocated-root', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-autopilot-install', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],
'facts': ['--admin-intent', '--after-id', '--brain', '--dry-run', '--entity', '--examples', '--expected-state', '--help', '--include-private', '--json', '--limit', '--max-cost-usd', '--max-usd', '--no-conflict-queue', '--no-llm', '--path', '--retry-model', '--since', '--slug', '--source'],
- 'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--embedding-model', '--expect', '--explain', '--facts', '--force', '--from-meetings', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--visibility', '--workers', '--yes'],
+ 'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--embedding-model', '--expect', '--explain', '--facts', '--force', '--from-meetings', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--workers', '--yes'],
'feedback': ['--brain', '--help', '--json', '--page', '--source'],
'files': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--no-pointer', '--page', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--source', '--timeout', '--type', '--wait', '--yes'],
'forget': ['--all-subjects', '--brain', '--dry-run', '--help', '--json', '--match', '--purge', '--reason', '--request-id', '--source', '--status', '--vacuum', '--yes'],
@@ -73,7 +73,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],
'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],
- 'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--visibility', '--wait', '--warn-only', '--workspace', '--yes'],
+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--all', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expand', '--expansion-model', '--expect-remote', '--facts', '--fast', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-pull', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--resolve', '--resume', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],
'jobs': ['--abbrev-ref', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-quiesced', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
@@ -87,7 +87,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],
'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--status', '--target-high', '--target-low', '--target-medium'],
'notices': ['--brain', '--help', '--json', '--source'],
- 'onboard': ['--access', '--add', '--allowed-operations', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--check', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-pages', '--full', '--fuzzy', '--help', '--history', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--only', '--page', '--params', '--path', '--phase', '--probe', '--purge', '--recent', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--row', '--save', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--to', '--updated-after', '--url', '--visibility', '--yes'],
+ 'onboard': ['--access', '--add', '--allowed-operations', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--check', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--from-pages', '--full', '--fuzzy', '--help', '--history', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--only', '--page', '--params', '--path', '--phase', '--probe', '--purge', '--recent', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--row', '--save', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--to', '--updated-after', '--url', '--yes'],
'orphans': ['--accept-pending', '--background', '--brain', '--count', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--older-than', '--source', '--yes'],
'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--path', '--probe', '--source', '--vectors', '--yes'],
@@ -118,7 +118,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],
'self-upgrade': ['--brain', '--check-only', '--ff-only', '--force', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--non-interactive', '--refresh-cache', '--remediation-plan', '--source', '--swap-only', '--version', '--yes'],
'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--all-new', '--apply-rewrites', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--migrate-legacy', '--min-trust', '--no-embedding', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--scopes', '--source', '--source-guard', '--sources', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],
- 'setup': ['--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--dry-run', '--entity', '--env', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--pglite', '--probe', '--provenance', '--providers', '--pure', '--remove', '--save', '--scope', '--source', '--surface', '--token', '--url', '--visibility', '--yes'],
+ 'setup': ['--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--dry-run', '--env', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--pglite', '--probe', '--providers', '--pure', '--remove', '--save', '--scope', '--source', '--surface', '--token', '--url', '--yes'],
'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],
'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--max-usd', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],
'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],
@@ -130,7 +130,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--session', '--source', '--timeout', '--wait'],
'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--exclude', '--exclude-standard', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--once', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
'takes': ['--accept', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
- 'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--take', '--until', '--visibility', '--with-calibration'],
+ 'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],
'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],
'trust': ['--accept-all', '--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--follow', '--from', '--help', '--http', '--json', '--kind', '--no-accept-pending', '--only', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--remove', '--resume', '--since', '--source', '--source-id', '--timeout', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],
'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-pull', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--search-mode', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--wait', '--warn-only', '--workers', '--yes'],
diff --git a/src/core/interop-notices.ts b/src/core/interop-notices.ts
index d2bbe3064f..0d1d9f0612 100644
--- a/src/core/interop-notices.ts
+++ b/src/core/interop-notices.ts
@@ -277,7 +277,7 @@ export function privateFactNotice(factId?: string | number): Notice {
return {
code: 'private_fact_not_pushed',
kind: 'info',
- why: `This fact is private: only local CLI recall reads it. Session hooks push world-visible facts only, so it will not reach a new agent session, and MCP agents cannot recall it. If the user wants their agents to know it without looking it up, ask them before saving it again with \`--visibility world\`${forget}.`,
+ why: `This fact is private: only local CLI recall reads it. Session hooks push world-visible facts only, so it will not reach a new agent session, and MCP agents cannot recall it. If the user wants their agents to know it without looking it up, ask them before saving it again with visibility world${forget}.`,
};
}
diff --git a/src/core/model-config.ts b/src/core/model-config.ts
index 5bc5ddde2c..606d3fb1e5 100644
--- a/src/core/model-config.ts
+++ b/src/core/model-config.ts
@@ -126,7 +126,7 @@ export function openaiStaticTierFallback(): Record<ModelTier, string> {
* TIER_DEFAULTS unchanged (keyless installs degrade honestly downstream).
*
* OpenAI tiers are RESOLVED PER CALL, never pinned: the account-discovered
- * latest (openai-latest.ts cache, refreshed at gateway connect) wins, the
+ * latest (openai-latest.ts cache, refreshed before the first OpenAI-routed gateway call, #6607) wins, the
* recipe-derived static ranking is the offline floor. The subagent tier runs
* without prompt caching on OpenAI → enforceSubagentCapable emits the
* degraded:no_caching cost warn.
diff --git a/test/doctor-provider-consent.serial.test.ts b/test/doctor-provider-consent.serial.test.ts
index 7ec8d43280..8cd1594603 100644
--- a/test/doctor-provider-consent.serial.test.ts
+++ b/test/doctor-provider-consent.serial.test.ts
@@ -2,10 +2,13 @@
* Cat 41 wave 2 consent negative: with provider keys in the environment and
* `gbrain setup`'s provider-use decision recorded as declined, `gbrain doctor`
* sent one unbilled `GET /v1/models` with the user's key in every run. The
- * request was OpenAI model discovery, which runs on every engine connect
+ * request was OpenAI model discovery, which ran on every engine connect
* (src/core/ai/openai-latest.ts). Now a recorded decline stops discovery and
* the opt-in embedding probe, and doctor reports `provider_consent` as
- * skipped by consent with the fix that records acceptance.
+ * skipped by consent with the fix that records acceptance. Since #6607
+ * discovery runs only before an OpenAI-routed call, so plain doctor sends
+ * nothing either way; the embedding probe is the OpenAI-routed call the
+ * controls and the decline are measured on.
*
* Subprocess: `bun src/cli.ts` against a fresh PGLite home, OPENAI_BASE_URL
* pointed at an in-process server that counts every request. The control runs
@@ -96,9 +99,12 @@ beforeEach(() => {
});
describe('doctor with provider keys present', () => {
- test('control: with no recorded decision, doctor contacts the provider (model discovery)', async () => {
+ test('control: with no recorded decision, plain doctor sends nothing and an OpenAI-routed call discovers first (#6607)', async () => {
const run = await gbrain(['doctor', '--json'], providerEnv());
- expect(requests).toContain('GET /v1/models');
+ expect(requests).toEqual([]);
+ setConfig({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536 }, ['embedding_disabled']);
+ await gbrain(['doctor', '--only', 'embedding_provider', '--probe', '--yes', '--json'], providerEnv());
+ expect(requests.slice(0, 2)).toEqual(['GET /v1/models', 'POST /v1/embeddings']);
const check = checksOf(run.stdout).find((c) => c.name === 'provider_consent');
expect(check?.status).toBe('ok');
expect(check?.readiness_state).toBe('not_applicable');
@@ -139,9 +145,12 @@ describe('doctor with provider keys present', () => {
expect((check.fix as { argv: string[] }).argv).toEqual(['gbrain', 'setup', 'claude-code', '--providers']);
}, 180_000);
- test('setup accepted provider use: discovery runs as before', async () => {
+ test('setup accepted provider use: discovery runs before the first OpenAI-routed call', async () => {
writeReceipt('accepted');
const run = await gbrain(['doctor', '--json'], providerEnv());
+ expect(requests).toEqual([]);
+ setConfig({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536 }, ['embedding_disabled']);
+ await gbrain(['doctor', '--only', 'embedding_provider', '--probe', '--yes', '--json'], providerEnv());
expect(requests).toContain('GET /v1/models');
expect(checksOf(run.stdout).find((c) => c.name === 'provider_consent')?.details).toMatchObject({ decision: 'accepted' });
}, 180_000);
diff --git a/test/openai-discovery-lazy.serial.test.ts b/test/openai-discovery-lazy.serial.test.ts
new file mode 100644
index 0000000000..004b1140d8
--- /dev/null
+++ b/test/openai-discovery-lazy.serial.test.ts
@@ -0,0 +1,121 @@
+/**
+ * #6607 (Cat 41 consent-negative): OpenAI latest-model discovery
+ * (`GET /v1/models`, unbilled) ran on every engine connect whenever
+ * OPENAI_API_KEY was set, so `gbrain doctor` on an existing keyless brain that
+ * never ran setup sent it with the user's key. Discovery now runs only before
+ * an OpenAI-routed gateway call. A request counter stands in for the OpenAI
+ * endpoint (OPENAI_BASE_URL): a keyless brain's doctor and search send
+ * nothing, an OpenAI-routed chat sends one discovery request (once per
+ * reconfigure) and the call itself runs on the freshly discovered tier, an
+ * Anthropic-routed chat sends none.
+ *
+ * Serial: mutates process env, GBRAIN_HOME and gateway module state.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { runCli } from './helpers/cli-spawn.ts';
+import { withEnv } from './helpers/with-env.ts';
+import {
+ __setChatTransportForTests,
+ chat,
+ configureGateway,
+ getChatModel,
+ reconfigureGatewayWithEngine,
+ resetGateway,
+} from '../src/core/ai/gateway.ts';
+import { _resetOpenAILatestForTests, latestOpenAITiers } from '../src/core/ai/openai-latest.ts';
+import { openaiStaticTierFallback } from '../src/core/model-config.ts';
+
+const requests: string[] = [];
+let server: ReturnType<typeof Bun.serve>;
+let base: string;
+const roots: string[] = [];
+
+beforeAll(() => {
+ server = Bun.serve({
+ port: 0,
+ fetch(req) {
+ requests.push(`${req.method} ${new URL(req.url).pathname}`);
+ return Response.json({ data: [{ id: 'gpt-5.6' }, { id: 'gpt-5.6-luna' }] });
+ },
+ });
+ base = `http://127.0.0.1:${server.port}/v1`;
+});
+afterAll(() => {
+ server.stop(true);
+ for (const r of roots) rmSync(r, { recursive: true, force: true });
+});
+
+function tempHome(): string {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-lazy-discovery-'));
+ roots.push(dir);
+ return dir;
+}
+
+const NO_KEYS = { OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined, VOYAGE_API_KEY: undefined, GEMINI_API_KEY: undefined,
+ GOOGLE_GENERATIVE_AI_API_KEY: undefined, OPENAI_BASE_URL: undefined, GBRAIN_MODEL_DISCOVERY: undefined };
+
+describe('an existing keyless brain with OPENAI_API_KEY in the environment (#6607)', () => {
+ test('doctor and search send no model-discovery request', async () => {
+ const home = tempHome();
+ const init = await runCli(['init', '--pglite', '--no-embedding', '--json'], { home, env: NO_KEYS, timeoutMs: 120_000 });
+ expect(init.exitCode).toBe(0);
+ requests.length = 0;
+ const keyed = { ...NO_KEYS, OPENAI_API_KEY: 'sk-test-discovery', OPENAI_BASE_URL: base };
+ await runCli(['doctor', '--json'], { home, env: keyed, timeoutMs: 120_000 });
+ await runCli(['search', 'anything'], { home, env: keyed, timeoutMs: 120_000 });
+ expect(requests).toEqual([]);
+ }, 300_000);
+});
+
+describe('OpenAI-routed calls still discover, at first use', () => {
+ class StubEngine {
+ readonly kind = 'pglite' as const;
+ async getConfig() { return null; }
+ async setConfig() {}
+ }
+ const reply = () => ({ text: 'ok', blocks: [], stopReason: 'end', usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: getChatModel(), providerId: 'test' }) as never;
+ let home: string;
+ beforeEach(() => {
+ home = tempHome();
+ requests.length = 0;
+ resetGateway();
+ _resetOpenAILatestForTests();
+ __setChatTransportForTests(async () => reply());
+ });
+ afterEach(() => {
+ __setChatTransportForTests(null);
+ resetGateway();
+ _resetOpenAILatestForTests();
+ });
+
+ test('connect sends nothing; the first OpenAI chat discovers once and runs on the discovered tier', async () => {
+ await withEnv({ ...NO_KEYS, GBRAIN_HOME: home, OPENAI_API_KEY: 'sk-test-discovery' }, async () => {
+ configureGateway({ env: { OPENAI_API_KEY: 'sk-test-discovery', OPENAI_BASE_URL: base } });
+ await reconfigureGatewayWithEngine(new StubEngine() as never);
+ expect(requests).toEqual([]);
+ expect(getChatModel()).toBe(openaiStaticTierFallback().reasoning);
+ let called = '';
+ __setChatTransportForTests(async () => { called = getChatModel(); return reply(); });
+ await chat({ messages: [{ role: 'user', content: 'hi' }] });
+ expect(requests).toEqual(['GET /v1/models']);
+ const discovered = latestOpenAITiers('reasoning');
+ expect(typeof discovered).toBe('string');
+ expect(discovered).not.toBe(openaiStaticTierFallback().reasoning);
+ expect(called).toBe(discovered as string);
+ await chat({ messages: [{ role: 'user', content: 'again' }] });
+ expect(requests).toEqual(['GET /v1/models']);
+ });
+ });
+
+ test('an Anthropic-routed chat sends no discovery request', async () => {
+ await withEnv({ ...NO_KEYS, GBRAIN_HOME: home, OPENAI_API_KEY: 'sk-test-discovery' }, async () => {
+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: { OPENAI_API_KEY: 'sk-test-discovery', OPENAI_BASE_URL: base, ANTHROPIC_API_KEY: 'sk-ant-test' } });
+ await chat({ messages: [{ role: 'user', content: 'hi' }] });
+ expect(requests).toEqual([]);
+ });
+ });
+});
diff --git a/test/remember-private-not-pushed.test.ts b/test/remember-private-not-pushed.test.ts
index be75ad606a..6e7159ec6c 100644
--- a/test/remember-private-not-pushed.test.ts
+++ b/test/remember-private-not-pushed.test.ts
@@ -51,7 +51,7 @@ describe('remember --visibility private says the fact is not pushed (#6606)', ()
const notice = notices.find(n => n.code === 'private_fact_not_pushed');
expect(notice).toBeDefined();
expect(notice!.why).toContain('will not reach a new agent session');
- expect(notice!.why).toContain('saving it again with `--visibility world`');
+ expect(notice!.why).toContain('saving it again with visibility world');
expect(notice!.why).toContain(`\`gbrain forget ${result.id}\` drops the private copy`);
expect(formatRememberResult(result, { visibility: 'private' })).toContain('note: private — local CLI recall only; not pushed into new agent sessions');
});
diff --git a/test/setup.test.ts b/test/setup.test.ts
index a0709f9355..e5139b053e 100644
--- a/test/setup.test.ts
+++ b/test/setup.test.ts
@@ -116,13 +116,13 @@ describe('gbrain setup claude-code: install lifecycle', () => {
const r = await setup(b, ['claude-code']);
expect(r.exitCode).toBe(0);
const next = r.stdout.indexOf('Next: open a new Claude Code session');
- const memory = r.stdout.indexOf('Memory: save what the user asks you to remember as a fact: gbrain remember "<fact>" --entity <slug>');
+ const memory = r.stdout.indexOf('Memory: save what the user asks you to remember as a fact with gbrain remember "<fact>", naming its entity and provenance');
expect(next).toBeGreaterThan(-1);
expect(memory).toBeGreaterThan(next);
expect(r.stdout.indexOf('[AGENT]')).toBeGreaterThan(memory);
const line = r.stdout.slice(memory).split('\n')[0];
expect(line).toContain('pushed into new sessions');
- expect(line).toContain('--visibility private keeps a fact out of them');
+ expect(line).toContain('a private fact is not (local CLI recall only)');
expect(line).toContain('capture writes a page, not a fact');
});