Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(extract_atoms): an explicit atoms cap refuses unpriced chat or embed routes

garrytan81631b879fd5
diff --git a/docs/TESTING.md b/docs/TESTING.md
index fd5e8fba35..f7bfb22e1f 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -2012,6 +2012,7 @@ Unit tests and what they cover:
- `test/models-per-task-extract-atoms.serial.test.ts` — `gbrain models` reports `models.dream.extract_atoms` through the phase's own resolver (pins the narrow-resolver divergence: `models.tier.utility` is deliberately ignored; unconfigured falls back to the same tier default the runtime uses).
- `test/conversation-facts-pricing-wiring.test.ts` — `pricing.overrides` reaches every conversation-facts entry point: the strict config registry accepts the key, and direct extraction, the cycle backfill, and `transcripts --facts` all price through the operator override.
- `test/budget/no-pricing-registration.test.ts` — explicit cost cap + unpriced model: the refusal carries the lookup-and-register guidance as text and structured fields on BudgetTracker, enrich, conversation facts (core and cycle phase) and skillopt; default caps warn (naming `gbrain pricing set`) and run; `gbrain pricing set` merges without clobbering other overrides, validates rates, warns on $0, and the retried run is priced and capped; list/unset; and the trust boundary (no operation registers prices, thin clients refuse `gbrain pricing`). PGLite + gateway test transports.
+- `test/extract-atoms-explicit-cap-no-pricing.test.ts` — extract_atoms with an explicit `cycle.extract_atoms.budget_usd`: an unpriced chat model or embed route is refused (status `warn`, no model call, `details.no_pricing` with `register_command`), the rollup records an expected limit not a halt, doctor's `extract_health` overlay names the command, and after `gbrain pricing set` the retried run extracts and the record clears; a default cap still warns and runs. PGLite + `_chat` seam + embed transport stub.
- `test/cycle/extract-atoms-model-config-fail-soft.test.ts` — a throwing `getConfig` during extract_atoms model resolution falls back to the tier default instead of rejecting the phase.
### Lane-move pilot (2026-09)
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.md
index e0c4e88e96..4ffbf24919 100644
--- a/docs/architecture/key-files/core-cycle.md
+++ b/docs/architecture/key-files/core-cycle.md
@@ -13,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/cycle/emotional-weight.ts` — Pure function `computeEmotionalWeight({tags, takes}, {highEmotionTags?, userHolder?})`. Deterministic 0..1 score: tag-emotion boost (max 0.5, case-insensitive match against `HIGH_EMOTION_TAGS` seed list), take density (0.1/take, capped at 0.3), take avg weight (0..0.1), user-holder ratio (0..0.1 over active takes; default holder `'garry'`). Total clamped to [0..1]. Anglocentric / personal-life-biased seed list intentional; override via config `emotional_weight.high_tags` (JSON array). `userHolder` overridable via `emotional_weight.user_holder`.
-- `src/core/cycle/extract-atoms-cost-gate.ts` — pure cost-gate decision for the extract_atoms `BudgetTracker`. `resolveExtractAtomsCostGate(extractModel, embedModel, overrides?, {explicitBudget?})` returns `{enforceCap, unpricedModel?, unpricedKind?, zeroPricedEmbedModel?, pricingOverrides?}`: the cap is enforceable only when EVERY model billed under the phase's tracker is priceable — the extraction chat model AND the embedding model the atom import (`importFromContent`, inside the same `withBudgetTracker` scope) calls — with operator `pricing.overrides` consulted first, matching `BudgetTracker.reserve()`. `resolveEmbedModelForCostGate()` mirrors the write site's `isAvailable('embedding')` gate (null when embedding is unavailable, so the import runs `noEmbed` and nothing embeds). Only a DEFAULT cap may be dropped that way: when the operator SET `cycle.extract_atoms.budget_usd` (`explicitBudget`), an unpriced EMBED route keeps the cap and is priced at $0 via the returned `pricingOverrides` (the caller's map plus the $0 row); an unpriced CHAT model drops the cap either way. The phase passes the decision into `maxCostUsd` and hands the gate's overrides (or its own) to the tracker; it warns once either way (unpriced: kind + model + the `pricing.overrides` remedy, running uncapped rather than latching `budget_exhausted` on the first item; zero-priced: the embed model + the rate remedy). Pinned by `test/extract-atoms-embed-cost-gate.test.ts` (pure cases + a PGLite round-trip with a $0 chat model and an unpriced embed route).
+- `src/core/cycle/extract-atoms-cost-gate.ts` — cost-gate decision for the extract_atoms `BudgetTracker`. `resolveExtractAtomsCostGate(extractModel, embedModel, overrides?, {explicitBudget?})` (pure) returns `{enforceCap, unpricedModel?, unpricedKind?, refusal?}`: the cap is enforceable only when EVERY model billed under the phase's tracker is priceable — the extraction chat model AND the embedding model the atom import (`importFromContent`, inside the same `withBudgetTracker` scope) calls — with operator `pricing.overrides` consulted first, matching `BudgetTracker.reserve()`. `resolveEmbedModelForCostGate()` mirrors the write site's `isAvailable('embedding')` gate (null when embedding is unavailable). A DEFAULT cap is dropped for an unpriced route (warn and run). When the operator SET `cycle.extract_atoms.budget_usd` (`explicitBudget`), an unpriced chat model or embed route yields `refusal` (the shared `no_pricing` guidance). `settleExtractAtomsCostGate` acts before any work item: it warns on a dropped cap; on a refusal it returns the phase's `warn` result (`details.reason: 'no_pricing'`, `details.no_pricing`, no model call), records the guidance at `cycle.extract_atoms.no_pricing.<source>` and upserts the rollup as an expected limit, not a halt; any run past the gate clears the source's record (dry runs record nothing). `readExtractAtomsNoPricing` + `withExtractAtomsNoPricing` overlay doctor's `extract_health` (wired in `doctor/checks/local-audits.ts`) with a `warn` naming the model and `register_command`. Pinned by `test/extract-atoms-embed-cost-gate.test.ts` and `test/extract-atoms-explicit-cap-no-pricing.test.ts`.
- `src/core/cycle/extract-atoms-drain.ts` — pure single-hold bounded drain for the silent lens-phase backlog. `runExtractAtomsDrain(deps, opts)` over injected deps (`withLock`, `runBatch`, `countRemaining`, `now`, optional `onBatch`) loops bounded batches under ONE lock hold, rediscovering eligibility each batch (idempotent NOT-EXISTS-on-`source_hash`; no cross-window cursor), until the backlog is empty or the window ends. Two stop signals: HARD (job `signal` + the lock's lease-loss signal + `deadlineAtMs`) reaches the chat call, the pacing pause and every backlog count; SOFT (hard + the window timer) is checked only between batches and items, so the item in flight finishes. Counts are cancellable and bounded (`countTimeoutMs`, capped by the remaining deadline). `stopped` is a `DrainStop` (`drained|window|deadline|lock_lost|aborted|no_progress|max_batches|provider_failure`); a hard stop skips `onBatch` and the recount and reports the last count as `remaining`, and the lease loss `withRefreshingLock` rethrows becomes `lock_lost` with the partial counters. Backs `gbrain dream --phase extract_atoms --drain` under the SAME `cycleLockIdFor(sourceId)` the routine cycle takes (a concurrent tick defers with `cycle_already_running`). `runExtractAtomsDrainForSource(engine, {sourceId, windowSeconds, brainDir?, maxBatches?, onBatch?, signal?, deadlineAtMs?})` owns the lock+batch+count wiring for all three callers — `dream --drain`, the `extract-atoms-drain` Minion handler, autopilot auto-drain. `sourceId: undefined` → legacy `gbrain-cycle` lock + `'default'`; a real id → `gbrain-cycle:<id>`. `LockUnavailableError` propagates. One `runExtractAtomsDrainForSource` call is one drain attempt: its batches share one `BudgetTracker` (the per-run `cycle.extract_atoms.budget_usd` cap is the attempt's cap) and one `MaintenanceWriteWait` (`persistence/maintenance-wait.ts`, bounded by `deadlineAtMs`). `structuralAtomRefusal` maps an `owner_unavailable`/`permission_denied` refusal from the atom session preflight to `STRUCTURAL_REFUSAL_PREFIX` text; the `extract-atoms-drain` Minion handler (`src/core/minions/handlers/extract-atoms-drain.ts`) throws it as `UnrecoverableError`, so the job dead-letters once with no model call and the auto-drain cap does not count it. `last_error` and the typed failure records pass through `sanitizeFailureText` (secret/DSN redaction, bounded). `formatDrainProviderFailure(result, {final?})` renders the handler's `provider_failure` throw; the handler throws `UnrecoverableError` on `deadline` or any failure at/past `deadlineAtMs`, the job's abort reason on `aborted`, and a retryable error on `lock_lost`. Tests: `test/extract-atoms-drain*.test.ts`.
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 47c482dc16..9911b2dce1 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -63,7 +63,7 @@ of making a duplicate.
| unknown option (repair) | `invalid_params` | `gbrain repair` refuses any option it does not list, so a mistyped flag or `--max-usd` never runs a repair silently without it. | Fix the option (`gbrain repair --help`). To cap paid repair work, run `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. |
| <a id="colon_slug_windows_write_through"></a>`colon_slug_windows_write_through` | `colon_slug_windows_write_through` | A page slug such as `calendar:abc` is valid, but its canonical file name would contain `:`, which Windows cannot store (it names an alternate data stream). On Windows, a write that would publish that file is refused before admission, and `gbrain sync` skips each such file with this reason instead of failing the run. Database-only writes of the same slug (no repo configured, `sync.write_through` off, an unbound source, or a [read-only mirror](multi-source-brains.md#read-only-mirror-sources) source and pages created while it was one) still succeed, and macOS and Linux are unchanged. | Use a slug without `:` (the suggestion names one), or write the page from a macOS or Linux host that owns the source. For a skipped sync file, rename it without `:` on a macOS or Linux checkout, commit, then run `gbrain sync --source <source> --no-pull` on the Windows host. |
| <a id="embedding_auth_failed"></a>`embedding_auth_failed` | `embedding_auth_failed` | The embedding provider rejected the configured key (HTTP 401 or 403). Printed once per process on stderr, naming the key source in effect: an environment variable (for example `OPENAI_API_KEY`, which wins over the config key) or the config key in `~/.gbrain/config.json`. No key or part of one is printed. | Environment key in effect but the config key is right: remove the variable from the environment of the process that reported it (shell profile, `~/.gbrain/.env`, or a daemon's service definition) and restart that process. Environment key intended: replace it with a valid key, restart, and run `gbrain config unset openai_api_key` (or the matching key). Config key in effect: `gbrain config set openai_api_key <valid key>`. Then `gbrain embed --stale` embeds what was saved meanwhile. `gbrain doctor` (`embedding_key_source`) shows the key source in doctor's own environment. |
-| <a id="no_pricing"></a>`no_pricing` | `no_pricing` | A cost cap you set (`--max-cost`, `--max-usd`, `--max-cost-usd`, or an explicit cap in config) cannot be enforced, because gbrain has no price for the model the run was about to call. The run stops before that call. Under a default cap an unpriced model warns and runs instead. The message names the model, provider and kind, and JSON output carries the same guidance as fields: `code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope` and `docs`. | Look up the provider's current price for the model, for example by searching the web for its pricing page. A chat model needs USD per 1M input tokens and USD per 1M output tokens; an embedding or reranker model needs USD per 1M tokens. On the brain host, run `gbrain pricing set <model> --input <usd> --output <usd> --source <pricing-page-url>` (or `--rate <usd>`), then retry. An agent connected over MCP cannot register prices: give the command to the brain's operator. See [registering a model price](../operations/spend-controls.md#registering-a-model-price). |
+| <a id="no_pricing"></a>`no_pricing` | `no_pricing` | A cost cap you set (`--max-cost`, `--max-usd`, `--max-cost-usd`, or an explicit cap in config such as `cycle.extract_atoms.budget_usd`) cannot be enforced, because gbrain has no price for the model the run was about to call. The run stops before that call. Under a default cap an unpriced model warns and runs instead. The message names the model, provider and kind, and JSON output carries the same guidance as fields: `code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope` and `docs`. | Look up the provider's current price for the model, for example by searching the web for its pricing page. A chat model needs USD per 1M input tokens and USD per 1M output tokens; an embedding or reranker model needs USD per 1M tokens. On the brain host, run `gbrain pricing set <model> --input <usd> --output <usd> --source <pricing-page-url>` (or `--rate <usd>`), then retry. An agent connected over MCP cannot register prices: give the command to the brain's operator. See [registering a model price](../operations/spend-controls.md#registering-a-model-price). |
### Other error codes
diff --git a/docs/operations/spend-controls.md b/docs/operations/spend-controls.md
index a3705cfd1c..694f066882 100644
--- a/docs/operations/spend-controls.md
+++ b/docs/operations/spend-controls.md
@@ -132,8 +132,15 @@ uses one slot per attempt. A job refused before any model call (no active
canonical owner on this host, untrusted caller) dead-letters once with
`structural_refusal:` and uses no slot; autopilot also skips a source whose
writer would refuse, and logs why. Checkout-backed and connector sources take
-turns for the daily slots. With a model the tracker cannot price, the dollar
-limit is not enforced (see above); only the attempt count bounds the drain.
+turns for the daily slots. With a model the tracker cannot price (the
+extraction chat model or the embedding route), the default dollar limit is not
+enforced and the phase warns and runs; only the attempt count bounds the drain.
+When you set `cycle.extract_atoms.budget_usd` yourself, an unpriced model
+instead stops the run before any model call: the phase reports `warn` with
+`details.no_pricing` (model, provider, kind, units, `register_command`), the
+stop counts as an expected limit rather than a halt in `extract_health`, and
+`gbrain doctor` names the command until you register the price with
+`gbrain pricing set` (see [registering a model price](#registering-a-model-price)).
Connector pages are opt-in. Gmail threads (`email`) and Calendar events
(`meeting`) from a Google or GitHub connector source are skipped by atom
diff --git a/llms-full.txt b/llms-full.txt
index 2aa46f17d5..fba6447bd0 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -9665,7 +9665,7 @@ of making a duplicate.
| unknown option (repair) | `invalid_params` | `gbrain repair` refuses any option it does not list, so a mistyped flag or `--max-usd` never runs a repair silently without it. | Fix the option (`gbrain repair --help`). To cap paid repair work, run `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. |
| <a id="colon_slug_windows_write_through"></a>`colon_slug_windows_write_through` | `colon_slug_windows_write_through` | A page slug such as `calendar:abc` is valid, but its canonical file name would contain `:`, which Windows cannot store (it names an alternate data stream). On Windows, a write that would publish that file is refused before admission, and `gbrain sync` skips each such file with this reason instead of failing the run. Database-only writes of the same slug (no repo configured, `sync.write_through` off, an unbound source, or a [read-only mirror](multi-source-brains.md#read-only-mirror-sources) source and pages created while it was one) still succeed, and macOS and Linux are unchanged. | Use a slug without `:` (the suggestion names one), or write the page from a macOS or Linux host that owns the source. For a skipped sync file, rename it without `:` on a macOS or Linux checkout, commit, then run `gbrain sync --source <source> --no-pull` on the Windows host. |
| <a id="embedding_auth_failed"></a>`embedding_auth_failed` | `embedding_auth_failed` | The embedding provider rejected the configured key (HTTP 401 or 403). Printed once per process on stderr, naming the key source in effect: an environment variable (for example `OPENAI_API_KEY`, which wins over the config key) or the config key in `~/.gbrain/config.json`. No key or part of one is printed. | Environment key in effect but the config key is right: remove the variable from the environment of the process that reported it (shell profile, `~/.gbrain/.env`, or a daemon's service definition) and restart that process. Environment key intended: replace it with a valid key, restart, and run `gbrain config unset openai_api_key` (or the matching key). Config key in effect: `gbrain config set openai_api_key <valid key>`. Then `gbrain embed --stale` embeds what was saved meanwhile. `gbrain doctor` (`embedding_key_source`) shows the key source in doctor's own environment. |
-| <a id="no_pricing"></a>`no_pricing` | `no_pricing` | A cost cap you set (`--max-cost`, `--max-usd`, `--max-cost-usd`, or an explicit cap in config) cannot be enforced, because gbrain has no price for the model the run was about to call. The run stops before that call. Under a default cap an unpriced model warns and runs instead. The message names the model, provider and kind, and JSON output carries the same guidance as fields: `code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope` and `docs`. | Look up the provider's current price for the model, for example by searching the web for its pricing page. A chat model needs USD per 1M input tokens and USD per 1M output tokens; an embedding or reranker model needs USD per 1M tokens. On the brain host, run `gbrain pricing set <model> --input <usd> --output <usd> --source <pricing-page-url>` (or `--rate <usd>`), then retry. An agent connected over MCP cannot register prices: give the command to the brain's operator. See [registering a model price](../operations/spend-controls.md#registering-a-model-price). |
+| <a id="no_pricing"></a>`no_pricing` | `no_pricing` | A cost cap you set (`--max-cost`, `--max-usd`, `--max-cost-usd`, or an explicit cap in config such as `cycle.extract_atoms.budget_usd`) cannot be enforced, because gbrain has no price for the model the run was about to call. The run stops before that call. Under a default cap an unpriced model warns and runs instead. The message names the model, provider and kind, and JSON output carries the same guidance as fields: `code`, `model`, `provider`, `kind`, `units`, `lookup`, `register_command`, `register_scope` and `docs`. | Look up the provider's current price for the model, for example by searching the web for its pricing page. A chat model needs USD per 1M input tokens and USD per 1M output tokens; an embedding or reranker model needs USD per 1M tokens. On the brain host, run `gbrain pricing set <model> --input <usd> --output <usd> --source <pricing-page-url>` (or `--rate <usd>`), then retry. An agent connected over MCP cannot register prices: give the command to the brain's operator. See [registering a model price](../operations/spend-controls.md#registering-a-model-price). |
### Other error codes
diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsv
index 16729608c9..cd562bf9eb 100644
--- a/scripts/function-size-baseline.tsv
+++ b/scripts/function-size-baseline.tsv
@@ -34,7 +34,7 @@ src/core/config.ts loadConfigWithEngine 362 seed: W5 baseline, refactor wave 1 (
src/core/context-engine.ts createGBrainContextEngine 519 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/context/retrieval-reflex.ts resolveEntitiesToPointers 355 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/cycle.ts runCycle 1236 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 #5809: extract_atoms phase gets a real abort signal; +2 #5809: cycle_already_running names the lock holder
-src/core/cycle/extract-atoms.ts runPhaseExtractAtoms 823 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +12 #5809/#5832: hard/soft stop checks, chat-call signal, abortable pacing, no post-stop writes; +1 #5856: one BudgetTracker per drain attempt (reuse the attempt's tracker)
+src/core/cycle/extract-atoms.ts runPhaseExtractAtoms 787 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +12 #5809/#5832: hard/soft stop checks, chat-call signal, abortable pacing, no post-stop writes; +1 #5856: one BudgetTracker per drain attempt (reuse the attempt's tracker)
src/core/cycle/extract-atoms.ts runPhaseExtractAtoms>withBudgetTracker(#1) 316 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +11 #5809/#5832: per-item and pre-commit abort checks, chat-call signal, abortable pacing, catch-side stop
src/core/cycle/extract-facts.ts runExtractFacts 505 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
src/core/cycle/grade-takes.ts GradeTakesPhase.process 402 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index de68b15f7c..760aae8a4b 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -15,7 +15,7 @@ src/core/ai/gateway.ts 4393 ratchet +7 fix wave 5 (#5137): provider-key redactor
src/commands/sync.ts 473 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals)
src/core/cycle.ts 3192 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set
src/core/cycle/synthesize.ts 3297 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts)
-src/core/cycle/extract-atoms.ts 1844 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts)
+src/core/cycle/extract-atoms.ts 1808 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts)
src/core/engine.ts 2678 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse)
src/core/import-file.ts 2230 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode)
src/core/migrate.ts 599 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3)
diff --git a/src/commands/doctor/checks/local-audits.ts b/src/commands/doctor/checks/local-audits.ts
index 3aa60fa985..a909f3b539 100644
--- a/src/commands/doctor/checks/local-audits.ts
+++ b/src/commands/doctor/checks/local-audits.ts
@@ -7,6 +7,7 @@
* src/commands/doctor/registry.ts and src/core/doctor-categories.ts.
*/
+import { applyExtractAtomsNoPricing, readExtractAtomsNoPricing } from '../../../core/cycle/extract-atoms-cost-gate.ts';
import { join } from 'path';
import { gbrainPath } from '../../../core/config.ts';
import { multiSourceDriftGitRootSkipNote, multiSourceDriftAdvice } from '../schema-pack-checks.ts';
@@ -190,7 +191,10 @@ async function runExtractionBacklogs(ctx: DoctorContext): Promise<Check[]> {
// operator should know the DB cache is degraded). See plan A5 + D-EXTRACT-32.
if (engine) {
try {
+ // An explicit extract_atoms cap that refused an unpriced model is an
+ // expected limit in the rollup, not a halt; the overlay names the fix.
const check = await computeExtractHealthCheck(engine);
+ applyExtractAtomsNoPricing(check, await readExtractAtomsNoPricing(engine).catch(() => []));
checks.push(check);
} catch {
// Best-effort; rollup-table missing on pre-v106 brains is normal
diff --git a/src/core/cycle/extract-atoms-cost-gate.ts b/src/core/cycle/extract-atoms-cost-gate.ts
index e407071ecc..8bb7d50323 100644
--- a/src/core/cycle/extract-atoms-cost-gate.ts
+++ b/src/core/cycle/extract-atoms-cost-gate.ts
@@ -9,6 +9,10 @@
import { isAvailable, getEmbeddingModel } from '../ai/gateway.ts';
import { isModelPriceable, type PricingOverrides } from '../budget/budget-tracker.ts';
+import { noPricingGuidance, noPricingMessage, pricingSetCommand, type NoPricingGuidance } from '../budget/no-pricing.ts';
+import type { BrainEngine } from '../engine.ts';
+import type { PhaseResult } from '../cycle.ts';
+import { classifyRunStop, upsertExtractRollup } from '../extract/rollup-writer.ts';
/**
* Cost-gate decision for the extract_atoms BudgetTracker.
@@ -16,21 +20,16 @@ import { isModelPriceable, type PricingOverrides } from '../budget/budget-tracke
* `enforceCap: true` → construct the tracker with `maxCostUsd`. `false` → run
* uncapped (the tracker then warns once on unpriced models instead of throwing)
* and `unpricedModel`/`unpricedKind` name the call that made the cap
- * unenforceable. Pure: no config or gateway access, so it is unit-testable and
- * the call site stays a one-liner.
+ * unenforceable. `refusal` → an explicit budget met an unpriced route: the run
+ * makes no model call and reports the guidance. Pure: no config or gateway
+ * access, so it is unit-testable.
*/
export interface ExtractAtomsCostGate {
enforceCap: boolean;
unpricedModel?: string;
unpricedKind?: 'chat' | 'embed';
- /**
- * Set when an EXPLICIT operator budget kept the cap on over an unpriced
- * embed route: that route bills at $0 under this tracker (one stderr
- * warning at the call site). `pricingOverrides` is then the caller's map
- * plus the $0 row — hand it to the tracker in place of the original.
- */
- zeroPricedEmbedModel?: string;
- pricingOverrides?: PricingOverrides;
+ /** Explicit budget + unpriced chat or embed route: refuse, with the no_pricing guidance. */
+ refusal?: NoPricingGuidance;
}
/**
@@ -40,11 +39,11 @@ export interface ExtractAtomsCostGate {
* which case the import runs with `noEmbed` and nothing embeds). Operator
* `pricing.overrides` are consulted first, matching BudgetTracker.reserve().
*
- * `explicitBudget` = the operator SET `cycle.extract_atoms.budget_usd`. Only
- * a *default* cap may be dropped for an unpriced embed route; a ceiling the
- * operator asked for stays enforced and the embed route is priced at $0
- * instead (Codex P1). An unpriced CHAT model still drops the cap either way —
- * it is the billable call the cap exists for, and $0 would enforce a fiction.
+ * `explicitBudget` = the operator SET `cycle.extract_atoms.budget_usd`. A
+ * default cap is dropped for an unpriced route (warn and run, so a new model
+ * still works). A cap the operator set is a spending limit: the run is
+ * refused with guidance to look the price up and register it, for the chat
+ * model and the embed route alike.
*/
export function resolveExtractAtomsCostGate(
extractModel: string,
@@ -52,22 +51,96 @@ export function resolveExtractAtomsCostGate(
overrides?: PricingOverrides,
opts: { explicitBudget?: boolean } = {},
): ExtractAtomsCostGate {
- if (!isModelPriceable(extractModel, 'chat', overrides)) {
- return { enforceCap: false, unpricedModel: extractModel, unpricedKind: 'chat' };
+ const unpriced: { model: string; kind: 'chat' | 'embed' } | null =
+ !isModelPriceable(extractModel, 'chat', overrides) ? { model: extractModel, kind: 'chat' }
+ : embedModel !== null && !isModelPriceable(embedModel, 'embed', overrides) ? { model: embedModel, kind: 'embed' }
+ : null;
+ if (!unpriced) return { enforceCap: true };
+ if (opts.explicitBudget) {
+ return { enforceCap: true, unpricedModel: unpriced.model, unpricedKind: unpriced.kind, refusal: noPricingGuidance(unpriced.model, unpriced.kind) };
}
- if (embedModel !== null && !isModelPriceable(embedModel, 'embed', overrides)) {
- if (opts.explicitBudget) {
- // Same key normalization as parsePricingOverrides / overrideFor.
- const key = embedModel.trim().toLowerCase();
- return {
- enforceCap: true,
- zeroPricedEmbedModel: embedModel,
- pricingOverrides: { ...overrides, [key]: { input: 0, output: 0 } },
- };
+ return { enforceCap: false, unpricedModel: unpriced.model, unpricedKind: unpriced.kind };
+}
+
+/** Config key holding the last refusal for a source; doctor's extract_health reads every one. */
+export const ATOMS_NO_PRICING_KEY_PREFIX = 'cycle.extract_atoms.no_pricing.';
+
+/**
+ * Act on the gate before any work item. Default-cap drop: warn and return
+ * null (the run proceeds uncapped). Refusal: record it for doctor, count the
+ * run as an expected limit (not a halt), and return the `warn` phase result
+ * the caller returns as-is — no model call. Any run past the gate clears the
+ * source's recorded refusal. A dry run records nothing.
+ */
+export async function settleExtractAtomsCostGate(
+ engine: BrainEngine,
+ sourceId: string,
+ gate: ExtractAtomsCostGate,
+ run: { budgetCap: number; extractModel: string; dryRun: boolean },
+): Promise<PhaseResult | null> {
+ const key = `${ATOMS_NO_PRICING_KEY_PREFIX}${sourceId}`;
+ if (!gate.refusal) {
+ if (!gate.enforceCap) {
+ console.error(
+ `[extract_atoms] ${gate.unpricedKind} model "${gate.unpricedModel}" is not in the pricing maps; ` +
+ `running without a cost gate (a default cap cannot be enforced on an unpriced model). Look up its per-token price and register it to restore the cap: ` +
+ `${pricingSetCommand(gate.unpricedModel!, gate.unpricedKind ?? 'chat')} (--rate 0 for local inference).`,
+ );
}
- return { enforceCap: false, unpricedModel: embedModel, unpricedKind: 'embed' };
+ if (!run.dryRun) await engine.unsetConfig(key).catch(() => 0);
+ return null;
+ }
+ const message = noPricingMessage(gate.refusal, { capUsd: run.budgetCap });
+ console.error(`[extract_atoms] ${message}`);
+ if (!run.dryRun) {
+ await engine.setConfig(key, JSON.stringify({ ...gate.refusal, at: new Date().toISOString() })).catch(() => {});
+ await upsertExtractRollup(engine, { kind: 'atoms', source_id: sourceId, cost_delta: 0, ...classifyRunStop({ budget_exhausted: true }) });
+ }
+ return {
+ phase: 'extract_atoms',
+ status: 'warn',
+ duration_ms: 0,
+ summary: `extract_atoms: ${message}`,
+ details: {
+ reason: 'no_pricing',
+ source_id: sourceId,
+ no_pricing: gate.refusal,
+ atoms_extracted: 0,
+ budget_usd: run.budgetCap,
+ budget_exhausted: true,
+ model: run.extractModel,
+ dry_run: run.dryRun,
+ },
+ };
+}
+
+/**
+ * Doctor's extract_health overlay, applied in place: a recorded refusal turns
+ * the check into a warning that names the model, what to look up and the
+ * registration command.
+ */
+export function applyExtractAtomsNoPricing(
+ check: { status: 'ok' | 'warn' | 'fail'; message: string; details?: Record<string, unknown> },
+ refusals: Array<NoPricingGuidance & { source_id: string }>,
+): void {
+ if (refusals.length === 0) return;
+ const first = refusals[0]!;
+ if (check.status !== 'fail') check.status = 'warn';
+ check.message = `extract_atoms refused under its cost cap in ${refusals.length} source(s): no price for ${first.model}. ` +
+ `${first.lookup} Then run on the brain host: ${first.register_command}; ${check.message}`;
+ check.details = { ...(check.details ?? {}), no_pricing: refusals };
+}
+
+/** Every source's recorded extract_atoms refusal, for doctor's extract_health. */
+export async function readExtractAtomsNoPricing(engine: BrainEngine): Promise<Array<NoPricingGuidance & { source_id: string }>> {
+ const out: Array<NoPricingGuidance & { source_id: string }> = [];
+ for (const key of await engine.listConfigKeys(ATOMS_NO_PRICING_KEY_PREFIX)) {
+ try {
+ const value = JSON.parse((await engine.getConfig(key)) ?? '');
+ if (value && value.code === 'no_pricing') out.push({ ...value, source_id: key.slice(ATOMS_NO_PRICING_KEY_PREFIX.length) });
+ } catch { /* unreadable record: skip */ }
}
- return { enforceCap: true };
+ return out;
}
/**
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts
index 4db5e241c7..17deeba6a0 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.ts
@@ -71,10 +71,9 @@ import { truncateUtf8 } from '../text-safe.ts';
import { corpusTextForExtraction } from '../context/corpus-segments.ts';
import { claudeCliSelfSessionIds } from '../ai/providers/claude-cli-scratch.ts';
import { BudgetExhausted, BudgetTracker, loadPricingOverrides } from '../budget/budget-tracker.ts';
-import { pricingSetCommand } from '../budget/no-pricing.ts';
import type { MaintenanceWriteWait } from '../persistence/maintenance-wait.ts';
import { connectorAtomExclusionSql } from './connector-atoms.ts';
-import { resolveExtractAtomsCostGate, resolveEmbedModelForCostGate } from './extract-atoms-cost-gate.ts';
+import { resolveExtractAtomsCostGate, resolveEmbedModelForCostGate, settleExtractAtomsCostGate } from './extract-atoms-cost-gate.ts';
import { writeReceipt } from '../extract/receipt-writer.ts';
import { classifyRunStop, upsertExtractRollup } from '../extract/rollup-writer.ts';
import { abortableSleep } from '../retry.ts';
@@ -935,53 +934,18 @@ export async function runPhaseExtractAtoms(
// Keep safe defaults on any config-read failure: key-aware utility-tier
// model, $0.30 cap, default input cap (max_input_chars).
}
- // A cost cap is only meaningful when the tracker can price EVERY call made
- // under it. BudgetTracker.reserve() hard-fails with
- // BudgetExhausted(reason:'no_pricing') when a model is absent from the pricing
- // maps AND a cap is set; with no cap it warns once and proceeds. Because this
- // phase always set a cap, every non-Anthropic chat model tripped that
- // hard-fail on the first item, latched `budgetExhausted`, and skipped the
- // entire workload while reporting ok.
- //
- // The chat model is not the only call under this tracker: the atom write
- // site below goes through importFromContent, which chunks AND embeds inside
- // the same withBudgetTracker scope. So the embedding model must be priceable
- // too. Pre-fix, a $0 local chat model (ollama/llama-server) kept the cap on
- // while an unpriced embedding route (e.g. `litellm:*`, which is deliberately
- // NOT assumed free because a proxy can front a paid provider) threw
- // no_pricing on the FIRST atom import — 0 atoms, `budget_exhausted: true`,
- // $0 spent, on every run. The operator escape hatch the error message
- // advertises (`pricing.overrides`, #4312) was also never loaded here, unlike
- // enrich / ingest-facts / extract-conversation-facts.
- //
- // Only a DEFAULT cap may be dropped that way. When the operator set
- // `cycle.extract_atoms.budget_usd` they asked for a ceiling; the gate keeps
- // it and bills the unpriced embed route at $0 (warned once, below).
+ // A cap is enforceable only when the tracker can price every call under it:
+ // the extraction chat model AND the embed route importFromContent calls.
+ // A default cap is dropped for an unpriced route (warn and run); a cap the
+ // operator set refuses the run with no_pricing guidance (cost-gate module).
const pricingOverrides = await loadPricingOverrides(engine);
- const costGate = resolveExtractAtomsCostGate(
- extractModel,
- resolveEmbedModelForCostGate(),
- pricingOverrides,
- { explicitBudget },
- );
- if (!costGate.enforceCap) {
- console.error(
- `[extract_atoms] ${costGate.unpricedKind} model "${costGate.unpricedModel}" is not in the pricing maps; ` +
- `running without a cost gate (a cap cannot be enforced on an unpriced model). ` +
- `Look up its per-token price and register it to restore the cap: ` +
- `${pricingSetCommand(costGate.unpricedModel!, costGate.unpricedKind === 'embed' ? 'embed' : 'chat')} (--rate 0 for local inference).`,
- );
- } else if (costGate.zeroPricedEmbedModel) {
- console.error(
- `[extract_atoms] embed model "${costGate.zeroPricedEmbedModel}" is not in the pricing maps; ` +
- `cycle.extract_atoms.budget_usd is set, so the $${budgetCap.toFixed(2)} cap stays enforced and embeds bill at $0 under it. ` +
- `Look up its real price and register it to meter them: ${pricingSetCommand(costGate.zeroPricedEmbedModel, 'embed')}.`,
- );
- }
+ const costGate = resolveExtractAtomsCostGate(extractModel, resolveEmbedModelForCostGate(), pricingOverrides, { explicitBudget });
+ const refused = await settleExtractAtomsCostGate(engine, sourceId, costGate, { budgetCap, extractModel, dryRun: opts.dryRun ?? false });
+ if (refused) return refused;
const budgetTracker = opts.attempt?.budgetTracker ?? new BudgetTracker({
maxCostUsd: costGate.enforceCap ? budgetCap : undefined,
label: 'cycle.extract_atoms',
- pricingOverrides: costGate.pricingOverrides ?? pricingOverrides,
+ pricingOverrides,
});
if (opts.attempt) opts.attempt.budgetTracker = budgetTracker;
diff --git a/test/extract-atoms-embed-cost-gate.test.ts b/test/extract-atoms-embed-cost-gate.test.ts
index 411a475804..d0c77c68eb 100644
--- a/test/extract-atoms-embed-cost-gate.test.ts
+++ b/test/extract-atoms-embed-cost-gate.test.ts
@@ -75,34 +75,35 @@ describe('resolveExtractAtomsCostGate', () => {
});
// An operator who SET `cycle.extract_atoms.budget_usd` asked for a ceiling.
- // Dropping the cap because the embed route is unpriced silently turns that
- // ceiling off (Codex P1); the cap stays and the unpriced embed bills at $0.
- test('an explicit operator budget keeps the cap on over an unpriced embed route, priced at $0', () => {
- expect(resolveExtractAtomsCostGate(FREE_CHAT, UNPRICED_EMBED, undefined, { explicitBudget: true })).toEqual({
- enforceCap: true,
- zeroPricedEmbedModel: UNPRICED_EMBED,
- pricingOverrides: { [UNPRICED_EMBED.toLowerCase()]: { input: 0, output: 0 } },
- });
+ // This used to keep the cap and bill the unpriced embed route at $0 (Codex
+ // P1). Garry's explicit-cap rule (2026-10-02) supersedes that: a cap the user
+ // set refuses an unpriced route and tells the agent to look the price up and
+ // register it, rather than assume $0.
+ test('an explicit operator budget refuses an unpriced embed route with no_pricing guidance', () => {
+ const gate = resolveExtractAtomsCostGate(FREE_CHAT, UNPRICED_EMBED, undefined, { explicitBudget: true });
+ expect(gate).toMatchObject({ enforceCap: true, unpricedModel: UNPRICED_EMBED, unpricedKind: 'embed' });
+ expect(gate.refusal).toMatchObject({ code: 'no_pricing', model: UNPRICED_EMBED, kind: 'embed', units: ['usd_per_1m_tokens'] });
+ expect(gate.refusal!.register_command).toStartWith(`gbrain pricing set ${UNPRICED_EMBED} --rate`);
});
- test('the $0 embed row merges into existing operator overrides without clobbering them', () => {
+ test('an explicit budget never invents a $0 embed row; other overrides are left as they were', () => {
+ // Superseded by the explicit-cap rule: the gate used to merge a $0 row for
+ // the embed route into the operator's overrides. It now returns no
+ // overrides at all and refuses, so the operator map is never rewritten.
const overrides = parsePricingOverrides(JSON.stringify({ 'litellm:gpt-4o': { input: 2.5, output: 10 } }))!;
const gate = resolveExtractAtomsCostGate(FREE_CHAT, UNPRICED_EMBED, overrides, { explicitBudget: true });
- expect(gate.enforceCap).toBe(true);
- expect(gate.pricingOverrides).toEqual({
- 'litellm:gpt-4o': { input: 2.5, output: 10 },
- [UNPRICED_EMBED.toLowerCase()]: { input: 0, output: 0 },
- });
+ expect(gate.refusal?.model).toBe(UNPRICED_EMBED);
+ expect('pricingOverrides' in gate).toBe(false);
+ expect(overrides).toEqual({ 'litellm:gpt-4o': { input: 2.5, output: 10 } });
});
- test('an explicit budget never zero-prices an unpriced CHAT model — the cap still drops', () => {
- // The chat model is the billable call the cap exists for; assuming $0 for
- // it would enforce a fiction. Only the embed route gets the $0 treatment.
- expect(resolveExtractAtomsCostGate('groq:llama-3.3-70b', UNPRICED_EMBED, undefined, { explicitBudget: true })).toEqual({
- enforceCap: false,
- unpricedModel: 'groq:llama-3.3-70b',
- unpricedKind: 'chat',
- });
+ test('an explicit budget refuses an unpriced CHAT model instead of dropping the cap', () => {
+ // Used to drop the cap and run uncapped. Superseded by Garry's explicit-cap
+ // rule (2026-10-02): a spending cap you set blocks an unpriced model and
+ // tells the agent to look up the price and register it.
+ const gate = resolveExtractAtomsCostGate('groq:llama-3.3-70b', UNPRICED_EMBED, undefined, { explicitBudget: true });
+ expect(gate).toMatchObject({ enforceCap: true, unpricedModel: 'groq:llama-3.3-70b', unpricedKind: 'chat' });
+ expect(gate.refusal).toMatchObject({ code: 'no_pricing', model: 'groq:llama-3.3-70b', provider: 'groq', kind: 'chat' });
});
test('without an explicit budget the unpriced embed still drops the (default) cap', () => {
@@ -170,7 +171,11 @@ describe('extract_atoms with a $0 chat model and an unpriced embedding model (PG
expect(result.details?.transcripts_skipped_budget).toBe(0);
}, 60000);
- test('an explicit cycle.extract_atoms.budget_usd keeps the cap enforced over the unpriced embed (Codex P1)', async () => {
+ // Used to run with the embed route billed at $0 (Codex P1). Superseded by
+ // Garry's explicit-cap rule (2026-10-02): the run is refused, makes no model
+ // call, and reports the no_pricing guidance.
+ test('an explicit cycle.extract_atoms.budget_usd refuses the unpriced embed route: no model call, guidance in details', async () => {
+ let chatCalls = 0;
await engine.setConfig('cycle.extract_atoms.budget_usd', '0.05');
const stderr: string[] = [];
const savedError = console.error;
@@ -180,21 +185,21 @@ describe('extract_atoms with a $0 chat model and an unpriced embedding model (PG
result = await runPhaseExtractAtoms(engine, {
_transcripts: [{ filePath: '/fake/meeting-c.txt', content: 'transcript content c', contentHash: 'c1b2c3d4e5f60718' }],
_pages: [],
- _chat: chat,
+ _chat: async (o) => { chatCalls++; return chat(o); },
});
} finally {
console.error = savedError;
}
- expect(result.status).toBe('ok');
- expect(result.details?.atoms_extracted).toBe(1);
- expect(result.details?.budget_exhausted).toBe(false);
+ expect(result.status).toBe('warn');
+ expect(chatCalls).toBe(0);
+ expect(result.details?.atoms_extracted).toBe(0);
expect(result.details?.budget_usd).toBe(0.05);
+ expect(result.details?.no_pricing).toMatchObject({ model: UNPRICED_EMBED, kind: 'embed' });
const joined = stderr.join('\n');
// The cap was NOT dropped — the operator asked for one.
expect(joined).not.toContain('running without a cost gate');
- // ...and the run says so, naming the embed model it bills at $0.
- expect(joined).toContain(UNPRICED_EMBED);
- expect(joined).toContain('$0');
+ // ...and the run names the embed model and the registration command.
+ expect(joined).toContain(`gbrain pricing set ${UNPRICED_EMBED} --rate`);
}, 60000);
test('with a $0 pricing override for the embed model the cap stays on and the run still extracts', async () => {
diff --git a/test/extract-atoms-explicit-cap-no-pricing.test.ts b/test/extract-atoms-explicit-cap-no-pricing.test.ts
new file mode 100644
index 0000000000..f440be0282
--- /dev/null
+++ b/test/extract-atoms-explicit-cap-no-pricing.test.ts
@@ -0,0 +1,187 @@
+/**
+ * extract_atoms under an explicit `cycle.extract_atoms.budget_usd` with a
+ * model gbrain has no price for: the run is refused (status `warn`, no model
+ * call), carries the shared no_pricing guidance in its details, records the
+ * stop as an expected limit (not a halt) for extract_health, and doctor's
+ * extract_health names the registration command until the price is
+ * registered. A default cap still warns and runs (#5825).
+ *
+ * Hermetic: in-memory PGLite, chat stubbed through the `_chat` seam, embed
+ * transport stubbed. No network or API keys.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runPhaseExtractAtoms } from '../src/core/cycle/extract-atoms.ts';
+import { applyExtractAtomsNoPricing, readExtractAtomsNoPricing } from '../src/core/cycle/extract-atoms-cost-gate.ts';
+import { computeExtractHealthCheck } from '../src/commands/doctor.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import type { ChatOpts, ChatResult } from '../src/core/ai/gateway.ts';
+import { _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';
+import { runPricing } from '../src/commands/pricing.ts';
+
+const UNPRICED_CHAT = 'litellm:custom-chat';
+const FREE_CHAT = 'llama-server:local-27b';
+const PRICED_EMBED = 'openai:text-embedding-3-large';
+const UNPRICED_EMBED = 'litellm:nvidia/some-local-embedder';
+const DIMS = 1536;
+
+let engine: PGLiteEngine;
+let chatCalls = 0;
+let n = 0;
+
+function useEmbedModel(model: string): void {
+ resetGateway();
+ configureGateway({ embedding_model: model, embedding_dimensions: DIMS, env: { OPENAI_API_KEY: 'test' } });
+ __setEmbedTransportForTests((async (args: { values: string[] }) => ({
+ embeddings: args.values.map(() => Array.from({ length: DIMS }, () => 0.01)),
+ usage: { tokens: 10 * args.values.length },
+ })) as never);
+}
+
+async function chat(_o: ChatOpts): Promise<ChatResult> {
+ chatCalls++;
+ return {
+ text: `[{"title":"Example atom","atom_type":"insight","body":"An example rollout finished."}]`,
+ blocks: [{ type: 'text', text: '' }],
+ stopReason: 'end',
+ usage: { input_tokens: 500, output_tokens: 200, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: UNPRICED_CHAT,
+ providerId: 'litellm',
+ };
+}
+
+async function runOnce() {
+ n++;
+ const errors: string[] = [];
+ const saved = console.error;
+ console.error = (...a: unknown[]) => { errors.push(a.map(String).join(' ')); };
+ try {
+ const result = await runPhaseExtractAtoms(engine, {
+ _transcripts: [{ filePath: `/fake/meeting-${n}.txt`, content: `transcript content ${n}`, contentHash: `${n}`.padStart(16, '0') }],
+ _pages: [],
+ _chat: chat,
+ });
+ return { result, stderr: errors.join('\n') };
+ } finally {
+ console.error = saved;
+ }
+}
+
+async function rollup(): Promise<{ halt: number; expected: number; completed: number }> {
+ const [row] = await engine.executeRaw<{ halt_count: number; expected_limit_count: number; round_completed_count: number }>(
+ `SELECT COALESCE(SUM(halt_count),0) AS halt_count, COALESCE(SUM(expected_limit_count),0) AS expected_limit_count,
+ COALESCE(SUM(round_completed_count),0) AS round_completed_count
+ FROM extract_rollup_7d WHERE kind = 'atoms'`,
+ );
+ return { halt: Number(row!.halt_count), expected: Number(row!.expected_limit_count), completed: Number(row!.round_completed_count) };
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ await engine.disconnect();
+});
+
+afterEach(async () => {
+ chatCalls = 0;
+ await engine.unsetConfig('cycle.extract_atoms.budget_usd');
+ await engine.unsetConfig('pricing.overrides');
+ for (const key of await engine.listConfigKeys('cycle.extract_atoms.no_pricing.')) await engine.unsetConfig(key);
+ await engine.executeRaw(`DELETE FROM extract_rollup_7d`);
+});
+
+describe('explicit extract_atoms cap + unpriced model', () => {
+ test('an unpriced chat model is refused: warn, no model call, guidance in details, expected limit not halt', async () => {
+ useEmbedModel(PRICED_EMBED);
+ await engine.setConfig('models.dream.extract_atoms', UNPRICED_CHAT);
+ await engine.setConfig('cycle.extract_atoms.budget_usd', '0.5');
+
+ const { result, stderr } = await runOnce();
+ expect(result.status).toBe('warn');
+ expect(chatCalls).toBe(0);
+ const details = result.details as Record<string, any>;
+ expect(details.reason).toBe('no_pricing');
+ expect(details.atoms_extracted).toBe(0);
+ expect(details.no_pricing).toMatchObject({
+ code: 'no_pricing', model: UNPRICED_CHAT, provider: 'litellm', kind: 'chat',
+ units: ['usd_per_1m_input_tokens', 'usd_per_1m_output_tokens'], register_scope: 'local_cli',
+ docs: 'docs/guides/write-refusals.md#no_pricing',
+ });
+ expect(details.no_pricing.register_command).toStartWith(`gbrain pricing set ${UNPRICED_CHAT} --input`);
+ expect(result.summary).toContain('the $0.50 cost cap can\'t be enforced');
+ expect(result.summary).toContain(details.no_pricing.register_command);
+ expect(stderr).toContain(details.no_pricing.register_command);
+ expect(stderr).not.toContain('running without a cost gate');
+
+ expect(await rollup()).toEqual({ halt: 0, expected: 1, completed: 0 });
+
+ const records = await readExtractAtomsNoPricing(engine);
+ expect(records).toHaveLength(1);
+ expect(records[0]).toMatchObject({ source_id: 'default', model: UNPRICED_CHAT });
+ const doctor = await computeExtractHealthCheck(engine);
+ applyExtractAtomsNoPricing(doctor, records);
+ expect(doctor.status).toBe('warn');
+ expect(doctor.message).toContain(details.no_pricing.register_command);
+ expect((doctor.details as Record<string, unknown>).no_pricing).toEqual(records);
+ }, 60_000);
+
+ test('an unpriced embedding route is refused the same way instead of billing at $0', async () => {
+ useEmbedModel(UNPRICED_EMBED);
+ await engine.setConfig('models.dream.extract_atoms', FREE_CHAT);
+ await engine.setConfig('cycle.extract_atoms.budget_usd', '0.5');
+
+ const { result } = await runOnce();
+ expect(result.status).toBe('warn');
+ expect(chatCalls).toBe(0);
+ const details = result.details as Record<string, any>;
+ expect(details.atoms_extracted).toBe(0);
+ expect(details.no_pricing).toMatchObject({ code: 'no_pricing', model: UNPRICED_EMBED, kind: 'embed', units: ['usd_per_1m_tokens'] });
+ expect(details.no_pricing.register_command).toStartWith(`gbrain pricing set ${UNPRICED_EMBED} --rate`);
+ expect(await rollup()).toEqual({ halt: 0, expected: 1, completed: 0 });
+ }, 60_000);
+
+ test('after the price is registered the retried run extracts under the cap and the doctor warning clears', async () => {
+ useEmbedModel(PRICED_EMBED);
+ await engine.setConfig('models.dream.extract_atoms', UNPRICED_CHAT);
+ await engine.setConfig('cycle.extract_atoms.budget_usd', '0.5');
+ expect((await runOnce()).result.status).toBe('warn');
+ expect(await readExtractAtomsNoPricing(engine)).toHaveLength(1);
+
+ const saved = console.log;
+ console.log = () => {};
+ try {
+ await runPricing(engine, ['set', UNPRICED_CHAT, '--input', '1', '--output', '2']);
+ } finally {
+ console.log = saved;
+ _resetCliExitVerdictForTests();
+ }
+
+ const { result } = await runOnce();
+ expect(result.status).toBe('ok');
+ expect(chatCalls).toBe(1);
+ expect(result.details?.atoms_extracted).toBe(1);
+ expect(result.details?.budget_exhausted).toBe(false);
+ expect(await readExtractAtomsNoPricing(engine)).toEqual([]);
+ }, 60_000);
+});
+
+describe('default extract_atoms cap + unpriced model', () => {
+ test('warns and runs (#5825)', async () => {
+ useEmbedModel(PRICED_EMBED);
+ await engine.setConfig('models.dream.extract_atoms', UNPRICED_CHAT);
+
+ const { result, stderr } = await runOnce();
+ expect(result.status).toBe('ok');
+ expect(chatCalls).toBe(1);
+ expect(result.details?.atoms_extracted).toBe(1);
+ expect(stderr).toContain('running without a cost gate');
+ expect(stderr).toContain(`gbrain pricing set ${UNPRICED_CHAT} --input`);
+ expect(await readExtractAtomsNoPricing(engine)).toEqual([]);
+ }, 60_000);
+});