Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

docs: register a model price after no_pricing; agent guidance in model-routing convention

garrytanb078f584d412
diff --git a/docs/TESTING.md b/docs/TESTING.md
index f466558198..fd5e8fba35 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -2011,6 +2011,7 @@ Unit tests and what they cover:
- `test/llm-json-reasoning-ladder.test.ts` — `parseLlmJson`'s reasoning-block recovery ladder: strips a closed or truncated `<think>` block ONLY after a raw parse fails (valid JSON containing the tag text is untouched), case-insensitive, array payloads, and the facts/atoms extractors routing through it (the ORIGINAL failure reason is preserved when the retry also fails).
- `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/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/commands-4.md b/docs/architecture/key-files/commands-4.md
index 4454a347c2..5843d1105c 100644
--- a/docs/architecture/key-files/commands-4.md
+++ b/docs/architecture/key-files/commands-4.md
@@ -30,6 +30,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/migrations/v0_60_31.ts` — the security fix wave orchestrated migration (ledger `0.60.31`), two phases. `credential_projection`: runs `runMigrateOnlyCore` first (schema v189 marks the pages; PGLite skips the runner's schema pre-flight), then `resealCredentialProjections`, provider-free and never embedding; a dry run reports the count; any failed page makes the run `partial`, so `gbrain apply-migrations --yes --no-autopilot-install` retries it, and re-sealed pages are no longer pending, so a rerun resumes. `google_file_modes_notice`: `googleFileModesNoticePhase` from `v0_60_31-google-file-modes.ts`. A brain without config completes with the phase skipped. Agent instructions: `skills/migrations/v0.60.31.0.md`.
- `src/commands/models.ts` — `gbrain models [--json]` read-only routing dashboard: prints tier defaults (`utility`/`reasoning`/`deep`/`subagent`), the resolved value for each (re-walking the resolution chain), every per-task override (14 `PER_TASK_KEYS`, including provider-neutral `models.contextual_synopsis` with legacy-key/env attribution and `models.dream.extract_atoms` which reports via its own caller-specific resolver — `resolveExtractAtomsModel()` in `extract-atoms.ts` — rather than the generic chain, so the report can't diverge from what the phase actually calls), the alias map, and a source-of-truth column (`default` / `config: <key>` / `env: <VAR>`) derived from `resolveModelDetailed`, so a tier key is attributed before `models.default`. A resolved Anthropic haiku/sonnet/opus id older (by major, minor) than the anthropic recipe's newest priced same-family id gets an advisory `[newer <family> available: <id>] (gbrain config set ...)` hint (JSON: `newer_available`); version parsing lives in `src/core/ai/anthropic-model-ids.ts` (8-digit segment is a date, so dated and undated forms compare equal; fable, non-Anthropic, newer-than-recipe and unparseable ids get no hint). The hint never changes a default. `gbrain models doctor [--skip=<provider>] [--json]` fires a 1-token `gateway.chat()` probe against each configured chat + expansion model and classifies failures into `{model_not_found, auth, rate_limit, network, unknown}`. The probe timeout resolves per model via `resolveChatProbeTimeoutMs` — the recipe touchpoint's `default_timeout_ms` when declared, else the flat 5000ms default (mirrors the reranker probe's recipe-default fallback; `claude-cli` declares 30s because its `claude -p` subprocess cold start routinely outruns 5s and would false-fail every run as `unknown`). Wired into `cli.ts` dispatch + `CLI_ONLY` set. A zero-token `embedding_config` probe runs FIRST, before any chat/expansion probes spend money: `probeEmbeddingConfig()` reads `getEmbeddingModel()` + `getEmbeddingDimensions()` and (for Voyage flexible-dim models) checks `isValidVoyageOutputDim(dims)` against `VOYAGE_VALID_OUTPUT_DIMS`. `ProbeStatus` variant `'config'` + optional `fix?: string` on `ProbeResult` surface a paste-ready `gbrain config set ...` line in human + JSON output; touchpoint label `'embedding_config'` joins `'chat'` and `'expansion'`.
+- `src/commands/pricing.ts` — `gbrain pricing set <model> --input <usd/1M> --output <usd/1M> | --rate <usd/1M> [--source <url>]`, `pricing list [--json]`, `pricing unset <model>`. Each write reads `pricing.overrides`, changes one entry (keyed by the lowercased model; case variants replaced) and writes it back, so other entries survive; an unreadable stored value is refused, never overwritten. Rates must be non-negative finite numbers; $0 is accepted with a stderr warning. Entries keep the parser schema (`{input, output}` or `pricePerMTok`) with `source` and `set_at` beside them. Trust boundary: CLI-only (never an operation, so MCP cannot reach it) and `thinClient: 'refuse'` in the command table. Pinned by `test/budget/no-pricing-registration.test.ts`.
- `src/commands/orphans.ts` — `gbrain orphans` and MCP `find_orphans` share islanded (no live inbound or outbound links) and legacy inbound-only modes. Read policy scopes candidates and excludes private candidates, endpoints and independent origin pages before counting. Cross-source public links still establish reachability by the documented orphan definition. Reporting exclusions (`shouldExcludeFromOrphanReporting`) stay centralized; the scoped live-page denominator excludes the same private/reporting rows. `--source` remains explicit; no new remote privacy parameter. Connector renders (an `email`/`meeting` page whose source `config.kind` is a connector kind) are islanded by construction, so they leave both totals and are reported as `connector_renders_excluded` (`--include-pseudo` keeps them); doctor `orphan_ratio` carries that count in `details` and prints `gbrain extract links --by-mention --source db` (plus `--source-id` when scoped). Pinned by `test/orphan-ratio-connector-renders.test.ts`.
diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.md
index 5823bef010..835bdb62f0 100644
--- a/docs/architecture/key-files/core-services-1.md
+++ b/docs/architecture/key-files/core-services-1.md
@@ -23,7 +23,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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/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 (warn-once preserved when cap is unset); `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.
+- `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.
+- `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`). 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/{eligibility,config,backstop,extract-events,ontology,narrative}.ts` + `src/eval/chronicle/harness.ts` + `src/commands/eval-chronicle.ts` — Life Chronicle: the temporal spine. `eligibility.isChronicleEligible` decides which pages auto-emit events (meeting/conversation/calendar-event + directory rescue; diary and event pages NEVER eligible — privacy + anti-loop). `backstop.runChronicleBackstop` is the put_page hook body (fires ONLY on `status==='imported'` + the auto-link trust gate + the default-OFF `auto_chronicle` flag; enqueues a `chronicle_extract` minion job — LLM never runs on the write path). `extract-events.runChronicleExtract` is the job body: 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 — a malformed batch writes NOTHING), then content-addressed `life/events/` pages + a `timeline_entries` projection via `engine.upsertEventProjection` (dedup `(event_page_id, date)`; idempotent re-runs). An unusable judge response is never recorded as `no_events`: a `stopReason: 'length'` truncation or a no-JSON-array response (`parseJudgeJson` returns `null` on parse failure; `[]` only for a legitimate empty array) surfaces as `status: 'skipped'` with reason `judge_truncated` / `judge_parse_failed`. `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; each `chronicle_extract` job carries idempotency key `chronicle_extract:<source>:<slug>:<content_hash>`, so a repeat run skips pages already enqueued or extracted for their current content, reports them as `already_enqueued`, and pages past them until `limit` new pages per type are enqueued, #5329). 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); doctor `chronicle_projection_health` (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`, `test/eval-chronicle.test.ts`.
diff --git a/docs/guides/skillopt.md b/docs/guides/skillopt.md
index 554f80f9f1..19859aac09 100644
--- a/docs/guides/skillopt.md
+++ b/docs/guides/skillopt.md
@@ -217,7 +217,7 @@ The reflect codes are emitted with a mode, as `reflect_failure_<class>` or
| <a id="one_shot_rewrite_body_truncated"></a>`one_shot_rewrite_body_truncated` | One-shot refused: the body had to be truncated | Skill body larger than the optimizer's context | Lower the reflect cap (it shares the window), use a larger-window `--optimizer-model`, or use reflect mode |
| <a id="one_shot_rewrite_empty_reply"></a>`one_shot_rewrite_empty_reply` | One-shot reply was empty | Optimizer is not following the rewrite contract | Try a different `--optimizer-model` |
| <a id="one_shot_rewrite_failed"></a>`one_shot_rewrite_failed` | One-shot provider call failed | Provider/network/auth error | Check `gbrain models doctor`, then resume |
-| <a id="budget_exhausted"></a>`budget_exhausted` | Run aborted at the cost cap | Spend (including each call's full-cap reservation) reached `--max-cost-usd` | Raise `--max-cost-usd` (cycle: `cycle.skillopt.per_skill_cap_usd`), or lower the reflect cap |
+| <a id="budget_exhausted"></a>`budget_exhausted` | Run aborted at the cost cap | Spend (including each call's full-cap reservation) reached `--max-cost-usd`; or, when the detail says `no_pricing`, gbrain has no price for a model, so the cap cannot be enforced | Raise `--max-cost-usd` (cycle: `cycle.skillopt.per_skill_cap_usd`), or lower the reflect cap. For `no_pricing`: look up the model's price and run the `gbrain pricing set` command the receipt's `no_pricing.register_command` names, then resume ([registering a model price](../operations/spend-controls.md#registering-a-model-price)) |
| <a id="runtime_exceeded"></a>`runtime_exceeded` | Run aborted at the wall-clock cap | `--max-runtime-min` reached | Raise `--max-runtime-min`, then resume |
| <a id="reservation_exceeds_cap"></a>`reservation_exceeds_cap` | No model call made: one call alone reserves more than the cost cap | Reflect cap x optimizer price exceeds `--max-cost-usd` / `cycle.skillopt.per_skill_cap_usd` | Lower the reflect cap, pick a cheaper model, or raise the cost cap |
diff --git a/docs/operations/spend-controls.md b/docs/operations/spend-controls.md
index 6f5e97a527..a3705cfd1c 100644
--- a/docs/operations/spend-controls.md
+++ b/docs/operations/spend-controls.md
@@ -201,19 +201,59 @@ gbrain config set dream.breaker.max_dead_submissions 5 # raise the limit; 0 di
## Operator price overrides (`pricing.overrides`)
-Cost caps are fail-closed: when `--max-cost` (or a phase's default cap) is set
-and a model has no shipped pricing row, the budget tracker aborts with
-`no_pricing` rather than pretend the call is free. Proxy routes hit this by
-design — a LiteLLM endpoint can front a paid provider, so `litellm:*` models
-are deliberately absent from both the pricing tables and the free-local sets.
+Under a cost cap you set (`--max-cost`, `--max-usd`, `--max-cost-usd`, or an
+explicit cap in config), a model with no shipped pricing row stops the run
+with `no_pricing` rather than pretend the call is free. A cap gbrain applied by
+default does not: an unpriced model warns and runs, so a newly released model
+always works. Proxy routes hit the explicit-cap refusal by design: a LiteLLM
+endpoint can front a paid provider, so `litellm:*` models are deliberately
+absent from both the pricing tables and the free-local sets.
+
+### Registering a model price
+
+The `no_pricing` refusal tells the agent what to do: look up the provider's
+current price for the model (for example, search the web for its pricing
+page), register it, and retry. The refusal text and its JSON fields
+(`model`, `provider`, `kind`, `units`, `lookup`, `register_command`,
+`register_scope`, `docs`) carry the exact command:
-Declare your real rate in the config plane instead:
+```bash
+# Chat models: USD per 1M input tokens and per 1M output tokens.
+gbrain pricing set litellm:gpt-4o --input 2.5 --output 10 \
+ --source https://example.com/pricing
+
+# Embedding and reranker models: one USD-per-1M-token rate.
+gbrain pricing set litellm:text-embedding-3-large --rate 0.13
+
+gbrain pricing list # what is registered, with source and date
+gbrain pricing unset litellm:gpt-4o
+```
+
+- `pricing set` and `pricing unset` change one entry and keep every other
+ entry in `pricing.overrides`. (`gbrain config set pricing.overrides '<json>'`
+ still works, but it replaces the whole value.)
+- Rates must be non-negative finite numbers; anything else is refused and
+ nothing is written. An unreadable stored value is left unchanged and the
+ command refuses rather than overwrite it.
+- `--source` and the registration time are stored beside the rates
+ (`source`, `set_at`) for provenance. Cost caps ignore them.
+- **$0 is allowed, with a warning.** The operator decides; $0 is right for a
+ local or flat-rate route. Every call to that model then counts as free
+ against every cost cap.
+- **Registration is trusted-local only.** `gbrain pricing` is a CLI-only
+ command on the brain host, never an MCP operation, and a thin client
+ refuses it. Otherwise a remote agent could register $0 and void the cap.
+ An agent connected over MCP that meets `no_pricing` looks the price up and
+ asks the brain's operator to run the command the refusal names.
+
+The raw config shape, for reference:
```bash
# Scalar = one USD-per-1M-token rate for input AND output (natural for embeddings):
gbrain config set pricing.overrides '{"litellm:text-embedding-3-large": 0.13}'
-# Object form for chat models with distinct input/output rates:
+# Object form for chat models with distinct input/output rates
+# (pricing set also writes source and set_at beside them):
gbrain config set pricing.overrides \
'{"litellm:gpt-4o": {"input": 2.5, "output": 10}, "litellm:text-embedding-3-large": 0.13}'
```
@@ -242,10 +282,10 @@ nobody chose. When the configured embedding model has no shipped pricing row
and no `pricing.overrides` entry (the `isModelPriceable` contract), enforcing
that implicit cap would fail-close every job for a model that may well be
free or self-hosted. So the handler drops the DEFAULT cap and runs uncapped,
-with a stderr warning naming both fixes (add a `pricing.overrides` entry, or
+with a stderr warning naming both fixes (register its price with `gbrain pricing set`, or
set `embed.backfill_max_usd` to an explicit number). An EXPLICIT cap is a
different contract: you chose a ceiling, so an unpriced model stays
-fail-closed (`no_pricing`) — declare the model's rate in `pricing.overrides`
+fail-closed (`no_pricing`) — register the model's rate with `gbrain pricing set`
to proceed. Spend is ledgered by the tracker either way; only the ceiling
changes.
diff --git a/llms-full.txt b/llms-full.txt
index db82b8412c..2aa46f17d5 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -9665,6 +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). |
### Other error codes
diff --git a/plugin-variants/gbrain-coding/skills/conventions/model-routing.md b/plugin-variants/gbrain-coding/skills/conventions/model-routing.md
index 16c6efdcff..b72c6a3525 100644
--- a/plugin-variants/gbrain-coding/skills/conventions/model-routing.md
+++ b/plugin-variants/gbrain-coding/skills/conventions/model-routing.md
@@ -89,6 +89,25 @@ never hardcode a model string. The v0.31.6 chat default
API and made `extractFactsFromTurn` silently return `[]`. The tier system
+ doctor probe is the structural fix for that bug class.
+### A model gbrain has no price for
+
+Under default settings an unpriced model (a newly released one, a proxy
+route) warns and runs. Under a cost cap the user set, the run stops with
+`no_pricing`, because the cap cannot be enforced without a price. The refusal
+names the model, provider and kind and the exact registration command. Then:
+
+1. Look up the provider's current price for that 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.
+2. With a shell on the brain host, run the command the refusal names, such as
+ `gbrain pricing set <model> --input <usd> --output <usd> --source <url>`
+ (or `--rate <usd>`), then retry. Over MCP you cannot register prices: give
+ the command and the price you found to the brain's operator.
+
+Do not register $0 to get past the refusal unless the route really is free:
+it makes every call to that model count as free against every cap.
+
## 2. Subagent spawn routing
When the user-facing agent (Claude in the main session) chooses which model
diff --git a/plugin-variants/gbrain-daily/skills/conventions/model-routing.md b/plugin-variants/gbrain-daily/skills/conventions/model-routing.md
index 16c6efdcff..b72c6a3525 100644
--- a/plugin-variants/gbrain-daily/skills/conventions/model-routing.md
+++ b/plugin-variants/gbrain-daily/skills/conventions/model-routing.md
@@ -89,6 +89,25 @@ never hardcode a model string. The v0.31.6 chat default
API and made `extractFactsFromTurn` silently return `[]`. The tier system
+ doctor probe is the structural fix for that bug class.
+### A model gbrain has no price for
+
+Under default settings an unpriced model (a newly released one, a proxy
+route) warns and runs. Under a cost cap the user set, the run stops with
+`no_pricing`, because the cap cannot be enforced without a price. The refusal
+names the model, provider and kind and the exact registration command. Then:
+
+1. Look up the provider's current price for that 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.
+2. With a shell on the brain host, run the command the refusal names, such as
+ `gbrain pricing set <model> --input <usd> --output <usd> --source <url>`
+ (or `--rate <usd>`), then retry. Over MCP you cannot register prices: give
+ the command and the price you found to the brain's operator.
+
+Do not register $0 to get past the refusal unless the route really is free:
+it makes every call to that model count as free against every cap.
+
## 2. Subagent spawn routing
When the user-facing agent (Claude in the main session) chooses which model
diff --git a/plugin/skills/conventions/model-routing.md b/plugin/skills/conventions/model-routing.md
index 16c6efdcff..b72c6a3525 100644
--- a/plugin/skills/conventions/model-routing.md
+++ b/plugin/skills/conventions/model-routing.md
@@ -89,6 +89,25 @@ never hardcode a model string. The v0.31.6 chat default
API and made `extractFactsFromTurn` silently return `[]`. The tier system
+ doctor probe is the structural fix for that bug class.
+### A model gbrain has no price for
+
+Under default settings an unpriced model (a newly released one, a proxy
+route) warns and runs. Under a cost cap the user set, the run stops with
+`no_pricing`, because the cap cannot be enforced without a price. The refusal
+names the model, provider and kind and the exact registration command. Then:
+
+1. Look up the provider's current price for that 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.
+2. With a shell on the brain host, run the command the refusal names, such as
+ `gbrain pricing set <model> --input <usd> --output <usd> --source <url>`
+ (or `--rate <usd>`), then retry. Over MCP you cannot register prices: give
+ the command and the price you found to the brain's operator.
+
+Do not register $0 to get past the refusal unless the route really is free:
+it makes every call to that model count as free against every cap.
+
## 2. Subagent spawn routing
When the user-facing agent (Claude in the main session) chooses which model
diff --git a/skills/conventions/model-routing.md b/skills/conventions/model-routing.md
index 16c6efdcff..b72c6a3525 100644
--- a/skills/conventions/model-routing.md
+++ b/skills/conventions/model-routing.md
@@ -89,6 +89,25 @@ never hardcode a model string. The v0.31.6 chat default
API and made `extractFactsFromTurn` silently return `[]`. The tier system
+ doctor probe is the structural fix for that bug class.
+### A model gbrain has no price for
+
+Under default settings an unpriced model (a newly released one, a proxy
+route) warns and runs. Under a cost cap the user set, the run stops with
+`no_pricing`, because the cap cannot be enforced without a price. The refusal
+names the model, provider and kind and the exact registration command. Then:
+
+1. Look up the provider's current price for that 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.
+2. With a shell on the brain host, run the command the refusal names, such as
+ `gbrain pricing set <model> --input <usd> --output <usd> --source <url>`
+ (or `--rate <usd>`), then retry. Over MCP you cannot register prices: give
+ the command and the price you found to the brain's operator.
+
+Do not register $0 to get past the refusal unless the route really is free:
+it makes every call to that model count as free against every cap.
+
## 2. Subagent spawn routing
When the user-facing agent (Claude in the main session) chooses which model
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 075bacb99b..4a56b6bb81 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -50,7 +50,7 @@
"conventions/cron-via-minions.md": "badb1cd6cd825d6f1ac0b6b28cc47e5d80facc783a3e59a14146ae901ee0f933",
"conventions/cross-modal.yaml": "c012c3d72614a87b1ee698173dce2a0fb0d057a54df7aab87993c4b07fff6280",
"conventions/exec-output.md": "2bf371ac3ec4987eff7cc13cd3ea8cc97c46bd43f588eec024ff27f3171bc58f",
- "conventions/model-routing.md": "c1aba7a5c34454d6913edadb52ec7b53a3741f318c47fab6a26d5214479a8532",
+ "conventions/model-routing.md": "c0d5031e4372c108d7e94346dc2958c21389f3b67544524578bbc9ea32d53c34",
"conventions/path-discipline.md": "8af5415721bd115e6979c96688bcf542a32675809ada9aaedbb6706a40926954",
"conventions/quality.md": "8aa681001114689d34268ccadaf0e2ff07b8f68aa5987c093a8c4a7a744f12a6",
"conventions/regex-discipline.md": "d96a9baa6f27184e165889a9c655607366a739d851684d9f41cdec294f99edac",