Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
54.0 KB
Raw Blame

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. countArchivedEmbeddingWork classifies 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 (a rebuild_failed image row keeps its reason); its blocked message names gbrain projections drain for the importer-attested ones and gbrain doctor --only text_projection_readiness --json for the class counts; listPendingProjectionPages lists the first blocked pages and reportBlockedProjections writes the CLI's failure sample. embed --stale and embedStaleForSource no longer stop when pages stay blocked: the guarded drain skips their unsealed snapshots (the CLI counts their chunks as failures and names them with gbrain embed --stale --images; the source drain adds them to blocked and 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 a FOR UPDATE on 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, adds overshoot_usd and sets halted, which refuses further dispatch until an explicit --max-cost-usd renewal. authorizeMigrationBudget(..., worstCase) throws MigrationBudgetRefusal (embedding_budget_below_worst_case, with cap, worst case, retained debits, the filled --max-cost-usd command and the write-refusals.md anchor) 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 from embed-batch-plan.ts over 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 by healOversizedChunks at the target chunk size over the complete page (a split re-indexes siblings, so every healed chunk of that page counts) and wrapped with wrapChunkTextsForStoredMode, the chunks projection recovery and the chunkless heal will create — replayed through readProjectionSnapshot + preparePageProjection at 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. usd is null only when the embedding model is unpriced; an unpriced reranker lands in unpriced_models and 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; partiallyEmbeddedFact flags facts whose UTF-16 length exceeds EMBED_MAX_CHARS (#6975). Legacy identity stays unknown. Both engine writers accept explicit embedding_model and compute the exact text hash; duplicate vector selection requires matching caller identity. embed-facts.ts installs 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 of model-pricing.ts (the anthropic: canonical entries with the prefix stripped). Kept distinct because many callers look up by bare Claude id and because estimateMaxCostUsd(modelId, inTokens, maxOutTokens) carries the null-on-miss contract the dream-cycle budget gate depends on (non-Anthropic ids return null; BudgetMeter tries canonicalLookup first and only falls back here, so it warns BUDGET_METER_NO_PRICING and runs unbounded only when canonical has no rates either). estimateMaxCostUsd routes bare/colon/slash ids through splitProviderModelId. Do NOT hand-edit prices here — the map is derived from canonical, so it cannot drift. ANTHROPIC_PRICING is consumed by budget/budget-tracker.ts and cycle/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 in page-state/projections.ts indexing 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 as page_body_segmented with nothing stamped, and the contextual_reindex_per_chunk job result names it in skip_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.ts covers 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: submitted requires jobId plus an explicit spend-bypass payload, cooldown requires a reason plus a numeric remaining duration or explicit null for active work, spend_capped requires cap/spend payloads, and no_worker_surface requires 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 private writer_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 of remaining. readOversizedStaleFacts (src/core/facts/embedding-identity.ts) feeds that, doctor fact_take_vectors and gbrain 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). embeddingInputHash digests 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, synopsisBodyHash of the chunk set and the text). acceptedEmbeddingInputHashes also accepts title-tier vectors on synopsis pages; plainEmbeddingTier mirrors wrapChunkTextsForStoredMode. A body change therefore nulls every synopsis-tier chunk and nothing else unchanged. Pinned by test/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 respect resolveMaxChunkTokens(), but --stale re-embeds existing chunk_text rows chunked under looser caps, which fail every sweep forever). healOversizedChunks splits 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 so upsertChunks preserves vectors for unchanged (chunk_index, chunk_text) pairs and NULLs the split/shifted ones; healOversizedPageChunks is 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 between src/commands/embed.ts:embedAllStale and src/core/embed-stale.ts:embedStaleForSource so the two drains cannot drift; chunk_source passes through UNCHANGED (coercing fenced_code to compiled_truth would make wrapChunkTextsForStoredMode prefix code chunks, violating the D20-T4 never-wrap convention). Pinned by test/embed-oversize-heal.test.ts.

  • src/core/embed-retry.ts — embed retry/backoff primitives + the title-tier restamp helper. An EmbeddingZeroNormError (#4616) is never retried or classified transient; embedBatchKeepingUsable returns the usable vectors of a partially refused batch with the refusal, and still throws when nothing is usable. It stays in core because src/core/import-file.ts and src/core/embed-stale.ts consume 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). embedBatchWithBackoff wraps embedBatch with rate-limit-aware retry: detects 429s via the wrapped error's cause.status (message-match fallback), also retries transient gateway 502/503/504, parses provider retry-delay hints, jitters ±30% so concurrent workers don't resynchronize, passes maxRetries: 0 through 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. restampIfDemotedToTitleTier restamps a per_chunk_synopsis page's CR state to 'title' after a plain re-embed so contextual_retrieval_mode keeps describing the vectors actually in the column (the reindex sweep restores the synopsis tier later). src/commands/embed.ts re-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. Exports shouldSkipEmbedding(frontmatter): boolean (JS predicate for callers holding the page in memory), EMBED_SKIP_SQL_FRAGMENT (parameterized SQL clause shared by Postgres + PGLite via executeRaw), and buildEmbedSkipMarker(reason: string) (writes frontmatter.embed_skip = {at: ISO_TIMESTAMP, reason} so the JSONB shape stays uniform). The 5 sites: embed.ts --stale, embed.ts --all, the embed-stale Minion helper, plus both engines' listStaleChunks + countStaleChunks. Single source of truth so the filter cannot drift. Pinned by test/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 of embedded | pending | keyword_only | quarantined | empty | deleted_page_chunks | chunkless_healable against the ACTIVE embedding column (no stored status). The classifier SQL lives once in engine-sql/chunks.ts (chunkEmbeddingState reuses staleChunkWhere, chunklessPageState reuses chunklessPagesWhere, which skips a page whose current revision's text projection is sealed with no chunks unless it carries embed_skip, so a body the writer chunked to nothing (only a takes fence) is empty, not healable; deleteChunks and an empty fragment replacement clear the seal, so a page emptied after sealing stays healable: #8473, test/embedding-state-projection-empty-8473.test.ts) behind BrainEngine.readEmbeddingStateCounts / listEmbeddingStateRows. readEmbeddingState(engine, { mode, sourceIds }): full is exact; ops reads only index-backed counts (the partial index WHERE <active column> IS NULL, the frontmatter GIN, the purge index; embedded is a planner estimate) and is status: 'unknown', reason: 'no_covering_index' without that index, never a scan. unsearchable sums pending, quarantined, empty and chunkless_healable (pending drops out on a brain keyless by choice). embeddingStateFix builds each state's protocol fix from existing commands. Consumers: doctor embedding_state, gbrain pages unsearchable, lane B's get_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 three src/commands/embed.ts paths 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.ts also retains this atomic completion boundary. test/embedding-completion-atomic.serial.test.ts exercises all five completion paths; test/e2e/migration-wave-healing-fence.test.ts pins healing rollback on both engines. #5902: without an explicit concurrency, embedStaleForSource (the unpaced embed-backfill job and the remediation embed step) runs resolveStaleEmbedConcurrency workers from src/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 explicit GBRAIN_EMBED_CONCURRENCY keeps the full-pool clamp. Pinned by test/embed-stale-pool-default.test.ts + test/e2e/embed-stale-pool-default-postgres.test.ts. Wave B: a segmented page is embedded by page-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 embed and the post-commit embedding effect (data.occurrence_ids limits 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? }) runs engine-sql/chunks.ts invalidateContentDriftBatch (5,000 chunk rows past the cursor in id order, bounded before any md5) one transaction per batch, committing the cursor in config row embed.content_drift_sweep.<column>.<all|source:id> with the batch under a FOR UPDATE lock 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 after embed.content_drift.pass_interval_hours (default 24) unless it fit in one batch. A failed batch is returned as state: 'failed' with the error and recorded as last_error (cleared by the next committed batch); a missing v133/v221 column is unsupported; an assertOwned throw propagates. embedAllStale (EmbedResult.content_drift), embedStaleForSource (contentDrift) and the embed, embed-backfill and cycle embed results carry the status; doctor content_drift_sweep reads 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), the gbrain embed --stale drain (src/commands/embed.ts), embedStaleForSource and embedStalePages (embed-stale.ts), and every segmented install (embedSegmentedRows in page-body/segmented-embedding.ts). acquirePageEmbeddingLease takes a gbrain_cycle_locks row embed-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 in whileWaiting. The wait is bounded by the caller's deadline (embedStaleForSource passes 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 throw pageEmbeddingLeaseUnavailable (lock_busy, retried with backoff), and embedSegmentedPage stops with stopped: 'busy'. A held lease's assertHeld(tx) renews the row inside every install transaction and throws lock_busy when 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. embedStalePages looks the page id up first and reads its snapshot under the lease. Callers bind it with await using, so leaving the scope releases it, error paths included; each release also deletes expired embed-page: rows (a crashed holder's), which keeps doctor stale_locks from listing them past the next embed. NOT_PAGE_EMBEDDING_LEASE (on PAGE_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 in admin-intent.ts skips them too). The holder then keeps only the chunks still without a vector (inline: stillPendingChunks over the fresh getChunks read; 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 after append_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] (requires GBRAIN_EMBEDDING_MULTIMODAL=true): selects live image pages whose index importImageFile's hash-skip would call incomplete: an unsealed page only in the reimport class (page-state/projection-class.ts; sealable, protected and archived are counted, never candidates), a sealed one with no embedding_image chunk or no OCR text/ocr_status: done while GBRAIN_EMBEDDING_IMAGE_OCR=true (incomplete_sealed); ocr_required counts distrusted reimport pages (the dry run's expectation with OCR off, the importer's refusals after a run), resolves each file from the source's local_path (the default source falls back to sync.repo_path; a subpath-scoped source_path resolves against the checkout's git root; a page with no recorded source_path is located by its slug, which is the lower-cased repo-relative path, and counted in missingSourcePath) 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 through importManagedFile (the coordinated importer; the legacy writer refuses a managed brain), only for a file inside the source root, and the import records source_path. Reports candidates, rebuilt, unchanged, missing source files (missing_samples: up to 5 source:slug: no file at <path tried> lines, the first printed) and failures; the explicit --images CLI (runEmbedStaleImagesCli) counts an all-missing, nothing-rebuilt sweep as failures (sweepFoundNoFiles), so it never exits 0 as a quiet success. runStaleImageSweepFirst is the sweep a plain gbrain embed --stale (no --slugs) runs before its text drain when multimodal embedding is on, and foldImageSweep folds it into the EmbedResult as images: 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 --images hint. Pinned by test/embed-stale-images.test.ts and test/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 --images run that rebuilds none of its candidates (files missing, left unchanged or needing OCR) reports status: nothing_rebuilt with a reason by 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 for gbrain 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, sets reason: 'time_budget', remaining_stale and resume_command (gbrain embed --stale --catch-up [--source X] [--include-null-signature]) on the result; skip covers dry runs, --catch-up and caller aborts. embedBudgetStopVerdict(result) is the stdout verdict runEmbed prints; src/cli/commands/embed.ts maps the reason to BUDGET_STOP_EXIT_CODE (failures still win with 1). Called from every budget exit in embedAllStale (readiness-phase deadline returns and the main drain). Pinned by test/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 foreground gbrain 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. noteEmbedCostStop records reason: 'cost_cap', budget_reason (cost/no_pricing), cap, spend and the resume command (the run without its approval flags); embedCostStopVerdict is the stdout line (stderr under --json). The gateway side: embedMultimodal reserves before any provider call (each image at MULTIMODAL_IMAGE_TOKEN_CEILING, Voyage's 16M-pixel maximum at 560 pixels per token) and settles at Voyage's reported usage.total_tokens; generateOcrText reserves and sends maxOutputTokens: 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 via noteEmbedApiResponse() on EVERY settled embed API attempt — success, error, or retry (hooked in embed-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) for GBRAIN_EMBED_STALL_ABORT_SECONDS (env-only knob; default 900 via DEFAULT_EMBED_STALL_ABORT_SEC, <= 0 disables, 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 a process.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 via assertEmbedNotStalled. 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 by test/embed-stall.test.ts.

  • src/core/embedding-dim-check.ts — facts.embedding dim drift surface. readFactsEmbeddingDim(engine): Promise<FactsColumnDimResult> covers both vector(N) and halfvec(N) shapes (migration v40 falls back to vector on pgvector < 0.7); regex ordering is halfvec-before-vector (substring "vec" appears in "halfvec"; naive /vector/i would shadow). buildFactsAlterRecipe(dims, configured, type) emits the paste-ready DROP 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 — throws FactsEmbeddingDimMismatchError (tagged tag: 'FACTS_EMBEDDING_DIM_MISMATCH' for parity with the worker-pool MUST_ABORT semantics) when configured dim ≠ column width; cached per-engine via WeakMap; PGLite engines silently skip. Doctor check facts_embedding_width_consistency (registered after embedding_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 named OperationError('embedding_plane_split', …) carrying the consequence (page NOT written, transaction rolled back) + recovery command; applied at importFromContent's transaction boundary so gbrain put fails loudly instead of echoing an unexplained provider string; every other error passes through untouched. Pinned by test/embedding-dim-check-facts.test.ts + test/put-page-embedding-plane-split.test.ts. embeddingMismatchMessage on PGLite offers, in order, keeping the existing width when the requested model supports it (in-place init --force … --path <active>), a previewed gbrain migrate embeddings --to … --dim … --dry-run that keeps pages and DB-only facts, and gbrain reinit-pglite as 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 (where init --force would 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 with embedding_width_mismatch or embedding_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-plane embedding_model/embedding_dimensions, clears embedding_disabled, and reports queued_chunks/queued_facts plus gbrain embed --stale [--brain]. The fix readiness emits for mounted brains; exercised by test/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 runs core/vector-prewarm.ts runVectorPrewarm on the selected Postgres brain (it lives here, not under search, because gbrain search takes a free-text query); test/vector-prewarm.test.ts pins 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 declared max_input_tokens is SPLIT, not parked and not retried identically forever. isSingleInputOverLengthError (lives in src/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's isTokenLimitError; isEmbedRetriableError, isTransientNetworkEmbedError and embedPageTexts' no-fan-out rule all exempt it, so the bad chunk is isolated instead of retried; tests test/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 below MIN_USEFUL_CHUNK_TOKENS = 128), healPageAfterOverLength (learns the cap for the model, heals the page at that cap at once; skipped with a reason — not_overlength, unresolved_model, declared_cap (recipe or GBRAIN_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) and describeOverLengthOutcome (the operator line naming the fix). healAndReportOverLength is the one-liner every failure site calls: src/commands/embed.ts (embedPage total/partial failure, embedAll, embedAllStale) and src/core/embed-stale.ts (embedStaleForSource catch). statusFromCause moved here from embed.ts (one home). Pinned by test/embed-overlength-heal.test.ts and test/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_TOKENS env (escape hatch for models not in a recipe; warn-once per distinct invalid value) → recipe per-model max_input_tokens × EMBED_INPUT_SAFETY (0.6 — covers the cl100k-based estimateEmbedTokens overestimate vs BERT-wordpiece tokenizer mismatch) → DEFAULT_MAX_CHUNK_TOKENS (2000 for every other provider). MIN_CHUNK_TOKENS floor 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) mirrors model_dims' case-fold lookup rule (exact match first, then case-insensitive scan). Consumed at import-file.ts's chunk step. Pinned by test/embedding-input-limit.test.ts. Declared limits ([R13] audit, PR #5922): NVIDIA nvidia/nv-embedqa-e5-v5 512; DashScope text-embedding-v1/v2 2048, v3 8192; Google gemini-embedding-001 2048 (the endpoint truncates silently past it); Zhipu embedding-2 512, embedding-3 3072; OpenAI text-embedding-3-* 8191 and Mistral mistral-embed 8192 (above the default, so no chunking change). Pinned by test/embedding-input-limit-hosted-caps.test.ts. Learned caps (learnChunkCap / learnedChunkCap / _resetLearnedChunkCapsForTest): a process-lifetime per-provider:model chunk cap that src/core/embed-overlength-heal.ts derives from a provider's single-input over-length rejection when the model declares nothing; resolveMaxChunkTokens applies 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 of SIGNATURE_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 in test/e2e/stale-signature-invalidation-postgres.test.ts). hasSignatureDrift is the embed paths' page-first pre-check: one EXISTS instead of two corpus-wide counts, so a healthy brain never reads content_chunks for 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. Source FOR SHARE locks 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 shared falseStampPageWhere and countFalseStampedChunks remain 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 by test/embedding-migration.test.ts and the shared test/embedding-recovery.serial.test.ts suite: PGLite runs in the serial lane, while test/e2e/embedding-recovery-parity.test.ts selects PostgreSQL.

  • src/core/embedding-pricing.ts — EMBEDDING_PRICING map keyed provider:model for the post-upgrade reindex cost estimate. Sibling to anthropic-pricing.ts; EMBEDDINGS only — chat/completion pricing lives in model-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-nano is 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 (known with price + unknown with 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 via currentEmbeddingPricePerMTok() (resolves the per-1M-token rate via lookupEmbeddingPrice(gatewayGetModel()) from embedding-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_TOKENS retained for back-compat with direct importers/tests. currentEmbeddingSignature(): string returns the embedding-provenance signature <provider:model>:<dims> (e.g. openai:text-embedding-3-large:1536) stamped onto pages.embedding_signature at every embed-write site; DELIBERATELY excludes the chunker version (tracked separately via pages.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. (See src/core/sync-delta.ts + src/core/spend-posture.ts for the cost-gate supporting modules.) willEmbedSynchronously({v2Enabled, serialFlag, noEmbed}): SyncEmbedMode retains the package-exported compatibility contract for downstream TypeScript and JavaScript consumers. The command-internal resolveWorkerBackedSyncEmbedMode({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'): boolean is the pure cost-gate decision: blocks ONLY when mode === 'inline' && costUsd > floorUsd — deferred mode never blocks (the backfill's $X/source/24h cap is the real money gate), and posture === 'tokenmax' never blocks (the operator declared cost isn't the constraint; an off/unlimited floor is Infinity and so is never exceeded). Pinned by test/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 at gbrain init. runInitEmbedCheck(opts) runs a config-only diagnoseEmbedding (catches a missing key for ANY provider) plus a best-effort liveTestEmbed (1-token gateway.embed(['probe'], {inputType:'query', abortSignal}), 5s AbortController timeout, never throws — catches an invalid/expired key). Loud warning to stderr; init still exits 0 (--no-embedding is the deferred-setup escape; --skip-embed-check / GBRAIN_INIT_SKIP_EMBED_CHECK=1 skip the check). Builds the effective env (process.env + every file-plane provider key buildGatewayConfig folds — openai/anthropic/voyage/dashscope/google — from loadConfigFileOnly() + opts.apiKey) and configures the gateway via buildGatewayConfig before 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 into initPGLite + initPostgres in src/commands/init.ts, with the result added to the --json envelope as embedding_check {ok, reason?, live_ok?}. Pinned by test/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, keptEmbeddingIdentity keeps the database's stored model and width (or leaves embedding settings unchanged when its vectors' identity cannot be confirmed) instead of writing embedding_disabled, unless the database plane already disables embeddings or holds only the schema seed with no vectors; keptEmbeddingNotice names the provider key and gbrain embed --stale.

  • src/core/llm-json.ts — tolerant JSON extraction from LLM output. parseLlmJson<T>(raw, {array?}) walks a strategy ladder (strip json 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 quoted cannot 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). Exports stripReasoningBlocks(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. Exports matchingCloseBracket(text, openAt = 0): the index of the bracket closing the array/object that opens at text[openAt] (counts the opener's own kind, skips string literals whole including escapes; -1 when text[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-rolled parseExtractorJsonDetailed applies the same raw-first fallback ladder with the shared stripReasoningBlocks.

  • src/core/model-config.ts — Model-string resolution (the seam every internal LLM call walks through). Four-tier system (ModelTier = 'utility' | 'reasoning' | 'deep' | 'subagent') with TIER_DEFAULTS (utility→haiku-4-5, reasoning→sonnet-4-6, deep→opus-4-7, subagent→sonnet-4-6) and tier?: ModelTier on ResolveModelOpts. 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 ABOVE models.default — tier-specific beats generic, so setting a cheap utility tier is honored even when models.default is 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 carries substituted_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 and gbrain models. Step 7 is KEY-AWARE: resolveTierDefault(tier, env?) walks PROVIDER_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); injected env is 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 via providerKeyReady, PIN_KEY_BY_TIER is 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_DEFAULTS unchanged. 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) with openaiStaticTierFallback() — 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. The gpt alias resolves dynamically through the same path (the map entry is a documentation floor). resolveEffectiveChatModel(fileCfg, env) / resolveEffectiveExpansionModel are the ENGINE-FREE shared effective-model resolvers (GBRAIN_MODEL > servable file pin per providerKeyReady (recipe auth_env.required) > key-aware tier default; unservable pins warn once and fall through) — used by BOTH reconfigureGatewayWithEngine's fallback layer and detectCapabilities' extraction probe so runtime routing and the capability report cannot diverge; they read RAW loadConfig() output, never gateway state (the boot fold stamps defaults, making explicit pins indistinguishable there). isAnthropicProvider(modelString) checks provider:model prefix OR claude- bare-id pattern (routes through splitProviderModelId from src/core/model-id.ts so slash-form ids like anthropic/claude-sonnet-4-6 classify correctly). enforceSubagentCapable() is the layer-2 runtime guard: tier === 'subagent' resolutions are classified via classifyCapabilities() — unusable:no_tools/unknown warn once and fall back to TIER_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 by test/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 of provider:model splitting — slash-form ids (anthropic/claude-sonnet-4-6) classify correctly instead of falling through to "unknown model". Distinct from the gateway-side parseModelId in src/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 by test/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_PRICING is a provider:model-keyed table (Anthropic Opus 5/4.8/4.7/4.6 $5/$25, Sonnet 4.6 $3/$15, Haiku 4.5 $1/$5 both dateless + dated, plus OpenAI / Google / Together / DeepSeek panel models). Exported as gbrain/core/model-pricing for 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 the anthropic: 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 in embedding-pricing.ts (different unit). DeepSeek rows (deepseek-flash, its legacy alias deepseek-v4-flash, deepseek-v4-pro) carry the vendor's PEAK rate so caps bound the worst case; peakRateNote(models) in src/core/budget/reservation-cost.ts labels 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's unpriced_models. Pinned by test/model-pricing.test.ts whose 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 carry long_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 above ANTHROPIC_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 / reservationCostUsd in src/core/budget/reservation-cost.ts (so BudgetTracker.reserve/record and the audit line see the tier; the reservation sizes the tier by the ESTIMATED input tokens, the record by the served input_tokens + cache_read + cache_write) and estimateChatCostUsd in src/core/ai/chat-usage.ts. The gateway's pre-call input estimate is estimateChatInputTokens in src/core/ai/chat-input-estimate.ts (system + text + tool calls/results + tool definitions at CHAT_INPUT_CHARS_PER_TOKEN), shared with the reservation so a 100K+ reservation is held at the tier rate. Pinned by test/model-pricing-long-context-tier.test.ts and test/model-pricing-tier-helpers.test.ts.

  • src/core/post-upgrade-reembed.ts — Pure functions backing the gbrain upgrade chunker-bump cost prompt. computeReembedEstimate(engine, model) queries real SQL (COUNT(*) + COALESCE(SUM(LENGTH(compiled_truth)) + SUM(LENGTH(timeline)), 0)) on pages 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 answer y to [chunker-bump] Re-embed now? [y/N]; the default, EOF and every non-TTY run decline and print REEMBED_DEFERRED_HINT (gbrain reindex --markdown, or gbrain repair safe-chunks --apply --no-embed then gbrain embed --stale), so an unattended upgrade never spends. Reasons: no_pending, bypassed_no_reembed, consent_required, tty_declined, tty_consented. GBRAIN_NO_REEMBED=1 skips the prompt with a doctor-warning marker. opts.confirm and opts.isTTY are test seams.

  • src/core/schema-embedded.generated.ts — AUTO-GENERATED from schema.sql by scripts/build-schema.ts (run bun run build:schema, which also regenerates schema.sql's fragment regions and the PGLite template src/core/pglite-schema.generated.ts, exposed through the src/core/pglite-schema.ts façade; canonical-source graph in docs/ENGINES.md#canonical-schema-sources; the .generated.ts suffix 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 the mcp_spend_log table. checkBudget(engine, clientId, capCents) is the pre-flight gate; throws BudgetExceededError when 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-plane spend.posture, fail-open gated); tokenmax makes every cost gate informational across sync/reindex/enrich/onboard (spend still ledgered — removes the ceiling, not the accounting). parseUsdLimit(raw, def, {allowZero?}) accepts off/unlimited/none → Infinity; formatUsdLimit(n) renders Infinity as the string 'unlimited' (never raw — JSON.stringify(Infinity) is null); usdLimitToCap(n) maps Infinity → undefined at the BudgetTracker boundary so ledger rows never serialize null. normalizeSpendPosture/isValidSpendPosture back the config set validation. Doc: docs/operations/spend-controls.md. Pinned by test/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 through invokeAI with kind transcription, so admission guards and invocation observers see it.