Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(search): a brain that opted out of embedding never sends query text to the provider

garrytand3b63c65c73e
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.md
index d6307154dc..e924713bca 100644
--- a/docs/architecture/key-files/agent-contract.md
+++ b/docs/architecture/key-files/agent-contract.md
@@ -20,7 +20,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-
- `test/cli-contract.test.ts` — D5: `--help` contract for every command-table record (exit 0, non-stub, curated flags only, `--yes` shown where parsed) against the shrink-only `test/fixtures/cli-contract/help-baseline.json`, and one success + one failure row per `json`-declared record.
- `src/cli/json-guard.ts` — picks the `--json` guard mode for an invocation: on only when `jsonRequested(argv)` and the command-table record declares `json: 'document' | 'ndjson'`; wires the E11 `json_document_missing` hook. The guard itself is `installStdoutPipeDelivery({ json })` in `src/core/cli-force-exit.ts`: stdout writes and console.log/info/debug go to stderr, only `writeStdoutFinal`/`writeNdjsonLine` reach fd 1, a non-zero exit with no document writes the fallback document, `spawnCliChild` pipes child stdout to stderr. Test: `test/cli-json-guard.test.ts`. A record whose subcommands differ in shape declares `jsonSubcommands` (keyed by the first positional after the command; `eval`). `writeCliError` adds `status:'error'` to the envelope under the ndjson guard; `writeCliRefusal` (cli-error.ts) keeps a site's pre-v1 stderr line and writes the envelope under `--json`. D5 (`test/cli-contract.test.ts`) has one row per declaration, `<command> <sub>` included.
- `scripts/check-agent-contract.ts` — syntax-only AST scanner (≈2 s) in `bun run verify` and `guards-manifest.tsv` (fixtures `test/fixtures/guards/check-agent-contract.ts/`). Rules: suggestion-less `OperationError`, `throw new Error` in ops/mcp/handlers, hand-built `fix`/`next_action` command strings, legacy advice keys, raw interactive stdin/readline/raw-mode outside `interaction.ts`/`consent.ts`, raw "re-run with --yes" strings outside `consent.ts`, `stdio: 'inherit'` outside `spawnCliChild`, marker literals outside `agent-output.ts`/`agent-markers.ts`, `verify.argv` naming a non-read-only command (read_only command-table records + a static read-only list), plus unregistered codes and code naming (never baselined). Two more never-baselined rules keep every refusal's next step site-specific: `defaulted-suggestion` (a function that builds an error through `opError`, `new OperationError`, `usageError`, `invalidParam` or `hostOnlyError` from a `*suggestion`/`*hint` parameter with a default, an optional marker or a `??` fallback) and `generic-suggestion` (a suggestion whose whole text is a denylisted phrase such as "see --help", "check your input" or "try again", at a constructor or at a call site of a file-local funnel). `funnelSites(files?)` lists every funnel call site (`invalid`, `fail`, `usage`, `deny`, …) with its literal suggestion texts, resolving file-level string constants; `test/helpers/agent-envelope.ts` (`expectFunnelSuggestions`, `envelopeFor`, `caught`) drives the per-funnel table tests in each module's owner test. Per-rule shrink-only baselines in `scripts/agent-contract-baselines/<rule>.tsv`; `--update` lowers them and refuses growth.
-- `src/core/interop-notices.ts` — Lane F notice producers (pure; callers emit). `DEGRADED_STAGE_GUIDANCE` (closed, typed exhaustive over recall-affecting stages + the verbs' markers) → one `degraded_recall` notice (kind degraded: names the stages, says a thin result is not proof of absence; fix = the embeddings enablement or a doctor diagnostic; none on a brain keyless by choice). `sourceBindingNarrowedNotice` (per-call info: a GBRAIN_SOURCE/.gbrain-source bound stdio read that came back empty while other sources are readable; fix = the explicit `source_id` read). `recallInteropNotices` is dispatch's one producer call. `chatKeyFix` (credentials + paid, both providers, free fallback, never a key on a command line), `keylessThinkNotice`, `thinkNotSavedNotice`, `degradedDedupNotice`, `writeCliNotices` (terminal lines / `[AGENT]` block for non-interactive callers). Test: `test/mcp-notice-channels.test.ts`.
+- `src/core/interop-notices.ts` — Lane F notice producers (pure; callers emit). `DEGRADED_STAGE_GUIDANCE` (closed, typed exhaustive over recall-affecting stages + the verbs' markers) → one `degraded_recall` notice (kind degraded: names the stages, says a thin result is not proof of absence; fix = the embeddings enablement or a doctor diagnostic; none on a brain keyless by choice, whose why says no query text was sent and that `gbrain doctor --json` names the enable command). `embeddingOptedOutFor` reads the opt-out markers (search/query degraded reason `embedding_disabled`, recall `keyword_only_embedding_disabled`, think `QUESTION_EMBED_SKIPPED_EMBEDDING_DISABLED`); `factEmbeddingDisabled` (src/core/embedding-disabled.ts) gates every query and fact embed. `sourceBindingNarrowedNotice` (per-call info: a GBRAIN_SOURCE/.gbrain-source bound stdio read that came back empty while other sources are readable; fix = the explicit `source_id` read). `recallInteropNotices` is dispatch's one producer call. `chatKeyFix` (credentials + paid, both providers, free fallback, never a key on a command line), `keylessThinkNotice`, `thinkNotSavedNotice`, `degradedDedupNotice`, `writeCliNotices` (terminal lines / `[AGENT]` block for non-interactive callers). Test: `test/mcp-notice-channels.test.ts`.
- `src/mcp/status-mode.ts` + `src/commands/serve-status.ts` + `src/commands/serve-http-status.ts` + `src/core/serve-http-status-marker.ts` — F4 status-only serve, stdio and `--http`. cli.ts hands over a host-brain `serve` (not `--fail-fast`/`GBRAIN_SERVE_FAIL_FAST=1`) with no config, an unreadable config, a missing or repair-failed brain, or a PGLite lock held by a live holder; `runStatusModeServe` is the one entry point for both transports and logs `serve_status_mode_enter` / `serve_status_mode_recovered` (`reason`, `transport`, `elapsed_ms`) as one-line JSON on stderr. `probeStatus` reads config + `peekLock` only; `reprobe(state, connect)` is the one re-probe (no lock attempt while blocked, `resetReadinessMemo()` before the throw-only connect from `src/core/engine-connect.ts`); a check that must run on every re-probe hooks the `probeAgain` wrapper in `runStatusModeServe`. stdio: a gated lazy engine (`createDegradedEngine` with the configured `kind`, reconnect `statusReconnect`, ≤1 attempt / 5 s inside tool calls) marked with `StatusModeState`; `statusPayload` → `{status, reason, why (lock owner PID/transport, brain path, config path), fix, user_message, decisions, share_http_plan}`. `--http`: `runHttpStatusServe` binds one `node:http` listener with a mutable handler (`/health` 503 + `Retry-After: 5` + `instance`; `/mcp` stateless SDK server with only `gbrain_status`; every other route a 503 `serve_status_only` envelope), each response built from the allowlist in `httpStatusPayload`/`httpStatusEnvelope` with `reason` collapsed to `unavailable`; a single-flight chained 5 s tick runs the re-probe, and on a connect `runServe(..., { adoptServer })` builds the full app and swaps the handler on the same listener; a failed build disconnects the engine and stays status-only (`brain_unopenable`); SIGINT/SIGTERM during a recovery waits for it, then closes once. The marker `GBRAIN_HOME/serve-http-status-<port>.json` `{pid, instance_nonce, brain_id, bind, port, reason, since}` is removed only by its own instance; live = PID alive and written after the last boot (readiness), plus `/health` 503 with the nonce within 500 ms (`verifiedStatusMarkers`, doctor, which deletes dead markers). `statusFix(state, transport)` words the fix for how the server re-checks. A recovered HTTP server answers authenticated `gbrain_status` (read scope, never listed) with `status: recovered`. Tests: `test/serve-status-mode.serial.test.ts` (stdio recover → recall; shared `serve --http`; no brain → init; `--fail-fast`; stdio transition lines; Postgres `--http` keeps the degraded path), `test/serve-http-status-mode.serial.test.ts` (HTTP journey, doctor, thin client, recovery with re-auth, `serve_port_in_use`, no-config recovery, stale marker, single-flight tick, failed build, shutdown during recovery, two-port markers).
- `src/mcp/initialize-context.ts` — per-initialize inputs for the generated instructions (`httpInstructionTools`: the tools/list filters with publish gates read on initialize; `instructionReadiness`: config plane + probed tier within 250 ms, HTTP view redacted) and `stdioCapabilityReadiness` (F2). Test: `test/mcp-capabilities-readiness.test.ts`.
- `src/mcp/hidden-tool-hint.ts` + `src/core/ops/cli-equivalent.ts` — F6: on the owner's stdio pipe a real tool outside the surface/read-only access gets `unknown_tool` naming itself and its CLI equivalent (`cliEquivalent`: `cliOnly` argv, curated overrides, `cliHints.name`, else `gbrain call`). Where `request_tools` is callable and session widening is on, the fix is `request_tools {surface:'full'}` (`next: run`, argv kept); otherwise the CLI equivalent with actor `user` and a `user_message`; `why` names the lasting route (`GBRAIN_SURFACE=full` in the harness's per-server env, or a `--surface full` re-registration) and that an inherited `GBRAIN_SURFACE` overrides a pinned `--surface`. Read-only access never offers a widen. HTTP stays opaque. `scripts/generate-plugin-tree.ts` appends the same map as a per-skill note to generated starter-gap skills. Test: `test/hidden-tool-hint.test.ts`.
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 1b744ca87b..b35628044f 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -22,8 +22,8 @@ src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in
src/core/operations.ts 339 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line)
src/core/pglite-engine.ts 2995 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts)
src/core/postgres-engine.ts 2932 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts)
-src/core/search/hybrid.ts 1586 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key
-src/core/types.ts 2210 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop)
+src/core/search/hybrid.ts 1591 ratchet +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate
+src/core/types.ts 2211 ratchet +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary)
src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)
src/commands/init.ts 1876 ratchet grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts)
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
diff --git a/src/commands/search-diagnose.ts b/src/commands/search-diagnose.ts
index 37b8f3154d..e81e1346c1 100644
--- a/src/commands/search-diagnose.ts
+++ b/src/commands/search-diagnose.ts
@@ -60,7 +60,10 @@ export async function runSearchDiagnose(engine: BrainEngine, args: string[]): Pr
// Vector layer (skip if no embedding provider).
let vector: LayerProbe;
const { isAvailable, embedQuery } = await import('../core/ai/gateway.ts');
- if (!isAvailable('embedding')) {
+ const { factEmbeddingDisabled } = await import('../core/embedding-disabled.ts');
+ if (await factEmbeddingDisabled(engine)) {
+ vector = { rank: null, score: null, top_slug: null, note: 'skipped — embeddings are off on this brain by choice (embedding_disabled); no query text was sent to a provider. `gbrain doctor --json` names the enable command if the user wants semantic search.' };
+ } else if (!isAvailable('embedding')) {
vector = { rank: null, score: null, top_slug: null, note: 'skipped — no embedding provider configured' };
} else {
try {
diff --git a/src/commands/takes.ts b/src/commands/takes.ts
index b9e7970b8f..2e46932649 100644
--- a/src/commands/takes.ts
+++ b/src/commands/takes.ts
@@ -24,7 +24,7 @@ import {
import { resolveSourceId } from '../core/source-resolver.ts';
import { resolveOwnerHolder } from '../core/owner-holder.ts';
import { embedStaleTakes } from '../core/embed-takes.ts';
-import { assertEmbeddingEnabled } from '../core/embedding-dim-check.ts';
+import { assertBrainEmbeddingEnabled } from '../core/embedding-dim-check.ts';
import { loadConfig } from '../core/config.ts';
import { embedQuery } from '../core/embedding.ts';
import {
@@ -177,7 +177,7 @@ async function cmdSearch(engine: BrainEngine, args: string[]): Promise<void> {
const limit = parseInt(flagValue(args, '--limit') ?? '30', 10);
let hits;
if (semantic) {
- assertEmbeddingEnabled(loadConfig());
+ await assertBrainEmbeddingEnabled(engine, loadConfig());
const { validateEmbeddingCreds } = await import('../core/embed-preflight.ts');
validateEmbeddingCreds();
const queryEmbedding = await embedQuery(query);
@@ -210,7 +210,7 @@ async function cmdEmbed(engine: BrainEngine, args: string[]): Promise<void> {
}
if (!dryRun) {
- assertEmbeddingEnabled(loadConfig());
+ await assertBrainEmbeddingEnabled(engine, loadConfig());
const { validateEmbeddingCreds } = await import('../core/embed-preflight.ts');
validateEmbeddingCreds();
}
diff --git a/src/core/embedding-dim-check.ts b/src/core/embedding-dim-check.ts
index 91cfc223b3..97dc2422b2 100644
--- a/src/core/embedding-dim-check.ts
+++ b/src/core/embedding-dim-check.ts
@@ -19,7 +19,7 @@ import { shellQuote, type Action } from './agent-output.ts';
import { embeddingEnablement } from './readiness.ts';
import { OperationError } from './ops/contract.ts';
import { PGVECTOR_HNSW_VECTOR_MAX_DIMS, hnswMaxDimsForType } from './vector-index.ts';
-import { gbrainPath } from './config.ts';
+import { gbrainPath, loadConfig } from './config.ts';
import { resolveRecipe } from './ai/model-resolver.ts';
import type { Recipe } from './ai/types.ts';
import { AIConfigError } from './ai/errors.ts';
@@ -77,6 +77,19 @@ export class EmbeddingDisabledError extends Error {
* present, effects credentials + paid), never `gbrain config set
* embedding_model`, which the config command refuses.
*/
+/**
+ * Refuse an explicit embedding action (semantic takes search, takes embed,
+ * image search, a vector eval) on a brain that opted out of embedding by any
+ * plane (factEmbeddingDisabled: caller config, running consumer, config file
+ * or the brain's own row), with the same enable-command error as
+ * assertEmbeddingEnabled. Nothing is sent to a provider.
+ */
+export async function assertBrainEmbeddingEnabled(engine: BrainEngine, cfg?: GBrainConfig | null): Promise<void> {
+ const { factEmbeddingDisabled } = await import('./embedding-disabled.ts');
+ if (!await factEmbeddingDisabled(engine, cfg)) return;
+ assertEmbeddingEnabled({ engine: engine.kind, ...(cfg ?? loadConfig() ?? {}), embedding_disabled: true });
+}
+
export function assertEmbeddingEnabled(cfg: GBrainConfig | null): void {
if (!cfg?.embedding_disabled) return;
const fix = embeddingEnablement(cfg);
diff --git a/src/core/interop-notices.ts b/src/core/interop-notices.ts
index 2f99e828d1..1954a9506d 100644
--- a/src/core/interop-notices.ts
+++ b/src/core/interop-notices.ts
@@ -78,7 +78,7 @@ function embeddingsFix(cfg: GBrainConfig | null | undefined, transport: 'stdio'
/** One `degraded_recall` notice for the recall-affecting stages of this call; null when none applies. */
export function degradedRecallNotice(
stages: ReadonlyArray<{ stage?: string; reason?: string } | string>,
- opts: { config?: GBrainConfig | null; transport: 'stdio' | 'http' | 'cli' },
+ opts: { config?: GBrainConfig | null; transport: 'stdio' | 'http' | 'cli'; optedOut?: boolean },
): Notice | null {
const names = [...new Set(stages
.map(s => (typeof s === 'string' ? { stage: s } : s))
@@ -87,9 +87,10 @@ export function degradedRecallNotice(
if (names.length === 0) return null;
const guidance = names.map(n => DEGRADED_STAGE_GUIDANCE[n]);
const fixKind: StageFix = guidance.some(g => g.fix === 'embeddings') ? 'embeddings' : guidance.some(g => g.fix === 'doctor') ? 'doctor' : null;
- const emb = fixKind === 'embeddings' ? embeddingsFix(opts.config, opts.transport) : undefined;
+ const byChoice = opts.optedOut || stages.some(s => typeof s !== 'string' && s.reason === 'embedding_disabled');
+ const emb = fixKind === 'embeddings' ? (byChoice ? { byChoice: true } as { fix?: Action; byChoice: boolean } : embeddingsFix(opts.config, opts.transport)) : undefined;
const fix = emb ? emb.fix : fixKind === 'doctor' ? doctorFix('Doctor names the failing retrieval dependency and its fix.') : undefined;
- const choice = emb?.byChoice ? ' This brain was set up keyword-only by the user\'s choice; mention it only if the user asks why something was not found.' : '';
+ const choice = emb?.byChoice ? ' This brain was set up keyword-only by the user\'s choice; mention it only if the user asks why something was not found. No query text was sent to an embedding provider. If the user wants semantic search, `gbrain doctor --json` names the enable command; turning it on needs their consent.' : '';
return {
code: 'degraded_recall',
kind: 'degraded',
@@ -193,7 +194,23 @@ export function degradedDedupNotice(cfg?: GBrainConfig | null): Notice {
// ── dispatch producer ──────────────────────────────────────────────────────
-const VECTOR_FALLBACK_WARNINGS: ReadonlySet<string> = new Set(['QUESTION_EMBED_FAILED']);
+/** think's warning when the brain opted out of embedding and the question was never embedded. */
+export const QUESTION_EMBED_OPTED_OUT = 'QUESTION_EMBED_SKIPPED_EMBEDDING_DISABLED';
+/** recall's `search_degraded` when the brain opted out of embedding. */
+export const RECALL_KEYWORD_ONLY_OPTED_OUT = 'keyword_only_embedding_disabled';
+const VECTOR_FALLBACK_WARNINGS: ReadonlySet<string> = new Set(['QUESTION_EMBED_FAILED', QUESTION_EMBED_OPTED_OUT]);
+
+/** Did this call run keyword-only because the brain opted out of embedding (not a missing or failing provider)? */
+export function embeddingOptedOutFor(op: string, result: unknown, meta: Record<string, unknown>): boolean {
+ const r = (result && typeof result === 'object' ? result : {}) as Record<string, unknown>;
+ if (op === 'search' || op === 'query') {
+ const retrieval = meta.retrieval as { degraded?: Array<{ stage?: string; reason?: string }> } | undefined;
+ return (retrieval?.degraded ?? []).some(d => d.reason === 'embedding_disabled');
+ }
+ if (op === 'recall') return r.search_degraded === RECALL_KEYWORD_ONLY_OPTED_OUT;
+ if (op === 'think') return Array.isArray(r.warnings) && r.warnings.includes(QUESTION_EMBED_OPTED_OUT);
+ return false;
+}
/** Recall-affecting stages of one successful call, from its result and the handler-emitted `retrieval` meta. */
export function recallStagesFor(op: string, result: unknown, meta: Record<string, unknown>, cfg?: GBrainConfig | null): string[] {
@@ -223,7 +240,7 @@ export function recallInteropNotices(
): Notice[] {
try {
const out: Notice[] = [];
- const degraded = degradedRecallNotice(recallStagesFor(op, result, meta, opts.config), opts);
+ const degraded = degradedRecallNotice(recallStagesFor(op, result, meta, opts.config), { ...opts, optedOut: embeddingOptedOutFor(op, result, meta) });
if (degraded) out.push(degraded);
const narrowed = opts.transport === 'stdio' ? sourceBindingNarrowedNotice(op, params, result, opts.binding) : null;
if (narrowed) out.push(narrowed);
diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.ts
index b40f480a84..cc718fadb4 100644
--- a/src/core/ops/facts.ts
+++ b/src/core/ops/facts.ts
@@ -445,9 +445,10 @@ const recall: Operation = {
// untrusted callers (matches the facts arms' world-only filter above).
const { resolveExcludePrivatePages } = await import('../search/private-visibility.ts');
const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);
- if (!isAvailable('embedding')) {
+ const keywordOnly = await recallKeywordOnlyReason(ctx);
+ if (keywordOnly) {
searchResults = await keylessRecallRows(ctx, queryText, limit, excludePrivate, searchScope);
- searchDegraded = 'keyword_only_no_embedding_provider';
+ searchDegraded = keywordOnly;
} else {
searchResults = await hybridSearchCached(ctx.engine, queryText, {
limit,
@@ -1217,6 +1218,13 @@ export const factsOperations: Operation[] = [
extract_facts, recall, context_pack, delta, forget_fact,
];
+/** Why recall's page-search arm runs keyword-only, or null: the brain opted out (no query text sent), or no provider. */
+async function recallKeywordOnlyReason(ctx: OperationContext): Promise<string | null> {
+ const { factEmbeddingDisabled } = await import('../embedding-disabled.ts');
+ if (await factEmbeddingDisabled(ctx.engine, ctx.config)) return (await import('../interop-notices.ts')).RECALL_KEYWORD_ONLY_OPTED_OUT;
+ return isAvailable('embedding') ? null : 'keyword_only_no_embedding_provider';
+}
+
/**
* Keyless recall's page arm: direct keyword FTS, except that a planned
* multi-relation question (planner on) goes through hybridSearch's keyless
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index 33b1a75108..ffecf927af 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -504,6 +504,15 @@ const RECENCY_PARAM = { type: 'string' as const, enum: ['off', 'on', 'strong'],
const SNIPPET_CHARS_PARAM_DESCRIPTION = 'Max chars per chunk_text (0 = full).';
+/** The query op's image branch embed; a brain that opted out of embedding refuses before the image reaches a provider. */
+async function embedSearchImage(ctx: OperationContext, data: string, mime: string): Promise<Float32Array> {
+ const { assertBrainEmbeddingEnabled } = await import('../embedding-dim-check.ts');
+ await assertBrainEmbeddingEnabled(ctx.engine, ctx.config);
+ const { embedMultimodal } = await import('../ai/gateway.ts');
+ const [vec] = await embedMultimodal([{ kind: 'image_base64', data, mime }]);
+ return vec;
+}
+
/**
* #3800: resolve the effective snippet cap for one call. Explicit
* `snippet_chars` param wins (0 = full text); else subagent callers
@@ -763,10 +772,7 @@ const query: Operation = {
const imageMeta: HybridSearchMeta = {
vector_enabled: true, expansion_applied: false, detail_resolved: null, degraded: [],
};
- const { embedMultimodal } = await import('../ai/gateway.ts');
- const [vec] = await embedMultimodal([
- { kind: 'image_base64', data: imageData, mime: imageMime },
- ]);
+ const vec = await embedSearchImage(ctx, imageData, imageMime);
// v0.34.1 (#861 F2 — 6th leak surface): the image path bypasses
// hybridSearch and calls searchVector directly, so it needs its
// own thread of the source scope. Pre-fix, this branch leaked
diff --git a/src/core/search/by-image.ts b/src/core/search/by-image.ts
index 4b896ea48e..35a7e649f3 100644
--- a/src/core/search/by-image.ts
+++ b/src/core/search/by-image.ts
@@ -79,6 +79,9 @@ export async function searchByImage(
// Both branches use the same source-scope threading.
};
+ // A brain that opted out of embedding refuses image search before anything is sent to a provider.
+ const { assertBrainEmbeddingEnabled } = await import('../embedding-dim-check.ts');
+ await assertBrainEmbeddingEnabled(engine);
// Image branch — always runs.
const imageEmbedding = await embedQueryMultimodalImage({
data: input.base64,
diff --git a/src/core/search/eval.ts b/src/core/search/eval.ts
index 1ef0cb99cc..6e4959a2f9 100644
--- a/src/core/search/eval.ts
+++ b/src/core/search/eval.ts
@@ -245,6 +245,8 @@ async function runQuery(
// model, searched on that column. `embed()` is the DOCUMENT side and
// handicapped the vector baseline on Voyage-class providers.
const cfg = (await loadConfigWithEngine(engine).catch(() => null)) ?? loadConfig();
+ const { assertBrainEmbeddingEnabled } = await import('../embedding-dim-check.ts');
+ await assertBrainEmbeddingEnabled(engine, cfg);
const column = resolveEmbeddingColumn(undefined, cfg ?? { engine: 'pglite' });
const embedding = await embedQuery(query, column.embeddingModel
? { embeddingModel: column.embeddingModel, dimensions: column.dimensions }
diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.ts
index 7a8602f190..1609f1dcb1 100644
--- a/src/core/search/hybrid.ts
+++ b/src/core/search/hybrid.ts
@@ -47,6 +47,7 @@ import { resolveHybridRequest } from './hybrid/request.ts';
import { prepareSemanticCache, resolveCacheSearchMode, semanticCacheSkipped, serveSemanticCacheHit } from './hybrid/cache-stages.ts';
import { buildPostFusionOpts, buildRelationalList, resolveModalityAndQueries, runLexicalArms, runVectorArms } from './hybrid/arms.ts';
import { searchVectorFallback, searchWithoutEmbeddings } from './hybrid/keyword-only.ts';
+import { factEmbeddingDisabled } from '../embedding-disabled.ts';
import { expandStructuralNeighbors, finalizeHybridResults, fuseArms, rerankAndPin, sizeReturnPool } from './hybrid/rank.ts';
export const RRF_K = 60;
@@ -943,6 +944,8 @@ export interface HybridSearchOpts extends SearchOpts {
* prepended to the text vector arm's query embeddings only.
*/
_queryPrefix?: string;
+ /** INTERNAL — the brain opted out of embedding (factEmbeddingDisabled), read once per request: keyword-only, no query embed. */
+ _embeddingOptedOut?: boolean;
/**
* Hermetic eval canaries/CI — non-semantic embeddings. When set, the query
@@ -1065,6 +1068,7 @@ export async function hybridSearch(
opts = { ...opts, ...filters };
}
if (opts?._queryPrefix === undefined) opts = { ...opts, _queryPrefix: await loadEmbeddingQueryPrefix(engine) };
+ if (opts._embeddingOptedOut === undefined) opts = { ...opts, _embeddingOptedOut: await factEmbeddingDisabled(engine) };
// Named stages (src/core/search/hybrid/): request -> lexical arms ->
// relational arm -> [keyword-only return] -> modality + expansion ->
// vector arms -> [keyword fallback return] -> fusion + post-fusion boosts
@@ -1100,11 +1104,12 @@ export async function hybridSearch(
earlyModality === 'image' ||
earlyModality === 'both' ||
mayEscalateToMultimodal) &&
+ !opts?._embeddingOptedOut &&
isAvailable('embedding', multimodalProviderProbe);
// Hermetic eval canaries/CI: a caller-supplied queryEmbedFn produces the
// vector-arm query embedding without the gateway, so provider
// availability is irrelevant — skip the keyword-only short-circuit.
- if (opts?.decide?.keywordOnly || (!opts?.queryEmbedFn && !isAvailable('embedding', providerProbe) && !willTryMultimodal)) {
+ if (opts?.decide?.keywordOnly || (!opts?.queryEmbedFn && (opts?._embeddingOptedOut || !isAvailable('embedding', providerProbe)) && !willTryMultimodal)) {
return searchWithoutEmbeddings(req, lexical, relationalList, postFusionOpts, providerProbe);
}
@@ -1176,6 +1181,7 @@ export async function hybridSearchCached(
if (opts?.types?.length === 0) return [];
const { modeInputForCache, resolvedForCache, knobsHash } = await resolveCacheSearchMode(engine, opts);
const queryPrefix = opts?._queryPrefix ?? await loadEmbeddingQueryPrefix(engine);
+ const embeddingOptedOut = opts?._embeddingOptedOut ?? await factEmbeddingDisabled(engine);
// Result caching is off (semanticResultCacheAvailable() === false): skip the
// key/config setup entirely so the wrapper costs no round-trips of its own.
const semanticCache = semanticResultCacheAvailable()
@@ -1206,7 +1212,7 @@ export async function hybridSearchCached(
// 'embedding' column (skipCache short-circuits non-default above),
// so this is the default embeddingModel — but threading it keeps
// the provider probe consistent with the bare hybridSearch path.
- if (isAvailable('embedding', semanticCache.providerProbe)) {
+ if (!embeddingOptedOut && isAvailable('embedding', semanticCache.providerProbe)) {
// v0.35.0.0+: query-side embedding (cache lookup path).
// v0.42.20.0 (Fix 3) — bounded by the shared deadline; on timeout this
// throws → caught below → cacheStatus 'disabled' → falls through to the
@@ -1238,6 +1244,7 @@ export async function hybridSearchCached(
// doesn't start a fresh 6s budget after the cache-lookup already spent it.
_queryEmbedDeadline: queryEmbedDl,
_queryPrefix: queryPrefix,
+ _embeddingOptedOut: embeddingOptedOut,
// #2952 — classify this search's telemetry record (emitted by the inner
// function) with the cache-consult outcome. 'hit' already returned above,
// so only miss/disabled reach this call.
diff --git a/src/core/search/hybrid/keyword-only.ts b/src/core/search/hybrid/keyword-only.ts
index f49e14ecf6..687cadb199 100644
--- a/src/core/search/hybrid/keyword-only.ts
+++ b/src/core/search/hybrid/keyword-only.ts
@@ -80,7 +80,14 @@ export async function searchWithoutEmbeddings(
// vector didn't run, and whether the keyword arm itself came up empty
// (skipped-by-modality is not a keyword miss, hence the image gate).
// System One S6 fire retrieval asks for keyword-only on purpose: vector is not degraded.
- if (!opts?.decide?.keywordOnly) {
+ if (!opts?.decide?.keywordOnly && opts?._embeddingOptedOut) {
+ // The brain opted out of embedding: keyword-only by choice, and the query text never left the brain.
+ pushDegraded(degraded, 'embed_unavailable', 'embedding_disabled');
+ warnOncePerProcess(
+ 'search-vector-leg-opted-out',
+ '[gbrain] embeddings are off on this brain by choice (embedding_disabled), so search is keyword-only and no query text is sent to an embedding provider. If the user wants semantic search, `gbrain doctor --json` names the enable command; turning it on needs their consent.',
+ );
+ } else if (!opts?.decide?.keywordOnly) {
pushDegraded(degraded, 'embed_unavailable', 'no_provider');
// #3808: meta names the degradation for programmatic callers, but a CLI
// human never saw it — mirror the embed-failure warn (once per process,
diff --git a/src/core/think/index.ts b/src/core/think/index.ts
index dd0e472512..a11faa63fa 100644
--- a/src/core/think/index.ts
+++ b/src/core/think/index.ts
@@ -521,6 +521,27 @@ async function renderThinkPages(engine: BrainEngine, opts: RunThinkOpts, pages:
return { pagesBlock, evidenceDelivery: delivered.delivery };
}
+/**
+ * The question embedding gather may use, or undefined. A brain that opted out
+ * of embedding never sends the question to a provider (warning
+ * QUESTION_EMBED_SKIPPED_EMBEDDING_DISABLED); a failing embedder degrades to
+ * QUESTION_EMBED_FAILED with the raw error on stderr only (D6).
+ */
+async function embedThinkQuestion(engine: BrainEngine, opts: RunThinkOpts, warnings: string[]): Promise<Float32Array | undefined> {
+ if (!opts.embedQuestion) return undefined;
+ const { factEmbeddingDisabled } = await import('../embedding-disabled.ts');
+ if (await factEmbeddingDisabled(engine)) {
+ warnings.push((await import('../interop-notices.ts')).QUESTION_EMBED_OPTED_OUT);
+ return undefined;
+ }
+ try {
+ return (await opts.embedQuestion(opts.question)) ?? undefined;
+ } catch (e) {
+ warnings.push('QUESTION_EMBED_FAILED');
+ process.stderr.write(`[think] question embed failed: ${e instanceof Error ? e.message : String(e)}\n`);
+ return undefined;
+ }
+}
/**
* Run the think pipeline. Returns a ThinkResult — caller decides whether
* to print, persist as synthesis page, or surface as MCP response.
@@ -556,18 +577,8 @@ export async function runThink(
}
}
- // Optional question embedding — caller decides whether to pay the embedder.
- let questionEmbedding: Float32Array | undefined;
- if (opts.embedQuestion) {
- try {
- const e = await opts.embedQuestion(opts.question);
- if (e) questionEmbedding = e;
- } catch (e) {
- // D6: code-only on the wire; raw exception text goes to server logs.
- warnings.push('QUESTION_EMBED_FAILED');
- process.stderr.write(`[think] question embed failed: ${e instanceof Error ? e.message : String(e)}\n`);
- }
- }
+ // Optional question embedding — caller decides whether to pay the embedder; an opted-out brain never does.
+ const questionEmbedding = await embedThinkQuestion(engine, opts, warnings);
const thinkDecide = await startThinkDecide(engine, opts, classifyIntent(opts.question)).catch(() => undefined); // System One S2/S4; undefined when both are off
// GATHER
diff --git a/src/core/types.ts b/src/core/types.ts
index 0c73f75d02..d48c0509c2 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -2000,6 +2000,7 @@ export const DEGRADED_REASONS = [
'candidate_budget',
'iterative_scan_unavailable',
'egress_denied', // System One: the Jev reranker skipped a query with a candidate from decide.egress.deny_sources
+ 'embedding_disabled', // the brain opted out of embedding: the query text was never sent to the provider
] as const;
export type DegradedReason = (typeof DEGRADED_REASONS)[number];
diff --git a/src/core/verbs.ts b/src/core/verbs.ts
index 8257cc21fd..20525da3f5 100644
--- a/src/core/verbs.ts
+++ b/src/core/verbs.ts
@@ -484,7 +484,7 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {
},
},
},
- search_degraded: { type: 'string', description: 'Present when the search arm fell back to keyword-only (no embedding provider).' },
+ search_degraded: { type: 'string', description: 'Present when the search arm fell back to keyword-only: keyword_only_no_embedding_provider (no embedding provider) or keyword_only_embedding_disabled (embeddings off by choice; no query text sent to a provider).' },
budget_tokens: { type: 'integer', description: 'Present for a positive finite numeric budget, including when its floor is zero.' },
budget_used: { type: 'integer' },
dropped_count: { type: 'integer' },
diff --git a/test/e2e/query-embedding-opt-out.test.ts b/test/e2e/query-embedding-opt-out.test.ts
new file mode 100644
index 0000000000..3fae36715d
--- /dev/null
+++ b/test/e2e/query-embedding-opt-out.test.ts
@@ -0,0 +1,4 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+// The PostgreSQL arm of test/query-embedding-opt-out.test.ts: no query text reaches the embedder on an opted-out brain.
+await registerPostgresTests(() => import('../query-embedding-opt-out.test.ts'));
diff --git a/test/fixtures/agent-contract/v1/journey/recall-degraded.json b/test/fixtures/agent-contract/v1/journey/recall-degraded.json
index 287e855970..f7dae1eab1 100644
--- a/test/fixtures/agent-contract/v1/journey/recall-degraded.json
+++ b/test/fixtures/agent-contract/v1/journey/recall-degraded.json
@@ -4,7 +4,7 @@
{
"code": "degraded_recall",
"kind": "degraded",
- "why": "Recall was degraded (keyword_only_no_embedding_provider): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\". This brain was set up keyword-only by the user's choice; mention it only if the user asks why something was not found.",
+ "why": "Recall was degraded (keyword_only_no_embedding_provider): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\". This brain was set up keyword-only by the user's choice; mention it only if the user asks why something was not found. No query text was sent to an embedding provider. If the user wants semantic search, `gbrain doctor --json` names the enable command; turning it on needs their consent.",
"contract_version": 1
}
]
@@ -12,11 +12,11 @@
"content": [
{
"type": "text",
- "text": "{\n \"facts\": [\n {\n \"id\": 1,\n \"fact\": \"quokka-journey-marker is the install-check fact\",\n \"kind\": \"fact\",\n \"entity_slug\": null,\n \"source_id\": \"default\",\n \"visibility\": \"world\",\n \"notability\": \"medium\",\n \"valid_from\": \"{{TIME}}\",\n \"valid_until\": null,\n \"expired_at\": null,\n \"superseded_by\": null,\n \"consolidated_at\": null,\n \"consolidated_into\": null,\n \"source\": \"install-check\",\n \"source_session\": null,\n \"context\": null,\n \"confidence\": 1,\n \"created_at\": \"{{TIME}}\",\n \"fact_id\": \"1\",\n \"provenance\": \"install-check\"\n }\n ],\n \"total\": 1,\n \"protocol_version\": 1,\n \"results\": [\n {\n \"slug\": \"journey-note-3\",\n \"title\": \"Journey note 3\",\n \"chunk\": \"# Journey note 3\\n\\nThe quokka-journey-marker 3 lives in note 3.\",\n \"evidence\": \"keyword_exact\",\n \"create_safety\": \"probable\",\n \"provenance\": \"journey-note-3\"\n },\n {\n \"slug\": \"journey-note-2\",\n \"title\": \"Journey note 2\",\n \"chunk\": \"# Journey note 2\\n\\nThe quokka-journey-marker 2 lives in note 2.\",\n \"evidence\": \"keyword_exact\",\n \"create_safety\": \"probable\",\n \"provenance\": \"journey-note-2\"\n },\n {\n \"slug\": \"journey-note-1\",\n \"title\": \"Journey note 1\",\n \"chunk\": \"# Journey note 1\\n\\nThe quokka-journey-marker 1 lives in note 1.\",\n \"evidence\": \"keyword_exact\",\n \"create_safety\": \"probable\",\n \"provenance\": \"journey-note-1\"\n }\n ],\n \"search_degraded\": \"keyword_only_no_embedding_provider\"\n}"
+ "text": "{\n \"facts\": [\n {\n \"id\": 1,\n \"fact\": \"quokka-journey-marker is the install-check fact\",\n \"kind\": \"fact\",\n \"entity_slug\": null,\n \"source_id\": \"default\",\n \"visibility\": \"world\",\n \"notability\": \"medium\",\n \"valid_from\": \"{{TIME}}\",\n \"valid_until\": null,\n \"expired_at\": null,\n \"superseded_by\": null,\n \"consolidated_at\": null,\n \"consolidated_into\": null,\n \"source\": \"install-check\",\n \"source_session\": null,\n \"context\": null,\n \"confidence\": 1,\n \"created_at\": \"{{TIME}}\",\n \"fact_id\": \"1\",\n \"provenance\": \"install-check\"\n }\n ],\n \"total\": 1,\n \"protocol_version\": 1,\n \"results\": [\n {\n \"slug\": \"journey-note-3\",\n \"title\": \"Journey note 3\",\n \"chunk\": \"# Journey note 3\\n\\nThe quokka-journey-marker 3 lives in note 3.\",\n \"evidence\": \"keyword_exact\",\n \"create_safety\": \"probable\",\n \"provenance\": \"journey-note-3\"\n },\n {\n \"slug\": \"journey-note-2\",\n \"title\": \"Journey note 2\",\n \"chunk\": \"# Journey note 2\\n\\nThe quokka-journey-marker 2 lives in note 2.\",\n \"evidence\": \"keyword_exact\",\n \"create_safety\": \"probable\",\n \"provenance\": \"journey-note-2\"\n },\n {\n \"slug\": \"journey-note-1\",\n \"title\": \"Journey note 1\",\n \"chunk\": \"# Journey note 1\\n\\nThe quokka-journey-marker 1 lives in note 1.\",\n \"evidence\": \"keyword_exact\",\n \"create_safety\": \"probable\",\n \"provenance\": \"journey-note-1\"\n }\n ],\n \"search_degraded\": \"keyword_only_embedding_disabled\"\n}"
},
{
"type": "text",
- "text": "[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (keyword_only_no_embedding_provider): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\". This brain was set up keyword-only by the user's choice; mention it only if the user asks why something was not found."
+ "text": "[gbrain notice degraded_recall kind=degraded]\nwhy: Recall was degraded (keyword_only_no_embedding_provider): semantic (vector) search did not run, so matches phrased differently from the query can be missing. Treat a thin or empty result as \"not found with a degraded search\", never as \"the brain has nothing on this\". This brain was set up keyword-only by the user's choice; mention it only if the user asks why something was not found. No query text was sent to an embedding provider. If the user wants semantic search, `gbrain doctor --json` names the enable command; turning it on needs their consent."
}
]
}
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 0a6ed63e01..47f1ad5578 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -447,7 +447,7 @@
"kind": "variable",
"name": "DEGRADED_REASONS",
"signature": [
- "readonly [\"no_provider\", \"provider_error\", \"timeout\", \"variant_embed_failed\", \"original_embed_failed\", \"first_result_truncated\", \"no_key\", \"empty_result_set\", \"malformed_shape\", \"budget\", \"candidate_budget\", \"iterative_scan_unavailable\", \"egress_denied\"]"
+ "readonly [\"no_provider\", \"provider_error\", \"timeout\", \"variant_embed_failed\", \"original_embed_failed\", \"first_result_truncated\", \"no_key\", \"empty_result_set\", \"malformed_shape\", \"budget\", \"candidate_budget\", \"iterative_scan_unavailable\", \"egress_denied\", \"embedding_disabled\"]"
]
},
{
@@ -461,7 +461,7 @@
"kind": "type",
"name": "DegradedReason",
"signature": [
- "\"candidate_budget\" | \"iterative_scan_unavailable\" | \"no_provider\" | \"provider_error\" | \"timeout\" | \"variant_embed_failed\" | \"original_embed_failed\" | \"first_result_truncated\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"budget\" | \"egress_denied\""
+ "\"candidate_budget\" | \"iterative_scan_unavailable\" | \"no_provider\" | \"provider_error\" | \"timeout\" | \"variant_embed_failed\" | \"original_embed_failed\" | \"first_result_truncated\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"budget\" | \"egress_denied\" | \"embedding_disabled\""
]
},
{
@@ -474,7 +474,7 @@
{
"kind": "interface",
"members": [
- "reason?: \"candidate_budget\" | \"iterative_scan_unavailable\" | \"no_provider\" | \"provider_error\" | \"timeout\" | \"variant_embed_failed\" | \"original_embed_failed\" | \"first_result_truncated\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"budget\" | \"egress_denied\" | undefined",
+ "reason?: \"candidate_budget\" | \"iterative_scan_unavailable\" | \"no_provider\" | \"provider_error\" | \"timeout\" | \"variant_embed_failed\" | \"original_embed_failed\" | \"first_result_truncated\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"budget\" | \"egress_denied\" | \"embedding_disabled\" | undefined",
"stage: \"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"projection_pending\" | \"projection_status_unknown\""
],
"name": "DegradedStageEntry"
@@ -5712,7 +5712,7 @@
{
"kind": "class",
"members": [
- "canonical?: \"unknown\" | \"projection_pending\" | \"timeout\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"consent_timeout\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_disabled\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_too_large\" | \"follow_approval_required\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"managed_pull_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pending_writes\" | \"pglite_busy\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"serve_port_in_use\" | \"serve_status_only\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_in_progress\" | \"sync_parser_regression\" | \"target_escape\" | \"topology_change_required\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined",
+ "canonical?: \"unknown\" | \"projection_pending\" | \"timeout\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"consent_timeout\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"file_too_large\" | \"follow_approval_required\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"managed_pull_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pending_writes\" | \"pglite_busy\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"serve_port_in_use\" | \"serve_status_only\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_in_progress\" | \"sync_parser_regression\" | \"target_escape\" | \"topology_change_required\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined",
"canonicalCode: string",
"cause?: unknown",
"code: ErrorCode",
@@ -6830,6 +6830,7 @@
{
"kind": "interface",
"members": [
+ "_embeddingOptedOut?: boolean | undefined",
"_queryEmbedDeadline?: QueryEmbedDeadline | undefined",
"_queryPrefix?: string | undefined",
"_searchModeInput?: ResolveSearchModeInput | undefined",
@@ -7655,7 +7656,7 @@
"kind": "variable",
"name": "DEGRADED_REASONS",
"signature": [
- "readonly [\"no_provider\", \"provider_error\", \"timeout\", \"variant_embed_failed\", \"original_embed_failed\", \"first_result_truncated\", \"no_key\", \"empty_result_set\", \"malformed_shape\", \"budget\", \"candidate_budget\", \"iterative_scan_unavailable\", \"egress_denied\"]"
+ "readonly [\"no_provider\", \"provider_error\", \"timeout\", \"variant_embed_failed\", \"original_embed_failed\", \"first_result_truncated\", \"no_key\", \"empty_result_set\", \"malformed_shape\", \"budget\", \"candidate_budget\", \"iterative_scan_unavailable\", \"egress_denied\", \"embedding_disabled\"]"
]
},
{
@@ -7669,7 +7670,7 @@
"kind": "type",
"name": "DegradedReason",
"signature": [
- "\"candidate_budget\" | \"iterative_scan_unavailable\" | \"no_provider\" | \"provider_error\" | \"timeout\" | \"variant_embed_failed\" | \"original_embed_failed\" | \"first_result_truncated\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"budget\" | \"egress_denied\""
+ "\"candidate_budget\" | \"iterative_scan_unavailable\" | \"no_provider\" | \"provider_error\" | \"timeout\" | \"variant_embed_failed\" | \"original_embed_failed\" | \"first_result_truncated\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"budget\" | \"egress_denied\" | \"embedding_disabled\""
]
},
{
@@ -7682,7 +7683,7 @@
{
"kind": "interface",
"members": [
- "reason?: \"candidate_budget\" | \"iterative_scan_unavailable\" | \"no_provider\" | \"provider_error\" | \"timeout\" | \"variant_embed_failed\" | \"original_embed_failed\" | \"first_result_truncated\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"budget\" | \"egress_denied\" | undefined",
+ "reason?: \"candidate_budget\" | \"iterative_scan_unavailable\" | \"no_provider\" | \"provider_error\" | \"timeout\" | \"variant_embed_failed\" | \"original_embed_failed\" | \"first_result_truncated\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"budget\" | \"egress_denied\" | \"embedding_disabled\" | undefined",
"stage: \"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"projection_pending\" | \"projection_status_unknown\""
],
"name": "DegradedStageEntry"
diff --git a/test/query-embedding-opt-out.test.ts b/test/query-embedding-opt-out.test.ts
new file mode 100644
index 0000000000..6ee842b4a7
--- /dev/null
+++ b/test/query-embedding-opt-out.test.ts
@@ -0,0 +1,139 @@
+/**
+ * A brain that opted out of embedding never sends query text to the
+ * embedding provider: search, query, recall and think run keyword-only and
+ * say so (retrieval degraded `embed_unavailable` / `embedding_disabled`,
+ * recall `keyword_only_embedding_disabled`, think
+ * `QUESTION_EMBED_SKIPPED_EMBEDDING_DISABLED`, and a `degraded_recall` notice
+ * that names the enable path without coaching). Image search refuses with
+ * `embedding_disabled`. A brain with embedding on still embeds the query.
+ * A fake embedder records every call. PostgreSQL arm:
+ * test/e2e/query-embedding-opt-out.test.ts.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { configureGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { embedQuery } from '../src/core/embedding.ts';
+import { runThink } from '../src/core/think/index.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { __resetProcessNoticeLedgerForTests } from '../src/core/notice-ledger.ts';
+import { prepareMarkdownChunks } from '../src/core/markdown-chunks.ts';
+import { installFixtureChunks } from './helpers/page-projection.ts';
+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+// Wire values (src/core/interop-notices.ts), spelled out so this file also runs against code without them.
+const QUESTION_EMBED_OPTED_OUT = 'QUESTION_EMBED_SKIPPED_EMBEDDING_DISABLED';
+const RECALL_KEYWORD_ONLY_OPTED_OUT = 'keyword_only_embedding_disabled';
+const PAGES = [
+ { slug: 'notes/heron-handbook', body: 'The heron program runs quarterly reviews. Heron pricing is tiered by seat.' },
+ { slug: 'notes/heron-roadmap', body: 'Heron roadmap: the next heron milestone ships in spring.' },
+];
+let embedded: string[] = [];
+
+beforeEach(() => {
+ embedded = [];
+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: { OPENAI_API_KEY: 'fixture-key' } });
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {
+ embedded.push(...values);
+ return { embeddings: values.map(() => [1, ...Array(LEGACY_EMBEDDING_CONFIG.embedding_dimensions - 1).fill(0)]) };
+ }) as never);
+});
+afterEach(() => { __setEmbedTransportForTests(null); });
+
+function ctxOf(engine: BrainEngine, meta: Array<{ key: string; value: unknown }>): OperationContext {
+ return { engine: engine as never, config: { engine: engine.kind } as never, logger: console as never, dryRun: false, remote: false, sourceId: 'default',
+ emitResponseMeta: (key: string, value: unknown) => { meta.push({ key, value }); } } as OperationContext;
+}
+const retrievalOf = (meta: Array<{ key: string; value: unknown }>) =>
+ meta.find(m => m.key === 'retrieval')?.value as { vector_enabled: boolean; degraded?: Array<{ stage: string; reason?: string }> };
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+
+ describe(`read paths on a brain that opted out of embedding send no query text to the provider (${backend})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => {
+ if (databaseUrl) {
+ ({ engine, close } = await isolatedPersistencePostgres(databaseUrl));
+ } else {
+ const pglite = new PGLiteEngine();
+ await pglite.connect({});
+ await pglite.initSchema();
+ engine = pglite;
+ close = () => pglite.disconnect();
+ }
+ for (const p of PAGES) {
+ await engine.putPage(p.slug, { type: 'note', title: p.slug, compiled_truth: p.body, timeline: '', frontmatter: {} });
+ await installFixtureChunks(engine, p.slug, await prepareMarkdownChunks({ compiled_truth: p.body, timeline: '' }));
+ }
+ }, 120_000);
+ afterAll(async () => { await close?.(); });
+
+ test('search and query run keyword-only with the embedding_disabled degraded reason', async () => {
+ await engine.setConfig('embedding_disabled', 'true');
+ for (const [op, params] of [['search', { query: 'heron pricing' }], ['query', { query: 'heron pricing', expand: false }]] as const) {
+ const meta: Array<{ key: string; value: unknown }> = [];
+ const rows = await operationsByName[op]!.handler(ctxOf(engine, meta), params) as Array<{ slug: string }>;
+ expect(rows.map(r => r.slug)).toContain('notes/heron-handbook');
+ const retrieval = retrievalOf(meta);
+ expect(retrieval.vector_enabled).toBe(false);
+ expect(retrieval.degraded).toContainEqual({ stage: 'embed_unavailable', reason: 'embedding_disabled' });
+ }
+ expect(embedded).toEqual([]);
+ }, 120_000);
+
+ test('recall and think skip the embedder and say so', async () => {
+ await engine.setConfig('embedding_disabled', 'true');
+ const recalled = await operationsByName.recall!.handler(ctxOf(engine, []), { query: 'heron roadmap' }) as { search_degraded?: string };
+ expect(recalled.search_degraded).toBe(RECALL_KEYWORD_ONLY_OPTED_OUT);
+ const thought = await runThink(engine, {
+ question: 'What is on the heron roadmap?', remote: false, embedQuestion: q => embedQuery(q),
+ client: { create: async () => ({ content: [{ type: 'text', text: '{"answer":"ok","citations":[],"gaps":[]}' }], usage: { input_tokens: 1, output_tokens: 1 } }) } as never,
+ });
+ expect(thought.warnings).toContain(QUESTION_EMBED_OPTED_OUT);
+ expect(embedded).toEqual([]);
+ }, 120_000);
+
+ test('the MCP degraded_recall notice says nothing was sent and names the enable path without coaching', async () => {
+ await engine.setConfig('embedding_disabled', 'true');
+ // stdio dedupes a notice once per process; each backend's arm reads its own.
+ __resetProcessNoticeLedgerForTests();
+ await withEnv({ GBRAIN_BACKUP_CHECK: '0' }, async () => {
+ const res = await dispatchToolCall(engine, 'search', { query: 'heron pricing' }, { remote: true, transport: 'stdio', sourceId: 'default' });
+ const notices = (res._meta?.gbrain_notices ?? []) as Array<{ code: string; why: string; fix?: unknown; user_message?: unknown }>;
+ const notice = notices.find(n => n.code === 'degraded_recall')!;
+ expect(notice.why).toContain("keyword-only by the user's choice");
+ expect(notice.why).toContain('No query text was sent to an embedding provider');
+ expect(notice.why).toContain('gbrain doctor --json');
+ expect(notice.fix).toBeUndefined();
+ expect(notice.user_message).toBeUndefined();
+ });
+ expect(embedded).toEqual([]);
+ }, 120_000);
+
+ test('image search refuses with embedding_disabled before anything is sent', async () => {
+ await engine.setConfig('embedding_disabled', 'true');
+ await expect(operationsByName.query!.handler(ctxOf(engine, []), { image: 'aGVsbG8=', image_mime: 'image/png' }))
+ .rejects.toMatchObject({ name: 'EmbeddingDisabledError' });
+ const png = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=';
+ await expect(operationsByName.search_by_image!.handler(ctxOf(engine, []), { image_data: png, query: 'heron' }))
+ .rejects.toMatchObject({ name: 'EmbeddingDisabledError' });
+ expect(embedded).toEqual([]);
+ }, 120_000);
+
+ test('a brain with embedding on still embeds the query', async () => {
+ await engine.setConfig('embedding_disabled', 'false');
+ const meta: Array<{ key: string; value: unknown }> = [];
+ await operationsByName.search!.handler(ctxOf(engine, meta), { query: 'heron pricing' });
+ expect(embedded).toContain('heron pricing');
+ expect(retrievalOf(meta).vector_enabled).toBe(true);
+ expect(retrievalOf(meta).degraded ?? []).not.toContainEqual({ stage: 'embed_unavailable', reason: 'embedding_disabled' });
+ }, 120_000);
+ });
+}