Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(embed): meter an approved --max-usd while the run spends, multimodal and OCR included (#6400, W13 P1.18)

time-attackea217cf5337c
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
index b7c0846629..e74c840f79 100644
--- a/docs/architecture/key-files/commands-2-continued.md
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -13,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/dream.ts` — `gbrain dream` CLI; thin alias over `runCycle`. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`, `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range), `--unsafe-bypass-dream-guard` (plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` / `readSingleTranscript({bypassGuard})`; loud stderr warning at synthesize-phase entry; never auto-applied for `--input`). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs the scored triage pass but skips synthesis (NOT zero LLM calls). Exit 1 on status=failed; a `cycle_already_running` skip names the lock holder (pid, host, age) from `report.lock_holder`. Source scope enters the shared 6-tier resolver whenever `--source <id>` is given OR `GBRAIN_SOURCE` is set (a null explicit falls through to tier 2: validated + `assertSourceExists`, so an invalid/unknown env value is a clean exit 1; the `__all__` sentinel is excluded and falls through to the unscoped routing, which already spans every source); an env scope naming the brain's default-like source keeps the full implicit cycle (#4700 semantics), any other keeps the `--source` freshness boundary. `resolveBrainDir` returns `string | null` (order: `--dir` → resolved source's `local_path` → global `sync.repo_path` → null); a checkout-less postgres/Supabase brain runs DB-only phases (incl. `resolve_symbol_edges`) and skips the 6 filesystem phases with `details.reason: 'no_brain_dir'`; `runDream` owns the only hard error (no checkout AND no engine). When `--source` resolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's global `sync.repo_path` (would mix scopes). Pinned by `test/dream-postgres.serial.test.ts`. `--drain [--window <seconds>]` for `--phase extract_atoms`: `runDrain()` bypasses the pack-gate and runs the single-hold bounded drain from `src/core/cycle/extract-atoms-drain.ts` under the same `cycleLockIdFor(sourceId)` the routine cycle uses (concurrent autopilot tick defers with `cycle_already_running`), reporting `{extracted, skipped, remaining, stopped}`. `--window` is a hard deadline for starting work (the item in flight finishes). Exits `EXIT_DRAIN_INCOMPLETE` (= `BUDGET_STOP_EXIT_CODE` 11; was 3, which A3 reserves for confirmation_required) unless `stopped: drained` with `remaining: 0` (a null count is exit 11, never a drained success; `--json` adds `resume_command`), printing the rerun command (`gbrain dream --drain --window <s> [--source <id>]`) on stderr; `LockUnavailableError` → `cycle_already_running` skip (also exit 11). Under `--json` (D2) every path is one document: usage errors are `invalid_params` envelopes (exit 2, unknown `--phase` included), a failed or contained cycle under the guard is a `cycle_failed` envelope leading with the CycleReport keys, and `retriage` / `reset-key` refusals are envelopes. The `extract_atoms_backlog` doctor check (`computeExtractAtomsBacklogCheck`) surfaces the silent pack-gated backlog with the exact `--drain` command; pack-gated cycle skips carry a greppable `pack_gated:true` marker. `dream retriage` dispatches on `args[0] === 'retriage'` BEFORE `parseArgs` (its flag set never collides with cycle flags; `dream retriage --help` prints subcommand help engine-free per the same IRON RULE). `--eval-run` opts the process in to `GBRAIN_DECIDE_SLOTS` (`enableDecideEvalOverride`) for eval harnesses; consent, egress and the daily cap still apply.
-- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. Explicit slug/slugs and non-stale all routes require live-source projection snapshots before healing or provider work; unavailable preparation and refused installation are recorded through existing failure results and the CLI nonzero exit verdict. Archived rows are preserved and never knowingly dispatched, while active pages in a mixed run can progress. Dry runs retain their read-only counts, and the global page selectors are unchanged. These routes keep provider calls outside the existing source-before-page guards. Pinned by the explicit archived-admission and actual CLI cases in `test/embedding-recovery.serial.test.ts` (PGLite) and its PostgreSQL wrapper, `test/e2e/embedding-recovery-parity.test.ts`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it reads the live canonical snapshot and re-checks `getChunks`. `installPageProjection` then locks the page, verifies the originating revision and source incarnation, and installs/seals chunks in one transaction. A newer canonical edit prevents installation; the single-page chunkless path uses the same guarded installer. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; a budget stop that leaves stale chunks is never silent: `src/core/embed-budget-stop.ts` records `reason: 'time_budget'`, `remaining_stale` and `resume_command`, `runEmbed` prints the verdict on stdout and the CLI exits 11 (`BUDGET_STOP_EXIT_CODE`); an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, captures a guarded projection snapshot, embeds outside the transaction, and installs through `installPageEmbeddings`. The installer checks revision, source incarnation, chunk identities/text and indexing context, then updates vectors and provenance without replacing chunk text or membership. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). Keep this shared field list for prepared chunk metadata rather than copying a per-path list. The final guarded embedding installer updates vectors and provenance only, preserving the installed modality, code metadata, text and chunk membership. Pinned by `test/embed-modality-preserved.test.ts`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Successful complete page embeddings stamp `pages.embedding_signature` inside the guarded installation transaction so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page through `stampIfPageProvenanceComplete` in `src/core/embed-stale.ts` (shared with the minion `embed-backfill` drain, `embedStaleForSource`): the stamp is judged from DB state — every chunk carries an active-column vector whose `model` and vector width match the signature and whose `embedded_text_hash` matches `md5(chunk_text)` — never from the batch subset, because `listStaleChunks` pages by row with no page alignment, so a page straddling a batch boundary is stamped by whichever batch lands its last chunk (a partially-stale page keeping preserved chunks of another model, or a NULL model/hash, stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent: all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). In `--stale`, a page whose guarded projection snapshot is unavailable when its turn comes (edited, tagged or unsealed after the readiness gate) counts its chunks as failures and is named in one end-of-run batch-summary sample (the first five slugs plus a count of the rest); a page whose source was archived mid-run is left to the archived-work report so it is counted once. Pinned by `test/embed-stale-unavailable-snapshot.serial.test.ts`. Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the single implementation — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-default-concurrency.test.ts` (20 page workers on both paths when the env var is unset) and `test/embed-pool-abort.test.ts` (an abort stops both page pools from claiming further pages). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.test.ts`. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two `countStaleChunks` calls) followed by one live `probeEmbedder` embed call (from `src/core/embed-stale.ts`; validates a real vector whose dims match the signature's trailing `:<dims>`) must succeed before anything is NULLed, so a misresolved config (temp `GBRAIN_HOME` → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls `engine.invalidateContentDriftEmbeddings` (not probe-gated — blast radius is bounded by real content edits) so chunks whose `embedded_text_hash` no longer matches `md5(chunk_text)` re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by `test/embed-stale.test.ts` (probe-gate + content-drift blocks). The `--stale` single-flight lock HEARTBEAT (interval `GBRAIN_EMBED_LOCK_HEARTBEAT_MS`, default 5 min — test seam) is refresh-bounded per tick: each `refresh()` races a per-tick timeout (`GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`, default 30s via `DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (`beating` guard), a refresh returning false (stolen/released lock) aborts the drain immediately as `lock_lost`, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as `lock_lost` rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. `runEmbedCore --stale` also arms the progress-keyed stall watchdog from `src/core/embed-stall.ts` (`GBRAIN_EMBED_STALL_ABORT_SECONDS`, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns `reason: 'stall_timeout'`. Pinned by `test/embed.serial.test.ts` (heartbeat + stall blocks) + `test/jobs-embed-stall-wiring.serial.test.ts`. Explicit `--stale --facts --source ID` is a read-only NULL-fact preview; `--yes --max-cost-usd N` consents to bounded execution, not automatic/full-brain repair. The selected-brain configuration is forwarded out of band to the resident owner, never reloaded from the host or supplied over the wire; selected and DB off-switches fail closed. #5183: the page-embedding worker count comes from `resolveEmbedConcurrency` in `src/core/embed-concurrency.ts` (GBRAIN_EMBED_CONCURRENCY, a paced cap, and on Postgres never above the client pool; one warning when an explicit setting is lowered). A chunkless page whose projection install loses to another installer (the resident rebuild) re-reads through `retryProjectionConflict` and embeds the sealed chunks it finds; a conflict that outlasts the retries is recorded as a `[page_projection_conflict]` failure sample with the envelope's next step (`test/embedding-recovery.serial.test.ts`). `--all` passes the sliding pool an `onError` handler: an error that escapes `embedOnePage` (its snapshot read runs before the page's own try) counts that page once on `result.failures` with an `Error embedding <slug>` stderr line, unless the run is already aborting when the error arrives (shutdown, not a failure); `test/embed-partial-failure-3037.serial.test.ts`. #6223: pages still blocked after bounded projection recovery no longer end `--stale` early; healthy chunks embed, the blocked pages' chunks count as failures, and one sample names them (not the mid-run "changed" summary) with `gbrain embed --stale --images` / `gbrain sync --full` for image and media pages.
+- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. Explicit slug/slugs and non-stale all routes require live-source projection snapshots before healing or provider work; unavailable preparation and refused installation are recorded through existing failure results and the CLI nonzero exit verdict. Archived rows are preserved and never knowingly dispatched, while active pages in a mixed run can progress. Dry runs retain their read-only counts, and the global page selectors are unchanged. These routes keep provider calls outside the existing source-before-page guards. Pinned by the explicit archived-admission and actual CLI cases in `test/embedding-recovery.serial.test.ts` (PGLite) and its PostgreSQL wrapper, `test/e2e/embedding-recovery-parity.test.ts`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it reads the live canonical snapshot and re-checks `getChunks`. `installPageProjection` then locks the page, verifies the originating revision and source incarnation, and installs/seals chunks in one transaction. A newer canonical edit prevents installation; the single-page chunkless path uses the same guarded installer. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; a budget stop that leaves stale chunks is never silent: `src/core/embed-budget-stop.ts` records `reason: 'time_budget'`, `remaining_stale` and `resume_command`, `runEmbed` prints the verdict on stdout and the CLI exits 11 (`BUDGET_STOP_EXIT_CODE`); an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, captures a guarded projection snapshot, embeds outside the transaction, and installs through `installPageEmbeddings`. The installer checks revision, source incarnation, chunk identities/text and indexing context, then updates vectors and provenance without replacing chunk text or membership. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). Keep this shared field list for prepared chunk metadata rather than copying a per-path list. The final guarded embedding installer updates vectors and provenance only, preserving the installed modality, code metadata, text and chunk membership. Pinned by `test/embed-modality-preserved.test.ts`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Successful complete page embeddings stamp `pages.embedding_signature` inside the guarded installation transaction so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page through `stampIfPageProvenanceComplete` in `src/core/embed-stale.ts` (shared with the minion `embed-backfill` drain, `embedStaleForSource`): the stamp is judged from DB state — every chunk carries an active-column vector whose `model` and vector width match the signature and whose `embedded_text_hash` matches `md5(chunk_text)` — never from the batch subset, because `listStaleChunks` pages by row with no page alignment, so a page straddling a batch boundary is stamped by whichever batch lands its last chunk (a partially-stale page keeping preserved chunks of another model, or a NULL model/hash, stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent: all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). In `--stale`, a page whose guarded projection snapshot is unavailable when its turn comes (edited, tagged or unsealed after the readiness gate) counts its chunks as failures and is named in one end-of-run batch-summary sample (the first five slugs plus a count of the rest); a page whose source was archived mid-run is left to the archived-work report so it is counted once. Pinned by `test/embed-stale-unavailable-snapshot.serial.test.ts`. Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the single implementation — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-default-concurrency.test.ts` (20 page workers on both paths when the env var is unset) and `test/embed-pool-abort.test.ts` (an abort stops both page pools from claiming further pages). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.test.ts`. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two `countStaleChunks` calls) followed by one live `probeEmbedder` embed call (from `src/core/embed-stale.ts`; validates a real vector whose dims match the signature's trailing `:<dims>`) must succeed before anything is NULLed, so a misresolved config (temp `GBRAIN_HOME` → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls `engine.invalidateContentDriftEmbeddings` (not probe-gated — blast radius is bounded by real content edits) so chunks whose `embedded_text_hash` no longer matches `md5(chunk_text)` re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by `test/embed-stale.test.ts` (probe-gate + content-drift blocks). The `--stale` single-flight lock HEARTBEAT (interval `GBRAIN_EMBED_LOCK_HEARTBEAT_MS`, default 5 min — test seam) is refresh-bounded per tick: each `refresh()` races a per-tick timeout (`GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`, default 30s via `DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (`beating` guard), a refresh returning false (stolen/released lock) aborts the drain immediately as `lock_lost`, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as `lock_lost` rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. `runEmbedCore --stale` also arms the progress-keyed stall watchdog from `src/core/embed-stall.ts` (`GBRAIN_EMBED_STALL_ABORT_SECONDS`, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns `reason: 'stall_timeout'`. Pinned by `test/embed.serial.test.ts` (heartbeat + stall blocks) + `test/jobs-embed-stall-wiring.serial.test.ts`. Explicit `--stale --facts --source ID` is a read-only NULL-fact preview; `--yes --max-cost-usd N` consents to bounded execution, not automatic/full-brain repair. The selected-brain configuration is forwarded out of band to the resident owner, never reloaded from the host or supplied over the wire; selected and DB off-switches fail closed. #5183: the page-embedding worker count comes from `resolveEmbedConcurrency` in `src/core/embed-concurrency.ts` (GBRAIN_EMBED_CONCURRENCY, a paced cap, and on Postgres never above the client pool; one warning when an explicit setting is lowered). A chunkless page whose projection install loses to another installer (the resident rebuild) re-reads through `retryProjectionConflict` and embeds the sealed chunks it finds; a conflict that outlasts the retries is recorded as a `[page_projection_conflict]` failure sample with the envelope's next step (`test/embedding-recovery.serial.test.ts`). `--all` passes the sliding pool an `onError` handler: an error that escapes `embedOnePage` (its snapshot read runs before the page's own try) counts that page once on `result.failures` with an `Error embedding <slug>` stderr line, unless the run is already aborting when the error arrives (shutdown, not a failure); `test/embed-partial-failure-3037.serial.test.ts`. #6223: pages still blocked after bounded projection recovery no longer end `--stale` early; healthy chunks embed, the blocked pages' chunks count as failures, and one sample names them (not the mid-run "changed" summary) with `gbrain embed --stale --images` / `gbrain sync --full` for image and media pages. Fix wave 13 P1.18 (#6400): `runEmbed` takes the CLI's consent outcome; a finite approved `cap_usd` runs the foreground text and `--images` paths under `embedCostCap` (`src/core/embed-cost-cap.ts`) and returns `reason: 'cost_cap'` (exit `BUDGET_STOP_EXIT_CODE` from `src/cli/commands/embed.ts`, which now returns the Authorization from `authorizeEmbed`); `--background` stores it on the row through `maybeBackground(...spendAuthorization)` (PGLite runs inline, metered). `--slugs` takes the arguments up to the next flag. Tests: `test/embed-max-usd-metered.serial.test.ts`, `test/e2e/embed-background-cap.test.ts`.
- `src/commands/doctor/checks/search-eval.ts` — search, model, and AI-config health checks. `checkSearchMode` (`search_mode`) reports the resolved mode and its `search.*` overrides; when the only override is an explicit `search.reranker.model` row equal to the mode bundle's own default (a row an init may have written on Voyage installs) it is called redundant with the precise `gbrain config unset search.reranker.model` — never a `--reset`, which would also wipe every other tuned search knob.
- `src/commands/doctor/checks/fence-integrity.ts` — `fence_integrity` (#6188, BRAIN, registered before `search_mode`). Each run advances the fence census within `GBRAIN_DOCTOR_FENCE_TIMEOUT_MS` (default 10 s), then reports per source the malformed facts/takes fences still waiting, each counted once (held file, stored page, unsynced file) and split by planned tier (deterministic, resolver, llm, manual), the oldest hold's age, the 7-day `fences_normalized` trend with top writers (warns at `FENCE_NORMALIZATION_WARN_7D` = 20), and the model-repair caps with today's ledger spend. `ok` only when nothing waits, every source's census is complete and no source reaches the trend threshold; a partial census warns with the resume command. The fix is the read-only `gbrain repair fences --source <id>` preview for holds, stored pages and files alike; a warn reads `readFenceAutoRepair` (details `auto_repair`): while a maintenance run is active and `fences.repair.enabled` is on, the non-manual fences are "repaired automatically by the next maintenance run", otherwise the fix's `then` is the apply. Model-tier fences say why they wait (`fences.repair.llm` off with the command that turns it on, or today's budget spent with the cap command), else the caps. `fenceIntegrityCheck(engine, sourceIds?)` is the `WAVE_CHECKS` entry (scoped for a remote caller). Location only. #6278: the check also counts `unrenderable_legacy_facts`: the active `row_num IS NULL` fact rows the fence step leaves unadopted because the fence codec would change their text (or their page already carries the claim), planned read-only per source within the census time budget (`planUnfencedFacts` + `auditUnadoptableFacts`) and listed by page, fact id and reason class, never the claim text. They stay active and searchable, so the finding says nothing is lost, never suggests `forget_fact`, and when it is the only finding its fix carries no command (`next: report`) with the doctor re-count as verify; an incomplete scan asks for a rerun. Test: `test/doctor-fence-integrity.test.ts`.
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.md
index b9bb60d2b6..7f209c761e 100644
--- a/docs/architecture/key-files/core-ai.md
+++ b/docs/architecture/key-files/core-ai.md
@@ -19,7 +19,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ai/errors.ts` — error normalization and classification. One private generator, `wrappedErrorLayers`, opens a thrown error's wrappers outermost first (`cause`, else RetryError's `lastError`; objects only, at most five layers, a repeated layer ends the walk). `isStructuredOutputRejection` and `readProviderFailureSignals` use it; the latter returns the first finite `status`/`statusCode`/`apiErrorStatus` plus every string `name` and `code` and never throws (a throwing getter ends the walk). `page-summary.ts` `classifyChatError` reads those signals, so a wrapped claude-cli 429, an AI SDK RetryError's 429/5xx or a `TimeoutError`/network code on `cause` classifies as rate_limit/provider_5xx/timeout/network instead of `malformed` (which drops the page to the title tier). `classifyGlobalLlmError` keeps its own depth-3 loop over `cause ?? lastError`, so a 404 there halts as `model_not_found`; the `--- raw ---` phrase barrier and billing-over-429 precedence hold (`test/synopsis-chat-failure-class.test.ts`, `test/ai/classify-global-llm-error.test.ts`).
-- `src/core/ai/gateway.ts` — unified seam for every AI call. The `ai` SDK loads at the first provider call (lazy default transports), not on configure. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `voyageCompatFetch` adapts Voyage embedding requests and responses; `openAICompatAsymmetricFetch` threads explicit query/document input types for other compatible recipes through the SDK boundary. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the EFFECTIVE reranker as `input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL` (imported from `ai/defaults.ts`; `voyage:rerank-2.5`), posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/rerank`; supported recipes declare their path explicitly) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `no_key` preflight: after `requireConfig()`, a recipe without a custom `resolveAuth` whose `auth_env.required` key is absent from `cfg.env` throws `RerankError('no_key')` BEFORE any HTTP — `noKeyOnce()` writes ONE `no_key` audit row per process per model without a stderr line, avoiding per-query noise. `auth` therefore means "key present but rejected" (HTTP 401/403). `RerankError.reason` classifier: `auth | no_key | rate_limit | network | timeout | payload_too_large | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` returns only the EXPLICITLY configured model (callers need not pre-check availability — `rerank()` fails `no_key` itself; the sync readiness predicate for dashboards is `reranker-readiness.ts`) + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. `src/core/ai/multimodal-model.ts:multimodalEmbeddingModel()` answers the model `embedMultimodal()` would use when it passes those same recipe and allow-list checks (null otherwise, or when the gateway is unconfigured); hybrid search routes an inferred image intent and the LLM modality tie-break to the image arm only when it is set (`test/cross-modal-hybrid-integration.serial.test.ts`). Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length, Layer 2 per-embedding base64) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (`test/ai/gateway.test.ts` drives both layers through `embed()`). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is load-bearing for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion: `src/core/skillopt/rollout.ts` builds tool schemas through the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default), never an inline converter. Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google deferred until its native suffix is verified). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions`. `configureGateway` does not backfill `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `ChatOpts.timeoutMs` replaces the default chat backstop (`GBRAIN_AI_CHAT_TIMEOUT_MS`, 300 s) for one call and `ToolLoopOpts.turnTimeoutMs` forwards it to every turn (the subagent handler's per-turn cap, #4921); `ChatOpts.thinking: 'off'` maps per route through `thinking-off.ts` (#5331). `ChatOpts.temperature` is threaded verbatim to the AI SDK `generateText` call (unset → the provider's default; the LongMemEval judge pins `0`, the official `evaluate_qa.py` setting). `ChatResult.responseModel` carries the model id the PROVIDER reported (`response.modelId`, e.g. a dated snapshot) when the SDK surfaced one and is absent otherwise, while `model` stays the requested `provider:modelId`; eval receipts pin the two side by side (`reader_model_snapshot`, `judge_model_snapshot`). `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook: optional `acquireTurnPermit()` acquires a provider permit before EVERY round-trip and releases in finally; a lease-full throw propagates without consuming the turn (the subagent path wires it to the rate leases with provider-derived keys — Anthropic models share `anthropic:messages`, others get `<recipeId>:chat`). `ToolLoopStopReason` includes `'length'`: a zero-tool-call turn that hit the output cap propagates 'length' instead of folding into 'end', so truncation is never reported as a clean finish. Per-part provider state: `ChatBlock` variants carry optional `providerMetadata` captured from SDK parts in `chat()` and re-emitted as `providerOptions` on the rebuilt parts in `toModelMessages()` (attached only when present — metadata-free blocks stay byte-identical); this is the Gemini 3.x thoughtSignature echo. `isThinkingByDefaultModel(modelStr)` (exported) matches Claude 5-family ids behind any provider-prefix chain with a letters-only family segment (never `claude-3-5-*`); `isThinkingModel(modelStr)` (exported) is that regex OR the recipe's chat `thinking_by_default` capability (fail-closed: unknown/chat-less recipes are non-thinking) and drives `defaultMaxOutputTokens`'s 32k thinking headroom for chat()/toolLoop() callers that omit maxTokens (e.g. `gbrain skillopt` rollouts) and the subagent handler's `resolveMaxOutputTokens`; think/index.ts shares the regex and makes the same capability check. Pinned by `test/ai/gateway-thinking-headroom.test.ts`. `expand()` and `generateOcrText()` also record on the ambient tracker (they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`): record-only, no reserve — a breach surfaces on the NEXT reserving call, matching `chat()`'s swallow of `BudgetExhausted` from `record()`. Successes record normalized SDK usage via `normalizeSdkUsage` (the ONE home for the v6/legacy usage shapes, used by chat's success path too; first FINITE field wins so a NaN v6 field can't shadow a real legacy value or poison the running total); failures record pessimistically under `gateway.expand.failed` / `gateway.ocr.failed` (a rejected attempt still billed provider tokens — one expand() can legitimately produce two records when the structured-output attempt fails and the text fallback runs). A recipe whose declared structured-output support is rejected at call time is remembered for the process lifetime (`_structuredOutputRejectedRecipes`) so the rejected attempt isn't re-paid on every call. OCR's input estimate is prompt text + a fixed per-image token constant, never base64 length (bytes are not tokens). `generateOcrText()` routes to `getImageOcrModel()` — `embedding_image_ocr_model` when set, else the expansion model — gated by `isAvailable('expansion', <ocr model>)` so a misconfigured OCR model (provider without an expansion touchpoint, or unkeyed) fails closed to `''` instead of silently OCRing with the expansion model; the accessor mirrors `getMultimodalModel()`, `configureGateway`/`buildGatewayConfig` thread the field, and an unconfigured gateway stays a silent `''` no-op. Pinned by `test/ai/ocr-model-routing.test.ts`. `__setGenerateObjectTransportForTests` mirrors the generateText seam. `ChatOpts.responseSchema` (`{ name, description?, schema }`) is honored ONLY when the resolved recipe is openai-compatible AND declares `supports_structured_outputs`: `chat()` attaches a tolerant `Output` spec (`jsonSchemaOutput` — carries the `{ type: 'json', schema, name }` responseFormat the provider turns into `response_format: json_schema`, and `parseCompleteOutput` hands the raw text back instead of throwing `NoObjectGeneratedError` the way `Output.object` does on unparseable text) to the generateText call, so `result.text`, stopReason mapping, budget recording and the caller's own parse + retry lane run unchanged; native / claude-cli lanes and undeclared openai-compatible recipes never see the field. A declared recipe whose backend REJECTS the schema at call time (`isStructuredOutputRejection` in `errors.ts`: a request-shaped 4xx naming `response_format` / `json_schema` / structured output — never a 5xx or an unrelated 400) gets ONE schemaless retry plus one warn line, and lands in `_structuredOutputRejectedRecipes` so later `chat()` and `expand()` calls skip the schema for the process lifetime instead of re-paying the rejection on every retry lane. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.test.ts` + `test/facts-extract-structured-output.test.ts` Tracker recording goes through `src/core/ai/budget-record.ts:recordOnTracker` (fail-open: a cap breach on `record()` surfaces on the next `reserve()`); every chat/toolLoop/expand/embed/rerank/OCR record site passes the requested model, `purpose` (optional on `ChatOpts` + toolLoop opts; skillopt sets `skillopt.optimizer|target|judge`, engine-internal calls leave it null), `failed` on failure paths, `countsAsCall: false` for expand's structured-output fallback attempt and `estimated` when tokens are char-estimated. `reconfigureGatewayWithEngine` records the expansion/chat `ResolveSource` (`file_config` for the servable config.json pin) in `src/core/ai/gateway-model-sources.ts`; its getters answer only while the gateway still routes to the recorded model, so a later reconfigure reads as unknown instead of stale provenance. `embedQuery` caches query vectors per process (`src/core/ai/query-embed-cache.ts`: 512-entry LRU, 10-min TTL), keyed by recipe, model id, `base_urls` override, effective dims and the exact provider input (prefix + text). It stores only resolved vectors, as copies; the cache clears with `_modelCache` (configure, env refresh, engine re-stamp, reset, `__setEmbedTransportForTests`) and a generation counter drops an embed straddling a clear. Document-side `embed()` is never cached; a caller under an AI invocation guard skips the cache read.
+- `src/core/ai/gateway.ts` — unified seam for every AI call. The `ai` SDK loads at the first provider call (lazy default transports), not on configure. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `voyageCompatFetch` adapts Voyage embedding requests and responses; `openAICompatAsymmetricFetch` threads explicit query/document input types for other compatible recipes through the SDK boundary. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the EFFECTIVE reranker as `input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL` (imported from `ai/defaults.ts`; `voyage:rerank-2.5`), posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/rerank`; supported recipes declare their path explicitly) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `no_key` preflight: after `requireConfig()`, a recipe without a custom `resolveAuth` whose `auth_env.required` key is absent from `cfg.env` throws `RerankError('no_key')` BEFORE any HTTP — `noKeyOnce()` writes ONE `no_key` audit row per process per model without a stderr line, avoiding per-query noise. `auth` therefore means "key present but rejected" (HTTP 401/403). `RerankError.reason` classifier: `auth | no_key | rate_limit | network | timeout | payload_too_large | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` returns only the EXPLICITLY configured model (callers need not pre-check availability — `rerank()` fails `no_key` itself; the sync readiness predicate for dashboards is `reranker-readiness.ts`) + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. `src/core/ai/multimodal-model.ts:multimodalEmbeddingModel()` answers the model `embedMultimodal()` would use when it passes those same recipe and allow-list checks (null otherwise, or when the gateway is unconfigured); hybrid search routes an inferred image intent and the LLM modality tie-break to the image arm only when it is set (`test/cross-modal-hybrid-integration.serial.test.ts`). Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length, Layer 2 per-embedding base64) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (`test/ai/gateway.test.ts` drives both layers through `embed()`). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is load-bearing for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion: `src/core/skillopt/rollout.ts` builds tool schemas through the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default), never an inline converter. Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google deferred until its native suffix is verified). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions`. `configureGateway` does not backfill `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `ChatOpts.timeoutMs` replaces the default chat backstop (`GBRAIN_AI_CHAT_TIMEOUT_MS`, 300 s) for one call and `ToolLoopOpts.turnTimeoutMs` forwards it to every turn (the subagent handler's per-turn cap, #4921); `ChatOpts.thinking: 'off'` maps per route through `thinking-off.ts` (#5331). `ChatOpts.temperature` is threaded verbatim to the AI SDK `generateText` call (unset → the provider's default; the LongMemEval judge pins `0`, the official `evaluate_qa.py` setting). `ChatResult.responseModel` carries the model id the PROVIDER reported (`response.modelId`, e.g. a dated snapshot) when the SDK surfaced one and is absent otherwise, while `model` stays the requested `provider:modelId`; eval receipts pin the two side by side (`reader_model_snapshot`, `judge_model_snapshot`). `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook: optional `acquireTurnPermit()` acquires a provider permit before EVERY round-trip and releases in finally; a lease-full throw propagates without consuming the turn (the subagent path wires it to the rate leases with provider-derived keys — Anthropic models share `anthropic:messages`, others get `<recipeId>:chat`). `ToolLoopStopReason` includes `'length'`: a zero-tool-call turn that hit the output cap propagates 'length' instead of folding into 'end', so truncation is never reported as a clean finish. Per-part provider state: `ChatBlock` variants carry optional `providerMetadata` captured from SDK parts in `chat()` and re-emitted as `providerOptions` on the rebuilt parts in `toModelMessages()` (attached only when present — metadata-free blocks stay byte-identical); this is the Gemini 3.x thoughtSignature echo. `isThinkingByDefaultModel(modelStr)` (exported) matches Claude 5-family ids behind any provider-prefix chain with a letters-only family segment (never `claude-3-5-*`); `isThinkingModel(modelStr)` (exported) is that regex OR the recipe's chat `thinking_by_default` capability (fail-closed: unknown/chat-less recipes are non-thinking) and drives `defaultMaxOutputTokens`'s 32k thinking headroom for chat()/toolLoop() callers that omit maxTokens (e.g. `gbrain skillopt` rollouts) and the subagent handler's `resolveMaxOutputTokens`; think/index.ts shares the regex and makes the same capability check. Pinned by `test/ai/gateway-thinking-headroom.test.ts`. `expand()` and `generateOcrText()` also record on the ambient tracker (they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`): record-only, no reserve — a breach surfaces on the NEXT reserving call, matching `chat()`'s swallow of `BudgetExhausted` from `record()`. Successes record normalized SDK usage via `normalizeSdkUsage` (the ONE home for the v6/legacy usage shapes, used by chat's success path too; first FINITE field wins so a NaN v6 field can't shadow a real legacy value or poison the running total); failures record pessimistically under `gateway.expand.failed` / `gateway.ocr.failed` (a rejected attempt still billed provider tokens — one expand() can legitimately produce two records when the structured-output attempt fails and the text fallback runs). A recipe whose declared structured-output support is rejected at call time is remembered for the process lifetime (`_structuredOutputRejectedRecipes`) so the rejected attempt isn't re-paid on every call. OCR's input estimate is prompt text + a fixed per-image token constant, never base64 length (bytes are not tokens). `generateOcrText()` routes to `getImageOcrModel()` — `embedding_image_ocr_model` when set, else the expansion model — gated by `isAvailable('expansion', <ocr model>)` so a misconfigured OCR model (provider without an expansion touchpoint, or unkeyed) fails closed to `''` instead of silently OCRing with the expansion model; the accessor mirrors `getMultimodalModel()`, `configureGateway`/`buildGatewayConfig` thread the field, and an unconfigured gateway stays a silent `''` no-op. Pinned by `test/ai/ocr-model-routing.test.ts`. `__setGenerateObjectTransportForTests` mirrors the generateText seam. `ChatOpts.responseSchema` (`{ name, description?, schema }`) is honored ONLY when the resolved recipe is openai-compatible AND declares `supports_structured_outputs`: `chat()` attaches a tolerant `Output` spec (`jsonSchemaOutput` — carries the `{ type: 'json', schema, name }` responseFormat the provider turns into `response_format: json_schema`, and `parseCompleteOutput` hands the raw text back instead of throwing `NoObjectGeneratedError` the way `Output.object` does on unparseable text) to the generateText call, so `result.text`, stopReason mapping, budget recording and the caller's own parse + retry lane run unchanged; native / claude-cli lanes and undeclared openai-compatible recipes never see the field. A declared recipe whose backend REJECTS the schema at call time (`isStructuredOutputRejection` in `errors.ts`: a request-shaped 4xx naming `response_format` / `json_schema` / structured output — never a 5xx or an unrelated 400) gets ONE schemaless retry plus one warn line, and lands in `_structuredOutputRejectedRecipes` so later `chat()` and `expand()` calls skip the schema for the process lifetime instead of re-paying the rejection on every retry lane. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.test.ts` + `test/facts-extract-structured-output.test.ts` Tracker recording goes through `src/core/ai/budget-record.ts:recordOnTracker` (fail-open: a cap breach on `record()` surfaces on the next `reserve()`); every chat/toolLoop/expand/embed/rerank/OCR record site passes the requested model, `purpose` (optional on `ChatOpts` + toolLoop opts; skillopt sets `skillopt.optimizer|target|judge`, engine-internal calls leave it null), `failed` on failure paths, `countsAsCall: false` for expand's structured-output fallback attempt and `estimated` when tokens are char-estimated. `reconfigureGatewayWithEngine` records the expansion/chat `ResolveSource` (`file_config` for the servable config.json pin) in `src/core/ai/gateway-model-sources.ts`; its getters answer only while the gateway still routes to the recorded model, so a later reconfigure reads as unknown instead of stale provenance. `embedQuery` caches query vectors per process (`src/core/ai/query-embed-cache.ts`: 512-entry LRU, 10-min TTL), keyed by recipe, model id, `base_urls` override, effective dims and the exact provider input (prefix + text). It stores only resolved vectors, as copies; the cache clears with `_modelCache` (configure, env refresh, engine re-stamp, reset, `__setEmbedTransportForTests`) and a generation counter drops an embed straddling a clear. Document-side `embed()` is never cached; a caller under an AI invocation guard skips the cache read. Fix wave 13 P1.18: `embedMultimodal` reserves on the ambient tracker before any provider call (text at chars-per-token, 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` when present; a config error releases the hold. `generateOcrText` reserves before the call and sends `maxOutputTokens: OCR_MAX_OUTPUT_TOKENS`, the bound its reservation holds. Tests: `test/gateway-ocr-reserve.test.ts`.
- `src/core/ai/chat-fallback.ts`: the `chat_fallback_chain` consumer. `gateway.chat()` hands a call to `chatWithFallback` when a chain is configured and the caller did not pass `allowFallback: false`; `configureGateway` normalizes the chain with `normalizeChatFallbackChain` (a comma-separated string, the env and DB form, is split). Attempts run the call's own model, then each chain entry not already tried (`chatFallbackAttempts`), each as a complete single-model `chat()`, so budget, usage ledger, guardrails and `ChatResult.model` follow the model that ran; an answer from a chain entry also carries `ChatResult.fallbackFrom` (the call's own model). A provider error (a claude-cli subscription limit arrives as `apiErrorStatus` 429) or a structural refusal (`stopReason` `refusal`/`content_filter`) moves to the next model with one `[ai.gateway]` stderr line, and the first hop of a process queues one `chat_fallback_hop` safety notice in `fallback-hop-queue.ts`; with `chat_fallback_on_refusal: false` (`ChatFallbackOptions.onRefusal`, passed by `chat()` from the gateway config) a structural refusal is returned and a provider content block (`providerContentBlockReason`: a Gemini prompt block, or an HTTP 400 content-policy body such as OpenAI `invalid_prompt`, Azure `content_filter` or DeepSeek "Content Exists Risk") is thrown instead of being sent on, while provider errors still fall back; a policy refusal (`isAIInvocationPolicyError` or a BudgetTracker `BudgetExhausted`, including an unpriced chain entry under an explicit cap) or the caller's own abort stops the chain, and a cancel that lands while an attempt refuses returns that refusal instead of forwarding it; an earlier refusal is returned in preference to a later error, otherwise the call's own model's error is thrown (the last failure logged), so retry and halt classification follow the configured model. `toolLoop` forwards `allowFallback` to every turn. Judge, critic and eval call sites pin their model: brainstorm judges, grade_takes, drift, the edge_contradictions judge (apply mode defaults from a per-model certification), voice-gate, eval-contradictions, notability-eval, takes-quality-eval, cross-modal eval, skillopt (judge, optimizer, rollouts), the LongMemEval reader and judge, the functional-area-resolver harness, the `models doctor` / `providers test` probes, `decide()` (its egress gate cleared one provider), `auto_think` (its BudgetMeter priced one model), and `think` with an explicit `--model`; the synthesize triage and concept synthesis fall back. Pinned by `test/ai/gateway-chat-fallback.test.ts` and `test/ai/chat-fallback-on-refusal.test.ts` (refusal switch through the real loader on every plane, the once-per-process hop notice).
- `src/core/ai/fallback-hop-queue.ts`: the process-level queue for the first hop's `chat_fallback_hop` notice (at most one per process; type-only imports so every drain site loads it cheaply). Drained by stdio MCP dispatch, the CLI op notice channel (`src/cli/op-notices.ts`) and `finishCliTeardown`; never by HTTP, because the notice names models.
- `src/core/ai/chat-fallback-planes.ts`: where the effective `chat_fallback_chain` comes from, read without network, subprocess or inference. `readChatFallbackPlanes(db)` reads env `GBRAIN_CHAT_FALLBACK_CHAIN` > the config.json key > the DB row (`parseDbChatFallbackChain` in `config-db-merge.ts`) with the loader's rule that the first plane that speaks wins even when its value yields no chain, and returns the winner, shadowed values, unreadable planes and the `chat_fallback_on_refusal` value with its plane. `diagnoseChatFallbackEntry` checks one entry by presence: `provider:model` parse, known provider with chat, the provider's own credential (recipe env keys or `authPresent`; for `claude-cli` the binary on PATH or `GBRAIN_CLAUDE_CLI_BIN`), and a price when a key in `USER_CHAT_CAP_KEYS` sets a user cap. `chatFallbackRemovalFix` is the per-plane removal guidance (DB `gbrain config unset chat_fallback_chain` with `destructive` consent → `ask_user`; env/file are the user's, with the restart note). Consumers: the `chat_fallback_chain` doctor check and the `behavior_changes` notice.
diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.md
index f2eee14905..899707c9d1 100644
--- a/docs/architecture/key-files/core-services-1.md
+++ b/docs/architecture/key-files/core-services-1.md
@@ -26,7 +26,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/budget/budget-tracker.ts` — the keystone budget primitive. One typed error (`BudgetExhausted` with `reason: 'cost' | 'runtime' | 'no_pricing'`), one schema-stable audit JSONL at `~/.gbrain/audit/budget-YYYY-Www.jsonl`. Contracts: `record()` throws when cumulative spend exceeds cap (the cap is a real ceiling, not a suggestion); `reserve()` admission checks cumulative + OUTSTANDING spend and returns an opaque `BudgetReservation` id for each held projection; `record({ reservation })` settles that id and `release(id)` frees an attempt that never billed (no-op when already settled), so N concurrent callers can't all pass against the same cumulative and a small same-model call finishing first can't free a large in-flight call's hold (settlement is by id, never by model; an id-less record settles nothing; a priced reservation recorded under an unpriced served id charges its held ceiling). `gateway.chat` reserves, then runs the attempt in one try/finally that releases the id (provider-resolution failure, invocation-policy refusal); embed reserves after its preflights; rerank, decide, the TypeSafe rerank adapter and embed-facts pass their ids. Record audit rows carry `requested_model` and `reservation`; `reserve()` hard-fails with `reason: 'no_pricing'` when `maxCostUsd` is set AND the model is missing from pricing maps, its message and `BudgetExhausted.pricing` built by `no-pricing.ts` (warn-once preserved when cap is unset, naming the registration command); `lookupPricing` normalizes recipe aliases through `resolveRecipe` before consulting the pricing tables, so `claude-cli:haiku` prices exactly like `claude-cli:claude-haiku-4-5-20251001` at `reserve()`, `record()` and `isModelPriceable()` alike (the gateway reserves with the pre-resolution string the user configured); `extractUsageFromError(err, fallback)` returns `err.usage` when the SDK provides it, else the pessimistic fallback (caller passes `maxOutputTokens`, not the optimistic pre-call estimate). `onExhausted(cb)` fires once synchronously BEFORE the throw propagates so callers can persist checkpoints. Pricing math lives in the pure `src/core/budget/reservation-cost.ts`: `priceFor(model, kind, overrides) → { pricing, source: 'override' | 'provider_wildcard' | 'table' } | null` is the one resolver (exact override, then a `<provider>:*` wildcard admitted only for recipes with `billing: 'subscription'` by `isAllowedPricingOverrideKey`, then aliases, the claude-cli → Anthropic sibling, canonical rows and free local providers); `isModelPriceable`, `usageCostUsd`/`reservationCostUsd`, skillopt preflight and synthesize_concepts all use it. `parsePricingOverrides` drops disallowed keys and adds each alias key's canonical twin. Every `record()` also feeds an in-memory model ledger keyed by (requested model, served model, touchpoint, purpose) — updated BEFORE the cap throw and before the unpriced early return — exposed as `snapshot().models`; `BudgetActualUsage` carries `requestedModelId`, `purpose`, `failed`, `countsAsCall` (default true) and `estimated`, and rows track `calls` (gateway operations), `attempts` (every record), `failed_calls`, tokens, `cost_usd` (`null` when unpriced) and `cost_basis` (`estimated` if any contributing record was). `src/core/budget/models-used.ts` maps labels to touchpoints (`gateway.chat`→chat, `gateway.expand*`→expansion, `gateway.embed*`→embedding, `gateway.rerank*`→rerank, `gateway.ocr*`→ocr, else other), builds receipt rows (`buildModelsUsed`), merges resumed segments and renders the "Models called" table. No DB change. Shared by brainstorm, cycle/budget-meter, and eval-contradictions; `BudgetMeter` keeps its public shape over it (`schema_version: 1` stamped on every dream-budget audit line). Pinned by 18 unit cases. A4 cap sources: `capSource: 'derived' | 'default' | 'user'` (getter `capSource`; an explicit `maxCostUsd` with no declared source is `user`, the pre-A4 behaviour). Only a `user` cap hard-fails an unpriced model, and that `BudgetExhausted` carries `fix` (`noPricingFix`, actor `agent` on the CLI, `host_admin` when `transport` is remote); `derived`/`default` caps warn once and run the model unmetered. Cost exhaustion carries `capSource`, and a `derived` one appends `derived_cap_exhausted` to the agent-contract log (callers report it with `consent.ts`'s `derivedCapExhaustedError`). Pinned by `test/budget-tracker-cap-source.test.ts`.
- `src/core/budget/daily-ledger.ts` — #6188 the durable per-UTC-day USD ledger over `budget_ledger`/`budget_reservations` (migration v012; no new schema), one ledger per (scope, resolver), e.g. `FENCE_REPAIR_LEDGER` (`llm_repair`/`fences`). `reserve(estimate, { capUsd })` is one conditional upsert (`reserved + committed + estimate <= cap`) plus a reservation row with `expires_at`; `dispatch` marks it sent; `settle(id, actual)` is idempotent, bound to the reservation's own day, and records an overrun; `release` returns an undispatched hold; expired holds are reclaimed before each reserve (a dispatched one is charged its estimate). Any ledger error means no call (`ledger_unavailable`); `meteredCall` runs the whole protocol. Amounts are NUMERIC(12,4), spend rounded up and caps down. `estimateChatCallUsd` prices a chat call through `pricing.overrides` and the canonical table; an unpriced model is metered at the highest canonical rate (`estimated: true`) under a default cap and refused with `noPricingGuidance` under a user cap. Never opens a BudgetTracker, so a caller's ambient tracker keeps metering. Read by doctor `fence_integrity` (today's spend). Tests: `test/daily-ledger.test.ts` (+ `test/e2e/daily-ledger-postgres.test.ts`, concurrent sessions).
- `src/core/consent.ts` + `src/core/consent-preapproval.ts` — the A4 consent primitive for trusted local CLI handlers. `requireConsent(req, env?)` evaluates the matrix (`paid`: `--yes`, finite `--max-usd`/`--max-cost`, `spend.posture=tokenmax` via `env.getConfig`, or the per-run preapproval; other effects: `--yes`, `--apply`/`--trust`, the per-command `NON_INTERACTIVE_AUTHORIZES` map (only `apply-migrations` → `persistent_install`), or the install preapproval, which never covers `credentials`; `destructive`: `--yes` plus `--expect <plan_hash>` when the request has one, never preapprovable, a mismatch is `preview_changed`), then a TTY prompt through `interaction.readLine` (EOF/timeout = decline), else throws `confirmation_required` carrying `confirmationPayload()` (`isConsentRefusal`; `renderConsentRefusal`/`printConsentRefusal`: `--json` payload document or an `[AGENT]` block with a fenced `[SHOW USER]` relay, exit 3). Caps on the returned `Authorization`: explicit or preapproved or configured → `user`; estimate → `derived` (x1.5, floor $0.25); no estimate → `default` ($5, printed). Refusals, declines and preapproved runs are logged to E11 (code, effects, outcome; never params). Destructive rail: `computePlanHash(selection)` (stable sha256 over brain, source, operation, records + revisions + incarnations, parameters, effects), `persistApproval`/`readApproval` under `<GBRAIN_HOME>/consent/approvals/`, `verifyApproval`/`assertApproval` re-ask on a changed, newly matching or dropped record. Preapprovals (`consent.preapprove.paid.max_usd_per_run`, `consent.preapprove.persistent_install`) live only in the host file plane; `setConsentPreapproval` refuses remote callers. Pinned by `test/consent.test.ts`; observational startup by `test/observational-startup.serial.test.ts`.
-- `src/core/embed-consent.ts` — consent for explicit embedding backfills (`gbrain embed`, `jobs submit embed|embed-backfill|embed-catch-up`, `features --auto-fix`): `requireEmbedBackfillConsent` (`paid`, an SQL estimate from the text it would embed, a user cap below the estimate refuses with `cost_cap_exceeded`), null when nothing can spend (`embedWouldSpend`: embeddings off, no credentials, or a local recipe billing $0 per `embeddingProviderIsFree`). `embedBackfillFix` is the doctor-side backlog fix. Write-path embedding and the unattended library paths (autopilot, cycles, queued jobs) are deliberately outside it. Doctor's opt-in live probe asks through `src/commands/doctor/probe-consent.ts` (`paid` + `egress`). Pinned by `test/agent-operator-gate-fixes.{,serial.}test.ts`.
+- `src/core/embed-consent.ts` — consent for explicit embedding backfills (`gbrain embed`, `jobs submit embed|embed-backfill|embed-catch-up`, `features --auto-fix`): `requireEmbedBackfillConsent` (`paid`, an SQL estimate from the text it would embed, a user cap below the estimate refuses with `cost_cap_exceeded`), null when nothing can spend (`embedWouldSpend`: embeddings off, no credentials, or a local recipe billing $0 per `embeddingProviderIsFree`). `embedBackfillFix` is the doctor-side backlog fix. Write-path embedding and the unattended library paths (autopilot, cycles, queued jobs) are deliberately outside it. Doctor's opt-in live probe asks through `src/commands/doctor/probe-consent.ts` (`paid` + `egress`). Pinned by `test/agent-operator-gate-fixes.{,serial.}test.ts`. Fix wave 13 P1.18: `scope.images` makes `embedWouldSpend` also count a paid multimodal model and, with `GBRAIN_EMBEDDING_IMAGE_OCR=true`, a paid OCR model, even behind a free text provider (`test/embed-consent-multimodal.test.ts`).
- `src/core/agent-markers.ts` — the one `[AGENT] … [/AGENT]` / `[SHOW USER]` builder (`agentBlock`): fixed field vocabulary, every value through `inertText()` so interpolated text cannot open or close a block.
- `src/core/budget/cap-flag.ts` — the one USD cost-cap flag parser (D19): `parseCapFlag(flag, raw, { zero })` returns `{ flag, usd }` (`usd: null` for `off`/`unlimited`/`none`) or throws `CapFlagError`; a bare `0` is refused unless the command declares it (`zero: 'off'` for skillopt's legacy `--max-cost-usd 0`, `'cap'` for eval longmemeval's $0 judge cap); `mergeCapFlag` refuses two disagreeing cap flags; `capNotice` renders the one `cap: $X (source; how to remove)` line. Used by brainstorm/lsd, skillopt, enrich, onboard and eval longmemeval. Pinned by `test/budget/cap-flag.test.ts`.
- `src/core/budget/no-pricing.ts` — the one `no_pricing` refusal builder. `noPricingGuidance(model, kind)` returns the structured fields (`code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope: 'local_cli'`, `docs` = the `ERROR_CATALOGUE.no_pricing` anchor); `noPricingMessage` renders the one-line cause plus `noPricingSteps` (look up the provider's price, run the `gbrain pricing set` command on the brain host, retry; remote MCP callers ask the operator); `pricingSetCommand` gives the command alone for warnings (chat: `--input`/`--output`, other kinds: `--rate`), rendered from `pricingSetArgv`; `noPricingFix(guidance, transport)` is the agent-contract `fix` for a user-cap refusal (the registration argv with `inputs` for each rate and the pricing page). Used by BudgetTracker, enrich, conversation facts (CLI and cycle phase), skillopt receipts, the embedding migration authorization and the extract-atoms, budget-meter, embed-backfill and conversation-budget warnings. Pinned by `test/budget/no-pricing-registration.test.ts`.
diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.md
index 33abcf97db..8f6977f52f 100644
--- a/docs/architecture/key-files/providers.md
+++ b/docs/architecture/key-files/providers.md
@@ -25,9 +25,10 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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/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`.
-- `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 (unsealed or stale projection, no `embedding_image` chunk, or no OCR text/`ocr_status: done` while `GBRAIN_EMBEDDING_IMAGE_OCR=true`), 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) and hands it back to `importImageFile`, so OCR budget, protected-OCR refusal and the rebuild stay in the importer. Reports candidates, rebuilt, unchanged, missing source files and failures (`failures > 0` exits non-zero). Pinned by `test/embed-stale-images.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 (unsealed or stale projection, no `embedding_image` chunk, or no OCR text/`ocr_status: done` while `GBRAIN_EMBEDDING_IMAGE_OCR=true`), 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) and hands it back to `importImageFile`, so OCR budget, protected-OCR refusal and the rebuild stay in the importer. Reports candidates, rebuilt, unchanged, missing source files and failures (`failures > 0` exits non-zero). Pinned by `test/embed-stale-images.test.ts`. 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.
- `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`).
- `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.
diff --git a/src/cli/commands/embed.ts b/src/cli/commands/embed.ts
index 4bce243419..3e1aa69ead 100644
--- a/src/cli/commands/embed.ts
+++ b/src/cli/commands/embed.ts
@@ -8,6 +8,7 @@ import { jsonRequested, setCliExitVerdict, writeStdoutFinal } from '../../core/c
import { lastBackgroundJob } from '../../core/cli-options.ts';
import { BUDGET_STOP_EXIT_CODE } from '../../core/exit-codes.ts';
import type { BrainEngine } from '../../core/engine.ts';
+import type { Authorization } from '../../core/consent.ts';
import type { CliDispatchContext } from '../command-table.ts';
export async function run(engine: BrainEngine, args: string[], ctx: CliDispatchContext): Promise<void> {
@@ -17,21 +18,25 @@ export async function run(engine: BrainEngine, args: string[], ctx: CliDispatchC
}
const { SELECTED_CONFIG_BY_ENGINE } = ctx;
// A4: an explicit backfill is paid work; consent first, on the probe-only engine (startup: 'observational').
- if (!(await authorizeEmbed(engine, args))) return;
+ const consent = await authorizeEmbed(engine, args);
+ if (!consent) return;
await ctx.completeStartup?.(engine);
const { runEmbed } = await import('../../commands/embed.ts');
// #3037: mirror the `import` case above — the CLI was discarding the
// result, so a run where every chunk failed to embed still exited 0
// and cron/CI/health gates read total silence as success. Surface
// non-zero on failures > 0. (undefined = backgrounded via --background.)
- const embedResult = await runEmbed(engine, args, SELECTED_CONFIG_BY_ENGINE.get(engine) ?? null);
+ const embedResult = await runEmbed(engine, args, SELECTED_CONFIG_BY_ENGINE.get(engine) ?? null, consent);
// D2: under --json the result is the one document (a budget stop carries
// remaining_stale + resume_command and exits 11; --background names its job).
if (jsonRequested(args)) {
const job = lastBackgroundJob();
await writeStdoutFinal(`${JSON.stringify(embedResult ?? { status: 'backgrounded', ...(job !== null ? { job_id: job } : {}) }, null, 2)}\n`);
}
- if (embedResult && embedResult.failures > 0) {
+ if (embedResult && 'reason' in embedResult && embedResult.reason === 'cost_cap') {
+ // Fix wave 13 P1.18: a stop at the approved cap is a budget stop, not a failure, even when earlier pages failed.
+ setCliExitVerdict(BUDGET_STOP_EXIT_CODE);
+ } else if (embedResult && embedResult.failures > 0) {
setCliExitVerdict(1);
} else if (embedResult && 'reason' in embedResult && embedResult.reason === 'time_budget') {
setCliExitVerdict(BUDGET_STOP_EXIT_CODE);
@@ -39,20 +44,22 @@ export async function run(engine: BrainEngine, args: string[], ctx: CliDispatchC
}
/**
- * False when consent refused (exit 3 already reported). `--dry-run` and `--help` spend nothing.
+ * Null when consent refused (exit 3 already reported); otherwise the approval
+ * the run spends under (`authorization` null when the run cannot spend).
+ * `--dry-run` and `--help` spend nothing.
* Consent flags (read by requireConsent): --yes, --max-usd, --max-cost.
*/
-async function authorizeEmbed(engine: BrainEngine, args: string[]): Promise<boolean> {
+async function authorizeEmbed(engine: BrainEngine, args: string[]): Promise<{ authorization: Authorization | null } | null> {
const end = args.indexOf('--');
const opts = end >= 0 ? args.slice(0, end) : args;
- if (opts.includes('--dry-run') || opts.includes('--help') || opts.includes('-h')) return true;
+ if (opts.includes('--dry-run') || opts.includes('--help') || opts.includes('-h')) return { authorization: null };
const { requireEmbedBackfillConsent } = await import('../../core/embed-consent.ts');
const { isConsentRefusal, printConsentRefusal } = await import('../../core/consent.ts');
const sourceAt = opts.indexOf('--source');
const estimable = opts.includes('--stale') || opts.includes('--all');
const argv = ['gbrain', 'embed', ...args.filter(a => a !== '--yes')];
try {
- await requireEmbedBackfillConsent(engine, {
+ const authorization = await requireEmbedBackfillConsent(engine, {
command: 'embed',
argv,
...(estimable && !opts.includes('--images') && !opts.includes('--facts') ? { preview_argv: [...argv.filter(a => a !== '--background'), '--dry-run'] } : {}),
@@ -61,11 +68,12 @@ async function authorizeEmbed(engine: BrainEngine, args: string[]): Promise<bool
all: opts.includes('--all'),
...(sourceAt >= 0 && opts[sourceAt + 1] ? { sourceId: opts[sourceAt + 1] } : {}),
unestimated: !estimable || opts.includes('--slugs') || opts.includes('--facts') || opts.includes('--images'),
+ ...(opts.includes('--images') ? { images: true } : {}),
},
});
- return true;
+ return { authorization };
} catch (e) {
- if (isConsentRefusal(e)) { setCliExitVerdict(printConsentRefusal(e, { json: jsonRequested(args) })); return false; }
+ if (isConsentRefusal(e)) { setCliExitVerdict(printConsentRefusal(e, { json: jsonRequested(args) })); return null; }
throw e;
}
}
diff --git a/src/commands/embed.ts b/src/commands/embed.ts
index bb4344e59c..974213a770 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -28,6 +28,8 @@ import { countRestampOnlyChunks, invalidateStaleSignatureEmbeddingsGuarded } fro
import { loadConfig, type GBrainConfig } from '../core/config.ts';
import { slog, serr } from '../core/console-prefix.ts';
import { embedBudgetStopVerdict, noteEmbedBudgetStop } from '../core/embed-budget-stop.ts';
+import { embedCostCap, embedCostStopVerdict, noteEmbedCostStop } from '../core/embed-cost-cap.ts';
+import type { Authorization } from '../core/consent.ts';
import { filterOutEmbedSkipped } from '../core/embed-skip.ts';
import { runSlidingPool } from '../core/worker-pool.ts';
import { isAborted, anySignal, AbortError } from '../core/abort-check.ts';
@@ -353,10 +355,14 @@ export interface EmbedResult {
* `failures`/`failure_samples` also carry a stall entry so existing
* failures>0 consumers surface it unchanged.
*/
- reason?: 'stall_timeout' | 'time_budget';
+ reason?: 'stall_timeout' | 'time_budget' | 'cost_cap';
/** With `reason: 'time_budget'` (src/core/embed-budget-stop.ts): stale chunks left and the command that finishes them. */
remaining_stale?: number;
resume_command?: string;
+ /** With `reason: 'cost_cap'` (src/core/embed-cost-cap.ts): the approved cap, what the run spent, and the refusal's reason. */
+ cap_usd?: number;
+ spent_usd?: number;
+ budget_reason?: string;
/** #5885: the takes pass of a `stale` drain, when it ran. Its failures are also counted in `failures`. */
takes?: EmbedTakesResult;
}
@@ -864,7 +870,15 @@ export function isKeylessStaleRefusal(args: string[], embeddingDisabled: boolean
&& embeddingDisabled === true;
}
-export async function runEmbed(engine: BrainEngine, args: string[], selectedConfig: GBrainConfig | null = null): Promise<EmbedResult | EmbedFactsResult | StaleImageSweepResult | undefined> {
+/** The `--slugs` list: the arguments after it up to the next flag, so `--slugs a b --max-usd 1` never reads `1` as a slug. */
+function slugsAfter(args: readonly string[], at: number): string[] {
+ const end = args.findIndex((a, i) => i > at && a.startsWith('--'));
+ return args.slice(at + 1, end < 0 ? undefined : end);
+}
+
+export async function runEmbed(engine: BrainEngine, args: string[], selectedConfig: GBrainConfig | null = null,
+ /** The CLI's consent outcome (src/cli/commands/embed.ts); its cap meters the run (fix wave 13 P1.18). */
+ consent: { authorization: Authorization | null } | null = null): Promise<EmbedResult | EmbedFactsResult | StaleImageSweepResult | undefined> {
if (args.includes('--facts')) {
const result = await embedStaleFacts(engine, parseFactEmbedArgs(args), selectedConfig);
console.log(JSON.stringify(result, null, 2));
@@ -886,11 +900,14 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConf
};
}
- if (args.includes('--images')) return (await import('../core/embed-stale-images.ts')).runEmbedStaleImagesCli(engine, args); // lazy: keeps import-file out of embed's graph
+ const authorization = consent?.authorization ?? null;
+ const costCap = args.includes('--dry-run') || args.includes('--background') ? null : embedCostCap(authorization?.cap_usd, authorization?.cap_source);
+ if (args.includes('--images')) return (await import('../core/embed-stale-images.ts')).runEmbedStaleImagesCli(engine, args, costCap); // lazy: keeps import-file out of embed's graph
// v0.36+ T7: --background submits via Minion queue, returns job_id to
// stdout, exits. Same semantics in TTY and cron (D9).
if (args.includes('--background')) {
const { maybeBackground } = await import('../core/cli-options.ts');
+ const { jobSpendAuthorization } = await import('../core/minions/spend-authorization.ts');
const backgrounded = await maybeBackground({
engine,
args,
@@ -905,7 +922,7 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConf
all: cleanArgs.includes('--all'),
stale: cleanArgs.includes('--stale'),
dryRun: cleanArgs.includes('--dry-run'),
- slugs: slugsI >= 0 ? cleanArgs.slice(slugsI + 1).filter(a => !a.startsWith('--')) : undefined,
+ slugs: slugsI >= 0 ? slugsAfter(cleanArgs, slugsI) : undefined,
sourceId: srcI >= 0 ? cleanArgs[srcI + 1] : undefined,
// Background parity (D7): these four used to be silently DROPPED,
// degrading the documented recovery command to a plain stale run.
@@ -920,9 +937,12 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConf
};
},
source: 'cli',
+ // Fix wave 13 P1.18: the approval travels on the row; the worker meters the job under its cap.
+ ...(authorization ? { spendAuthorization: jobSpendAuthorization(authorization, { command: 'embed', of: 1, argv: ['gbrain', 'embed', ...args.filter(a => a !== '--yes')] }) } : {}),
});
if (backgrounded) return;
- // PGLite degraded to inline — fall through.
+ // PGLite runs inline: meter it like any foreground run.
+ return runEmbed(engine, args.filter(a => a !== '--background'), selectedConfig, consent);
}
const slugsIdx = args.indexOf('--slugs');
@@ -946,7 +966,7 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConf
let opts: EmbedOpts;
if (slugsIdx >= 0) {
- opts = { slugs: args.slice(slugsIdx + 1).filter(a => !a.startsWith('--')), dryRun, sourceId, batchSize, priority, catchUp };
+ opts = { slugs: slugsAfter(args, slugsIdx), dryRun, sourceId, batchSize, priority, catchUp };
} else if (all || stale) {
// E-2: CLI-only single-flight for stale runs (the minion path locks itself).
opts = { all, stale, dryRun, sourceId, batchSize, priority, catchUp, ...(pace && { pace }), ...(stale && { singleFlight: true }), ...(includeNullSignature && { includeNullSignature: true }) };
@@ -972,9 +992,16 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConf
progress.tick(1);
};
+ if (costCap) opts.signal = costCap.signal;
try {
- const result = await runEmbedCore(engine, opts);
+ const result = costCap ? await costCap.metered(() => runEmbedCore(engine, opts)) : await runEmbedCore(engine, opts);
if (progressStarted) progress.finish();
+ const capped = costCap?.hit();
+ if (capped) {
+ noteEmbedCostStop(result, capped, args);
+ (args.includes('--json') ? serr : slog)(embedCostStopVerdict(result, capped));
+ return result;
+ }
// #3037: loud end-of-run summary so failures are visible even when the
// per-page stderr lines scrolled away. cli.ts turns failures>0 into a
// non-zero exit verdict.
@@ -996,6 +1023,13 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConf
return result;
} catch (e) {
if (progressStarted) progress.finish();
+ const capped = costCap?.hit();
+ if (capped) {
+ const stopped: EmbedResult = { embedded: 0, skipped: 0, would_embed: 0, total_chunks: 0, pages_processed: 0, failures: 0, failure_samples: [], dryRun: false, chunkless_pages_healed: 0 };
+ noteEmbedCostStop(stopped, capped, args);
+ (args.includes('--json') ? serr : slog)(embedCostStopVerdict(stopped, capped));
+ return stopped;
+ }
if (args.includes('--json')) process.exit(writeCliError(e, 'embed', { json: true })); // D2: one v1 envelope on stdout
// v0.41.6.0 D1: preflight throws EmbeddingCredentialError; surface the
// paste-ready userMessage instead of the bare exception text.
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index 11ac7ebca3..626b2029ae 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -1862,6 +1862,37 @@ export async function embedMultimodal(
opts: EmbedMultimodalOpts = {},
): Promise<Float32Array[]> {
if (!inputs || inputs.length === 0) return [];
+ // Fix wave 13 P1.18: reserve on the ambient tracker before any provider call,
+ // as embed() does. An image is reserved at the provider's per-input maximum
+ // (MULTIMODAL_IMAGE_TOKEN_CEILING) and settled at the provider's reported
+ // tokens when it reports them, so a cap is never crossed by an estimate.
+ const tracker = __budgetStore.getStore() ?? null;
+ if (!tracker) return embedMultimodalUnmetered(inputs, opts);
+ const modelStr = requireConfig().embedding_multimodal_model ?? getEmbeddingModel();
+ const { parsed, recipe } = resolveRecipe(modelStr);
+ const mmModelId = `${recipe.id}:${parsed.modelId}`;
+ const charsPerToken = Math.max(recipe.touchpoints.embedding?.chars_per_token ?? DEFAULT_CHARS_PER_TOKEN, 1);
+ const estimatedInputTokens = inputs.reduce((n, input) => n + (input.kind === 'text' ? Math.ceil(input.text.length / charsPerToken) : MULTIMODAL_IMAGE_TOKEN_CEILING), 0);
+ const reservation = tracker.reserve({ modelId: mmModelId, estimatedInputTokens, maxOutputTokens: 0, kind: 'embed', label: 'gateway.multimodal' });
+ const usage: { tokens: number | null } = { tokens: 0 };
+ try {
+ const out = await embedMultimodalUnmetered(inputs, opts, usage);
+ recordOnTracker(tracker, { modelId: mmModelId, reservation, requestedModelId: modelStr, kind: 'embed', label: 'gateway.multimodal',
+ inputTokens: usage.tokens || estimatedInputTokens, outputTokens: 0, estimated: !usage.tokens });
+ return out;
+ } catch (err) {
+ if (err instanceof AIConfigError) tracker.release(reservation);
+ else recordOnTracker(tracker, { modelId: mmModelId, reservation, requestedModelId: modelStr, kind: 'embed', label: 'gateway.multimodal.failed',
+ inputTokens: estimatedInputTokens, outputTokens: 0, failed: true, estimated: true });
+ throw err;
+ }
+}
+
+async function embedMultimodalUnmetered(
+ inputs: MultimodalInput[],
+ opts: EmbedMultimodalOpts,
+ usage: { tokens: number | null } = { tokens: null },
+): Promise<Float32Array[]> {
const cfg = requireConfig();
// Prefer embedding_multimodal_model when set, so brains using OpenAI for
@@ -1895,6 +1926,7 @@ export async function embedMultimodal(
// recipe is `openai-compat` per tier but uses its own /multimodalembeddings
// path, so we still branch on recipe.id for that one.
if (recipe.id !== 'voyage' && recipe.implementation === 'openai-compatible') {
+ usage.tokens = null;
return embedMultimodalOpenAICompat(inputs, recipe, parsed.modelId, cfg, opts);
}
if (recipe.id !== 'voyage') {
@@ -1987,9 +2019,9 @@ export async function embedMultimodal(
);
}
- let parsedBody: { data?: Array<{ embedding: number[] }> };
+ let parsedBody: { data?: Array<{ embedding: number[] }>; usage?: { total_tokens?: unknown } };
try {
- parsedBody = (await res.json()) as { data?: Array<{ embedding: number[] }> };
+ parsedBody = (await res.json()) as { data?: Array<{ embedding: number[] }>; usage?: { total_tokens?: unknown } };
} catch (err) {
throw new AITransientError(
`Voyage multimodal returned malformed JSON: ${err instanceof Error ? err.message : String(err)}.`,
@@ -2011,6 +2043,8 @@ export async function embedMultimodal(
}
allEmbeddings.push(new Float32Array(row.embedding));
}
+ const reported = parsedBody.usage?.total_tokens;
+ usage.tokens = usage.tokens !== null && typeof reported === 'number' && reported > 0 ? usage.tokens + reported : null;
}
return screenAlignedEmbeddings(allEmbeddings, `${recipe.id}:${parsed.modelId}`);
@@ -2380,6 +2414,14 @@ export function parseExpansionResponse(text: string): string[] | null {
// by the image token cost, NOT its base64 length (bytes are not tokens).
const EXPANSION_FAILED_PESSIMISTIC_OUTPUT_TOKENS = 512;
const OCR_IMAGE_INPUT_TOKEN_ESTIMATE = 1600;
+/** Fix wave 13 P1.18: OCR's explicit output bound, the same number its tracker reservation holds. */
+const OCR_MAX_OUTPUT_TOKENS = 4096;
+/**
+ * Fix wave 13 P1.18: the tokens one image input can cost a multimodal embedding
+ * provider at most, reserved before the call (Voyage: 16M pixels at 560 pixels
+ * per token). The provider's reported usage settles it when present.
+ */
+const MULTIMODAL_IMAGE_TOKEN_CEILING = Math.ceil(16_000_000 / 560);
/**
* #4121 — the v6/legacy AI-SDK usage shapes (`inputTokens|promptTokens`,
@@ -2640,12 +2682,15 @@ export async function generateOcrText(imageBytes: Buffer, mime: string): Promise
const estimatedOcrInputTokens =
estimateChatInputTokens({ system: systemPrompt, messages: [{ content: 'Extract visible text only.' }] }) +
OCR_IMAGE_INPUT_TOKEN_ESTIMATE;
+ // Fix wave 13 P1.18: reserve before the call with the explicit output bound the call is sent with.
+ const reservation = tracker?.reserve({ modelId: ocrModelId, estimatedInputTokens: estimatedOcrInputTokens, maxOutputTokens: OCR_MAX_OUTPUT_TOKENS, kind: 'chat', label: 'gateway.ocr' });
const recordOcr = (label: 'gateway.ocr' | 'gateway.ocr.failed', usage: { inputTokens: number; outputTokens: number }): void =>
- recordOnTracker(tracker, { modelId: ocrModelId, requestedModelId: ocrModel, label, ...usage });
+ recordOnTracker(tracker, { modelId: ocrModelId, requestedModelId: ocrModel, label, reservation, ...usage });
let result: Awaited<ReturnType<GenerateTextFn>>;
try {
result = await guardedGeneration(ocrModelId, _generateTextTransport, {
model,
+ maxOutputTokens: OCR_MAX_OUTPUT_TOKENS,
// v0.42.20.0 (codex) — OCR is a 5th unbounded generateText entry point.
abortSignal: withDefaultTimeout(undefined, AI_CHAT_TIMEOUT_MS),
messages: [
@@ -2669,7 +2714,7 @@ export async function generateOcrText(imageBytes: Buffer, mime: string): Promise
if (isAIInvocationPolicyError(err)) throw err;
recordOcr('gateway.ocr.failed', failedCallUsage(err, {
inputTokens: estimatedOcrInputTokens,
- outputTokens: DEFAULT_MAX_OUTPUT_TOKENS,
+ outputTokens: OCR_MAX_OUTPUT_TOKENS,
}));
// Throw-to-caller contract unchanged: importImageFile routes this to
// ocr_failed_other. A cap breach surfaces there as a real import failure.
diff --git a/src/core/embed-budget-stop.ts b/src/core/embed-budget-stop.ts
index d227744138..72934eda2a 100644
--- a/src/core/embed-budget-stop.ts
+++ b/src/core/embed-budget-stop.ts
@@ -10,7 +10,7 @@ import type { BrainEngine } from './engine.ts';
export interface EmbedBudgetStopFields {
embedded: number;
- reason?: 'stall_timeout' | 'time_budget';
+ reason?: 'stall_timeout' | 'time_budget' | 'cost_cap';
remaining_stale?: number;
resume_command?: string;
}
diff --git a/src/core/embed-consent.ts b/src/core/embed-consent.ts
index 5e978a27ca..5b2e77d47f 100644
--- a/src/core/embed-consent.ts
+++ b/src/core/embed-consent.ts
@@ -27,6 +27,8 @@ export interface EmbedBackfillScope {
sourceId?: string;
/** Slug lists, facts and images have no cheap pre-flight estimate. */
unestimated?: boolean;
+ /** `--images`: the run spends with the multimodal embedding model and, when OCR is on, the OCR model. */
+ images?: boolean;
}
/**
@@ -60,15 +62,27 @@ export async function embeddingProviderIsFree(model?: string): Promise<boolean>
}
}
-/** True when an embed run would spend: embeddings on, a paid embedding provider with credentials. */
-export async function embedWouldSpend(engine: BrainEngine): Promise<boolean> {
+/**
+ * True when an embed run would spend: embeddings on, a paid embedding provider
+ * with credentials. An image run (fix wave 13 P1.18) also spends with the
+ * multimodal model and, when OCR is on, the OCR model, even when the text
+ * provider is free; an unreadable model counts as paid.
+ */
+export async function embedWouldSpend(engine: BrainEngine, opts: { images?: boolean } = {}): Promise<boolean> {
const { embeddingsDisabled } = await import('./embedding-disabled.ts');
if (await embeddingsDisabled(engine)) return false;
try {
- const { isAvailable } = await import('./ai/gateway.ts');
- return isAvailable('embedding') && !(await embeddingProviderIsFree());
+ const { isAvailable, getImageOcrModel } = await import('./ai/gateway.ts');
+ if (isAvailable('embedding') && !(await embeddingProviderIsFree())) return true;
+ if (!opts.images) return false;
+ const { multimodalEmbeddingModel } = await import('./ai/multimodal-model.ts');
+ const multimodal = multimodalEmbeddingModel();
+ if (multimodal && !(await embeddingProviderIsFree(multimodal))) return true;
+ if (process.env.GBRAIN_EMBEDDING_IMAGE_OCR !== 'true') return false;
+ const ocr = getImageOcrModel();
+ return isAvailable('expansion', ocr) && !(await embeddingProviderIsFree(ocr));
} catch {
- return false;
+ return opts.images === true;
}
}
@@ -109,7 +123,7 @@ export async function requireEmbedBackfillConsent(engine: BrainEngine, opts: {
args: readonly string[];
scope: EmbedBackfillScope;
}): Promise<Authorization | null> {
- if (!(await embedWouldSpend(engine))) return null;
+ if (!(await embedWouldSpend(engine, { images: opts.scope.images === true }))) return null;
const est = await estimateEmbedBackfillUsd(engine, opts.scope);
const cost = est === null ? 'its cost could not be estimated in advance' : `it is estimated at $${est.toFixed(4)}`;
const auth = await requireConsent({
diff --git a/src/core/embed-cost-cap.ts b/src/core/embed-cost-cap.ts
new file mode 100644
index 0000000000..0311e742d4
--- /dev/null
+++ b/src/core/embed-cost-cap.ts
@@ -0,0 +1,79 @@
+/**
+ * The approved spend cap of a foreground `gbrain embed` run (fix wave 13
+ * P1.18, from PR #6400). Consent returns an Authorization with `cap_usd`; the
+ * run spends under a BudgetTracker holding that cap, so every embedding,
+ * multimodal and OCR call reserves before it is sent. The first refused
+ * reservation aborts the run's signal before the refusal propagates: the
+ * page and batch catches see a shutdown, not a chunk failure (no quarantine
+ * strike, no per-chunk fan-out), vectors already installed stay banked, and
+ * the CLI exits BUDGET_STOP_EXIT_CODE with the command that resumes.
+ */
+import type { CapSource } from './consent.ts';
+import { BudgetExhausted, BudgetTracker } from './budget/budget-tracker.ts';
+import { withBudgetTracker } from './ai/gateway.ts';
+
+export interface EmbedCostCap {
+ readonly signal: AbortSignal;
+ /** The cap's refusal once the run reached it; null while under it. */
+ hit(): BudgetExhausted | null;
+ metered<T>(fn: () => Promise<T>): Promise<T>;
+}
+
+export interface EmbedCostStopFields {
+ reason?: string;
+ /** The tracker's refusal reason: `cost`, or `no_pricing` (a model with no known price under a user cap). */
+ budget_reason?: string;
+ cap_usd?: number;
+ spent_usd?: number;
+ resume_command?: string;
+}
+
+/** Null when the authorization carries no finite positive cap (nothing to meter). */
+export function embedCostCap(capUsd: number | null | undefined, capSource: CapSource | null | undefined): EmbedCostCap | null {
+ if (typeof capUsd !== 'number' || !Number.isFinite(capUsd) || capUsd <= 0) return null;
+ const tracker = new BudgetTracker({ maxCostUsd: capUsd, label: 'embed', ...(capSource ? { capSource } : {}) });
+ const controller = new AbortController();
+ let refusal: BudgetExhausted | null = null;
+ // The refusal itself (cost, or a model with no price under a user cap) is kept for the verdict.
+ const reserve = tracker.reserve.bind(tracker);
+ tracker.reserve = estimate => {
+ try { return reserve(estimate); } catch (err) { if (err instanceof BudgetExhausted) refusal ??= err; throw err; }
+ };
+ tracker.onExhausted(() => controller.abort());
+ return {
+ signal: controller.signal,
+ hit: () => refusal ?? (controller.signal.aborted
+ ? new BudgetExhausted(`embed reached its $${capUsd.toFixed(2)} cost cap`, { reason: 'cost', spent: tracker.totalSpent, cap: capUsd })
+ : null),
+ metered: fn => withBudgetTracker(tracker, fn),
+ };
+}
+
+/**
+ * Record the stop on `result`. The resume command is the run itself without
+ * its approval flags, so the user approves the rest again: a slug run skips
+ * chunks that already have vectors, a stale run picks up where this one stopped.
+ */
+export function noteEmbedCostStop(result: EmbedCostStopFields, refusal: BudgetExhausted, args: readonly string[]): void {
+ const resume: string[] = [];
+ for (let i = 0; i < args.length; i++) {
+ if (args[i] === '--yes' || args[i] === '--json') continue;
+ if (args[i] === '--max-usd' || args[i] === '--max-cost') { i++; continue; }
+ if (/^--max-(?:usd|cost)=/.test(args[i]!)) continue;
+ resume.push(args[i]!);
+ }
+ result.reason = 'cost_cap';
+ result.budget_reason = refusal.reason;
+ result.cap_usd = refusal.cap;
+ result.spent_usd = refusal.spent;
+ result.resume_command = ['gbrain', 'embed', ...resume].join(' ');
+}
+
+/** The stdout verdict line for a cost-cap stop. */
+export function embedCostStopVerdict(result: EmbedCostStopFields, refusal?: BudgetExhausted | null): string {
+ const why = result.budget_reason === 'no_pricing' && refusal
+ ? refusal.message
+ : `the run reached its approved $${result.cap_usd?.toFixed(2)} cost cap after spending $${result.spent_usd?.toFixed(4)}`;
+ return `[embed] stopped (reason: cost_cap): ${why}; embeddings already written are kept. `
+ + `Resume, after the user approves more spend: ${result.resume_command} --max-usd <usd>`;
+}
diff --git a/src/core/embed-stale-images.ts b/src/core/embed-stale-images.ts
index f38dfef682..b32ae2f03f 100644
--- a/src/core/embed-stale-images.ts
+++ b/src/core/embed-stale-images.ts
@@ -19,8 +19,9 @@ import { importImageFile } from './import-file.ts';
import { safeChunksFilter } from './search/safe-chunks.ts';
import { serr } from './console-prefix.ts';
import { gitChildEnv } from './git-env.ts';
+import { embedCostStopVerdict, noteEmbedCostStop, type EmbedCostCap, type EmbedCostStopFields } from './embed-cost-cap.ts';
-export interface StaleImageSweepResult {
+export interface StaleImageSweepResult extends EmbedCostStopFields {
candidates: number;
rebuilt: number;
/** Candidates the importer left unchanged (complete by its own check, or refused). */
@@ -32,7 +33,7 @@ export interface StaleImageSweepResult {
export async function embedStaleImages(
engine: BrainEngine,
- opts: { sourceId?: string; dryRun: boolean },
+ opts: { sourceId?: string; dryRun: boolean; costCap?: EmbedCostCap | null },
): Promise<StaleImageSweepResult> {
const ocrWanted = process.env.GBRAIN_EMBEDDING_IMAGE_OCR === 'true';
const params: unknown[] = [ocrWanted];
@@ -53,16 +54,22 @@ export async function embedStaleImages(
if (opts.dryRun) return result;
const repoPath = await engine.getConfig('sync.repo_path').catch(() => null);
const gitRoots = new Map<string, string | null>();
+ const cap = opts.costCap;
for (const row of rows) {
+ // Fix wave 13 P1.18: the approved cap stops the sweep before the next image; a refused image is not a failure.
+ if (cap?.hit()) break;
const root = row.local_path ?? (row.source_id === 'default' ? repoPath : null);
const file = root && row.source_path ? locateSourceFile(root, row.source_path, gitRoots) : null;
if (!file) { result.missingFile++; continue; }
try {
- const imported = await importImageFile(engine, file, row.source_path!, { sourceId: row.source_id });
+ const run = () => importImageFile(engine, file, row.source_path!, { sourceId: row.source_id });
+ const imported = cap ? await cap.metered(run) : await run();
if (imported.status === 'imported') result.rebuilt++;
+ else if (cap?.hit()) break;
else if (imported.status === 'error') fail(row, imported.error ?? 'import failed');
else result.skipped++;
} catch (e) {
+ if (cap?.hit()) break;
fail(row, e instanceof Error ? e.message : String(e));
}
}
@@ -70,18 +77,21 @@ export async function embedStaleImages(
}
/** The `gbrain embed --stale --images` CLI surface (dispatched from commands/embed.ts). */
-export async function runEmbedStaleImagesCli(engine: BrainEngine, args: string[]): Promise<StaleImageSweepResult> {
+export async function runEmbedStaleImagesCli(engine: BrainEngine, args: string[], costCap: EmbedCostCap | null = null): Promise<StaleImageSweepResult> {
if (!args.includes('--stale') || process.env.GBRAIN_EMBEDDING_MULTIMODAL !== 'true') {
serr('Usage: gbrain embed --stale --images [--source <id>] [--dry-run] [--json] (requires GBRAIN_EMBEDDING_MULTIMODAL=true)');
process.exit(1);
}
const srcI = args.indexOf('--source');
const dryRun = args.includes('--dry-run');
- const result = await embedStaleImages(engine, { sourceId: srcI >= 0 ? args[srcI + 1] : undefined, dryRun });
+ const result = await embedStaleImages(engine, { sourceId: srcI >= 0 ? args[srcI + 1] : undefined, dryRun, costCap });
+ const capped = costCap?.hit();
+ if (capped) noteEmbedCostStop(result, capped, args);
if (args.includes('--json')) console.log(JSON.stringify(result));
else console.log(`[embed] images: ${result.candidates} incomplete, ${dryRun ? '(dry run) nothing rebuilt'
: `${result.rebuilt} rebuilt, ${result.skipped} unchanged, ${result.missingFile} missing source file, ${result.failures} failed`}`);
if (result.failures > 0) serr(`[embed] first image failure: ${result.failure_samples[0]}`);
+ if (capped) (args.includes('--json') ? serr : console.log)(embedCostStopVerdict(result, capped));
return result;
}
diff --git a/test/doctor-stub-guard.test.ts b/test/doctor-stub-guard.test.ts
index 425062e3d8..5c9d8a4a50 100644
--- a/test/doctor-stub-guard.test.ts
+++ b/test/doctor-stub-guard.test.ts
@@ -13,6 +13,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { logStubGuardEvent } from '../src/core/facts/stub-guard-audit.ts';
import { stubGuardEntry } from '../src/commands/doctor/checks/local-audits.ts';
import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
import { withEnv } from './helpers/with-env.ts';
let engine: PGLiteEngine;
@@ -24,7 +25,7 @@ async function stubGuardCheck(events: Array<'unprefixed' | 'fallback_resolution'
try {
return await withEnv({ GBRAIN_AUDIT_DIR: dir, GBRAIN_HOME: dir }, async () => {
events.forEach((reason, i) => logStubGuardEvent({ slug: `people/p${i}`, source_id: 'default', fact_count: 1, ...(reason ? { reason } : {}) }));
- const checks = await stubGuardEntry.run({ engine, orphanRatioSourceId: null } as unknown as DoctorContext);
+ const checks = await stubGuardEntry.run({ engine, orphanRatioSourceId: null } as unknown as DoctorContext) as Check[];
return checks.find(c => c.name === 'stub_guard_24h');
});
} finally { rmSync(dir, { recursive: true, force: true }); }
diff --git a/test/e2e/embed-background-cap.test.ts b/test/e2e/embed-background-cap.test.ts
new file mode 100644
index 0000000000..94f67431ed
--- /dev/null
+++ b/test/e2e/embed-background-cap.test.ts
@@ -0,0 +1,40 @@
+/**
+ * Fix wave 13 P1.18 [R4]: `gbrain embed --background --max-usd N` carries the
+ * approval to the worker. The queued `embed` row stores the spend
+ * authorization with the approved cap (the worker's runWithJobSpend meters
+ * every provider call against it); a run with no authorization (a free
+ * provider) queues no authorization, as before.
+ * Seams: none; Postgres only.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { runEmbed } from '../../src/commands/embed.ts';
+
+const RUN = hasDatabase();
+const d = RUN ? describe : describe.skip;
+let engine: PostgresEngine;
+
+beforeAll(async () => { if (RUN) engine = await setupDB() as PostgresEngine; }, 120_000);
+afterAll(async () => { if (RUN) await teardownDB(); });
+
+async function queued(sourceId: string) {
+ const rows = await engine.executeRaw<{ spend_authorization: Record<string, unknown> | string | null }>(
+ `SELECT spend_authorization FROM minion_jobs WHERE name = 'embed' AND data->>'sourceId' = $1 ORDER BY id DESC LIMIT 1`, [sourceId]);
+ const raw = rows[0]?.spend_authorization ?? null;
+ return typeof raw === 'string' ? JSON.parse(raw) as Record<string, unknown> : raw;
+}
+
+d('embed --background carries the approved cap', () => {
+ test('the queued row stores the authorization with cap_usd', async () => {
+ const write = process.stdout.write;
+ process.stdout.write = (() => true) as typeof process.stdout.write;
+ try {
+ await runEmbed(engine, ['--stale', '--source', 'cap-src', '--max-usd', '0.25', '--background'], null,
+ { authorization: { consented_effects: ['paid'], cap_usd: 0.25, cap_source: 'user', via: 'max_usd' } });
+ await runEmbed(engine, ['--stale', '--source', 'free-src', '--background'], null, { authorization: null });
+ } finally { process.stdout.write = write; }
+ expect(await queued('cap-src')).toMatchObject({ kind: 'authorized', cap_usd: 0.25, cap_source: 'user', command: 'embed' });
+ expect(await queued('free-src')).toBeNull();
+ });
+});
diff --git a/test/embed-consent-multimodal.test.ts b/test/embed-consent-multimodal.test.ts
new file mode 100644
index 0000000000..60ce142005
--- /dev/null
+++ b/test/embed-consent-multimodal.test.ts
@@ -0,0 +1,40 @@
+/**
+ * Fix wave 13 P1.18 [R4]: `embed --stale --images` spends with the multimodal
+ * embedding model and, when OCR is on, the OCR model. Consent skipped the ask
+ * whenever the TEXT provider was free, so a paid multimodal or OCR model ran
+ * with a null Authorization and no cap.
+ * Protects: free text provider + paid multimodal model → consent asks (exit-3
+ * refusal without approval); free text provider + OCR on with a paid OCR model
+ * → asks; free text provider with no paid image model → no ask, as before; a
+ * text-only run is unchanged.
+ * Seams: GBRAIN_EMBEDDING_IMAGE_OCR via withEnv; PGLite.
+ */
+import { afterAll, afterEach, beforeAll, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { requireEmbedBackfillConsent } from '../src/core/embed-consent.ts';
+import { isConsentRefusal } from '../src/core/consent.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);
+afterAll(async () => { await engine.disconnect(); });
+afterEach(() => resetGateway());
+
+const consent = (images: boolean) => requireEmbedBackfillConsent(engine, {
+ command: 'embed', argv: ['gbrain', 'embed', '--stale', ...(images ? ['--images'] : [])], args: [], scope: { unestimated: true, ...(images ? { images: true } : {}) },
+}).then(auth => ({ asked: false, auth }), (e: unknown) => { if (isConsentRefusal(e)) return { asked: true, auth: null }; throw e; });
+
+test('a paid multimodal model behind a free text provider asks for approval', () => withEnv({ GBRAIN_EMBEDDING_IMAGE_OCR: undefined }, async () => {
+ configureGateway({ embedding_model: 'ollama:nomic-embed-text', embedding_dimensions: 768, embedding_multimodal_model: 'voyage:voyage-multimodal-3',
+ env: { VOYAGE_API_KEY: 'test-key' } });
+ expect((await consent(true)).asked).toBe(true);
+ expect(await consent(false)).toEqual({ asked: false, auth: null });
+}));
+
+test('OCR on with a paid OCR model asks; OCR off with no paid image model does not', async () => {
+ configureGateway({ embedding_model: 'ollama:nomic-embed-text', embedding_dimensions: 768, expansion_model: 'anthropic:claude-haiku-4-5-20251001',
+ env: { ANTHROPIC_API_KEY: 'sk-test-fake' } });
+ await withEnv({ GBRAIN_EMBEDDING_IMAGE_OCR: 'true' }, async () => { expect((await consent(true)).asked).toBe(true); });
+ await withEnv({ GBRAIN_EMBEDDING_IMAGE_OCR: undefined }, async () => { expect(await consent(true)).toEqual({ asked: false, auth: null }); });
+});
diff --git a/test/embed-max-usd-metered.serial.test.ts b/test/embed-max-usd-metered.serial.test.ts
new file mode 100644
index 0000000000..fca98c0334
--- /dev/null
+++ b/test/embed-max-usd-metered.serial.test.ts
@@ -0,0 +1,141 @@
+/**
+ * Fix wave 13 P1.18 (from PR #6400, credit @daveove): `gbrain embed` checked an
+ * approved `--max-usd` only against the pre-run estimate, which is null for
+ * `--slugs` and `--images`, so the run was never metered.
+ * Protects: the CLI runs under the approved cap. A provider priced past it
+ * after batch 1 stops the run with `reason: cost_cap`, exit
+ * BUDGET_STOP_EXIT_CODE (not 1), batch 1's vectors kept, zero calls after the
+ * stop, no failures recorded (no quarantine strike, no per-chunk fan-out),
+ * and a resume command. `--images` stops the same way. A free provider (no
+ * authorization) runs as before. PGLite `--background` runs inline, metered.
+ * Serial: configures the AI gateway and fetch for the whole file.
+ * Seams: __setEmbedTransportForTests, a fetch stub, GBRAIN_HOME temp dir.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { importFromContent, importImageFile } from '../src/core/import-file.ts';
+import { run as runEmbedCli } from '../src/cli/commands/embed.ts';
+import { runEmbed } from '../src/commands/embed.ts';
+import { requireEmbedBackfillConsent } from '../src/core/embed-consent.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
+import { BUDGET_STOP_EXIT_CODE } from '../src/core/exit-codes.ts';
+import { runSources } from '../src/commands/sources.ts';
+import { withEnv } from './helpers/with-env.ts';
+import type { CliDispatchContext } from '../src/cli/command-table.ts';
+
+const DIMS = 1536;
+const SLUGS = ['notes/a', 'notes/b', 'notes/c', 'notes/d'];
+let engine: PGLiteEngine;
+let home: string;
+let calls = 0;
+let tokensPerCall = 1_000_000;
+const origFetch = globalThis.fetch;
+const ctx = { SELECTED_CONFIG_BY_ENGINE: new Map() } as unknown as CliDispatchContext;
+
+function textGateway() {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'sk-test-fake' } });
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {
+ calls++;
+ return { embeddings: values.map(() => new Array(DIMS).fill(0.001)), usage: { tokens: tokensPerCall } };
+ }) as never);
+}
+
+beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-embed-cap-'));
+ textGateway();
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+}, 60_000);
+afterAll(async () => { __setEmbedTransportForTests(null); globalThis.fetch = origFetch; resetGateway(); await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });
+beforeEach(async () => {
+ calls = 0; tokensPerCall = 1_000_000; _resetCliExitVerdictForTests(); textGateway();
+ for (const slug of SLUGS) await importFromContent(engine, slug, `---\ntitle: ${slug}\ntype: note\n---\n\nA short note about ${slug} for the embedding cap test.\n`, { noEmbed: true });
+ await engine.executeRaw('UPDATE content_chunks SET embedding = NULL, embedded_at = NULL');
+});
+
+const embedded = async () => (await engine.executeRaw<{ slug: string }>(
+ 'SELECT DISTINCT p.slug FROM pages p JOIN content_chunks c ON c.page_id = p.id WHERE c.embedding IS NOT NULL ORDER BY p.slug')).map(r => r.slug);
+async function cli(args: string[]) {
+ const out: string[] = [];
+ const log = console.log;
+ const write = process.stdout.write;
+ console.log = (...a: unknown[]) => { out.push(a.map(String).join(' ')); };
+ process.stdout.write = ((chunk: unknown) => { out.push(String(chunk)); return true; }) as typeof process.stdout.write;
+ try { await withEnv({ GBRAIN_HOME: home, GBRAIN_AUDIT_DIR: home }, () => runEmbedCli(engine, args, ctx)); } finally { console.log = log; process.stdout.write = write; }
+ return { out: out.join('\n'), exit: currentExitCode() };
+}
+
+describe('embed --max-usd is metered', () => {
+ test('--slugs: stops at the cap after batch 1, exit 11, batch 1 kept, no calls after, resume command printed', async () => {
+ const { out, exit } = await cli(['--slugs', ...SLUGS, '--max-usd', '0.10']);
+ expect(exit).toBe(BUDGET_STOP_EXIT_CODE);
+ expect(calls).toBe(1);
+ expect(await embedded()).toEqual(['notes/a']);
+ expect(out).toContain('[embed] stopped (reason: cost_cap)');
+ expect(out).toContain(`gbrain embed --slugs ${SLUGS.join(' ')} --max-usd <usd>`);
+ });
+
+ test('the result records the stop and no failure (no quarantine strike, no per-chunk fan-out)', async () => {
+ const authorization = await withEnv({ GBRAIN_HOME: home }, () => requireEmbedBackfillConsent(engine, { command: 'embed', argv: ['gbrain', 'embed'], args: ['--max-usd', '0.10'], scope: { unestimated: true } }));
+ const result = await withEnv({ GBRAIN_HOME: home, GBRAIN_AUDIT_DIR: home }, () => runEmbed(engine, ['--slugs', ...SLUGS, '--max-usd', '0.10', '--yes'], null, { authorization }));
+ expect(result).toMatchObject({ reason: 'cost_cap', budget_reason: 'cost', cap_usd: 0.1, failures: 0, embedded: 1, failure_samples: [],
+ resume_command: `gbrain embed --slugs ${SLUGS.join(' ')}` });
+ expect(calls).toBe(1);
+ });
+
+ test('--stale with multi-chunk pages: one provider call, then a clean stop (no per-chunk fan-out, no failures)', async () => {
+ const long = Array.from({ length: 40 }, (_, i) => `## Section ${i}\n\n${'Plain words about the cap test and its pages. '.repeat(40)}`).join('\n\n');
+ for (const slug of ['long/one', 'long/two']) await importFromContent(engine, slug, `---\ntitle: ${slug}\ntype: note\n---\n\n${long}\n`, { noEmbed: true });
+ await engine.executeRaw('UPDATE content_chunks SET embedding = NULL, embedded_at = NULL');
+ const authorization = await withEnv({ GBRAIN_HOME: home }, () => requireEmbedBackfillConsent(engine, { command: 'embed', argv: ['gbrain', 'embed'], args: ['--max-usd', '0.10'], scope: { unestimated: true } }));
+ const result = await withEnv({ GBRAIN_HOME: home, GBRAIN_AUDIT_DIR: home, GBRAIN_EMBED_CONCURRENCY: '1' }, () => runEmbed(engine, ['--stale', '--max-usd', '0.10'], null, { authorization }));
+ expect(result).toMatchObject({ reason: 'cost_cap', failures: 0, failure_samples: [], resume_command: 'gbrain embed --stale' });
+ expect(calls).toBe(1);
+ });
+
+ test('a cap the run stays under changes nothing', async () => {
+ tokensPerCall = 10;
+ const { exit } = await cli(['--slugs', ...SLUGS, '--max-usd', '0.10']);
+ expect(exit).toBe(0);
+ expect(await embedded()).toEqual(SLUGS);
+ });
+
+ test('PGLite --background runs inline under the same cap', async () => {
+ const { exit } = await cli(['--slugs', ...SLUGS, '--max-usd', '0.10', '--background']);
+ expect(exit).toBe(BUDGET_STOP_EXIT_CODE);
+ expect(calls).toBe(1);
+ });
+
+ test('a free provider needs no authorization and runs unmetered', async () => {
+ configureGateway({ embedding_model: 'ollama:nomic-embed-text', embedding_dimensions: DIMS, env: {} });
+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => { calls++; return { embeddings: values.map(() => new Array(DIMS).fill(0.001)), usage: { tokens: tokensPerCall } }; }) as never);
+ const { exit } = await cli(['--slugs', ...SLUGS]);
+ expect(exit).toBe(0);
+ expect(calls).toBe(SLUGS.length);
+ });
+});
+
+describe('embed --stale --images --max-usd is metered', () => {
+ const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64');
+ test('stops before the second image once the first exceeded the cap', async () => {
+ const dir = join(home, 'imgs'); mkdirSync(join(dir, 'photos'), { recursive: true });
+ await withEnv({ GBRAIN_HOME: home }, () => runSources(engine, ['add', 'img', '--path', dir, '--no-federated', '--force']));
+ let fetches = 0;
+ globalThis.fetch = (async () => {
+ fetches++;
+ return new Response(JSON.stringify({ data: [{ embedding: Array.from({ length: 1024 }, () => 0.1) }], usage: { total_tokens: 1_000_000 } }), { status: 200, headers: { 'Content-Type': 'application/json' } });
+ }) as unknown as typeof fetch;
+ configureGateway({ embedding_model: 'voyage:voyage-multimodal-3', embedding_multimodal_model: 'voyage:voyage-multimodal-3', embedding_dimensions: 1024, env: { VOYAGE_API_KEY: 'test-key' } });
+ for (const name of ['one.png', 'two.png']) {
+ writeFileSync(join(dir, 'photos', name), PNG);
+ await importImageFile(engine, join(dir, 'photos', name), `photos/${name}`, { noEmbed: true, sourceId: 'img' });
+ }
+ const { out, exit } = await withEnv({ GBRAIN_EMBEDDING_MULTIMODAL: 'true' }, () => cli(['--stale', '--images', '--source', 'img', '--max-usd', '0.10', '--json']));
+ expect(JSON.parse(out.slice(out.search(/^\{/m)))).toMatchObject({ reason: 'cost_cap', rebuilt: 1, failures: 0 });
+ expect(exit).toBe(BUDGET_STOP_EXIT_CODE);
+ expect(fetches).toBe(1);
+ });
+});
diff --git a/test/gateway-ocr-reserve.test.ts b/test/gateway-ocr-reserve.test.ts
new file mode 100644
index 0000000000..a54c1f96c8
--- /dev/null
+++ b/test/gateway-ocr-reserve.test.ts
@@ -0,0 +1,73 @@
+/**
+ * Fix wave 13 P1.18 (from PR #6400): OCR and multimodal embedding reserve on
+ * the ambient BudgetTracker BEFORE the provider call, as embed() and chat do.
+ * Protects: an exhausted tracker means zero OCR / multimodal provider calls;
+ * OCR is sent with the explicit output bound its reservation holds; a
+ * multimodal call settles at the provider's reported tokens when present;
+ * outside a tracker nothing changes.
+ * Seams: __setGenerateTextTransportForTests, a fetch stub (Voyage multimodal).
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ configureGateway, embedMultimodal, generateOcrText, resetGateway, withBudgetTracker, __setGenerateTextTransportForTests,
+} from '../src/core/ai/gateway.ts';
+import { BudgetExhausted, BudgetTracker } from '../src/core/budget/budget-tracker.ts';
+
+const tmp = mkdtempSync(join(tmpdir(), 'gbrain-w13-reserve-'));
+const tracker = (maxCostUsd?: number) => new BudgetTracker({ label: 'w13', auditPath: join(tmp, 'budget.jsonl'), ...(maxCostUsd !== undefined ? { maxCostUsd } : {}) });
+const origFetch = globalThis.fetch;
+afterEach(() => { __setGenerateTextTransportForTests(null); globalThis.fetch = origFetch; resetGateway(); });
+
+describe('generateOcrText reserves before the call', () => {
+ const ocrGateway = () => configureGateway({ expansion_model: 'anthropic:claude-haiku-4-5-20251001', env: { ANTHROPIC_API_KEY: 'sk-test-fake' } });
+ test('an exhausted cap refuses with zero OCR calls; the call carries the bound it reserved', async () => {
+ ocrGateway();
+ const sent: Array<{ maxOutputTokens?: number }> = [];
+ __setGenerateTextTransportForTests((async (opts: { maxOutputTokens?: number }) => { sent.push(opts); return { text: 'hi', usage: { inputTokens: 10, outputTokens: 2 } }; }) as never);
+ await expect(withBudgetTracker(tracker(0.000001), () => generateOcrText(Buffer.from('x'), 'image/png'))).rejects.toBeInstanceOf(BudgetExhausted);
+ expect(sent).toHaveLength(0);
+ const t = tracker(1);
+ await withBudgetTracker(t, () => generateOcrText(Buffer.from('x'), 'image/png'));
+ expect(sent).toHaveLength(1);
+ expect(sent[0]!.maxOutputTokens).toBe(4096);
+ expect(t.snapshot().callsRecorded).toBe(1);
+ });
+});
+
+describe('embedMultimodal reserves before the call', () => {
+ const voyage = (usage?: number) => {
+ let calls = 0;
+ globalThis.fetch = (async () => {
+ calls++;
+ return new Response(JSON.stringify({ data: [{ embedding: Array.from({ length: 1024 }, () => 0.1) }], ...(usage ? { usage: { total_tokens: usage } } : {}) }),
+ { status: 200, headers: { 'Content-Type': 'application/json' } });
+ }) as unknown as typeof fetch;
+ configureGateway({ embedding_model: 'voyage:voyage-multimodal-3', embedding_multimodal_model: 'voyage:voyage-multimodal-3', embedding_dimensions: 1024, env: { VOYAGE_API_KEY: 'test-key' } });
+ return () => calls;
+ };
+ const image = [{ kind: 'image_base64' as const, data: 'aGk=', mime: 'image/png' }];
+
+ test('an exhausted cap refuses with zero provider calls', async () => {
+ const calls = voyage();
+ await expect(withBudgetTracker(tracker(0.000001), () => embedMultimodal(image))).rejects.toBeInstanceOf(BudgetExhausted);
+ expect(calls()).toBe(0);
+ });
+
+ test('the reported tokens settle the reservation; an overrun stops the next call', async () => {
+ const calls = voyage(1_000_000);
+ const t = tracker(0.1);
+ await withBudgetTracker(t, () => embedMultimodal(image));
+ expect(t.totalSpent).toBeCloseTo(0.12, 6);
+ await expect(withBudgetTracker(t, () => embedMultimodal(image))).rejects.toBeInstanceOf(BudgetExhausted);
+ expect(calls()).toBe(1);
+ });
+
+ test('outside a tracker nothing changes', async () => {
+ const calls = voyage();
+ expect(await embedMultimodal(image)).toHaveLength(1);
+ expect(calls()).toBe(1);
+ });
+});