Garry's Opinionated OpenClaw/Hermes Agent Brain
Key files: Providers
Subsystem index. Read only the entries relevant to your change. Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
src/core/embedding-readiness.ts— bounded source-aware recovery through canonical projection snapshots, queued intent, preparation and guarded installation. Global readiness remains archive-visible. Plain stale repair selects active sources for recovery and separately reports archived stranded work, so live pages can progress without pretending the whole brain completed.countArchivedEmbeddingWorkclassifies archived NULL vectors, non-NULL hash drift, signature work, contentful chunkless pages and, for migration, pending projections before authorization. Repair queues and snapshots require a live source under the existing source-before-page guard; unsupported pages remain blocked, never revision-stamped. The invalidation SQL additionally excludes unsealed projections. #6223: repair walks a keyset cursor (each candidate once per call, ending on a short batch) over Markdown, code and segmented pages only (#6803), so image pages stay counted as blocked and are never queued or re-stamped (arebuild_failedimage row keeps its reason); its blocked message namesgbrain projections drainfor the importer-attested ones andgbrain doctor --only text_projection_readiness --jsonfor the class counts;listPendingProjectionPageslists the first blocked pages andreportBlockedProjectionswrites the CLI's failure sample.embed --staleandembedStaleForSourceno longer stop when pages stay blocked: the guarded drain skips their unsealed snapshots (the CLI counts their chunks as failures and names them withgbrain embed --stale --images; the source drain adds them toblockedand stays incomplete).src/core/embedding-migration-retention.ts— fail-closed retained-vector rebuildability check shared by migration preflight, direct apply, schema transition, pinned-column repair and invalidation/config transactions. Transaction-local SHARE locks freeze source/page/vector/withdrawal/config eligibility during the census and mutation. Sealed importer text chunks can be embedded and oversized chunks healed without regenerating their source projection; unsealed unsupported media still refuses. Width changes protect archived, skipped, deleted and unrebuildable retained page vectors; same-width checks match the shared false-stamp predicate, signature gate and current-space test. Archived pending work, including same-target content drift, metadata-only restamping, NULL vectors and chunkless pages, refuses before authorization or provider work; correct target-stamped archived vectors, including grandfathered NULL hashes, are retained controls. Companion retention checks follow actual schema/pinned-width changes and the same-target persisted migration marker; the guard returns the locked companion-clear decision consumed by the writer, ignoring a different target's completed-clear flag. Schema-only work leaves takes untouched. Existing fact eligibility and deliberate expiry/supersession/audit/withdrawal policy remain unchanged. Unknown registry, width or census fails closed. The source census includes archive state, but embed leases are not archive coordination. Synthetic two-engine regressions cover preservation refusals, real imported-image migration, same-target companion preservation, retarget/first-clear refusal and fail-closed metadata. Completion counts remain archive-visible; refusal never restores a source automatically.src/core/embedding-migration-budget.ts— finite authorization in the existing migration marker. Each provider attempt reserves its maximum input price under the acquired leases and aFOR UPDATEon the marker row, and records a pending entry keyed by attempt id;settle(usage)takes the same lock and replaces the reservation with the reported usage (refund or overshoot). Idempotent per (authorization_generation, attempt id): a repeated or stale-generation settle is a no-op, so a crash before settlement keeps the maximum. Missing usage keeps the maximum. Usage above the reservation debits actual, addsovershoot_usdand setshalted, which refuses further dispatch until an explicit--max-cost-usdrenewal.authorizeMigrationBudget(..., worstCase)throwsMigrationBudgetRefusal(embedding_budget_below_worst_case, with cap, worst case, retained debits, the filled--max-cost-usdcommand and thewrite-refusals.mdanchor) before writing any state when the cap is below debits + worst case. Refusal copy prints the operator's cap, never a remainder. Resume preserves every debit; unknown prices or missing input bounds refuse. Marker corruption cannot erase a versioned authorization. Only an explicitly reauthorized legacy marker without authorization fields can be replaced.src/core/embedding-migration-worst-case.ts—planMigrationWorstCase(engine, plan, { rerankerModel }): Σ per-request maximum input fromembed-batch-plan.tsover what the run sends (target probe, the drain's two probes, stale chunks per page (including content drift: a stored text hash that no longer matches) split byhealOversizedChunksat the target chunk size over the complete page (a split re-indexes siblings, so every healed chunk of that page counts) and wrapped withwrapChunkTextsForStoredMode, the chunks projection recovery and the chunkless heal will create — replayed throughreadProjectionSnapshot+preparePageProjectionat the current chunk size then the target-size heal, and directly at the target size, keeping the larger ceiling, replacing those pages' existing chunks — stale facts in 100-row per-source batches, three smoke-check queries, the reranker probe when switching), priced with operator overrides.usdis null only when the embedding model is unpriced; an unpriced reranker lands inunpriced_modelsand the embedding bound is still enforced. Owns the migration and reranker probe texts. Computed at plan time for the printed estimate and again under the migration locks for the refusal.src/core/facts/embedding-identity.ts— active fact eligibility and stale model/text/width census shared by migration and fact repair;partiallyEmbeddedFactflags facts whose UTF-16 length exceedsEMBED_MAX_CHARS(#6975). Legacy identity stays unknown. Both engine writers accept explicitembedding_modeland compute the exact text hash; duplicate vector selection requires matching caller identity.embed-facts.tsinstalls under source-incarnation, row-version, withdrawal and configuration guards, retaining the outer migration invocation budget when nested.src/core/anthropic-pricing.ts— bare-keyed Anthropic VIEW ofmodel-pricing.ts(theanthropic:canonical entries with the prefix stripped). Kept distinct because many callers look up by bare Claude id and becauseestimateMaxCostUsd(modelId, inTokens, maxOutTokens)carries the null-on-miss contract the dream-cycle budget gate depends on (non-Anthropic ids return null;BudgetMetertriescanonicalLookupfirst and only falls back here, so it warnsBUDGET_METER_NO_PRICINGand runs unbounded only when canonical has no rates either).estimateMaxCostUsdroutes bare/colon/slash ids throughsplitProviderModelId. Do NOT hand-edit prices here — the map is derived from canonical, so it cannot drift.ANTHROPIC_PRICINGis consumed bybudget/budget-tracker.tsandcycle/budget-meter.ts.src/core/contextual-retrieval-service.ts— captures the complete originating projection before synopsis/embedding providers, then installs vectors with UPDATE-only CAS and stamps mode/generation in the same guarded transaction. Stored corpus generation participates inpage-state/projections.tsindexing context even when the mode and canonical revision stay unchanged. New vectors receive the captured provider model; text, chunk identity, metadata and retrieval seal remain intact. Source contextual policy is rechecked before publication. Superseded preparation returns the existing retryable database result. Empty/disabled-mode stamps compare identity, seal, context and raw chunk inventory under the guard; unsealed nonempty chunks never reach a provider. A segmented page is skipped aspage_body_segmentedwith nothing stamped, and thecontextual_reindex_per_chunkjob result names it inskip_reason(Wave B PR 2; per-segment synopses are PR 4;test/large-pages/contextual-reembed-segmented.test.ts).test/embedding-completion-atomic.serial.test.tscovers real service/edit/rechunk/context interleavings and ordinary retrieval on both engines.src/core/embed-backfill-submit.ts— Automatic per-source embed-backfill submitter with a true discriminated result union:submittedrequiresjobIdplus an explicit spend-bypass payload,cooldownrequires a reason plus a numeric remaining duration or explicitnullfor active work,spend_cappedrequires cap/spend payloads, andno_worker_surfacerequires the refused engine kind. It queries cooldown/spend state only after the shared admission classification accepts a worker-backed engine, preserving Postgres behavior while guaranteeing PGLite/unknown refusal before config, schema, or SQL access; callers handle every status exhaustively.src/core/embed-facts.ts— explicit source-scoped NULL-fact vector repair with read-only default preview, finite nonnegative spend cap plus optional count/time bounds, row-version/incarnation/withdrawal CAS and per-attempt cost accounting. Selected-brain policy is a trusted out-of-band argument; engine DB off-switch and policy are rechecked on every provider attempt. Managed mode updates physical projection only and live PGLite delegates through privatewriter_embed_facts, not a canonical fact rewrite. A fact over the embedding input limit is skipped, never sent or truncated, and does not use up--max-facts; the result reports it (refused_oversized,refused_samples,refused_fix) and leaves it out ofremaining.readOversizedStaleFacts(src/core/facts/embedding-identity.ts) feeds that, doctorfact_take_vectorsandgbrain embed --held(#7211). Tests:test/e2e/fact-embedding-backfill-parity.test.ts,test/fact-backfill-resident.test.ts,test/fact-embedding-oversized-7211.test.ts.src/core/embedding-input-hash.ts— per-chunk embedding-input provenance (#5553).embeddingInputHashdigests the vector column, model, dimensions, wrapping tier and the exact input (chunk text; title prefix + text; or, for the unrecomputable synopsis tier, the page's corpus generation, title,synopsisBodyHashof the chunk set and the text).acceptedEmbeddingInputHashesalso accepts title-tier vectors on synopsis pages;plainEmbeddingTiermirrorswrapChunkTextsForStoredMode. A body change therefore nulls every synopsis-tier chunk and nothing else unchanged. Pinned bytest/projection-embedding-input-hash.test.ts(PGLite and Postgres).src/core/embed-oversize-heal.ts— heals ALREADY-STORED chunks that exceed the active embedding model's per-input token cap (new imports respectresolveMaxChunkTokens(), but--stalere-embeds existingchunk_textrows chunked under looser caps, which fail every sweep forever).healOversizedChunkssplits oversized rows in place (never truncates; char-based hard split as the pathological fallback), re-indexes contiguously, carries each piece's modality/code-symbol metadata, and leaves embeddings unset soupsertChunkspreserves vectors for unchanged(chunk_index, chunk_text)pairs and NULLs the split/shifted ones;healOversizedPageChunksis the load-split-upsert-reload wrapper.healedChunksToStaleRows(chunks, slug, sourceId)remaps a post-heal chunk list back into the stale-row shape — the shared seam betweensrc/commands/embed.ts:embedAllStaleandsrc/core/embed-stale.ts:embedStaleForSourceso the two drains cannot drift;chunk_sourcepasses through UNCHANGED (coercingfenced_codetocompiled_truthwould makewrapChunkTextsForStoredModeprefix code chunks, violating the D20-T4 never-wrap convention). Pinned bytest/embed-oversize-heal.test.ts.src/core/embed-retry.ts— embed retry/backoff primitives + the title-tier restamp helper. AnEmbeddingZeroNormError(#4616) is never retried or classified transient;embedBatchKeepingUsablereturns the usable vectors of a partially refused batch with the refusal, and still throws when nothing is usable. It stays in core becausesrc/core/import-file.tsandsrc/core/embed-stale.tsconsume these (a core→commands import would make every import-file consumer eagerly load the embed COMMAND module — one value import away from a real ESM cycle).embedBatchWithBackoffwrapsembedBatchwith rate-limit-aware retry: detects 429s via the wrapped error'scause.status(message-match fallback), also retries transient gateway 502/503/504, parses provider retry-delay hints, jitters ±30% so concurrent workers don't resynchronize, passesmaxRetries: 0through so the AI SDK's own retry stack doesn't multiply attempts, and threads an external AbortSignal into both the sleep and the in-flight HTTP call.restampIfDemotedToTitleTierrestamps aper_chunk_synopsispage's CR state to'title'after a plain re-embed socontextual_retrieval_modekeeps describing the vectors actually in the column (the reindex sweep restores the synopsis tier later).src/commands/embed.tsre-exports everything here (façade rule) so import sites and tests never chase the peel.src/core/embed-skip.ts— 5-site shared predicate for the soft-block embed-skip filter. ExportsshouldSkipEmbedding(frontmatter): boolean(JS predicate for callers holding the page in memory),EMBED_SKIP_SQL_FRAGMENT(parameterized SQL clause shared by Postgres + PGLite viaexecuteRaw), andbuildEmbedSkipMarker(reason: string)(writesfrontmatter.embed_skip = {at: ISO_TIMESTAMP, reason}so the JSONB shape stays uniform). The 5 sites:embed.ts --stale,embed.ts --all, theembed-staleMinion helper, plus both engines'listStaleChunks+countStaleChunks. Single source of truth so the filter cannot drift. Pinned bytest/embed-skip.test.ts(cross-site invariant + JSONB shape).src/core/embedding-state.ts— #6696 B3 derived embedding state: every chunk, and every live page with no chunk row, in one ofembedded | pending | keyword_only | quarantined | empty | deleted_page_chunks | chunkless_healableagainst the ACTIVE embedding column (no stored status). The classifier SQL lives once inengine-sql/chunks.ts(chunkEmbeddingStatereusesstaleChunkWhere,chunklessPageStatereuseschunklessPagesWhere, which skips a page whose current revision's text projection is sealed with no chunks unless it carriesembed_skip, so a body the writer chunked to nothing (only a takes fence) isempty, not healable;deleteChunksand an empty fragment replacement clear the seal, so a page emptied after sealing stays healable: #8473,test/embedding-state-projection-empty-8473.test.ts) behindBrainEngine.readEmbeddingStateCounts/listEmbeddingStateRows.readEmbeddingState(engine, { mode, sourceIds }):fullis exact;opsreads only index-backed counts (the partial indexWHERE <active column> IS NULL, the frontmatter GIN, the purge index;embeddedis a planner estimate) and isstatus: 'unknown', reason: 'no_covering_index'without that index, never a scan.unsearchablesums pending, quarantined, empty and chunkless_healable (pending drops out on a brain keyless by choice).embeddingStateFixbuilds each state's protocol fix from existing commands. Consumers: doctorembedding_state,gbrain pages unsearchable, lane B'sget_brain_health. Tests:test/embedding-state.test.ts.src/core/embed-stale.ts— source-wide stale embedding and explicit-page completion keep vector installation, complete-provenance signature checks and title-tier demotion in one page-guarded transaction. The threesrc/commands/embed.tspaths use the same transaction boundary; providers run before it. Standalone/background projection recovery preserves NULL-signature grandfathering and existing stale eligibility; the job's deadline, abort signal and source lease fence recovery, invalidation and publication. Oversized-chunk healing checks ownership and stop conditions before and after its transaction, rolling back prepared changes on loss. The restamp always uses the captured page metadata, so a later same-revision contextual rebuild cannot retain its vectors while an older completion overwrites its mode or corpus generation.persistence/effects.tsalso retains this atomic completion boundary.test/embedding-completion-atomic.serial.test.tsexercises all five completion paths;test/e2e/migration-wave-healing-fence.test.tspins healing rollback on both engines. #5902: without an explicitconcurrency,embedStaleForSource(the unpacedembed-backfilljob and the remediation embed step) runsresolveStaleEmbedConcurrencyworkers fromsrc/core/embed-concurrency.ts:min(20, max(1, floor(poolMax/2)))of the engine's real pool (getPoolDiagnostics().poolMax, a worker's instance pool included), 20 without a pool; an explicitGBRAIN_EMBED_CONCURRENCYkeeps the full-pool clamp. Pinned bytest/embed-stale-pool-default.test.ts+test/e2e/embed-stale-pool-default-postgres.test.ts. Wave B: a segmented page is embedded bypage-body/segmented-embedding.ts(vector-less live rows by chunk_index keyset with the title and plain tier, metered per page, installed by chunk_index and exact text onto rows still in the live generation; never the body or every chunk), from here,gbrain embedand the post-commit embedding effect (data.occurrence_idslimits an append's effect to the new occurrences).src/core/content-drift-sweep.ts— the content-drift sweep (#4246) as a resumable pass:runContentDriftSweep(engine, { sourceId?, signal?, deadline?, stopped?, assertOwned?, timeBudgetMs?, batchRows? })runsengine-sql/chunks.tsinvalidateContentDriftBatch(5,000 chunk rows past the cursor in id order, bounded before any md5) one transaction per batch, committing the cursor in config rowembed.content_drift_sweep.<column>.<all|source:id>with the batch under aFOR UPDATElock on that row, so concurrent runs share one pass. A run stops at its 60 s budget, the job deadline or an abort; a completed pass restarts afterembed.content_drift.pass_interval_hours(default 24) unless it fit in one batch. A failed batch is returned asstate: 'failed'with the error and recorded aslast_error(cleared by the next committed batch); a missing v133/v221 column isunsupported; anassertOwnedthrow propagates.embedAllStale(EmbedResult.content_drift),embedStaleForSource(contentDrift) and the embed, embed-backfill and cycle embed results carry the status; doctorcontent_drift_sweepreads the saved rows.src/core/page-embedding-lease.ts— one provider call per chunk content version (gbrain-evals#180, N14). Every path that embeds a page's vector-less chunks holds the page's embedding lease from reading which chunks lack a vector through its install: the post-write embedding effect (persistence/effects.ts, inline and segmented), thegbrain embed --staledrain (src/commands/embed.ts),embedStaleForSourceandembedStalePages(embed-stale.ts), and every segmented install (embedSegmentedRowsinpage-body/segmented-embedding.ts).acquirePageEmbeddingLeasetakes agbrain_cycle_locksrowembed-page:<page id>with plain statements (TTL 2 minutes, refreshed every 30 s while held, no process-liveness takeover), waiting with backoff while another path holds it; an effect renews its claim inwhileWaiting. The wait is bounded by the caller'sdeadline(embedStaleForSourcepasses its drain deadline) or one TTL, and then returns a busy lease ({ busy: true }): drains skip the page without counting a failure, the effect and the segmented effect throwpageEmbeddingLeaseUnavailable(lock_busy, retried with backoff), andembedSegmentedPagestops withstopped: 'busy'. A held lease'sassertHeld(tx)renews the row inside every install transaction and throwslock_busywhen it matches no row (the lease expired and another path took or deleted it), so a holder that stalled past the TTL installs nothing; a background refresh that matches no row marks the lease lost the same way.embedStalePageslooks the page id up first and reads its snapshot under the lease. Callers bind it withawait using, so leaving the scope releases it, error paths included; each release also deletes expiredembed-page:rows (a crashed holder's), which keeps doctorstale_locksfrom listing them past the next embed.NOT_PAGE_EMBEDDING_LEASE(onPAGE_EMBEDDING_LEASE_PREFIX) keeps these rows, live or expired, out of activation's legacy-lock inspection (persistence/legacy-locks.ts), deactivation's lease blockers and shared-skill activation's quiescence check: a lease dedupes provider calls and guards vector installs that ran unleased before it, its holders run inside a lock, job lease or effect claim those checks already see, and a crashed holder's expired row must not block them (the writer admin fingerprint inadmin-intent.tsskips them too). The holder then keeps only the chunks still without a vector (inline:stillPendingChunksover the freshgetChunksread; segmented:vectorlessChunkIndexes), so a drain whose listing predates an effect's install sends nothing for them.pageEmbeddingLeaseProbe(contended,waitBoundMs) is the test seam. Forced probes (effect first on a segmented page afterappend_page, drain first on an inline page; both engines):test/embed-once-per-content-version.serial.test.ts; bounded wait, lost lease, snapshot under the lease, expired-row sweep and release on throw (both engines):test/page-embedding-lease.serial.test.ts.src/core/embed-stale-images.ts—gbrain embed --stale --images [--source <id>] [--dry-run] [--json](requiresGBRAIN_EMBEDDING_MULTIMODAL=true): selects live image pages whose indeximportImageFile's hash-skip would call incomplete: an unsealed page only in thereimportclass (page-state/projection-class.ts;sealable,protectedandarchivedare counted, never candidates), a sealed one with noembedding_imagechunk or no OCR text/ocr_status: donewhileGBRAIN_EMBEDDING_IMAGE_OCR=true(incomplete_sealed);ocr_requiredcounts distrusted reimport pages (the dry run's expectation with OCR off, the importer's refusals after a run), resolves each file from the source'slocal_path(thedefaultsource falls back tosync.repo_path; a subpath-scopedsource_pathresolves against the checkout's git root; a page with no recordedsource_pathis located by its slug, which is the lower-cased repo-relative path, and counted inmissingSourcePath) and hands it back to the importer, so OCR budget, protected-OCR refusal and the rebuild stay there. #6529: on a managed brain the import goes throughimportManagedFile(the coordinated importer; the legacy writer refuses a managed brain), only for a file inside the source root, and the import recordssource_path. Reports candidates, rebuilt, unchanged, missing source files (missing_samples: up to 5source:slug: no file at <path tried>lines, the first printed) and failures; the explicit--imagesCLI (runEmbedStaleImagesCli) counts an all-missing, nothing-rebuilt sweep as failures (sweepFoundNoFiles), so it never exits 0 as a quiet success.runStaleImageSweepFirstis the sweep a plaingbrain embed --stale(no--slugs) runs before its text drain when multimodal embedding is on, andfoldImageSweepfolds it into theEmbedResultasimages: import failures count toward the run's failures, fileless pages are reported once on stderr (missingFile, first sample) and leave the exit code to the text run; a text-only install skips it and keeps the--imageshint. Pinned bytest/embed-stale-images.test.tsandtest/embed-stale-images-managed-6529.test.ts(both engines). Under a cost cap (fix wave 13 P1.18) each import is metered and the sweep stops before the next image once the cap refused; a refused image is not a failure. An explicit--imagesrun that rebuilds none of its candidates (files missing, left unchanged or needing OCR) reportsstatus: nothing_rebuiltwith areasonby cause and counts every candidate as failed, so it exits 1 (#7193;test/image-distrusted-reimport.test.ts).src/core/embed-budget-stop.ts— the loud time-budget stop forgbrain embed --stale.noteEmbedBudgetStop(engine, result, {sourceId, signature, includeNullSignature, skip})counts the stale chunks left (same predicate as the catch-up remaining count) and, when any remain, setsreason: 'time_budget',remaining_staleandresume_command(gbrain embed --stale --catch-up [--source X] [--include-null-signature]) on the result;skipcovers dry runs,--catch-upand caller aborts.embedBudgetStopVerdict(result)is the stdout verdictrunEmbedprints;src/cli/commands/embed.tsmaps the reason toBUDGET_STOP_EXIT_CODE(failures still win with 1). Called from every budget exit inembedAllStale(readiness-phase deadline returns and the main drain). Pinned bytest/embed.serial.test.ts("time-budget stop is loud").src/core/embed-cost-cap.ts— fix wave 13 P1.18 (from #6400): the approved--max-usd(or derived/default) cap of a foregroundgbrain embed.embedCostCap(cap, source)builds a BudgetTracker plus an AbortController; the first refused reservation aborts the run's signal before the refusal propagates, so page/batch catches treat it as shutdown (no failure, quarantine strike or per-chunk fan-out) and installed vectors stay banked.noteEmbedCostStoprecordsreason: 'cost_cap',budget_reason(cost/no_pricing), cap, spend and the resume command (the run without its approval flags);embedCostStopVerdictis the stdout line (stderr under--json). The gateway side:embedMultimodalreserves before any provider call (each image atMULTIMODAL_IMAGE_TOKEN_CEILING, Voyage's 16M-pixel maximum at 560 pixels per token) and settles at Voyage's reportedusage.total_tokens;generateOcrTextreserves and sendsmaxOutputTokens: OCR_MAX_OUTPUT_TOKENS, the bound it reserved (test/gateway-ocr-reserve.test.ts).src/core/embed-stall.ts— progress-keyed stall watchdog for embed drains (mirror of sync's stall watchdog; bounds embed drains that hang without a pinned root cause). Two clocks, one trigger: LIVENESS ticks vianoteEmbedApiResponse()on EVERY settled embed API attempt — success, error, or retry (hooked inembed-retry.ts:embedBatchWithBackoff; diagnostic only, distinguishes "fully wedged" from "live but failing" in the abort message, scoped to the armed run); the TRIGGER is no SUCCESSFUL forward progress (readProgress(), wired to chunks embedded) forGBRAIN_EMBED_STALL_ABORT_SECONDS(env-only knob; default 900 viaDEFAULT_EMBED_STALL_ABORT_SEC,<= 0disables, garbage falls back to default) — a retry storm that never lands a chunk trips it BY DESIGN. A stall produces an ERROR RESULT (reason: 'stall_timeout'), never aprocess.exit: only the CLI wrapper (src/commands/embed.ts:runEmbed) maps it to a non-zero exit, and minion handlers and the cycle's embed phase (cycle.ts:runPhaseEmbed) convert it to a failure viaassertEmbedNotStalled. The abort path runs an idempotent, deadline-bounded cleanup (EMBED_STALL_CLEANUP_DEADLINE_MS) that releases only the run's self-acquired single-flight locks and banks partial progress, so the next run resumes cleanly. The check interval is deliberately NOT unref'd — for non-single-flight callers it can be the only handle keeping a lost-promise hang loud;stop()clears it on every normal path. Pinned bytest/embed-stall.test.ts.src/core/embedding-dim-check.ts— facts.embedding dim drift surface.readFactsEmbeddingDim(engine): Promise<FactsColumnDimResult>covers bothvector(N)andhalfvec(N)shapes (migration v40 falls back tovectoron pgvector < 0.7); regex ordering is halfvec-before-vector (substring "vec" appears in "halfvec"; naive/vector/iwould shadow).buildFactsAlterRecipe(dims, configured, type)emits the paste-readyDROP INDEX IF EXISTS idx_facts_embedding_hnsw; ALTER TABLE facts ALTER COLUMN embedding TYPE halfvec(N) USING embedding::halfvec(N); CREATE INDEX idx_facts_embedding_hnsw ON facts USING hnsw (embedding halfvec_cosine_ops) WHERE ...flow (NOT bare REINDEX, which doesn't rewrite the index after a column-type change).assertFactsEmbeddingDimMatchesConfig(engine)is the preflight — throwsFactsEmbeddingDimMismatchError(taggedtag: 'FACTS_EMBEDDING_DIM_MISMATCH'for parity with the worker-pool MUST_ABORT semantics) when configured dim ≠ column width; cached per-engine viaWeakMap; PGLite engines silently skip. Doctor checkfacts_embedding_width_consistency(registered afterembedding_width_consistency) reuses the same helpers with an identical ALTER recipe.decorateEmbeddingDimError(err, slug): maps pgvector's bare "expected N dimensions, not M" write rejection to a namedOperationError('embedding_plane_split', …)carrying the consequence (page NOT written, transaction rolled back) + recovery command; applied atimportFromContent's transaction boundary sogbrain putfails loudly instead of echoing an unexplained provider string; every other error passes through untouched. Pinned bytest/embedding-dim-check-facts.test.ts+test/put-page-embedding-plane-split.test.ts.embeddingMismatchMessageon PGLite offers, in order, keeping the existing width when the requested model supports it (in-placeinit --force … --path <active>), a previewedgbrain migrate embeddings --to … --dim … --dry-runthat keeps pages and DB-only facts, andgbrain reinit-pgliteas the labelled last resort; it never prints a hand-run wipe.src/commands/embeddings.ts—gbrain embeddings enable --embedding-model <p:m> [--embedding-dimensions N] [--brain <id>] [--json]: turns embeddings on in place for the selected brain, including a mount (whereinit --forcewould repoint the host config at the mount's datastore). Opens the datastore, reads the vector column width (default for--embedding-dimensions) and stored identity; refuses withembedding_width_mismatchorembedding_model_mismatch(fix Action, nothing changed); refuses a mount whose host already embeds with another model (the model is host-wide). Writes the host file-planeembedding_model/embedding_dimensions, clearsembedding_disabled, and reportsqueued_chunks/queued_factsplusgbrain embed --stale [--brain]. The fix readiness emits for mounted brains; exercised bytest/readiness-embedding-enablement.serial.test.ts.gbrain embeddings prewarm [--dry-run] [--brain <id>] [--json]refuses a thin client and a PGLite brain (vector_prewarm_unsupported_engine) before opening an engine, then runscore/vector-prewarm.tsrunVectorPrewarmon the selected Postgres brain (it lives here, not undersearch, becausegbrain searchtakes a free-text query);test/vector-prewarm.test.tspins the CLI refusals.src/core/embed-overlength-heal.ts— [R13] (PR #5347): a chunk the embedder rejects as too long on a model with NO declaredmax_input_tokensis SPLIT, not parked and not retried identically forever.isSingleInputOverLengthError(lives insrc/core/embed-overlength-classify.ts, re-exported here: status 400/413/422 with one of the field-seen message shapes, or #6772 a 5xx or statusless error whose message names a token or context limit, such as llama.cpp's "larger than the max context size" and Ollama's 500 "input length exceeds the context length"; never a batch-shaped message or the gateway'sisTokenLimitError;isEmbedRetriableError,isTransientNetworkEmbedErrorandembedPageTexts' no-fan-out rule all exempt it, so the bad chunk is isolated instead of retried; teststest/embed-overlength-classification.test.ts,test/embed-partial-failure-3037.serial.test.ts),overLengthLimitFromMessage,deriveOverLengthChunkCap(named limit ×EMBED_INPUT_SAFETY, else half the largest failed text's estimate; null when not below the current cap or belowMIN_USEFUL_CHUNK_TOKENS= 128),healPageAfterOverLength(learns the cap for the model, heals the page at that cap at once;skippedwith a reason —not_overlength,unresolved_model,declared_cap(recipe orGBRAIN_MAX_CHUNK_TOKENS: the declaration is what to fix),attempts_exhausted(MAX_OVERLENGTH_HEAL_ATTEMPTS= 3 per page per process),cap_floor,nothing_to_split,heal_failed— leaves the page untouched) anddescribeOverLengthOutcome(the operator line naming the fix).healAndReportOverLengthis the one-liner every failure site calls:src/commands/embed.ts(embedPage total/partial failure, embedAll, embedAllStale) andsrc/core/embed-stale.ts(embedStaleForSourcecatch).statusFromCausemoved here from embed.ts (one home). Pinned bytest/embed-overlength-heal.test.tsandtest/embed-overlength-drain.serial.test.ts.src/core/embedding-input-limit.ts— per-model embedding INPUT token caps. Some hosted encoders reject any single input over a hard per-input limit far below their batch budget (a 512-token model would otherwise leave ~35% of a typical vault's chunks permanently unembeddable, re-failing every sweep).resolveMaxChunkTokens(env?)resolves the effective chunk-token cap for the ACTIVE embedding model so the chunkers SPLIT (never truncate) at a size the model accepts:GBRAIN_MAX_CHUNK_TOKENSenv (escape hatch for models not in a recipe; warn-once per distinct invalid value) → recipe per-modelmax_input_tokens×EMBED_INPUT_SAFETY(0.6 — covers the cl100k-basedestimateEmbedTokensoverestimate vs BERT-wordpiece tokenizer mismatch) →DEFAULT_MAX_CHUNK_TOKENS(2000 for every other provider).MIN_CHUNK_TOKENSfloor of 64 so a tiny declared limit can't produce confetti chunks; fail-open on any resolver error (a resolver bug must never change chunking for unaffected installs).maxInputTokensForModel(recipe, modelId)mirrorsmodel_dims' case-fold lookup rule (exact match first, then case-insensitive scan). Consumed atimport-file.ts's chunk step. Pinned bytest/embedding-input-limit.test.ts. Declared limits ([R13] audit, PR #5922): NVIDIAnvidia/nv-embedqa-e5-v5512; DashScopetext-embedding-v1/v22048,v38192; Googlegemini-embedding-0012048 (the endpoint truncates silently past it); Zhipuembedding-2512,embedding-33072; OpenAItext-embedding-3-*8191 and Mistralmistral-embed8192 (above the default, so no chunking change). Pinned bytest/embedding-input-limit-hosted-caps.test.ts. Learned caps (learnChunkCap/learnedChunkCap/_resetLearnedChunkCapsForTest): a process-lifetime per-provider:modelchunk cap thatsrc/core/embed-overlength-heal.tsderives from a provider's single-input over-length rejection when the model declares nothing;resolveMaxChunkTokensapplies it after the env override and the recipe declaration (both win over it), clamped to the same floor/ceiling.src/core/embedding-invalidation.ts— signature-truth guards shared by migration and embed paths, using identical SQL on both engines.invalidateStaleSignatureEmbeddingsGuarded(engine, {signature, sourceId?, includeNullSignature?})adds the stale selectors' embed-skip and projection-seal fences to raw engine invalidation. It runs as one statement pair per window ofSIGNATURE_INVALIDATION_PAGE_BATCH(1000) page ids inside one transaction, so a full-corpus model swap on a large brain stays inside the statement timeout (#7148; Postgres proof intest/e2e/stale-signature-invalidation-postgres.test.ts).hasSignatureDriftis the embed paths' page-first pre-check: one EXISTS instead of two corpus-wide counts, so a healthy brain never readscontent_chunksfor it and a drifted brain is never counted before the probe. Current model/hash/width chunks survive interrupted batches; fully current active pages can be restamped without another embedding call. SourceFOR SHARElocks precede mutation in short transactions, serializing both signature writes, raw engine signature/content-drift invalidation, false-stamp clearing and final reconciliation against archive. Archived vectors and page signatures are never mutated. The sharedfalseStampPageWhereandcountFalseStampedChunksremain archive-visible for retention, plan and completion diagnostics; only the clearing write is fenced. Bare provider-less model aliases retain their existing exemption. Provider dispatch and completion smoke run outside source locks and revalidate live, safe snapshots before sending text. Pinned bytest/embedding-migration.test.tsand the sharedtest/embedding-recovery.serial.test.tssuite: PGLite runs in the serial lane, whiletest/e2e/embedding-recovery-parity.test.tsselects PostgreSQL.src/core/embedding-pricing.ts—EMBEDDING_PRICINGmap keyedprovider:modelfor the post-upgrade reindex cost estimate. Sibling toanthropic-pricing.ts; EMBEDDINGS only — chat/completion pricing lives inmodel-pricing.ts(different unit) and is never mixed in. Every entry carries its official source URL + the date it was last read. Entries: OpenAI text-embedding-3-large ($0.13/1M), 3-small ($0.02/1M), ada-002 ($0.10/1M); Voyage 4-large ($0.12/1M), 4 ($0.06/1M), 4-lite ($0.02/1M), legacy 3-large ($0.18/1M), 3 ($0.06/1M); Mistral mistral-embed ($0.10/1M); Perplexity pplx-embed-v1-4b ($0.03/1M), 0.6b ($0.004/1M).voyage-4-nanois deliberately unpriced (open-weight variant, no published hosted rate) so it degrades to "estimate unavailable" rather than a fabricated 0.lookupEmbeddingPrice(modelString)returns a tagged union (knownwith price +unknownwith provider name);estimateCostFromChars(charCount, pricePerMTok)uses 3.5 chars/token. Unknown providers degrade to "estimate unavailable" instead of fabricating numbers.src/core/embedding.ts— OpenAI text-embedding-3-large, batch, retry, backoff.BATCH_SIZE=100(per-recipe pre-split + recursive halving + adaptive shrink-on-miss live in the gateway; the outer paginator is for progress-callback granularity, not batch protection).estimateEmbeddingCostUsd(tokens)prices against the currently-configured model's rate viacurrentEmbeddingPricePerMTok()(resolves the per-1M-token rate vialookupEmbeddingPrice(gatewayGetModel())fromembedding-pricing.ts, falling back to the OpenAI 3-large rate 0.13 only when the gateway is unconfigured or the model is unknown to the pricing table).EMBEDDING_COST_PER_1K_TOKENSretained for back-compat with direct importers/tests.currentEmbeddingSignature(): stringreturns the embedding-provenance signature<provider:model>:<dims>(e.g.openai:text-embedding-3-large:1536) stamped ontopages.embedding_signatureat every embed-write site; DELIBERATELY excludes the chunker version (tracked separately viapages.chunker_version) — this signature is strictly the EMBEDDING space, so a model OR dimension swap makes the stored signature differ from current and a page becomes stale. Same unconfigured-gateway fallback as the cost helpers. (Seesrc/core/sync-delta.ts+src/core/spend-posture.tsfor the cost-gate supporting modules.)willEmbedSynchronously({v2Enabled, serialFlag, noEmbed}): SyncEmbedModeretains the package-exported compatibility contract for downstream TypeScript and JavaScript consumers. The command-internalresolveWorkerBackedSyncEmbedMode({deferEligible, noEmbed})uses the engine-aware admission result, so PGLite/unknown runtimes stay inline while worker-backed Postgres preserves v2 deferral even with one runnable source; source count separately controls fan-out.shouldBlockSync(costUsd, floorUsd, mode, posture='gated'): booleanis the pure cost-gate decision: blocks ONLY whenmode === 'inline' && costUsd > floorUsd— deferred mode never blocks (the backfill's $X/source/24h cap is the real money gate), andposture === 'tokenmax'never blocks (the operator declared cost isn't the constraint; anoff/unlimitedfloor isInfinityand so is never exceeded). Pinned bytest/sync-cost-preview.test.ts+test/embedding-signature-stale.test.ts. The Google embedding recipe caps each provider batch at 100; gateway splitting preserves input/vector order.src/core/init-embed-check.ts— embedding-key validation atgbrain init.runInitEmbedCheck(opts)runs a config-onlydiagnoseEmbedding(catches a missing key for ANY provider) plus a best-effortliveTestEmbed(1-tokengateway.embed(['probe'], {inputType:'query', abortSignal}), 5sAbortControllertimeout, never throws — catches an invalid/expired key). Loud warning to stderr; init still exits 0 (--no-embeddingis the deferred-setup escape;--skip-embed-check/GBRAIN_INIT_SKIP_EMBED_CHECK=1skip the check). Builds the effective env (process.env+ every file-plane provider keybuildGatewayConfigfolds — openai/anthropic/voyage/dashscope/google — fromloadConfigFileOnly()+opts.apiKey) and configures the gateway viabuildGatewayConfigbefore diagnose/probe, so the check sees the same keys AND provider base URLs runtime will (no false "missing key" for config.json-keyed users; the probe hits the right endpoint). Init-specific warning text names--no-embedding/--skip-embed-check, not the sync-flavored--no-embed. Wired intoinitPGLite+initPostgresinsrc/commands/init.ts, with the result added to the--jsonenvelope asembedding_check {ok, reason?, live_ok?}. Pinned bytest/init-embed-check.test.ts(hermetic via the gateway embed-transport seam +withEnv).src/commands/init-embedding-plane.ts— GBRA-248: when init fell back to keyless only because no provider key was found (ResolvedAIOptions.implicitKeyless) and the database is not fresh,keptEmbeddingIdentitykeeps the database's stored model and width (or leaves embedding settings unchanged when its vectors' identity cannot be confirmed) instead of writingembedding_disabled, unless the database plane already disables embeddings or holds only the schema seed with no vectors;keptEmbeddingNoticenames the provider key andgbrain embed --stale.src/core/llm-json.ts— tolerant JSON extraction from LLM output.parseLlmJson<T>(raw, {array?})walks a strategy ladder (stripjson fences → direct parse → first `{...}`/`[...]` substring; when the fenced extract fails, the same parses retry from the opening fence, or on the whole text when the fence sat inside a JSON string, so a quotedcannot truncate the payload), then — only after the raw parse has failed — retries the same ladder with reasoning blocks stripped, so a payload that parses raw is untouched and a payload legitimately containing<think>is unaffected; returns null on any failure (adversarial throws swallowed). ExportsstripReasoningBlocks(raw): removes closed<think>…</think>pairs AND a truncated never-closed<think>tail (output-budget exhaustion) — reasoning models draft their JSON inside the think block, which defeats the greedy first-to-last-brace substring scan. ExportsmatchingCloseBracket(text, openAt = 0): the index of the bracket closing the array/object that opens attext[openAt](counts the opener's own kind, skips string literals whole including escapes; -1 whentext[openAt]is not a bracket or the value never closes), which the chronicle judge, propose_takes and extract_atoms recovery paths use so a trailing[Source: X]citation cannot hijack the slice.src/core/facts/extract.ts's hand-rolledparseExtractorJsonDetailedapplies the same raw-first fallback ladder with the sharedstripReasoningBlocks.src/core/model-config.ts— Model-string resolution (the seam every internal LLM call walks through). Four-tier system (ModelTier = 'utility' | 'reasoning' | 'deep' | 'subagent') withTIER_DEFAULTS(utility→haiku-4-5, reasoning→sonnet-4-6, deep→opus-4-7, subagent→sonnet-4-6) andtier?: ModelTieronResolveModelOpts.resolveModelDetailed()runs the 8-step chain and reports WHICH step won (ResolveSource): cliFlag → config key → deprecated key →models.tier.<tier>→models.default→ env var (GBRAIN_MODEL) → key-aware tier default → caller fallback (the tier key sits ABOVEmodels.default— tier-specific beats generic, so setting a cheap utility tier is honored even whenmodels.defaultis also set);resolveModel()is the thin wrapper for callers that only want the string. When the subagent capability gate replaces a configured model, the detailed result carriessubstituted_from+substitution_reason(no_tools/no_subagent_loop/unknown_provider);describeResolveOrigin(source, opts)renders the key-name origin (models.tier.deep,models.default,GBRAIN_MODEL,built-in default) used by the skillopt banner andgbrain models. Step 7 is KEY-AWARE:resolveTierDefault(tier, env?)walksPROVIDER_TIER_DEFAULTS(anthropic first — zero change for keyed installs; openai second so an OPENAI_API_KEY-only install resolves servable defaults) over the merged provider env (mergedProviderEnv, config-file keys folded, env wins, empty strings dropped); injectedenvis used EXCLUSIVELY (no config read — hermetic for tests); when neither anthropic nor openai key is present, a SERVABLE file-plane pin for the tier (utility→expansion_model, other tiers→chat_model, checked viaproviderKeyReady,PIN_KEY_BY_TIERis the single tier→key map) wins over the floor so a single-provider install (DeepSeek-only, OpenRouter-only, ...) routes every bare-default caller — extract_atoms, facts classify, page-summary — to the provider it actually has a key for; no key and no servable pin →TIER_DEFAULTSunchanged. The openai entry carries NO literal model pins: it resolves per call through the latest-model discovery cache (src/core/ai/openai-latest.ts, account-discovered, priced-only) withopenaiStaticTierFallback()— the openai recipe's chat list ranked by the same grammar — as the offline floor, so the recipe is the single human-updated source and the account is the runtime source. Thegptalias resolves dynamically through the same path (the map entry is a documentation floor).resolveEffectiveChatModel(fileCfg, env)/resolveEffectiveExpansionModelare the ENGINE-FREE shared effective-model resolvers (GBRAIN_MODEL> servable file pin perproviderKeyReady(recipeauth_env.required) > key-aware tier default; unservable pins warn once and fall through) — used by BOTHreconfigureGatewayWithEngine's fallback layer anddetectCapabilities' extraction probe so runtime routing and the capability report cannot diverge; they read RAWloadConfig()output, never gateway state (the boot fold stamps defaults, making explicit pins indistinguishable there).isAnthropicProvider(modelString)checksprovider:modelprefix ORclaude-bare-id pattern (routes throughsplitProviderModelIdfromsrc/core/model-id.tsso slash-form ids likeanthropic/claude-sonnet-4-6classify correctly).enforceSubagentCapable()is the layer-2 runtime guard:tier === 'subagent'resolutions are classified viaclassifyCapabilities()—unusable:no_tools/unknownwarn once and fall back toTIER_DEFAULTS.subagent;degraded:no_caching(e.g. OpenAI) passes with a once-per-(source, model)cost warn._resetDeprecationWarningsForTest()clears all three warn memos (deprecation, subagent, unservable-pin). Pinned bytest/model-config.serial.test.ts.src/core/model-id.ts—splitProviderModelId(input: string | null | undefined): {provider: string | null, model: string}shared parser for the pricing side. Splits on:first, then/. Defensive contract: null/undefined/empty/whitespace returns{provider: null, model: ''}. Five sites consume it (src/core/anthropic-pricing.ts:estimateMaxCostUsd,src/core/budget/budget-tracker.ts:lookupPricing,src/core/eval-contradictions/cost-tracker.ts:pricingFor,src/core/model-config.ts:isAnthropicProvider) so the pricing + classification surface has no parallel re-implementations ofprovider:modelsplitting — slash-form ids (anthropic/claude-sonnet-4-6) classify correctly instead of falling through to "unknown model". Distinct from the gateway-sideparseModelIdinsrc/core/ai/model-resolver.ts, which throws on bare names because routing needs an explicit provider; this one returns{provider: null, model: 'bare'}because pricing lookups happen against bare model ids. Pinned bytest/model-id.test.ts.src/core/model-pricing.ts— single source of truth for paid-cloud CHAT/completion model pricing (USD per 1M tokens, input | output).CANONICAL_PRICINGis aprovider:model-keyed table (Anthropic Opus 5/4.8/4.7/4.6$5/$25, Sonnet 4.6$3/$15, Haiku 4.5$1/$5both dateless + dated, plus OpenAI / Google / Together / DeepSeek panel models). Exported asgbrain/core/model-pricingfor companion evaluators to enforce the canonical price cap.canonicalLookup(modelId)resolves bare (claude-opus-4-8), colon (anthropic:claude-opus-4-8), and slash (anthropic/...) forms — bare ids default to theanthropic:provider; nested OpenRouter ids (openrouter:anthropic/...) intentionally MISS so OpenRouter markup isn't repriced as the inner vendor; after the exact match, a case-insensitive fallback folds BOTH sides (some canonical keys carry cased model tails verbatim), safe only while no two canonical keys collide case-insensitively (pinned by the drift guard). Every other chat-pricing table is a DERIVED view of this one (NOT a hand-copied duplicate), so cross-table price drift is structurally impossible. Embeddings live separately inembedding-pricing.ts(different unit). DeepSeek rows (deepseek-flash, its legacy aliasdeepseek-v4-flash,deepseek-v4-pro) carry the vendor's PEAK rate so caps bound the worst case;peakRateNote(models)insrc/core/budget/reservation-cost.tslabels estimates that use them. OpenRouter rows are the router's own catalogue rate, never the vendor's.bun run check:recipe-pricing(scripts/check-recipe-pricing.ts) requires every recipe touchpoint model to price or be named in the recipe'sunpriced_models. Pinned bytest/model-pricing.test.tswhose drift guard asserts each derived view equals canonical and that the cross-modal panel models are all present. Long-prompt tiers (#6448 item 1): a row may carrylong_prompt: LongPromptTier(threshold_tokens+ a full rate set);priceAtPromptSize(row, inputTokens)returns the tier (tier-free) when the call's input tokens are STRICTLY above the threshold, else the base row. Haiku 5.5 declares the vendor's 5x tier aboveANTHROPIC_LONG_PROMPT_THRESHOLD_TOKENS(100,000; the tier's cache rates derive from the tier's input rate by the row's multipliers, pinned by the drift guard). Every spend site prices through it:usageCostUsd/reservationCostUsdinsrc/core/budget/reservation-cost.ts(soBudgetTracker.reserve/recordand the audit line see the tier; the reservation sizes the tier by the ESTIMATED input tokens, the record by the servedinput_tokens + cache_read + cache_write) andestimateChatCostUsdinsrc/core/ai/chat-usage.ts. The gateway's pre-call input estimate isestimateChatInputTokensinsrc/core/ai/chat-input-estimate.ts(system + text + tool calls/results + tool definitions atCHAT_INPUT_CHARS_PER_TOKEN), shared with the reservation so a 100K+ reservation is held at the tier rate. Pinned bytest/model-pricing-long-context-tier.test.tsandtest/model-pricing-tier-helpers.test.ts.src/core/post-upgrade-reembed.ts— Pure functions backing thegbrain upgradechunker-bump cost prompt.computeReembedEstimate(engine, model)queries real SQL (COUNT(*)+COALESCE(SUM(LENGTH(compiled_truth)) + SUM(LENGTH(timeline)), 0)) onpages WHERE chunker_version < MARKDOWN_CHUNKER_VERSION.formatReembedPrompt(est)is the stderr-line formatter (count, model, cost estimate when priced).runPostUpgradeReembedPrompt(engine, model, opts)re-embeds only on consent: a TTY operator must answeryto[chunker-bump] Re-embed now? [y/N]; the default, EOF and every non-TTY run decline and printREEMBED_DEFERRED_HINT(gbrain reindex --markdown, orgbrain repair safe-chunks --apply --no-embedthengbrain embed --stale), so an unattended upgrade never spends. Reasons:no_pending,bypassed_no_reembed,consent_required,tty_declined,tty_consented.GBRAIN_NO_REEMBED=1skips the prompt with a doctor-warning marker.opts.confirmandopts.isTTYare test seams.src/core/schema-embedded.generated.ts— AUTO-GENERATED from schema.sql byscripts/build-schema.ts(runbun run build:schema, which also regenerates schema.sql's fragment regions and the PGLite templatesrc/core/pglite-schema.generated.ts, exposed through thesrc/core/pglite-schema.tsfaçade; canonical-source graph indocs/ENGINES.md#canonical-schema-sources; the.generated.tssuffix exempts it from the module-size ratchet's new-file cap, per the guard's generated-file carve-out)src/core/spend-log.ts— per-OAuth-client paid-API spend tracking against themcp_spend_logtable.checkBudget(engine, clientId, capCents)is the pre-flight gate; throwsBudgetExceededErrorwhen today's spend has hit the cap.recordSpend(engine, entry)is best-effort post-call. UTC day-aligned aggregation so caps roll over deterministically regardless of server timezone. Local CLI callers (no clientId) bypass the gate; brains without the table fail open to spend=0.VOYAGE_MULTIMODAL_3_PER_IMAGE_CENTS= 0.12 cents per image embed.src/core/spend-posture.ts— spend-control surface.resolveSpendPosture(engine): 'gated'|'tokenmax'(DB-planespend.posture, fail-opengated);tokenmaxmakes every cost gate informational across sync/reindex/enrich/onboard (spend still ledgered — removes the ceiling, not the accounting).parseUsdLimit(raw, def, {allowZero?})acceptsoff/unlimited/none→Infinity;formatUsdLimit(n)rendersInfinityas the string'unlimited'(never raw —JSON.stringify(Infinity)isnull);usdLimitToCap(n)mapsInfinity→undefinedat the BudgetTracker boundary so ledger rows never serialize null.normalizeSpendPosture/isValidSpendPostureback theconfig setvalidation. Doc:docs/operations/spend-controls.md. Pinned bytest/sync-cost-preview.test.ts+test/spend-off-switch.test.ts.src/core/transcription.ts— Audio transcription: Groq Whisper (default), OpenAI fallback, ffmpeg segmentation for >25MB. Each provider request routes throughinvokeAIwith kindtranscription, so admission guards and invocation observers see it.