Skip to content

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
27.0 KB
Raw Blame

Honest Embedding Spend - priced, gated and scoped embedding work, vectors that survive an edit and a semantic belief reader

Status: draft Author: Open Second Brain maintainers (via feature-release-playbook) Audience: implementation

Problem statement

The embedding cost kernel prices any model outside a four-entry frozen table at 0. Under an explicit positive embedding_cost_gate_usd, a backfill on a paid model the table does not list (the built-in zeroentropy provider, every registry profile, every curated preset) is estimated at $0 and never refused. The maintenance banner then prints estimated $0.0000, and the spend receipt cannot tell "free" from "price unknown". Four places price spend (the phase gate, the maintenance preview, the backfill dry run and the search status estimate). They resolve the model in two different ways, so the backfill reports a local model as "cost unknown". An edited note re-embeds and re-pays every chunk, including the chunks that did not change. Paying for vectors is all-or-nothing across the vault, and the belief reader brain_context_pack cannot rank by meaning even though belief notes already carry vectors.

Premise verdicts (authoritative for scope)

Every claim was checked against the live source before the brainstorm. Line numbers in the cards had drifted. The table records the verdict that bounds what is built.

Card Verdict What is built
t_0bed79f3 pricing overrides with fail-closed caps confirmed, corrected in three places Built: an operator price pair, a price-source vocabulary, and a fail-closed refusal for an unpriced model under an explicit positive gate. Every pricing site renders an unknown price as unknown. Corrections: (1) visibility is partly present already (planVectorBackfill reports costKnown), but the banner, receipt and status hide or misstate it. (2) There is no "implicit default cap" in Open Second Brain. The gate is either off (0, the default) or explicitly positive, so the upstream "warn under the implicit cap" leg maps to "gate off: never block, report unknown". (3) No cost-gated conversation-facts extractor exists on the embedding kernel, and decision models have their own per-day gate, so the scope is embeddings only. The card's accounting anchors (recall-telemetry.ts, memory-cost-meter.ts) are the wrong files: they meter memory reads, not spend.
t_82c3b275 model refresh and recall tooling refuted in part, corrected in part Refuted and not built: (1) latest-model discovery from the operator's account (GET /v1/models, 24 h cache, fail-open). It contradicts the documented no-unrequested-network stance in src/core/search/embeddings/sunset.ts and the egress census. (2) Automatic switching to a newer model, because a model switch invalidates every vector, so an automatic upgrade is an unrequested paid re-embed. (3) Folding env-key presence into resolveSemanticCapability, which is documented as derived from the resolved config alone. Corrected: keyless tiering already ships, recall tooling already ships (benchmark, rerank-eval, check, doctor), and an automatic model-change trigger exists (ensureEmbeddingModel clears on a change). Built: (a) search check names the credential sources it consulted and the registered profiles whose key is present (names only), which is the offline form of "key-aware". (b) Vectors survive an edit when content hash and model provenance match, which is the upstream provenance-gated survival rule applied at chunk level.
t_0431f64d semantic retrieval over beliefs refuted premise, residue buildable Refuted: "beliefs have no embeddings of their own". Belief notes are indexed documents, and their chunks get vectors on any embedding pass. surprisal.ts already reads them. No new belief vector table and no new embed pass are built. Corrected: the belief-specific reader brain_context_pack is lexical (substring, and ranked documented as "no model, no embedding"), and routing beliefs through search(pathPrefix) under-returns because the prefix filter runs after a global KNN. Built: query_mode: "semantic" on the context pack, which uses exact cosine over the stored vectors of the post-reach candidates, plus a path-scoped vector backfill so belief vectors can be previewed and paid for on their own.

Scope

  • Price sources (t_0bed79f3). A registered closed vocabulary EMBEDDING_PRICE_SOURCE with the values builtin, operator and unknown, and a PriceQuote { usdPerMtok: number | null, source } resolved by one function. The resolution order is: the operator pair when its model matches, then the frozen table, then unknown. The local hashing embedder is builtin at 0, so it is known-free and never unpriced.

  • Operator price pair (t_0bed79f3). Two flat config keys: embedding_price_model and embedding_price_usd_per_mtok, with env overrides OPEN_SECOND_BRAIN_EMBEDDING_PRICE_MODEL and OPEN_SECOND_BRAIN_EMBEDDING_PRICE_USD_PER_MTOK. They must be set both or neither. The rate is a non-negative finite number, and 0 declares a model free. The pair binds the price to one model name, so switching models never silently re-targets the price. The override wins over the table, so a vendor price change can be declared.

  • One spend plan (t_0bed79f3, t_0431f64d). planEmbeddingSpend owns the pending census (optionally path-scoped), the model resolution, the token estimate, the price quote, the estimate and the gate verdict. The phase gate, the maintenance preview, the backfill dry run and the search status refresh estimate all consume it, so what is announced, refused, spent and receipted is one computation.

  • Fail-closed under an explicit cap (t_0bed79f3). The plan refuses as unpriced when all three hold: the gate is positive, the run is not forced, and the price source is unknown with a non-empty pending set. The phase throws the new SearchError code EMBEDDING_COST_UNPRICED, naming the model, the two price keys and --force-cost. With the gate at 0 nothing new blocks.

  • Unknown rendered as unknown (t_0bed79f3). The estimate is number | null across the plan, the preview, the backfill result and the status snapshot, with null meaning the price is unknown. The maintenance banner prints price unknown instead of $0.0000. The spend receipt, the maintenance_spend metric payload and the JSON surfaces gain an optional price_source, and a new receipt for an unknown price stores estimatedUsd: null. The backfill's costKnown reads the quote source, so a local model is known-free.

  • Check recommendations (t_0bed79f3). search check emits one recommendation when the active model's price is unknown. It names the price pair, says what the gate does with it, and is silent for priced and local models. It emits another when the declared price pair names a model that is not the active one (a stale declaration).

  • Credential-source report (t_82c3b275). When the capability tier is credential-missing, search check names the credential sources it consulted: the embedding_api_key config key and OPEN_SECOND_BRAIN_EMBEDDING_KEY, or the active registry profile's env-key names in probe order. It also lists the other registered profiles whose env key is present. Only names are reported. Values are tested for presence and never read further. Only operator-declared names (config keys and registry profiles) are consulted, never a vendor list.

  • Vector carry-over on edit (t_82c3b275). replaceChunks keeps a stored vector for a new chunk whose content_hash equals an old chunk's hash in the same document, provided the old row's model and dimension equal the identity recorded in index_state. It purges only the vectors it does not carry. IndexStats gains embeddingsReused.

  • Path-scoped backfill (t_0431f64d). o2b search vector-backfill --path <prefix> is repeatable and validated by the existing assertSafePathPrefix. It scopes the pending census, the estimate, the gate and the receipt to chunks under those prefixes.

  • Semantic belief order (t_0431f64d). brain_context_pack accepts query_mode: "semantic". This is the MCP surface only, as ranked is today: the o2b brain context-pack verb has no --query-mode flag, and adding one is a separate parity change. The async boundary embeds the query once, reads the stored vectors of every belief note, and passes a relevanceByPath map into the still-synchronous packContext. That function uses the map in the relevance slot of its existing comparator, and reports semantic facts computed after the reach filter:

    • the model, the price source, the query tokens and the estimated query cost;
    • the number of scored candidates;
    • the ids of kept candidates that have no vector.

    The mode refuses by name in three cases: the tier is not configured, sqlite-vec is not loadable, or no kept candidate has a usable vector. The first two are decided by the loader before any query embed. The third is decided by the tool from the post-reach semantic.scored count, because only packContext knows the kept set. The last refusal names o2b search vector-backfill --path Brain/preferences/ --apply. A usable vector is a stored row whose embeddings.model and dimension equal the configured model and the query vector's dimension. Older rows count as unembedded, never as scored. A contradicted embedding identity is carried as the same drift warning the search lane attaches (formatEmbeddingAbiDrift).

Out of scope

  • Account-side model discovery, a model registry over the network, and automatic model switching (refuted, see the verdict table).
  • Env-key presence inside resolveSemanticCapability (refused, see the verdict table).
  • A guarded migrate-embeddings verb and retaining stale-model vectors across a model change. A dimension change cannot coexist in one vec0 table, so the model-change lifecycle needs its own design. restamp.ts keeps naming it as deferred.
  • A price field on registry profiles or presets. One active model at a time is priced by the pair. A per-profile price would add a second source to keep consistent with the pair, for no case the pair cannot express.
  • Making the search(pathPrefix) KNN a pre-filter for every caller. The semantic belief mode avoids KNN entirely, and changing the hot search path is a separate change.
  • A belief-specific vector table or embed-at-write pass (refuted premise).
  • The hygiene dedup detector's live embedding of up to 200 preference principles (src/core/brain/hygiene/detectors/dedup.ts). It calls the provider outside the spend plan, with no gate and no receipt. It is a known residual of this release, and a follow-up card moves it onto stored vectors through the reader this release adds.
  • Pricing with the two-sided token ceiling (tokenEstimateCeiling) instead of the chars/4 floor.
  • A --query-mode flag on o2b brain context-pack. Neither ranked nor semantic is on the CLI, and CLI parity for both is a separate change.
  • Gating the single query embed of the semantic belief mode. It is disclosed on the wire, as below, and is not gated, matching search.

Chosen approach

This is consultant Variant 2, "one spend plan feeds estimate, gate, receipt and a belief-scoped semantic mode", accepted with three overrides.

The cost kernel gains a price-source vocabulary and a quote resolver (src/core/search/embeddings/pricing.ts). A new src/core/search/embedding-spend.ts holds planEmbeddingSpend(store, config, { scope, forced }). It returns the pending set, the model, the tokens, the quote, the estimate and a gate verdict { blocked, reason: "over_cap" | "unpriced" | null }. runEmbeddingPhase is the only spender and throws on a blocked verdict. estimatePendingEmbeddingSpend, planVectorBackfill and indexStatus read the same plan, so a fifth pricing site has nothing to call but the plan. The store's pending census grows an optional path scope that the plan threads end to end.

On the read side, a new src/core/brain/belief-semantic.ts holds a pure scorer and a store-backed loader. The MCP tool calls the loader before packContext, so the CLI verb, the planner, the bench and the anticipatory cache keep calling packContext synchronously and byte-identically.

Override 1: no pre-filtered KNN. The consultant proposed a KNN restricted to belief chunk rowids through chunk_vec_map. We score exact cosine over the stored vectors of the belief notes instead, reading them the way surprisal.ts already does (getDocumentIdByPath, then chunksForDocument, then embeddingForChunk). The belief set is bounded by the vault's preferences, so exact scoring is cheap. It adds no new vec0 query shape and no size guard, and it cannot under-return.

Override 2: no price on registry profiles. The consultant proposed an optional profile price as a second price source. We keep the single model-bound pair. Exactly one model is active at a time, and the pair already binds the price to its name. A second source would need a precedence rule and a consistency check for a case the pair already covers. When the operator switches to an unpriced model, the honest answer is the named refusal, not a second table.

Override 3: partial coverage reports, it does not refuse. The consultant proposed refusing whenever belief coverage is incomplete. That would make the mode unusable after every new preference until the next embedding pass. The mode refuses only when no kept candidate has a usable vector, which is when a "semantic" order would be pure recency. Below that, it names every kept candidate without a vector in semantic.unembedded. Those candidates read relevance 0 and are sorted by the existing tier and recency keys, which is stated in the response rather than implied.

Design decisions

  • Vocabulary values. EMBEDDING_PRICE_SOURCE = { builtin: "builtin", operator: "operator", unknown: "unknown" } follows the four-piece idiom: frozen object, union, members array and an isEmbeddingPriceSource(value: unknown) guard. The value leaves TypeScript in receipts, metrics, JSON and MCP output, so it is registered with the vocabulary census. Alternative considered: table | override | unknown. Rejected, because "builtin" and "operator" name who stated the price, which is what a receipt reader needs.

  • Pair, not a map. A model-keyed key (pricing.overrides.<model>) cannot carry colon-bearing model ids (nomic-embed-text:latest), because the flat parser splits on the first colon, and the _brain.yaml key index refuses model-keyed maps by construction. The pair mirrors embeddings.sunset_model and sunset_at. The model is compared after canonicalToken (NFC, trim, lowercase), the same normalisation the table uses. A half pair, a negative rate or a non-numeric rate fails config resolution with SearchError("INVALID_INPUT") naming the key, the error parseNonNegativeFloat already raises.

  • Where the pair lives. It goes in the flat plugin config beside embedding_cost_gate_usd, so the price resolves where the gate resolves (resolveSearchConfig). It is added to ResolvedEmbeddingConfig as an optional priceOverride?: { model, usdPerMtok }, so the dozen literal fixtures that build the config stay untouched. Alternative considered: the vault's _brain.yaml embeddings: block. Rejected, because price is a fact about the account and the provider, which the flat config already carries, while the vault file is replicated vault policy.

  • Price stays out of identity. embeddingSignature, isStaleSignature and the corpus-generation fingerprint are not touched. An explicit regression test asserts that the signature of a model is identical with and without an override, so editing a price can never trigger a paid reindex.

  • Fail-closed only under an explicit cap. The upstream card's "implicit default cap" does not exist here. Gate 0 keeps today's behaviour for blocking. The inverted polarity applies only to an operator who asked for a ceiling, and for that operator an unknown price is not a price below the ceiling. The docblocks that state the old polarity (signature.ts above the table, presets.ts, and the cross-references in sunset.ts) are rewritten to the new rule. --force-cost passes an unpriced refusal as it passes an over-cap one. The receipt then says forced: true with price_source: unknown and estimatedUsd: null. The operator scope choice for this release accepted the polarity change.

  • What counts as free. Two things count as free: the builtin local model, and an operator declaration of 0. A loopback embedding_base_url (Ollama, llama.cpp) is not inferred to be free. It stays unknown, which only matters to an operator who set a positive gate, and the refusal tells them how to declare it. Alternative considered: treating loopback as free. Rejected, because a loopback URL can be a paid proxy, and inference is the silent assumption this release removes.

  • Null estimates, not zero. estimatedUsd becomes number | null in CostGateResult, the plan, EmbeddingSpendPreview, the backfill result (estimatedCostUsd), the status snapshot (estimatedRefreshCostUsd) and new receipts. The type change reaches ten source sites, all inside this diff. Old journal rows have no price_source and read as unrecorded. Their numeric estimatedUsd stays as written, and the renderer does not reinterpret history. Alternative considered: keeping 0 plus a source field. Rejected, because a JSON consumer reading estimated_usd alone would read 0 as "free", which is the misleading value this release removes.

  • One model resolution. The plan resolves the model as the phase does (config.semantic.model ?? provider.model). The backfill estimate (today config.semantic.model alone) and the status estimate (activeEmbeddingModel) switch to it. If implementation finds that activeEmbeddingModel is the same rule, the plan calls it and the duplicate goes.

  • Scope on the census. findChunksWithoutEmbeddings and its count form take an optional pathPrefixes list. They join documents and match path with the substr(d.path, 1, length(?)) = ? form the vector prefix filter in store/vectors.ts already uses. That form needs no wildcard escaping. An empty list means vault-wide, so today's SQL is unchanged when the flag is absent. The phase receives the scope only through the plan, so the gate and the receipt cannot read a different census from the estimate.

  • Carry-over key. The key is content_hash alone within one document. The embedded text is exactly chunks.content (indexer.ts: texts = batch.map((p) => p.content)), and content_hash = sha256(content). Query and passage prefixes are store-level, and any change to them already clears every vector through ensureEmbeddingModel. Duplicate hashes match as a multiset in chunk_index order. The guard is that the old row's embeddings.model and dimension equal the index_state model and dimension. When the identity is unrecorded nothing is carried, and the guard says so in a code comment and a test. Mechanics, inside the existing transaction:

    1. Read old (content_hash, chunk_id, vec_rowid, model, dimension, embedding_hash).
    2. Purge only the vec rows that will not be carried.
    3. Delete the old chunks. The cascades remove the old map and embeddings rows.
    4. Insert the new chunks.
    5. Insert map and embeddings rows for the carried pairs.

    Alternative considered: keying on (content_hash, heading_path). Rejected, because the heading path is not embedded, so it would re-pay for identical vectors.

  • Credential report placement. A pure describeCredentialSources(semantic, registry, env) in src/core/search/embeddings/credential-report.ts returns { consulted: string[], presentElsewhere: string[] }. The search check path passes the env and the loaded registry explicitly. The tier function is not touched. The report is attached to the check result as an additive field and rendered as two lines under the existing keyless warning.

  • Semantic score per note. The score is the maximum cosine over the note's chunk vectors. The frontmatter chunk and the body chunk both carry the principle, so a sum would double-count, and the maximum is invariant to chunk count. Cosine is computed in JS over the Float32Array vectors read from the store. Ties fall through to the comparator's existing keys, ending in the id, so output is deterministic. The query is embedded with the query prefix through the configured provider, the same call search makes.

  • Scored set and reach. The loader scores every belief note (Brain/preferences/, Brain/retired/, through the existing path constants that collectPreferencePages uses). packContext reads the map only for candidates that survived the reach filter. scored and unembedded are computed after that filter, so a withheld page can influence neither the order nor the report.

  • Refusal codes. The semantic mode reuses the registered capability codes for a blocked tier (EMBEDDING_DISABLED, EMBEDDING_KEY_MISSING) and VEC_EXTENSION_UNAVAILABLE, and adds one code, BELIEF_VECTORS_MISSING. A contradicted embedding identity warns rather than refuses, matching the search lane under the shipped warn default. The per-row model check above is what keeps a stale vector out of the score. EMBEDDING_COST_UNPRICED joins SEARCH_ERROR_CODES and the MCP stable-error-code registry. The semantic mode joins CONTEXT_PACK_QUERY_MODES and the MCP schema enum.

  • Query spend disclosure. The semantic report carries query_tokens, estimated_usd (null when the price is unknown) and price_source. This is the release's rule applied to the one spend path that stays ungated.

  • Byte identity. The following cases are pinned by tests:

    • the substring and ranked pack modes;
    • every pricing surface for a table model with gate 0;
    • findChunksWithoutEmbeddings without a scope;
    • replaceChunks when vec is not loaded;
    • search check on a configured tier;
    • the embeddingSignature of every model.

File changes

Cost kernel and plan:

  • src/core/search/embeddings/pricing.ts (new): EMBEDDING_PRICE_SOURCE, EmbeddingPriceSource, EMBEDDING_PRICE_SOURCES, isEmbeddingPriceSource, PriceQuote, resolveEmbeddingPrice(model, override).
  • src/core/search/embeddings/signature.ts (modified): the table docblock is rewritten. estimateCostUsd and evaluateCostGate take a PriceQuote and return a nullable estimate plus a reason. pricePerMillionTokens is removed once its callers move, and its test moves to the resolver.
  • src/core/search/embeddings/presets.ts, src/core/search/embeddings/sunset.ts (modified): polarity cross-references.
  • src/core/search/embedding-spend.ts (new): planEmbeddingSpend, EmbeddingSpendPlan, EMBEDDING_GATE_REASON (closed vocabulary over_cap, unpriced).
  • src/core/search/index.ts (modified): parse and validate the price pair. src/core/search/types.ts (modified): priceOverride, the nullable estimates, priceSource on the preview, the spend and the status, and embeddingsReused on IndexStats.
  • src/core/search/search-error.ts (modified): EMBEDDING_COST_UNPRICED, BELIEF_VECTORS_MISSING.
  • src/core/search/indexer.ts (modified): runEmbeddingPhase, estimatePendingEmbeddingSpend and indexStatus consume the plan. buildRecommendations gains the unpriced-model and stale-pair hints, and the check result gains the credential report.
  • src/core/search/vector-backfill.ts (modified): pathPrefixes, the plan, costKnown from the quote.
  • src/core/search/store/chunks.ts, src/core/search/store.ts (modified): the scoped census and the count form, and vector carry-over in replaceChunks.
  • src/core/search/embeddings/credential-report.ts (new): describeCredentialSources.

Spend surfaces:

  • src/core/brain/maintenance/journal.ts, src/core/brain/maintenance/reindex-task.ts (modified): receipt and metric priceSource, nullable estimate.
  • src/cli/brain/verbs/maintenance.ts (modified): banner price unknown.
  • src/cli/search/verbs/vector-backfill.ts, src/cli/search/verbs/status.ts, src/cli/search/verbs/check.ts, src/core/search/serialize.ts, src/mcp/search-tools.ts (modified): rendering and JSON fields.
  • src/cli/command-manifest.ts, src/cli/search.ts (modified): --path on the backfill in the manifest and the search help.

Belief reader:

  • src/core/brain/belief-semantic.ts (new): scoreBeliefsByVector (pure) and loadBeliefSemanticRelevance (store-backed, async).
  • src/core/brain/context-pack.ts (modified): the semantic mode, semanticRelevance option and semantic report.
  • src/mcp/brain/pack-tools.ts (modified): schema enum, async load, refusal mapping and output.
  • src/core/search/visibility-surface-registry.ts (modified only if the pack surface's reason text changes).

Docs:

  • docs/cli-reference.md, docs/how-it-works.md, docs/updating.md (migration note: gated vaults on unpriced models now refuse), docs/mcp.md.
  • skills/embeddings-setup/SKILL.md, followed by bun run sync-plugin-mirrors.
  • The CHANGELOG entry and version bump happen in PR preparation.

Risks and open questions

  • Gated vaults start refusing. An operator with a positive gate on an unpriced model (ZeroEntropy, any registry profile) sees maintenance reindex and backfills refused after upgrading, and a nightly lane reports refused. The mitigation is the named error, which carries the exact keys to set, plus the check recommendation, the updating.md entry and the CHANGELOG. This is the intended behaviour change, accepted at scope choice.
  • Nullable estimate reach. Any consumer of estimatedUsd outside this repository (scripts reading the journal JSONL) sees null for unknown prices on new rows. This is disclosed in CHANGELOG. Old rows are unchanged.
  • Carry-over correctness. A carried vector that does not match its content would be silent garbage. The guards are the model and dimension check against index_state, the exact-content key, and the fact that every identity change already clears all vectors. Tests cover an edited note, a moved paragraph, duplicated paragraphs, a model mismatch, unrecorded identity and vec not loaded. The embedder record audit (store/embedder-audit.ts) must still pass on carried rows. Implementation verifies that it reads only the model and dimension.
  • Foreign-key cascade. The carry-over relies on ON DELETE CASCADE for chunk_vec_map and embeddings. If the store does not enable foreign_keys, the old rows are deleted explicitly, which the existing replaceChunks and purge code already have to do. Implementation reads the pragma state and writes the test against it.
  • Census churn. New error codes, a new vocabulary, a new query mode, a new CLI flag and new JSON fields move the vocabulary, MCP surface, help-parity and instruction-body fixtures. Each is registered, not excluded.
  • Local embedder labelled semantic. Over the hashing n-gram embedder, semantic order is lexical in practice. The report names the model, so the caller can see it. No silent relabelling is done.
  • Open question for implementation. Whether estimatePendingEmbeddingSpend keeps its null-return contract unchanged when the plan reports an unpriced refusal. Expected answer: yes. It returns a preview with blocked: true, reason: "unpriced" and estimatedUsd: null, and the banner renders it. A test pins it.