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.
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_SOURCEwith the valuesbuiltin,operatorandunknown, and aPriceQuote { 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 isbuiltinat 0, so it is known-free and never unpriced.Operator price pair (t_0bed79f3). Two flat config keys:
embedding_price_modelandembedding_price_usd_per_mtok, with env overridesOPEN_SECOND_BRAIN_EMBEDDING_PRICE_MODELandOPEN_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).
planEmbeddingSpendowns 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 thesearch statusrefresh 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
unknownwith a non-empty pending set. The phase throws the newSearchErrorcodeEMBEDDING_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 | nullacross the plan, the preview, the backfill result and the status snapshot, with null meaning the price is unknown. The maintenance banner printsprice unknowninstead of$0.0000. The spend receipt, themaintenance_spendmetric payload and the JSON surfaces gain an optionalprice_source, and a new receipt for an unknown price storesestimatedUsd: null. The backfill'scostKnownreads the quote source, so a local model is known-free.Check recommendations (t_0bed79f3).
search checkemits 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 checknames the credential sources it consulted: theembedding_api_keyconfig key andOPEN_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).
replaceChunkskeeps a stored vector for a new chunk whosecontent_hashequals an old chunk's hash in the same document, provided the old row'smodelanddimensionequal the identity recorded inindex_state. It purges only the vectors it does not carry.IndexStatsgainsembeddingsReused.Path-scoped backfill (t_0431f64d).
o2b search vector-backfill --path <prefix>is repeatable and validated by the existingassertSafePathPrefix. It scopes the pending census, the estimate, the gate and the receipt to chunks under those prefixes.Semantic belief order (t_0431f64d).
brain_context_packacceptsquery_mode: "semantic". This is the MCP surface only, asrankedis today: theo2b brain context-packverb has no--query-modeflag, 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 arelevanceByPathmap into the still-synchronouspackContext. That function uses the map in the relevance slot of its existing comparator, and reportssemanticfacts 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-reachsemantic.scoredcount, because onlypackContextknows the kept set. The last refusal nameso2b search vector-backfill --path Brain/preferences/ --apply. A usable vector is a stored row whoseembeddings.modelanddimensionequal 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-embeddingsverb and retaining stale-model vectors across a model change. A dimension change cannot coexist in onevec0table, so the model-change lifecycle needs its own design.restamp.tskeeps 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-modeflag ono2b brain context-pack. Neitherrankednorsemanticis 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 anisEmbeddingPriceSource(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.yamlkey index refuses model-keyed maps by construction. The pair mirrorsembeddings.sunset_modelandsunset_at. The model is compared aftercanonicalToken(NFC, trim, lowercase), the same normalisation the table uses. A half pair, a negative rate or a non-numeric rate fails config resolution withSearchError("INVALID_INPUT")naming the key, the errorparseNonNegativeFloatalready 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 toResolvedEmbeddingConfigas an optionalpriceOverride?: { model, usdPerMtok }, so the dozen literal fixtures that build the config stay untouched. Alternative considered: the vault's_brain.yamlembeddings: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,isStaleSignatureand 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.tsabove the table,presets.ts, and the cross-references insunset.ts) are rewritten to the new rule.--force-costpasses an unpriced refusal as it passes an over-cap one. The receipt then saysforced: truewithprice_source: unknownandestimatedUsd: null. The operator scope choice for this release accepted the polarity change.What counts as free. Two things count as free: the
builtinlocal model, and anoperatordeclaration of 0. A loopbackembedding_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.
estimatedUsdbecomesnumber | nullinCostGateResult, 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 noprice_sourceand read as unrecorded. Their numericestimatedUsdstays as written, and the renderer does not reinterpret history. Alternative considered: keeping 0 plus a source field. Rejected, because a JSON consumer readingestimated_usdalone 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 (todayconfig.semantic.modelalone) and the status estimate (activeEmbeddingModel) switch to it. If implementation finds thatactiveEmbeddingModelis the same rule, the plan calls it and the duplicate goes.Scope on the census.
findChunksWithoutEmbeddingsand its count form take an optionalpathPrefixeslist. They joindocumentsand matchpathwith thesubstr(d.path, 1, length(?)) = ?form the vector prefix filter instore/vectors.tsalready 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_hashalone within one document. The embedded text is exactlychunks.content(indexer.ts:texts = batch.map((p) => p.content)), andcontent_hash = sha256(content). Query and passage prefixes are store-level, and any change to them already clears every vector throughensureEmbeddingModel. Duplicate hashes match as a multiset inchunk_indexorder. The guard is that the old row'sembeddings.modelanddimensionequal theindex_statemodel 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:- Read old
(content_hash, chunk_id, vec_rowid, model, dimension, embedding_hash). - Purge only the vec rows that will not be carried.
- Delete the old chunks. The cascades remove the old map and embeddings rows.
- Insert the new chunks.
- 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.- Read old
Credential report placement. A pure
describeCredentialSources(semantic, registry, env)insrc/core/search/embeddings/credential-report.tsreturns{ consulted: string[], presentElsewhere: string[] }. Thesearch checkpath 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
Float32Arrayvectors 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 thequeryprefix through the configured provider, the same callsearchmakes.Scored set and reach. The loader scores every belief note (
Brain/preferences/,Brain/retired/, through the existing path constants thatcollectPreferencePagesuses).packContextreads the map only for candidates that survived the reach filter.scoredandunembeddedare 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) andVEC_EXTENSION_UNAVAILABLE, and adds one code,BELIEF_VECTORS_MISSING. A contradicted embedding identity warns rather than refuses, matching the search lane under the shippedwarndefault. The per-row model check above is what keeps a stale vector out of the score.EMBEDDING_COST_UNPRICEDjoinsSEARCH_ERROR_CODESand the MCP stable-error-code registry. Thesemanticmode joinsCONTEXT_PACK_QUERY_MODESand the MCP schema enum.Query spend disclosure. The
semanticreport carriesquery_tokens,estimated_usd(null when the price is unknown) andprice_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
substringandrankedpack modes; - every pricing surface for a table model with gate 0;
findChunksWithoutEmbeddingswithout a scope;replaceChunkswhen vec is not loaded;search checkon a configured tier;- the
embeddingSignatureof every model.
- the
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.estimateCostUsdandevaluateCostGatetake aPriceQuoteand return a nullable estimate plus a reason.pricePerMillionTokensis 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 vocabularyover_cap,unpriced).src/core/search/index.ts(modified): parse and validate the price pair.src/core/search/types.ts(modified):priceOverride, the nullable estimates,priceSourceon the preview, the spend and the status, andembeddingsReusedonIndexStats.src/core/search/search-error.ts(modified):EMBEDDING_COST_UNPRICED,BELIEF_VECTORS_MISSING.src/core/search/indexer.ts(modified):runEmbeddingPhase,estimatePendingEmbeddingSpendandindexStatusconsume the plan.buildRecommendationsgains 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,costKnownfrom 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 inreplaceChunks.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 metricpriceSource, nullable estimate.src/cli/brain/verbs/maintenance.ts(modified): bannerprice 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):--pathon the backfill in the manifest and the search help.
Belief reader:
src/core/brain/belief-semantic.ts(new):scoreBeliefsByVector(pure) andloadBeliefSemanticRelevance(store-backed, async).src/core/brain/context-pack.ts(modified): thesemanticmode,semanticRelevanceoption andsemanticreport.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 bybun 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.mdentry and the CHANGELOG. This is the intended behaviour change, accepted at scope choice. - Nullable estimate reach. Any consumer of
estimatedUsdoutside this repository (scripts reading the journal JSONL) seesnullfor 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 CASCADEforchunk_vec_mapandembeddings. If the store does not enableforeign_keys, the old rows are deleted explicitly, which the existingreplaceChunksand 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,
semanticorder 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
estimatePendingEmbeddingSpendkeeps its null-return contract unchanged when the plan reports an unpriced refusal. Expected answer: yes. It returns a preview withblocked: true,reason: "unpriced"andestimatedUsd: null, and the banner renders it. A test pins it.