Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
docs(pricing): wave 9 lane A spend-controls, key files, release notes
time-attack4c7727d1cadd
diff --git a/docs/ai-providers/claude-cli.md b/docs/ai-providers/claude-cli.mdindex 6837729daa..d2bd245d0e 100644--- a/docs/ai-providers/claude-cli.md+++ b/docs/ai-providers/claude-cli.md@@ -135,7 +135,7 @@ above.| Multimodal | Not supported over the subprocess path. File/image message parts are rendered as a `[file <mediaType>]` text stub, not sent as actual content. || Prompt caching | The recipe declares `supports_prompt_cache: true`: Claude Code caches prompt prefixes itself on every `--print` run (Anthropic's Claude Code docs put `-p` runs in the main-conversation TTL bucket — one hour on a subscription, five minutes on an API key). gbrain cannot place `cache_control` breakpoints on this path — the adapter renders messages to stdin text and ignores `providerOptions` — so caching is automatic rather than gateway-driven, and `doctor`'s `subagent_capability` does not grade a claude-cli subagent tier `degraded:no_caching`. `cache_read_input_tokens` is surfaced as `usage.cachedInputTokens` (next row). || Usage / token counts | Reported `usage.input_tokens` / `usage.output_tokens` are read straight from the CLI's `--output-format json` envelope (`result.usage?.input_tokens` / `output_tokens`); gbrain does not independently count tokens for this path. The envelope's `cache_read_input_tokens` is surfaced as `usage.cachedInputTokens`, so cache reads are counted in gbrain's usage accounting; `cache_creation_input_tokens` is not surfaced (the AI SDK's usage shape has no corresponding field). |-| Cost figures | The recipe declares `cost_per_1m_input_usd: 3.0` / `cost_per_1m_output_usd: 15.0` — the same Sonnet-class figures the `anthropic` recipe declares (`price_last_verified: 2026-06-17`) — purely so gbrain's budget ledger has a number to attribute per call. Neither the recipe nor the adapter code checks what you're actually billed; treat these as the ledger's nominal per-call number, not a verified charge. The `--max-usd` / `--max-cost` budget gate does not read them either: it prices `claude-cli:<model>` at the nominal Anthropic rate for that model, and a short alias (`claude-cli:haiku`) prices identically to the dated id it resolves to; `pricing.overrides` forces $0 or a real rate for any `claude-cli:*` string. |+| Cost figures | The recipe declares `cost_per_1m_input_usd: 3.0` / `cost_per_1m_output_usd: 15.0` — the same Sonnet-class figures the `anthropic` recipe declares (`price_last_verified: 2026-06-17`) — purely so gbrain's budget ledger has a number to attribute per call. Neither the recipe nor the adapter code checks what you're actually billed; treat these as the ledger's nominal per-call number, not a verified charge. The `--max-usd` / `--max-cost` budget gate does not read them either: it prices `claude-cli:<model>` at the nominal Anthropic rate for that model, and a short alias (`claude-cli:haiku`) prices identically to the dated id it resolves to; `pricing.overrides` forces $0 or a real rate for any `claude-cli:*` string, and on a subscription one line prices every claude-cli model: `gbrain pricing set 'claude-cli:*' --rate 0` (an exact model entry still wins; at $0 no cap limits claude-cli calls). || User-level CLAUDE.md | `~/.claude/CLAUDE.md` still loads on every call (see above) — only the working directory changes (see "What actually happens on a call" for exactly what that directory is and isn't). |## Doctor probe timeout: per-recipe, 30s for claude-clidiff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.mdindex 12e4e66542..f4680613a4 100644--- a/docs/architecture/key-files/core-services-1.md+++ b/docs/architecture/key-files/core-services-1.md@@ -21,12 +21,13 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/brainstorm/checkpoint.ts` — crash-resilient checkpoint for `gbrain brainstorm` and `gbrain lsd`. Persists FULL idea bodies (~50KB/run) so resume MERGES pre-crash ideas with post-resume ideas before the judge runs (a resume that produces only second-run output is silent partial output). `run_id = sha256(question + profile + sort(close_slugs) + sort(far_slugs)).slice(0,16)` — NO embedding bits, stable across embedding-model swaps. Atomic write via `.tmp + rename`. ONE resume flag (`--resume <run_id>` covers failed crosses, never-attempted crosses, AND a failed judge phase — the orchestrator keeps the checkpoint with `judge_done=false` whenever the judge throws, so `--resume` short-circuits every completed cross from disk and re-runs only the judge; there is no separate retry-judge flag); only a fully clean run (all crosses + judge) clears the file. The checkpoint also banks the CLI's saved-page slug (`idea_slug`, from `RunBrainstormOpts.ideaSlug`) and the orchestrator echoes it back as `BrainstormResult.idea_slug` on resume, so the re-scored page overwrites the one the failed run saved instead of forking a second page under a fresh nonce. `--list-runs` prints run_ids mtime-newest-first; `--force-resume` bypasses the 7-day staleness gate. Cycle purge phase (`gbrain dream --phase purge`) GCs checkpoints older than 7 days via `gcStaleCheckpoints(7)`. Pinned by `test/e2e/brainstorm-resume.test.ts` (20 unit + 5 E2E cases incl. the merge contract and judge-failed retention/re-score).-- `src/core/brainstorm/{domain-bank,orchestrator,judges}.ts` + `src/commands/{brainstorm,lsd,eval-brainstorm}.ts` + `src/core/last-retrieved.ts` — bisociation-grounded idea generation pair: `gbrain brainstorm <question>` (defensible, cite-heavy, 4 close × 6 far, judge threshold 4.0/5, save by default) and `gbrain lsd <question>` (Lateral Synaptic Drift — inverted judge rejecting ideas with resistance >4.5 "too obvious", stale-page bias via `pages.last_retrieved_at`, 2 close × 12 far, axiomatic inversions required, ephemeral by default). The "domain bank" is prefix-stratified sampling from the user's own brain (`SELECT DISTINCT substring(slug from '^[^/]+/[^/]+')` cached 1h-TTL in `config` per source) tiebroken by `JOIN page_links` connection_count, with corpus-sampling fallback when fewer prefixes than M exist. Distance normalized to [0,1] via `1 - clamp(cosine_distance, 0, 2) / 2`. `judges.ts` exports `runJudge(config, ideas)` + two configs (`BRAINSTORM_JUDGE_CONFIG` weighted originality/resistance/thesis_density/concrete_grounding/cognitive_load 0.25/0.20/0.20/0.20/0.15 vs `LSD_JUDGE_CONFIG` cognitive_load 0.50 + inversion rule). Calibration cold-start fallback: when `calibration_profiles.active_bias_tags` is empty, judge runs without anti-bias context AND stderr-warns. Op-layer write-back in `src/core/operations.ts` `search`/`query`/`get_page` handlers fires `bumpLastRetrievedAt(engine, pageIds)` (fire-and-forget, 5-min throttled via SQL clause, default-on with `search.track_retrieval` config escape hatch); internal callers (sync, migrations, dream cycle) bypass the op layer so the LSD stale signal stays clean. The fire-and-forget IIFE is tracked in a module-scoped `Set<Promise<unknown>>`; `awaitPendingLastRetrievedWrites(timeoutMs?: number): Promise<{outcome, pending}>` resolves once all tracked promises settle, bounded by a 5s `Promise.race` timeout that stderr-warns the pending count. `src/cli.ts` awaits the drain unconditionally for every op in the op-dispatch finally block BEFORE `engine.disconnect()`, then a fallback `process.exit(0)` fires ONLY when `outcome === 'timeout'` AND `shouldForceExitAfterMain(argv)` (excludes `serve` so daemons stay alive) — so the IIFE cannot race disconnect and leave PGLite's WASM keeping Bun's event loop alive. `pages.last_retrieved_at TIMESTAMPTZ NULL` has a full (NOT partial) B-tree index covering both NULL and range branches; full forward-reference bootstrap probe on both engines. Frontmatter `mode: lsd` makes the dream-cycle synthesize phase skip LSD output via `isLsdOutput()` in `src/core/cycle/transcript-discovery.ts` short-circuiting `isDreamOutput()`. `gbrain eval brainstorm <fixture.jsonl>` is a three-axis conjunctive gate (distance + usefulness + grounding — distance alone is gameable). `gbrain doctor` has a `brainstorm_health` check (migration applied, `search.track_retrieval` setting, calibration cold-start status). `judges.ts` computes the judge token budget via `computeJudgeMaxTokens(ideaCount, modelId)` (named constants `TOKEN_BUDGET_PER_IDEA`, `TOKEN_BUDGET_ENVELOPE`, `LEGACY_MIN_MAX_TOKENS`, `MAX_OUTPUT_TOKENS_CEIL`; `ANTHROPIC_OUTPUT_CAPS` map: Opus 4.7 32K, Sonnet 4.6 / Haiku 4.5 64K, legacy Claude 3.5 8K) so a large multi-call judge doesn't truncate mid-JSON; with no `modelOverride` the cap routes through the gateway's actual configured chat model via `getChatModel()`. `--save` for both commands persists through the canonical ingestion path: `persistSavedIdea(engine, {slug, content, provenanceVia})` calls `importFromContent({noEmbed:true, sourcePath})` (chunked + tagged + content_hash so search finds it, no embedding cost at save) THEN renders the saved row to disk via the shared `writePageThrough` helper (file rendered FROM the row so the two sinks can't diverge and `gbrain sync` doesn't churn it). `formatSaveOutcome(outcome, ctx)` returns an honest per-branch message (both-sinks, DB-only when no `sync.repo_path`/repo-not-a-dir, DB-saved-but-file-errored, total-failure → loud `save FAILED … NOT persisted` on stderr + nonzero exit) — `--save` never prints "Saved" when the DB write failed. `buildIdeaSlug(question, label, nonce?)` adds a random nonce suffix (injectable for tests) so two same-day runs sharing the first 60 slug chars don't clobber. `--json` callers stay DB-only. `buildBrainstormFrontmatterObject(result)` in orchestrator.ts returns the object form for `serializeMarkdown`. Pinned by `test/last-retrieved.test.ts`, `test/e2e/pglite-cli-exit.serial.test.ts` (IRON-RULE: real `bun src/cli.ts` subprocess against a hermetic PGLite tempdir asserts search/get/query exit 0 in <15s + daemon-survival), `test/fix-wave-structural.test.ts` (asserts the drain `await` is textually BEFORE `engine.disconnect`), `test/brainstorm/{distance,lsd-mode-skip,eval-brainstorm,judges-maxtokens,save}.test.ts`. Open Collider source: `github.com/CL-ML/open-collider`.+- `src/core/brainstorm/{domain-bank,orchestrator,judges}.ts` + `src/commands/{brainstorm,lsd,eval-brainstorm}.ts` + `src/core/last-retrieved.ts` — bisociation-grounded idea generation pair: `gbrain brainstorm <question>` (defensible, cite-heavy, 4 close × 6 far, judge threshold 4.0/5, save by default) and `gbrain lsd <question>` (Lateral Synaptic Drift — inverted judge rejecting ideas with resistance >4.5 "too obvious", stale-page bias via `pages.last_retrieved_at`, 2 close × 12 far, axiomatic inversions required, ephemeral by default). The "domain bank" is prefix-stratified sampling from the user's own brain (`SELECT DISTINCT substring(slug from '^[^/]+/[^/]+')` cached 1h-TTL in `config` per source) tiebroken by `JOIN page_links` connection_count, with corpus-sampling fallback when fewer prefixes than M exist. Distance normalized to [0,1] via `1 - clamp(cosine_distance, 0, 2) / 2`. `judges.ts` exports `runJudge(config, ideas)` + two configs (`BRAINSTORM_JUDGE_CONFIG` weighted originality/resistance/thesis_density/concrete_grounding/cognitive_load 0.25/0.20/0.20/0.20/0.15 vs `LSD_JUDGE_CONFIG` cognitive_load 0.50 + inversion rule). Calibration cold-start fallback: when `calibration_profiles.active_bias_tags` is empty, judge runs without anti-bias context AND stderr-warns. Op-layer write-back in `src/core/operations.ts` `search`/`query`/`get_page` handlers fires `bumpLastRetrievedAt(engine, pageIds)` (fire-and-forget, 5-min throttled via SQL clause, default-on with `search.track_retrieval` config escape hatch); internal callers (sync, migrations, dream cycle) bypass the op layer so the LSD stale signal stays clean. The fire-and-forget IIFE is tracked in a module-scoped `Set<Promise<unknown>>`; `awaitPendingLastRetrievedWrites(timeoutMs?: number): Promise<{outcome, pending}>` resolves once all tracked promises settle, bounded by a 5s `Promise.race` timeout that stderr-warns the pending count. `src/cli.ts` awaits the drain unconditionally for every op in the op-dispatch finally block BEFORE `engine.disconnect()`, then a fallback `process.exit(0)` fires ONLY when `outcome === 'timeout'` AND `shouldForceExitAfterMain(argv)` (excludes `serve` so daemons stay alive) — so the IIFE cannot race disconnect and leave PGLite's WASM keeping Bun's event loop alive. `pages.last_retrieved_at TIMESTAMPTZ NULL` has a full (NOT partial) B-tree index covering both NULL and range branches; full forward-reference bootstrap probe on both engines. Frontmatter `mode: lsd` makes the dream-cycle synthesize phase skip LSD output via `isLsdOutput()` in `src/core/cycle/transcript-discovery.ts` short-circuiting `isDreamOutput()`. `gbrain eval brainstorm <fixture.jsonl>` is a three-axis conjunctive gate (distance + usefulness + grounding — distance alone is gameable). `gbrain doctor` has a `brainstorm_health` check (migration applied, `search.track_retrieval` setting, an unpriced cross or judge chat model, calibration cold-start status). Cost policy lives in `src/core/brainstorm/cost-gate.ts`: no cap flag is the $5 `default` tracker cap (an unpriced model warns and runs, priced calls stay metered; the estimate, mid-run guard and pre-judge check count it at Sonnet rates), `--max-usd N` (legacy `--max-cost`) is a `user` cap that refuses a run touching an unpriced chat, judge or embedding model before any work with the `no-pricing.ts` refusal, `--max-usd off` drops the USD ceiling; every price reads `pricing.overrides`; results carry `cost.cap_usd`/`cost.cap_source`. `judges.ts` computes the judge token budget via `computeJudgeMaxTokens(ideaCount, modelId)` (named constants `TOKEN_BUDGET_PER_IDEA`, `TOKEN_BUDGET_ENVELOPE`, `LEGACY_MIN_MAX_TOKENS`, `MAX_OUTPUT_TOKENS_CEIL`; `ANTHROPIC_OUTPUT_CAPS` map: Opus 4.7 32K, Sonnet 4.6 / Haiku 4.5 64K, legacy Claude 3.5 8K) so a large multi-call judge doesn't truncate mid-JSON; with no `modelOverride` the cap routes through the gateway's actual configured chat model via `getChatModel()`. `--save` for both commands persists through the canonical ingestion path: `persistSavedIdea(engine, {slug, content, provenanceVia})` calls `importFromContent({noEmbed:true, sourcePath})` (chunked + tagged + content_hash so search finds it, no embedding cost at save) THEN renders the saved row to disk via the shared `writePageThrough` helper (file rendered FROM the row so the two sinks can't diverge and `gbrain sync` doesn't churn it). `formatSaveOutcome(outcome, ctx)` returns an honest per-branch message (both-sinks, DB-only when no `sync.repo_path`/repo-not-a-dir, DB-saved-but-file-errored, total-failure → loud `save FAILED … NOT persisted` on stderr + nonzero exit) — `--save` never prints "Saved" when the DB write failed. `buildIdeaSlug(question, label, nonce?)` adds a random nonce suffix (injectable for tests) so two same-day runs sharing the first 60 slug chars don't clobber. `--json` callers stay DB-only. `buildBrainstormFrontmatterObject(result)` in orchestrator.ts returns the object form for `serializeMarkdown`. Pinned by `test/last-retrieved.test.ts`, `test/e2e/pglite-cli-exit.serial.test.ts` (IRON-RULE: real `bun src/cli.ts` subprocess against a hermetic PGLite tempdir asserts search/get/query exit 0 in <15s + daemon-survival), `test/fix-wave-structural.test.ts` (asserts the drain `await` is textually BEFORE `engine.disconnect`), `test/brainstorm/{distance,lsd-mode-skip,eval-brainstorm,judges-maxtokens,save}.test.ts`. Open Collider source: `github.com/CL-ML/open-collider`.-- `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 — each admitted projection is held until its `record()` settles it, so N concurrent callers (skillopt's validation gate) can't all pass against the same cumulative and breach `--max-cost-usd` by (N-1)×per-call cost; `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 (`reservationCostUsd`, overrides, free local providers, unknown-price `null`) lives in the pure `src/core/budget/reservation-cost.ts`, shared with skillopt preflight's impossible-reservation check so the two cannot disagree. 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/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). `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/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/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`.- `src/core/chronicle/{contract,eligibility,config,reasons,ledger,ledger-stats,execute,publish,event-identity,invite-projection,backfill,job,upgrade-notice,extract-events,ontology,narrative}.ts` + `src/core/cycle/chronicle.ts` + `src/eval/chronicle/harness.ts` + `src/commands/eval-chronicle.ts` — Life Chronicle: the temporal spine. `contract.ts` holds the ledger columns, the extractor version (part of the ledger key: a bump makes extracted content new to discovery and backfill), the phase bounds and the phase result details. `reasons.ts` is the one reason table (`CHRONICLE_REASONS`: stage, meaning, stored fix Action with argv/preview_argv/consent/actor, never a stored `next`; `auto_chronicle_off` has no fix because it is off by choice) and builds the `chronicle_backstop` receipt field (`{pending:'next_cycle', daily_remaining}` or `{skipped, stage, why, fix}`, omitted for pages that are not chronicle-shaped); `docs/guides/life-chronicle.md` renders its table from it. `eligibility.isChronicleEligible` is the one eligibility function (meeting/conversation/calendar-event + directory rescue; diary and event pages NEVER eligible — privacy + anti-loop); with a time policy it also applies the invite end (`not_yet_happened`), the recency window on the page's own date (an authored `effective_date`, else frontmatter `date`/`start`; a `fallback` date counts as undated) and the settle window. `config.ts` owns the switch and knobs: `autoChronicleSetting` reads `auto_chronicle` as on when unset, on/off for true/false words, and `invalid` (off) for any other word; `chronicleSettings` reads `chronicle.job_budget_usd`/`auto_daily_limit`/`auto_recent_days`/`auto_settle_seconds`/`judge_max_tokens` with ranges (`CHRONICLE_NUMERIC_KEYS`, enforced by `config set`; a malformed stored row falls back and is listed in `invalid`) and `chronicle.activated_at` (stamped by the first write decision or phase run; earlier revisions are history); `autoChronicleNeedsAcknowledgement` is true while on and `chronicle.default_on_acknowledged` is unset (stamped by `config set auto_chronicle`). The opt-out is `gbrain config set auto_chronicle false` everywhere. `ledger.ts` owns `chronicle_page_state` (one row per source/page/content hash/extractor version: state, reason, trigger, deciding writer and request, `no_extract`, attempts, `next_attempt_at`, cost/unpriced, event slugs and hashes): `recordChronicleDecision` runs inside every coordinated publication that imports a page (from `queuePublicationEffects`), applies the shared writer-confinement predicate, `--no-extract`, the opt-out and eligibility, and puts `chronicle_backstop` on the outcome through `reasons.ts`; `reserveChronicleSlot` is the rolling 24 h reservation under a transaction advisory lock. `ledger-stats.ts` rolls up the ledger and reservations for doctor and the advisor. `upgrade-notice.ts` is the one-shot post-upgrade notice (`chronicle.default_on_notice_shown`). The global `chronicle` cycle phase (`cycle/chronicle.ts`) supersedes rows whose content is no longer live, discovers pages changed since activation with no row (unmanaged brains decide there; managed ones record `no_write_decision`), and executes settled rows round-robin across sources (≤50 judged items and a wall-time bound per run; automatic rows only while `auto_chronicle` is on, backfill rows always); no chat provider → no calls; the extract_atoms cost gate refuses an explicit cap on an unpriced model. `execute.ts` runs one row: live-content check, time rules, the reservation (automatic rows; attempts count), the judge in a `chronicle:<trigger>` BudgetTracker scope with the per-page cap and an explicit post-call cap check, failure classes (chat_error/budget → failed with backoff, no provider/no_pricing → failed until config changes, refused → skipped, only a parsed `[]` is `no_events`). `invite-projection.ts` stands in for the judge on an ended calendar invite (slug under `calendar/`/`cal/` or type `calendar-event`, with a title, `start` and `end`): one `Scheduled: <title>` event (`kind: meeting`, `captured_via: life-chronicle:invite`, not proof of attendance) with no chat call, no daily reservation and zero cost, through the same publication and ledger path. `publish.ts` publishes one generation against the pinned depth snapshot: each event write re-validates the depth revision, content hash, source incarnation, privacy and the deciding writer's grant (events also read as private when their `event.depth` origin is private by field or declared lineage, or missing, `search/private-visibility.ts`) (`managed_maintenance_chronicle_event`/`_retire` intents on managed brains, one transaction per event otherwise), stamps the depth's visibility, never overwrites an operator-edited event (live hash not in the ledger) or resurrects an operator-deleted one, and after a complete generation retires the previous generation's owned events (`retired_by: life-chronicle`; restored when produced again). `event-identity.ts` assigns final slugs before publication: events sharing a base slug `life/events/<day>-<hash8>` (who, what, depth) are told apart by instant, `where` and `kind`; one keeps the base slug and the rest get `-<hash6>` (identical copies `-2`…); assignment reads the pages already at the candidate slugs, so it is order-independent, keeps a page's existing slug across corrections and re-extractions, and a page extracted before disambiguation keeps its base slug. `extract-events.runChronicleExtract` is the direct-caller body over the same snapshot and publication path: deterministic when/who, injectable judge (default = chat gateway; output cap 4000 tokens by default, operator override `chronicle.judge_max_tokens`), an ALL-or-nothing parse barrier (`isValidProposal` requires a real parseable date), then `screenChronicleProposals` drops, never writes, each proposal without a day (`date_imprecise`: `when` is a year or month) or dated after the page's own day (`future_dated`: `chronicleEventCutoff` is the latest of the page's own date, a meeting's `end` and a conversation's last parsed message, as a day in `chronicle.tz`, capped at today); drops are counted in `events_dropped` (phase details, row outcome, direct result) and a page whose every proposal was dropped records the drop reason on its extracted ledger row instead of `no_events`; content-addressed `life/events/` pages + a `timeline_entries` projection. An unusable judge response is never recorded as `no_events`: truncation, unparseable output, a provider error and a refusal surface as `judge_truncated`/`judge_parse_failed`/`judge_chat_error`/`judge_refused`. `backfill.ts` (`chronicle_backfill`) queues `trigger='backfill'` ledger rows, exempt from the daily limit and recency (unless `--recent`), across types and rescue prefixes under one global `--limit`; `--since` is the update date, `--dated-since` the page date; a dry run reports `estimated_usd` and skip reasons; a live run needs `--yes`; content already extracted or queued is never re-queued, even after `gbrain jobs prune`. `job.ts` drains `chronicle_extract` jobs from older releases through the same executor. `ontology.ts` carries the deterministic pieces of the bi-temporal per-entity ontology that RIDES THE `facts` TABLE (migration v122 adds `dimension`/`value`/`value_hash`/`dim_status`): `valueHash` (normalized, timestamp-free; the v188 dedup index adds the stint's `valid_from`, so a crash-retry conflicts while a same-provenance return to an earlier value records a new interval), `normalizeDimension` (seed alias lexicon), `isNovelDimension` (novel → quarantined, excluded from resolution/context until confirmed). The engine methods (`mergeOntologyFact` — corroborate on same value (noop when the same provenance already observed it during the current stint), forward-supersede via `valid_until`+`superseded_by` on a new value, backdated conflicts kept + flagged; `getOntology` with `--asof` valid-time travel; `discoverOntologyDimensions`; `findOntologyConflicts` — currently-open rows only) live in BOTH engines; both engines are on the R8 `valid_until` write allow-list (engine-layer, `dimension IS NOT NULL` rows only). Chronicle reads (`getTimelineForDate`/`getSince`/`getLastSeen`/`getOnThisDay`) JOIN the depth page (`deleted_at IS NULL`), hide soft-deleted event projections at READ time, and order by event `effective_date` for intra-day sequence. Ops: `chronicle_day`/`chronicle_since`/`chronicle_last_seen`/`chronicle_on_this_day`/`ontology_*`/`volunteer_chronicle` (agent orientation via `src/core/context/chronicle-context.ts`)/`chronicle_backfill` (admin, localOnly). Diary privacy: fail-closed for `ctx.remote !== false` callers — diary-sourced ontology + conflict values are redacted, the four timeline read ops (`chronicle_day`/`chronicle_since`/`chronicle_on_this_day` + `volunteer_chronicle`'s `recent_timeline`) drop rows whose depth page, event page, or `source` provenance lives under `life/diary/`, and `chronicle_last_seen` answers the never-seen shape (`last_date`/`last_event_slug`/`days_ago` all null) when the latest sighting is diary-sourced or a diary page is queried as the entity. Remote callers read only `visibility = 'world'` observations, like recall: `getOntology`/`findOntologyConflicts` take a `visibility` filter applied before resolution and the conflict HAVING. `ontology_propose` commits through `coordinatedDatabaseWrite` on a managed brain. Page visibility rides the same policy: `ontology_get`/`ontology_conflicts`/`volunteer_chronicle`'s ontologies resolve through `readPolicyOpts`, and both engines' `getOntology`/`findOntologyConflicts` apply `privateProvenanceFilterFragment` (an observation whose provenance page, looked up in the fact's own source, is `visibility: private` is dropped BEFORE per-dimension resolution and before the conflict HAVING, so an untrusted caller resolves the newest value they may see rather than a private value or a hole). The chronicle reads' event-page LEFT JOIN carries the caller's source scope in BOTH engines, so a scoped read can't surface another source's event pages through the join. Search: `applyChronicleTypeBoost` in `search/hybrid.ts` (bounded [1.0,1.25], fires only inside the `recency !== 'off'` post-fusion branch → non-temporal search bit-for-bit unchanged). Advisor collector `collect-chronicle.ts` (conflicts; coverage gap with a scoped `chronicle-backfill --since <date> --limit 50 --dry-run`; `auto_chronicle_default_on` ask_user until acknowledged; `auto_chronicle_invalid`; `chronicle_chat_unavailable`; `chronicle_extraction_failing`; `chronicle_daily_limit`); doctor `chronicle_projection_health` and `auto_chronicle` (`checks/auto-chronicle.ts`; BRAIN category). Eval: `gbrain eval chronicle` — deterministic, own in-memory PGLite, 6 gold tasks (day order, last-seen, supersession, asof, conflict, isolation), exit 0 iff 6/6. Tests: `test/chronicle-*.test.ts` (automatic path: `chronicle-auto-{decision,phase,unmanaged}`, `chronicle-date-quality`, `chronicle-event-privacy`, `chronicle-event-identity`, `chronicle-invite-projection`, `chronicle-backfill`, `chronicle-reasons-5876`; Postgres arms in `test/e2e/chronicle-*-postgres.test.ts`), `test/eval-chronicle.test.ts`, `test/auto-chronicle-surfaces-5876.test.ts`.diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.mdindex 9f88e3bf36..8820d66801 100644--- a/docs/architecture/key-files/providers.md+++ b/docs/architecture/key-files/providers.md@@ -49,7 +49,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/model-id.ts` — `splitProviderModelId(input: string | null | undefined): {provider: string | null, model: string}` shared parser for the pricing side. Splits on `:` first, then `/`. Defensive contract: null/undefined/empty/whitespace returns `{provider: null, model: ''}`. Five sites consume it (`src/core/anthropic-pricing.ts:estimateMaxCostUsd`, `src/core/budget/budget-tracker.ts:lookupPricing`, `src/core/eval-contradictions/cost-tracker.ts:pricingFor`, `src/core/model-config.ts:isAnthropicProvider`) so the pricing + classification surface has no parallel re-implementations of `provider:model` splitting — slash-form ids (`anthropic/claude-sonnet-4-6`) classify correctly instead of falling through to "unknown model". Distinct from the gateway-side `parseModelId` in `src/core/ai/model-resolver.ts`, which throws on bare names because routing needs an explicit provider; this one returns `{provider: null, model: 'bare'}` because pricing lookups happen against bare model ids. Pinned by `test/model-id.test.ts`.-- `src/core/model-pricing.ts` — single source of truth for paid-cloud CHAT/completion model pricing (USD per 1M tokens, input | output). `CANONICAL_PRICING` is a `provider:model`-keyed table (Anthropic Opus 5/4.8/4.7/4.6 `$5/$25`, Sonnet 4.6 `$3/$15`, Haiku 4.5 `$1/$5` both dateless + dated, plus OpenAI / Google / Together / DeepSeek panel models). Exported as `gbrain/core/model-pricing` for companion evaluators to enforce the canonical price cap. `canonicalLookup(modelId)` resolves bare (`claude-opus-4-8`), colon (`anthropic:claude-opus-4-8`), and slash (`anthropic/...`) forms — bare ids default to the `anthropic:` provider; nested OpenRouter ids (`openrouter:anthropic/...`) intentionally MISS so OpenRouter markup isn't repriced as the inner vendor; after the exact match, a case-insensitive fallback folds BOTH sides (some canonical keys carry cased model tails verbatim), safe only while no two canonical keys collide case-insensitively (pinned by the drift guard). Every other chat-pricing table is a DERIVED view of this one (NOT a hand-copied duplicate), so cross-table price drift is structurally impossible. Embeddings live separately in `embedding-pricing.ts` (different unit). Pinned by `test/model-pricing.test.ts` whose drift guard asserts each derived view equals canonical and that the cross-modal panel models are all present.+- `src/core/model-pricing.ts` — single source of truth for paid-cloud CHAT/completion model pricing (USD per 1M tokens, input | output). `CANONICAL_PRICING` is a `provider:model`-keyed table (Anthropic Opus 5/4.8/4.7/4.6 `$5/$25`, Sonnet 4.6 `$3/$15`, Haiku 4.5 `$1/$5` both dateless + dated, plus OpenAI / Google / Together / DeepSeek panel models). Exported as `gbrain/core/model-pricing` for companion evaluators to enforce the canonical price cap. `canonicalLookup(modelId)` resolves bare (`claude-opus-4-8`), colon (`anthropic:claude-opus-4-8`), and slash (`anthropic/...`) forms — bare ids default to the `anthropic:` provider; nested OpenRouter ids (`openrouter:anthropic/...`) intentionally MISS so OpenRouter markup isn't repriced as the inner vendor; after the exact match, a case-insensitive fallback folds BOTH sides (some canonical keys carry cased model tails verbatim), safe only while no two canonical keys collide case-insensitively (pinned by the drift guard). Every other chat-pricing table is a DERIVED view of this one (NOT a hand-copied duplicate), so cross-table price drift is structurally impossible. Embeddings live separately in `embedding-pricing.ts` (different unit). DeepSeek rows (`deepseek-flash`, its legacy alias `deepseek-v4-flash`, `deepseek-v4-pro`) carry the vendor's PEAK rate so caps bound the worst case; `peakRateNote(models)` labels estimates that use them. OpenRouter rows are the router's own catalogue rate, never the vendor's. `bun run check:recipe-pricing` (`scripts/check-recipe-pricing.ts`) requires every recipe touchpoint model to price or be named in the recipe's `unpriced_models`. Pinned by `test/model-pricing.test.ts` whose drift guard asserts each derived view equals canonical and that the cross-modal panel models are all present.- `src/core/post-upgrade-reembed.ts` — Pure functions backing the `gbrain upgrade` chunker-bump cost prompt. `computeReembedEstimate(engine, model)` queries real SQL (`COUNT(*)` + `COALESCE(SUM(LENGTH(compiled_truth)) + SUM(LENGTH(timeline)), 0)`) on `pages WHERE chunker_version < MARKDOWN_CHUNKER_VERSION`. `formatReembedPrompt(est)` is the stderr-line formatter (count, model, cost estimate when priced). `runPostUpgradeReembedPrompt(engine, model, opts)` re-embeds only on consent: a TTY operator must answer `y` to `[chunker-bump] Re-embed now? [y/N]`; the default, EOF and every non-TTY run decline and print `REEMBED_DEFERRED_HINT` (`gbrain reindex --markdown`, or `gbrain repair safe-chunks --apply --no-embed` then `gbrain embed --stale`), so an unattended upgrade never spends. Reasons: `no_pending`, `bypassed_no_reembed`, `consent_required`, `tty_declined`, `tty_consented`. `GBRAIN_NO_REEMBED=1` skips the prompt with a doctor-warning marker. `opts.confirm` and `opts.isTTY` are test seams.diff --git a/docs/operations/spend-controls.md b/docs/operations/spend-controls.mdindex 0ba831d9e8..9755dda05f 100644--- a/docs/operations/spend-controls.md+++ b/docs/operations/spend-controls.md@@ -107,6 +107,25 @@ unclaimable; cancel them first (`gbrain jobs cancel --group <id>`).The USD-limit knobs accept `off`, `unlimited`, or `none` (case-insensitive) to mean"no limit", so no sentinel value like `100000` is needed.+On the command line, `--max-usd off` is the canonical way to run uncapped.+`brainstorm`, `lsd`, `skillopt`, `enrich`, `onboard` and `eval longmemeval`+parse their cap flag through one parser (`src/core/budget/cap-flag.ts`), so+the rules match everywhere:++| Command | Canonical | Legacy spellings still accepted |+|---|---|---|+| `brainstorm`, `lsd` | `--max-usd N\|off` | `--max-cost N\|off` |+| `skillopt` | `--max-usd N\|off` | `--max-cost-usd N` (`0` = uncapped, deprecated), `--no-max-cost` |+| `enrich` | `--max-usd N\|off` | `--max-cost-usd N\|off` |+| `onboard`, `eval longmemeval` | `--max-usd N\|off` | none |++A malformed value, a bare `0` (ambiguous: free or uncapped?) and two cap flags+that disagree are refused before any paid call. `eval longmemeval --max-usd 0`+keeps its meaning, a $0 judge cap. Runtime, call and token bounds stay in+force when the USD cap is off. `brainstorm`, `lsd` and `skillopt` print one+line naming the cap, its source and how to remove it, e.g.+`cap: $5.00 (default; change it with --max-usd <usd>, remove it with --max-usd off)`.+- `0` is **not** "off". On `sync.cost_gate_min_usd`, `0` means "block on any nonzerospend" (a real choice). On the backfill caps, `0` falls back to the default — and on`embed.backfill_max_usd` specifically, any present-but-invalid value (`0`, a@@ -312,6 +331,23 @@ always works. Proxy routes hit the explicit-cap refusal by design: a LiteLLMendpoint can front a paid provider, so `litellm:*` models are deliberatelyabsent from both the pricing tables and the free-local sets.+`brainstorm` / `lsd` and `skillopt` follow the same rule. With no cap flag the+$5 default is a default cap: an unpriced model warns and runs, priced calls+in the same run stay metered, and brainstorm's estimate, mid-run and pre-judge+checks count the unpriced model at Sonnet rates so an oversized run still+stops. With `--max-usd N` a run that would call an unpriced chat, judge or+embedding model is refused before any work (skillopt: before any spend, in the+preflight). The skillopt preflight never invents a rate: an unpriced model+shows `Est. cost: unpriced (...)`. `brainstorm_health` in `gbrain doctor`+names an unpriced brainstorm chat or judge model.++Shipped rates are list rates. DeepSeek bills half its peak rate off-peak;+gbrain's DeepSeek rows are the peak rate so caps bound the worst case, and+estimates that use them say `(DeepSeek at peak rates, an upper bound)`.++Every model a recipe lists is either priced or declared in the recipe's+`unpriced_models`; `bun run check:recipe-pricing` enforces it in CI.+### Registering a model priceThe `no_pricing` refusal tells the agent what to do: look up the provider's@@ -363,7 +399,18 @@ gbrain config set pricing.overrides \Semantics:-- Keys are full `provider:model` strings (case-insensitive, exact match).+- Keys are full `provider:model` strings (case-insensitive, exact match). An+ override keyed by a model alias also prices the id the provider serves for it.+- **Provider wildcard (subscription providers only).** `<provider>:*` prices+ every model of a provider whose recipe bills by subscription, today only+ `claude-cli`: `gbrain pricing set 'claude-cli:*' --rate 0`. Precedence is+ exact model entry, then the wildcard, then the shipped tables. This is a+ cap bypass by design: at $0 every claude-cli call counts as free against+ every cap, including models gbrain ships a rate for. It is an operator+ assumption, labelled as such by `gbrain pricing list`, which also names the+ models the wildcard prices. A bare `*` and a wildcard on a per-token API+ provider (`openai:*`) are refused by `pricing set` and ignored if written+ into the config directly.- Overrides win over shipped tables — you own your bill (negotiated rates,markup-charging proxies).- Models with neither a table row nor an override stay fail-closed under a cap.diff --git a/docs/wave9/lane-a.md b/docs/wave9/lane-a.mdnew file mode 100644index 0000000000..b51b588821--- /dev/null+++ b/docs/wave9/lane-a.md@@ -0,0 +1,35 @@+# Wave 9 lane A: pricing, caps, budget reservations++Integrator notes for the release files. No version stamp or CHANGELOG header+was written on this branch.++## CHANGELOG lines++- **DeepSeek caps now bound what DeepSeek bills.** `deepseek-flash` (new row) and the legacy `deepseek-v4-flash` price at $0.30 / $1.20 per 1M tokens and `deepseek-v4-pro` at $1.32 / $3.96, DeepSeek's peak rates (read 2026-10-05). The old $0.14 / $0.28 and $0.435 / $0.87 rows let a cap under-enforce by up to about 4.5x on output. Estimates that use a DeepSeek row say `(DeepSeek at peak rates, an upper bound; off-peak bills half)`. The recipe lists `deepseek-flash` first for chat and expansion. The OpenRouter `deepseek/deepseek-v4-flash-0731` row is now OpenRouter's own rate ($0.0152 / $1.28). (A-N1, #5847)+- **`gbrain brainstorm` and `gbrain lsd` run on a model gbrain has no price for.** With no cap flag the $5 default warns and runs it (priced calls stay metered; the estimate, mid-run and new pre-judge checks count it at Sonnet rates, so an oversized run still stops). `pricing.overrides` now reaches the run. An explicit `--max-usd N` refuses a run that would call an unpriced chat, judge or embedding model before any work and names the `gbrain pricing set` command. `gbrain doctor`'s `brainstorm_health` names an unpriced brainstorm model. Builds on #5959 by @andreineacsu. (#5873)+- **`gbrain skillopt` no longer refuses a valid model only because it has no price.** The $5 default warns and runs it; an explicit cap refuses it in the preflight, before any spend, with the shared guidance. The preflight no longer invents Sonnet rates: it uses `pricing.overrides` and the claude-cli sibling rate, and shows `Est. cost: unpriced (...)` for a model nothing prices. (#5563, A-N4)+- **One cost-cap flag everywhere: `--max-usd N|off`.** `brainstorm`, `lsd`, `skillopt`, `enrich`, `onboard` and `eval longmemeval` share one parser. Legacy spellings keep working (`--max-cost`, `--max-cost-usd`, `--no-max-cost`). A malformed value, a bare `0` or two disagreeing cap flags are refused before any paid call; `enrich` and `onboard` used to ignore them silently. brainstorm, lsd and skillopt print one `cap: ...` line naming the cap and how to remove it; brainstorm's `--json` result carries `cost.cap_usd` and `cost.cap_source`. (D19)+- **`gbrain pricing set 'claude-cli:*' --rate 0`** prices every claude-cli model at once for subscription users. Only providers that bill by subscription accept a wildcard; an exact model entry still wins; `gbrain pricing list` names the models it covers and labels it an operator assumption. (D20)+- **synthesize_concepts meters claude-cli models and `pricing.overrides` correctly** instead of the Sonnet fallback, and names any model it had to meter at the fallback in `details.pricing_fallback_models`. (A-N2, #5166)+- **Concurrent paid calls can no longer slip past a cost cap.** Each budget reservation is settled by its own id: a small call finishing first no longer frees a large in-flight call's hold, and an attempt that never reached the provider (unknown provider, invocation policy refusal) no longer keeps its hold or gets charged. (eng I6)+- **CI: every model a recipe lists is priced or declared unpriced** (`bun run check:recipe-pricing`). (X1)++## Upgrade-note rows++| Who | What changes | What to do |+| --- | --- | --- |+| DeepSeek users with a cost cap | Caps and estimates use rates up to about 4.5x the old DeepSeek rows; a run that fit before may now stop at the cap | Raise the cap, or register your own rate: `gbrain pricing set deepseek:deepseek-flash --input <usd> --output <usd>` |+| brainstorm / lsd / skillopt on an unpriced model, no cap flag | Runs with a warning instead of exiting with `no_pricing` | Nothing; to meter it, `gbrain pricing set <model> ...` |+| Scripts passing `--max-cost 5` / `--max-cost-usd 5` on an unpriced model | Still refused, now before any work, with the registration command | Register the rate, or pass `--max-usd off` |+| `enrich` / `onboard` scripts passing `--max-usd 0` or a typo | Refused (exit 2 / usage error) instead of silently falling back | Pass a positive amount or `--max-usd off` |+| `skillopt --max-cost-usd 0` | Still uncapped, with a deprecation note | Write `--max-usd off` |+| Queued skillopt jobs from before the upgrade | Keep the old fail-closed cap behavior (no `max_cost_source` stored) | Nothing |+| claude-cli subscription users | Can price all claude-cli models at $0 in one line; this voids every cap for claude-cli calls | `gbrain pricing set 'claude-cli:*' --rate 0` only if that is what you want |++## Notes for the integrator++- No migrations.+- `src/core/budget/no-pricing.ts` is unchanged (interface and guidance text); brainstorm and skillopt call `noPricingGuidance` / `noPricingMessage` / `noPricingFix` / `pricingSetCommand`.+- `BudgetTracker.reserve()` now returns a `BudgetReservation | undefined`; `record()` settles only the id it is given and `release(id)` frees an unbilled attempt. Lane B's fallback hops and Lane C's probe budget should keep the id from each `reserve()` and pass it to `record()` or `release()`; an id-less `record()` settles nothing.+- `priceFor(model, kind, overrides)` in `src/core/budget/reservation-cost.ts` is the shared resolver for Lanes B and C.+- Regenerated: `src/core/cli-flag-registry.generated.ts` (new `--max-usd` on brainstorm, lsd, skillopt).