Local-first ๐ง memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly ๐ด dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.
TypeScript
feat: honest query embeds and drift-checked upgrades (v1.73.0) (#235)
Serg Eroshe0f0c9a76c581
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 479b316a..ad98fce6 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.72.0",+ "version": "1.73.0","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 489f84c3..182ddb89 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.72.0",+ "version": "1.73.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bbb24e12..a38082fc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,41 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [1.73.0] - 2026-10-06++Open Second Brain now makes every query embed honest and every upgrade safe: one query-embed gateway applies the caller's reach and the embedding price gate before any provider is called, for the search lane behind six MCP tools and two hooks and for the `brain_context_pack` semantic belief order, and fits the query, instruction prefix included, to the model's input window, disclosing a refusal or a cut by trail code; an operator can declare the input window of an uncurated model and send extra request fields to an OpenAI-compatible endpoint; recall feedback, benchmark, eval and tune reports name the degradations their searches met; and `o2b brain upgrade` and the automatic upgrade worker apply exactly the plan they computed, refusing a managed file edited in between instead of overwriting it.++### Added++- **One gate for every query embed.** The search lane (reached by `o2b search`, `brain_search`, `brain_recall_feedback`, `brain_file_context`, `brain_eval`, `brain_benchmark`, `brain_tune` and the recall-inject and gap-promote hooks) and the `brain_context_pack` semantic belief order now decide through one gateway whether, and with what text, a query is embedded. Under a positive `embedding_cost_gate_usd`, a caller that is not local is refused the query embed of a model with no known price before any provider is called. A search that asked for the semantic lane by name fails with `EMBEDDING_COST_UNPRICED`; a hybrid search falls back to keyword-only, warns, and records the new trail code `semantic-cost-unpriced`. The message names the model and the price pair that clears the refusal and says only that the gate is positive, never its amount. The CLI runs at local reach and is not gated.+- **Queries fitted to the model's input window.** The gateway cuts a query to the effective input window, counting the instruction prefix the provider sends, at a code-point boundary under the conservative token estimate, so it never sends more than the window and treats every language alike. A cut is disclosed by a warning naming the window and how much of the query was embedded, and by the new trail code `semantic-query-truncated` with `detail.windowTokens`. When the instruction prefix alone fills the window nothing is embedded: an explicit semantic search and the semantic belief order refuse with `INVALID_INPUT`, and a hybrid search falls back to keyword-only with the trail code `semantic-query-empty-fit`, which, unlike a cut, always counts as a stopped semantic lane. An unknown window cuts nothing.+- **`embedding_input_window_tokens`.** The effective window is this key (env `OPEN_SECOND_BRAIN_EMBEDDING_INPUT_WINDOW_TOKENS`, an integer of at least 1), then the window the curated model table declares, then unknown. The chunk-window census of an index run and of `o2b search status` reads the same window, so a declared window enables it for an uncurated model. A blank value is refused rather than read as unset, and the key is refused for the `local` provider, which has no window.+- **`embedding_extra_body`.** One JSON object (env `OPEN_SECOND_BRAIN_EMBEDDING_EXTRA_BODY`) whose fields are sent with every embedding request to an OpenAI-compatible endpoint. The owned fields `model`, `input` and `encoding_format` are refused by name in any spelling (case, separators, fullwidth and zero-width variants are folded first); a blank value, invalid JSON or a non-object is refused naming the key or env variable that supplied it. The key is refused for any provider other than `openai-compat` (`disabled` is exempt, it sends nothing), and a `dimensions` field requires `embedding_dimension` and must agree with it. The checks run on the resolved config too, so a programmatic override meets them. The extra body is not part of the embedding identity and never triggers a reindex.+- **Degradations reported where results are measured.** `brain_recall_feedback` returns an additive `degraded` array with the codes of its re-run search, and `brain_benchmark`, `brain_eval` and `brain_tune` reports carry a `degraded` union (and per query or per grid row) when a run measured a smaller system than the configured one.+- **Hook audit lines name the retrieval codes.** The recall-inject and gap-promote hooks run at remote reach, so a gated query embed is now visible: their local audit lines carry `retrieval_degraded`, the trail codes of the searches behind the decision, each once in first-seen order. The codes ride the local line only, never the synced `recall_telemetry` record.+- **`BrainUpgradeError.drifted` and `--apply --json` refusals.** An upgrade refused for drift names every refused path, and `o2b brain upgrade --apply --json` prints `{ "ok": false, "error", "run_id", "drifted" }` for a refusal so a script can tell a drift from any other failure.++### Changed++- **Upgrades apply the plan they showed.** `o2b brain upgrade --apply` and the automatic upgrade worker plan once and apply that plan; each planned row records the bytes it was read with, or `null` when the file was absent (an absent file used to read as an empty one). A managed file that changed after the plan was read is refused before the snapshot is taken, with nothing written and `o2b brain upgrade --dry-run` advised, and again right before each write, so an edit that lands mid-apply is left as it is. When earlier files were already rewritten, the message names them and advises the same dry-run re-plan; a rollback is deliberately not offered, because the pre-apply snapshot predates the rewritten files, so its own drift guard would refuse it, and forcing it would destroy the edit. The `--dry-run --json` plan still reports `before_size: 0` for an absent file, and the text plan reads `absent`.+- **`brain_context_pack` semantic mode counts what it sends.** `semantic.query_tokens` and the estimate count the text actually sent, instruction prefix included, and an omitted reach now resolves to remote like every other reader instead of local.+- **`brain_tune` refuses to save a keyword-only winner.** A winner measured with the semantic lane missing is not saved: `EMBEDDING_COST_UNPRICED` for the cost gate, `EMBEDDING_KEY_MISSING` or `EMBEDDING_DISABLED` for a blocked tier, `EMBEDDING_PROVIDER_HTTP` when the provider did not answer, and the same `EMBEDDING_PROVIDER_HTTP` for any other stop that left the hybrid caller keyword-only (the composite deadline, an empty query vector, an empty fit recorded as `semantic-query-empty-fit`), each with its remedy. An index with no embeddings or a machine without sqlite-vec is keyword-only by construction and still tunes.+- **Recall feedback does not learn from a keyword-only answer.** A feedback event whose re-run lost the semantic lane records zero layer contributions, so the vault's learned weights stay as they were.+- **Gated answers are never cached; cut answers are cached under their window.** A search answer refused by the cost gate is not stored in the search cache, so declaring a price takes effect on the next search. A search answer cut to the input window is cached under a key that carries the effective window and the query prefix sent with it, so a repeated long query is not embedded again, and a declared or changed window or prefix takes effect on the next search.+- **Docs:** `docs/cli-reference.md` gains the three trail-table rows, "Query embeds", `embedding_input_window_tokens`, `embedding_extra_body`, the extra-body note in the egress table and the upgrade drift behaviour, `docs/how-it-works.md` the query-embed gateway and the drift-checked upgrade, `docs/mcp.md` the gateway, the `degraded` fields and the tune refusal, `docs/observability.md` the `retrieval_degraded` audit field, and `docs/updating.md` "Upgrading to 1.73.0"; the `embeddings-setup` skill gains the input window and extra body steps. The README names this release.++### Fixed++- **A managed file edited during an upgrade is no longer overwritten.** The upgrade used to plan again at apply time, so the plan an operator confirmed was not the plan applied, and an edit made in between was replaced without notice.+- **The query embed of an MCP search or a hook was not gated.** The v1.72.0 cost gate covered embedding runs and the semantic belief order, but the search lane's query embed spent on an unpriced model for any caller; it now passes the same gate.++### Notes++- The rerank and decision-model spend paths stay outside the query-embed gate.+- gap-promote verdicts are unchanged on degraded evidence: the codes are disclosed, the decisions are not altered.+- An extra request body for the ZeroEntropy provider and for the reranker is not part of this release.+- A width field under a name other than `dimensions` is not cross-checked against `embedding_dimension`; the provider's response-width checks still catch a mismatch.+## [1.72.0] - 2026-10-05Open Second Brain now prices embedding spend honestly: every estimate names where its price came from (`builtin`, `operator` or `unknown`), an operator can declare the price of a model the built-in table does not list, and one spend plan feeds the estimate, the cost gate, the spend receipt and `search status`, so an unknown price is reported as unknown instead of as $0 and a positive cost gate refuses it by name; edits re-embed only the chunks that changed, `o2b search vector-backfill` can be scoped to vault paths, `o2b search check` names an unpriced model, a stale price declaration and the places it looked for an embedding key, and `brain_context_pack` gains a `semantic` query mode that orders the curated belief notes by the stored vectors of their chunks.@@ -8197,6 +8232,7 @@ plugin config (vault field)`, and exits with a clear- Sandbox vault and plugin manifest fixtures for tests.- GitHub release workflow for tag-based and manually dispatched releases.+[1.73.0]: https://github.com/itechmeat/open-second-brain/compare/v1.72.0...v1.73.0[1.72.0]: https://github.com/itechmeat/open-second-brain/compare/v1.71.0...v1.72.0[1.71.0]: https://github.com/itechmeat/open-second-brain/compare/v1.70.0...v1.71.0[1.70.0]: https://github.com/itechmeat/open-second-brain/compare/v1.69.0...v1.70.0diff --git a/README.md b/README.mdindex 9c04821f..19deaa56 100644--- a/README.md+++ b/README.md@@ -113,7 +113,7 @@ The full router with readiness criteria is [`install.md`](install.md); native Wi## What is new-1.72.0 makes embedding spend honest. Every estimate names its price source (`builtin`, `operator` or `unknown`), `embedding_price_model` and `embedding_price_usd_per_mtok` declare the price of a model the built-in table does not list, and an unknown price is reported as `price unknown` instead of $0; under a positive `embedding_cost_gate_usd` such a model is refused with `EMBEDDING_COST_UNPRICED` until its price is declared or the run is forced. Edited notes keep the vectors of their unchanged chunks, `o2b search vector-backfill` accepts a repeatable `--path`, `o2b search check` names an unpriced model and where it looked for an embedding key, and `brain_context_pack` gains `query_mode: "semantic"`, which orders the curated belief notes by the stored vectors of their chunks. Every release is described in the [CHANGELOG](CHANGELOG.md).+1.73.0 makes the query embed honest and upgrades safe. Every query embed, from the search lane behind the MCP tools and hooks to the `brain_context_pack` semantic belief order, passes one gate: under a positive `embedding_cost_gate_usd` an unpriced model is refused for any caller that is not local (a hybrid search falls back to keyword-only and says so by trail code), and a query longer than the model's input window is cut to it and disclosed. `embedding_input_window_tokens` declares the window of a model the curated table does not list, and `embedding_extra_body` sends extra request fields to an OpenAI-compatible endpoint. `brain_recall_feedback` and the benchmark, eval and tune reports name the degradations their searches met, and `brain_tune` no longer saves a winner measured without the semantic lane. `o2b brain upgrade` and the automatic upgrade worker apply exactly the plan they computed and refuse a managed file edited in between instead of overwriting it. Every release is described in the [CHANGELOG](CHANGELOG.md).## Documentationdiff --git a/docs/brainstorm/honest-query-embed-and-safe-upgrades/cli-output/claude.md b/docs/brainstorm/honest-query-embed-and-safe-upgrades/cli-output/claude.mdnew file mode 100644index 00000000..5204b1c0--- /dev/null+++ b/docs/brainstorm/honest-query-embed-and-safe-upgrades/cli-output/claude.md@@ -0,0 +1,35 @@+### Variant 1: Provider choke point+- **Approach**: Move every query-embed rule into the embedding provider layer: `embed(texts, { kind, reach })` performs the reach-and-price gate, the window truncation (it already knows the prefix it prepends) and the extra-body merge, so `belief-semantic.ts` drops its inline check and `runSemanticPhase` only threads `transportReach` through. Compare-before-write lands as a new `expectBefore` option on `atomicWriteFileSync` in `fs-atomic.ts` with a tri-state expectation (absent, or exact bytes), and `applyUpgrade` passes each row's `before` through it.+- **Trade-offs**:+ - Pro: literally one place; impossible to add a query surface that bypasses the rule.+ - Pro: truncation sees the real prefix and model window, no mirrored estimate needed.+ - Con: the provider also serves index-side passage embeds, so the gate must be keyed on `kind` and reach must be invented for the indexer; cost policy and transport reach leak into a transport adapter.+ - Con: refusal surfaces as a provider error that `semantic-phase` must map back onto its explicit/implicit arms and `brain_context_pack` onto `EMBEDDING_COST_UNPRICED`, so the typed-code mapping is duplicated anyway.+ - Con: `query_tokens` disclosure and `truncated` flag have to travel back up through a result shape change on `embed()`.+- **Complexity**: large+- **Risk**: medium++### Variant 2: Query-embed gateway module plus drift-checked writes+- **Approach**: Add one module (`src/core/search/embeddings/query-embed.ts`) exporting `prepareQueryEmbed({ query, reach, model, config })` that returns either a typed refusal (`EMBEDDING_COST_UNPRICED`) or a prepared input (`text`, `truncated`, `estimatedTokens` using the ceiling estimator minus a `queryPrefixSentByProvider` twin of the passage-prefix helper; no declared window means no truncation). `belief-semantic.ts` and `runSemanticPhase` both call it, with `search()` threading `transportReach` into `runSemanticLane`; the explicit arm throws, the implicit arm records the existing `RETRIEVAL_DEGRADATION` member, and `brain_recall_feedback` inherits the behaviour unchanged. Extra body is one flat key `embedding_request_extra` holding a JSON object string with env twin, validated against a `RESERVED_EMBEDDING_BODY_KEYS` const, excluded from index identity. `applyUpgrade(vault, plan?)` accepts the plan the caller already showed, snapshots, then writes each row through a new `expectBefore` option on `atomicWriteFileSync` (tri-state: `null` for absent) and raises `BrainUpgradeError` `UPGRADE_DRIFT` naming the files whose bytes moved.+- **Trade-offs**:+ - Pro: one rule in one named module, but the module stays query-specific so the indexer is untouched.+ - Pro: refusal codes, truncation disclosure and reach resolution are computed once and returned as data, so the two call sites only differ in how they surface them.+ - Pro: `expectBefore` is a reusable compare-and-swap primitive that mirrors `writePreferenceTxn` expectRevision and can be reused by other managed writers later.+ - Con: `before: ""` must become `before: string | null` in plan rows, a type change across planner, CLI renderer and self-heal worker.+ - Con: `embedding_request_extra` as a JSON string in flat YAML is a new value shape for the hand parser and its error message must name the key.+- **Complexity**: medium+- **Risk**: low++### Variant 3: Policy resolved at the entry points, plan-digest guarded upgrade+- **Approach**: `search()` and `brain_context_pack` each build a resolved `QueryEmbedPolicy` value (reach, price known, window or null) and pass it down; `runSemanticPhase` and `belief-semantic.ts` consume it through a small pure `applyQueryBudget(policy, query)` in `search/query-budget.ts`. Extra body fields use a flat prefix convention `embedding_body_<field>: value` with env twins, each scalar passed through as typed YAML, reserved names refused. `applyUpgrade(vault, sealedDigest)` keeps re-planning but seals the plan (digest over every row's path and `before`) like note revert, and refuses with `UPGRADE_PLAN_DRIFT` when the fresh plan's digest disagrees with the one the CLI or self-heal worker computed.+- **Trade-offs**:+ - Pro: smallest diff on the semantic lane; hooks and MCP callers need no change since reach resolution already happens in `search()`.+ - Pro: prefix keys fit the existing flat config vocabulary without a new value shape.+ - Con: the policy is assembled in two places, so the "one rule" is enforced by convention, not by a single function, and a new entry point can forget it.+ - Con: a plan digest guards the window between show-and-apply but not the window between re-plan and write, so a hand edit landing during the tar+zstd snapshot is still overwritten.+ - Con: prefix keys cannot express nested or array values, and the hand parser's unknown-key validation must learn a wildcard.+- **Complexity**: small+- **Risk**: medium++### Recommended: Variant 2+**Rationale**: The task's spine is "one rule on every surface", and only a query-specific gateway module makes that rule a single function both callers must go through without dragging cost policy into the provider adapter that also serves indexing. Its `expectBefore` write primitive closes the actual drift window at the moment of the write, which Variant 3's plan digest does not, and it follows the repo's existing expectRevision and sealed-digest precedents. The one JSON-object config key keeps the extra body expressive without a new wildcard key family in the hand-written YAML parser, and keeping it out of the index identity matches the v1.72.0 pricing precedent.diff --git a/docs/brainstorm/honest-query-embed-and-safe-upgrades/cli-output/prompt.md b/docs/brainstorm/honest-query-embed-and-safe-upgrades/cli-output/prompt.mdnew file mode 100644index 00000000..e9d81b11--- /dev/null+++ b/docs/brainstorm/honest-query-embed-and-safe-upgrades/cli-output/prompt.md@@ -0,0 +1,69 @@+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.++# Task++One release of Open Second Brain with four units that share one spine: every surface that turns a caller's query into a paid embedding obeys one rule, and managed-file upgrades write only bytes that still match what the plan read.++1. Reach and price gate on every query embed (follow-up from v1.72.0, no card). `brain_context_pack` semantic mode refuses a remote caller's query embed with `EMBEDDING_COST_UNPRICED` when `embedding_cost_gate_usd` is positive and the active embedding model has no known price (inline check in `src/core/brain/belief-semantic.ts:256-270`, which defaults an omitted reach to local). The search semantic lane (`src/core/search/semantic-phase.ts:133-140`, `runSemanticPhase`) embeds the query with no reach and no price check. It is reached by MCP `brain_search`, `brain_recall_feedback`, `brain_file_context`, `brain_eval`, `brain_benchmark`, `brain_tune`, and the `recall-inject` and `gap-promote` hooks (which pass no reach; `search()` resolves an omitted reach to remote via `resolvedTransportReach`). `SearchOptions.transportReach` already reaches `search()` but is not threaded into `runSemanticLane` / `runSemanticPhase`. The semantic phase has an explicit arm (caller asked for semantic: typed `SearchError`) and an implicit arm (warn + typed `RETRIEVAL_DEGRADATION` member, served keyword-only). `brain_recall_feedback` re-runs `search()` implicitly and records per-layer contributions into a learned-weight fold.++2. Compare-before-write in `applyUpgrade` (follow-up, no card). `src/core/brain/upgrade.ts:133-208`: `applyUpgrade(vault)` re-plans from scratch (the CLI already showed the operator its own plan; the self-heal worker planned too), takes a slow tar+zstd snapshot, then `atomicWriteFileSync(path, file.after)` for each `update` row with no check that disk still holds `file.before`. A hand edit to `_brain.yaml`, `_BRAIN.md` or a `Brain/preferences/*.md` file landing in that window is silently overwritten. Plan rows carry the full `before` string, but `before: ""` conflates an absent file with an empty one. Precedents for refusing on drift exist: note revert sealed plan digest (`notes/revert.ts:620-646`), migrate rollback digest mismatch, `writePreferenceTxn` expectRevision. `fs-atomic.ts` only offers `skipIfUnchanged` (compare against the NEW contents).++3. Card t_ddbfed93: truncate over-long search queries to the embedding input limit before embedding. No truncation exists on any query path. A declared per-model window exists: `EmbeddingModelPreset.inputWindowTokens` read by `declaredInputWindowTokens(model)` (null = unknown, never "fits"), used today only by the index-side oversize-chunk census, which subtracts the passage prefix the backend actually sends (`passagePrefixSentByProvider`). Token estimators: chars/4 floor (`estimateTokens`) and a two-sided ceiling (`tokenEstimateCeiling`) because chars/4 under-reports Han text about fourfold. No real tokenizer per provider. The query instruction prefix (`EmbedKind "query"`, e5 `"query: "`) is prepended inside `OpenAICompatProvider.embed`. MCP queries are capped at 2000 code points, which already exceeds the 512-token e5-small window. Most OpenAI-compatible serving stacks silently truncate over-long input; some refuse with HTTP 4xx (then explicit search throws, implicit degrades). The `brain_context_pack` semantic mode embeds a query too and discloses `query_tokens` without the prefix.++4. Card t_ebaac93f: configurable extra request body fields for OpenAI-compatible embedding endpoints. The body is fixed `{ model, input, encoding_format: "float" }` (`openai-compat.ts:459-463`). Config is a flat `key: value` YAML subset (no nested maps) parsed by hand, with env twins `OPEN_SECOND_BRAIN_EMBEDDING_<X>` and typed validators that fail with `INVALID_INPUT` naming the key. Identity of the vector index is `<provider>:<model>:<dimension>`; v1.72.0 precedent: a price is not part of the identity. Reserved-key refusal precedents: `RESERVED_UPDATE_FRONTMATTER_KEYS`, `RESERVED_REACH_ARGUMENTS` (normalised names).++# Project context++Open Second Brain: TypeScript on Bun, an MCP server + CLI over an Obsidian-compatible Markdown vault, SQLite + sqlite-vec search index. Current version 1.72.0.+Recent commits:+2b424d9a feat: honest embedding spend and a semantic belief order (v1.72.0) (#234)+2353cb1e feat: recall injection that arrives once and survives compaction (v1.71.0) (#232)+39c2f225 feat: scoped operator rules per project, harness and host, per-profile Hermes settings on a multiplexed gateway and readers that answer at the caller's reach (v1.70.0) (#229)+d49c4697 feat: ingest that reads CSV, TSV and HTML into table and parts sections, names the formats it skips and previews with o2b brain extract (v1.69.0) (#228)+f5c46615 feat: dependency facts from project manifests, Terraform seeds in the pre-extractor and readers that answer at the caller's reach (v1.68.0) (#227)+400b20ea feat: distillation pages that prove what they quote and say how much of their source the vault holds (v1.67.0)+3ec2334a feat: stable error codes on the MCP wire, typed rerank degradation and a rerank doctor check (v1.66.0) (#225)+a1ecfe7b feat: unattended maintenance recipes, install-owned lane tasks and an MCP fault guard (v1.65.0) (#224)+4499698c feat: search that honours pins and event time, diagnostics that prove action, writes that name their residue (v1.64.0) (#223)+a0b3c2e0 feat: exactly-one binding for mentions and imports, once-only write receipts, selectable search breadth and per-device ledgers (v1.63.0) (#222)+f4f9e3e6 feat: silent failures surface by name in redaction, receipts, ingest, search store, doctor (v1.62.0) (#220)+eb3c4c85 docs: concise README, ZCode client page, CLI reference and safety notes moved to child pages (#219)+f22df2c5 chore(apb): zg search, code-ranker and OpenCodeReview before push, scope-scan hardening (#218)+83979b9d fix: MCP startup off the upgrade path, fair ingest locks, inline plugin MCP manifest, inbox archive (v1.61.0) (#217)+3e59f319 feat: decision-model uses, adapters and setup skill (v1.60.0) (#215)+eacad953 feat: optional decision-model core and decision-model rerank kind (v1.59.0) (#214)+0afa0c5a chore(deps): bump the bun-minor-and-patch group with 5 updates (#201)+f6212cd2 fix: quiet one-line Stop reminder via Claude Code feedback channel (v1.58.2) (#202)+534befdb chore(deps): bump the github-actions group with 3 updates (#200)+5c550263 fix: session capture off the hook path, registry scanner hygiene (v1.58.1) (#199)+Related files:+src/core/search/semantic-phase.ts, src/core/search/pipeline/semantic-lane.ts, src/core/search/search.ts, src/core/search/types.ts, src/core/search/feedback.ts, src/core/search/embedding-spend.ts, src/core/search/retrieval-trail.ts, src/core/brain/belief-semantic.ts, src/core/brain/recall-inject.ts, src/core/brain/gaps/gap-recall.ts, src/core/search/embeddings/{openai-compat,presets,signature,pricing,contract}.ts, src/core/search/index.ts (config resolution), src/core/search/indexer.ts (census), src/core/brain/upgrade.ts, src/core/maintenance/self-heal-upgrade.ts, src/cli/brain/verbs/upgrade.ts, src/core/fs-atomic.ts+Conventions:+- SOLID, KISS, DRY; repeated literals hoisted into named constants; closed vocabularies registered as const objects.+- Errors surface explicitly by name (typed SearchError codes, BrainUpgradeError); no silent fallbacks; unknown reads as unknown, never as "fits" or "free".+- No hardcoded natural-language phrases beyond English messages; other languages handled abstractly (no per-language tables).+- Every release documents behaviour changes in CHANGELOG, docs/cli-reference.md, docs/how-it-works.md, docs/mcp.md, docs/updating.md.+- Config keys are flat `embedding_<noun>` with env twin; absent key = byte-identical old behaviour.+Constraints:+- No new external dependencies (no tokenizer libraries).+- Do not widen visibility: hooks keep their resolved reach (remote by default) because reach also filters reserved pages.+- Do not change existing public MCP argument names; additive response fields only.+- The extra body must never override `model`, `input` or `encoding_format`.+- Truncation never guesses a window: a model with no declared window is not truncated.++# Required output format++Produce exactly 3 distinct architectural variants. For each variant:++### Variant N: <short name>+- **Approach**: 2-3 sentences describing the variant.+- **Trade-offs**: bullet list of pros and cons.+- **Complexity**: small | medium | large+- **Risk**: low | medium | high++After the three variants, add exactly one recommendation:++### Recommended: Variant N+**Rationale**: 2-3 sentences explaining why this variant over the others, considering the project context and constraints above.++Output nothing outside of these sections.diff --git a/docs/brainstorm/honest-query-embed-and-safe-upgrades/design.md b/docs/brainstorm/honest-query-embed-and-safe-upgrades/design.mdnew file mode 100644index 00000000..5de76739--- /dev/null+++ b/docs/brainstorm/honest-query-embed-and-safe-upgrades/design.md@@ -0,0 +1,115 @@+# Honest Query Embed and Safe Upgrades - one rule for every paid query embed, and upgrades that write only what the plan read++**Status:** draft+**Author:** Open Second Brain maintainers (via feature-release-playbook)+**Audience:** implementation+**Target version:** 1.73.0 (minor: new config keys, new refusal on a search path, new degradation codes)++## Problem statement++In v1.72.0, `brain_context_pack` refuses a remote caller's query embed when the model has no known price and `embedding_cost_gate_usd` is positive. The search semantic lane embeds every query with no reach check and no price check. Six MCP tools (`brain_search`, `brain_recall_feedback`, `brain_file_context`, `brain_eval`, `brain_benchmark`, `brain_tune`) and two hooks therefore let a remote caller spend the operator's money on an unpriced model, despite the positive gate. The v1.72.0 release notes document this asymmetry.++The query is also sent at any length. A model with a 512-token window, served by an OpenAI-compatible stack, either silently describes a prefix of the query or refuses the request. The request body is fixed, so an endpoint that needs an extra field (Matryoshka `dimensions`, gateway metadata) cannot be used.++On the write side, `applyUpgrade` re-plans, takes a slow snapshot, then overwrites each managed file with bytes computed from what it read before the snapshot. A hand edit that lands in that window is silently lost.++## Premise verdicts (authoritative for scope)++Every claim was checked against the live source at `2b424d9a` (v1.72.0) before the brainstorm, using the zg index and direct reads. No card is refused. Each one is confirmed, and four claims needed correcting.++| Item | Verdict | Corrections and what is built |+|---|---|---|+| Follow-up: reach for `brain_search` and `brain_recall_feedback` (no card) | confirmed, widened | (1) The ungated site is one function, `runSemanticPhase` (`src/core/search/semantic-phase.ts:133-140`). It is reached by six MCP tools and the `recall-inject` and `gap-promote` hooks, not two tools. (2) `brain_recall_feedback` already passes the caller's reach into `search()` (`src/mcp/search-tools.ts:1502`). The gap is downstream: `search.ts` builds `semanticLaneInput` without reach, and neither `runSemanticLane` nor `runSemanticPhase` accepts one. (3) `belief-semantic.ts:224` resolves an omitted reach to local, while the rest of the tree (`resolvedTransportReach`) resolves it to remote. (4) The docblock at `src/core/search/types.ts:904-907` claims that recall feedback passes local reach, which is stale. Built: one shared gate that both query-embed sites call, with reach threaded into the lane. |+| Follow-up: compare-before-write in `applyUpgrade` (no card) | confirmed, extended | (1) `applyUpgrade` re-plans internally (`src/core/brain/upgrade.ts:139`), so the plan the CLI shows for confirmation, and the plan the self-heal worker computes, are not the plan applied. (2) Plan rows record `before: ""` for both an absent file and an empty file (`upgrade.ts:226`, `:257`). (3) The upgrade's preference repair does not take the per-file sync lock that `writePreferenceTxn` uses. Built: the applied plan is the caller's plan, every `update` row is checked against the disk before the first write and again right before its own rename, and drift is refused by name. |+| t_ddbfed93 truncate over-long queries | confirmed, corrected | (1) The validator anchor `semantic-phase.ts:135` is the `makeProvider` line; the embed is at `:136`. (2) "No per-input max-token configuration exists" is true for operator config, but a declared per-model window exists: `EmbeddingModelPreset.inputWindowTokens`, read by `declaredInputWindowTokens` (`presets.ts:37-53`, `:166-169`). Today only the index-side census reads it. (3) "The failure is already loud" holds only for serving stacks that refuse over-long input. The presets docblock (`presets.ts:37-46`) records that OpenAI-compatible stacks usually truncate silently and report nothing. The change therefore turns a silent server-side cut into a disclosed client-side cut, and a refusal into a working semantic lane. (4) A second query-embed site, `belief-semantic.ts:272`, must share the fit. Its disclosed `query_tokens` (`:273`) leaves out the instruction prefix the provider sends. (5) The 2000-code-point MCP cap already exceeds the 512-token e5-small window, so the problem is reachable over MCP today. Built: query fit to an effective window, with an operator key to declare the window of an uncurated model. |+| t_ebaac93f extra request body fields | confirmed, anchor corrected | (1) The validator anchor `openai-compat.ts:457` is the `authorization` header; the body is at `:459-463`. (2) No passthrough exists in any provider (`rg extraBody\|extra_body` over `src` finds nothing). (3) The config file cannot hold a nested map (`parseSimpleYaml`, `src/core/config.ts:146-170`), so the value is a JSON object in one flat key. Built for `openai-compat` only. ZeroEntropy is not an OpenAI-compatible endpoint, and the card names the rerank twin only as optional; both are deferred. |++## Scope++- **One query-embed gateway.** This is a new module, `src/core/search/embeddings/query-embed.ts`. `prepareQueryEmbed(config, query, reach)` returns a discriminated result:+ - `{ kind: "refused", code: "EMBEDDING_COST_UNPRICED", model }` when all three hold: reach is not local, `semantic.costGateUsd > 0`, and `activeSpendQuote(config).quote.source` is `unknown`.+ - Otherwise `{ kind: "ready", text, truncated, sentTokens, windowTokens, quote, model }`.++ The gate keeps v1.72.0's rule exactly (the unpriced arm only, never over-cap). It is now the one place that rule lives.+- **Reach threaded into the semantic lane.** `search()` passes the resolved `transportReach` into `SemanticLaneInput`, then into the `runSemanticPhase` options. The phase calls `prepareQueryEmbed` after the capability guard and before `makeProvider`. A refusal follows the phase's existing two arms:+ - explicit (`semantic: true`): throws `SearchError("EMBEDDING_COST_UNPRICED", ...)`, whose message names the model, `embedding_cost_gate_usd` and the price pair;+ - implicit: a warning plus the new `RETRIEVAL_DEGRADATION.semanticCostUnpriced`. The lane is not attempted, so `hybridDegraded` fires on its own.++ A query-cache hit still returns before any lane, and still spends nothing.+- **Query fit (t_ddbfed93).** The effective window is the operator key `embedding_input_window_tokens` when set, otherwise `declaredInputWindowTokens(model)`, otherwise unknown. When the window is known:+ - the budget is the window minus the ceiling estimate of the prefix the backend actually sends (`queryPrefixSentByProvider`, an exhaustive twin of `passagePrefixSentByProvider`);+ - the query is cut to the longest code-point prefix whose `tokenEstimateCeiling` fits the budget.++ An unknown window means no cut and no new warning, which is byte-identical to today. A cut search reports the warning plus `RETRIEVAL_DEGRADATION.semanticQueryTruncated` (`detail.windowTokens`). The lane still runs, so `hybridDegraded` does not fire.+- **Effective window feeds the census too.** `censusChunkWindow` reads the same resolver, so an operator-declared window also enables the oversize-chunk census for an uncurated model. One resolver means one answer.+- **Semantic belief order adopts the gateway.** `loadBeliefSemanticRelevance` replaces its inline gate with `prepareQueryEmbed`. An omitted reach now resolves through `resolvedTransportReach`, as everywhere else. The only production caller already passes reach. The embed sends the fitted text. The disclosed `query_tokens` is the estimate for the text actually sent, prefix included. A cut adds a warning to the existing `warnings` array.+- **Recall feedback discloses a gated re-run.** `captureRecallFeedback` returns the re-run's degradation codes, and the `brain_recall_feedback` response gains an additive `degraded` array. The recorded contributions still describe the ranking the caller's own search produces under the same rule. Neither the recording nor the fold changes.+- **Hook refusals become visible.** The recall retrievers carry the search trail's degradation codes into their result. `recall-inject` writes them to its local audit line, so a gated or degraded semantic lane at the hook is no longer silent. `plugins/hermes/_schemas.py` vendors no `brain_recall_feedback` response shape (verified), so it is untouched.+- **Hooks keep their reach.** `recall-inject` and `gap-promote` pass no reach today, so they resolve to remote, which also keeps reserved pages out of injected context. They are not widened. Under a positive gate with an unpriced model, their semantic lane therefore degrades by name. That is the gate doing its job on the most frequent embed in the system. The fix for a self-hosted model is to declare its price (0 for free), documented in `docs/updating.md`.+- **Extra request body (t_ebaac93f).** A new optional key, `embedding_extra_body`, with env twin `OPEN_SECOND_BRAIN_EMBEDDING_EXTRA_BODY`, holds a JSON object as a string.+ - Resolution refuses each of these with `INVALID_INPUT`, naming the key (and the env variable when it is the source): a blank value, invalid JSON, a non-object, and any key in `RESERVED_EMBEDDING_BODY_KEYS` (`model`, `input`, `encoding_format`). A reserved key is matched after the same normalisation `reach-refusal.ts` uses (NFC, lower case, `_` and `-` dropped), and the refusal lists the offending spellings.+ - `OpenAICompatProvider` spreads the fields into the request body before the owned fields, so the owned fields win structurally as well.+ - The fields are not part of the embedding identity, following the v1.72.0 price precedent. A width change caused by `dimensions` is caught by the existing response and index dimension checks, and a test pins that.+ - The egress row for `search-embedding-openai-compat` gains one sentence.+- **Compare-before-write upgrades.**+ - Plan rows record `before: string | null`, with null for an absent file. The JSON plan render keeps `before_size`, reporting 0 for null.+ - `fs-atomic.ts` gains the `expectBefore?: string | null` option on `atomicWriteFileSync`. It re-reads the target right before the rename and throws `FileDriftError` (with an `isFileDrift` guard), naming the path, when the target's state differs: present versus absent, or different bytes.+ - `applyUpgrade(vault, { plan? })` applies the caller's plan when given and plans itself otherwise. The CLI passes the plan it showed and the self-heal worker passes the plan it computed, which also removes the worker's double plan.+ - Before the snapshot, every `update` row is checked against the disk. Any drift refuses the whole run with `BrainUpgradeError`, with `runId` null, a `drifted` path list, and a message naming each path plus the re-run command. Nothing is written and no snapshot is taken.+ - Each write then passes `expectBefore: file.before`. A drift detected after earlier rows were written reuses the mid-apply message, which carries the rollback command.++## Out of scope++- An over-cap arm on the query gate. One query embed against a per-run spend cap is not a meaningful comparison, and v1.72.0 gates only the unpriced arm. Unchanged.+- Widening hook reach to local. It would leak reserved pages into injected context.+- A real tokenizer per provider (no new dependency). The ceiling estimate over-cuts non-ASCII text. That is the safe direction, and it is documented.+- Cutting at grapheme or word boundaries. The cut is at a code-point boundary, which is language-agnostic and never splits a surrogate pair.+- Extra body for ZeroEntropy, the rerank endpoint and the decision model. Extra headers are also out.+- An extra body per registry profile.+- Taking the self-heal worker lock in CLI `--apply`, and taking the per-file preference sync lock inside the upgrade. Compare-before-write turns both races from silent loss into a named refusal. The remaining window, between the final read and the rename, is the same advisory window `skipIfUnchanged` has, and it is documented.+- The hygiene dedup and entity alias detectors' live embeds. They still have no production caller, as v1.72.0 noted.++## Chosen approach++This is consultant Variant 2, "Query-embed gateway module plus drift-checked writes", accepted with three overrides.++**Override 1: key name `embedding_extra_body`, not `embedding_request_extra`.** The card, and the OpenAI client libraries operators already know, call this `extra_body`. The name says what it is.++**Override 2: an operator-declared window key.** The consultant left truncation to the curated preset table, which would cut queries for six local models only. An operator on any other model would have no way to declare a window, the same gap that v1.72.0 closed for prices with the price pair. `embedding_input_window_tokens` is a declared value with no default. Absent means unknown, and unknown means no cut.++**Override 3: drift is checked before the snapshot as well as at each write.** The per-write `expectBefore` alone would detect drift only after the slow snapshot and possibly after earlier rows were rewritten. A pre-flight pass refuses a run that is already stale, with nothing written and no snapshot to roll back.++Variant 1 (rules inside the provider) was rejected because it leaks cost and reach policy into the adapter that also serves indexing. Variant 3 (a policy assembled at each entry point, plus a plan digest) was rejected because it enforces the rule by convention and leaves the snapshot window open.++## Design decisions++- **A discriminated result, not a thrown refusal, from the gateway.** The two callers surface a refusal differently: the search lane has explicit and implicit arms, while the context pack always refuses. Returning data keeps one computation and lets each caller decide how to report it, without catch-by-code.+- **Reach and price only, not "remote" as a proxy for "paid".** The local hashing embedder is priced at 0 (`builtin`), so it is never refused. An Ollama or LM Studio model is unpriced until the operator declares it, as in v1.72.0.+- **Ceiling estimate for the cut, floor estimate for spend.** The cut must never send more than the window, so it uses the bound that cannot under-count. Spend disclosure keeps the shared `estimateTokens` the rest of the spend plan uses, so the receipts stay comparable.+- **A cut is reported as a degradation.** The lane ran on a prefix of what the caller sent. The trail vocabulary exists to say why recall narrowed, and the rule that `detail` carries integers only holds (`windowTokens`).+- **Extra-body fields are spread first, owned fields last.** Refusal is the primary guard, and the ordering is defence in depth, so a future reserved key cannot be overridden by accident.+- **`expectBefore` lives in `fs-atomic.ts`.** It is a reusable compare-and-swap primitive next to `skipIfUnchanged`, named like `FileAlreadyExistsError`, and other managed writers can adopt it later without a second implementation.+- **The applied plan is the shown plan.** The operator confirmed specific paths and diffs. Applying a re-plan could write something they never saw.++## File changes++New:+- `src/core/search/embeddings/query-embed.ts`: `prepareQueryEmbed`, `fitQueryToWindow` and the result types.+- `tests/core/search/query-embed.test.ts`, `tests/core/search/semantic-phase-spend-gate.test.ts`, `tests/core/search/embeddings.extra-body.test.ts`, `tests/core/search/embeddings.input-window.test.ts`, `tests/core/brain/upgrade-drift.test.ts`.++Modified:+- Search lane: `src/core/search/semantic-phase.ts`, `src/core/search/pipeline/semantic-lane.ts`, `src/core/search/search.ts`, `src/core/search/types.ts` (the reach docblock, `inputWindowTokens?`, `extraBody?`), `src/core/search/retrieval-trail.ts` (two members, closed list, sentences).+- Embedding configuration: `src/core/search/index.ts` (two keys, validation), `src/core/search/embeddings/presets.ts` (`queryPrefixSentByProvider`, `effectiveInputWindowTokens`), `src/core/search/embeddings/openai-compat.ts`, `src/core/search/indexer.ts` (census via the resolver).+- Readers: `src/core/brain/belief-semantic.ts`, `src/core/search/feedback.ts`, `src/mcp/search-tools.ts` (additive `degraded`), `src/core/brain/recall-inject.ts` and `src/core/brain/gaps/gap-recall.ts` (carry the trail codes to the local audit).+- Upgrade: `src/core/fs-atomic.ts`, `src/core/brain/upgrade.ts`, `src/cli/brain/upgrade-render.ts`, `src/cli/brain/verbs/upgrade.ts`, `src/core/maintenance/self-heal-upgrade.ts`.+- Docs (phase 5): `CHANGELOG.md`, `README.md`, `docs/cli-reference.md`, `docs/how-it-works.md`, `docs/mcp.md`, `docs/updating.md`, `skills/embeddings-setup/SKILL.md` (then `bun run sync-plugin-mirrors`).+- Version manifests via `scripts/sync-version.ts`.++## Risks and open questions++- **Hook behaviour under a positive gate.** Operators who run a positive gate with an unpriced self-hosted model lose the semantic lane of recall injection until they declare a price. This is intended, but it is visible, so it gets its own `docs/updating.md` section. Spec review confirmed that `defaultRecallRetriever` (`src/core/brain/recall-inject.ts:1122-1160`) maps only `outcome.results` and drops `warnings` and the retrieval trail. Every semantic degradation is already silent at the hook today, so the new refusal would be too. This PR carries the trail codes into `RecallResultSet` and onto the local audit line `recallInjectAuditDetails` (`:1053-1077`), next to the decision-model degrade reason. Codes only; the synced telemetry record stays unchanged.+- **Tests that pin the old asymmetry.** `tests/core/brain/belief-semantic.test.ts:464` and `tests/mcp/context-pack-tool.test.ts:875-910` pin "local caller ungated". That stays true, so they should stay green. Tests that call `loadBeliefSemanticRelevance` with no reach under a positive gate change meaning, and must be audited and pass reach explicitly.+- **MCP harness tests without reach.** `tests/mcp/embedding-abi-visibility.test.ts` uses an unpriced `fake-model` with no reach (so remote) and gate 0. It stays green because the gate is off. Any test combining a positive gate with an unpriced model and no reach will change meaning.+- **`dimensions` in the extra body.** It must be verified that a width differing from the stored index surfaces as a named error and not as an empty result. If it does not, `dimensions` that disagrees with `embedding_dimension` is refused at config resolution.+- **Non-atomic compare and rename.** A write landing between the final re-read and `rename(2)` is still lost. Closing that needs an OS-level lock that the vault's sync tools do not honour, so it is documented, not solved.+- **`before: null` type change.** It touches the planner, the renderer, the worker and the tests. The JSON contract keeps `before_size`, so no consumer breaks.diff --git a/docs/brainstorm/honest-query-embed-and-safe-upgrades/plan.md b/docs/brainstorm/honest-query-embed-and-safe-upgrades/plan.mdnew file mode 100644index 00000000..bdefce48--- /dev/null+++ b/docs/brainstorm/honest-query-embed-and-safe-upgrades/plan.md@@ -0,0 +1,118 @@+# Honest Query Embed and Safe Upgrades - implementation plan++Every task is TDD: write the failing test, watch it fail for the expected reason, implement, refactor green. Run the formatter and linter before every commit (`bun run fmt`, `bun run lint`, `bun run typecheck`). One conventional commit per task.++## Tasks++### Task 1: Effective input window and the query prefix the backend sends+- **Files**: `src/core/search/types.ts` (`inputWindowTokens?` on `ResolvedEmbeddingConfig`), `src/core/search/index.ts` (key `embedding_input_window_tokens` / env `OPEN_SECOND_BRAIN_EMBEDDING_INPUT_WINDOW_TOKENS`, `parseInteger(raw, 0, key, { min: 1 })`, and post-merge validation in `validateResolvedConfig`), `src/core/search/embeddings/presets.ts` (`effectiveInputWindowTokens(semantic)`: operator key, then `declaredInputWindowTokens(model)`, then null; `queryPrefixSentByProvider(provider, configuredQueryPrefix)` as an exhaustive switch), `src/core/search/indexer.ts` (`censusChunkWindow` reads `effectiveInputWindowTokens`), `tests/core/search/embeddings.input-window.test.ts`.+- **Acceptance**:+ - absent key: the field stays absent and the `Object.keys(semantic)` pin in `embeddings.batch-tokens.test.ts` is unchanged;+ - config and env both set the key;+ - 0, a fraction and a blank value are refused with `INVALID_INPUT` naming the key, both from the string and from an override;+ - the operator key beats the preset window, the preset window applies when the key is absent, and an unknown model with no key resolves to null;+ - `queryPrefixSentByProvider` returns the configured query prefix only for `openai-compat`;+ - the census reports an over-window chunk for an uncurated model once the key is set.+- **Depends on**: none++### Task 2: Query fit to the window+- **Files**: `src/core/search/embeddings/query-embed.ts` (`fitQueryToWindow(query, prefix, windowTokens | null)` returning `{ text, truncated, sentTokens }`), `tests/core/search/query-embed.test.ts`.+- **Acceptance**:+ - a null window returns the query unchanged with `truncated: false`;+ - an ASCII query over the window is cut so that `tokenEstimateCeiling(prefix + text) <= window`, and one more code point would exceed it;+ - a Han query is cut under the ceiling bound, never the floor;+ - a cut never splits a surrogate pair (an astral-plane character at the boundary);+ - a prefix that alone fills the window gives an empty text with `truncated: true`, and the caller treats that as a degradation, not an embed;+ - `sentTokens` counts the prefix.+- **Depends on**: Task 1++### Task 3: The query-embed gateway (reach and price gate)+- **Files**: `src/core/search/embeddings/query-embed.ts` (`prepareQueryEmbed(config, query, reach)` returning `refused | ready`, using `activeSpendQuote`, `COST_GATE_KEY`, `EMBEDDING_PRICE_SOURCE`, `TRANSPORT_REACH`), `tests/core/search/query-embed.test.ts`.+- **Acceptance**:+ - remote + positive gate + unpriced: `refused`, carrying the model;+ - local + positive gate + unpriced: `ready`;+ - remote + gate 0: `ready`;+ - remote + positive gate + operator-priced: `ready`;+ - the local provider: `ready` (builtin price 0);+ - the `ready` result carries the fitted text from Task 2 and the quote;+ - no provider is constructed by the gateway (it is pure over config).+- **Depends on**: Task 2++### Task 4: Reach threaded into the semantic lane, gated and fitted+- **Files**: `src/core/search/search.ts` (pass the resolved reach into `semanticLaneInput`), `src/core/search/pipeline/semantic-lane.ts` (`SemanticLaneInput.transportReach`, forwarded), `src/core/search/semantic-phase.ts` (reach in opts, `prepareQueryEmbed` after the capability guard, the explicit arm throws `EMBEDDING_COST_UNPRICED` naming the model, the gate key and the price pair, the implicit arm warns plus `semanticCostUnpriced`, a cut warns plus `semanticQueryTruncated { windowTokens }`, the fitted text is embedded), `src/core/search/retrieval-trail.ts` (two members, the closed list, the sentence switch), `src/core/search/types.ts` (fix the stale reach docblock at `:904-907`), `tests/core/search/semantic-phase-spend-gate.test.ts`.+- **Acceptance**, using `startFakeHttp` and `callCount()`:+ - remote implicit search under a positive gate and an unpriced model sends no embed, returns keyword results, and the trail carries `semantic-cost-unpriced` and `hybrid-degraded`;+ - remote explicit search throws `EMBEDDING_COST_UNPRICED` with `callCount() === 0`;+ - local search embeds once;+ - an MCP `brain_search` over `MCPServer({..},{ reach: "remote" })` refuses before the embed, and a local server embeds once;+ - an over-window query with a declared window embeds the cut text (the captured `input` length is checked) and the trail carries `semantic-query-truncated` without `hybrid-degraded`;+ - the existing `semantic-degrade-quota`, `semantic-explicit-blocked`, `capability-tier` and `hybrid-deadline` tests stay green.+- **Depends on**: Task 3++### Task 5: The semantic belief order adopts the gateway+- **Files**: `src/core/brain/belief-semantic.ts` (replace the inline gate with `prepareQueryEmbed`, resolve an omitted reach with `resolvedTransportReach`, embed the fitted text, `queryTokens` from the gateway, a cut warning in `warnings`, fix the docblocks at `:85-86` and `:257-260`), `tests/core/brain/belief-semantic.test.ts`, `tests/mcp/context-pack-tool.test.ts`.+- **Acceptance**:+ - the existing remote refusal (`:449`) and local embed (`:464`) tests stay green;+ - a call with no reach under a positive gate and an unpriced model is now refused;+ - the disclosed `query_tokens` includes the instruction prefix for an e5 model;+ - an over-window query is embedded cut, with one warning;+ - the wire test `:875` stays green.+- **Depends on**: Task 3++### Task 6: Recall feedback discloses the gated re-run+- **Files**: `src/core/search/feedback.ts` (the outcome gains `degraded: ReadonlyArray<RetrievalDegradationCode>` from the re-run trail), `src/mcp/search-tools.ts` (additive `degraded` in the `brain_recall_feedback` response), `tests/mcp/recall-feedback-tool.test.ts`.+- **Acceptance**:+ - a remote feedback call under a positive gate and an unpriced model sends no embed, records the event, and returns `degraded` containing `semantic-cost-unpriced`;+ - a local call embeds once and returns an empty `degraded`;+ - the CLI twin `learned-weights` is unchanged.+- **Depends on**: Task 4++### Task 7: Hook refusals become visible+- **Files**: `src/core/brain/recall-inject.ts` (`RecallResultSet.degraded`, filled from `outcome.retrievalTrail?.degraded` in `defaultRecallRetriever`; the codes are carried onto `recallInjectAuditDetails`), `src/core/brain/gaps/gap-recall.ts` (the same codes on `gapScopedRecallRetriever`'s result), `tests/core/brain/recall-inject*.test.ts`, `tests/core/brain/gaps/*.test.ts`.+- **Acceptance**:+ - the recall-inject retriever under a positive gate and an unpriced model sends no embed, returns keyword candidates, and its result carries `semantic-cost-unpriced`;+ - the local audit details carry the codes;+ - the synced telemetry metadata (`recallInjectTelemetryMetadata`) is unchanged;+ - no hook passes local reach (the reserved-page filter is unchanged);+ - existing recall-inject and gap-promote tests stay green.+- **Depends on**: Task 4++### Task 8: Extra request body for OpenAI-compatible endpoints+- **Files**: `src/core/search/types.ts` (`extraBody?: Readonly<Record<string, unknown>>`), `src/core/search/index.ts` (key `embedding_extra_body` / env `OPEN_SECOND_BRAIN_EMBEDDING_EXTRA_BODY`, JSON object parse, `RESERVED_EMBEDDING_BODY_KEYS` with normalised matching, `INVALID_INPUT` naming the key or env variable and the refused spellings), `src/core/search/embeddings/openai-compat.ts` (spread `extraBody` before the owned fields), `tests/core/search/embeddings.extra-body.test.ts`.+- **Acceptance**:+ - absent key: the request body is exactly `{ model, input, encoding_format }` (a new pin via the fake-http handler body);+ - a declared `{ "dimensions": 256, "user": "x" }` arrives in the body next to the owned fields;+ - each of `model`, `Input`, `encoding-format` is refused, naming the spelling;+ - invalid JSON, an array, a scalar and a blank value are each refused, naming the key;+ - an env value beats config;+ - the embedding identity is unchanged by the key (no reindex is required);+ - a response width that differs from the stored index surfaces as a named error, not an empty result (if not, refuse a `dimensions` that disagrees with `embedding_dimension` at resolution and pin that instead).+- **Depends on**: none++### Task 9: Compare-before-write primitive+- **Files**: `src/core/fs-atomic.ts` (`AtomicWriteOptions.expectBefore?: string | null`, `FileDriftError`, `isFileDrift`), `tests/core/fs-atomic.test.ts`.+- **Acceptance**:+ - matching bytes write;+ - different bytes throw `FileDriftError` naming the path and leave the target untouched;+ - `null` with an absent target writes, and `null` with a present target throws;+ - a string expectation with an absent target throws;+ - the option composes with `skipIfUnchanged`;+ - no temp file is left after a refusal.+- **Depends on**: none++### Task 10: Upgrades apply the shown plan and refuse drift+- **Files**: `src/core/brain/upgrade.ts` (`before: string | null`, `applyUpgrade(vault, { plan?, agent?, now? })`, a pre-snapshot drift pass, `expectBefore` per write, `BrainUpgradeError.drifted`), `src/cli/brain/upgrade-render.ts` (null-safe `before_size` and diff), `src/cli/brain/verbs/upgrade.ts` (pass the shown plan), `src/core/maintenance/self-heal-upgrade.ts` (pass its plan; drop the double plan), `tests/core/brain/upgrade-drift.test.ts`, `tests/core/brain/upgrade.test.ts`, `tests/core/maintenance/self-heal-upgrade.test.ts`, `tests/cli/brain-upgrade.test.ts`.+- **Acceptance**:+ - a missing `_brain.yaml` plans `before: null`, and an empty one plans `before: ""`;+ - a hand edit made after the plan and before the apply refuses with `drifted` naming the path, no snapshot is created, and the edit survives;+ - an edit injected between the snapshot and the write (via a spy on `createSnapshot`) refuses at that row with the rollback command, and the edit survives;+ - a clean apply is unchanged (snapshot, log row, idempotent re-run);+ - the CLI `--apply --yes` applies the plan it printed;+ - the worker calls `planUpgrade` once per attempt;+ - all existing upgrade, self-heal and CLI tests stay green.+- **Depends on**: Task 9++### Task 11: Docs, CHANGELOG and version 1.73.0 (phase 5, in osb-pr-prepare)+- **Files**: `CHANGELOG.md` (`## [1.73.0] - YYYY-MM-DD` with the day the PR is prepared and the compare link), `README.md` ("What is new"), `docs/cli-reference.md` (both keys, the query gate, the egress sentence), `docs/how-it-works.md` (the gateway bullet, plus a correction to the 1.72.0 "as for search" sentence in the current-behaviour text), `docs/mcp.md` (the `brain_search` spend refusal, `brain_recall_feedback.degraded`, the two degradation codes), `docs/updating.md` ("Upgrading to 1.73.0": hooks under a positive gate, declare a price for a self-hosted model), `skills/embeddings-setup/SKILL.md`, then `bun run sync-plugin-mirrors`, the `package.json` bump plus `bun run scripts/sync-version.ts`.+- **Acceptance**: `bun run sync-version:check` and `bun run sync-plugin-mirrors:check` pass; every key, code and command named in the docs exists in the source.+- **Depends on**: Tasks 1-10diff --git a/docs/brainstorm/honest-query-embed-and-safe-upgrades/variants.md b/docs/brainstorm/honest-query-embed-and-safe-upgrades/variants.mdnew file mode 100644index 00000000..58e178f1--- /dev/null+++ b/docs/brainstorm/honest-query-embed-and-safe-upgrades/variants.md@@ -0,0 +1,53 @@+# Honest Query Embed and Safe Upgrades - variants++The variants come from the primary consultant (`claude -p`, exit 0, 3 variants; `cli-output/claude.md`). The prompt is `cli-output/prompt.md`. The fallback consultant was not run, because the primary returned three parseable variants.++## Consultant output (verbatim)++### Variant 1: Provider choke point+- **Approach**: Move every query-embed rule into the embedding provider layer: `embed(texts, { kind, reach })` performs the reach-and-price gate, the window truncation (it already knows the prefix it prepends) and the extra-body merge, so `belief-semantic.ts` drops its inline check and `runSemanticPhase` only threads `transportReach` through. Compare-before-write lands as a new `expectBefore` option on `atomicWriteFileSync` in `fs-atomic.ts` with a tri-state expectation (absent, or exact bytes), and `applyUpgrade` passes each row's `before` through it.+- **Trade-offs**:+ - Pro: literally one place; impossible to add a query surface that bypasses the rule.+ - Pro: truncation sees the real prefix and model window, no mirrored estimate needed.+ - Con: the provider also serves index-side passage embeds, so the gate must be keyed on `kind` and reach must be invented for the indexer; cost policy and transport reach leak into a transport adapter.+ - Con: refusal surfaces as a provider error that `semantic-phase` must map back onto its explicit/implicit arms and `brain_context_pack` onto `EMBEDDING_COST_UNPRICED`, so the typed-code mapping is duplicated anyway.+ - Con: `query_tokens` disclosure and `truncated` flag have to travel back up through a result shape change on `embed()`.+- **Complexity**: large+- **Risk**: medium++### Variant 2: Query-embed gateway module plus drift-checked writes+- **Approach**: Add one module (`src/core/search/embeddings/query-embed.ts`) exporting `prepareQueryEmbed({ query, reach, model, config })` that returns either a typed refusal (`EMBEDDING_COST_UNPRICED`) or a prepared input (`text`, `truncated`, `estimatedTokens` using the ceiling estimator minus a `queryPrefixSentByProvider` twin of the passage-prefix helper; no declared window means no truncation). `belief-semantic.ts` and `runSemanticPhase` both call it, with `search()` threading `transportReach` into `runSemanticLane`; the explicit arm throws, the implicit arm records the existing `RETRIEVAL_DEGRADATION` member, and `brain_recall_feedback` inherits the behaviour unchanged. Extra body is one flat key `embedding_request_extra` holding a JSON object string with env twin, validated against a `RESERVED_EMBEDDING_BODY_KEYS` const, excluded from index identity. `applyUpgrade(vault, plan?)` accepts the plan the caller already showed, snapshots, then writes each row through a new `expectBefore` option on `atomicWriteFileSync` (tri-state: `null` for absent) and raises `BrainUpgradeError` `UPGRADE_DRIFT` naming the files whose bytes moved.+- **Trade-offs**:+ - Pro: one rule in one named module, but the module stays query-specific so the indexer is untouched.+ - Pro: refusal codes, truncation disclosure and reach resolution are computed once and returned as data, so the two call sites only differ in how they surface them.+ - Pro: `expectBefore` is a reusable compare-and-swap primitive that mirrors `writePreferenceTxn` expectRevision and can be reused by other managed writers later.+ - Con: `before: ""` must become `before: string | null` in plan rows, a type change across planner, CLI renderer and self-heal worker.+ - Con: `embedding_request_extra` as a JSON string in flat YAML is a new value shape for the hand parser and its error message must name the key.+- **Complexity**: medium+- **Risk**: low++### Variant 3: Policy resolved at the entry points, plan-digest guarded upgrade+- **Approach**: `search()` and `brain_context_pack` each build a resolved `QueryEmbedPolicy` value (reach, price known, window or null) and pass it down; `runSemanticPhase` and `belief-semantic.ts` consume it through a small pure `applyQueryBudget(policy, query)` in `search/query-budget.ts`. Extra body fields use a flat prefix convention `embedding_body_<field>: value` with env twins, each scalar passed through as typed YAML, reserved names refused. `applyUpgrade(vault, sealedDigest)` keeps re-planning but seals the plan (digest over every row's path and `before`) like note revert, and refuses with `UPGRADE_PLAN_DRIFT` when the fresh plan's digest disagrees with the one the CLI or self-heal worker computed.+- **Trade-offs**:+ - Pro: smallest diff on the semantic lane; hooks and MCP callers need no change since reach resolution already happens in `search()`.+ - Pro: prefix keys fit the existing flat config vocabulary without a new value shape.+ - Con: the policy is assembled in two places, so the "one rule" is enforced by convention, not by a single function, and a new entry point can forget it.+ - Con: a plan digest guards the window between show-and-apply but not the window between re-plan and write, so a hand edit landing during the tar+zstd snapshot is still overwritten.+ - Con: prefix keys cannot express nested or array values, and the hand parser's unknown-key validation must learn a wildcard.+- **Complexity**: small+- **Risk**: medium++### Recommended: Variant 2+**Rationale**: The task's spine is "one rule on every surface", and only a query-specific gateway module makes that rule a single function both callers must go through without dragging cost policy into the provider adapter that also serves indexing. Its `expectBefore` write primitive closes the actual drift window at the moment of the write, which Variant 3's plan digest does not, and it follows the repo's existing expectRevision and sealed-digest precedents. The one JSON-object config key keeps the extra body expressive without a new wildcard key family in the hand-written YAML parser, and keeping it out of the index identity matches the v1.72.0 pricing precedent.++## Orchestrator decision++Variant 2 is accepted, as the consultant recommended, with three overrides. The full rationale is in `design.md`, "Chosen approach".++1. **Key name.** The key is `embedding_extra_body`, not `embedding_request_extra`. It matches the card and the `extra_body` name operators already know from OpenAI client libraries.+2. **An operator-declared input window** (`embedding_input_window_tokens`). Without it, query truncation would reach only the six curated preset models. This mirrors how v1.72.0 let the operator declare a price for an uncurated model. Absent means unknown, and unknown means no cut.+3. **A drift pre-flight before the snapshot,** in addition to the per-write `expectBefore`. A run that is already stale is refused with nothing written and no snapshot taken.++Variant 1 is rejected because it puts cost and reach policy inside the provider adapter that also serves indexing, and it still duplicates the typed-code mapping at both callers. Variant 3 is rejected because "one rule" would rest on each entry point remembering to build the policy. Its plan digest also leaves the read-to-write window during the snapshot open, which is the exact window the follow-up is about.++Spec review (phase 1) found two things. First, `defaultRecallRetriever` drops the search trail, so a gated lane at the hooks would be silent. A task now carries the codes to the local audit line. Second, `plugins/hermes/_schemas.py` vendors no `brain_recall_feedback` response shape, so it is not touched.diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex 1403daca..eff65f88 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -152,6 +152,23 @@ each consecutive failure up to 24 hours, instead of repeating the samefailing upgrade on every start. `o2b brain upgrade --apply --yes` ignoresthe cooldown and clears the record once nothing is pending.+Since v1.73.0 an upgrade applies exactly the plan it showed.+`o2b brain upgrade --apply` and the automatic worker plan once and apply+that plan; each planned row records the bytes it was read with, or that+the file was absent. A managed file that changed on disk after the plan+was read is refused before the snapshot is taken: nothing is written, and+the message names the files and advises `o2b brain upgrade --dry-run` to+review a plan that reads the edit. Each write checks the file again right+before it replaces it, so an edit that lands mid-apply is left as it is;+when earlier files were already rewritten the message names them and+advises the same dry-run re-plan; a rollback is deliberately not+offered, because the pre-apply snapshot predates the rewritten files,+so its own drift guard would refuse it, and forcing it would destroy+the edit. With `--apply --json`+a refusal prints `{ "ok": false, "error", "run_id", "drifted" }`, where+`drifted` lists the refused paths. A file that holds bytes which are not+valid UTF-8 and was not edited still upgrades.+### The codegraph partner check`o2b doctor` consults the optional [codegraph](https://github.com/colbymchenry/codegraph)@@ -2007,6 +2024,9 @@ so there is no separate lane field that could drift from it:| `semantic-embeddings-absent` | the index holds no compatible embedding || `semantic-vec-extension-unavailable` | sqlite-vec is not loaded on this machine || `semantic-capability-blocked` | the configured semantic capability blocks the vector lane; `detail.tier` names the rung |+| `semantic-cost-unpriced` | the embedding model has no known price and `embedding_cost_gate_usd` is positive, so the query embed of a caller that is not local was refused before any provider call and the semantic lane did not run |+| `semantic-query-truncated` | the query was longer than the effective embedding input window, so the semantic lane searched a cut prefix of it; `detail.windowTokens` is the window |+| `semantic-query-empty-fit` | the instruction prefix alone fills the effective embedding input window, so no part of the query was left to embed and the semantic lane did not run; `detail.windowTokens` is the window || `semantic-provider-unavailable` | the embedding provider could not answer; `detail.category` carries the error category || `semantic-empty-query-vector` | the provider answered with an empty query vector || `semantic-structured-lanes-skipped` | a structured semantic lane was requested while semantic search is off |@@ -2130,6 +2150,88 @@ refusal, and the receipt then records `forced: true`, `price_source:unknown` and a null estimate. With the gate at 0 (the default) nothing isrefused.+Query embeds (since v1.73.0). Every paid query embed passes one gate: the+search lane (reached by `o2b search`, `brain_search`,+`brain_recall_feedback`, `brain_file_context`, `brain_eval`,+`brain_benchmark`, `brain_tune` and the recall-inject and gap-promote+hooks) and the `brain_context_pack` semantic belief order. Under a+positive `embedding_cost_gate_usd`, a caller that is not local is refused+the query embed of a model with no known price before any provider is+called. A search that asked for the semantic lane by name fails with+`EMBEDDING_COST_UNPRICED`; a hybrid search falls back to keyword-only,+says so in a warning and records `semantic-cost-unpriced` in its trail.+The message names the model and the price pair that clears the refusal,+and says only that the gate is positive, never its amount. The CLI runs+at local reach, so `o2b search` is not gated, as before. The hooks run at+remote reach: under a positive gate on an unpriced model they recall by+keyword only and name the code on their local audit line+(`retrieval_degraded`). Declare the price (`0` for a free self-hosted+model) to bring the semantic lane back.++The same gate fits the query to the model's input window before it is+sent. The effective window is `embedding_input_window_tokens` when set,+then the window the curated model table declares, then unknown; an+unknown window cuts nothing. The cut counts the instruction prefix the+provider sends, is made at a code-point boundary under the conservative+token estimate, and is disclosed: a warning names the window and how much+of the query was embedded, and the trail records+`semantic-query-truncated` with `detail.windowTokens`. When the+instruction prefix alone fills the window nothing is embedded: an explicit+semantic search and the semantic belief order refuse with `INVALID_INPUT`,+and a hybrid search falls back to keyword-only with the trail code+`semantic-query-empty-fit`, which, unlike a cut, always means the+semantic lane did not run.+An answer refused by the gate is never cached, so declaring a price takes+effect on the next search. An answer cut to the window is cached under a+key that carries the effective window and the query prefix, so a repeated+long query is not embedded again, and a declared or changed window takes+effect on the next search.+`brain_context_pack` discloses `query_tokens` for the text actually sent,+instruction prefix included, and its omitted reach now resolves to remote+like every other reader.++`embedding_input_window_tokens`+(`OPEN_SECOND_BRAIN_EMBEDDING_INPUT_WINDOW_TOKENS`, since v1.73.0)+declares the input window, in the model's own tokens, of a model the+curated table does not list, or overrides the table's value. It is an+integer of at least 1; a blank value is refused rather than read as+unset. The chunk-window census of an index run and of `o2b search status`+reads the same window, so a declared window enables it for an uncurated+model. The+offline `local` embedder has no input window, so the key is refused with+`INVALID_INPUT` when `embedding_provider` is `local`.++`embedding_extra_body` (`OPEN_SECOND_BRAIN_EMBEDDING_EXTRA_BODY`, since+v1.73.0) sends operator-declared fields with every embedding request to an+OpenAI-compatible endpoint, for a serving stack that needs a field the+provider does not send (a `dimensions` value, a truncation switch). The+value is one JSON object in one key, because the flat config format+cannot hold a nested map:++```yaml+embedding_extra_body: '{"dimensions": 512}'+embedding_dimension: 512+```++The owned request fields `model`, `input` and `encoding_format` may not+be set, in any spelling (case, `_` and `-`, fullwidth and zero-width+variants are folded before the comparison), and are refused by name with+`INVALID_INPUT`. A blank value, invalid JSON or a JSON value that is not+an object is refused the same way, naming the env variable or the key+that supplied it. Only `openai-compat` sends the body, so the key is+refused for any other provider; `disabled` sends nothing and is exempt. A+`dimensions` field changes the width the provider answers with, so it+requires `embedding_dimension` and must agree with it. The checks run on+the resolved config, so a programmatic override meets them too. The extra+body is not part of the embedding identity: declaring or editing it never+triggers a reindex. Some fields shape the vectors the provider returns+(a provider `task`, `input_type`, `normalize` or `truncate` switch); after+changing such a field, rebuild the vectors with+`o2b search reindex --embeddings` so new query vectors stay in the space+of the stored passages. Nothing triggers that rebuild on its own, and+`o2b search index --force` is not enough: an unchanged chunk keeps its+stored vector.+Vector carry-over (since v1.72.0). When a note is edited, a chunk whosecontent did not change keeps its stored vector, provided the vector waswritten by the model and dimension the index records. Only changed chunks@@ -2354,7 +2456,7 @@ by the id below.| id | verb | what leaves | when it can happen || --- | --- | --- | --- |-| `search-embedding-openai-compat` | `o2b search index` / any reindex | every indexed chunk BODY, verbatim | only once `search_embedding_endpoint` + an API key are configured; the endpoint is whichever host you name, including a local one |+| `search-embedding-openai-compat` | `o2b search index` / any reindex | every indexed chunk BODY, verbatim, plus any fields declared in `embedding_extra_body` | only once `search_embedding_endpoint` + an API key are configured; the endpoint is whichever host you name, including a local one || `search-embedding-zeroentropy` | `o2b search index` (zeroentropy profile) | the same chunk bodies, to a second vendor's embed endpoint | same gate, when that provider profile is selected || `search-rerank-cross-encoder` | `o2b search --rerank` | the QUERY plus the top-of-pool candidate DOCUMENTS - vault text the embedding path may never have seen, chosen by relevance to what you just asked | only with a reranker endpoint configured || `brain-telegram-capture` | `o2b brain telegram-run` | reply text POSTed to the Telegram Bot API; the `/catchup` reply is composed from vault content | only while the runner verb is running; an install that never starts it never reaches this path |diff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex aec31bdc..053e988f 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -660,7 +660,7 @@ are mirrored in MCP; destructive operations are CLI-only by design.| Toggle pin | `o2b brain pin / unpin` | โ (CLI-only) | flips `pinned` field; regenerates `Brain/active.md` || Protect Brain/ | `o2b brain protect / unprotect` | โ (CLI-only) | machine-enforced deny rules for `claudecode` / `codex` runtimes; sidecar manifest at `.open-second-brain/protect.lock.json` || Restore snapshot | `o2b brain rollback` | โ (CLI-only) | overwrites Brain/ from snapshot; from v0.10.6 aborts on drift unless `--force-rollback`, see [Snapshots and rollback](#snapshots-and-rollback) |-| Upgrade managed files | `o2b brain upgrade` | โ (CLI-only) | migrates the three release-owned files (`_brain.yaml`, `_BRAIN.md`, `_OPEN_SECOND_BRAIN.md`) forward. `_brain.yaml` is text-merged additively (user values, comments, and ordering preserved); the other two are byte-compared and overwritten. `--dry-run` prints a per-file plan; `--check` exits 2 on pending updates (CI-friendly); `--apply --yes` takes an `upgrade-<ts>` snapshot before rewriting. After a plugin update the MCP server and the `SessionStart` hook run the same upgrade in a detached worker, off the start-up path, and back off after a failure (see `docs/updating.md`). |+| Upgrade managed files | `o2b brain upgrade` | โ (CLI-only) | migrates the three release-owned files (`_brain.yaml`, `_BRAIN.md`, `_OPEN_SECOND_BRAIN.md`) forward. `_brain.yaml` is text-merged additively (user values, comments, and ordering preserved); the other two are byte-compared and overwritten. `--dry-run` prints a per-file plan; `--check` exits 2 on pending updates (CI-friendly); `--apply --yes` applies the plan it showed: a file edited after the plan was read is refused before the `upgrade-<ts>` snapshot, and again at each write, instead of being overwritten. After a plugin update the MCP server and the `SessionStart` hook run the same upgrade in a detached worker, off the start-up path, and back off after a failure (see `docs/updating.md`). || Export active prefs | `o2b brain export --format json\|llms-txt` | โ (CLI-only) | read-only dump of `confirmed \| unconfirmed \| quarantine` preferences from `Brain/preferences/`. `--out <path>` writes a file (refuses to overwrite without `--force`); default sink is stdout. Retired and signal artifacts are deliberately excluded. || Export a transcript corpus | `o2b brain export --format transcripts-jsonl --transcripts <file\|dir>` | โ (CLI-only) | since v1.50.0: one JSON object per line, one per CONVERSATION, built from recorded session logs. Reads no vault. Messages carry role, text and the NAMES of the tools a turn called, never the tool inputs. `--runtime` filters by adapter; `--since`/`--until` select whole conversations by their start. Guarded record by record; a secret-shaped identifier refuses the whole export and writes nothing. Full contract in [`cli-reference.md`](cli-reference.md). || Force-directed explorer | `o2b brain explorer [--port \| --export]` | โ (CLI-only) | live HTTP on `127.0.0.1` (default `:7777`) or single-file HTML at `<path>`; renders preferences + retired as a graph; zero backend. Keyboard-accessible `<ul role="listbox">` mirror of visible nodes (ArrowUp/Down/Home/End/Enter/Escape); layout + filter state persisted to `localStorage` under `osb-explorer-layout:<vault_basename>`; "Reset layout" button clears the key. |@@ -1259,6 +1259,21 @@ semantic_weightยทcosine + link_boost + recency_boost + entity_boost)`remote caller's embed is refused with `EMBEDDING_COST_UNPRICED` whenthe model has no known price and `embedding_cost_gate_usd` ispositive, while a local caller's embed is not gated, as for `search`.+- **One query-embed gateway (v1.73.0).** The search lane and the+ semantic belief order ask the same gateway whether, and with what+ text, a query is embedded. It applies the caller's reach and the+ price gate before any provider exists (a caller that is not local,+ under a positive `embedding_cost_gate_usd`, on an unpriced model, is+ refused), then fits the query, instruction prefix included, to the+ effective input window: `embedding_input_window_tokens`, then the+ curated model table, then unknown, which cuts nothing. The cut is at a+ code-point boundary under the ceiling token estimate, so it never sends+ more than the window and treats every language alike. A refused or cut+ query is disclosed by trail code (`semantic-cost-unpriced`,+ `semantic-query-truncated`, and `semantic-query-empty-fit` when the+ instruction prefix alone fills the window). A refused answer is never+ cached; a cut one is cached under a key that carries the effective+ window and the query prefix, so a changed window re-keys it.- **Atomic reindex.** `o2b search reindex` writes to`brain.sqlite.new`, renames to `brain.sqlite`, and keeps theprevious file as `brain.sqlite.bak`. If the main file is missing ondiff --git a/docs/mcp.md b/docs/mcp.mdindex d816b57c..66f95b50 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -2394,3 +2394,35 @@ format characters), when it contains NUL, or when it exceeds the cap.model has no known price), `brain_maintenance` spend receipts carry`price_source` with a null `estimated_usd` for an unknown price. No newtool.+- Since v1.73.0 every paid query embed passes one gate. Under a positive+ `embedding_cost_gate_usd`, a caller that is not local is refused the+ query embed of a model with no known price before any provider call:+ `brain_search` with an explicit semantic request fails with+ `EMBEDDING_COST_UNPRICED`, and a hybrid search (also inside+ `brain_recall_feedback`, `brain_file_context`, `brain_eval`,+ `brain_benchmark` and `brain_tune`) falls back to keyword-only with+ `semantic-cost-unpriced` in its retrieval trail. A query longer than+ the effective embedding input window (`embedding_input_window_tokens`,+ then the curated model table, then unknown, which cuts nothing) is cut+ and records `semantic-query-truncated`; when the instruction prefix+ alone fills the window, an explicit semantic search and the+ `brain_context_pack` semantic belief order refuse with `INVALID_INPUT`,+ and a hybrid search falls back to keyword-only with+ `semantic-query-empty-fit`.+ `brain_context_pack` resolves an omitted reach to remote like every+ other reader, and its `semantic.query_tokens` counts the text actually+ sent, instruction prefix included. `brain_recall_feedback` returns an+ additive `degraded` array with the re-run's degradation codes (empty+ when nothing narrowed it), and a feedback event whose re-run lost the+ semantic lane records zero layer contributions, so the learned weights+ do not learn from a keyword-only answer. `brain_benchmark`, `brain_eval`+ and `brain_tune` reports carry a `degraded` union (and per query or per+ grid row) when a run measured a smaller system than the configured one,+ and `brain_tune` refuses to save a winner measured with the semantic+ lane missing: `EMBEDDING_COST_UNPRICED` for the cost gate,+ `EMBEDDING_KEY_MISSING` or `EMBEDDING_DISABLED` for a blocked tier,+ `EMBEDDING_PROVIDER_HTTP` when the provider did not answer, and the+ same `EMBEDDING_PROVIDER_HTTP` for any other stop that left the hybrid+ caller keyword-only (the composite deadline, an empty query vector, an+ empty fit recorded as `semantic-query-empty-fit`), with a remedy naming `search_hybrid_deadline_ms` or the+ input window. Each refusal names the remedy.diff --git a/docs/observability.md b/docs/observability.mdindex 7402fc07..1ad77b8a 100644--- a/docs/observability.md+++ b/docs/observability.md@@ -179,7 +179,7 @@ No-consumer regression tests cover each gated surface, so a future call site can- `brain_recall_telemetry` (MCP) and `o2b brain recall-telemetry list|summary|gate-list|gate-summary` aggregate recall and gate records. Since v1.46.0 every `recall_telemetry` payload carries a `channel` naming the seam the recall came through - `mcp`, `cli`, or `hook`, a closed set. It is a property of the emit site rather than a caller argument: the MCP handlers stamp `mcp`, `o2b brain context-pack --telemetry` stamps `cli`, and the recall-inject hook stamps `hook`. Every emit site must name one, enforced at build time, so no new record lacks it. `channel` is clip-protected alongside `session_id` and `agent_id`, so an output-budget clip may not drop it. Filter on it with the `channel` argument (MCP) or `--channel` (CLI) on `list` and `summary`, and read the `by_channel` rollup on `summary`; a channel with no record is absent from that rollup rather than reported as `0`. Records written before v1.46.0 carry no `channel` at all and are never migrated, so they count in `total` / `by_mode` / `by_status` but fall into no `by_channel` bucket, and any `channel` filter excludes them. `o2b brain doctor` crosses the rollup against per-channel install state and reports `recall-channel-silent` (installed, expected to deliver, silent for 30 days) or `recall-channel-unmeasured` (one half of that cross could not be read - the latter rides the `uncertain` stream and does not affect the exit code).- The recall-inject hook's optional decision-model filter (`decision_model_uses: "recall_inject:shadow|enforce"`, see `docs/decision-models/recall-inject.md`) adds to the hook's `recall_telemetry` `metadata` and to its local hook-audit line a `decision_model` object: `mode`, `outcome` (`ok`, `not_sent` or `degraded`), `latency_ms` (the time the filter added to the prompt), `notes_dropped` and `abstained` (in `shadow`, what `enforce` would have done). Only the local audit line adds `degrade_reason` on a failure. In `enforce` a withheld brief is an `abstain` with reason `decision_model_abstain` (status `empty`). Its `decision_model_call` records carry `note_paths` (a note that may not leave the machine as `(withheld)`), `helps`, `inject_any`, `abstained`, `notes_dropped`, `withheld_count`, `budget_dropped_count` and `budget_ms`; an enforced brief that got shorter writes one `token_impact` sample with `source: decision_model:recall_inject` when `token_impact_ledger_enabled` is on. None of these carries prompt or note text. `o2b decision-model report --use recall_inject` reads them with p50/p95 added latency, timeout rate, abstain rate and notes dropped next to the hook's recall telemetry.-- The recall-inject hook's local hook-audit line (`action: recall_inject_decision`) carries what only the hook knows, each field present only when it applies: `config_invalid` (the settings among `recall_inject_max_notes`, `recall_inject_max_chars`, `recall_inject_time_budget_ms` and `recall_inject_confidence_floor` whose value was rejected, so the built-in default ran; a value taken from the environment is named by its `OPEN_SECOND_BRAIN_RECALL_INJECT_*` variable), `dedupe_sets` (`already_injected` and `digest_paths`, the sizes of the session's recall set and SessionStart digest set the decision consulted, not counts of suppressed notes; absent without a session id or with `recall_inject_dedupe` off), `ledger_recorded: false` (an injected brief whose post-stdout ledger write failed, so its notes can repeat; absent when the write succeeded or no ledger applies), `slices` (one `{name, outcome, notes}` per declared slice, `outcome` being `inject` or that slice's abstain reason) and `slices_config: "invalid"` (the vault's `_brain.yaml` failed to load; the search reads the same file, so that decision is an `error` with fault `retriever_failed`). Slice names are vault policy vocabulary and ride the local audit line only, never the synced `recall_telemetry` record. The abstain reasons `all_already_injected` and `all_slices_abstained` reach both surfaces through the existing `reason` field. See `docs/decision-models/recall-inject.md`.+- The recall-inject hook's local hook-audit line (`action: recall_inject_decision`) carries what only the hook knows, each field present only when it applies: `config_invalid` (the settings among `recall_inject_max_notes`, `recall_inject_max_chars`, `recall_inject_time_budget_ms` and `recall_inject_confidence_floor` whose value was rejected, so the built-in default ran; a value taken from the environment is named by its `OPEN_SECOND_BRAIN_RECALL_INJECT_*` variable), `dedupe_sets` (`already_injected` and `digest_paths`, the sizes of the session's recall set and SessionStart digest set the decision consulted, not counts of suppressed notes; absent without a session id or with `recall_inject_dedupe` off), `ledger_recorded: false` (an injected brief whose post-stdout ledger write failed, so its notes can repeat; absent when the write succeeded or no ledger applies), `slices` (one `{name, outcome, notes}` per declared slice, `outcome` being `inject` or that slice's abstain reason) `slices_config: "invalid"` (the vault's `_brain.yaml` failed to load; the search reads the same file, so that decision is an `error` with fault `retriever_failed`) and, since v1.73.0, `retrieval_degraded` (the retrieval trail codes of the searches behind the decision, each once in first-seen order, for example `semantic-cost-unpriced` when the hook's query embed was refused by the cost gate). The gap-promote hook's audit line carries the same `retrieval_degraded` field for its recall checks. Slice names are vault policy vocabulary and ride the local audit line only, never the synced `recall_telemetry` record. The abstain reasons `all_already_injected` and `all_slices_abstained` reach both surfaces through the existing `reason` field. See `docs/decision-models/recall-inject.md`.- `brain_recall_telemetry` `operation: "cost"` (MCP) and `o2b brain recall-telemetry cost` fold WRITE volume against the read telemetry above: memory-write ops (Brain-log `feedback`/`apply-evidence`/`note` verbs plus `host_memory_write` continuity records) are counted per period and reported alongside reads as a write-vs-read ratio, a `write_heavy` flag, and a rough weighted cost signal. Weights (`--write-cost`/`--read-cost`, default 1 each) model "some tools charge on write, some on read"; `--write-heavy-ratio` (default 1) sets the write-heavy threshold. Read-only; period-scoped by `--since`/`--until`. `brain_create_note` file creation emits no telemetry event today and is not counted.- `brain_context_receipts` and `o2b brain context-receipts` inspect served-context receipts.- The SessionStart hook writes one `context_receipt` per injection (`host: "hook"`, `trigger: "session_inject"`) with one item per source it injected. On a measured run its `budget` block carries `inject_budget_chars` (the configured value), `budgeted_source_count` and, since v1.70.0, `scoped_rules_chars`: the length of the rendered scoped operator rules block, `0` when none rendered. The scoped block is a budgeted source named `scoped-rules`, but it is subtracted from the budget rather than charged against the full ceiling: the active body was budgeted to `inject_budget_chars` minus `scoped_rules_chars` (never below zero). The `budget` block is present whenever the scoped block rendered, also when there is no `active.md`. A run that fell back to the last good cache records no `budget` block, as before, but keeps the `standing-rules` and `scoped-rules` items, which are produced outside the fail-open boundary. See "Scoped operator rules" in [`how-it-works.md`](how-it-works.md).diff --git a/docs/updating.md b/docs/updating.mdindex 777fa15d..06e47d90 100644--- a/docs/updating.md+++ b/docs/updating.md@@ -47,6 +47,60 @@ instruction files such as `CLAUDE.md`/`AGENTS.md`, installed`.claude/skills/`) and warns with the exact replacement for any stalereference it finds (`removed-tool-reference`).+## Upgrading to 1.73.0++No step is required unless you set a positive `embedding_cost_gate_usd`+on a model with no known price, run a model the curated table does not+list, or want to send extra request fields to your embedding endpoint.++**Hooks and MCP searches under a positive gate fall back to keyword-only+and say so.** The query embed of a search that is not at local reach+(every MCP tool and the recall-inject and gap-promote hooks) now passes+the same price gate as the embedding runs of 1.72.0. With a positive+`embedding_cost_gate_usd` on a model with no known price, a hybrid+search answers keyword-only and records `semantic-cost-unpriced` in its+trail, a hook names the code on its local audit line+(`retrieval_degraded`), and an explicit semantic search fails with+`EMBEDDING_COST_UNPRICED`. `o2b search` at the CLI runs at local reach+and is unchanged. Declare the price of a self-hosted model to keep the+semantic lane:++```yaml+embedding_price_model: nomic-embed-text:latest+embedding_price_usd_per_mtok: 0+```++`brain_tune` now refuses to save a winner measured without the semantic+lane, and recall feedback on such a search no longer moves the learned+weights.++**Declare the input window of an uncurated model.** A query longer than+the model's input window is now cut to it before the embed and the trail+records `semantic-query-truncated`. For a model the curated table does+not list the window is unknown and nothing is cut; set+`embedding_input_window_tokens` to the model's window (in its own+tokens) so long queries are cut and disclosed instead of truncated or+refused silently by the server. The key is refused for the `local`+provider.++**Extra request fields need `openai-compat`.** `embedding_extra_body`+takes one JSON object, is sent only by the `openai-compat` provider+(refused for others, inert for `disabled`), refuses `model`, `input` and+`encoding_format`, and a `dimensions` field needs `embedding_dimension`+set to the same width.++**Upgrades refuse a file edited after the plan was read.**+`o2b brain upgrade --apply` and the automatic upgrade worker now apply+the plan they computed. When a managed file changed in between, nothing+is overwritten: re-run `o2b brain upgrade --dry-run` and apply the new+plan. Under `--apply --json` a refusal prints+`{ "ok": false, "error", "run_id", "drifted" }`. In the `--dry-run --json`+plan, a file that does not exist yet still reports `before_size: 0`.++`brain_recall_feedback` gains an additive `degraded` array, and+`brain_context_pack` in `semantic` mode resolves an omitted reach to+remote and counts the instruction prefix in `query_tokens`.+## Upgrading to 1.72.0No step is required unless you set a positive `embedding_cost_gate_usd`,diff --git a/hooks/gap-promote.ts b/hooks/gap-promote.tsindex 2e5cb1c9..f57a9018 100644--- a/hooks/gap-promote.ts+++ b/hooks/gap-promote.ts@@ -139,6 +139,11 @@ async function main(): Promise<void> {capped: promotion.capped,closed: closure.closed.length,kept: closure.kept.length,+ // Why a recall narrowed (a gated query embed, a missing semantic+ // lane) rides this local line only, present only when non-empty.+ ...(closure.retrievalDegraded !== undefined+ ? { retrieval_degraded: closure.retrievalDegraded }+ : {}),});} finally {disarm();diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 702fc487..a51a36f0 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -2,7 +2,7 @@"id": "open-second-brain","name": "Open Second Brain","description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",- "version": "1.72.0",+ "version": "1.73.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/openclaw/index.js b/openclaw/index.jsindex 7514f4d6..99fe798b 100644--- a/openclaw/index.js+++ b/openclaw/index.js@@ -1565,6 +1565,7 @@ import { homedir as homedir2 } from "node:os";import { dirname as dirname2, isAbsolute, join as join3, resolve as resolve2 } from "node:path";// src/core/fs-atomic.ts+import { isUtf8 } from "node:buffer";import {closeSync,existsSync,@@ -1612,9 +1613,14 @@ function withWindowsSharingRetry(op, seams) {}}function atomicWriteFileSync(target, contents, opts = {}) {+ const expected = opts.expectBefore;+ if (expected !== undefined)+ assertExpectedBefore(target, expected);if (opts.skipIfUnchanged && isUnchanged(target, contents))return false;withTempFile(target, contents, (tmpPath) => {+ if (expected !== undefined)+ assertExpectedBefore(target, expected);renameWithRetry(tmpPath, target);});return true;@@ -1628,6 +1634,36 @@ function isUnchanged(target, contents) {return false;}}+function fileMatchesExpected(target, expected) {+ let current;+ try {+ current = readFileSync(target);+ } catch (err) {+ if (err?.code !== "ENOENT")+ throw err;+ return expected === null;+ }+ if (expected === null)+ return false;+ if (current.equals(Buffer.from(expected, "utf8")))+ return true;+ return !isUtf8(current) && current.toString("utf8") === expected;+}+function assertExpectedBefore(target, expected) {+ if (!fileMatchesExpected(target, expected))+ throw new FileDriftError(target);+}+var FILE_DRIFT_CODE = "FILE_DRIFT";++class FileDriftError extends Error {+ code = FILE_DRIFT_CODE;+ path;+ constructor(path) {+ super(`file changed since it was read: ${path}; the write was refused ` + "and the file left as it is. Re-read it and retry.");+ this.name = "FileDriftError";+ this.path = path;+ }+}function withTempFile(target, contents, commit, mode = 420) {const dir = dirname(target);mkdirSync(dir, { recursive: true });@@ -2377,7 +2413,7 @@ var EGRESS_SITES = Object.freeze({verb: "o2b search index (embedding provider)",module: "src/core/search/embeddings/openai-compat.ts",redaction: R.unscannedNetworkPayload,- reason: "the largest and most continuous egress in this product: every indexed chunk BODY " + "is POSTed verbatim to whichever endpoint the operator configured, for every " + "reindex, and nothing scans it. It is declared unscanned rather than wired to the " + "guard because redaction here would corrupt the thing being built - a vector " + "computed over a placeholder is a vector for the placeholder, so the chunk would " + "come back unfindable while the index reported success, which is a silent failure " + "where this one is at least a stated exposure. The controls that do exist are " + "the operator's: semantic search is off until an endpoint and a key are configured, " + "and the endpoint is whichever host they name, including a local one."+ reason: "the largest and most continuous egress in this product: every indexed chunk BODY " + "is POSTed verbatim to whichever endpoint the operator configured, for every " + "reindex, and nothing scans it. It is declared unscanned rather than wired to the " + "guard because redaction here would corrupt the thing being built - a vector " + "computed over a placeholder is a vector for the placeholder, so the chunk would " + "come back unfindable while the index reported success, which is a silent failure " + "where this one is at least a stated exposure. The controls that do exist are " + "the operator's: semantic search is off until an endpoint and a key are configured, " + "and the endpoint is whichever host they name, including a local one. The request " + "also carries any extra body fields the operator declared in `embedding_extra_body`, " + "verbatim, next to the owned model, input and encoding fields."},"search-embedding-zeroentropy": {id: "search-embedding-zeroentropy",diff --git a/package.json b/package.jsonindex 8fc042ae..b85e9272 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.72.0",+ "version": "1.73.0","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.","keywords": [diff --git a/plugin.yaml b/plugin.yamlindex bd1a43a9..4b67b90c 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.72.0"+version: "1.73.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex 49263deb..fdafe5d7 100644--- a/plugins/codex/.codex-plugin/plugin.json+++ b/plugins/codex/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.72.0",+ "version": "1.73.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/codex/README.md b/plugins/codex/README.mdindex 0a57da76..d92cbfc8 100644--- a/plugins/codex/README.md+++ b/plugins/codex/README.md@@ -113,7 +113,7 @@ The full router with readiness criteria is [`install.md`](https://github.com/ite## What is new-1.72.0 makes embedding spend honest. Every estimate names its price source (`builtin`, `operator` or `unknown`), `embedding_price_model` and `embedding_price_usd_per_mtok` declare the price of a model the built-in table does not list, and an unknown price is reported as `price unknown` instead of $0; under a positive `embedding_cost_gate_usd` such a model is refused with `EMBEDDING_COST_UNPRICED` until its price is declared or the run is forced. Edited notes keep the vectors of their unchanged chunks, `o2b search vector-backfill` accepts a repeatable `--path`, `o2b search check` names an unpriced model and where it looked for an embedding key, and `brain_context_pack` gains `query_mode: "semantic"`, which orders the curated belief notes by the stored vectors of their chunks. Every release is described in the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md).+1.73.0 makes the query embed honest and upgrades safe. Every query embed, from the search lane behind the MCP tools and hooks to the `brain_context_pack` semantic belief order, passes one gate: under a positive `embedding_cost_gate_usd` an unpriced model is refused for any caller that is not local (a hybrid search falls back to keyword-only and says so by trail code), and a query longer than the model's input window is cut to it and disclosed. `embedding_input_window_tokens` declares the window of a model the curated table does not list, and `embedding_extra_body` sends extra request fields to an OpenAI-compatible endpoint. `brain_recall_feedback` and the benchmark, eval and tune reports name the degradations their searches met, and `brain_tune` no longer saves a winner measured without the semantic lane. `o2b brain upgrade` and the automatic upgrade worker apply exactly the plan they computed and refuse a managed file edited in between instead of overwriting it. Every release is described in the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md).## Documentationdiff --git a/plugins/codex/skills/embeddings-setup/SKILL.md b/plugins/codex/skills/embeddings-setup/SKILL.mdindex 66772095..def40a63 100644--- a/plugins/codex/skills/embeddings-setup/SKILL.md+++ b/plugins/codex/skills/embeddings-setup/SKILL.md@@ -88,7 +88,10 @@ model the table does not list (most local servers, newer or nichemodels) is `unknown`, and its estimates print `price unknown`. When theuser has set a positive `embedding_cost_gate_usd`, an unknown pricerefuses embedding runs with `EMBEDDING_COST_UNPRICED` until the price is-declared. Ask the user for the provider's rate (USD per million tokens)+declared, and it also refuses the query embeds of searches that do not+run at local reach (MCP tools and hooks): a hybrid search falls back to+keyword-only and names `semantic-cost-unpriced` in its trail. Ask the+user for the provider's rate (USD per million tokens)and write the pair beside the other embedding settings:```bash@@ -103,6 +106,43 @@ loopback URL can still be a paid proxy. The pair names one model, soafter a model switch `o2b search check` flags the stale declarationuntil it is updated. Declaring a price never triggers a reindex.+### Declare the model's input window (uncurated models)++A search query longer than the model's input window is cut to it before+the embed and the trail names `semantic-query-truncated`. The window+comes from the curated model table; for a model it does not list the+window is unknown and nothing is cut, so a serving stack that truncates+silently or refuses long inputs does so unannounced. When the user knows+the model's window (in its own tokens), declare it:++```bash+OPEN_SECOND_BRAIN_EMBEDDING_INPUT_WINDOW_TOKENS=512+```++(or `embedding_input_window_tokens` in the o2b config). It is refused+for the `local` provider, which has no window.++### Extra request fields (OpenAI-compatible endpoints)++When the user's serving stack needs a request field the provider does+not send, put a JSON object in `embedding_extra_body` (env+`OPEN_SECOND_BRAIN_EMBEDDING_EXTRA_BODY`). Only `openai-compat` sends it,+and `model`, `input` and `encoding_format` are refused by name. A+`dimensions` field needs `embedding_dimension` set to the same width:++```bash+OPEN_SECOND_BRAIN_EMBEDDING_EXTRA_BODY='{"dimensions": 512}'+OPEN_SECOND_BRAIN_EMBEDDING_DIM=512+```++The extra body is not part of the embedding identity, so changing it+never triggers a reindex; a changed `embedding_dimension` does. Some+fields shape the vectors the provider returns (a provider `task`,+`input_type`, `normalize` or `truncate` switch): after changing such a+field, rebuild the vectors with `o2b search reindex --embeddings` so new+query vectors stay in the space of the stored passages (`o2b search index+--force` keeps the stored vector of every unchanged chunk).+## Step 3 โ macOS: install Homebrew SQLiteApple ships `/usr/lib/libsqlite3.dylib` withdiff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex bd1a43a9..4b67b90c 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.72.0"+version: "1.73.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/pyproject.toml b/pyproject.tomlindex 882d7c27..ea593372 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"# CLI entry points (those moved to `package.json` `bin`).[project]name = "open-second-brain"-version = "1.72.0"+version = "1.73.0"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/skills/embeddings-setup/SKILL.md b/skills/embeddings-setup/SKILL.mdindex 66772095..def40a63 100644--- a/skills/embeddings-setup/SKILL.md+++ b/skills/embeddings-setup/SKILL.md@@ -88,7 +88,10 @@ model the table does not list (most local servers, newer or nichemodels) is `unknown`, and its estimates print `price unknown`. When theuser has set a positive `embedding_cost_gate_usd`, an unknown pricerefuses embedding runs with `EMBEDDING_COST_UNPRICED` until the price is-declared. Ask the user for the provider's rate (USD per million tokens)+declared, and it also refuses the query embeds of searches that do not+run at local reach (MCP tools and hooks): a hybrid search falls back to+keyword-only and names `semantic-cost-unpriced` in its trail. Ask the+user for the provider's rate (USD per million tokens)and write the pair beside the other embedding settings:```bash@@ -103,6 +106,43 @@ loopback URL can still be a paid proxy. The pair names one model, soafter a model switch `o2b search check` flags the stale declarationuntil it is updated. Declaring a price never triggers a reindex.+### Declare the model's input window (uncurated models)++A search query longer than the model's input window is cut to it before+the embed and the trail names `semantic-query-truncated`. The window+comes from the curated model table; for a model it does not list the+window is unknown and nothing is cut, so a serving stack that truncates+silently or refuses long inputs does so unannounced. When the user knows+the model's window (in its own tokens), declare it:++```bash+OPEN_SECOND_BRAIN_EMBEDDING_INPUT_WINDOW_TOKENS=512+```++(or `embedding_input_window_tokens` in the o2b config). It is refused+for the `local` provider, which has no window.++### Extra request fields (OpenAI-compatible endpoints)++When the user's serving stack needs a request field the provider does+not send, put a JSON object in `embedding_extra_body` (env+`OPEN_SECOND_BRAIN_EMBEDDING_EXTRA_BODY`). Only `openai-compat` sends it,+and `model`, `input` and `encoding_format` are refused by name. A+`dimensions` field needs `embedding_dimension` set to the same width:++```bash+OPEN_SECOND_BRAIN_EMBEDDING_EXTRA_BODY='{"dimensions": 512}'+OPEN_SECOND_BRAIN_EMBEDDING_DIM=512+```++The extra body is not part of the embedding identity, so changing it+never triggers a reindex; a changed `embedding_dimension` does. Some+fields shape the vectors the provider returns (a provider `task`,+`input_type`, `normalize` or `truncate` switch): after changing such a+field, rebuild the vectors with `o2b search reindex --embeddings` so new+query vectors stay in the space of the stored passages (`o2b search index+--force` keeps the stored vector of every unchanged chunk).+## Step 3 โ macOS: install Homebrew SQLiteApple ships `/usr/lib/libsqlite3.dylib` withdiff --git a/src/cli/brain/upgrade-render.ts b/src/cli/brain/upgrade-render.tsindex 9554f94f..c44d9430 100644--- a/src/cli/brain/upgrade-render.ts+++ b/src/cli/brain/upgrade-render.ts@@ -26,7 +26,8 @@ export function renderUpgradePlanJson(plan: UpgradePlan): {files: plan.files.map((f) => ({path: f.path,status: f.status,- before_size: f.before.length,+ // An absent file (`before: null`) reports 0, as before the split.+ before_size: f.before?.length ?? 0,after_size: f.after.length,...(f.error ? { error: f.error } : {}),})),@@ -43,8 +44,9 @@ export function printUpgradePlanText(plan: UpgradePlan): void {info(` ${f.path}: ERROR ${f.error}`);continue;}- info(` ${f.path}: update (${f.before.length} โ ${f.after.length} bytes)`);- info(renderUnifiedDiff(f.before, f.after, f.path));+ const from = f.before === null ? "absent" : String(f.before.length);+ info(` ${f.path}: update (${from} โ ${f.after.length} bytes)`);+ info(renderUnifiedDiff(f.before ?? "", f.after, f.path));}if (plan.pending === 0 && plan.errors === 0) {ok("upgrade: all managed files match the current release.");diff --git a/src/cli/brain/verbs/upgrade.ts b/src/cli/brain/verbs/upgrade.tsindex 4a92b57d..aa51e3e3 100644--- a/src/cli/brain/verbs/upgrade.ts+++ b/src/cli/brain/verbs/upgrade.ts@@ -133,7 +133,10 @@ export async function cmdBrainUpgrade(argv: string[]): Promise<number> {let result;const now = new Date();try {- result = applyUpgrade(vault, { now });+ // The plan computed (and, interactively, confirmed) above, not a+ // re-plan: a file that changed since it was read is refused by name+ // instead of overwritten.+ result = applyUpgrade(vault, { plan, now });} catch (exc) {// Recorded as the automatic path records it, so `o2b doctor` shows// the latest failure and the automatic retry waits its cooldown.@@ -148,7 +151,13 @@ export async function cmdBrainUpgrade(argv: string[]): Promise<number> {// The error below is what the operator acts on.}if (exc instanceof BrainUpgradeError) {- process.stderr.write(`error: ${exc.message}\n`);+ if (flags["json"]) {+ // `drifted` names each refused file, so a script can tell a drift+ // from any other failure without parsing the message.+ okJson({ ok: false, error: exc.message, run_id: exc.runId, drifted: [...exc.drifted] });+ } else {+ process.stderr.write(`error: ${exc.message}\n`);+ }return 1;}return fail(`upgrade failed: ${describeErrorChain(exc)}`);diff --git a/src/core/brain/belief-semantic.ts b/src/core/brain/belief-semantic.tsindex a894eaa7..701cf0e6 100644--- a/src/core/brain/belief-semantic.ts+++ b/src/core/brain/belief-semantic.ts@@ -19,11 +19,14 @@* with the query and counts as unembedded, never as scored.* - {@link loadBeliefSemanticRelevance} opens the index, refuses a* blocked capability tier and a missing sqlite-vec by name BEFORE it- * embeds anything, embeds the query exactly once with the `query`- * prefix kind, and discloses that one spend: the model, the price- * source, the query tokens and the cost (null when the price is- * unknown). A remote caller's embed of an unpriced model is refused- * under a positive cost gate, before the call.+ * embeds anything, asks the query-embed gateway (`prepareQueryEmbed`)+ * whether and with what text to embed, embeds that text exactly once+ * with the `query` prefix kind, and discloses that one spend: the+ * model, the price source, the query tokens actually sent (prefix+ * included) and the cost (null when the price is unknown). A caller+ * that is not local is refused an unpriced model's embed under a+ * positive cost gate, before the call; a query cut to the model's+ * input window adds a warning.** No belief row under the model anywhere is refused here, before the* embed, with `BELIEF_VECTORS_MISSING`: none in reach can have one. Any@@ -39,13 +42,23 @@ import {semanticCapabilityLabel,} from "../search/capability-tier.ts";import type { EmbeddingProvider } from "../search/embeddings/contract.ts";-import { activeSpendQuote, COST_GATE_KEY, formatEstimatedUsd } from "../search/embedding-spend.ts";-import { EMBEDDING_PRICE_SOURCE, type EmbeddingPriceSource } from "../search/embeddings/pricing.ts";+import { formatEstimatedUsd } from "../search/embedding-spend.ts";+import type { EmbeddingPriceSource } from "../search/embeddings/pricing.ts";import { makeProvider } from "../search/embeddings/provider.ts";-import { estimateCostUsd, estimateTokens } from "../search/embeddings/signature.ts";+import {+ prepareQueryEmbed,+ queryEmbedCutMessage,+ queryEmbedEmptyFitMessage,+ queryEmbedRefusalMessage,+} from "../search/embeddings/query-embed.ts";+import { estimateCostUsd } from "../search/embeddings/signature.ts";import { SearchError } from "../search/search-error.ts";import { isRemotelyReadable } from "../graph/visibility.ts";-import { TRANSPORT_REACH, type TransportReach } from "../graph/transport-reach.ts";+import {+ resolvedTransportReach,+ TRANSPORT_REACH,+ type TransportReach,+} from "../graph/transport-reach.ts";import { contradictedAbiFields, formatEmbeddingAbiDrift, Store } from "../search/store.ts";import type { ResolvedSearchConfig } from "../search/types.ts";import { assertValidVector } from "../search/vector-guard.ts";@@ -85,10 +98,11 @@ export interface BeliefVectorScores {readonly scored: number;}-/** The one ungated spend of the semantic mode, disclosed rather than hidden. */+/** The one query spend of the semantic mode, disclosed rather than hidden. */export interface BeliefSemanticQueryReport {readonly model: string;readonly priceSource: EmbeddingPriceSource;+ /** The estimate of the text actually sent, the instruction prefix included. */readonly queryTokens: number;/** Null when nobody stated the model's price. */readonly estimatedUsd: number | null;@@ -96,7 +110,11 @@ export interface BeliefSemanticQueryReport {export interface BeliefSemanticRelevance extends BeliefVectorScores {readonly report: BeliefSemanticQueryReport;- /** The search lane's embedding-ABI drift warning when the index contradicts this build. */+ /**+ * The search lane's embedding-ABI drift warning when the index+ * contradicts this build, and one warning when the query was cut to the+ * model's input window.+ */readonly warnings: ReadonlyArray<string>;}@@ -106,7 +124,8 @@ export interface BeliefSemanticDeps {/** Whether the store loads sqlite-vec; omitted loads it. */readonly loadVec?: boolean;/**- * The caller's transport reach; local when omitted. Below local reach a+ * The caller's transport reach; remote when omitted, as everywhere else+ * (`resolvedTransportReach`). Below local reach a* belief whose INDEXED visibility is not readable there loses its* vectors: they were captured from bytes reserved at index time, and a* live file rewritten since must not be ordered by them.@@ -193,10 +212,14 @@ function isBeliefPath(path: string): boolean {}/**- * Embed `query` once and score every indexed belief note by its stored- * vectors. Throws a named {@link SearchError} for a blocked tier- * (`EMBEDDING_DISABLED`, `EMBEDDING_KEY_MISSING`) and for a store without- * sqlite-vec (`VEC_EXTENSION_UNAVAILABLE`), each before any embed call.+ * Embed `query`, fitted to the model's input window, once and score every+ * indexed belief note by its stored vectors. Throws a named+ * {@link SearchError} for a blocked tier (`EMBEDDING_DISABLED`,+ * `EMBEDDING_KEY_MISSING`), for a store without sqlite-vec+ * (`VEC_EXTENSION_UNAVAILABLE`), for an unpriced model under a positive+ * cost gate when the caller is not local (`EMBEDDING_COST_UNPRICED`) and+ * for a window the instruction prefix alone fills (`INVALID_INPUT`), each+ * before any embed call.*/export async function loadBeliefSemanticRelevance(config: ResolvedSearchConfig,@@ -221,7 +244,7 @@ export async function loadBeliefSemanticRelevance("semantic belief order unavailable: sqlite-vec extension not loaded",);}- const reach = deps.reach ?? TRANSPORT_REACH.local;+ const reach = resolvedTransportReach(deps.reach);const inView = deps.inView ?? (() => true);const beliefDocs = [...store.listDocuments()].filter(([path]) => isBeliefPath(path) && inView(path),@@ -251,31 +274,29 @@ export async function loadBeliefSemanticRelevance(`for the configured model; run: ${BELIEF_VECTORS_BACKFILL_COMMAND}`,);}- // Priced through the resolution every spend surface shares; `model`- // above stays the row filter because it matches the indexer's stamp.- const spend = activeSpendQuote(config);- // A remote caller spends the operator's money on every request. Under- // a positive gate an unpriced model is the spend the gate exists to- // stop, so it is refused before the call; a local caller keeps the- // disclosed, ungated embed, as for `search`.- if (- reach !== TRANSPORT_REACH.local &&- config.semantic.costGateUsd > 0 &&- spend.quote.source === EMBEDDING_PRICE_SOURCE.unknown- ) {+ // The gateway every query embed shares decides whether the embed is+ // sent and with what text; `model` above stays the row filter because+ // it matches the indexer's stamp. This order has no keyword fallback,+ // so a refusal is always an error here.+ const prepared = prepareQueryEmbed(config, query, reach);+ if (prepared.kind === "refused") {throw new SearchError(- "EMBEDDING_COST_UNPRICED",- "semantic belief order refused: the embedding model has no known price " +- `and ${COST_GATE_KEY} is positive`,+ prepared.code,+ `semantic belief order refused: ${queryEmbedRefusalMessage(prepared)}`,);}- const [queryVector = []] = await provider.embed([query], "query");- const queryTokens = estimateTokens([query]);+ if (prepared.emptyFit) {+ throw new SearchError(+ "INVALID_INPUT",+ `semantic belief order unavailable: ${queryEmbedEmptyFitMessage(prepared)}`,+ );+ }+ const [queryVector = []] = await provider.embed([prepared.text], "query");const report: BeliefSemanticQueryReport = {- model: spend.model ?? model,- priceSource: spend.quote.source,- queryTokens,- estimatedUsd: estimateCostUsd(queryTokens, spend.quote),+ model: prepared.model ?? model,+ priceSource: prepared.quote.source,+ queryTokens: prepared.sentTokens,+ estimatedUsd: estimateCostUsd(prepared.sentTokens, prepared.quote),};try {assertValidVector(queryVector, QUERY_VECTOR_CONTEXT);@@ -283,12 +304,15 @@ export async function loadBeliefSemanticRelevance(throw e instanceof SearchError ? discloseSpentQuery(e, report) : e;}const contradicted = contradictedAbiFields(store.embeddingAbiMismatches());+ const warnings: string[] = [];+ if (contradicted.length > 0) warnings.push(formatEmbeddingAbiDrift(contradicted));+ if (prepared.truncated) {+ warnings.push(`semantic belief order: ${queryEmbedCutMessage(prepared, query)}`);+ }return {...scoreBeliefsByVector({ model, queryVector, vectorsByPath }),report,- warnings: Object.freeze(- contradicted.length > 0 ? [formatEmbeddingAbiDrift(contradicted)] : [],- ),+ warnings: Object.freeze(warnings),};} finally {await store.close();diff --git a/src/core/brain/gaps/gap-loop.ts b/src/core/brain/gaps/gap-loop.tsindex 42f74030..5624b176 100644--- a/src/core/brain/gaps/gap-loop.ts+++ b/src/core/brain/gaps/gap-loop.ts@@ -36,6 +36,7 @@ import { aggregateUnmetRecall } from "../query-demand.ts";import { summarizeRecallTelemetry } from "../recall-telemetry.ts";import { renderActivityTimeline, type ActivityItem } from "../render/activity-line.ts";import type { RecallResultSet, RecallRetriever } from "../recall-inject.ts";+import type { RetrievalDegradationCode } from "../../search/retrieval-trail.ts";import { isFileAlreadyExists } from "../../fs-atomic.ts";import { parseFrontmatterText, writeFrontmatterAtomic } from "../../vault.ts";import type { FrontmatterMap } from "../../types.ts";@@ -434,6 +435,14 @@ export interface GapAutoCloseResult {readonly closed: ReadonlyArray<string>;/** Keys left open (recall below the floor, or the recall failed). */readonly kept: ReadonlyArray<string>;+ /**+ * Why any of this run's recalls narrowed, as the search trail's codes:+ * first-seen order, each code once, present only when non-empty. A hook+ * resolves to remote reach, so a gated query embed lands here and the+ * hook names it on its LOCAL audit line. Reported only: a degraded+ * recall is judged by the same floor as any other.+ */+ readonly retrievalDegraded?: ReadonlyArray<RetrievalDegradationCode>;}/**@@ -469,6 +478,7 @@ export async function autoCloseRecalledGaps(const floor = opts.confidenceFloor ?? GAP_LOOP_AUTO_CLOSE_FLOOR;const closed: string[] = [];const kept: string[] = [];+ const degraded: RetrievalDegradationCode[] = [];for (const task of listGapTasks(vault, { status: GAP_TASK_STATUS_OPEN })) {let coveredElsewhere = false;let matchQuality: number | null = null;@@ -487,6 +497,7 @@ export async function autoCloseRecalledGaps(.map((candidate) => candidate.path).filter((path) => !admitsGapCoverageRow(path));if (rejected.length > 0) throw new GapRecallScopeError(task.topic, rejected);+ for (const code of result.degraded ?? []) if (!degraded.includes(code)) degraded.push(code);// Only genuine vault coverage elsewhere may close a task - and the// quality now describes the same rows, because the retriever was told// which rows count before it measured them.@@ -499,7 +510,11 @@ export async function autoCloseRecalledGaps(kept.push(task.key);}}- return Object.freeze({ closed: Object.freeze(closed), kept: Object.freeze(kept) });+ return Object.freeze({+ closed: Object.freeze(closed),+ kept: Object.freeze(kept),+ ...(degraded.length > 0 ? { retrievalDegraded: Object.freeze(degraded) } : {}),+ });}function closeGapTask(task: GapTask, now: Date): void {diff --git a/src/core/brain/gaps/gap-recall.ts b/src/core/brain/gaps/gap-recall.tsindex 71d290b3..1963b480 100644--- a/src/core/brain/gaps/gap-recall.ts+++ b/src/core/brain/gaps/gap-recall.ts@@ -102,10 +102,14 @@ export function gapScopedRecallRetriever(const admitted = outcome.results.filter((result) => admits(result.path)).slice(0, Math.max(1, limit));+ // The trail's codes ride the result (a hook resolves to remote reach,+ // so a gated query embed is reported here rather than dropped).+ const degraded = outcome.retrievalTrail?.degraded ?? [];return Object.freeze({candidates: Object.freeze(admitted.map(toRecallCandidate)),total: outcome.total,idfWeightedCoverage: await coverageOverAdmitted(config, topic, admitted),+ ...(degraded.length > 0 ? { degraded: Object.freeze(degraded.map((d) => d.code)) } : {}),});};}diff --git a/src/core/brain/recall-inject.ts b/src/core/brain/recall-inject.tsindex 17400470..3a345032 100644--- a/src/core/brain/recall-inject.ts+++ b/src/core/brain/recall-inject.ts@@ -20,6 +20,7 @@import { deriveRecallHint, type RecallHintInput } from "../search/recall-hint.ts";import { searchAcrossVaults } from "../search/cross-vault.ts";+import type { RetrievalDegradationCode } from "../search/retrieval-trail.ts";import type { RecallSource } from "./portability/recall-sources.ts";import { LOCAL_ORIGIN } from "./portability/origins.ts";import { fenceUntrustedContent, neutralizeUntrustedText } from "./untrusted-source.ts";@@ -101,6 +102,13 @@ export interface RecallResultSet {* that there is nothing to report.*/readonly idfWeightedCoverage: number | null;+ /**+ * Why the retrieval narrowed, as the search trail's codes. Absent or+ * empty when nothing did. A hook resolves to remote reach, so a gated+ * query embed (`semantic-cost-unpriced`) lands here instead of being+ * dropped with the rest of the trail.+ */+ readonly degraded?: ReadonlyArray<RetrievalDegradationCode>;}/** Relevance retriever: maps a query to a candidate set. */@@ -326,6 +334,8 @@ export type RecallInjectDecision =readonly slices?: ReadonlyArray<RecallSliceOutcome>;/** Present only when the decision-model filter ran (use not `off`). */readonly decisionModel?: RecallInjectDecisionModelInfo;+ /** See {@link RecallResultSet.degraded}; present only when non-empty. */+ readonly retrievalDegraded?: ReadonlyArray<RetrievalDegradationCode>;}| {readonly kind: "abstain";@@ -342,6 +352,8 @@ export type RecallInjectDecision =readonly slices?: ReadonlyArray<RecallSliceOutcome>;/** Present only on a `decision_model_abstain`. */readonly decisionModel?: RecallInjectDecisionModelInfo;+ /** See {@link RecallResultSet.degraded}; present only when non-empty. */+ readonly retrievalDegraded?: ReadonlyArray<RetrievalDegradationCode>;}| {readonly kind: "error";@@ -354,6 +366,11 @@ export type RecallInjectDecision =* in the first place.*/readonly detail?: string;+ /**+ * See {@link RecallResultSet.degraded}; present only when non-empty.+ * A slice that answered before another failed still reports here.+ */+ readonly retrievalDegraded?: ReadonlyArray<RetrievalDegradationCode>;};/** The identity of one rendered brief bullet. */@@ -438,6 +455,33 @@ export async function decideRecallInject(prompt: string,retriever: RecallRetriever,options: RecallInjectOptions = {},+): Promise<RecallInjectDecision> {+ // Every retrieval this decision makes reports through one recorder, so+ // the codes reach the decision on every return path below without each+ // path having to remember them. Order is first-seen, each code once.+ const seen: RetrievalDegradationCode[] = [];+ const recorded =+ (inner: RecallRetriever): RecallRetriever =>+ async (query) => {+ const set = await inner(query);+ for (const code of set.degraded ?? []) if (!seen.includes(code)) seen.push(code);+ return set;+ };+ const sliceRetriever = options.sliceRetriever;+ const decision = await decideOverRetrieval(prompt, recorded(retriever), {+ ...options,+ ...(sliceRetriever !== undefined+ ? { sliceRetriever: (spec, limit) => recorded(sliceRetriever(spec, limit)) }+ : {}),+ });+ if (seen.length === 0) return decision;+ return Object.freeze({ ...decision, retrievalDegraded: Object.freeze(seen) });+}++async function decideOverRetrieval(+ prompt: string,+ retriever: RecallRetriever,+ options: RecallInjectOptions,): Promise<RecallInjectDecision> {const clock = options.now ?? Date.now;const started = clock();@@ -1061,18 +1105,29 @@ export function recallInjectAuditDetails(decision.slices === undefined ? safe : Object.freeze({ ...safe, slices: decision.slices });// The decision-model degrade reason is local operational evidence,// like a retriever's message: it rides this line only.+ // So are the retrieval's degradation codes: a gated or degraded+ // semantic lane at the hook is named here, never in the synced record.+ const degraded =+ decision.retrievalDegraded === undefined+ ? sliced+ : Object.freeze({ ...sliced, retrieval_degraded: decision.retrievalDegraded });const reason = decision.decisionModel?.degradeReason;- if (reason === undefined) return sliced;+ if (reason === undefined) return degraded;return Object.freeze({- ...sliced,+ ...degraded,decision_model: Object.freeze({...(safe["decision_model"] as Readonly<Record<string, unknown>>),degrade_reason: reason,}),});}- if (decision.detail === undefined) return safe;- return Object.freeze({ ...safe, detail: decision.detail });+ return Object.freeze({+ ...safe,+ ...(decision.detail !== undefined ? { detail: decision.detail } : {}),+ ...(decision.retrievalDegraded !== undefined+ ? { retrieval_degraded: decision.retrievalDegraded }+ : {}),+ });}/**@@ -1151,10 +1206,12 @@ export function defaultRecallRetriever(content: result.content,}),);+ const degraded = outcome.retrievalTrail?.degraded ?? [];return Object.freeze({candidates: Object.freeze(candidates),total: outcome.total,idfWeightedCoverage: outcome.idfWeightedCoverage,+ ...(degraded.length > 0 ? { degraded: Object.freeze(degraded.map((d) => d.code)) } : {}),});};}diff --git a/src/core/brain/upgrade.ts b/src/core/brain/upgrade.tsindex bf96dc5c..48a5dcc2 100644--- a/src/core/brain/upgrade.ts+++ b/src/core/brain/upgrade.ts@@ -18,7 +18,7 @@import { existsSync, readFileSync, readdirSync } from "node:fs";import { join } from "node:path";-import { atomicWriteFileSync } from "../fs-atomic.ts";+import { atomicWriteFileSync, fileMatchesExpected, isFileDrift } from "../fs-atomic.ts";import { formatFrontmatter, parseFrontmatterText } from "../vault.ts";import { sanitisePrinciple } from "./text/sanitize-principle.ts";import { defaultConfigPath, resolveAgentName } from "../config.ts";@@ -40,8 +40,13 @@ export interface UpgradeFilePlan {/** Vault-relative path, e.g. `Brain/_brain.yaml`. */readonly path: string;readonly status: UpgradeFileStatus;- /** Current bytes on disk. Empty when the file does not exist yet. */- readonly before: string;+ /**+ * Bytes on disk when the plan was read; `null` when the file was absent.+ * An empty file is `""`, so the two states stay apart for the+ * compare-before-write check. Not carried by `noop` and `error` rows,+ * which hold `""`.+ */+ readonly before: string | null;/** Target bytes for the file under the current release. */readonly after: string;/**@@ -66,19 +71,36 @@ export interface UpgradeApplyResult {readonly files_updated: ReadonlyArray<string>;}+export interface ApplyUpgradeOptions {+ /**+ * The plan to apply - the one the operator was shown, or the one the+ * self-heal worker computed. Absent, `applyUpgrade` plans itself.+ */+ readonly plan?: UpgradePlan;+ readonly agent?: string;+ readonly now?: Date;+}+export class BrainUpgradeError extends Error {/*** The `upgrade-<ts>` snapshot run id when the failure happened* after the pre-apply snapshot was taken. `null` for failures- * during planning (malformed `_brain.yaml`, read errors) โ those- * never wrote anything, so there is nothing to roll back.+ * during planning (malformed `_brain.yaml`, read errors) or a drift+ * found before the snapshot โ those never wrote anything, so there+ * is nothing to roll back.*/readonly runId: string | null;+ /**+ * Vault-relative paths that changed on disk after the plan was read.+ * Empty unless the run was refused for drift.+ */+ readonly drifted: ReadonlyArray<string>;- constructor(message: string, runId: string | null = null) {+ constructor(message: string, runId: string | null = null, drifted: ReadonlyArray<string> = []) {super(message);this.name = "BrainUpgradeError";this.runId = runId;+ this.drifted = Object.freeze([...drifted]);}}@@ -114,29 +136,32 @@ export function planUpgrade(vault: string): UpgradePlan {// ----- applyUpgrade --------------------------------------------------------/**- * Apply every pending update from {@link planUpgrade}.+ * Apply every pending update of `opts.plan`, or of a fresh+ * {@link planUpgrade} when no plan is given.** Sequence:- * 1. Compute the plan. If `errors > 0`, throw โ never touch disk+ * 1. Take the plan. If `errors > 0`, throw โ never touch disk* when the schema source is malformed.* 2. If `pending === 0`, return early without taking a snapshot or* appending a log row. Idempotent re-run is free.- * 3. `createSnapshot(vault, run_id)` โ sidecar manifest comes+ * 3. Check every `update` row against the disk. A file that no+ * longer holds the bytes (or the absence) the plan read refuses+ * the whole run, naming each path, before anything is written.+ * 4. `createSnapshot(vault, run_id)` โ sidecar manifest comes* along automatically. The run id includes a `upgrade-` prefix* so the operator can spot upgrade snapshots in `--list`.- * 4. Write each `update` file via `atomicWriteFileSync`.- * 5. Append a `BRAIN_LOG_EVENT_KIND.upgrade` event.+ * 5. Write each `update` file via `atomicWriteFileSync` with+ * `expectBefore: file.before`, so an edit that landed during the+ * snapshot is refused at its row instead of overwritten.+ * 6. Append a `BRAIN_LOG_EVENT_KIND.upgrade` event.** On any write failure mid-step we throw โ the snapshot already* persisted is the recovery path (`o2b brain rollback upgrade-<ts>`).*/-export function applyUpgrade(- vault: string,- opts: { agent?: string; now?: Date } = {},-): UpgradeApplyResult {+export function applyUpgrade(vault: string, opts: ApplyUpgradeOptions = {}): UpgradeApplyResult {// Vault-identity write guard (context-integrity-gates, Unit J).assertVaultIdentityForWrite(vault);- const plan = planUpgrade(vault);+ const plan = opts.plan ?? planUpgrade(vault);if (plan.errors > 0) {const messages = plan.files.filter((f) => f.status === "error")@@ -154,6 +179,19 @@ export function applyUpgrade(});}+ const drifted = plan.files+ .filter((f) => f.status === "update" && !fileMatchesExpected(join(vault, f.path), f.before))+ .map((f) => f.path);+ if (drifted.length > 0) {+ throw new BrainUpgradeError(+ `upgrade refused: ${drifted.length} file(s) changed on disk since the upgrade plan ` ++ `was read: ${drifted.join(", ")}. Nothing was written and no snapshot was taken; ` ++ "re-run `o2b brain upgrade --dry-run` to review the current plan, then apply it.",+ null,+ drifted,+ );+ }+const now = opts.now ?? new Date();// One constant for the run-id prefix and the recorded reason.const runId = `${BRAIN_SNAPSHOT_REASON.upgrade}-${isoSecondCompact(now)}`;@@ -163,16 +201,20 @@ export function applyUpgrade(for (const file of plan.files) {if (file.status !== "update") continue;try {- atomicWriteFileSync(join(vault, file.path), file.after);+ atomicWriteFileSync(join(vault, file.path), file.after, { expectBefore: file.before });} catch (err) {+ // A drift leaves the edit on disk, so its remedy must not destroy+ // it: no rollback at all, only a re-plan that reads the edit.+ if (isFileDrift(err)) {+ throw new BrainUpgradeError(midApplyDriftMessage(file.path, updated), runId, [file.path]);+ }// Mid-apply failure: one or more files have already been// rewritten under the new release, the rest still match the// old. The pre-apply snapshot is the recovery path โ embed// its run id so the operator does not need to grep// `.snapshots/` to find it.throw new BrainUpgradeError(- `upgrade aborted mid-apply at ${file.path}: ` +- `${(err as Error).message ?? String(err)}. ` ++ `upgrade aborted mid-apply at ${file.path}: ${(err as Error).message ?? String(err)}. ` +`${updated.length} file(s) already rewritten; ` +`roll back via \`o2b brain rollback ${runId} --force-rollback\` ` +`before re-running.`,@@ -223,7 +265,7 @@ function planBrainYaml(vault: string): UpgradeFilePlan {// missing as an update from empty so `--apply` restores the// canonical body. Refusing here would block every other// managed-file update behind one missing config.- return makeUpdate(rel, "", DEFAULT_BRAIN_CONFIG_YAML);+ return makeUpdate(rel, null, DEFAULT_BRAIN_CONFIG_YAML);}return makeError(rel, `read failed: ${e.message ?? String(err)}`);}@@ -253,8 +295,8 @@ function planManagedPath(): UpgradeFilePlan {if (!existsSync(absolutePath)) {// File missing entirely: an upgrade should restore it. Treat as- // update with empty `before` so the diff shows the full body.- return makeUpdate(relPath, "", renderTarget(null));+ // update from absent (`null`) so the diff shows the full body.+ return makeUpdate(relPath, null, renderTarget(null));}let before: string;try {@@ -287,7 +329,7 @@ function makeNoop(path: string): UpgradeFilePlan {});}-function makeUpdate(path: string, before: string, after: string): UpgradeFilePlan {+function makeUpdate(path: string, before: string | null, after: string): UpgradeFilePlan {return Object.freeze({path,status: "update" as const,@@ -307,6 +349,29 @@ function makeError(path: string, message: string): UpgradeFilePlan {});}+/**+ * The refusal for a row that changed on disk during the apply. The next+ * plan reads the edit, so a fresh dry run is the only way forward offered.+ * A rollback is not: the snapshot manifest predates the apply, so plain+ * rollback reports every rewritten row as drift and exits, and+ * `--force-rollback` would destroy the edit.+ */+function midApplyDriftMessage(drifted: string, updated: ReadonlyArray<string>): string {+ const head =+ `upgrade refused at ${drifted}: the file changed on disk after the upgrade plan was ` ++ "read and was left as it is.";+ if (updated.length === 0) {+ return (+ `${head} Nothing was written; re-run \`o2b brain upgrade --dry-run\` to review a ` ++ "plan that reads the edit, then apply it."+ );+ }+ return (+ `${head} ${updated.length} file(s) already rewritten: ${updated.join(", ")}. ` ++ "Re-run `o2b brain upgrade --dry-run` to plan the rest against the edit, then apply it."+ );+}+/*** Compact ISO without colons or `Z` suffix so the run id is* filesystem-safe under every snapshot validator.diff --git a/src/core/egress/registry.ts b/src/core/egress/registry.tsindex 2710733e..19a9be2e 100644--- a/src/core/egress/registry.ts+++ b/src/core/egress/registry.ts@@ -239,7 +239,9 @@ export const EGRESS_SITES = Object.freeze({"come back unfindable while the index reported success, which is a silent failure " +"where this one is at least a stated exposure. The controls that do exist are " +"the operator's: semantic search is off until an endpoint and a key are configured, " +- "and the endpoint is whichever host they name, including a local one.",+ "and the endpoint is whichever host they name, including a local one. The request " ++ "also carries any extra body fields the operator declared in `embedding_extra_body`, " ++ "verbatim, next to the owned model, input and encoding fields.",},"search-embedding-zeroentropy": {id: "search-embedding-zeroentropy",diff --git a/src/core/fs-atomic.ts b/src/core/fs-atomic.tsindex 3aeac6cd..a44178a8 100644--- a/src/core/fs-atomic.ts+++ b/src/core/fs-atomic.ts@@ -11,6 +11,7 @@* directory entry to durably persist the rename).*/+import { isUtf8 } from "node:buffer";import {closeSync,existsSync,@@ -33,6 +34,19 @@ export interface AtomicWriteOptions {* churn in a vault the user is also hand-editing.*/readonly skipIfUnchanged?: boolean;+ /**+ * Compare-before-write. When set, the target must still hold exactly these+ * bytes (a string) or still be absent (`null`), checked before the temp+ * file is made and again right before the rename; otherwise the write+ * throws {@link FileDriftError} and the target is left untouched. An empty+ * string and an absent file are different states. `undefined` (the+ * default) keeps the unconditional overwrite.+ *+ * The window between the final re-read and `rename(2)` stays open: it is+ * the same advisory window `skipIfUnchanged` has, and closing it needs an+ * OS lock that vault sync tools do not honour.+ */+ readonly expectBefore?: string | null;}/**@@ -133,8 +147,13 @@ export function atomicWriteFileSync(contents: string,opts: AtomicWriteOptions = {},): boolean {+ const expected = opts.expectBefore;+ if (expected !== undefined) assertExpectedBefore(target, expected);if (opts.skipIfUnchanged && isUnchanged(target, contents)) return false;withTempFile(target, contents, (tmpPath) => {+ // Re-read right before the rename: the temp write and fsync are the+ // slow part, and an edit that landed during them must not be lost.+ if (expected !== undefined) assertExpectedBefore(target, expected);// POSIX `rename(2)` is atomic and clobbers an existing target โ that's// exactly the "overwrite" semantic we want. No exclusivity guarantee.// Windows `MoveFileEx(REPLACE_EXISTING)` is too, once no reader holds@@ -157,6 +176,76 @@ function isUnchanged(target: string, contents: string): boolean {}}+/**+ * Is `target` in the `expected` state: absent for `null`, holding exactly+ * these bytes for a string? The one definition of drift, shared by the+ * write below and by callers that check a batch before writing any of it.+ *+ * Valid UTF-8 is compared byte for byte, so any real edit is drift. Bytes+ * that are not valid UTF-8 can never equal an encoded string, yet the+ * caller's `expected` came from a lossy UTF-8 read of those same bytes; for+ * them the lossy decodings are compared instead, or an untouched legacy file+ * would be refused on every attempt. Known limits of that lossy arm: two+ * different invalid sequences that decode to the same text (0xfe and 0xff+ * both become U+FFFD) are indistinguishable, and so is a valid UTF-8 file+ * whose literal U+FFFD character was replaced by an invalid byte, because+ * the edited file decodes back to the text the caller read. A read error+ * other than "absent" propagates - an+ * unreadable target cannot be shown to be unchanged.+ */+export function fileMatchesExpected(target: string, expected: string | null): boolean {+ let current: Buffer;+ try {+ current = readFileSync(target);+ } catch (err) {+ if ((err as NodeJS.ErrnoException | null)?.code !== "ENOENT") throw err;+ return expected === null;+ }+ if (expected === null) return false;+ if (current.equals(Buffer.from(expected, "utf8"))) return true;+ return !isUtf8(current) && current.toString("utf8") === expected;+}++/** Throw {@link FileDriftError} unless {@link fileMatchesExpected} holds. */+function assertExpectedBefore(target: string, expected: string | null): void {+ if (!fileMatchesExpected(target, expected)) throw new FileDriftError(target);+}++/** Stable code a {@link FileDriftError} carries, for `isFileDrift`. */+const FILE_DRIFT_CODE = "FILE_DRIFT";++/**+ * A compare-before-write refused: the target no longer holds the bytes (or+ * the absence) the caller read, so writing would overwrite a change the+ * caller never saw. Named like {@link FileAlreadyExistsError}, its sibling+ * refusal for a create.+ */+export class FileDriftError extends Error {+ readonly code: typeof FILE_DRIFT_CODE = FILE_DRIFT_CODE;+ /** Absolute path whose state drifted. */+ readonly path: string;++ constructor(path: string) {+ super(+ `file changed since it was read: ${path}; the write was refused ` ++ "and the file left as it is. Re-read it and retry.",+ );+ this.name = "FileDriftError";+ this.path = path;+ }+}++/** Is `err` a {@link FileDriftError}, directly or nested on `.cause`? */+export function isFileDrift(err: unknown): boolean {+ let current: unknown = err;+ for (let depth = 0; depth < CAUSE_WALK_LIMIT; depth += 1) {+ if (typeof current !== "object" || current === null) return false;+ if ((current as { readonly code?: unknown }).code === FILE_DRIFT_CODE) return true;+ current = (current as { readonly cause?: unknown }).cause;+ }+ return false;+}+export interface AtomicWriteTextOptions {/** File mode for the new inode. Defaults to private `0o600`. */readonly mode?: number;diff --git a/src/core/maintenance/self-heal-upgrade.ts b/src/core/maintenance/self-heal-upgrade.tsindex c9e8be6a..6539fcd4 100644--- a/src/core/maintenance/self-heal-upgrade.ts+++ b/src/core/maintenance/self-heal-upgrade.ts@@ -164,7 +164,9 @@ function attempt(vault: string, now: Date): SelfHealUpgradeRun {}pending = plan.files.filter((f) => f.status === "update").map((f) => f.path);if (vaultGone(vault)) return run(SELF_HEAL_UPGRADE_OUTCOME.notInitialized);- const applied = applyUpgrade(vault, { now });+ // The plan just computed, so the attempt plans once and a file edited+ // since is refused as drift rather than overwritten.+ const applied = applyUpgrade(vault, { plan, now });// The metrics row creates its directory: a vault removed during the// rewrite would come back for it.if (vaultGone(vault)) return run(SELF_HEAL_UPGRADE_OUTCOME.notInitialized);diff --git a/src/core/search/benchmark.ts b/src/core/search/benchmark.tsindex a792d7e1..cd4d8764 100644--- a/src/core/search/benchmark.ts+++ b/src/core/search/benchmark.ts@@ -22,6 +22,8 @@import { Semaphore } from "./embeddings/http-util.ts";import { search } from "./search.ts";import { resolvedTransportReach, type TransportReach } from "../graph/transport-reach.ts";+import { BLOCKED_TIER_ERROR_CODE, type BlockedCapabilityTier } from "./capability-tier.ts";+import { RETRIEVAL_DEGRADATION, type RetrievalDegradationCode } from "./retrieval-trail.ts";import { SearchError } from "./types.ts";import type { ResolvedSearchConfig, SearchOutcome } from "./types.ts";@@ -120,6 +122,12 @@ export interface RecallBenchmarkQueryResult {readonly expectedFound: number;/** Total expected paths declared for this query. */readonly expectedTotal: number;+ /**+ * The retrieval trail's degradation codes for this query, present only+ * when the search was degraded: a hit scored by a lane that did not run+ * (the spend gate, a provider outage) is a keyword-only measurement.+ */+ readonly degraded?: ReadonlyArray<RetrievalDegradationCode>;}export interface RecallBenchmarkReport {@@ -159,9 +167,27 @@ export interface RecallBenchmarkReport {* this with `source_warnings_max`.*/readonly sourceWarnings: number;+ /**+ * Every degradation code any query carried, sorted and de-duplicated.+ * Empty when every query ran the pipeline it asked for; otherwise the+ * scores above measure a degraded system, not the configured one.+ */+ readonly degraded: ReadonlyArray<RetrievalDegradationCode>;+ /**+ * The capability rung behind `semantic-capability-blocked`, present only+ * when {@link degraded} carries that code. The rung is configuration, so+ * every query that carried the code carried the same one; it is what+ * lets a refusal name the error the explicit lane throws for it.+ */+ readonly capabilityTier?: BlockedCapabilityTier;readonly perQuery: ReadonlyArray<RecallBenchmarkQueryResult>;}+/** Narrow a trail detail value to a blocked rung, without a cast. */+function isBlockedCapabilityTier(value: unknown): value is BlockedCapabilityTier {+ return typeof value === "string" && Object.hasOwn(BLOCKED_TIER_ERROR_CODE, value);+}+/** Folded substring containment, language-agnostic (no word lists). */function answerContainedIn(answer: string, contents: ReadonlyArray<string>): boolean {const needle = answer.replace(/\s+/gu, " ").trim().toLowerCase();@@ -253,6 +279,7 @@ export async function runRecallBenchmark(const expand = opts.expand === true;const reach = resolvedTransportReach(opts.transportReach);+ let capabilityTier: BlockedCapabilityTier | undefined;const perQuery = await Promise.all(dataset.queries.map(async (q): Promise<RecallBenchmarkQueryResult> => {const depth = q.k ?? k;@@ -289,6 +316,16 @@ export async function runRecallBenchmark(q.answer,topK.map((r) => r.content),);+ const degraded = (outcome.retrievalTrail?.degraded ?? []).map((d) => d.code);+ for (const d of outcome.retrievalTrail?.degraded ?? []) {+ const tier = d.detail?.tier;+ if (+ d.code === RETRIEVAL_DEGRADATION.semanticCapabilityBlocked &&+ isBlockedCapabilityTier(tier)+ ) {+ capabilityTier = tier;+ }+ }return Object.freeze({id: q.id,query: q.query,@@ -298,6 +335,7 @@ export async function runRecallBenchmark(answerContained,expectedFound,expectedTotal: expected.size,+ ...(degraded.length > 0 ? { degraded: Object.freeze(degraded) } : {}),});}),);@@ -309,6 +347,7 @@ export async function runRecallBenchmark(const expectedFoundTotal = perQuery.reduce((sum, r) => sum + r.expectedFound, 0);const expectedDeclaredTotal = perQuery.reduce((sum, r) => sum + r.expectedTotal, 0);const hitRanks = perQuery.filter((r) => r.rank !== null).map((r) => r.rank!);+ const degraded = [...new Set(perQuery.flatMap((r) => r.degraded ?? []))].toSorted();return Object.freeze({total: perQuery.length,k,@@ -322,6 +361,8 @@ export async function runRecallBenchmark(citationDepth:hitRanks.length === 0 ? 0 : hitRanks.reduce((sum, r) => sum + r, 0) / hitRanks.length,sourceWarnings: perQuery.length - hits,+ degraded: Object.freeze(degraded),+ ...(capabilityTier !== undefined ? { capabilityTier } : {}),perQuery: Object.freeze(perQuery),});}diff --git a/src/core/search/embeddings/openai-compat.ts b/src/core/search/embeddings/openai-compat.tsindex c0242c43..f204413c 100644--- a/src/core/search/embeddings/openai-compat.ts+++ b/src/core/search/embeddings/openai-compat.ts@@ -456,7 +456,10 @@ export class OpenAICompatProvider implements EmbeddingProvider {"content-type": "application/json",authorization: `Bearer ${this.activeKey}`,},+ // The operator's extra fields go first so the owned fields always+ // win; resolution already refuses a reserved key by name.body: JSON.stringify({+ ...this.config.extraBody,model: this.model,input: texts,encoding_format: "float",diff --git a/src/core/search/embeddings/presets.ts b/src/core/search/embeddings/presets.tsindex a977ac37..e502b0e6 100644--- a/src/core/search/embeddings/presets.ts+++ b/src/core/search/embeddings/presets.ts@@ -15,7 +15,7 @@* width, useful when setting `embedding_dimension` up front.*/-import type { EmbeddingProviderName } from "../types.ts";+import type { EmbeddingProviderName, ResolvedEmbeddingConfig } from "../types.ts";/*** Instruction prefix an e5-family model expects before a search query@@ -168,6 +168,38 @@ export function declaredInputWindowTokens(model: string | null): number | null {return findEmbeddingPreset(model)?.inputWindowTokens ?? null;}+/**+ * The config key an operator declares a model's input window with. Named+ * once so the resolver, its validation and every refusal spell it alike.+ */+export const INPUT_WINDOW_TOKENS_KEY = "embedding_input_window_tokens";++/**+ * The input window that governs the configured backend, or `null` when+ * nobody declared one.+ *+ * Precedence: the operator's `embedding_input_window_tokens`, then the+ * window the curated table declares for the model, then unknown. The+ * operator key exists for the same reason the price pair does: a model+ * outside the table has no other way to be declared, and an unknown+ * window cuts nothing and censuses nothing.+ *+ * `model` defaults to the configured one; a caller that falls back to the+ * model the index recorded (the census) passes that instead.+ *+ * The offline local embedder answers `null` whatever the key says: it+ * hashes n-gram features over the whole text, with no encoder and no+ * positional limit, so there is no window to cut a query to or to+ * census chunks against.+ */+export function effectiveInputWindowTokens(+ semantic: Pick<ResolvedEmbeddingConfig, "provider" | "model" | "inputWindowTokens">,+ model: string | null = semantic.model,+): number | null {+ if (semantic.provider === "local") return null;+ return semantic.inputWindowTokens ?? declaredInputWindowTokens(model);+}+/*** Structural e5-family detection (memory-write-path-integrity B2). Matches the* `e5` token wherever it appears delimited by `/` or `-` in the model id@@ -213,6 +245,30 @@ export function passagePrefixSentByProvider(}}+/**+ * The query prefix the CONFIGURED BACKEND will actually prepend to a+ * search query - the twin of {@link passagePrefixSentByProvider}, for the+ * same reason: a query fit that charged a prefix to a backend that never+ * sends one would cut a query that fits.+ *+ * Exhaustive over {@link EmbeddingProviderName} with no default arm, so a+ * new backend fails to compile here.+ */+export function queryPrefixSentByProvider(+ provider: EmbeddingProviderName,+ configuredQueryPrefix: string | undefined,+): string {+ switch (provider) {+ case "openai-compat":+ // Exactly `OpenAICompatProvider.prefixFor("query")`.+ return configuredQueryPrefix ?? "";+ case "zeroentropy":+ case "local":+ case "disabled":+ return "";+ }+}+/** The prefix pair active for an embed run, after preset + config resolution. */export interface ResolvedEmbeddingPrefixes {readonly queryPrefix: string;diff --git a/src/core/search/embeddings/query-embed.ts b/src/core/search/embeddings/query-embed.tsnew file mode 100644index 00000000..62a2b379--- /dev/null+++ b/src/core/search/embeddings/query-embed.ts@@ -0,0 +1,257 @@+/**+ * The query-embed gateway (honest-query-embed-and-safe-upgrades).+ *+ * Every paid query embed answers the same question before it spends: what+ * text goes on the wire. This module answers it once, so the search lane+ * and the semantic belief order cannot disagree about it.+ *+ * The fit cuts the query to the effective input window+ * (`effectiveInputWindowTokens` in `presets.ts`), charging the prefix the+ * backend actually sends against it. The cut uses the CEILING estimate,+ * the bound that cannot under-count, so it never sends more than the+ * window. Spend disclosure keeps the shared floor-side `estimateTokens`,+ * so a query receipt stays comparable with every other spend surface.+ * The ceiling over-cuts non-ASCII text; that is the safe direction, and+ * there is no real tokenizer here on purpose (no dependency).+ *+ * An unknown window cuts nothing, which is byte-identical to the+ * behaviour before the window was known to anyone.+ *+ * The gate decides whether the embed is sent at all. A caller that is not+ * local spends the operator's money on every request, so under a positive+ * `embedding_cost_gate_usd` a model nobody priced is refused before any+ * provider exists. That is v1.72.0's rule exactly (the unpriced arm only,+ * never an over-cap comparison for one query), and this is the one place+ * it lives. The gateway returns data rather than throwing, because its+ * callers report a refusal differently: the search lane has an explicit+ * and an implicit arm, the semantic belief order always refuses.+ */++import { resolvedTransportReach, TRANSPORT_REACH } from "../../graph/transport-reach.ts";+import type { TransportReach } from "../../graph/transport-reach.ts";+import { activeSpendQuote, COST_GATE_KEY } from "../embedding-spend.ts";+import type { ResolvedSearchConfig } from "../types.ts";+import {+ effectiveInputWindowTokens,+ INPUT_WINDOW_TOKENS_KEY,+ queryPrefixSentByProvider,+} from "./presets.ts";+import {+ EMBEDDING_PRICE_MODEL_KEY,+ EMBEDDING_PRICE_RATE_KEY,+ EMBEDDING_PRICE_SOURCE,+ type PriceQuote,+} from "./pricing.ts";+import { estimateTokens, textExtent, tokenEstimateCeiling } from "./signature.ts";++/** What a query fit decided: the text to send and what it costs. */+export interface QueryFit {+ /**+ * The query as it will be sent, without the prefix (the provider adds+ * the prefix itself). Empty when the prefix alone fills the window: the+ * caller must treat that as a degradation, never embed it.+ */+ readonly text: string;+ /** True when {@link text} is shorter than the query the caller sent. */+ readonly truncated: boolean;+ /**+ * The spend estimate (`estimateTokens`) of what goes on the wire, prefix+ * included. Zero when nothing is sent.+ */+ readonly sentTokens: number;+}++/** UTF-8 byte length of one code point. */+function utf8Length(codePoint: number): number {+ if (codePoint < 0x80) return 1;+ if (codePoint < 0x800) return 2;+ if (codePoint < 0x10000) return 3;+ return 4;+}++/**+ * The longest code-point prefix of `query` whose ceiling estimate, with+ * `prefix` in front, fits `windowTokens`. A `null` window means unknown,+ * and an unknown window cuts nothing.+ *+ * The cut is at a code-point boundary, so it never splits a surrogate+ * pair, and it is language-agnostic: no word or grapheme rule. The+ * ceiling never decreases as code points are appended (each one adds at+ * most one non-ASCII slot and at most one remainder code point), so the+ * first code point that overflows marks the cut.+ */+export function fitQueryToWindow(+ query: string,+ prefix: string,+ windowTokens: number | null,+): QueryFit {+ const whole = (): QueryFit =>+ Object.freeze({+ text: query,+ truncated: false,+ sentTokens: estimateTokens([prefix + query]),+ });+ if (windowTokens === null) return whole();++ const base = textExtent(prefix);+ const fits = (codePoints: number, utf8Bytes: number): boolean =>+ tokenEstimateCeiling({+ codePoints: base.codePoints + codePoints,+ utf8Bytes: base.utf8Bytes + utf8Bytes,+ }) <= windowTokens;++ const codePoints = [...query];+ let kept = 0;+ let bytes = 0;+ for (const ch of codePoints) {+ const next = bytes + utf8Length(ch.codePointAt(0)!);+ if (!fits(kept + 1, next)) break;+ kept++;+ bytes = next;+ }+ if (kept === codePoints.length) return whole();++ const text = codePoints.slice(0, kept).join("");+ return Object.freeze({+ text,+ truncated: true,+ sentTokens: text === "" ? 0 : estimateTokens([prefix + text]),+ });+}++/** The gateway refused: the embed must not be sent. */+export interface QueryEmbedRefused {+ readonly kind: "refused";+ readonly code: "EMBEDDING_COST_UNPRICED";+ /** The model the embed would have named, null when none is configured. */+ readonly model: string | null;+}++/** The gateway cleared the embed: send {@link text}, disclose the rest. */+interface QueryEmbedReadyBase extends QueryFit {+ readonly kind: "ready";+ /** The price quote every spend surface shares for {@link model}. */+ readonly quote: PriceQuote;+ /** The model the embed names, null when none is configured. */+ readonly model: string | null;+}++/** The query fits its window (or the window is unknown): it is sent whole. */+export interface QueryEmbedWhole extends QueryEmbedReadyBase {+ readonly truncated: false;+ readonly emptyFit: false;+ /** The effective input window the text was fitted to; null when unknown. */+ readonly windowTokens: number | null;+}++/** The query was cut to its window; only a known window cuts. */+export interface QueryEmbedCut extends QueryEmbedReadyBase {+ readonly truncated: true;+ /**+ * True when the instruction prefix alone fills the window, so nothing of+ * the query survived the cut. Every caller must treat it as a+ * degradation and never embed the prefix by itself.+ */+ readonly emptyFit: boolean;+ /** The effective input window the text was cut to. */+ readonly windowTokens: number;+}++/** A cleared embed: whole, or cut to a known window. */+export type QueryEmbedReady = QueryEmbedWhole | QueryEmbedCut;++/** What {@link prepareQueryEmbed} decided. */+export type QueryEmbedPreparation = QueryEmbedRefused | QueryEmbedReady;++/**+ * Decide whether, and with what text, a query is embedded.+ *+ * Pure over the config: no provider is constructed and nothing is sent.+ * An omitted reach resolves through `resolvedTransportReach` (remote), as+ * everywhere else in the tree. The local hashing embedder is priced at 0+ * by the builtin table, so it is never refused; a self-hosted model is+ * unpriced until the operator declares its price (0 for free).+ */+export function prepareQueryEmbed(+ config: ResolvedSearchConfig,+ query: string,+ reach: TransportReach | undefined,+): QueryEmbedPreparation {+ const { model, quote } = activeSpendQuote(config);+ if (+ resolvedTransportReach(reach) !== TRANSPORT_REACH.local &&+ config.semantic.costGateUsd > 0 &&+ quote.source === EMBEDDING_PRICE_SOURCE.unknown+ ) {+ return Object.freeze({ kind: "refused", code: "EMBEDDING_COST_UNPRICED", model });+ }+ const windowTokens = effectiveInputWindowTokens(config.semantic);+ const fit = fitQueryToWindow(+ query,+ queryPrefixSentByProvider(config.semantic.provider, config.semantic.queryPrefix),+ windowTokens,+ );+ if (fit.truncated && windowTokens !== null) {+ return Object.freeze({+ kind: "ready",+ ...fit,+ truncated: true,+ emptyFit: fit.text === "",+ windowTokens,+ quote,+ model,+ });+ }+ return Object.freeze({+ kind: "ready",+ ...fit,+ truncated: false,+ emptyFit: false,+ windowTokens,+ quote,+ model,+ });+}++/**+ * The operator-facing sentence for a refused query embed: the model, the+ * gate key, and the price pair that clears it. Shared so every caller+ * that surfaces the refusal names the same lever.+ *+ * The gate amount is the operator's budget and the gateway refuses only+ * callers that are not local, so the sentence says the gate is positive+ * and never states the amount.+ */+export function queryEmbedRefusalMessage(refused: QueryEmbedRefused): string {+ return (+ `embedding model ${refused.model ?? "(unset)"} has no known price and ` ++ `${COST_GATE_KEY} is positive, so a query embed for a caller ` ++ `that is not local is refused. Declare its price with ${EMBEDDING_PRICE_MODEL_KEY} ` ++ `and ${EMBEDDING_PRICE_RATE_KEY} (0 for a free self-hosted model).`+ );+}++/**+ * The operator-facing sentence for an empty fit: the window, and the key+ * that raises it when the model accepts more. Shared so the search lane+ * and the semantic belief order name the same lever.+ */+export function queryEmbedEmptyFitMessage(cut: QueryEmbedCut): string {+ return (+ `the ${cut.windowTokens}-token embedding input window leaves no room for the query ` ++ `after the instruction prefix; raise ${INPUT_WINDOW_TOKENS_KEY} if the model accepts ` ++ `more, or shorten the query prefix`+ );+}++/**+ * The operator-facing sentence for a query cut to its window: the window,+ * how much of `query` was embedded, and the key that raises the window.+ */+export function queryEmbedCutMessage(cut: QueryEmbedCut, query: string): string {+ return (+ `query cut to the ${cut.windowTokens}-token embedding input window: ` ++ `${[...cut.text].length} of ${[...query].length} code point(s) embedded; ` ++ `raise ${INPUT_WINDOW_TOKENS_KEY} if the model accepts more`+ );+}diff --git a/src/core/search/feedback.ts b/src/core/search/feedback.tsindex 4c58321e..f8a1cc24 100644--- a/src/core/search/feedback.ts+++ b/src/core/search/feedback.ts@@ -25,6 +25,7 @@ import { join } from "node:path";import type { BrainSearchResult, ResolvedSearchConfig, WeightProfile } from "./types.ts";import type { TransportReach } from "../graph/transport-reach.ts";+import { semanticLaneMissing, type RetrievalDegradationCode } from "./retrieval-trail.ts";/** Lower bound for one learned per-layer multiplier. */export const LEARNED_WEIGHT_MIN = 0.8;@@ -314,6 +315,14 @@ export interface CaptureRecallFeedbackOutcome {readonly learned: LearnedWeights;/** False when the judged path was not in the re-ran result set. */readonly resultFound: boolean;+ /**+ * Why the re-run narrowed, as the trail's codes; empty when nothing did.+ * The re-run is gated like any search (a remote caller's unpriced query+ * embed is refused), so the contributions it recorded describe the+ * ranking this caller's own search produces, and this says when that+ * ranking was keyword-only.+ */+ readonly degraded: ReadonlyArray<RetrievalDegradationCode>;}/**@@ -336,9 +345,17 @@ export async function captureRecallFeedback(...(input.transportReach !== undefined ? { transportReach: input.transportReach } : {}),});const hit = outcome.results.find((r) => r.path === input.resultPath);- const contributions: LayerContributions = hit- ? contributionsFromResult(hit)- : Object.freeze({ keyword: 0, semantic: 0, entity: 0, recency: 0 });+ const degraded = Object.freeze((outcome.retrievalTrail?.degraded ?? []).map((d) => d.code));+ // A re-run the semantic lane never reached (the spend gate, or any other+ // stop under hybrid recall) scored the hit on a keyword-only pool, so its+ // layer shares describe the degradation, not the result. The event keeps+ // its audit row with zero contributions, which the fold skips, so the+ // vault-wide weights never drift toward keyword while the gate holds.+ const laneMissing = semanticLaneMissing(degraded);+ const contributions: LayerContributions =+ hit && !laneMissing+ ? contributionsFromResult(hit)+ : Object.freeze({ keyword: 0, semantic: 0, entity: 0, recency: 0 });const normalized = input.query.trim().replace(/\s+/gu, " ").toLowerCase();const event: RecallFeedbackEvent = Object.freeze({ts: input.nowMs ?? Date.now(),@@ -349,5 +366,5 @@ export async function captureRecallFeedback(});const file = recordRecallFeedback(config.vault, event);const learned = readLearnedWeights(config.vault) ?? NEUTRAL_LEARNED_WEIGHTS;- return Object.freeze({ file, event, learned, resultFound: hit !== undefined });+ return Object.freeze({ file, event, learned, resultFound: hit !== undefined, degraded });}diff --git a/src/core/search/index.ts b/src/core/search/index.tsindex b149c695..ef8c320e 100644--- a/src/core/search/index.ts+++ b/src/core/search/index.ts@@ -9,6 +9,7 @@ import {parseBool as parseBoolShared,parseFloat01 as parseFloat01Shared,parseInteger as parseIntegerShared,+ normalizeReservedName,} from "../validate.ts";import { resolveVaultScope } from "../vault-scope/index.ts";import { DEFAULT_HYBRID_DEADLINE_MS } from "./pipeline/request.ts";@@ -29,7 +30,7 @@ import {} from "./embeddings/credential-report.ts";import { loadRerankRegistry, expandRegisteredRerankProvider } from "./rerank/registry.ts";import { decisionModelModeFor, resolveDecisionModelConfig } from "../decision-model/config.ts";-import { resolveEmbeddingPrefixes } from "./embeddings/presets.ts";+import { INPUT_WINDOW_TOKENS_KEY, resolveEmbeddingPrefixes } from "./embeddings/presets.ts";import {EMBEDDING_PRICE_MODEL_ENV,EMBEDDING_PRICE_MODEL_KEY,@@ -402,6 +403,135 @@ function resolveEmbeddingPriceOverride(return Object.freeze({ model, usdPerMtok });}+export const EXTRA_BODY_KEY = "embedding_extra_body";+export const EXTRA_BODY_ENV = "OPEN_SECOND_BRAIN_EMBEDDING_EXTRA_BODY";+const EMBEDDING_DIMENSION_KEY = "embedding_dimension";++/**+ * Request-body fields the OpenAI-compatible provider owns. An extra body+ * may not name them in any spelling: the provider spreads the extra+ * fields first so these win anyway, but a silently ignored field is a+ * configuration the operator believes is in force when it is not.+ */+export const RESERVED_EMBEDDING_BODY_KEYS: ReadonlyArray<string> = Object.freeze([+ "model",+ "input",+ "encoding_format",+]);++const RESERVED_BODY_KEYS_NORMALIZED: ReadonlySet<string> = new Set(+ RESERVED_EMBEDDING_BODY_KEYS.map(normalizeReservedName),+);++/**+ * The operator's extra request body: a JSON object in one flat key,+ * because the config file cannot hold a nested map. Read with raw+ * presence so a blank value is refused rather than folded into "unset".+ * Every refusal names the source the value came from - the env variable+ * when it is set, the config key otherwise. The cross-checks against the+ * rest of the resolved config (the `dimensions` field, the provider)+ * live in `validateExtraBody`, so a programmatic override meets them too.+ * Null when neither source sets the key.+ */+function resolveEmbeddingExtraBody(+ env: NodeJS.ProcessEnv,+ config: Readonly<Record<string, string>>,+): Readonly<Record<string, unknown>> | null {+ const raw = rawSetting(env, config, EXTRA_BODY_ENV, EXTRA_BODY_KEY);+ if (raw === null) return null;+ const source = env[EXTRA_BODY_ENV] !== undefined ? EXTRA_BODY_ENV : EXTRA_BODY_KEY;+ if (raw.trim() === "") {+ throw new SearchError("INVALID_INPUT", `${source} must be a JSON object, got a blank value`);+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ throw new SearchError("INVALID_INPUT", `${source} must be a JSON object, got invalid JSON`);+ }+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {+ throw new SearchError(+ "INVALID_INPUT",+ `${source} must be a JSON object, got ${describeJsonKind(parsed)}`,+ );+ }+ const body = parsed as Record<string, unknown>;+ refuseReservedBodyKeys(body, source);+ return Object.freeze(body);+}++/** The kind of a parsed JSON value that is not an object, as a refusal names it. */+function describeJsonKind(value: unknown): string {+ if (value === null) return "null";+ if (Array.isArray(value)) return "an array";+ return typeof value;+}++/**+ * Refuse every key that names an owned request field in any spelling,+ * listing them all in one sentence that names `source`. Run at parse time+ * to name the env variable or the key, and again in `validateExtraBody`+ * so an override that never passed through the parser meets it too.+ */+function refuseReservedBodyKeys(body: Readonly<Record<string, unknown>>, source: string): void {+ const reserved = Object.keys(body).filter((k) =>+ RESERVED_BODY_KEYS_NORMALIZED.has(normalizeReservedName(k)),+ );+ if (reserved.length > 0) {+ throw new SearchError(+ "INVALID_INPUT",+ `${source} may not set the owned request fields (${RESERVED_EMBEDDING_BODY_KEYS.join(", ")}): ` ++ `refused ${reserved.map((k) => `'${k}'`).join(", ")}`,+ );+ }+}++/**+ * Cross-check a resolved extra body against the config it rides in.+ *+ * A `dimensions` field, in any spelling, changes the width the provider+ * answers with. With no configured `embedding_dimension` nothing pins the+ * index to that width, so a mismatch with the stored index would surface+ * as a raw vector-store error mid-search; with one configured, the two+ * must agree. Only the OpenAI-compatible provider sends an extra body at+ * all, so naming one for another backend is refused rather than left as a+ * configuration the operator believes is in force; `disabled` sends+ * nothing, so the body is inert there. All of it is refused here rather+ * than at parse time so an override that never passed through the parser+ * meets it too. Every refusal names `source`: the env variable when it+ * supplied the body, the config key otherwise.+ */+function validateExtraBody(semantic: ResolvedEmbeddingConfig, source: string): void {+ const body = semantic.extraBody;+ if (body === undefined) return;+ if (semantic.provider !== "openai-compat" && semantic.provider !== "disabled") {+ throw new SearchError(+ "INVALID_INPUT",+ `${source} is only sent by the 'openai-compat' provider, ` ++ `but embedding_provider is '${semantic.provider}': remove the key or switch providers`,+ );+ }+ refuseReservedBodyKeys(body, source);+ const target = normalizeReservedName("dimensions");+ for (const key of Object.keys(body)) {+ if (normalizeReservedName(key) !== target) continue;+ const value = JSON.stringify(body[key]);+ if (semantic.dimension === null) {+ throw new SearchError(+ "INVALID_INPUT",+ `${source} sets '${key}' ${value} but ${EMBEDDING_DIMENSION_KEY} is not set: ` ++ `declare ${EMBEDDING_DIMENSION_KEY} with the same width so the index is pinned to it`,+ );+ }+ if (body[key] !== semantic.dimension) {+ throw new SearchError(+ "INVALID_INPUT",+ `${source} sets '${key}' ${value} but ${EMBEDDING_DIMENSION_KEY} is ${semantic.dimension}`,+ );+ }+ }+}+/*** Raw setting lookup that preserves an explicit empty string* (memory-write-path-integrity B2). Unlike `envOrConfig`, which folds `""`@@ -471,7 +601,7 @@ function validateWeight(n: number, fieldName: string): void {}}-function validateResolvedConfig(config: ResolvedSearchConfig): void {+function validateResolvedConfig(config: ResolvedSearchConfig, extraBodySource: string): void {validateIntegerRange(config.chunkSize, "search_chunk_size", { min: 1 });validateIntegerRange(config.chunkOverlap, "search_chunk_overlap", { min: 0 });if (config.chunkOverlap >= config.chunkSize) {@@ -496,7 +626,7 @@ function validateResolvedConfig(config: ResolvedSearchConfig): void {);}if (config.semantic.dimension !== null) {- validateIntegerRange(config.semantic.dimension, "embedding_dimension", {+ validateIntegerRange(config.semantic.dimension, EMBEDDING_DIMENSION_KEY, {min: 1,});}@@ -527,9 +657,26 @@ function validateResolvedConfig(config: ResolvedSearchConfig): void {min: 1,});}+ // Optional and default-free, like the token budget: a window that holds+ // nothing is a misconfiguration whatever its source. The offline local+ // embedder hashes the whole text with no positional limit and never+ // reads this key, so a declared window there would not be in force.+ if (config.semantic.inputWindowTokens !== undefined) {+ validateIntegerRange(config.semantic.inputWindowTokens, INPUT_WINDOW_TOKENS_KEY, {+ min: 1,+ });+ if (config.semantic.provider === "local") {+ throw new SearchError(+ "INVALID_INPUT",+ `${INPUT_WINDOW_TOKENS_KEY} is not read by the 'local' provider, ` ++ `which has no input window: remove the key or switch providers`,+ );+ }+ }validateIntegerRange(config.semantic.maxRetries, "embedding_max_retries", {min: 1,});+ validateExtraBody(config.semantic, extraBodySource);}function parseProvider(raw: string | null): ResolvedEmbeddingConfig["provider"] {@@ -716,9 +863,14 @@ export function resolveSearchConfig(opts: {const apiKeys: ReadonlyArray<string> = explicitApiKey? [explicitApiKey]: (registryExpansion?.apiKeys ?? (apiKey ? [apiKey] : []));- const dimRaw = envOrConfig(env, config, "OPEN_SECOND_BRAIN_EMBEDDING_DIM", "embedding_dimension");+ const dimRaw = envOrConfig(+ env,+ config,+ "OPEN_SECOND_BRAIN_EMBEDDING_DIM",+ EMBEDDING_DIMENSION_KEY,+ );const dimension =- dimRaw === null ? null : parseInteger(dimRaw, 0, "embedding_dimension", { min: 1 });+ dimRaw === null ? null : parseInteger(dimRaw, 0, EMBEDDING_DIMENSION_KEY, { min: 1 });const timeoutMs = parseInteger(envOrConfig(env, config, "OPEN_SECOND_BRAIN_EMBEDDING_TIMEOUT", "embedding_timeout_ms"),DEFAULTS.timeoutMs,@@ -767,6 +919,19 @@ export function resolveSearchConfig(opts: {batchTokensRaw === null? null: parseInteger(batchTokensRaw, 0, "embedding_batch_tokens", { min: 1 });+ // The declared input window of an uncurated model. Read with raw+ // presence, not `envOrConfig`, so a blank value is refused rather than+ // folded into "unset": an operator who wrote the key meant a window.+ const inputWindowTokensRaw = rawSetting(+ env,+ config,+ "OPEN_SECOND_BRAIN_EMBEDDING_INPUT_WINDOW_TOKENS",+ INPUT_WINDOW_TOKENS_KEY,+ );+ const inputWindowTokens =+ inputWindowTokensRaw === null+ ? null+ : parseInteger(inputWindowTokensRaw, 0, INPUT_WINDOW_TOKENS_KEY, { min: 1 });const maxRetries = parseInteger(envOrConfig(env, config, "OPEN_SECOND_BRAIN_EMBEDDING_MAX_RETRIES", "embedding_max_retries"),DEFAULTS.maxRetries,@@ -779,6 +944,7 @@ export function resolveSearchConfig(opts: {"embedding_cost_gate_usd",);const priceOverride = resolveEmbeddingPriceOverride(env, config);+ const extraBody = resolveEmbeddingExtraBody(env, config);// Instruction prefixes (memory-write-path-integrity B2). Resolved with raw// presence, not `envOrConfig`, because an explicit empty string must DISABLE@@ -808,11 +974,13 @@ export function resolveSearchConfig(opts: {concurrency,batchSize,...(batchTokens === null ? {} : { batchTokens }),+ ...(inputWindowTokens === null ? {} : { inputWindowTokens }),maxRetries,costGateUsd,...(priceOverride === null ? {} : { priceOverride }),queryPrefix,passagePrefix,+ ...(extraBody === null ? {} : { extraBody }),});// Cross-encoder rerank (retrieval-precision-quality-loop, card A). Off@@ -1229,8 +1397,14 @@ export function resolveSearchConfig(opts: {ftsTokenize,});+ // The env variable names an extra-body refusal only when its value is+ // the one in force, by the same raw-presence rule the parser used.+ const extraBodySource =+ opts.overrides?.semantic?.extraBody === undefined && env[EXTRA_BODY_ENV] !== undefined+ ? EXTRA_BODY_ENV+ : EXTRA_BODY_KEY;if (!opts.overrides) {- validateResolvedConfig(base);+ validateResolvedConfig(base, extraBodySource);return base;}const merged = Object.freeze({@@ -1242,6 +1416,6 @@ export function resolveSearchConfig(opts: {? Object.freeze({ ...opts.overrides.scopeRules }): base.scopeRules,});- validateResolvedConfig(merged);+ validateResolvedConfig(merged, extraBodySource);return merged;}diff --git a/src/core/search/indexer.ts b/src/core/search/indexer.tsindex a5e3345e..a60cb3e7 100644--- a/src/core/search/indexer.ts+++ b/src/core/search/indexer.ts@@ -29,7 +29,7 @@ import { sha256Hex } from "../integrity/digest.ts";import { parseAuthoredAtSeconds } from "./authored-at.ts";import { CHUNKER_VERSION, chunkMarkdown } from "./chunker.ts";import { expandTextForCjkFts } from "./cjk-tokenizer.ts";-import { declaredInputWindowTokens, passagePrefixSentByProvider } from "./embeddings/presets.ts";+import { effectiveInputWindowTokens, passagePrefixSentByProvider } from "./embeddings/presets.ts";import {activeEmbeddingModel,activeSpendQuote,@@ -878,7 +878,9 @@ function censusChunkWindow(if (chunksMeasured === 0) return null;const model = activeEmbeddingModel(config, storedModel);- const windowTokens = declaredInputWindowTokens(model);+ // The one resolver the query fit reads too: an operator-declared window+ // enables the census for an uncurated model.+ const windowTokens = effectiveInputWindowTokens(config.semantic, model);if (model === null || windowTokens === null) {return Object.freeze({ verdict: "window-undeclared" as const, model, chunksMeasured });}diff --git a/src/core/search/pipeline/cache-slot.ts b/src/core/search/pipeline/cache-slot.tsindex be55e9a7..752e4687 100644--- a/src/core/search/pipeline/cache-slot.ts+++ b/src/core/search/pipeline/cache-slot.ts@@ -9,6 +9,7 @@import { canonicalSourceSetKey } from "../../scope-key.ts";import { activationStateFingerprint } from "../activation/store.ts";+import { effectiveInputWindowTokens, queryPrefixSentByProvider } from "../embeddings/presets.ts";import { learnedWeightsFingerprint } from "../feedback.ts";import { buildCacheKey, getCachedOutcome, putCachedOutcome } from "../query-cache.ts";import { reinforceFingerprint } from "../reinforce.ts";@@ -108,6 +109,17 @@ function configFingerprint(config: ResolvedSearchConfig): string {tri: r.trigramPrefilterEnabled,triMin: r.trigramPrefilterMinChunks,triSel: r.trigramPrefilterMaxSelectivity,+ // The query embed is fitted to the effective input window with the+ // instruction prefix the provider sends counted in, so either one+ // changes the text embedded (and whether it was cut): a declared or+ // changed window, or another prefix, re-keys the answer. Present only+ // with semantic search on, so every keyword-only key is unchanged.+ ...(config.semantic.enabled+ ? {+ qWin: effectiveInputWindowTokens(config.semantic),+ qPre: queryPrefixSentByProvider(config.semantic.provider, config.semantic.queryPrefix),+ }+ : {}),});}diff --git a/src/core/search/pipeline/semantic-lane.ts b/src/core/search/pipeline/semantic-lane.tsindex 1a107e84..0726affe 100644--- a/src/core/search/pipeline/semantic-lane.ts+++ b/src/core/search/pipeline/semantic-lane.ts@@ -11,6 +11,7 @@ import { RETRIEVAL_DEGRADATION, noteDegradation } from "../retrieval-trail.ts";import type { RetrievalDegradationSink } from "../retrieval-trail.ts";import type { SemanticPolicy } from "../semantic-phase.ts";import type { Store } from "../store.ts";+import type { TransportReach } from "../../graph/transport-reach.ts";import type { ResolvedSearchConfig } from "../types.ts";export interface SemanticLaneInput {@@ -26,6 +27,12 @@ export interface SemanticLaneInput {readonly keywordHitCount: number;/** The composite deadline's cancellation; absent when no deadline runs. */readonly signal?: AbortSignal;+ /**+ * The caller's reach, forwarded to the query-embed gateway. Absent+ * resolves to remote there, so an internal caller that must embed+ * under a positive cost gate passes local explicitly.+ */+ readonly transportReach?: TransportReach;}export interface SemanticLaneOutcome {@@ -53,6 +60,7 @@ export async function runSemanticLane(input: SemanticLaneInput): Promise<SemantipathPrefix,explicit: policy.explicit,...(input.signal !== undefined ? { signal: input.signal } : {}),+ ...(input.transportReach !== undefined ? { transportReach: input.transportReach } : {}),});attempted = semOutcome.attempted;hits = semOutcome.hits;diff --git a/src/core/search/retrieval-trail.ts b/src/core/search/retrieval-trail.tsindex 0ed80dc5..c41ac501 100644--- a/src/core/search/retrieval-trail.ts+++ b/src/core/search/retrieval-trail.ts@@ -93,6 +93,26 @@ export const RETRIEVAL_DEGRADATION = Object.freeze({* site and, until now, stringified into a sentence and thrown away.*/semanticProviderUnavailable: "semantic-provider-unavailable",+ /**+ * The query-embed gateway refused the embed: a caller that is not local,+ * under a positive `embedding_cost_gate_usd`, on a model nobody priced.+ * No `detail`: the model name is configuration, and the warning names+ * it with the price pair that clears the refusal.+ */+ semanticCostUnpriced: "semantic-cost-unpriced",+ /**+ * The query was cut to the effective embedding input window, so the+ * semantic lane searched a prefix of what the caller sent.+ * `detail.windowTokens` is the window it was fitted to. The lane ran.+ */+ semanticQueryTruncated: "semantic-query-truncated",+ /**+ * The instruction prefix alone fills the effective embedding input+ * window, so no part of the query was left to embed and the semantic+ * lane did not run. `detail.windowTokens` is that window. A code of its+ * own, apart from the cut, because this one always means a stopped lane.+ */+ semanticQueryEmptyFit: "semantic-query-empty-fit",/** The provider answered with an empty vector, so there was nothing to search. */semanticEmptyQueryVector: "semantic-empty-query-vector",/** A structured semantic lane was requested while semantic search is off. */@@ -105,8 +125,8 @@ export const RETRIEVAL_DEGRADATION = Object.freeze({semanticEmbeddingAbiDrift: "semantic-embedding-abi-drift",/*** The caller wanted hybrid recall and the semantic lane did not run, so- * the answer is keyword-only. The umbrella over the five codes above -- * they say why, this says what the caller received.+ * the answer is keyword-only. The umbrella over the semantic codes above+ * that stop the lane - they say why, this says what the caller received.*/hybridDegraded: "hybrid-degraded",/**@@ -178,6 +198,9 @@ export const RETRIEVAL_DEGRADATION_CODES: ReadonlyArray<RetrievalDegradationCodeRETRIEVAL_DEGRADATION.semanticEmbeddingsAbsent,RETRIEVAL_DEGRADATION.semanticVecExtensionUnavailable,RETRIEVAL_DEGRADATION.semanticCapabilityBlocked,+ RETRIEVAL_DEGRADATION.semanticCostUnpriced,+ RETRIEVAL_DEGRADATION.semanticQueryTruncated,+ RETRIEVAL_DEGRADATION.semanticQueryEmptyFit,RETRIEVAL_DEGRADATION.semanticProviderUnavailable,RETRIEVAL_DEGRADATION.semanticEmptyQueryVector,RETRIEVAL_DEGRADATION.semanticStructuredLanesSkipped,@@ -286,6 +309,43 @@ export function noteDegradation(sink.push(Object.freeze(detail !== undefined ? { code, detail } : { code }));}+/** The codes that each mean the semantic lane a hybrid caller wanted did not run. */+const SEMANTIC_LANE_STOPS: ReadonlySet<RetrievalDegradationCode> = new Set([+ RETRIEVAL_DEGRADATION.hybridDegraded,+ RETRIEVAL_DEGRADATION.semanticCapabilityBlocked,+ RETRIEVAL_DEGRADATION.semanticCostUnpriced,+ RETRIEVAL_DEGRADATION.semanticQueryEmptyFit,+ RETRIEVAL_DEGRADATION.semanticProviderUnavailable,+ RETRIEVAL_DEGRADATION.semanticEmptyQueryVector,+]);++/**+ * Whether a hybrid caller was served keyword-only for a reason that is not+ * the index or the machine: the one definition every consumer that must+ * not learn from, or save, a keyword-only measurement reads.+ *+ * `hybrid-degraded` is the umbrella - the caller wanted the semantic lane+ * and it did not run - so the deadline counts without a code of its own.+ * The umbrella is only noted when the keyword lane found something, so the+ * codes that always mean the lane stopped count on their own too: a hit+ * that arrived through another lane was still scored without the+ * semantic one. A cut query is not one of them - the lane ran on the cut+ * text - while an empty fit, where the instruction prefix alone fills the+ * window, is.+ * An index with no embeddings or a machine without sqlite-vec is+ * keyword-only by construction: the system it measured is the one that+ * will serve.+ */+export function semanticLaneMissing(degraded: ReadonlyArray<RetrievalDegradationCode>): boolean {+ if (+ degraded.includes(RETRIEVAL_DEGRADATION.semanticEmbeddingsAbsent) ||+ degraded.includes(RETRIEVAL_DEGRADATION.semanticVecExtensionUnavailable)+ ) {+ return false;+ }+ return degraded.some((code) => SEMANTIC_LANE_STOPS.has(code));+}+/*** The one English mapping, exhaustive over the vocabulary with no default* arm - so adding a code fails to compile here rather than silently@@ -304,6 +364,12 @@ export function describeRetrievalDegradation(code: RetrievalDegradationCode): streturn "the sqlite-vec extension is not loaded, so the semantic lane could not run";case RETRIEVAL_DEGRADATION.semanticCapabilityBlocked:return "the configured semantic capability blocks the vector lane, so it did not run";+ case RETRIEVAL_DEGRADATION.semanticCostUnpriced:+ return "the embedding model has no known price and the cost gate is on, so a query embed for a caller that is not local was refused and the semantic lane did not run";+ case RETRIEVAL_DEGRADATION.semanticQueryTruncated:+ return "the query was longer than the embedding input window, so the semantic lane searched a cut prefix of it";+ case RETRIEVAL_DEGRADATION.semanticQueryEmptyFit:+ return "the instruction prefix alone fills the embedding input window, so no part of the query was left to embed and the semantic lane did not run";case RETRIEVAL_DEGRADATION.semanticProviderUnavailable:return "the embedding provider could not answer, so the semantic lane did not run";case RETRIEVAL_DEGRADATION.semanticEmptyQueryVector:diff --git a/src/core/search/search.ts b/src/core/search/search.tsindex 8d116271..b4a9eb1d 100644--- a/src/core/search/search.ts+++ b/src/core/search/search.ts@@ -283,9 +283,16 @@ export async function search(: CACHE_BYPASSED;if (cache.hit !== null) return cache.hit;// A deadline-degraded answer is keyword-only under a key that promises- // the hybrid one: serve it, but never cache it.+ // the hybrid one: serve it, but never cache it. A spend-gated one is+ // the same, and the key carries no gate or price either, so a cached+ // refusal would outlive the operator's price declaration. A query cut+ // to its window is cached: the key carries the effective window and+ // the query prefix, so a declared or changed window re-keys it.const finalize = (outcome: SearchOutcome): SearchOutcome => {- if (cache.slot !== null && deadline?.hasFired() !== true) {+ const configBound = degraded.some(+ (d) => d.code === RETRIEVAL_DEGRADATION.semanticCostUnpriced,+ );+ if (cache.slot !== null && deadline?.hasFired() !== true && !configBound) {persistCachedOutcome(store, cache.slot, outcome);}return outcome;@@ -327,6 +334,7 @@ export async function search(limit,pathPrefix,keywordHitCount: keywordHits.length,+ ...(opts.transportReach !== undefined ? { transportReach: opts.transportReach } : {}),};const semanticLane =deadline === nulldiff --git a/src/core/search/semantic-phase.ts b/src/core/search/semantic-phase.tsindex fdf956af..e47e0527 100644--- a/src/core/search/semantic-phase.ts+++ b/src/core/search/semantic-phase.ts@@ -13,9 +13,16 @@ import {} from "./capability-tier.ts";import { classifyEmbeddingError } from "./embeddings/openai-compat.ts";import { makeProvider } from "./embeddings/provider.ts";+import {+ prepareQueryEmbed,+ queryEmbedCutMessage,+ queryEmbedEmptyFitMessage,+ queryEmbedRefusalMessage,+} from "./embeddings/query-embed.ts";import { RETRIEVAL_DEGRADATION, noteDegradation } from "./retrieval-trail.ts";import { Store } from "./store.ts";import { EMBEDDING_QUOTA_MESSAGE, SearchError } from "./types.ts";+import type { TransportReach } from "../graph/transport-reach.ts";import type { RetrievalDegradationSink } from "./retrieval-trail.ts";import type { ResolvedSearchConfig, SearchOptions } from "./types.ts";@@ -79,6 +86,12 @@ export async function runSemanticPhase(* signal's reason, so an abandoned lane never reaches the store.*/signal?: AbortSignal;+ /**+ * How far the caller reached (`SearchOptions.transportReach`). The+ * query-embed gateway reads it: absent resolves to remote, as+ * everywhere else in the tree.+ */+ transportReach?: TransportReach;},): Promise<SemanticPhaseOutcome> {const warnings: string[] = [];@@ -130,11 +143,42 @@ export async function runSemanticPhase(return { attempted: false, hits: [], warnings, degraded };}+ // The query-embed gateway (honest-query-embed-and-safe-upgrades): the+ // one place that decides whether a query embed is sent at all and with+ // what text. It runs before any provider exists, so a refusal sends+ // nothing. The explicit arm throws, like every other condition above+ // that stops a lane the caller asked for by name; the implicit arm+ // degrades by code and the lane is not attempted.+ const prepared = prepareQueryEmbed(config, query, opts.transportReach);+ if (prepared.kind === "refused") {+ const message = queryEmbedRefusalMessage(prepared);+ if (opts.explicit) throw new SearchError(prepared.code, message);+ warnings.push(message);+ noteDegradation(degraded, RETRIEVAL_DEGRADATION.semanticCostUnpriced);+ return { attempted: false, hits: [], warnings, degraded };+ }+ if (prepared.truncated) {+ const detail = { windowTokens: prepared.windowTokens };+ if (prepared.emptyFit) {+ // The instruction prefix alone fills the window: there is no query+ // left to embed, and embedding the prefix would search for nothing.+ const message = queryEmbedEmptyFitMessage(prepared);+ if (opts.explicit) throw new SearchError("INVALID_INPUT", message);+ warnings.push(message);+ noteDegradation(degraded, RETRIEVAL_DEGRADATION.semanticQueryEmptyFit, detail);+ return { attempted: false, hits: [], warnings, degraded };+ }+ // A cut the server would otherwise make silently (or refuse), made+ // here and disclosed. The lane still runs on the cut query.+ warnings.push(queryEmbedCutMessage(prepared, query));+ noteDegradation(degraded, RETRIEVAL_DEGRADATION.semanticQueryTruncated, detail);+ }+let queryVec: number[];try {const provider = makeProvider(config.semantic);const vectors = await provider.embed(- [query],+ [prepared.text],"query",opts.signal !== undefined ? { signal: opts.signal } : undefined,);diff --git a/src/core/search/tuning.ts b/src/core/search/tuning.tsindex eb23de4a..fdfc8090 100644--- a/src/core/search/tuning.ts+++ b/src/core/search/tuning.ts@@ -14,7 +14,10 @@* grid order break ties), so the choice is auditable;* - the winner persists to `Brain/search/tuning.json` with every* evaluated score and the dataset hash - delete the file (reset)- * and nothing else changes;+ * and nothing else changes. A winner measured while the semantic+ * lane was missing (the spend gate, a blocked capability, a provider+ * outage, the hybrid deadline) is never saved: it scored a+ * keyword-only system, not the configured one;* - `search()` consults the tuned parameters ONLY when self-tuning* is enabled (`search_self_tuning_enabled` /* `OPEN_SECOND_BRAIN_SEARCH_SELF_TUNING`), values re-validated@@ -33,6 +36,15 @@ import { createHash } from "node:crypto";import { runRecallBenchmark } from "./benchmark.ts";import type { RecallBenchmarkDataset } from "./benchmark.ts";+import { BLOCKED_TIER_ERROR_CODE, type BlockedCapabilityTier } from "./capability-tier.ts";+import { COST_GATE_KEY } from "./embedding-spend.ts";+import { EMBEDDING_PRICE_MODEL_KEY, EMBEDDING_PRICE_RATE_KEY } from "./embeddings/pricing.ts";+import { INPUT_WINDOW_TOKENS_KEY } from "./embeddings/presets.ts";+import {+ RETRIEVAL_DEGRADATION,+ semanticLaneMissing,+ type RetrievalDegradationCode,+} from "./retrieval-trail.ts";import {applyTunedParameters,TUNING_POOL_MULTIPLIERS,@@ -41,18 +53,25 @@ import {tuningPath,} from "./tuning-store.ts";import type { TransportReach } from "../graph/transport-reach.ts";+import { SearchError, type SearchErrorCode } from "./types.ts";import type { ResolvedSearchConfig, TunedParameters } from "./types.ts";export interface TuningEvaluation {readonly params: TunedParameters;readonly mrr: number;readonly hitAtK: number;+ /** The benchmark's degradation codes for this cell (empty when none). */+ readonly degraded: ReadonlyArray<RetrievalDegradationCode>;+ /** The blocked capability rung, when {@link degraded} names one. */+ readonly capabilityTier?: BlockedCapabilityTier;}export interface TuneRecallReport {readonly chosen: TunedParameters;readonly evaluated: ReadonlyArray<TuningEvaluation>;readonly datasetHash: string;+ /** Every cell's degradation codes, sorted and de-duplicated. */+ readonly degraded: ReadonlyArray<RetrievalDegradationCode>;}export interface TuneRecallOptions {@@ -89,6 +108,68 @@ export function defaultTuningGrid(): TunedParameters[] {return grid;}+/** Why a sweep's winner was refused: the typed error and the lever that clears it. */+interface SemanticLaneRefusal {+ readonly trail: RetrievalDegradationCode;+ readonly error: (chosen: TuningEvaluation) => SearchErrorCode;+ readonly remedy: (config: ResolvedSearchConfig, chosen: TuningEvaluation) => string;+}++/**+ * The trail codes that name WHY the semantic lane did not run, in the+ * order a refusal names them, each with the typed error the explicit+ * semantic lane throws for the same cause. Whether the lane was missing+ * at all is {@link semanticLaneMissing}'s call, not this list's: a stop+ * no entry names refuses through {@link SEMANTIC_LANE_STOPPED}.+ */+const SEMANTIC_LANE_CAUSES: ReadonlyArray<SemanticLaneRefusal> = Object.freeze<+ SemanticLaneRefusal[]+>([+ {+ trail: RETRIEVAL_DEGRADATION.semanticCostUnpriced,+ error: () => "EMBEDDING_COST_UNPRICED",+ remedy: (config) =>+ `It was refused by ${COST_GATE_KEY}: declare the price of ` ++ `${config.semantic.model ?? "the embedding model"} with ${EMBEDDING_PRICE_MODEL_KEY} and ` ++ `${EMBEDDING_PRICE_RATE_KEY} (0 for a free self-hosted model), or lower ${COST_GATE_KEY}`,+ },+ {+ trail: RETRIEVAL_DEGRADATION.semanticCapabilityBlocked,+ // The rung the benchmark carried picks the code the explicit lane+ // throws for it; a summary without one keeps the pre-tier code.+ error: (chosen) =>+ chosen.capabilityTier !== undefined+ ? BLOCKED_TIER_ERROR_CODE[chosen.capabilityTier]+ : "EMBEDDING_DISABLED",+ remedy: () => "Complete the embedding provider configuration and its credential",+ },+ {+ trail: RETRIEVAL_DEGRADATION.semanticProviderUnavailable,+ error: () => "EMBEDDING_PROVIDER_HTTP",+ remedy: () => "Wait until the embedding provider answers again (o2b search check)",+ },+]);++/**+ * The named generic arm: the composite hybrid deadline cut the lane, the+ * provider answered with an empty vector, the instruction prefix alone+ * filled the input window, or another stop left the hybrid caller+ * keyword-only. The message names the codes the winner carried, and an+ * empty fit adds the window lever, which no provider check clears. A cut+ * where the lane still ran is not a stop, so it names no lever here.+ */+const SEMANTIC_LANE_STOPPED: SemanticLaneRefusal = Object.freeze({+ trail: RETRIEVAL_DEGRADATION.hybridDegraded,+ error: () => "EMBEDDING_PROVIDER_HTTP",+ remedy: (_config: ResolvedSearchConfig, chosen: TuningEvaluation) =>+ "Check why the embedding provider did not answer in time (o2b search check) " ++ "or raise search_hybrid_deadline_ms" ++ (chosen.degraded.includes(RETRIEVAL_DEGRADATION.semanticQueryEmptyFit)+ ? `; the instruction prefix fills the input window: raise ${INPUT_WINDOW_TOKENS_KEY} ` ++ "or shorten the query prefix"+ : ""),+});+/*** Grid-evaluate against the benchmark and persist the winner.* Deterministic for a fixed index state and dataset.@@ -108,7 +189,13 @@ export async function tuneRecall(...(opts.transportReach !== undefined ? { transportReach: opts.transportReach } : {}),expand: params.expansion,});- return Object.freeze({ params, mrr: report.mrr, hitAtK: report.hitAtK });+ return Object.freeze({+ params,+ mrr: report.mrr,+ hitAtK: report.hitAtK,+ degraded: report.degraded,+ ...(report.capabilityTier !== undefined ? { capabilityTier: report.capabilityTier } : {}),+ });}),);@@ -123,6 +210,21 @@ export async function tuneRecall(}}+ // A winner scored while the semantic lane was missing would be saved as+ // the vault's parameters for the hybrid system it never ran.+ if (semanticLaneMissing(chosen.degraded)) {+ const missing =+ SEMANTIC_LANE_CAUSES.find(({ trail }) => chosen.degraded.includes(trail)) ??+ SEMANTIC_LANE_STOPPED;+ throw new SearchError(+ missing.error(chosen),+ `the tuning sweep was measured with the semantic lane missing ` ++ `(${chosen.degraded.join(", ")}), ` ++ `so its winner scores a keyword-only system and was not saved. ` ++ `${missing.remedy(config, chosen)}, then run the sweep again.`,+ );+ }+const datasetHash = createHash("sha256").update(JSON.stringify(dataset)).digest("hex");const path = tuningPath(config.vault);mkdirSync(dirname(path), { recursive: true });@@ -149,5 +251,6 @@ export async function tuneRecall(chosen: chosen.params,evaluated: Object.freeze(evaluated),datasetHash,+ degraded: Object.freeze([...new Set(evaluated.flatMap((e) => e.degraded))].toSorted()),});}diff --git a/src/core/search/types.ts b/src/core/search/types.tsindex c1033e06..5e46e6c9 100644--- a/src/core/search/types.ts+++ b/src/core/search/types.ts@@ -901,10 +901,16 @@ export interface SearchOptions {** Absent resolves to {@link TRANSPORT_REACH.remote}, the narrowest: a* search whose caller nobody established anything about is not a search- * that proved local access. Every internal lane that must see the whole- * corpus - benchmarks, recall feedback, rerank fit - passes- * {@link TRANSPORT_REACH.local} explicitly, and so does the CLI, which- * runs in the operator's own shell.+ * that proved local access. An internal lane that must see the whole+ * corpus passes {@link TRANSPORT_REACH.local} explicitly, and so does+ * the CLI, which runs in the operator's own shell. Recall feedback does+ * not: it re-runs the search under the reach of the caller who sent the+ * feedback.+ *+ * The semantic lane's query embed reads this too: a caller that is not+ * local, under a positive `embedding_cost_gate_usd`, on a model nobody+ * priced, is refused before the embed is sent+ * (`embeddings/query-embed.ts`).** NOT to be confused with {@link SearchOptions.disclosure}, which is* the result-DEPTH mode; this one decides which pages exist for this@@ -1247,6 +1253,15 @@ export interface ResolvedEmbeddingConfig {* is sent alone rather than dropped or split.*/readonly batchTokens?: number;+ /**+ * The operator's declared input window of the configured model, in the+ * model's own tokens (`embedding_input_window_tokens`). Absent when the+ * key is absent, which leaves the curated preset window (or no window at+ * all) in charge; read it through `effectiveInputWindowTokens` in+ * `embeddings/presets.ts`, never directly. No default: a window nobody+ * declared is unknown, and an unknown window cuts nothing.+ */+ readonly inputWindowTokens?: number;/*** Per-batch transient-retry budget (attempts, not extra retries) for* 429 / 5xx / network errors. Default 6, raised from the former hardcoded@@ -1280,6 +1295,14 @@ export interface ResolvedEmbeddingConfig {readonly queryPrefix?: string;/** Active instruction prefix for an indexed passage; see {@link queryPrefix}. */readonly passagePrefix?: string;+ /**+ * Extra request-body fields for an OpenAI-compatible endpoint, from+ * `embedding_extra_body` / `OPEN_SECOND_BRAIN_EMBEDDING_EXTRA_BODY` (a+ * JSON object). Absent when the key is unset. Never carries a reserved+ * owned field, and never part of the embedding identity, so declaring or+ * editing it never triggers a reindex.+ */+ readonly extraBody?: Readonly<Record<string, unknown>>;}/**diff --git a/src/core/validate.ts b/src/core/validate.tsindex 434ad677..dcd6f7f1 100644--- a/src/core/validate.ts+++ b/src/core/validate.ts@@ -179,3 +179,18 @@ export function envOrConfig(): string | null {return resolveWithOrigin(env, config, envKey, configKey).value;}++/**+ * The one comparison form for a reserved name (a request-body field, a+ * tool argument), so a spelling variant is never a second name. NFKC folds+ * compatibility forms (fullwidth letters and separators) onto ASCII;+ * default-ignorable code points (zero-width space, soft hyphen) and+ * whitespace are dropped, then case and the `_` / `-` separators.+ */+export function normalizeReservedName(name: string): string {+ return name+ .normalize("NFKC")+ .replaceAll(/[\p{Default_Ignorable_Code_Point}\s]/gu, "")+ .toLowerCase()+ .replaceAll(/[_-]/g, "");+}diff --git a/src/mcp/brain/recall-tools.ts b/src/mcp/brain/recall-tools.tsindex 9d04300d..6147e491 100644--- a/src/mcp/brain/recall-tools.ts+++ b/src/mcp/brain/recall-tools.ts@@ -144,6 +144,8 @@ async function toolBrainBenchmark(expand: report.expand,hit_at_k: report.hitAtK,mrr: report.mrr,+ // A degraded run measured a smaller system than the configured one.+ ...(report.degraded.length > 0 ? { degraded: report.degraded } : {}),per_query: report.perQuery,};}@@ -206,8 +208,14 @@ async function toolBrainTune(}return {chosen: report.chosen,- evaluated: report.evaluated.map((e) => ({ params: e.params, mrr: e.mrr, hit_at_k: e.hitAtK })),+ evaluated: report.evaluated.map((e) => ({+ params: e.params,+ mrr: e.mrr,+ hit_at_k: e.hitAtK,+ ...(e.degraded.length > 0 ? { degraded: e.degraded } : {}),+ })),dataset_hash: report.datasetHash,+ ...(report.degraded.length > 0 ? { degraded: report.degraded } : {}),};}diff --git a/src/mcp/reach-refusal.ts b/src/mcp/reach-refusal.tsindex c37e6ad9..b095c6e5 100644--- a/src/mcp/reach-refusal.ts+++ b/src/mcp/reach-refusal.ts@@ -22,13 +22,14 @@* the surfaces that would be worth attacking are exactly the ones a* future open schema would leave uncovered.*- * Comparison is over a normalised name (case-folded, separators dropped),- * so `reach`, `Reach`, `transport_reach`, `transport-reach` and+ * Comparison is over a normalised name (compatibility-folded, case-folded,+ * whitespace, invisible code points and separators dropped), so `reach`, `Reach`, `transport_reach`, `transport-reach` and* `transportReach` are one argument rather than five holes. `disclosure`* is deliberately NOT reserved: it is the progressive result-depth mode* on the recall surfaces and has nothing to do with this boundary.*/+import { normalizeReservedName } from "../core/validate.ts";import { INVALID_PARAMS, MCPError } from "./protocol.ts";import type { ToolDefinition } from "./tool-contract.ts";@@ -38,20 +39,15 @@ export const REACH_REFUSAL = "caller-supplied-reach";/*** The argument names this server will not read a reach from, in their* canonical spelling. Every case and separator variant of these normalises- * onto the same key - see {@link normalizeArgumentName}.+ * onto the same key - see {@link normalizeReservedName}.*/export const RESERVED_REACH_ARGUMENTS: ReadonlyArray<string> = Object.freeze(["reach","transport_reach",]);-/** Case-folded, separator-free form, so one name is not five holes. */-function normalizeArgumentName(name: string): string {- return name.normalize("NFC").toLowerCase().replaceAll(/[_-]/g, "");-}-const RESERVED_KEYS: ReadonlySet<string> = new Set(- RESERVED_REACH_ARGUMENTS.map(normalizeArgumentName),+ RESERVED_REACH_ARGUMENTS.map(normalizeReservedName),);/** The structured payload attached to the refusal, for machine callers. */@@ -73,7 +69,7 @@ export interface CallerSuppliedReachData {*/export function findCallerSuppliedReach(args: Record<string, unknown>): ReadonlyArray<string> {return Object.freeze(- Object.keys(args).filter((k) => RESERVED_KEYS.has(normalizeArgumentName(k))),+ Object.keys(args).filter((k) => RESERVED_KEYS.has(normalizeReservedName(k))),);}diff --git a/src/mcp/search-tools.ts b/src/mcp/search-tools.tsindex 82ae4ee4..7b71ccf6 100644--- a/src/mcp/search-tools.ts+++ b/src/mcp/search-tools.ts@@ -1468,6 +1468,9 @@ const RECALL_FEEDBACK_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]>recorded: { type: "boolean" },result_found: { type: "boolean" },learned: { type: "object" },+ // Retrieval degradation codes of the re-run (for example+ // semantic-cost-unpriced); empty when nothing narrowed it.+ degraded: { type: "array", items: { type: "string" } },},required: ["recorded", "result_found", "learned"],};@@ -1505,6 +1508,7 @@ async function toolBrainRecallFeedback(recorded: true,result_found: outcome.resultFound,learned: outcome.learned,+ degraded: outcome.degraded,};}@@ -1594,6 +1598,7 @@ const EVAL_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {source_utilization_at_k: { type: "number" },citation_depth: { type: "number" },source_warnings: { type: "integer" },+ degraded: { type: "array", items: { type: "string" } },per_query: {type: "array",items: {@@ -1603,6 +1608,7 @@ const EVAL_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {hit: { type: "boolean" },rank: { type: "integer" },answer_contained: { type: "boolean" },+ degraded: { type: "array", items: { type: "string" } },},},},@@ -1684,11 +1690,14 @@ async function toolBrainEval(source_utilization_at_k: report.sourceUtilizationAtK,citation_depth: report.citationDepth,source_warnings: report.sourceWarnings,+ // A degraded run measured a smaller system than the configured one.+ ...(report.degraded.length > 0 ? { degraded: report.degraded } : {}),per_query: report.perQuery.map((q) => ({id: q.id,hit: q.hit,...(q.rank !== null ? { rank: q.rank } : {}),...(q.answerContained !== null ? { answer_contained: q.answerContained } : {}),+ ...(q.degraded !== undefined ? { degraded: q.degraded } : {}),})),};}diff --git a/tests/cli/brain-upgrade.test.ts b/tests/cli/brain-upgrade.test.tsindex 932cdadf..82624294 100644--- a/tests/cli/brain-upgrade.test.ts+++ b/tests/cli/brain-upgrade.test.ts@@ -7,11 +7,14 @@* stdout shape, and (for `--apply`) post-state on disk.*/-import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";+import { cmdBrainUpgrade } from "../../src/cli/brain/verbs/upgrade.ts";+import * as upgradeModule from "../../src/core/brain/upgrade.ts";+import type { UpgradePlan } from "../../src/core/brain/upgrade.ts";import { runCli } from "../helpers/run-cli.ts";let tmp: string;@@ -163,4 +166,98 @@ describe("brain upgrade", () => {true,);});++ test("a missing _BRAIN.md renders as an update from absent (text and JSON)", async () => {+ await bootstrap();+ rmSync(join(vault, "Brain", "_BRAIN.md"), { force: true });+ const text = await runCli(["brain", "upgrade", "--vault", vault, "--dry-run"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(text.returncode).toBe(0);+ expect(text.stdout).toContain("Brain/_BRAIN.md: update (absent โ");+ expect(text.stdout).toContain("+++ Brain/_BRAIN.md (release)");++ const json = await runCli(["brain", "upgrade", "--vault", vault, "--dry-run", "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(json.returncode).toBe(0);+ const payload = JSON.parse(json.stdout) as {+ files: Array<{ path: string; status: string; before_size: number; after_size: number }>;+ };+ const manual = payload.files.find((f) => f.path === "Brain/_BRAIN.md")!;+ expect(manual.status).toBe("update");+ expect(manual.before_size).toBe(0);+ expect(manual.after_size).toBeGreaterThan(0);+ });+});++describe("brain upgrade --apply applies the plan it printed", () => {+ let prevConfigEnv: string | undefined;+ beforeEach(() => {+ prevConfigEnv = process.env["OPEN_SECOND_BRAIN_CONFIG"];+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = config;+ });+ afterEach(() => {+ if (prevConfigEnv === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = prevConfigEnv;+ });++ test("--apply --yes hands the shown plan to applyUpgrade, planning once", async () => {+ await bootstrap();+ writeFileSync(join(vault, "Brain", "_BRAIN.md"), "stale\n");+ const realPlan = upgradeModule.planUpgrade;+ const shown: UpgradePlan[] = [];+ const planSpy = spyOn(upgradeModule, "planUpgrade").mockImplementation((v) => {+ const plan = realPlan(v);+ shown.push(plan);+ return plan;+ });+ const applySpy = spyOn(upgradeModule, "applyUpgrade");+ const out = spyOn(process.stdout, "write").mockImplementation(() => true);+ try {+ const code = await cmdBrainUpgrade(["--vault", vault, "--apply", "--yes", "--json"]);+ out.mockRestore();+ expect(code).toBe(0);+ expect(shown).toHaveLength(1);+ expect(applySpy).toHaveBeenCalledTimes(1);+ expect(applySpy.mock.calls[0]![1]?.plan).toBe(shown[0]);+ } finally {+ out.mockRestore();+ planSpy.mockRestore();+ applySpy.mockRestore();+ }+ expect(readFileSync(join(vault, "Brain", "_BRAIN.md"), "utf8")).not.toBe("stale\n");+ });++ test("--apply --json reports a drift refusal as JSON with run_id and drifted", async () => {+ await bootstrap();+ const manual = join(vault, "Brain", "_BRAIN.md");+ writeFileSync(manual, "stale\n");+ const realPlan = upgradeModule.planUpgrade;+ // The hand edit lands between the plan and the apply.+ const planSpy = spyOn(upgradeModule, "planUpgrade").mockImplementation((v) => {+ const plan = realPlan(v);+ writeFileSync(manual, "hand edit\n");+ return plan;+ });+ const written: string[] = [];+ const out = spyOn(process.stdout, "write").mockImplementation((chunk) => {+ written.push(String(chunk));+ return true;+ });+ let code: number;+ try {+ code = await cmdBrainUpgrade(["--vault", vault, "--apply", "--yes", "--json"]);+ } finally {+ out.mockRestore();+ planSpy.mockRestore();+ }+ expect(code).toBe(1);+ const payload = JSON.parse(written.join("")) as Record<string, unknown>;+ expect(payload["ok"]).toBe(false);+ expect(payload["error"]).toContain("Brain/_BRAIN.md");+ expect(payload["run_id"]).toBeNull();+ expect(payload["drifted"]).toEqual(["Brain/_BRAIN.md"]);+ expect(readFileSync(manual, "utf8")).toBe("hand edit\n");+ });});diff --git a/tests/core/brain/belief-semantic.test.ts b/tests/core/brain/belief-semantic.test.tsindex 301dad9d..907c49a6 100644--- a/tests/core/brain/belief-semantic.test.ts+++ b/tests/core/brain/belief-semantic.test.ts@@ -9,7 +9,10 @@* and `Brain/retired/` notes, embeds the query exactly once with the* `query` prefix kind, refuses a blocked tier and a missing sqlite-vec* by name BEFORE any query embed, and discloses the model, the price- * source, the query tokens and the nullable query cost.+ * source, the query tokens and the nullable query cost. The query goes+ * through the shared query-embed gateway: an omitted reach is remote, the+ * text is fitted to the model's input window (a cut adds one warning) and+ * the disclosed query tokens count the instruction prefix.** Deliberately not covered here: the reach filter and the* `BELIEF_VECTORS_MISSING` refusal, which are decided after the pack@@ -26,8 +29,16 @@ import {type StoredBeliefVector,} from "../../../src/core/brain/belief-semantic.ts";import { TRANSPORT_REACH } from "../../../src/core/graph/transport-reach.ts";+import { COST_GATE_KEY, formatEstimatedUsd } from "../../../src/core/search/embedding-spend.ts";+import {+ E5_QUERY_PREFIX,+ INPUT_WINDOW_TOKENS_KEY,+} from "../../../src/core/search/embeddings/presets.ts";import { EMBEDDING_PRICE_SOURCE } from "../../../src/core/search/embeddings/pricing.ts";-import { LOCAL_EMBEDDING_MODEL } from "../../../src/core/search/embeddings/signature.ts";+import {+ estimateTokens,+ LOCAL_EMBEDDING_MODEL,+} from "../../../src/core/search/embeddings/signature.ts";import type { EmbedKind, EmbeddingProvider } from "../../../src/core/search/embeddings/contract.ts";import { indexVault } from "../../../src/core/search/indexer.ts";import { EMBEDDING_DIMENSION_STATE_KEY, Store } from "../../../src/core/search/store.ts";@@ -456,6 +467,24 @@ describe("loadBeliefSemanticRelevance", () => {reach: TRANSPORT_REACH.remote,}).catch((e: unknown) => e);+ expect(refusal).toBeInstanceOf(SearchError);+ expect((refusal as SearchError).code).toBe("EMBEDDING_COST_UNPRICED");+ // The operator's budget is not the remote caller's business.+ expect((refusal as SearchError).message).toContain(`${COST_GATE_KEY} is positive`);+ expect((refusal as SearchError).message).not.toContain(formatEstimatedUsd(1));+ },+ );++ // An omitted reach resolves as everywhere else in the tree: remote.+ test.skipIf(!VEC_LOADABLE)(+ "is refused with EMBEDDING_COST_UNPRICED when the caller names no reach",+ async () => {+ const config = await seed({ costGateUsd: 1 });++ const refusal = await loadBeliefSemanticRelevance(config, QUERY, {+ provider: throwingProvider,+ }).catch((e: unknown) => e);+expect(refusal).toBeInstanceOf(SearchError);expect((refusal as SearchError).code).toBe("EMBEDDING_COST_UNPRICED");},@@ -495,6 +524,74 @@ describe("loadBeliefSemanticRelevance", () => {);});+ describe("the query is fitted to the model's input window", () => {+ const E5_MODEL = "intfloat/multilingual-e5-small";++ async function seed(semantic: Partial<ResolvedEmbeddingConfig>): Promise<ResolvedSearchConfig> {+ writeBelief("Brain/preferences/pref-a.md", "pref-a", "Keep answers short");+ const config = vecConfig({ model: E5_MODEL, queryPrefix: E5_QUERY_PREFIX, ...semantic });+ await indexVault(config);+ await plant(config, {+ "Brain/preferences/pref-a.md": { vector: [1, 0, 0, 0], model: E5_MODEL },+ });+ return config;+ }++ test.skipIf(!VEC_LOADABLE)(+ "discloses the query tokens of the text sent, instruction prefix included",+ async () => {+ const config = await seed({});+ const { provider, calls } = countingProvider(unit([1, 0, 0, 0]));++ const loaded = await loadBeliefSemanticRelevance(config, QUERY, { provider });++ // The provider adds the prefix itself, so the query goes in bare.+ expect(calls).toEqual([{ texts: [QUERY], kind: "query" }]);+ expect(loaded.report.queryTokens).toBe(estimateTokens([E5_QUERY_PREFIX + QUERY]));+ expect(loaded.report.queryTokens).toBeGreaterThan(estimateTokens([QUERY]));+ expect(loaded.warnings).toEqual([]);+ },+ );++ test.skipIf(!VEC_LOADABLE)(+ "embeds an over-window query cut, with one warning naming the window",+ async () => {+ const config = await seed({ inputWindowTokens: 8 });+ const { provider, calls } = countingProvider(unit([1, 0, 0, 0]));+ const long = `${QUERY} ${"and keep every answer brief ".repeat(20)}`;++ const loaded = await loadBeliefSemanticRelevance(config, long, { provider });++ expect(calls).toHaveLength(1);+ const sent = calls[0]!.texts[0]!;+ expect(sent.length).toBeGreaterThan(0);+ expect(sent.length).toBeLessThan(long.length);+ expect(long.startsWith(sent)).toBe(true);+ expect(loaded.report.queryTokens).toBe(estimateTokens([E5_QUERY_PREFIX + sent]));+ expect(loaded.warnings).toHaveLength(1);+ expect(loaded.warnings[0]).toContain("8-token");+ expect(loaded.warnings[0]).toContain(INPUT_WINDOW_TOKENS_KEY);+ expect(loaded.scored).toBe(1);+ },+ );++ test.skipIf(!VEC_LOADABLE)(+ "refuses with INVALID_INPUT before any embed when the prefix alone fills the window",+ async () => {+ const config = await seed({ inputWindowTokens: 1 });++ const refusal = await loadBeliefSemanticRelevance(config, QUERY, {+ provider: throwingProvider,+ }).catch((e: unknown) => e);++ expect(refusal).toBeInstanceOf(SearchError);+ expect((refusal as SearchError).code).toBe("INVALID_INPUT");+ expect((refusal as SearchError).message).toContain("1-token");+ expect((refusal as SearchError).message).toContain(INPUT_WINDOW_TOKENS_KEY);+ },+ );+ });+test.skipIf(!VEC_LOADABLE)("a contradicted embedding identity reaches the warnings", async () => {writeBelief("Brain/preferences/pref-a.md", "pref-a", "Keep answers short");const config = vecConfig();diff --git a/tests/core/brain/gaps/gap-recall-spend-gate.test.ts b/tests/core/brain/gaps/gap-recall-spend-gate.test.tsnew file mode 100644index 00000000..e994af0c--- /dev/null+++ b/tests/core/brain/gaps/gap-recall-spend-gate.test.ts@@ -0,0 +1,170 @@+/**+ * The gap-promote hook's retriever carries the search trail's codes+ * (honest-query-embed-and-safe-upgrades, task 7).+ *+ * `gapScopedRecallRetriever` resolves to remote reach like every hook,+ * so under a positive cost gate with an unpriced model its semantic lane+ * is refused. The refusal is now named on its result instead of dropped,+ * and `autoCloseRecalledGaps` gathers the codes of every recall it ran so+ * the hook can put them on its audit line.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ autoCloseRecalledGaps,+ GAP_SOURCE_TELEMETRY,+ GAP_TASK_KIND,+ GAP_TASK_STATUS_OPEN,+ type GapRecallRetriever,+} from "../../../../src/core/brain/gaps/gap-loop.ts";+import { gapScopedRecallRetriever } from "../../../../src/core/brain/gaps/gap-recall.ts";+import { brainGapTasksDir } from "../../../../src/core/brain/paths.ts";+import type { RecallResultSet } from "../../../../src/core/brain/recall-inject.ts";+import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";+import { indexVault, resolveSearchConfig } from "../../../../src/core/search/index.ts";+import {+ RETRIEVAL_DEGRADATION,+ type RetrievalDegradationCode,+} from "../../../../src/core/search/retrieval-trail.ts";+import { writeFrontmatterAtomic } from "../../../../src/core/vault.ts";+import { FAKE_PROVIDER_KEY } from "../../../helpers/fake-credentials.ts";+import { startFakeHttp, type FakeHttp } from "../../../helpers/fake-http.ts";+import { sqliteVecLoadable } from "../../../helpers/sqlite-vec.ts";++let tmp: string;+let vault: string;+let configPath: string;+let server: FakeHttp;++beforeEach(async () => {+ server = await startFakeHttp();+ tmp = mkdtempSync(join(tmpdir(), "o2b-gap-gate-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Notes"), { recursive: true });+ writeFileSync(+ join(vault, "Notes", "ledger.md"),+ "# Ledger\n\nthe quarterly ledger reconciliation runbook\n",+ );+ configPath = join(tmp, "config.yaml");+ const lines = (gate: number) =>+ [+ `vault: ${vault}`,+ "search_semantic_enabled: true",+ "embedding_provider: openai-compat",+ `embedding_base_url: ${server.url}`,+ "embedding_model: fake-model",+ `embedding_api_key: ${FAKE_PROVIDER_KEY}`,+ "embedding_dimension: 4",+ `embedding_cost_gate_usd: ${gate}`,+ "",+ ].join("\n");+ atomicWriteFileSync(configPath, lines(0));+ if (sqliteVecLoadable()) {+ await indexVault(resolveSearchConfig({ vault, configPath }), { embeddings: true });+ }+ atomicWriteFileSync(configPath, lines(1));+});++afterEach(async () => {+ await server.close();+ rmSync(tmp, { recursive: true, force: true });+});++test.skipIf(!sqliteVecLoadable())(+ "a gated gap recall sends no embed and names the refusal on its result",+ async () => {+ const before = server.callCount();+ const set = await gapScopedRecallRetriever(configPath, vault)("quarterly ledger", () => true);+ expect(server.callCount()).toBe(before);+ expect(set.candidates.map((c) => c.path.replaceAll("\\", "/"))).toContain("Notes/ledger.md");+ expect(set.degraded).toContain(RETRIEVAL_DEGRADATION.semanticCostUnpriced);+ expect(set.degraded).toContain(RETRIEVAL_DEGRADATION.hybridDegraded);+ },+);++// ----- the codes reach the auto-close result, and from there the audit line --++const NOW = new Date("2026-10-06T12:00:00.000Z");++/** Write one open gap-task note directly, the way a minted one reads. */+function writeOpenTask(key: string, topic: string): void {+ writeFrontmatterAtomic(+ join(brainGapTasksDir(vault), `${key}.md`),+ {+ kind: GAP_TASK_KIND,+ gap_key: key,+ gap_topic: topic,+ gap_source: GAP_SOURCE_TELEMETRY,+ status: GAP_TASK_STATUS_OPEN,+ occurrences: "3",+ created_at: "2026-01-01T00:00:00.000Z",+ },+ `Recurring recall gap for ${topic}.`,+ { vaultForRelativePath: vault, overwrite: true },+ );+}++/** A retriever that admits nothing and reports `codes` as its narrowing. */+function degradedRetriever(codes: ReadonlyArray<RetrievalDegradationCode>): GapRecallRetriever {+ return async () =>+ ({+ candidates: [],+ total: 0,+ idfWeightedCoverage: null,+ ...(codes.length > 0 ? { degraded: codes } : {}),+ }) satisfies RecallResultSet;+}++test.skipIf(!sqliteVecLoadable())(+ "a gated gap recall carries its refusal onto the auto-close result",+ async () => {+ writeOpenTask("gap-ledger", "quarterly ledger");+ const before = server.callCount();+ const result = await autoCloseRecalledGaps(vault, gapScopedRecallRetriever(configPath, vault), {+ now: NOW,+ });+ expect(server.callCount()).toBe(before);+ expect(result.retrievalDegraded).toContain(RETRIEVAL_DEGRADATION.semanticCostUnpriced);+ expect(result.closed.length + result.kept.length).toBe(1);+ },+);++test("the auto-close result names each code once, in first-seen order", async () => {+ writeOpenTask("gap-one", "first topic");+ const result = await autoCloseRecalledGaps(+ vault,+ degradedRetriever([+ RETRIEVAL_DEGRADATION.hybridDegraded,+ RETRIEVAL_DEGRADATION.semanticCostUnpriced,+ RETRIEVAL_DEGRADATION.hybridDegraded,+ ]),+ { now: NOW },+ );+ expect(result.retrievalDegraded).toEqual([+ RETRIEVAL_DEGRADATION.hybridDegraded,+ RETRIEVAL_DEGRADATION.semanticCostUnpriced,+ ]);+});++test("a code every task's recall reports is named once for the run", async () => {+ writeOpenTask("gap-one", "first topic");+ writeOpenTask("gap-two", "second topic");+ const result = await autoCloseRecalledGaps(+ vault,+ degradedRetriever([RETRIEVAL_DEGRADATION.semanticCostUnpriced]),+ { now: NOW },+ );+ expect(result.kept).toHaveLength(2);+ expect(result.retrievalDegraded).toEqual([RETRIEVAL_DEGRADATION.semanticCostUnpriced]);+});++test("a recall that narrowed nothing leaves the codes off the result", async () => {+ writeOpenTask("gap-one", "first topic");+ const result = await autoCloseRecalledGaps(vault, degradedRetriever([]), { now: NOW });+ expect(result.kept).toHaveLength(1);+ expect("retrievalDegraded" in result).toBe(false);+});diff --git a/tests/core/brain/recall-inject-spend-gate.test.ts b/tests/core/brain/recall-inject-spend-gate.test.tsnew file mode 100644index 00000000..5cb3185c--- /dev/null+++ b/tests/core/brain/recall-inject-spend-gate.test.ts@@ -0,0 +1,206 @@+/**+ * Hook refusals become visible (honest-query-embed-and-safe-upgrades,+ * task 7).+ *+ * The recall-inject hook resolves to remote reach (it passes none), so+ * under a positive `embedding_cost_gate_usd` with an unpriced model its+ * semantic lane is refused by the query-embed gateway. Before this, the+ * default retriever mapped only `outcome.results` and dropped the search+ * trail, so that refusal - and every other semantic degradation at the+ * hook - was silent. The codes now ride the retrieval result, the+ * decision and the local audit line. The synced telemetry record does+ * not change.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ decideRecallInject,+ defaultRecallRetriever,+ recallInjectAuditDetails,+ recallInjectTelemetryMetadata,+ type RecallCandidate,+ type RecallRetriever,+} from "../../../src/core/brain/recall-inject.ts";+import type { RecallSliceSpec } from "../../../src/core/brain/types.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";+import { indexVault, resolveSearchConfig } from "../../../src/core/search/index.ts";+import {+ RETRIEVAL_DEGRADATION,+ type RetrievalDegradationCode,+} from "../../../src/core/search/retrieval-trail.ts";+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";+import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";+import { sqliteVecLoadable } from "../../helpers/sqlite-vec.ts";++const UNPRICED = RETRIEVAL_DEGRADATION.semanticCostUnpriced;+const HYBRID = RETRIEVAL_DEGRADATION.hybridDegraded;++function candidate(path: string): RecallCandidate {+ return {+ path,+ title: path,+ score: 0.9,+ searchType: "keyword",+ startLine: 1,+ endLine: 2,+ };+}++function retrieverWith(degraded?: ReadonlyArray<RetrievalDegradationCode>): RecallRetriever {+ return async () => ({+ candidates: [candidate("Notes/a.md")],+ total: 1,+ idfWeightedCoverage: 1,+ ...(degraded !== undefined ? { degraded } : {}),+ });+}++describe("the decision carries the retrieval's degradation codes", () => {+ test("an inject decision carries them onto the local audit line only", async () => {+ const decision = await decideRecallInject("ledger", retrieverWith([UNPRICED, HYBRID]));+ expect(decision.kind).toBe("inject");+ const audit = recallInjectAuditDetails(decision);+ expect(audit["retrieval_degraded"]).toEqual([UNPRICED, HYBRID]);++ const telemetry = recallInjectTelemetryMetadata(decision);+ expect("retrieval_degraded" in telemetry).toBe(false);+ expect(JSON.stringify(telemetry)).not.toContain(UNPRICED);+ });++ test("an abstain decision carries them too", async () => {+ const empty: RecallRetriever = async () => ({+ candidates: [],+ total: 0,+ idfWeightedCoverage: 0,+ degraded: [UNPRICED, HYBRID],+ });+ const decision = await decideRecallInject("ledger", empty);+ expect(decision.kind).toBe("abstain");+ expect(recallInjectAuditDetails(decision)["retrieval_degraded"]).toEqual([UNPRICED, HYBRID]);+ });++ test("a retrieval that reports nothing leaves the audit line byte-identical", async () => {+ for (const degraded of [undefined, []]) {+ const decision = await decideRecallInject("ledger", retrieverWith(degraded));+ expect(recallInjectAuditDetails(decision)).toEqual(recallInjectTelemetryMetadata(decision));+ }+ });++ test("the slice path carries the union of its slices' codes, once each", async () => {+ const spec = (name: string): RecallSliceSpec => ({+ name,+ heading: name,+ pathPrefix: null,+ types: [],+ limit: null,+ maxChars: null,+ });+ const perSlice: Record<string, ReadonlyArray<RetrievalDegradationCode>> = {+ first: [UNPRICED, HYBRID],+ second: [HYBRID, RETRIEVAL_DEGRADATION.rankCapTruncatedPool],+ };+ const decision = await decideRecallInject("ledger", retrieverWith(), {+ slices: [spec("first"), spec("second")],+ sliceRetriever: (s) => async () => ({+ candidates: [candidate(`${s.name}/a.md`)],+ total: 1,+ idfWeightedCoverage: 1,+ degraded: perSlice[s.name]!,+ }),+ });+ expect(recallInjectAuditDetails(decision)["retrieval_degraded"]).toEqual([+ UNPRICED,+ HYBRID,+ RETRIEVAL_DEGRADATION.rankCapTruncatedPool,+ ]);+ });++ test("an error decision keeps the codes of a slice that answered first", async () => {+ const spec = (name: string): RecallSliceSpec => ({+ name,+ heading: name,+ pathPrefix: null,+ types: [],+ limit: null,+ maxChars: null,+ });+ const decision = await decideRecallInject("ledger", retrieverWith(), {+ slices: [spec("gated"), spec("broken")],+ sliceRetriever: (s) =>+ s.name === "gated"+ ? retrieverWith([UNPRICED])+ : async () => {+ await new Promise((resolve) => setTimeout(resolve, 5));+ throw new Error("slice store unreadable");+ },+ });+ expect(decision.kind).toBe("error");+ expect(recallInjectAuditDetails(decision)["retrieval_degraded"]).toEqual([UNPRICED]);+ expect(JSON.stringify(recallInjectTelemetryMetadata(decision))).not.toContain(UNPRICED);+ });+});++describe("the default retriever under a positive gate and an unpriced model", () => {+ let tmp: string;+ let vault: string;+ let configPath: string;+ let server: FakeHttp;++ beforeEach(async () => {+ server = await startFakeHttp();+ tmp = mkdtempSync(join(tmpdir(), "o2b-recall-gate-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Notes"), { recursive: true });+ writeFileSync(+ join(vault, "Notes", "ledger.md"),+ "# Ledger\n\nthe quarterly ledger reconciliation runbook\n",+ );+ configPath = join(tmp, "config.yaml");+ const lines = (gate: number) =>+ [+ `vault: ${vault}`,+ "search_semantic_enabled: true",+ "embedding_provider: openai-compat",+ `embedding_base_url: ${server.url}`,+ "embedding_model: fake-model",+ `embedding_api_key: ${FAKE_PROVIDER_KEY}`,+ "embedding_dimension: 4",+ `embedding_cost_gate_usd: ${gate}`,+ "",+ ].join("\n");+ atomicWriteFileSync(configPath, lines(0));+ if (sqliteVecLoadable()) {+ await indexVault(resolveSearchConfig({ vault, configPath }), { embeddings: true });+ }+ atomicWriteFileSync(configPath, lines(1));+ });++ afterEach(async () => {+ await server.close();+ rmSync(tmp, { recursive: true, force: true });+ });++ test.skipIf(!sqliteVecLoadable())(+ "sends no embed, returns keyword candidates and names the refusal",+ async () => {+ const before = server.callCount();+ const set = await defaultRecallRetriever(configPath, vault)("quarterly ledger");+ expect(server.callCount()).toBe(before);+ expect(set.candidates.map((c) => c.path.replaceAll("\\", "/"))).toContain("Notes/ledger.md");+ expect(set.degraded).toContain(UNPRICED);+ expect(set.degraded).toContain(HYBRID);++ const decision = await decideRecallInject(+ "quarterly ledger",+ defaultRecallRetriever(configPath, vault),+ { confidenceFloor: 0 },+ );+ expect(recallInjectAuditDetails(decision)["retrieval_degraded"]).toContain(UNPRICED);+ expect(server.callCount()).toBe(before);+ },+ );+});diff --git a/tests/core/brain/upgrade-drift.test.ts b/tests/core/brain/upgrade-drift.test.tsnew file mode 100644index 00000000..59fd4e98--- /dev/null+++ b/tests/core/brain/upgrade-drift.test.ts@@ -0,0 +1,279 @@+/**+ * Compare-before-write upgrades: `applyUpgrade` writes the plan it was+ * handed, and a managed file that changed on disk after that plan was read+ * is refused by name instead of being overwritten.+ *+ * Two windows are pinned. An edit made after the plan and before the apply+ * is refused before any snapshot is taken. An edit that lands while the+ * snapshot runs (injected through a spy on `createSnapshot`) is refused at+ * its own row: with nothing written yet the message says so and points at a+ * fresh dry run; with rows already rewritten it names them and points at+ * the same dry run. No rollback is offered: the snapshot manifest predates+ * the apply, so a plain rollback refuses on the rewritten rows and a forced+ * one would destroy the edit.+ */++import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { brainConfigPath, brainManualPath } from "../../../src/core/brain/paths.ts";+import * as snapshotModule from "../../../src/core/brain/snapshot.ts";+import { listSnapshots } from "../../../src/core/brain/snapshot.ts";+import {+ BrainUpgradeError,+ applyUpgrade,+ planUpgrade,+ type UpgradePlan,+} from "../../../src/core/brain/upgrade.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";++let vault: string;+let configHome: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-upgrade-drift-vault-"));+ configHome = mkdtempSync(join(tmpdir(), "o2b-upgrade-drift-cfg-"));+ const configPath = join(configHome, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);+ bootstrapBrain(vault, { configPath });+});+afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+});++function row(plan: UpgradePlan, path: string) {+ const found = plan.files.find((f) => f.path === path);+ if (found === undefined) throw new Error(`no plan row for ${path}`);+ return found;+}++function upgradeError(fn: () => unknown): BrainUpgradeError {+ try {+ fn();+ } catch (err) {+ expect(err).toBeInstanceOf(BrainUpgradeError);+ return err as BrainUpgradeError;+ }+ throw new Error("expected a BrainUpgradeError");+}++function snapshotCount(): number {+ return listSnapshots(vault).snapshots.length;+}++/**+ * A plan with both managed files pending: a stale manual, and a config with+ * its trailing `snapshots:` block cut. The cut pins the default layout, so+ * it is asserted to have happened before the plan is trusted.+ */+function twoRowPlan(): { plan: UpgradePlan; without: string } {+ writeFileSync(brainManualPath(vault), "stale\n");+ const yaml = readFileSync(brainConfigPath(vault), "utf8");+ const without = yaml.replace(/\nsnapshots:[\s\S]*$/, "\n");+ expect(without).not.toBe(yaml);+ writeFileSync(brainConfigPath(vault), without);+ const plan = planUpgrade(vault);+ expect(plan.pending).toBe(2);+ return { plan, without };+}++/** Run `applyUpgrade` with `edit` injected right after the snapshot is taken. */+function applyWithEditDuringSnapshot(plan: UpgradePlan, edit: () => void): BrainUpgradeError {+ const realCreate = snapshotModule.createSnapshot;+ const spy = spyOn(snapshotModule, "createSnapshot").mockImplementationOnce((v, id, opts) => {+ const snap = realCreate(v, id, opts);+ edit();+ return snap;+ });+ try {+ const err = upgradeError(() => applyUpgrade(vault, { plan, agent: "test-agent" }));+ expect(spy).toHaveBeenCalledTimes(1);+ return err;+ } finally {+ spy.mockRestore();+ }+}++describe("plan rows tell an absent file from an empty one", () => {+ test("a missing _brain.yaml plans before: null", () => {+ rmSync(brainConfigPath(vault), { force: true });+ expect(row(planUpgrade(vault), "Brain/_brain.yaml").before).toBeNull();+ });++ test("an empty _brain.yaml is still refused as malformed, never planned as absent", () => {+ // The strict parser needs `schema_version`, so an empty config is an+ // `error` row (fix by hand), not an update from `null`.+ writeFileSync(brainConfigPath(vault), "");+ const yaml = row(planUpgrade(vault), "Brain/_brain.yaml");+ expect(yaml.status).toBe("error");+ expect(yaml.before).not.toBeNull();+ });++ test("an empty _BRAIN.md plans before: an empty string", () => {+ writeFileSync(brainManualPath(vault), "");+ const manual = row(planUpgrade(vault), "Brain/_BRAIN.md");+ expect(manual.status).toBe("update");+ expect(manual.before).toBe("");+ });++ test("a missing _BRAIN.md plans before: null", () => {+ rmSync(brainManualPath(vault), { force: true });+ const manual = row(planUpgrade(vault), "Brain/_BRAIN.md");+ expect(manual.status).toBe("update");+ expect(manual.before).toBeNull();+ });+});++describe("applyUpgrade applies the plan it is handed", () => {+ test("the given plan's bytes are written, not a re-plan", () => {+ writeFileSync(brainManualPath(vault), "stale\n");+ const plan = planUpgrade(vault);+ const shown: UpgradePlan = Object.freeze({+ ...plan,+ files: plan.files.map((f) =>+ f.path === "Brain/_BRAIN.md" ? Object.freeze({ ...f, after: "the shown body\n" }) : f,+ ),+ });+ const res = applyUpgrade(vault, { plan: shown, agent: "test-agent" });+ expect(res.files_updated).toEqual(["Brain/_BRAIN.md"]);+ expect(readFileSync(brainManualPath(vault), "utf8")).toBe("the shown body\n");+ });++ test("a clean apply of a given plan snapshots, logs and is idempotent", () => {+ writeFileSync(brainManualPath(vault), "stale\n");+ const before = snapshotCount();+ const res = applyUpgrade(vault, {+ plan: planUpgrade(vault),+ agent: "test-agent",+ now: new Date("2026-10-06T10:00:00Z"),+ });+ expect(res.run_id.startsWith("upgrade-")).toBe(true);+ expect(snapshotCount()).toBe(before + 1);+ const log = readFileSync(join(vault, "Brain", "log", "2026-10-06.md"), "utf8");+ expect(log).toContain(res.run_id);+ expect(planUpgrade(vault).pending).toBe(0);+ expect(applyUpgrade(vault, { plan: planUpgrade(vault) }).files_updated).toEqual([]);+ });+});++describe("a managed file holding invalid UTF-8", () => {+ const stale = Buffer.from([...Buffer.from("stale "), 0xff, 0x0a]);++ test("upgrades when nobody touched it since the plan", () => {+ writeFileSync(brainManualPath(vault), stale);+ const plan = planUpgrade(vault);++ const res = applyUpgrade(vault, { plan, agent: "test-agent" });++ expect(res.files_updated).toEqual(["Brain/_BRAIN.md"]);+ expect(planUpgrade(vault).pending).toBe(0);+ });++ test("is drift when its text changed since the plan", () => {+ writeFileSync(brainManualPath(vault), stale);+ const plan = planUpgrade(vault);+ const edited = Buffer.from([...Buffer.from("edited "), 0xff, 0x0a]);+ writeFileSync(brainManualPath(vault), edited);++ const err = upgradeError(() => applyUpgrade(vault, { plan }));++ expect(err.drifted).toEqual(["Brain/_BRAIN.md"]);+ expect(readFileSync(brainManualPath(vault))).toEqual(edited);+ });+});++describe("drift found before the snapshot", () => {+ test("a hand edit after the plan refuses with drifted, no snapshot, the edit survives", () => {+ writeFileSync(brainManualPath(vault), "stale\n");+ const plan = planUpgrade(vault);+ writeFileSync(brainManualPath(vault), "hand edit after the plan\n");+ const before = snapshotCount();++ const err = upgradeError(() => applyUpgrade(vault, { plan, agent: "test-agent" }));++ expect(err.runId).toBeNull();+ expect(err.drifted).toEqual(["Brain/_BRAIN.md"]);+ expect(err.message).toContain("Brain/_BRAIN.md");+ expect(err.message).toContain("o2b brain upgrade");+ expect(snapshotCount()).toBe(before);+ expect(readFileSync(brainManualPath(vault), "utf8")).toBe("hand edit after the plan\n");+ });++ test("a file planned as absent that appeared since is drift", () => {+ rmSync(brainManualPath(vault), { force: true });+ const plan = planUpgrade(vault);+ writeFileSync(brainManualPath(vault), "");++ const err = upgradeError(() => applyUpgrade(vault, { plan }));++ expect(err.drifted).toEqual(["Brain/_BRAIN.md"]);+ expect(readFileSync(brainManualPath(vault), "utf8")).toBe("");+ });++ test("a file planned as present that vanished since is drift", () => {+ writeFileSync(brainManualPath(vault), "stale\n");+ const plan = planUpgrade(vault);+ rmSync(brainManualPath(vault), { force: true });++ const err = upgradeError(() => applyUpgrade(vault, { plan }));++ expect(err.drifted).toEqual(["Brain/_BRAIN.md"]);+ expect(existsSync(brainManualPath(vault))).toBe(false);+ });++ test("every drifted path is named, and no row is written", () => {+ const { plan, without } = twoRowPlan();+ writeFileSync(brainManualPath(vault), "edited manual\n");+ writeFileSync(brainConfigPath(vault), `${without}# a comment\n`);++ const err = upgradeError(() => applyUpgrade(vault, { plan }));++ expect(err.drifted.toSorted()).toEqual(["Brain/_BRAIN.md", "Brain/_brain.yaml"]);+ expect(readFileSync(brainConfigPath(vault), "utf8")).toBe(`${without}# a comment\n`);+ });+});++describe("drift found at the write", () => {+ test("drift at the first row: nothing was written, re-plan, no rollback offered", () => {+ writeFileSync(brainManualPath(vault), "stale\n");+ const plan = planUpgrade(vault);+ const err = applyWithEditDuringSnapshot(plan, () =>+ writeFileSync(brainManualPath(vault), "hand edit during the snapshot\n"),+ );++ expect(err.runId).not.toBeNull();+ expect(err.runId!.startsWith("upgrade-")).toBe(true);+ expect(err.drifted).toEqual(["Brain/_BRAIN.md"]);+ expect(err.message).toContain("Brain/_BRAIN.md");+ expect(err.message).toContain("Nothing was written");+ expect(err.message).toContain("o2b brain upgrade --dry-run");+ expect(err.message).not.toContain("rollback");+ expect(readFileSync(brainManualPath(vault), "utf8")).toBe("hand edit during the snapshot\n");+ });++ test("drift at a later row: names the rewritten rows, re-plans against the edit", () => {+ const { plan } = twoRowPlan();+ const rows = plan.files.filter((f) => f.status === "update");+ const [first, second] = [rows[0]!, rows[1]!];+ const secondAbs = join(vault, second.path);+ const edit = "# hand edit during the snapshot\n";+ const err = applyWithEditDuringSnapshot(plan, () => writeFileSync(secondAbs, edit));++ expect(readFileSync(join(vault, first.path), "utf8")).toBe(first.after);+ expect(readFileSync(secondAbs, "utf8")).toBe(edit);+ expect(err.drifted).toEqual([second.path]);+ expect(err.message).toContain(second.path);+ expect(err.message).toContain(`1 file(s) already rewritten: ${first.path}`);+ expect(err.message).toContain("o2b brain upgrade --dry-run");+ expect(err.message).not.toContain("rollback");+ // The offered dry run plans the rest from the partial state: the+ // rewritten row is settled and the drifted row is read with the edit.+ const replan = planUpgrade(vault);+ expect(row(replan, first.path).status).toBe("noop");+ expect(row(replan, second.path).before).toBe(edit);+ });+});diff --git a/tests/core/brain/upgrade.test.ts b/tests/core/brain/upgrade.test.tsindex d81990c6..b7cfff7c 100644--- a/tests/core/brain/upgrade.test.ts+++ b/tests/core/brain/upgrade.test.ts@@ -179,7 +179,7 @@ describe("planUpgrade", () => {expect(yamlPlan.error.length).toBeGreaterThan(0);});- test("missing _brain.yaml โ status: update with empty before (recoverable)", () => {+ test("missing _brain.yaml โ status: update from absent before (recoverable)", () => {// ENOENT path: a user (or a bad rsync) deleted _brain.yaml from// an otherwise-bootstrapped vault. Upgrade must restore it from// the canonical default rather than refusing every managed-file@@ -189,7 +189,7 @@ describe("planUpgrade", () => {expect(plan.errors).toBe(0);const yamlPlan = plan.files.find((f) => f.path === "Brain/_brain.yaml")!;expect(yamlPlan.status).toBe("update");- expect(yamlPlan.before).toBe("");+ expect(yamlPlan.before).toBeNull();expect(yamlPlan.after).toContain("schema_version: 1");});diff --git a/tests/core/fs-atomic.test.ts b/tests/core/fs-atomic.test.tsindex dc3550e3..d175c6b5 100644--- a/tests/core/fs-atomic.test.ts+++ b/tests/core/fs-atomic.test.ts@@ -1,4 +1,5 @@-import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";+import * as fs from "node:fs";import {existsSync,mkdtempSync,@@ -13,10 +14,13 @@ import { join } from "node:path";import {FileAlreadyExistsError,+ FileDriftError,atomicCreateFileSyncExclusive,atomicWriteFileSync,atomicWriteText,+ fileMatchesExpected,isFileAlreadyExists,+ isFileDrift,} from "../../src/core/fs-atomic.ts";import { writeFrontmatterAtomic } from "../../src/core/vault.ts";@@ -272,3 +276,164 @@ describe("skipIfUnchanged short-circuit", () => {expect(atomicWriteText(target, "world", { skipIfUnchanged: true })).toBe(true);});});++describe("expectBefore compare-before-write", () => {+ function tempFiles(): string[] {+ return readdirSync(tmp).filter((n) => n.startsWith(".") && n.endsWith(".tmp"));+ }++ function driftOf(fn: () => unknown): FileDriftError {+ try {+ fn();+ } catch (err) {+ expect(isFileDrift(err)).toBe(true);+ return err as FileDriftError;+ }+ throw new Error("expected a FileDriftError");+ }++ test("matching bytes write", () => {+ const target = join(tmp, "x.md");+ writeFileSync(target, "old\n");+ expect(atomicWriteFileSync(target, "new\n", { expectBefore: "old\n" })).toBe(true);+ expect(readFileSync(target, "utf8")).toBe("new\n");+ });++ test("different bytes throw FileDriftError naming the path and leave the target untouched", () => {+ const target = join(tmp, "x.md");+ writeFileSync(target, "hand edit\n");+ const err = driftOf(() => atomicWriteFileSync(target, "new\n", { expectBefore: "old\n" }));+ expect(err).toBeInstanceOf(FileDriftError);+ expect(err.path).toBe(target);+ expect(err.message).toContain(target);+ expect(readFileSync(target, "utf8")).toBe("hand edit\n");+ expect(tempFiles()).toEqual([]);+ });++ test("null with an absent target writes", () => {+ const target = join(tmp, "fresh.md");+ expect(atomicWriteFileSync(target, "body\n", { expectBefore: null })).toBe(true);+ expect(readFileSync(target, "utf8")).toBe("body\n");+ });++ test("null with a present target throws, even when it is empty", () => {+ const target = join(tmp, "x.md");+ writeFileSync(target, "");+ driftOf(() => atomicWriteFileSync(target, "body\n", { expectBefore: null }));+ expect(readFileSync(target, "utf8")).toBe("");+ expect(tempFiles()).toEqual([]);+ });++ test("a string expectation with an absent target throws, even an empty one", () => {+ const target = join(tmp, "gone.md");+ driftOf(() => atomicWriteFileSync(target, "body\n", { expectBefore: "" }));+ expect(existsSync(target)).toBe(false);+ expect(tempFiles()).toEqual([]);+ });++ test("undefined keeps the unconditional overwrite", () => {+ const target = join(tmp, "x.md");+ writeFileSync(target, "anything\n");+ expect(atomicWriteFileSync(target, "new\n", { expectBefore: undefined })).toBe(true);+ expect(readFileSync(target, "utf8")).toBe("new\n");+ });++ test("composes with skipIfUnchanged", () => {+ const target = join(tmp, "x.md");+ writeFileSync(target, "same\n");+ // The expectation holds and the bytes already match: nothing to write.+ expect(+ atomicWriteFileSync(target, "same\n", { expectBefore: "same\n", skipIfUnchanged: true }),+ ).toBe(false);+ // The expectation fails: drift wins over the short-circuit.+ driftOf(() =>+ atomicWriteFileSync(target, "same\n", { expectBefore: "other\n", skipIfUnchanged: true }),+ );+ // The expectation holds and the bytes differ: it writes.+ expect(+ atomicWriteFileSync(target, "next\n", { expectBefore: "same\n", skipIfUnchanged: true }),+ ).toBe(true);+ expect(readFileSync(target, "utf8")).toBe("next\n");+ expect(tempFiles()).toEqual([]);+ });++ test("an edit landing after the temp write is refused before the rename", () => {+ const target = join(tmp, "x.md");+ writeFileSync(target, "old\n");+ // The first fsync is the temp file's: by then the up-front check has+ // passed and the temp file exists, so only the re-check before the+ // rename can see this edit.+ const realFsync = fs.fsyncSync;+ const spy = spyOn(fs, "fsyncSync").mockImplementationOnce((fd) => {+ realFsync(fd);+ writeFileSync(target, "edit during the write\n");+ });+ try {+ const err = driftOf(() => atomicWriteFileSync(target, "new\n", { expectBefore: "old\n" }));+ expect(spy).toHaveBeenCalled();+ expect(err.path).toBe(target);+ } finally {+ spy.mockRestore();+ }+ expect(readFileSync(target, "utf8")).toBe("edit during the write\n");+ expect(tempFiles()).toEqual([]);+ });++ test("an unchanged file holding invalid UTF-8 matches the lossy read of it", () => {+ const target = join(tmp, "bin.md");+ const bytes = Buffer.from([...Buffer.from("stale "), 0xff, 0x0a]);+ writeFileSync(target, bytes);+ const read = readFileSync(target, "utf8");+ expect(fileMatchesExpected(target, read)).toBe(true);+ atomicWriteFileSync(target, "new\n", { expectBefore: read });+ expect(readFileSync(target, "utf8")).toBe("new\n");+ });++ test("valid UTF-8 is compared byte for byte", () => {+ const target = join(tmp, "x.md");+ writeFileSync(target, "cafรฉ\n");+ const read = readFileSync(target, "utf8");+ // NFD: same text on screen, different bytes on disk.+ writeFileSync(target, "cafeฬ\n");+ expect(fileMatchesExpected(target, read)).toBe(false);+ driftOf(() => atomicWriteFileSync(target, "new\n", { expectBefore: read }));+ expect(readFileSync(target, "utf8")).toBe("cafeฬ\n");+ });++ test("an invalid-UTF-8 file is drift when its decoding changed", () => {+ const target = join(tmp, "bin.md");+ writeFileSync(target, Buffer.from([...Buffer.from("stale "), 0xff, 0x0a]));+ const read = readFileSync(target, "utf8");+ const edited = Buffer.from([...Buffer.from("edited "), 0xff, 0x0a]);+ writeFileSync(target, edited);+ expect(fileMatchesExpected(target, read)).toBe(false);+ driftOf(() => atomicWriteFileSync(target, "new\n", { expectBefore: read }));+ expect(readFileSync(target)).toEqual(edited);+ });++ test("known limit: two invalid sequences with the same decoding look equal", () => {+ // 0xff and 0xfe both decode to U+FFFD; the lossy read cannot tell them apart.+ const target = join(tmp, "bin.md");+ writeFileSync(target, Buffer.from([0xfe]));+ expect(fileMatchesExpected(target, Buffer.from([0xff]).toString("utf8"))).toBe(true);+ });++ test("fileMatchesExpected tells absent, empty and different apart", () => {+ const target = join(tmp, "x.md");+ expect(fileMatchesExpected(target, null)).toBe(true);+ expect(fileMatchesExpected(target, "")).toBe(false);+ writeFileSync(target, "");+ expect(fileMatchesExpected(target, "")).toBe(true);+ expect(fileMatchesExpected(target, null)).toBe(false);+ writeFileSync(target, "body\n");+ expect(fileMatchesExpected(target, "body\n")).toBe(true);+ expect(fileMatchesExpected(target, "other\n")).toBe(false);+ });++ test("isFileDrift rejects other errors and follows a wrapped cause", () => {+ expect(isFileDrift(new Error("x"))).toBe(false);+ expect(isFileDrift(null)).toBe(false);+ const inner = new FileDriftError(join(tmp, "x.md"));+ expect(isFileDrift(new Error("wrapped", { cause: inner }))).toBe(true);+ });+});diff --git a/tests/core/maintenance/self-heal-upgrade.test.ts b/tests/core/maintenance/self-heal-upgrade.test.tsindex d439a28e..f9eba519 100644--- a/tests/core/maintenance/self-heal-upgrade.test.ts+++ b/tests/core/maintenance/self-heal-upgrade.test.ts@@ -397,3 +397,48 @@ describe("a vault removed while the worker runs", () => {}});});++describe("the worker applies the plan it computed", () => {+ test("planUpgrade runs once per attempt and its plan is the one applied", () => {+ makeManualStale();+ const realPlan = upgradeModule.planUpgrade;+ const plans: upgradeModule.UpgradePlan[] = [];+ const planSpy = spyOn(upgradeModule, "planUpgrade").mockImplementation((v) => {+ const plan = realPlan(v);+ plans.push(plan);+ return plan;+ });+ const applySpy = spyOn(upgradeModule, "applyUpgrade");+ try {+ const run = runSelfHealUpgrade(vault, { now: T0 });++ expect(run.outcome).toBe(SELF_HEAL_UPGRADE_OUTCOME.applied);+ expect(plans).toHaveLength(1);+ expect(applySpy).toHaveBeenCalledTimes(1);+ expect(applySpy.mock.calls[0]![1]?.plan).toBe(plans[0]);+ } finally {+ planSpy.mockRestore();+ applySpy.mockRestore();+ }+ });++ test("a drift between its plan and its apply is recorded as a failure, the edit kept", () => {+ makeManualStale();+ const realPlan = upgradeModule.planUpgrade;+ const spy = spyOn(upgradeModule, "planUpgrade").mockImplementationOnce((v) => {+ const plan = realPlan(v);+ writeFileSync(brainManualPath(vault), "hand edit after the plan\n");+ return plan;+ });+ try {+ const run = runSelfHealUpgrade(vault, { now: T0 });++ expect(run.outcome).toBe(SELF_HEAL_UPGRADE_OUTCOME.failed);+ expect(run.error).toContain("Brain/_BRAIN.md");+ expect(readFileSync(brainManualPath(vault), "utf8")).toBe("hand edit after the plan\n");+ expect(readSelfHealUpgradeFailure(vault)!.pending).toEqual(["Brain/_BRAIN.md"]);+ } finally {+ spy.mockRestore();+ }+ });+});diff --git a/tests/core/search/embeddings.extra-body.test.ts b/tests/core/search/embeddings.extra-body.test.tsnew file mode 100644index 00000000..e5e4de7d--- /dev/null+++ b/tests/core/search/embeddings.extra-body.test.ts@@ -0,0 +1,410 @@+import { test, expect, beforeEach, afterEach } from "bun:test";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { OpenAICompatProvider } from "../../../src/core/search/embeddings/openai-compat.ts";+import { makeProvider } from "../../../src/core/search/embeddings/provider.ts";+import { providerCeilingKey } from "../../../src/core/search/embeddings/provider-semaphore.ts";+import {+ EXTRA_BODY_ENV,+ EXTRA_BODY_KEY,+ RESERVED_EMBEDDING_BODY_KEYS,+ resolveSearchConfig,+} from "../../../src/core/search/index.ts";+import { indexStatus, indexVault, reindexVault } from "../../../src/core/search/indexer.ts";+import { SearchError } from "../../../src/core/search/search-error.ts";+import type {+ ResolvedEmbeddingConfig,+ ResolvedSearchConfig,+} from "../../../src/core/search/types.ts";+import { SafeguardAbortError } from "../../../src/core/brain/safeguard.ts";+import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";+import { makeConfig, writeMd } from "../../helpers/search-fixtures.ts";+import { sqliteVecLoadable } from "../../helpers/sqlite-vec.ts";+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";++let server: FakeHttp;+let tmp: string;+let configPath: string;+let savedEnv: string | undefined;++beforeEach(async () => {+ server = await startFakeHttp();+ tmp = mkdtempSync(join(tmpdir(), "o2b-extra-body-"));+ configPath = join(tmp, "config.yaml");+ savedEnv = process.env[EXTRA_BODY_ENV];+ delete process.env[EXTRA_BODY_ENV];+});++afterEach(async () => {+ await server.close();+ rmSync(tmp, { recursive: true, force: true });+ if (savedEnv === undefined) delete process.env[EXTRA_BODY_ENV];+ else process.env[EXTRA_BODY_ENV] = savedEnv;+});++function cfg(overrides: Partial<ResolvedEmbeddingConfig> = {}): ResolvedEmbeddingConfig {+ return Object.freeze({+ enabled: true,+ provider: "openai-compat",+ baseUrl: server.url,+ model: "fake-model",+ apiKey: FAKE_PROVIDER_KEY,+ dimension: 4,+ timeoutMs: 5_000,+ concurrency: 2,+ batchSize: 32,+ costGateUsd: 0,+ maxRetries: 1,+ ...overrides,+ });+}++/** Records every request body and answers with `width`-wide vectors. */+function captureBodies(bodies: unknown[], width = 4) {+ return (req: { body: unknown }) => {+ bodies.push(req.body);+ const input = (req.body as { input: string[] }).input;+ const data = input.map((_, i) => ({+ object: "embedding",+ embedding: Array.from({ length: width }, (_, j) => (j === 0 ? 1 : 0)),+ index: i,+ }));+ return { status: 200, body: { data } };+ };+}++function resolveWith(lines: string[], envValue?: string): ResolvedSearchConfig {+ writeFileSync(configPath, [`vault: "${tmp}"`, ...lines, ""].join("\n"));+ if (envValue !== undefined) process.env[EXTRA_BODY_ENV] = envValue;+ return resolveSearchConfig({ vault: tmp, configPath });+}++function refusal(lines: string[], envValue?: string): SearchError {+ try {+ resolveWith(lines, envValue);+ } catch (e) {+ if (e instanceof SearchError) return e;+ throw e;+ }+ throw new Error("expected resolveSearchConfig to refuse");+}++// โโ request body โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++test("an absent extra body sends exactly the owned fields", async () => {+ const bodies: unknown[] = [];+ server.setHandler(captureBodies(bodies));+ await new OpenAICompatProvider(cfg()).embed(["alpha", "beta"]);+ expect(bodies).toEqual([+ { model: "fake-model", input: ["alpha", "beta"], encoding_format: "float" },+ ]);+});++test("declared extra fields arrive next to the owned fields", async () => {+ const bodies: unknown[] = [];+ server.setHandler(captureBodies(bodies));+ const extraBody = Object.freeze({ dimensions: 256, user: "x" });+ await new OpenAICompatProvider(cfg({ extraBody })).embed(["alpha"]);+ expect(bodies).toEqual([+ {+ dimensions: 256,+ user: "x",+ model: "fake-model",+ input: ["alpha"],+ encoding_format: "float",+ },+ ]);+});++test("owned fields win over an extra body that slipped past resolution", async () => {+ const bodies: unknown[] = [];+ server.setHandler(captureBodies(bodies));+ const extraBody = Object.freeze({ model: "other", input: ["x"], encoding_format: "base64" });+ await new OpenAICompatProvider(cfg({ extraBody })).embed(["alpha"]);+ expect(bodies).toEqual([{ model: "fake-model", input: ["alpha"], encoding_format: "float" }]);+});++test("a response width changed by the extra body surfaces as a named error", async () => {+ server.setHandler(captureBodies([], 2));+ const provider = new OpenAICompatProvider(cfg({ extraBody: Object.freeze({ dimensions: 2 }) }));+ const error = await provider.embed(["alpha"]).then(+ () => null,+ (e: unknown) => e,+ );+ expect(error).toBeInstanceOf(SearchError);+ expect((error as SearchError).code).toBe("EMBEDDING_DIMENSION_MISMATCH");+});++// โโ resolution โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++test("an absent key resolves to no extra body", () => {+ const resolved = resolveWith([]);+ expect(resolved.semantic.extraBody).toBeUndefined();+ expect("extraBody" in resolved.semantic).toBe(false);+});++test("a JSON object in the config key resolves to the extra body", () => {+ const resolved = resolveWith([+ "embedding_dimension: 256",+ `${EXTRA_BODY_KEY}: {"dimensions": 256, "user": "x"}`,+ ]);+ expect(resolved.semantic.extraBody).toEqual({ dimensions: 256, user: "x" });+ expect(Object.isFrozen(resolved.semantic.extraBody)).toBe(true);+});++test("the env value beats the config value", () => {+ const resolved = resolveWith([`${EXTRA_BODY_KEY}: {"user": "config"}`], '{"user": "env"}');+ expect(resolved.semantic.extraBody).toEqual({ user: "env" });+});++test("the reserved keys are the owned request fields", () => {+ expect([...RESERVED_EMBEDDING_BODY_KEYS]).toEqual(["model", "input", "encoding_format"]);+});++for (const spelling of ["model", "Input", "encoding-format"]) {+ test(`a reserved key spelled '${spelling}' is refused by its spelling`, () => {+ const e = refusal([`${EXTRA_BODY_KEY}: {"${spelling}": 1, "user": "x"}`]);+ expect(e.code).toBe("INVALID_INPUT");+ expect(e.message).toContain(EXTRA_BODY_KEY);+ expect(e.message).toContain(`'${spelling}'`);+ expect(e.message).not.toContain("'user'");+ });+}++for (const spelling of ["\uFF4D\uFF4F\uFF44\uFF45\uFF4C", " input ", "encoding\u200B_format"]) {+ test(`a reserved key in a compatibility or invisible spelling ${JSON.stringify(spelling)} is refused`, () => {+ const e = refusal([`${EXTRA_BODY_KEY}: ${JSON.stringify({ [spelling]: 1 })}`]);+ expect(e.code).toBe("INVALID_INPUT");+ expect(e.message).toContain(`'${spelling}'`);+ });+}++test("every reserved spelling is listed in one refusal", () => {+ const e = refusal([`${EXTRA_BODY_KEY}: {"MODEL": 1, "Encoding_Format": "x"}`]);+ expect(e.message).toContain("'MODEL'");+ expect(e.message).toContain("'Encoding_Format'");+});++const MALFORMED: ReadonlyArray<readonly [string, string]> = [+ ["invalid JSON", "{not json"],+ ["an array", '["dimensions", 256]'],+ ["a scalar", "256"],+ ["null", "null"],+];++for (const [label, value] of MALFORMED) {+ test(`${label} is refused naming the key`, () => {+ const e = refusal([`${EXTRA_BODY_KEY}: ${value}`]);+ expect(e.code).toBe("INVALID_INPUT");+ expect(e.message).toContain(EXTRA_BODY_KEY);+ });+}++test("a blank config value is refused naming the key", () => {+ const e = refusal([`${EXTRA_BODY_KEY}: " "`]);+ expect(e.code).toBe("INVALID_INPUT");+ expect(e.message).toContain(EXTRA_BODY_KEY);+});++test("a blank env value is refused naming the env variable", () => {+ const e = refusal([], " ");+ expect(e.code).toBe("INVALID_INPUT");+ expect(e.message).toContain(EXTRA_BODY_ENV);+});++test("a refusal from the env value names the env variable", () => {+ const e = refusal([`${EXTRA_BODY_KEY}: {"user": "x"}`], '{"model": "y"}');+ expect(e.code).toBe("INVALID_INPUT");+ expect(e.message).toContain(EXTRA_BODY_ENV);+ expect(e.message).toContain("'model'");+});++test("a dimensions field that disagrees with embedding_dimension is refused", () => {+ const e = refusal(["embedding_dimension: 4", `${EXTRA_BODY_KEY}: {"dimensions": 256}`]);+ expect(e.code).toBe("INVALID_INPUT");+ expect(e.message).toContain("embedding_dimension");+ expect(e.message).toContain(EXTRA_BODY_KEY);+});++test("a dimensions field that agrees with embedding_dimension resolves", () => {+ const resolved = resolveWith([+ "embedding_dimension: 256",+ `${EXTRA_BODY_KEY}: {"dimensions": 256}`,+ ]);+ expect(resolved.semantic.extraBody).toEqual({ dimensions: 256 });+});++test("a dimensions field with no embedding_dimension is refused", () => {+ const e = refusal([`${EXTRA_BODY_KEY}: {"dimensions": 256}`]);+ expect(e.code).toBe("INVALID_INPUT");+ expect(e.message).toContain(EXTRA_BODY_KEY);+ expect(e.message).toContain("embedding_dimension");+});++test("a dimensions field in another spelling is checked by its spelling", () => {+ const e = refusal(["embedding_dimension: 4", `${EXTRA_BODY_KEY}: {"Dimensions": 256}`]);+ expect(e.code).toBe("INVALID_INPUT");+ expect(e.message).toContain("'Dimensions'");+});++function overrideRefusal(semantic: Partial<ResolvedEmbeddingConfig>): SearchError {+ writeFileSync(configPath, [`vault: "${tmp}"`, ""].join("\n"));+ try {+ resolveSearchConfig({ vault: tmp, configPath, overrides: { semantic } });+ } catch (e) {+ if (e instanceof SearchError) return e;+ throw e;+ }+ throw new Error("expected resolveSearchConfig to refuse");+}++test("an override cannot carry a dimensions field past an unset width", () => {+ const e = overrideRefusal({ dimension: null, extraBody: Object.freeze({ dimensions: 256 }) });+ expect(e.code).toBe("INVALID_INPUT");+ expect(e.message).toContain("embedding_dimension");+});++test("an override cannot carry a dimensions field that disagrees with its width", () => {+ const e = overrideRefusal({ dimension: 4, extraBody: Object.freeze({ dimensions: 256 }) });+ expect(e.code).toBe("INVALID_INPUT");+ expect(e.message).toContain("embedding_dimension is 4");+});++for (const provider of ["zeroentropy", "local"]) {+ test(`an extra body is refused for the ${provider} provider, naming it`, () => {+ const e = refusal([`embedding_provider: ${provider}`, `${EXTRA_BODY_KEY}: {"user": "x"}`]);+ expect(e.code).toBe("INVALID_INPUT");+ expect(e.message).toContain(EXTRA_BODY_KEY);+ expect(e.message).toContain(`'${provider}'`);+ });+}++test("an extra body from the env for another provider is refused naming the env variable", () => {+ const e = refusal(["embedding_provider: zeroentropy"], '{"user": "x"}');+ expect(e.code).toBe("INVALID_INPUT");+ expect(e.message).toContain(EXTRA_BODY_ENV);+ expect(e.message).not.toContain(EXTRA_BODY_KEY);+});++test("a dimensions field from the env is refused naming the env variable", () => {+ const e = refusal(["embedding_dimension: 4"], '{"dimensions": 256}');+ expect(e.code).toBe("INVALID_INPUT");+ expect(e.message).toContain(EXTRA_BODY_ENV);+ expect(e.message).toContain("embedding_dimension is 4");+});++test("an override cannot pair a non-openai-compat provider with an extra body", () => {+ const e = overrideRefusal({ provider: "zeroentropy", extraBody: Object.freeze({ user: "x" }) });+ expect(e.code).toBe("INVALID_INPUT");+ expect(e.message).toContain("'zeroentropy'");+});++test("an override cannot carry an owned request field in any spelling", () => {+ const e = overrideRefusal({ extraBody: Object.freeze({ Encoding_Format: "base64" }) });+ expect(e.code).toBe("INVALID_INPUT");+ expect(e.message).toContain(EXTRA_BODY_KEY);+ expect(e.message).toContain("'Encoding_Format'");+});++test("a disabled provider accepts an extra body and builds a provider that sends nothing", async () => {+ const resolved = resolveWith([+ "embedding_provider: disabled",+ `${EXTRA_BODY_KEY}: {"user": "x"}`,+ ]);+ expect(resolved.semantic.provider).toBe("disabled");+ const provider = makeProvider(resolved.semantic);+ expect(provider.producesVectors).toBe(false);+ await expect(provider.embed(["hello"])).rejects.toMatchObject({ code: "EMBEDDING_DISABLED" });+});++// โโ identity โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++/** A config over the test vault that indexes through the fake provider. */+function indexConfig(+ extraBody?: Readonly<Record<string, unknown>>,+ rest: Partial<ResolvedSearchConfig> = {},+): ResolvedSearchConfig {+ const semantic = cfg(extraBody === undefined ? {} : { extraBody: Object.freeze(extraBody) });+ return Object.freeze({+ ...makeConfig({+ vault: tmp,+ dbPath: join(tmp, ".open-second-brain", "brain.sqlite"),+ semantic,+ }),+ ...rest,+ });+}++test.skipIf(!sqliteVecLoadable())(+ "adding an extra body to an indexed vault re-embeds nothing and keeps the status signature",+ async () => {+ writeMd(tmp, "a.md", "# A\n\nFirst note about something.");+ const plain = indexConfig();+ const first = await indexVault(plain, { embeddings: true });+ expect(first.embeddingsComputed).toBeGreaterThan(0);+ const plainStatus = await indexStatus(plain);+ const calls = server.callCount();++ const extra = indexConfig({ user: "x" });+ const second = await indexVault(extra, { embeddings: true });+ expect(second.embeddingsComputed).toBe(0);+ expect(server.callCount()).toBe(calls);++ const extraStatus = await indexStatus(extra);+ expect(extraStatus.embeddingSignature).toBe(plainStatus.embeddingSignature);+ expect(extraStatus.staleEmbeddings).toBe(0);+ expect(extraStatus.embeddings).toBe(extraStatus.chunks);++ // The body is in force: a new note goes out with it, and alone.+ const bodies: unknown[] = [];+ server.setHandler(captureBodies(bodies));+ writeMd(tmp, "b.md", "# B\n\nSecond note discussing things.");+ await indexVault(extra, { embeddings: true });+ expect(bodies.length).toBeGreaterThan(0);+ for (const body of bodies) {+ expect(body).toMatchObject({ user: "x" });+ expect(JSON.stringify(body)).not.toContain("First note");+ }+ },+);++test.skipIf(!sqliteVecLoadable())(+ "an interrupted rebuild resumes under a config that adds an extra body",+ async () => {+ for (let i = 0; i < 4; i++) writeMd(tmp, `n${i}.md`, `# N${i}\n\nbody number ${i}`);+ const ac = new AbortController();+ let processed = 0;+ await expect(+ reindexVault(indexConfig(undefined, { resumeReindex: true }), {+ embeddings: true,+ signal: ac.signal,+ onFile: () => {+ if (++processed === 1) ac.abort();+ },+ }),+ ).rejects.toBeInstanceOf(SafeguardAbortError);++ const stats = await reindexVault(indexConfig({ user: "x" }, { resumeReindex: true }), {+ embeddings: true,+ });+ // A discarded staging build would count every note as added.+ expect(stats.unchanged).toBeGreaterThanOrEqual(1);+ expect(stats.added + stats.unchanged).toBe(4);+ },+);++test("an extra body shares the provider's concurrency ceiling", () => {+ const base = [+ "embedding_provider: openai-compat",+ "embedding_model: fake-model",+ "embedding_dimension: 4",+ ];+ const plain = resolveWith(base).semantic;+ const extra = resolveWith([...base, `${EXTRA_BODY_KEY}: {"user": "x"}`]).semantic;+ expect(extra.extraBody).toEqual({ user: "x" });+ expect(providerCeilingKey("openai-compat", extra, server.url)).toBe(+ providerCeilingKey("openai-compat", plain, server.url),+ );+});diff --git a/tests/core/search/embeddings.input-window.test.ts b/tests/core/search/embeddings.input-window.test.tsnew file mode 100644index 00000000..05217c23--- /dev/null+++ b/tests/core/search/embeddings.input-window.test.ts@@ -0,0 +1,259 @@+/**+ * The effective input window (honest-query-embed-and-safe-upgrades, task 1).+ *+ * One resolver answers "how many tokens does the configured model accept":+ * the operator's `embedding_input_window_tokens` when set, otherwise the+ * window the curated preset table declares, otherwise unknown (null). The+ * query fit and the oversize-chunk census both read it, so an operator who+ * declares the window of an uncurated model gets both from one key.+ *+ * Also pinned here: the query prefix the configured BACKEND sends, which+ * is not the prefix the configuration asks for. Only `openai-compat`+ * implements the instruction-prefix contract.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { writeFileSync } from "node:fs";+import { join } from "node:path";++import { resolveSearchConfig } from "../../../src/core/search/index.ts";+import { indexVault } from "../../../src/core/search/indexer.ts";+import {+ declaredInputWindowTokens,+ effectiveInputWindowTokens,+ INPUT_WINDOW_TOKENS_KEY,+ queryPrefixSentByProvider,+ RECOMMENDED_EMBEDDING_MODEL,+} from "../../../src/core/search/embeddings/presets.ts";+import { charLengthOverTokenBudget } from "../../../src/core/search/embeddings/signature.ts";+import type {+ EmbeddingProviderName,+ ResolvedEmbeddingConfig,+ ResolvedSearchConfig,+} from "../../../src/core/search/types.ts";+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";++const ENV_KEY = "OPEN_SECOND_BRAIN_EMBEDDING_INPUT_WINDOW_TOKENS";++/** A model string deliberately outside the curated table. */+const UNCURATED_MODEL = "acme/custom-embed-9000";++/** The curated window of the shipped recommended default. */+const RECOMMENDED_WINDOW = declaredInputWindowTokens(RECOMMENDED_EMBEDDING_MODEL)!;++let vault: string;+let dbPath: string;+let configPath: string;+let cleanup: () => void;+let savedEnv: string | undefined;++beforeEach(() => {+ const v = createTempVault("input-window");+ vault = v.vault;+ dbPath = v.dbPath;+ cleanup = v.cleanup;+ configPath = join(vault, "_brain.yaml");+ savedEnv = process.env[ENV_KEY];+ delete process.env[ENV_KEY];+});++afterEach(() => {+ if (savedEnv === undefined) delete process.env[ENV_KEY];+ else process.env[ENV_KEY] = savedEnv;+ cleanup();+});++function writeConfig(extra = ""): void {+ writeFileSync(configPath, `vault: "${vault}"\n${extra}`);+}++function semantic(overrides: Partial<ResolvedEmbeddingConfig> = {}): ResolvedEmbeddingConfig {+ return Object.freeze({+ enabled: true,+ provider: "openai-compat",+ baseUrl: "https://embeddings.invalid/v1",+ model: UNCURATED_MODEL,+ apiKey: FAKE_PROVIDER_KEY,+ dimension: 384,+ timeoutMs: 5_000,+ concurrency: 1,+ batchSize: 32,+ costGateUsd: 0,+ maxRetries: 3,+ ...overrides,+ });+}++function indexCfg(overrides: Partial<ResolvedEmbeddingConfig> = {}): ResolvedSearchConfig {+ return Object.freeze(+ makeConfig({+ vault,+ dbPath,+ semantic: {+ enabled: true,+ provider: "openai-compat",+ // Never reached: the census is a read over already-indexed rows.+ baseUrl: "https://embeddings.invalid/v1",+ model: UNCURATED_MODEL,+ apiKey: FAKE_PROVIDER_KEY,+ dimension: 384,+ ...overrides,+ },+ }),+ );+}++// โโ config resolution โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++test("an absent key leaves the field absent", () => {+ writeConfig();+ const resolved = resolveSearchConfig({ vault, configPath }).semantic;+ expect("inputWindowTokens" in resolved).toBe(false);+ expect(JSON.stringify(resolved)).not.toContain("inputWindowTokens");+});++test("the key resolves from config, and the env variable beats config", () => {+ writeConfig(`${INPUT_WINDOW_TOKENS_KEY}: "300"\n`);+ expect(resolveSearchConfig({ vault, configPath }).semantic.inputWindowTokens).toBe(300);+ process.env[ENV_KEY] = "700";+ expect(resolveSearchConfig({ vault, configPath }).semantic.inputWindowTokens).toBe(700);+});++test("zero, a fraction and a blank value are refused from the string, naming the key", () => {+ for (const raw of ["0", "2.5", "", " "]) {+ writeConfig(`${INPUT_WINDOW_TOKENS_KEY}: "${raw}"\n`);+ let caught: unknown = null;+ try {+ resolveSearchConfig({ vault, configPath });+ } catch (e) {+ caught = e;+ }+ expect(`${raw}: ${(caught as { code?: string } | null)?.code}`).toBe(`${raw}: INVALID_INPUT`);+ expect((caught as Error).message).toContain(INPUT_WINDOW_TOKENS_KEY);+ }+});++test("a blank env value is refused, naming the key", () => {+ writeConfig();+ process.env[ENV_KEY] = "";+ expect(() => resolveSearchConfig({ vault, configPath })).toThrow(INPUT_WINDOW_TOKENS_KEY);+});++test("zero, a fraction and a non-number are refused from an override, naming the key", () => {+ writeConfig();+ for (const bad of [0, -1, 2.5, Number.NaN]) {+ let caught: unknown = null;+ try {+ resolveSearchConfig({+ vault,+ configPath,+ overrides: { semantic: { inputWindowTokens: bad } },+ });+ } catch (e) {+ caught = e;+ }+ expect(`${bad}: ${(caught as { code?: string } | null)?.code}`).toBe(`${bad}: INVALID_INPUT`);+ expect((caught as Error).message).toContain(INPUT_WINDOW_TOKENS_KEY);+ }+});++test("the key is refused for the offline local embedder, naming the provider", () => {+ writeConfig(`embedding_provider: local\n${INPUT_WINDOW_TOKENS_KEY}: "512"\n`);+ let caught: unknown = null;+ try {+ resolveSearchConfig({ vault, configPath });+ } catch (e) {+ caught = e;+ }+ expect((caught as { code?: string } | null)?.code).toBe("INVALID_INPUT");+ expect((caught as Error).message).toContain(INPUT_WINDOW_TOKENS_KEY);+ expect((caught as Error).message).toContain("'local'");+});++test("an override cannot pair the local embedder with a window", () => {+ writeConfig();+ expect(() =>+ resolveSearchConfig({+ vault,+ configPath,+ overrides: { semantic: { provider: "local", inputWindowTokens: 64 } },+ }),+ ).toThrow(INPUT_WINDOW_TOKENS_KEY);+});++test("the key resolves for every provider that reads it", () => {+ for (const provider of ["openai-compat", "zeroentropy"]) {+ writeConfig(`embedding_provider: ${provider}\n${INPUT_WINDOW_TOKENS_KEY}: "512"\n`);+ expect(resolveSearchConfig({ vault, configPath }).semantic.inputWindowTokens).toBe(512);+ }+});++// โโ the resolver โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++test("the operator key beats the preset window", () => {+ expect(+ effectiveInputWindowTokens(+ semantic({ model: RECOMMENDED_EMBEDDING_MODEL, inputWindowTokens: 64 }),+ ),+ ).toBe(64);+});++test("the preset window applies when the key is absent", () => {+ expect(effectiveInputWindowTokens(semantic({ model: RECOMMENDED_EMBEDDING_MODEL }))).toBe(+ RECOMMENDED_WINDOW,+ );+});++test("an uncurated model with no key resolves to unknown, and unknown is not zero", () => {+ expect(effectiveInputWindowTokens(semantic())).toBeNull();+ expect(effectiveInputWindowTokens(semantic({ model: null }))).toBeNull();+ expect(effectiveInputWindowTokens(semantic({ inputWindowTokens: 300 }))).toBe(300);+});++test("a model passed explicitly stands in for an unset configured model", () => {+ expect(effectiveInputWindowTokens(semantic({ model: null }), RECOMMENDED_EMBEDDING_MODEL)).toBe(+ RECOMMENDED_WINDOW,+ );+});++test("the offline local embedder has no window, whatever the key says", () => {+ expect(+ effectiveInputWindowTokens(semantic({ provider: "local", inputWindowTokens: 64 })),+ ).toBeNull();+});++// โโ the prefix the backend sends โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++test("only openai-compat sends the configured query prefix", () => {+ const cases: ReadonlyArray<readonly [EmbeddingProviderName, string]> = [+ ["openai-compat", "query: "],+ ["zeroentropy", ""],+ ["local", ""],+ ["disabled", ""],+ ];+ for (const [provider, expected] of cases) {+ expect(`${provider}: ${JSON.stringify(queryPrefixSentByProvider(provider, "query: "))}`).toBe(+ `${provider}: ${JSON.stringify(expected)}`,+ );+ }+ expect(queryPrefixSentByProvider("openai-compat", undefined)).toBe("");+ expect(queryPrefixSentByProvider("openai-compat", "")).toBe("");+});++// โโ the census reads the same resolver โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++test("the census reports an over-window chunk for an uncurated model once the key is set", async () => {+ const window = 64;+ writeMd(vault, "big.md", `# Big\n\n${"overflow ".repeat(charLengthOverTokenBudget(window))}\n`);+ const undeclared = await indexVault(indexCfg());+ expect(undeclared.chunkWindow?.verdict).toBe("window-undeclared");++ const declared = await indexVault(indexCfg({ inputWindowTokens: window }), { force: true });+ const census = declared.chunkWindow;+ expect(census?.verdict).toBe("over-window");+ if (census?.verdict !== "over-window") throw new Error("verdict narrowed wrong");+ expect(census.model).toBe(UNCURATED_MODEL);+ expect(census.windowTokens).toBe(window);+ expect(census.chunksOverWindow).toBeGreaterThan(0);+});diff --git a/tests/core/search/feedback-spend-gate.test.ts b/tests/core/search/feedback-spend-gate.test.tsnew file mode 100644index 00000000..fc44726e--- /dev/null+++ b/tests/core/search/feedback-spend-gate.test.ts@@ -0,0 +1,202 @@+/**+ * Recall feedback on a re-run the semantic lane never reached+ * (honest-query-embed-and-safe-upgrades, security audit round 1).+ *+ * `captureRecallFeedback` re-runs the query to read the judged result's+ * per-layer contributions. Under the spend gate a remote re-run is+ * keyword-only, so those shares describe the refusal, not the result:+ * recorded as a normal event they would push the vault-wide learned+ * weights toward keyword for as long as the gate holds. The event keeps+ * its audit row with zero contributions, which the fold skips.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";++import { TRANSPORT_REACH } from "../../../src/core/graph/transport-reach.ts";+import {+ captureRecallFeedback,+ NEUTRAL_LEARNED_WEIGHTS,+} from "../../../src/core/search/feedback.ts";+import { indexVault } from "../../../src/core/search/indexer.ts";+import { RETRIEVAL_DEGRADATION } from "../../../src/core/search/retrieval-trail.ts";+import type { ResolvedSearchConfig } from "../../../src/core/search/types.ts";+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";+import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";+import { sqliteVecLoadable } from "../../helpers/sqlite-vec.ts";++const MODEL = "fake-model";+const NOW = new Date("2026-10-06T12:00:00Z");++let server: FakeHttp;+let cleanup: () => void = () => {};++beforeEach(async () => {+ server = await startFakeHttp();+ server.setHandler((req) => {+ const body = (req.body ?? {}) as { input?: string[] };+ const batch = Array.isArray(body.input) ? body.input : [];+ return {+ status: 200,+ body: {+ data: batch.map((text, index) => ({+ object: "embedding",+ embedding: [text.length, index, 1, 1],+ index,+ })),+ model: MODEL,+ },+ };+ });+});++afterEach(async () => {+ cleanup();+ cleanup = () => {};+ await server.close();+});++/** Indexed with embeddings, then served under a positive gate on an unpriced model. */+async function gatedIndex(): Promise<ResolvedSearchConfig> {+ const v = createTempVault("feedback-spend-gate");+ cleanup = v.cleanup;+ writeMd(v.vault, "Notes/fox.md", "# Fox\n\nThe quick brown fox jumps over the lazy dog.");+ const config = makeConfig({+ vault: v.vault,+ dbPath: v.dbPath,+ semantic: {+ enabled: true,+ provider: "openai-compat",+ baseUrl: server.url,+ model: MODEL,+ apiKey: FAKE_PROVIDER_KEY,+ dimension: 4,+ maxRetries: 1,+ costGateUsd: 0,+ },+ });+ await indexVault(config, { embeddings: true });+ return { ...config, semantic: { ...config.semantic, costGateUsd: 1 } };+}++test.skipIf(!sqliteVecLoadable())(+ "feedback on a gated re-run keeps the row and carries no layer signal",+ async () => {+ const config = await gatedIndex();+ const out = await captureRecallFeedback(config, {+ query: "fox",+ resultPath: "Notes/fox.md",+ verdict: "up",+ nowMs: NOW.getTime(),+ });+ expect(out.resultFound).toBe(true);+ expect(out.degraded).toContain(RETRIEVAL_DEGRADATION.semanticCostUnpriced);+ expect(out.event.contributions).toEqual({ keyword: 0, semantic: 0, entity: 0, recency: 0 });+ // The row is kept and counted; it moves no multiplier.+ expect(out.learned.events).toBe(1);+ expect(out.learned).toMatchObject({+ keywordMul: NEUTRAL_LEARNED_WEIGHTS.keywordMul,+ semanticMul: NEUTRAL_LEARNED_WEIGHTS.semanticMul,+ entityMul: NEUTRAL_LEARNED_WEIGHTS.entityMul,+ recencyMul: NEUTRAL_LEARNED_WEIGHTS.recencyMul,+ });+ },+);++test.skipIf(!sqliteVecLoadable())(+ "feedback on an ungated local re-run records the layer contributions",+ async () => {+ const config = await gatedIndex();+ const out = await captureRecallFeedback(config, {+ query: "fox",+ resultPath: "Notes/fox.md",+ verdict: "up",+ nowMs: NOW.getTime(),+ transportReach: TRANSPORT_REACH.local,+ });+ expect(out.degraded).toEqual([]);+ expect(out.event.contributions.keyword).toBeGreaterThan(0);+ expect(out.learned.events).toBe(1);+ expect(out.learned.keywordMul).toBeGreaterThan(1);+ },+);++test("feedback on an index with no embeddings records the layer contributions", async () => {+ // Keyword-only by construction: the system the re-run measured is the+ // one that serves, so its shares are signal, not a degradation.+ const v = createTempVault("feedback-no-embeddings");+ cleanup = v.cleanup;+ writeMd(v.vault, "Notes/fox.md", "# Fox\n\nThe quick brown fox jumps over the lazy dog.");+ const config = makeConfig({+ vault: v.vault,+ dbPath: v.dbPath,+ semantic: {+ enabled: true,+ provider: "openai-compat",+ baseUrl: server.url,+ model: MODEL,+ apiKey: FAKE_PROVIDER_KEY,+ dimension: 4,+ maxRetries: 1,+ costGateUsd: 0,+ },+ });+ await indexVault(config);+ const out = await captureRecallFeedback(config, {+ query: "fox",+ resultPath: "Notes/fox.md",+ verdict: "up",+ nowMs: NOW.getTime(),+ transportReach: TRANSPORT_REACH.local,+ });+ expect(out.degraded).toContain(RETRIEVAL_DEGRADATION.semanticEmbeddingsAbsent);+ expect(out.degraded).toContain(RETRIEVAL_DEGRADATION.hybridDegraded);+ expect(out.event.contributions.keyword).toBeGreaterThan(0);+ expect(out.learned.keywordMul).toBeGreaterThan(1);+});++test.skipIf(!sqliteVecLoadable())(+ "feedback on an empty-fit re-run with no keyword hit carries no layer signal",+ async () => {+ // The instruction prefix alone fills the input window, so the semantic+ // lane never runs; the keyword lane finds nothing either, so no+ // `hybrid-degraded` umbrella is noted. The judged page still arrives+ // through the relational arm, scored without the semantic lane.+ const v = createTempVault("feedback-empty-fit");+ cleanup = v.cleanup;+ writeMd(v.vault, "qx.md", '---\nrelated: "[[neighbor]]"\n---\n\nalpha topic.');+ writeMd(v.vault, "neighbor.md", "# Beta\n\nbeta divergent content.");+ const semantic = {+ enabled: true,+ provider: "openai-compat" as const,+ baseUrl: server.url,+ model: MODEL,+ apiKey: FAKE_PROVIDER_KEY,+ dimension: 4,+ maxRetries: 1,+ costGateUsd: 0,+ };+ const indexed = makeConfig({ vault: v.vault, dbPath: v.dbPath, semantic });+ await indexVault(indexed, { embeddings: true });+ const config = makeConfig({+ vault: v.vault,+ dbPath: v.dbPath,+ fusionMode: "rrf",+ relationalArmEnabled: true,+ semantic: { ...semantic, inputWindowTokens: 1, queryPrefix: "a long instruction prefix: " },+ });+ const embedsBefore = server.callCount();+ const out = await captureRecallFeedback(config, {+ query: "[[qx]] related",+ resultPath: "neighbor.md",+ verdict: "up",+ nowMs: NOW.getTime(),+ transportReach: TRANSPORT_REACH.local,+ });+ expect(server.callCount()).toBe(embedsBefore);+ expect(out.resultFound).toBe(true);+ expect(out.degraded).toEqual([RETRIEVAL_DEGRADATION.semanticQueryEmptyFit]);+ expect(out.event.contributions).toEqual({ keyword: 0, semantic: 0, entity: 0, recency: 0 });+ expect(out.learned.events).toBe(1);+ },+);diff --git a/tests/core/search/query-embed.test.ts b/tests/core/search/query-embed.test.tsnew file mode 100644index 00000000..87252dcd--- /dev/null+++ b/tests/core/search/query-embed.test.ts@@ -0,0 +1,320 @@+/**+ * The query-embed gateway (honest-query-embed-and-safe-upgrades, tasks 2-3).+ *+ * Two questions every paid query embed shares, answered once:+ *+ * - what text is sent: the query cut to the effective input window,+ * with the prefix the backend actually sends charged against it under+ * the CEILING estimate, so the cut never sends more than the window;+ * - whether it is sent at all: a caller that is not local, under a+ * positive `embedding_cost_gate_usd`, on a model nobody priced, is+ * refused before any provider exists.+ */++import { expect, test } from "bun:test";++import {+ fitQueryToWindow,+ prepareQueryEmbed,+ queryEmbedCutMessage,+ queryEmbedEmptyFitMessage,+ queryEmbedRefusalMessage,+} from "../../../src/core/search/embeddings/query-embed.ts";+import { makeProvider } from "../../../src/core/search/embeddings/provider.ts";+import {+ INPUT_WINDOW_TOKENS_KEY,+ RECOMMENDED_EMBEDDING_MODEL,+} from "../../../src/core/search/embeddings/presets.ts";+import {+ EMBEDDING_PRICE_MODEL_KEY,+ EMBEDDING_PRICE_RATE_KEY,+ EMBEDDING_PRICE_SOURCE,+} from "../../../src/core/search/embeddings/pricing.ts";+import { COST_GATE_KEY, formatEstimatedUsd } from "../../../src/core/search/embedding-spend.ts";+import { TRANSPORT_REACH } from "../../../src/core/graph/transport-reach.ts";+import type {+ ResolvedEmbeddingConfig,+ ResolvedSearchConfig,+} from "../../../src/core/search/types.ts";+import { makeConfig } from "../../helpers/search-fixtures.ts";+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";+import {+ estimateTokens,+ LOCAL_EMBEDDING_MODEL,+ textExtent,+ tokenEstimateCeiling,+ tokenEstimateFloor,+} from "../../../src/core/search/embeddings/signature.ts";++const PREFIX = "query: ";++function ceiling(text: string): number {+ return tokenEstimateCeiling(textExtent(text));+}++/** The code point after `text` in `query`, or undefined at the end. */+function nextCodePoint(query: string, text: string): string | undefined {+ return [...query][[...text].length];+}++// โโ task 2: the fit โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++test("a null window returns the query unchanged", () => {+ const query = "x".repeat(10_000);+ const fit = fitQueryToWindow(query, PREFIX, null);+ expect(fit.text).toBe(query);+ expect(fit.truncated).toBe(false);+});++test("a query that fits a known window is not cut", () => {+ const fit = fitQueryToWindow("short query", PREFIX, 512);+ expect(fit.text).toBe("short query");+ expect(fit.truncated).toBe(false);+});++test("an ASCII query over the window is cut to the longest prefix that fits", () => {+ const window = 16;+ const query = "abcdefghij".repeat(20);+ const fit = fitQueryToWindow(query, PREFIX, window);+ expect(fit.truncated).toBe(true);+ expect(query.startsWith(fit.text)).toBe(true);+ expect(ceiling(PREFIX + fit.text)).toBeLessThanOrEqual(window);+ const next = nextCodePoint(query, fit.text);+ expect(next).toBeDefined();+ expect(ceiling(PREFIX + fit.text + next!)).toBeGreaterThan(window);+});++test("a Han query is cut under the ceiling bound, never the floor", () => {+ const window = 32;+ const query = "็ฅ่ฏ็ฎก็็ณป็ป".repeat(20);+ const fit = fitQueryToWindow(query, PREFIX, window);+ expect(fit.truncated).toBe(true);+ expect(ceiling(PREFIX + fit.text)).toBeLessThanOrEqual(window);+ expect(ceiling(PREFIX + fit.text + nextCodePoint(query, fit.text)!)).toBeGreaterThan(window);+ // The floor would have admitted roughly four times as much Han text.+ const floorCut = [...query].slice(0, (window - 2) * 4).join("");+ expect(tokenEstimateFloor(textExtent(PREFIX + floorCut))).toBeLessThanOrEqual(window);+ expect([...fit.text].length).toBeLessThan([...floorCut].length);+});++test("a cut never splits a surrogate pair", () => {+ // Astral-plane characters: each is one code point and two UTF-16 units.+ for (let window = 3; window <= 12; window++) {+ const query = "๐".repeat(40);+ const fit = fitQueryToWindow(query, "", window);+ expect(fit.truncated).toBe(true);+ // A lone high surrogate would round-trip as U+FFFD.+ expect(fit.text.length % 2).toBe(0);+ expect(fit.text).toBe("๐".repeat([...fit.text].length));+ expect(Buffer.from(fit.text, "utf8").toString("utf8")).toBe(fit.text);+ }+});++test("a prefix that alone fills the window gives an empty text, truncated", () => {+ const prefix = "an instruction prefix far longer than the window allows: ";+ const fit = fitQueryToWindow("the actual question", prefix, 4);+ expect(fit.text).toBe("");+ expect(fit.truncated).toBe(true);+ // Nothing is sent, so nothing is counted.+ expect(fit.sentTokens).toBe(0);+});++test("sentTokens counts the prefix, with the shared spend estimator", () => {+ const uncut = fitQueryToWindow("hello world", PREFIX, null);+ expect(uncut.sentTokens).toBe(estimateTokens([PREFIX + "hello world"]));+ expect(uncut.sentTokens).toBeGreaterThan(estimateTokens(["hello world"]));+ const cut = fitQueryToWindow("abcdefghij".repeat(20), PREFIX, 16);+ expect(cut.sentTokens).toBe(estimateTokens([PREFIX + cut.text]));+});++// โโ task 3: the reach and price gate โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++/** A model string outside both the price table and the preset table. */+const UNPRICED_MODEL = "acme/custom-embed-9000";++function cfg(semantic: Partial<ResolvedEmbeddingConfig> = {}): ResolvedSearchConfig {+ return makeConfig({+ vault: "/vault-never-read",+ dbPath: "/index-never-opened.db",+ semantic: {+ enabled: true,+ provider: "openai-compat",+ baseUrl: "https://embeddings.invalid/v1",+ model: UNPRICED_MODEL,+ apiKey: FAKE_PROVIDER_KEY,+ dimension: 4,+ costGateUsd: 1,+ ...semantic,+ },+ });+}++test("a remote caller under a positive gate on an unpriced model is refused, naming the model", () => {+ const result = prepareQueryEmbed(cfg(), "what did I decide", TRANSPORT_REACH.remote);+ expect(result).toEqual({+ kind: "refused",+ code: "EMBEDDING_COST_UNPRICED",+ model: UNPRICED_MODEL,+ });+});++test("an omitted reach is remote, as everywhere else", () => {+ expect(prepareQueryEmbed(cfg(), "what did I decide", undefined).kind).toBe("refused");+});++test("a local caller under a positive gate on an unpriced model is ready", () => {+ const result = prepareQueryEmbed(cfg(), "what did I decide", TRANSPORT_REACH.local);+ expect(result.kind).toBe("ready");+ if (result.kind !== "ready") throw new Error("narrowed wrong");+ expect(result.quote.source).toBe(EMBEDDING_PRICE_SOURCE.unknown);+});++test("a remote caller under a zero gate is ready", () => {+ expect(prepareQueryEmbed(cfg({ costGateUsd: 0 }), "q", TRANSPORT_REACH.remote).kind).toBe(+ "ready",+ );+});++test("a remote caller on an operator-priced model is ready", () => {+ const result = prepareQueryEmbed(+ cfg({ priceOverride: { model: UNPRICED_MODEL, usdPerMtok: 0 } }),+ "q",+ TRANSPORT_REACH.remote,+ );+ expect(result.kind).toBe("ready");+ if (result.kind !== "ready") throw new Error("narrowed wrong");+ expect(result.quote).toEqual({ usdPerMtok: 0, source: EMBEDDING_PRICE_SOURCE.operator });+});++test("the offline local embedder is ready: its builtin price is zero", () => {+ const result = prepareQueryEmbed(+ cfg({ provider: "local", model: LOCAL_EMBEDDING_MODEL, baseUrl: null, apiKey: null }),+ "q",+ TRANSPORT_REACH.remote,+ );+ expect(result.kind).toBe("ready");+ if (result.kind !== "ready") throw new Error("narrowed wrong");+ expect(result.quote.source).toBe(EMBEDDING_PRICE_SOURCE.builtin);+ expect(result.model).toBe(LOCAL_EMBEDDING_MODEL);+ expect(result.windowTokens).toBeNull();+});++test("the ready result carries the fitted text, the window and the quote", () => {+ const query = "abcdefghij".repeat(40);+ const config = cfg({ costGateUsd: 0, inputWindowTokens: 16, queryPrefix: "query: " });+ const result = prepareQueryEmbed(config, query, TRANSPORT_REACH.remote);+ expect(result.kind).toBe("ready");+ if (result.kind !== "ready") throw new Error("narrowed wrong");+ const fit = fitQueryToWindow(query, "query: ", 16);+ expect(result.text).toBe(fit.text);+ expect(result.truncated).toBe(true);+ expect(result.sentTokens).toBe(fit.sentTokens);+ expect(result.windowTokens).toBe(16);+ expect(result.model).toBe(UNPRICED_MODEL);+ expect(result.quote.source).toBe(EMBEDDING_PRICE_SOURCE.unknown);+});++test("the fit charges the prefix the backend sends, not the one configured", () => {+ const query = "abcdefghij".repeat(40);+ const config = cfg({+ provider: "zeroentropy",+ costGateUsd: 0,+ inputWindowTokens: 16,+ queryPrefix: "query: ",+ });+ const result = prepareQueryEmbed(config, query, TRANSPORT_REACH.local);+ if (result.kind !== "ready") throw new Error("narrowed wrong");+ expect(result.text).toBe(fitQueryToWindow(query, "", 16).text);+});++test("a curated model is fitted to its declared window with no operator key", () => {+ const query = "word ".repeat(2000);+ const result = prepareQueryEmbed(+ cfg({ model: RECOMMENDED_EMBEDDING_MODEL, costGateUsd: 0 }),+ query,+ TRANSPORT_REACH.local,+ );+ if (result.kind !== "ready") throw new Error("narrowed wrong");+ expect(result.truncated).toBe(true);+ expect(result.windowTokens).toBeGreaterThan(0);+});++test("the gateway constructs no provider: it is pure over config", () => {+ // A config no provider can be built from: makeProvider throws on it.+ const unbuildable = cfg({ baseUrl: null, apiKey: null, costGateUsd: 0 });+ expect(() => makeProvider(unbuildable.semantic)).toThrow();+ const result = prepareQueryEmbed(unbuildable, "q", TRANSPORT_REACH.remote);+ expect(result instanceof Promise).toBe(false);+ expect(result.kind).toBe("ready");+});++test("the refusal sentence names the model, the gate key and the price pair", () => {+ const result = prepareQueryEmbed(cfg(), "q", TRANSPORT_REACH.remote);+ if (result.kind !== "refused") throw new Error("narrowed wrong");+ const message = queryEmbedRefusalMessage(result);+ for (const needle of [+ UNPRICED_MODEL,+ COST_GATE_KEY,+ EMBEDDING_PRICE_MODEL_KEY,+ EMBEDDING_PRICE_RATE_KEY,+ ]) {+ expect(message).toContain(needle);+ }+});++test("the refusal sentence says the gate is on, never its amount", () => {+ const result = prepareQueryEmbed(cfg({ costGateUsd: 7.25 }), "q", TRANSPORT_REACH.remote);+ if (result.kind !== "refused") throw new Error("narrowed wrong");+ const message = queryEmbedRefusalMessage(result);+ expect(message).toContain(`${COST_GATE_KEY} is positive`);+ expect(message).not.toContain(formatEstimatedUsd(7.25));+ expect(message).not.toContain("7.25");+});++// โโ the shared sentences for a cut โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++test("a prefix that fills the window is an empty fit, cut to that window", () => {+ const config = cfg({ costGateUsd: 0, inputWindowTokens: 1, queryPrefix: "query: " });+ const result = prepareQueryEmbed(config, "the actual question", TRANSPORT_REACH.remote);+ if (result.kind !== "ready") throw new Error("narrowed wrong");+ expect(result.text).toBe("");+ expect(result.truncated).toBe(true);+ expect(result.emptyFit).toBe(true);+ expect(result.windowTokens).toBe(1);+});++test("a cut that keeps some of the query is not an empty fit", () => {+ const config = cfg({ costGateUsd: 0, inputWindowTokens: 16, queryPrefix: "query: " });+ const result = prepareQueryEmbed(config, "abcdefghij".repeat(40), TRANSPORT_REACH.remote);+ if (result.kind !== "ready") throw new Error("narrowed wrong");+ expect(result.truncated).toBe(true);+ expect(result.emptyFit).toBe(false);+});++test("an empty query is sent as it came, not reported as an empty fit", () => {+ const config = cfg({ costGateUsd: 0, inputWindowTokens: 16, queryPrefix: "query: " });+ const result = prepareQueryEmbed(config, "", TRANSPORT_REACH.remote);+ if (result.kind !== "ready") throw new Error("narrowed wrong");+ expect(result.truncated).toBe(false);+ expect(result.emptyFit).toBe(false);+});++test("the empty-fit sentence names the window and the key that raises it", () => {+ const config = cfg({ costGateUsd: 0, inputWindowTokens: 3, queryPrefix: "a long prefix: " });+ const result = prepareQueryEmbed(config, "q", TRANSPORT_REACH.remote);+ if (result.kind !== "ready" || !result.truncated) throw new Error("narrowed wrong");+ const message = queryEmbedEmptyFitMessage(result);+ expect(message).toContain("3-token");+ expect(message).toContain(INPUT_WINDOW_TOKENS_KEY);+});++test("the cut sentence names the window, what was kept and the key that raises it", () => {+ const query = "abcdefghij".repeat(40);+ const config = cfg({ costGateUsd: 0, inputWindowTokens: 16, queryPrefix: "query: " });+ const result = prepareQueryEmbed(config, query, TRANSPORT_REACH.remote);+ if (result.kind !== "ready" || !result.truncated) throw new Error("narrowed wrong");+ const message = queryEmbedCutMessage(result, query);+ expect(message).toContain("16-token");+ expect(message).toContain(`${[...result.text].length} of ${[...query].length} code point(s)`);+ expect(message).toContain(INPUT_WINDOW_TOKENS_KEY);+});diff --git a/tests/core/search/semantic-phase-spend-gate.test.ts b/tests/core/search/semantic-phase-spend-gate.test.tsnew file mode 100644index 00000000..b2a76015--- /dev/null+++ b/tests/core/search/semantic-phase-spend-gate.test.ts@@ -0,0 +1,443 @@+/**+ * The search lane's query embed goes through the query-embed gateway+ * (honest-query-embed-and-safe-upgrades, task 4).+ *+ * Before this, `runSemanticPhase` embedded every query with no reach and+ * no price check, so a remote caller of `brain_search` (and every tool+ * that reaches the lane) spent the operator's money on a model nobody+ * priced, despite a positive `embedding_cost_gate_usd`. The query was+ * also sent at any length, so a model with a small window either+ * described a prefix silently or refused the request.+ *+ * Every assertion counts requests on a loopback stub: "refused" means+ * nothing reached the wire, not that a response was ignored.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { TRANSPORT_REACH } from "../../../src/core/graph/transport-reach.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";+import { COST_GATE_KEY, formatEstimatedUsd } from "../../../src/core/search/embedding-spend.ts";+import {+ fitQueryToWindow,+ prepareQueryEmbed,+ queryEmbedCutMessage,+ queryEmbedEmptyFitMessage,+} from "../../../src/core/search/embeddings/query-embed.ts";+import { INPUT_WINDOW_TOKENS_KEY } from "../../../src/core/search/embeddings/presets.ts";+import {+ EMBEDDING_PRICE_MODEL_KEY,+ EMBEDDING_PRICE_RATE_KEY,+} from "../../../src/core/search/embeddings/pricing.ts";+import { resolveSearchConfig } from "../../../src/core/search/index.ts";+import { indexVault } from "../../../src/core/search/indexer.ts";+import { runSemanticLane } from "../../../src/core/search/pipeline/semantic-lane.ts";+import {+ RETRIEVAL_DEGRADATION,+ describeRetrievalDegradation,+ RETRIEVAL_DEGRADATION_CODES,+ semanticLaneMissing,+} from "../../../src/core/search/retrieval-trail.ts";+import { search } from "../../../src/core/search/search.ts";+import { runSemanticPhase } from "../../../src/core/search/semantic-phase.ts";+import type { Store } from "../../../src/core/search/store.ts";+import { SearchError } from "../../../src/core/search/types.ts";+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../../src/mcp/index.ts";+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";+import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";+import { sqliteVecLoadable } from "../../helpers/sqlite-vec.ts";++const MODEL = "fake-model";+const GATE_USD = 1;++let server: FakeHttp;+let inputs: string[][];++beforeEach(async () => {+ server = await startFakeHttp();+ inputs = [];+ server.setHandler((req) => {+ const body = (req.body ?? {}) as { input?: string[] };+ const batch = Array.isArray(body.input) ? body.input : [];+ inputs.push(batch);+ return {+ status: 200,+ body: {+ data: batch.map((text, index) => ({+ object: "embedding",+ embedding: [text.length, index, 1, 1],+ index,+ })),+ model: MODEL,+ },+ };+ });+});++afterEach(async () => {+ await server.close();+});++/** Enough surface for the phase and the lane to reach the embed. */+function fakeStore(): Store {+ return {+ counts: () => ({ documents: 1, chunks: 1, embeddings: 1, staleEmbeddings: 0 }),+ vecLoaded: () => true,+ semanticTopK: () => [],+ embeddingAbiMismatches: () => [],+ } as unknown as Store;+}++function gatedConfig(semantic: Record<string, unknown> = {}) {+ return makeConfig({+ vault: "/tmp/does-not-matter",+ dbPath: "/tmp/does-not-matter/db.sqlite",+ semantic: {+ enabled: true,+ provider: "openai-compat",+ baseUrl: server.url,+ model: MODEL,+ apiKey: FAKE_PROVIDER_KEY,+ dimension: 4,+ maxRetries: 1,+ costGateUsd: GATE_USD,+ ...semantic,+ },+ });+}++function phaseOpts(explicit: boolean, reach?: "local" | "remote") {+ return {+ limit: 10,+ pathPrefix: undefined,+ explicit,+ ...(reach !== undefined ? { transportReach: TRANSPORT_REACH[reach] } : {}),+ };+}++function codes(degraded: ReadonlyArray<{ code: string }>): string[] {+ return degraded.map((d) => d.code);+}++// โโ the vocabulary โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++test("the three new codes are members of the closed list and carry a sentence", () => {+ for (const code of [+ RETRIEVAL_DEGRADATION.semanticCostUnpriced,+ RETRIEVAL_DEGRADATION.semanticQueryTruncated,+ RETRIEVAL_DEGRADATION.semanticQueryEmptyFit,+ ]) {+ expect(RETRIEVAL_DEGRADATION_CODES).toContain(code);+ expect(describeRetrievalDegradation(code).length).toBeGreaterThan(0);+ }+ expect(RETRIEVAL_DEGRADATION.semanticCostUnpriced).toBe("semantic-cost-unpriced");+ expect(RETRIEVAL_DEGRADATION.semanticQueryTruncated).toBe("semantic-query-truncated");+ expect(RETRIEVAL_DEGRADATION.semanticQueryEmptyFit).toBe("semantic-query-empty-fit");+});++// โโ the phase โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++test("an implicit remote query under a positive gate and an unpriced model sends nothing", async () => {+ const out = await runSemanticPhase(fakeStore(), gatedConfig(), "q", phaseOpts(false, "remote"));+ expect(server.callCount()).toBe(0);+ expect(out.attempted).toBe(false);+ expect(codes(out.degraded)).toEqual([RETRIEVAL_DEGRADATION.semanticCostUnpriced]);+ expect(out.warnings).toHaveLength(1);+ for (const part of [MODEL, COST_GATE_KEY, EMBEDDING_PRICE_MODEL_KEY, EMBEDDING_PRICE_RATE_KEY]) {+ expect(out.warnings[0]).toContain(part);+ }+ expect(out.warnings.some((w) => w.includes(formatEstimatedUsd(GATE_USD)))).toBe(false);+});++test("an omitted reach is remote, so the gate refuses it too", async () => {+ const out = await runSemanticPhase(fakeStore(), gatedConfig(), "q", phaseOpts(false));+ expect(server.callCount()).toBe(0);+ expect(codes(out.degraded)).toEqual([RETRIEVAL_DEGRADATION.semanticCostUnpriced]);+});++test("an explicit remote query throws EMBEDDING_COST_UNPRICED naming the levers", async () => {+ let err: unknown = null;+ try {+ await runSemanticPhase(fakeStore(), gatedConfig(), "q", phaseOpts(true, "remote"));+ } catch (e) {+ err = e;+ }+ expect(server.callCount()).toBe(0);+ expect(err).toBeInstanceOf(SearchError);+ const e = err as SearchError;+ expect(e.code).toBe("EMBEDDING_COST_UNPRICED");+ for (const part of [MODEL, COST_GATE_KEY, EMBEDDING_PRICE_MODEL_KEY, EMBEDDING_PRICE_RATE_KEY]) {+ expect(e.message).toContain(part);+ }+ // The operator's budget is not the remote caller's business.+ expect(e.message).not.toContain(formatEstimatedUsd(GATE_USD));+});++test("a local query under the same gate embeds once", async () => {+ const out = await runSemanticPhase(fakeStore(), gatedConfig(), "q", phaseOpts(true, "local"));+ expect(server.callCount()).toBe(1);+ expect(out.attempted).toBe(true);+ expect(out.degraded).toEqual([]);+});++test("a remote query on an operator-priced model embeds once", async () => {+ const config = gatedConfig({ priceOverride: { model: MODEL, usdPerMtok: 0 } });+ const out = await runSemanticPhase(fakeStore(), config, "q", phaseOpts(true, "remote"));+ expect(server.callCount()).toBe(1);+ expect(out.attempted).toBe(true);+});++test("an over-window query embeds the cut text and names the window", async () => {+ const window = 8;+ const query = "abcdefghij".repeat(20);+ const config = gatedConfig({ costGateUsd: 0, inputWindowTokens: window });+ const out = await runSemanticPhase(fakeStore(), config, query, phaseOpts(false, "remote"));+ expect(server.callCount()).toBe(1);+ const expected = fitQueryToWindow(query, "", window).text;+ expect(expected.length).toBeLessThan(query.length);+ expect(inputs).toEqual([[expected]]);+ expect(out.attempted).toBe(true);+ expect(out.degraded).toEqual([+ { code: RETRIEVAL_DEGRADATION.semanticQueryTruncated, detail: { windowTokens: window } },+ ]);+ const prepared = prepareQueryEmbed(config, query, TRANSPORT_REACH.remote);+ if (prepared.kind !== "ready" || !prepared.truncated) throw new Error("narrowed wrong");+ expect(out.warnings).toEqual([queryEmbedCutMessage(prepared, query)]);+ expect(out.warnings[0]).toContain(INPUT_WINDOW_TOKENS_KEY);+});++test("a query that fits the window is sent whole with no warning", async () => {+ const config = gatedConfig({ costGateUsd: 0, inputWindowTokens: 512 });+ const out = await runSemanticPhase(fakeStore(), config, "short", phaseOpts(false, "remote"));+ expect(inputs).toEqual([["short"]]);+ expect(out.warnings).toEqual([]);+ expect(out.degraded).toEqual([]);+});++test("a prefix that fills the window is never embedded", async () => {+ const config = gatedConfig({+ costGateUsd: 0,+ inputWindowTokens: 1,+ queryPrefix: "a long instruction prefix: ",+ });+ const out = await runSemanticPhase(fakeStore(), config, "q", phaseOpts(false, "remote"));+ expect(server.callCount()).toBe(0);+ expect(out.attempted).toBe(false);+ // Its own code, not the cut's: the lane did not run, so it counts as a stop.+ expect(out.degraded).toEqual([+ { code: RETRIEVAL_DEGRADATION.semanticQueryEmptyFit, detail: { windowTokens: 1 } },+ ]);+ const prepared = prepareQueryEmbed(config, "q", TRANSPORT_REACH.remote);+ if (prepared.kind !== "ready" || !prepared.truncated) throw new Error("narrowed wrong");+ expect(out.warnings).toEqual([queryEmbedEmptyFitMessage(prepared)]);++ let err: unknown = null;+ try {+ await runSemanticPhase(fakeStore(), config, "q", phaseOpts(true, "remote"));+ } catch (e) {+ err = e;+ }+ expect(server.callCount()).toBe(0);+ expect((err as SearchError).code).toBe("INVALID_INPUT");+ expect((err as SearchError).message).toBe(queryEmbedEmptyFitMessage(prepared));+});++// โโ the lane โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++function laneInput(config: ReturnType<typeof gatedConfig>, query: string, reach?: "local") {+ return {+ store: fakeStore(),+ config,+ policy: { explicit: false, wantSemantic: true },+ query,+ semanticLaneQuery: null,+ limit: 10,+ pathPrefix: undefined,+ keywordHitCount: 1,+ ...(reach !== undefined ? { transportReach: TRANSPORT_REACH[reach] } : {}),+ };+}++test("the lane forwards reach: a refused remote lane degrades the hybrid answer", async () => {+ const out = await runSemanticLane(laneInput(gatedConfig(), "q"));+ expect(server.callCount()).toBe(0);+ expect(codes(out.degraded)).toEqual([+ RETRIEVAL_DEGRADATION.semanticCostUnpriced,+ RETRIEVAL_DEGRADATION.hybridDegraded,+ ]);+});++test("the lane forwards reach: a local lane embeds", async () => {+ const out = await runSemanticLane(laneInput(gatedConfig(), "q", "local"));+ expect(server.callCount()).toBe(1);+ expect(out.attempted).toBe(true);+});++test("a cut lane still ran, so the hybrid answer is not degraded", async () => {+ const config = gatedConfig({ costGateUsd: 0, inputWindowTokens: 8 });+ const out = await runSemanticLane(laneInput(config, "abcdefghij".repeat(20)));+ expect(codes(out.degraded)).toEqual([RETRIEVAL_DEGRADATION.semanticQueryTruncated]);+});++test("an empty-fit lane with no keyword hit still reads as a stopped lane", async () => {+ const config = gatedConfig({+ costGateUsd: 0,+ inputWindowTokens: 1,+ queryPrefix: "a long instruction prefix: ",+ });+ const out = await runSemanticLane({ ...laneInput(config, "q"), keywordHitCount: 0 });+ expect(server.callCount()).toBe(0);+ expect(codes(out.degraded)).toEqual([RETRIEVAL_DEGRADATION.semanticQueryEmptyFit]);+ expect(semanticLaneMissing(out.degraded.map((d) => d.code))).toBe(true);+});++// โโ search() over a real index โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++const NOTE = "# Fox\n\nThe quick brown fox jumps over the lazy dog.";++async function indexedSearchConfig(costGateUsd: number) {+ const v = createTempVault("spend-gate");+ writeMd(v.vault, "Notes/fox.md", NOTE);+ const config = gatedConfig({ costGateUsd: 0 });+ const indexed = { ...config, vault: v.vault, dbPath: v.dbPath };+ await indexVault(indexed, { embeddings: true });+ return {+ config: { ...indexed, semantic: { ...indexed.semantic, costGateUsd } },+ cleanup: v.cleanup,+ };+}++test.skipIf(!sqliteVecLoadable())(+ "search() threads reach: remote implicit serves keyword results without an embed",+ async () => {+ const { config, cleanup } = await indexedSearchConfig(GATE_USD);+ try {+ const before = server.callCount();+ const out = await search(config, { query: "fox", limit: 5 });+ expect(server.callCount()).toBe(before);+ expect(out.results.length).toBeGreaterThan(0);+ const trail = codes(out.retrievalTrail?.degraded ?? []);+ expect(trail).toContain(RETRIEVAL_DEGRADATION.semanticCostUnpriced);+ expect(trail).toContain(RETRIEVAL_DEGRADATION.hybridDegraded);+ } finally {+ cleanup();+ }+ },+);++test.skipIf(!sqliteVecLoadable())(+ "search() threads reach: remote explicit throws before the embed",+ async () => {+ const { config, cleanup } = await indexedSearchConfig(GATE_USD);+ try {+ const before = server.callCount();+ let err: unknown = null;+ try {+ await search(config, { query: "fox", limit: 5, semantic: true });+ } catch (e) {+ err = e;+ }+ expect(server.callCount()).toBe(before);+ expect((err as SearchError).code).toBe("EMBEDDING_COST_UNPRICED");+ } finally {+ cleanup();+ }+ },+);++test.skipIf(!sqliteVecLoadable())(+ "search() threads reach: a local search embeds once",+ async () => {+ const { config, cleanup } = await indexedSearchConfig(GATE_USD);+ try {+ const before = server.callCount();+ await search(config, {+ query: "fox",+ limit: 5,+ semantic: true,+ transportReach: TRANSPORT_REACH.local,+ });+ expect(server.callCount()).toBe(before + 1);+ } finally {+ cleanup();+ }+ },+);++// โโ brain_search over MCP โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++let tmp: string;+let configPath: string;++async function mcpVault(): Promise<string> {+ tmp = mkdtempSync(join(tmpdir(), "o2b-spend-gate-"));+ const vault = join(tmp, "vault");+ mkdirSync(join(vault, "Notes"), { recursive: true });+ writeFileSync(join(vault, "Notes", "fox.md"), NOTE);+ configPath = join(tmp, "config.yaml");+ const lines = (gate: number) =>+ [+ `vault: ${vault}`,+ "agent_name: claude",+ "search_semantic_enabled: true",+ "embedding_provider: openai-compat",+ `embedding_base_url: ${server.url}`,+ `embedding_model: ${MODEL}`,+ `embedding_api_key: ${FAKE_PROVIDER_KEY}`,+ "embedding_dimension: 4",+ `${COST_GATE_KEY}: ${gate}`,+ "",+ ].join("\n");+ atomicWriteFileSync(configPath, lines(0));+ await indexVault(resolveSearchConfig({ vault, configPath }), { embeddings: true });+ atomicWriteFileSync(configPath, lines(GATE_USD));+ return vault;+}++async function mcpSearch(vault: string, reach: "local" | "remote", semantic: boolean) {+ const mcp = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH[reach] });+ await mcp.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: "spend-gate-test", version: "0" },+ },+ });+ await mcp.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });+ return (await mcp.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 2,+ method: "tools/call",+ params: { name: "brain_search", arguments: { query: "fox", limit: 5, semantic } },+ })) as { error?: { data?: { code?: string } } };+}++test.skipIf(!sqliteVecLoadable())(+ "brain_search over a remote server refuses before the embed; a local one embeds",+ async () => {+ const vault = await mcpVault();+ const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;+ try {+ const before = server.callCount();+ const remote = await mcpSearch(vault, "remote", true);+ expect(server.callCount()).toBe(before);+ expect(remote.error?.data?.code).toBe("EMBEDDING_COST_UNPRICED");++ const local = await mcpSearch(vault, "local", true);+ expect(local.error).toBeUndefined();+ expect(server.callCount()).toBe(before + 1);+ } finally {+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;+ rmSync(tmp, { recursive: true, force: true });+ }+ },+);diff --git a/tests/core/search/spend-gate-disclosure.test.ts b/tests/core/search/spend-gate-disclosure.test.tsnew file mode 100644index 00000000..82ab1971--- /dev/null+++ b/tests/core/search/spend-gate-disclosure.test.ts@@ -0,0 +1,317 @@+/**+ * What the spend gate's keyword-only answer must not turn into+ * (honest-query-embed-and-safe-upgrades, security audit round 1).+ *+ * The query-embed gateway refuses an unpriced embed for a caller that is+ * not local and serves the keyword lane instead, disclosed on the trail.+ * That answer is honest for the one request that received it. It is not+ * honest as a cached answer the operator's later price declaration cannot+ * reach, as a learned-weights signal, or as a benchmark score a tuning+ * sweep saves as the vault's parameters.+ *+ * Every refused embed is counted on a loopback stub: the gated runs below+ * reach nothing on the wire.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { existsSync } from "node:fs";++import { TRANSPORT_REACH } from "../../../src/core/graph/transport-reach.ts";+import {+ parseRecallBenchmarkDataset,+ runRecallBenchmark,+} from "../../../src/core/search/benchmark.ts";+import { COST_GATE_KEY } from "../../../src/core/search/embedding-spend.ts";+import { indexVault } from "../../../src/core/search/indexer.ts";+import { RETRIEVAL_DEGRADATION } from "../../../src/core/search/retrieval-trail.ts";+import { search } from "../../../src/core/search/search.ts";+import { tuneRecall } from "../../../src/core/search/tuning.ts";+import { tuningPath } from "../../../src/core/search/tuning-store.ts";+import { SearchError, type ResolvedSearchConfig } from "../../../src/core/search/types.ts";+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";+import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";+import { sqliteVecLoadable } from "../../helpers/sqlite-vec.ts";++const MODEL = "fake-model";+const GATE_USD = 1;+const NOTE = "# Fox\n\nThe quick brown fox jumps over the lazy dog.";+const NOW = new Date("2026-10-06T12:00:00Z");++let server: FakeHttp;+let cleanup: () => void = () => {};++beforeEach(async () => {+ server = await startFakeHttp();+ server.setHandler((req) => {+ const body = (req.body ?? {}) as { input?: string[] };+ const batch = Array.isArray(body.input) ? body.input : [];+ return {+ status: 200,+ body: {+ data: batch.map((text, index) => ({+ object: "embedding",+ embedding: [text.length, index, 1, 1],+ index,+ })),+ model: MODEL,+ },+ };+ });+});++afterEach(async () => {+ cleanup();+ cleanup = () => {};+ await server.close();+});++/**+ * An index built with embeddings (no gate while indexing), then served+ * under a positive gate on an unpriced model with the query cache on.+ */+async function gatedIndex(): Promise<ResolvedSearchConfig> {+ const v = createTempVault("spend-gate-disclosure");+ cleanup = v.cleanup;+ writeMd(v.vault, "Notes/fox.md", NOTE);+ const config = makeConfig({+ vault: v.vault,+ dbPath: v.dbPath,+ cacheEnabled: true,+ semantic: {+ enabled: true,+ provider: "openai-compat",+ baseUrl: server.url,+ model: MODEL,+ apiKey: FAKE_PROVIDER_KEY,+ dimension: 4,+ maxRetries: 1,+ costGateUsd: 0,+ },+ });+ await indexVault(config, { embeddings: true });+ return { ...config, semantic: { ...config.semantic, costGateUsd: GATE_USD } };+}++function priced(config: ResolvedSearchConfig): ResolvedSearchConfig {+ return {+ ...config,+ semantic: { ...config.semantic, priceOverride: { model: MODEL, usdPerMtok: 0 } },+ };+}++const DATASET = parseRecallBenchmarkDataset({+ queries: [{ id: "fox", query: "fox", expected: ["Notes/fox.md"] }],+});++// โโ the query cache โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++test.skipIf(!sqliteVecLoadable())(+ "a gated keyword-only answer is served and discloses the gate",+ async () => {+ const config = await gatedIndex();+ const out = await search(config, { query: "fox", limit: 5 });+ expect(out.retrievalTrail?.degraded.map((d) => d.code)).toContain(+ RETRIEVAL_DEGRADATION.semanticCostUnpriced,+ );+ expect(out.results.length).toBeGreaterThan(0);+ },+);++test.skipIf(!sqliteVecLoadable())(+ "a gated answer is not cached: a price declared afterwards reaches the next remote query",+ async () => {+ const config = await gatedIndex();+ await search(config, { query: "fox", limit: 5 });+ const before = server.callCount();+ const out = await search(priced(config), { query: "fox", limit: 5 });+ expect(server.callCount()).toBe(before + 1);+ expect(out.retrievalTrail?.degraded.map((d) => d.code) ?? []).not.toContain(+ RETRIEVAL_DEGRADATION.semanticCostUnpriced,+ );+ },+);++test.skipIf(!sqliteVecLoadable())("an ungated local answer is still cached", async () => {+ const config = await gatedIndex();+ const local = { query: "fox", limit: 5, transportReach: TRANSPORT_REACH.local };+ await search(config, local);+ const before = server.callCount();+ await search(config, local);+ expect(server.callCount()).toBe(before);+});++function windowed(config: ResolvedSearchConfig, inputWindowTokens: number): ResolvedSearchConfig {+ return { ...config, semantic: { ...config.semantic, inputWindowTokens } };+}++/** A curated model whose window the table declares (512 tokens), indexed with the cache on. */+const E5_MODEL = "intfloat/multilingual-e5-small";++async function e5Index(): Promise<ResolvedSearchConfig> {+ const v = createTempVault("spend-gate-e5");+ cleanup = v.cleanup;+ writeMd(v.vault, "Notes/fox.md", NOTE);+ const config = makeConfig({+ vault: v.vault,+ dbPath: v.dbPath,+ cacheEnabled: true,+ semantic: {+ enabled: true,+ provider: "openai-compat",+ baseUrl: server.url,+ model: E5_MODEL,+ apiKey: FAKE_PROVIDER_KEY,+ dimension: 4,+ maxRetries: 1,+ costGateUsd: 0,+ queryPrefix: "query: ",+ },+ });+ await indexVault(config, { embeddings: true });+ return config;+}++const LONG_QUERY = Array.from({ length: 2000 }, () => "fox").join(" ");++function codesOf(out: Awaited<ReturnType<typeof search>>): string[] {+ return out.retrievalTrail?.degraded.map((d) => d.code) ?? [];+}++test.skipIf(!sqliteVecLoadable())(+ "a query cut to a curated window is cached under that window",+ async () => {+ const config = await e5Index();+ const local = { query: LONG_QUERY, limit: 5, transportReach: TRANSPORT_REACH.local };+ const before = server.callCount();+ const cut = await search(config, local);+ expect(server.callCount()).toBe(before + 1);+ expect(codesOf(cut)).toContain(RETRIEVAL_DEGRADATION.semanticQueryTruncated);+ expect(cut.results.length).toBeGreaterThan(0);+ // The same cut query under the same window is served from the cache.+ const again = await search(config, local);+ expect(server.callCount()).toBe(before + 1);+ expect(codesOf(again)).toContain(RETRIEVAL_DEGRADATION.semanticQueryTruncated);+ },+);++test.skipIf(!sqliteVecLoadable())(+ "a declared or changed window re-keys the cut answer",+ async () => {+ const config = await e5Index();+ const local = { query: LONG_QUERY, limit: 5, transportReach: TRANSPORT_REACH.local };+ await search(config, local);+ // A wider window declared afterwards reaches the next identical query.+ const before = server.callCount();+ const whole = await search(windowed(config, 1_000_000), local);+ expect(server.callCount()).toBe(before + 1);+ expect(codesOf(whole)).not.toContain(RETRIEVAL_DEGRADATION.semanticQueryTruncated);+ // A narrower one is a different cut, so it is computed again too.+ const narrower = await search(windowed(config, 64), local);+ expect(server.callCount()).toBe(before + 2);+ expect(codesOf(narrower)).toContain(RETRIEVAL_DEGRADATION.semanticQueryTruncated);+ },+);++test.skipIf(!sqliteVecLoadable())("a changed query prefix re-keys the cut answer", async () => {+ const config = await e5Index();+ const local = { query: LONG_QUERY, limit: 5, transportReach: TRANSPORT_REACH.local };+ await search(config, local);+ const before = server.callCount();+ await search(+ { ...config, semantic: { ...config.semantic, queryPrefix: "search_query: " } },+ local,+ );+ expect(server.callCount()).toBe(before + 1);+});++// โโ the benchmark โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++test.skipIf(!sqliteVecLoadable())(+ "a gated benchmark discloses the degradation per query and in aggregate",+ async () => {+ const config = await gatedIndex();+ const report = await runRecallBenchmark(config, DATASET, {+ transportReach: TRANSPORT_REACH.remote,+ });+ expect(report.degraded).toContain(RETRIEVAL_DEGRADATION.semanticCostUnpriced);+ expect(report.degraded).toContain(RETRIEVAL_DEGRADATION.hybridDegraded);+ expect(report.perQuery[0]?.degraded).toContain(RETRIEVAL_DEGRADATION.semanticCostUnpriced);+ },+);++test.skipIf(!sqliteVecLoadable())(+ "an ungated benchmark reports no degradation and adds no per-query field",+ async () => {+ const config = await gatedIndex();+ const report = await runRecallBenchmark(config, DATASET, {+ transportReach: TRANSPORT_REACH.local,+ });+ expect(report.degraded).toEqual([]);+ expect(report.perQuery[0]).not.toHaveProperty("degraded");+ },+);++// โโ the tuning sweep โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++const GRID = [{ poolMultiplier: 3, traversalDepth: 1, learnedWeights: false, expansion: false }];++test.skipIf(!sqliteVecLoadable())(+ "a tuning sweep measured with a gated lane refuses to save its winner",+ async () => {+ const config = await gatedIndex();+ let err: unknown = null;+ try {+ await tuneRecall(config, DATASET, {+ grid: GRID,+ now: NOW,+ transportReach: TRANSPORT_REACH.remote,+ });+ } catch (e) {+ err = e;+ }+ expect(err).toBeInstanceOf(SearchError);+ expect((err as SearchError).code).toBe("EMBEDDING_COST_UNPRICED");+ expect((err as SearchError).message).toContain(COST_GATE_KEY);+ expect(existsSync(tuningPath(config.vault))).toBe(false);+ },+);++test.skipIf(!sqliteVecLoadable())(+ "a tuning sweep measured with the provider unreachable refuses to save its winner",+ async () => {+ const config = await gatedIndex();+ server.setHandler(() => ({ status: 500, body: { error: { message: "down" } } }));+ let err: unknown = null;+ try {+ await tuneRecall(config, DATASET, {+ grid: GRID,+ now: NOW,+ transportReach: TRANSPORT_REACH.local,+ });+ } catch (e) {+ err = e;+ }+ expect(err).toBeInstanceOf(SearchError);+ expect((err as SearchError).code).toBe("EMBEDDING_PROVIDER_HTTP");+ expect((err as SearchError).message).toContain(+ RETRIEVAL_DEGRADATION.semanticProviderUnavailable,+ );+ expect(existsSync(tuningPath(config.vault))).toBe(false);+ },+);++test.skipIf(!sqliteVecLoadable())(+ "an ungated tuning sweep saves its winner and reports no degradation",+ async () => {+ const config = await gatedIndex();+ const report = await tuneRecall(config, DATASET, {+ grid: GRID,+ now: NOW,+ transportReach: TRANSPORT_REACH.local,+ });+ expect(report.degraded).toEqual([]);+ expect(report.evaluated[0]?.degraded).toEqual([]);+ expect(existsSync(tuningPath(config.vault))).toBe(true);+ },+);diff --git a/tests/core/search/tuning-semantic-lane.test.ts b/tests/core/search/tuning-semantic-lane.test.tsnew file mode 100644index 00000000..f616dda1--- /dev/null+++ b/tests/core/search/tuning-semantic-lane.test.ts@@ -0,0 +1,187 @@+/**+ * A tuning sweep measured with the semantic lane missing never saves its+ * winner (honest-query-embed-and-safe-upgrades, security final).+ *+ * The refusal reads the one shared "semantic lane missing" predicate, so+ * every stop that leaves a hybrid caller keyword-only refuses, including+ * the composite deadline, which no lane-specific code names. A blocked+ * capability refuses with the code the explicit lane throws for the same+ * rung, so a missing credential is not reported as a disabled provider.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync } from "node:fs";++import { TRANSPORT_REACH } from "../../../src/core/graph/transport-reach.ts";+import { parseRecallBenchmarkDataset } from "../../../src/core/search/benchmark.ts";+import { INPUT_WINDOW_TOKENS_KEY } from "../../../src/core/search/embeddings/presets.ts";+import { indexVault } from "../../../src/core/search/indexer.ts";+import {+ RETRIEVAL_DEGRADATION,+ semanticLaneMissing,+} from "../../../src/core/search/retrieval-trail.ts";+import { tuneRecall } from "../../../src/core/search/tuning.ts";+import { tuningPath } from "../../../src/core/search/tuning-store.ts";+import { SearchError, type ResolvedSearchConfig } from "../../../src/core/search/types.ts";+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";+import { startFakeHttp, type FakeHttp, type FakeResponseSpec } from "../../helpers/fake-http.ts";+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";+import { sqliteVecLoadable } from "../../helpers/sqlite-vec.ts";++const MODEL = "fake-model";+const NOW = new Date("2026-10-06T12:00:00Z");+const GRID = [{ poolMultiplier: 3, traversalDepth: 1, learnedWeights: false, expansion: false }];+const DATASET = parseRecallBenchmarkDataset({+ queries: [{ id: "fox", query: "fox", expected: ["Notes/fox.md"] }],+});++let server: FakeHttp;+let cleanup: () => void = () => {};++beforeEach(async () => {+ server = await startFakeHttp();+ server.setHandler((req) => {+ const body = (req.body ?? {}) as { input?: string[] };+ const batch = Array.isArray(body.input) ? body.input : [];+ return {+ status: 200,+ body: {+ data: batch.map((text, index) => ({+ object: "embedding",+ embedding: [text.length, index, 1, 1],+ index,+ })),+ model: MODEL,+ },+ };+ });+});++afterEach(async () => {+ cleanup();+ cleanup = () => {};+ await server.close();+});++async function embeddedIndex(): Promise<ResolvedSearchConfig> {+ const v = createTempVault("tuning-semantic-lane");+ cleanup = v.cleanup;+ writeMd(v.vault, "Notes/fox.md", "# Fox\n\nThe quick brown fox jumps over the lazy dog.");+ const config = makeConfig({+ vault: v.vault,+ dbPath: v.dbPath,+ semantic: {+ enabled: true,+ provider: "openai-compat",+ baseUrl: server.url,+ model: MODEL,+ apiKey: FAKE_PROVIDER_KEY,+ dimension: 4,+ maxRetries: 1,+ costGateUsd: 0,+ },+ });+ await indexVault(config, { embeddings: true });+ return config;+}++async function refusal(config: ResolvedSearchConfig): Promise<SearchError> {+ let err: unknown = null;+ try {+ await tuneRecall(config, DATASET, {+ grid: GRID,+ now: NOW,+ transportReach: TRANSPORT_REACH.local,+ });+ } catch (e) {+ err = e;+ }+ expect(err).toBeInstanceOf(SearchError);+ return err as SearchError;+}++describe("semanticLaneMissing", () => {+ test("a hybrid caller served keyword-only is missing the lane", () => {+ expect(+ semanticLaneMissing([+ RETRIEVAL_DEGRADATION.hybridDeadlineExceeded,+ RETRIEVAL_DEGRADATION.hybridDegraded,+ ]),+ ).toBe(true);+ });++ test("a keyword-only-by-construction index or machine is not", () => {+ for (const code of [+ RETRIEVAL_DEGRADATION.semanticEmbeddingsAbsent,+ RETRIEVAL_DEGRADATION.semanticVecExtensionUnavailable,+ ]) {+ expect(semanticLaneMissing([code, RETRIEVAL_DEGRADATION.hybridDegraded])).toBe(false);+ }+ });++ test("a lane stop counts without the umbrella, which needs a keyword hit", () => {+ for (const code of [+ RETRIEVAL_DEGRADATION.semanticCapabilityBlocked,+ RETRIEVAL_DEGRADATION.semanticCostUnpriced,+ RETRIEVAL_DEGRADATION.semanticProviderUnavailable,+ RETRIEVAL_DEGRADATION.semanticEmptyQueryVector,+ RETRIEVAL_DEGRADATION.semanticQueryEmptyFit,+ ]) {+ expect(semanticLaneMissing([code])).toBe(true);+ }+ });++ test("a cut query or a clean trail is not", () => {+ expect(semanticLaneMissing([RETRIEVAL_DEGRADATION.semanticQueryTruncated])).toBe(false);+ expect(semanticLaneMissing([])).toBe(false);+ });+});++test.skipIf(!sqliteVecLoadable())(+ "a sweep the hybrid deadline cut refuses to save its winner",+ async () => {+ const config = await embeddedIndex();+ // The provider sleeps past the composite budget on every query embed.+ server.setHandler(() => new Promise<FakeResponseSpec>(() => {}));+ const err = await refusal({ ...config, hybridDeadlineMs: 200 });+ expect(err.message).toContain(RETRIEVAL_DEGRADATION.hybridDeadlineExceeded);+ expect(existsSync(tuningPath(config.vault))).toBe(false);+ },+);+test.skipIf(!sqliteVecLoadable())(+ "a sweep under a missing credential refuses with the credential code",+ async () => {+ const config = await embeddedIndex();+ const err = await refusal({ ...config, semantic: { ...config.semantic, apiKey: null } });+ expect(err.code).toBe("EMBEDDING_KEY_MISSING");+ expect(err.message).toContain("Complete the embedding provider configuration");+ expect(existsSync(tuningPath(config.vault))).toBe(false);+ },+);++test.skipIf(!sqliteVecLoadable())(+ "a sweep under a disabled provider keeps the disabled code",+ async () => {+ const config = await embeddedIndex();+ const err = await refusal({+ ...config,+ semantic: { ...config.semantic, provider: "disabled" },+ });+ expect(err.code).toBe("EMBEDDING_DISABLED");+ expect(existsSync(tuningPath(config.vault))).toBe(false);+ },+);++test.skipIf(!sqliteVecLoadable())(+ "a sweep whose query prefix fills the input window names the window lever",+ async () => {+ const config = await embeddedIndex();+ const err = await refusal({+ ...config,+ semantic: { ...config.semantic, inputWindowTokens: 1, queryPrefix: "query: " },+ });+ expect(err.message).toContain(RETRIEVAL_DEGRADATION.semanticQueryEmptyFit);+ expect(err.message).toContain(INPUT_WINDOW_TOKENS_KEY);+ expect(existsSync(tuningPath(config.vault))).toBe(false);+ },+);diff --git a/tests/hooks/gap-loop.test.ts b/tests/hooks/gap-loop.test.tsindex bd244f6f..bffcc00b 100644--- a/tests/hooks/gap-loop.test.ts+++ b/tests/hooks/gap-loop.test.ts@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";+import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join, resolve } from "node:path";import { fileURLToPath } from "node:url";@@ -22,6 +22,7 @@ import {GAP_TASKS_MAX_NOTES,} from "../../src/core/brain/gaps/gap-loop.ts";import { brainGapTasksDir } from "../../src/core/brain/paths.ts";+import { RETRIEVAL_DEGRADATION } from "../../src/core/search/retrieval-trail.ts";import { writeFrontmatterAtomic } from "../../src/core/vault.ts";import { homeEnv } from "../helpers/platform.ts";@@ -293,6 +294,32 @@ describe("gap-promote hook audit line and auto-close", () => {]);});+ test("names the recall's degradation codes on the audit line, local only", async () => {+ // Semantic search on with no embedding provider configured: the gap+ // recall's semantic lane cannot run, and the trail says so. The codes+ // must reach the operator through the audit line, not vanish in the+ // hook.+ const configPath = join(configHome, "gap-config.yaml");+ writeFileSync(configPath, `vault: ${vault}\nsearch_semantic_enabled: true\n`);+ writeTask("gap-uncovered", GAP_TASK_STATUS_OPEN, { topic: COVERED_TOPIC });+ const run = await runHook(+ "gap-promote",+ { hook_event_name: "SessionEnd" },+ { VAULT_DIR: vault, OPEN_SECOND_BRAIN_CONFIG: configPath, ...FLAG_ON },+ );+ expect(run.exit).toBe(0);+ const [details] = auditDetails();+ const raw = details?.["retrieval_degraded"];+ expect(Array.isArray(raw)).toBe(true);+ const codes = raw as ReadonlyArray<string>;+ expect(codes.length).toBeGreaterThan(0);+ const known: ReadonlyArray<string> = Object.values(RETRIEVAL_DEGRADATION);+ for (const code of codes) expect(known).toContain(code);+ expect(new Set(codes).size).toBe(codes.length);+ // Reported, not judged: the task stays open exactly as it would have.+ expect(details?.["kept"]).toBe(1);+ });+test("keeps a gap task whose only match is its own note", async () => {writeTask("gap-uncovered", GAP_TASK_STATUS_OPEN, { topic: COVERED_TOPIC });const run = await runHook(diff --git a/tests/mcp/link-recall-tools.test.ts b/tests/mcp/link-recall-tools.test.tsindex 705ba599..a84b75c3 100644--- a/tests/mcp/link-recall-tools.test.ts+++ b/tests/mcp/link-recall-tools.test.ts@@ -6,7 +6,7 @@*/import { afterEach, beforeEach, expect, test } from "bun:test";-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -225,6 +225,7 @@ test("brain_benchmark run scores an inline dataset and records the metric", asynconst report = await call(server, "brain_benchmark", { operation: "run", dataset: DATASET });expect(report["total"]).toBe(1);expect(report["hit_at_k"]).toBe(1);+ expect("degraded" in report).toBe(false);expect(listMetrics(vault, { surface: "recall_benchmark" })).toHaveLength(1);const bad = await callError(server, "brain_benchmark", {@@ -263,3 +264,41 @@ test("brain_tune run/status/reset lifecycle", async () => {const missingDataset = await callError(server, "brain_tune", { operation: "run" });expect(missingDataset.code).toBe(-32602);});++/** The whole tool payload, fetched from the artifact store when the preview truncated it. */+async function fullPayload(+ server: MCPServer,+ tool: string,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const out = await call(server, tool, args);+ if (out["preview_truncated"] !== true) return out;+ const stored = await call(server, "brain_artifact_get", { artifact_id: out["artifact_id"] });+ return JSON.parse(stored["content"] as string) as Record<string, unknown>;+}++test("brain_benchmark and brain_tune name the degradation a run carried", async () => {+ writeGroup();+ await indexDefaultLocation();+ const server = new MCPServer({ vault, configPath });+ await initialize(server);++ // Semantic recall configured over an index built without embeddings:+ // keyword-only by construction, so the sweep saves and still says so.+ atomicWriteFileSync(+ configPath,+ `vault: ${vault}\nagent_name: claude\nsearch_semantic_enabled: true\nembedding_provider: local\n`,+ );+ const absent = "semantic-embeddings-absent";+ const expected = ["hybrid-degraded", absent];++ const bench = await call(server, "brain_benchmark", { operation: "run", dataset: DATASET });+ expect(bench["degraded"]).toEqual(expected);++ const tuned = await fullPayload(server, "brain_tune", { operation: "run", dataset: DATASET });+ expect(tuned["degraded"]).toEqual(expected);+ const rows = tuned["evaluated"] as Array<Record<string, unknown>>;+ expect(rows.length).toBeGreaterThan(0);+ for (const row of rows) expect(row["degraded"]).toEqual(expected);+ expect(existsSync(join(vault, "Brain", "search", "tuning.json"))).toBe(true);+});diff --git a/tests/mcp/reach-refusal.test.ts b/tests/mcp/reach-refusal.test.tsindex ca266675..206efa41 100644--- a/tests/mcp/reach-refusal.test.ts+++ b/tests/mcp/reach-refusal.test.ts@@ -142,6 +142,20 @@ describe("a caller-supplied reach is refused by name", () => {expect(findCallerSuppliedReach({ "transport-reach": "local" })).toEqual(["transport-reach"]);});+ test("a compatibility, spaced or invisibly split spelling is the same argument", () => {+ const spellings = [+ "\uFF52\uFF45\uFF41\uFF43\uFF48",+ " reach ",+ "Transport Reach",+ "re\u200Bach",+ "transport\u00ADreach",+ "transport\uFF3Freach",+ ];+ for (const name of spellings) {+ expect(findCallerSuppliedReach({ [name]: "local" })).toEqual([name]);+ }+ });+test("an ordinary argument is not mistaken for one", () => {// `disclosure` is the progressive result-DEPTH mode and is a real// argument on the recall surfaces; refusing it would break them.diff --git a/tests/mcp/recall-feedback-tool.test.ts b/tests/mcp/recall-feedback-tool.test.tsindex 2293f132..9f1a83fb 100644--- a/tests/mcp/recall-feedback-tool.test.ts+++ b/tests/mcp/recall-feedback-tool.test.ts@@ -14,6 +14,11 @@ import { SEARCH_TOOLS } from "../../src/mcp/search-tools.ts";import { indexVault, resolveSearchConfig } from "../../src/core/search/index.ts";import { feedbackDir } from "../../src/core/search/feedback.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";+import { RETRIEVAL_DEGRADATION } from "../../src/core/search/retrieval-trail.ts";+import { FAKE_PROVIDER_KEY } from "../helpers/fake-credentials.ts";+import { startFakeHttp, type FakeHttp } from "../helpers/fake-http.ts";+import { sqliteVecLoadable } from "../helpers/sqlite-vec.ts";let vault: string;let configHome: string;@@ -64,3 +69,68 @@ describe("brain_recall_feedback", () => {).rejects.toThrow();});});++/**+ * The re-run is a search like any other, so it goes through the same+ * query-embed gate: a remote caller under a positive cost gate on an+ * unpriced model gets no embed. The event is still recorded, and the+ * response now says the re-run was degraded instead of hiding it.+ */+describe("brain_recall_feedback discloses a gated re-run", () => {+ let server: FakeHttp;++ beforeEach(async () => {+ server = await startFakeHttp();+ const configPath = join(configHome, "config.yaml");+ const lines = (gate: number) =>+ [+ `vault: ${vault}`,+ "search_semantic_enabled: true",+ "embedding_provider: openai-compat",+ `embedding_base_url: ${server.url}`,+ "embedding_model: fake-model",+ `embedding_api_key: ${FAKE_PROVIDER_KEY}`,+ "embedding_dimension: 4",+ `embedding_cost_gate_usd: ${gate}`,+ "",+ ].join("\n");+ atomicWriteFileSync(configPath, lines(0));+ await indexVault(resolveSearchConfig({ vault, configPath }), { embeddings: true });+ atomicWriteFileSync(configPath, lines(1));+ });++ afterEach(async () => {+ await server.close();+ });++ async function feedback(reach: "local" | "remote") {+ const tool = SEARCH_TOOLS.find((t) => t.name === "brain_recall_feedback")!;+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ return (await tool.handler({ ...ctx, reach: TRANSPORT_REACH[reach] } as any, {+ query: "quarterly ledger reconciliation",+ result_path: "note.md",+ verdict: "up",+ })) as { recorded: boolean; result_found: boolean; degraded: string[] };+ }++ test.skipIf(!sqliteVecLoadable())(+ "a remote call sends no embed, records the event and names the refusal",+ async () => {+ const before = server.callCount();+ const out = await feedback("remote");+ expect(server.callCount()).toBe(before);+ expect(out.recorded).toBe(true);+ expect(out.result_found).toBe(true);+ expect(readdirSync(feedbackDir(vault))).toHaveLength(1);+ expect(out.degraded).toContain(RETRIEVAL_DEGRADATION.semanticCostUnpriced);+ expect(out.degraded).toContain(RETRIEVAL_DEGRADATION.hybridDegraded);+ },+ );++ test.skipIf(!sqliteVecLoadable())("a local call embeds once and reports nothing", async () => {+ const before = server.callCount();+ const out = await feedback("local");+ expect(server.callCount()).toBe(before + 1);+ expect(out.degraded).toEqual([]);+ });+});diff --git a/uv.lock b/uv.lockindex 585171ab..d60cc9c4 100644--- a/uv.lock+++ b/uv.lock@@ -4,5 +4,5 @@ requires-python = ">=3.11"[[package]]name = "open-second-brain"-version = "1.72.0"+version = "1.73.0"source = { editable = "." }