Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Port #8324 (GBRA-268) providers/models + skills wave and the Particle recipe, without its #7257 commit

garrytanbc3cdda329ce
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5e2d4601d3..5b18589279 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -55,6 +55,18 @@ Every `gbrain ...` invocation a bundled skill shows now runs through the dispatc
OpenClaw serves a skill only whole. A SKILL.md larger than one read (64,000 characters on a model with 200k+ context, 32,000 at 100k to 200k, 16,000 below that, and a 32,768-byte page when the context window is unknown) gets "cannot be partially served" and nothing else. `company-brainify` (37 KB) is trimmed to 30 KB with the same steps, gates and checks. A unit test now fails when any SKILL.md that `gbrain skillpack scaffold --harness openclaw --all` installs passes 32,000 bytes, or when anything gbrain writes for OpenClaw names `skills_read`, OpenClaw's deferred skill tool, which fails when called directly. In harness-evals, a listed skill was followed on 1-3% of turns and a per-turn rule on 97-100%. `gbrain setup openclaw` already installs that rule; it now says the rule is the primary route, `skillpack scaffold --harness openclaw` says its skills are the fallback, and INSTALL_FOR_AGENTS.md and docs/mcp/OPENCLAW.md lead with the rule.
+### Providers and skills
+
+**Six provider and skill bugs fixed (#8142, #8143), and Particle joins as a chat provider.**
+
+- **Particle is a chat and expansion provider.** Set `PARTICLE_API_KEY` and use `particle:particle-1` (the id Particle's responses report, `particle-ai/particle-1`, works too). It runs over Chat Completions at `https://api.particle.ai/v1`, with tools, the subagent loop, prompt caching and a 1,048,576-token context; point `provider_base_urls.particle` at `https://us.api.particle.ai/v1` to keep traffic in the US. Spend caps price it at $0.25 input and $1.00 output per million tokens, with reasoning billed as output; cached input (listed at $0.03) is priced at the input rate until that rate is verified. A `thinking: 'off'` call such as an eval judge sends `reasoning_effort: 'none'` and keeps its requested output cap, and reasoning text never becomes answer text. No default model changed.
+- **A System One provider that refuses every call no longer reads as "budget exhausted" (#7272).** A decide call the provider refuses with a 4xx (402 billing, 401/403 auth, 400/404 model) never ran, so it now costs $0. Before, each refusal was charged its estimate, the daily budget filled with calls that never ran, and `decide status`, doctor and every slot reported `budget_exhausted` instead of the provider error. A 429, 5xx, timeout or transport failure keeps its charge.
+- **An embedding migration keeps a provider URL set with `gbrain config set` (#7666).** After the switch committed, the migration rebuilt its AI gateway from file and env config only, so a `provider_base_urls.<provider>` override in the database (a local Ollama on a non-default port) vanished and every re-embed failed with `Cannot connect to API`. The gateway now keeps the database overlay; file and env still win per key, and nothing from the database is written to the config file.
+- **A `deepseek:` model pointed at another OpenAI-compatible endpoint gets room to think (#7662).** With `provider_base_urls.deepseek` on another origin (Ollama Cloud, a proxy), gbrain still sent DeepSeek's thinking switch and the small judge cap that assumes it works, so a model that kept thinking used the whole cap and every `facts relink` judgement came back `model_unparseable`. That route now gets no switch and the thinking-model output headroom, priced the same way. The native DeepSeek origin, any path on it included, is unchanged.
+- **`openrouter:voyageai/voyage-*` embeddings are priced (#7034).** OpenRouter names Voyage's models `voyageai/<model>`, which missed the `voyage:` price rows, so a capped `gbrain embed` stopped with `no_pricing`. They now price from those rows (OpenRouter's rates are the same).
+- **The bootstrap interview saves an OpenRouter key as `openrouter_api_key` (#7977).** A `sk-or-v1-` key matched the OpenAI `sk-` prefix and was saved as `openai_api_key`.
+- **daily-task-manager names its page by the slug `ops/tasks` (#7932).** Its tool calls used `ops/tasks.md`, a different slug, so `get_page` missed the existing task list and the first-run rule could start a second one.
+
## [0.60.620.0] - 2026-11-09
**A diverged managed checkout now publishes its local commits on refresh by default when Git durability is on, after a secret scan of those commits.** Commits a script made with plain `git commit` in a managed checkout used to strand there whenever the remote moved: every `gbrain sources refresh` refused `refresh_diverged` and asked the user, unless `sources.refresh_publish_diverged` was set to `true`. With the setting unset, a worktree whose Git durability is on (`gbrain sources writer git-durability <source> --enable`, or the legacy hook) now publishes them itself: the local commits merged with the upstream in memory, never a rebase or force-push, then the fast-forward. The publish child scans, under its publish lock and for the exact commits it pushes, what they add: commit messages, added lines (including a value a later commit removed) and merge-commit conflict resolutions. A value that looks like a secret, added text too large to scan, or a commit that changes `.gbrain-scan-allow` or a `.gitattributes` refuses the new `publish_secret_found` naming the file, line, rule and commit, never the value, with nothing pushed; commits the scan cannot read in full refuse `publish_scan_unreadable` instead. The rewritten-upstream refusal and the `--expect-remote` bound are unchanged. `false` turns it off; `true` still publishes with durability off.
diff --git a/docs/architecture/decide.md b/docs/architecture/decide.md
index 5f011ea235..3ea545da09 100644
--- a/docs/architecture/decide.md
+++ b/docs/architecture/decide.md
@@ -143,7 +143,11 @@ with the background-work drain (500 ms bound at CLI exit). Retention:
`decide.receipts.retention_days` (7), pruned by the cycle `purge` phase. The
daily cap sums `decide_spend` for the UTC day (third-party only; cached 60 s;
soft in both directions); remote-triggered spend is capped by
-`decide.budget.remote_share`.
+`decide.budget.remote_share`. A batch the provider refuses with a 4xx other
+than 408 or 429 (402 billing, 401/403 auth, 400/404 model) never ran, so its
+row is `failed` at $0 and the provider error is not hidden behind
+`budget_exhausted` (#7272); a 429, 5xx, timeout or transport failure keeps its
+estimated charge.
### S9 proposals and sweep state
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.md
index c422f6283d..fde9291aee 100644
--- a/docs/architecture/key-files/core-ai.md
+++ b/docs/architecture/key-files/core-ai.md
@@ -26,7 +26,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ai/fallback-hop-queue.ts`: the process-level queue for the first hop's `chat_fallback_hop` notice (at most one per process; type-only imports so every drain site loads it cheaply). Drained by stdio MCP dispatch, the CLI op notice channel (`src/cli/op-notices.ts`) and `finishCliTeardown`; never by HTTP, because the notice names models.
- `src/core/ai/chat-fallback-planes.ts`: where the effective `chat_fallback_chain` comes from, read without network, subprocess or inference. `readChatFallbackPlanes(db)` reads env `GBRAIN_CHAT_FALLBACK_CHAIN` > the config.json key > the DB row (`parseDbChatFallbackChain` in `config-db-merge.ts`) with the loader's rule that the first plane that speaks wins even when its value yields no chain, and returns the winner, shadowed values, unreadable planes and the `chat_fallback_on_refusal` value with its plane. `diagnoseChatFallbackEntry` checks one entry by presence: `provider:model` parse, known provider with chat, the provider's own credential (recipe env keys or `authPresent`; for `claude-cli` the binary on PATH or `GBRAIN_CLAUDE_CLI_BIN`), and a price when a key in `USER_CHAT_CAP_KEYS` sets a user cap. `chatFallbackRemovalFix` is the per-plane removal guidance (DB `gbrain config unset chat_fallback_chain` with `destructive` consent → `ask_user`; env/file are the user's, with the restart note). Consumers: the `chat_fallback_chain` doctor check and the `behavior_changes` notice.
- `src/core/ai/sdk-warnings.ts` — AI SDK provider warnings to stderr (#5892). The gateway calls `installAiSdkWarningWriter()` when it loads, which sets `globalThis.AI_SDK_LOG_WARNINGS` to a writer with the `ai` logger signature (`{ warnings, provider, model }`) that prints each warning in the SDK's own wording to stderr and never the SDK's `console.info` banner, which landed on stdout and broke `--json` output (the claude-cli model's v2-compat notice fires on every process's first call). A user-set value (`false` or a function) is kept. Tests: `ai-sdk-warnings.test.ts`, `json-stdout-ai-warnings.test.ts`.
-- `src/core/ai/thinking-off.ts`: the per-route mapping behind `ChatOpts.thinking: 'off'` (#5331). `thinkingOffControl(modelStr)` is the per-model capability table: the provider-options namespace and keys to set, and whether they turn reasoning off (`disables`) or only set its floor. Full off: native `anthropic`, `deepseek`, `openrouter` with a `deepseek/` model (`thinking: { type: 'disabled' }`), Gemini 2.5 Flash/Flash-Lite (`thinkingConfig.thinkingBudget: 0`), OpenAI gpt-5.1/5.2/5.4/5.5/5.6 (`reasoningEffort: 'none'`). Floor: Gemini 2.5 Pro (`thinkingBudget: 128`), Gemini 3.x (`thinkingLevel` `minimal`, or `low` on 3.7/3.8 Flash and 3.x Pro, where `minimal` is a 400), gpt-5/-mini/-nano (`minimal`), o-series (`low`). Other Gemini 3+ and OpenAI gpt-5/o-series reasoning ids get no option and the headroom. gpt-6 ids have no row (the pinned @ai-sdk/openai drops their effort, and no live check measured them), so they keep the requested cap that fence repair's measured default `openai:gpt-6.1-sol` is costed against. Only native recipes get an option; the two Google fields are never sent together. `applyThinkingOff` sets the keys, replacing a configured value under the same key while siblings such as `cacheControl` or `promptCacheKey` survive; `chat()` applies it after the call-scoped `providerOptions` merge, on the resolved recipe. `thinkingOffMaxOutputTokens` keeps the requested cap where reasoning turns off and raises a route that keeps reasoning (a floor row, or no row and `isThinkingModel`) to the thinking headroom. gateway.ts `thinkingOffOutputCap(model, requested)` wraps it for `chat()` and for the takes-quality and cross-modal preflight estimates, so they price the cap the call sends. Callers: those two judges and the synthesize triage judge. Rows were checked live on 2026-10-07 (`docs/fix-wave-notes/capy-wave-9-followups.md`). Pinned by `test/ai/chat-thinking-off.test.ts` (request bodies per route against a local stub, estimate parity per default panel model) and `test/ai/gateway-chat.test.ts`.
+- `src/core/ai/thinking-off.ts`: the per-route mapping behind `ChatOpts.thinking: 'off'` (#5331). `thinkingOffControl(modelStr)` is the per-model capability table: the provider-options namespace and keys to set, and whether they turn reasoning off (`disables`) or only set its floor. Full off: native `anthropic`, `deepseek`, `openrouter` with a `deepseek/` model (`thinking: { type: 'disabled' }`), Gemini 2.5 Flash/Flash-Lite (`thinkingConfig.thinkingBudget: 0`), OpenAI gpt-5.1/5.2/5.4/5.5/5.6 and native `particle` (`reasoningEffort: 'none'`, sent as `reasoning_effort` on Chat Completions; pinned by `test/ai/recipe-particle.test.ts`). Floor: Gemini 2.5 Pro (`thinkingBudget: 128`), Gemini 3.x (`thinkingLevel` `minimal`, or `low` on 3.7/3.8 Flash and 3.x Pro, where `minimal` is a 400), gpt-5/-mini/-nano (`minimal`), o-series (`low`). Other Gemini 3+ and OpenAI gpt-5/o-series reasoning ids get no option and the headroom. gpt-6 ids have no row (the pinned @ai-sdk/openai drops their effort, and no live check measured them), so they keep the requested cap that fence repair's measured default `openai:gpt-6.1-sol` is costed against. Only native recipes get an option; the two Google fields are never sent together. `applyThinkingOff` sets the keys, replacing a configured value under the same key while siblings such as `cacheControl` or `promptCacheKey` survive; `chat()` applies it after the call-scoped `providerOptions` merge, on the resolved recipe. `thinkingOffMaxOutputTokens` keeps the requested cap where reasoning turns off and raises a route that keeps reasoning (a floor row, or no row and `isThinkingModel`) to the thinking headroom. gateway.ts `thinkingOffOutputCap(model, requested)` wraps it for `chat()` and for the takes-quality and cross-modal preflight estimates, so they price the cap the call sends. Callers: those two judges and the synthesize triage judge. Rows were checked live on 2026-10-07 (`docs/fix-wave-notes/capy-wave-9-followups.md`). Pinned by `test/ai/chat-thinking-off.test.ts` (request bodies per route against a local stub, estimate parity per default panel model) and `test/ai/gateway-chat.test.ts`.
- `src/core/ai/model-resolver.ts` — Recipe-touchpoint validator. `assertTouchpoint(recipe, touchpoint, modelId)` checks the PROVIDER's capability only (anthropic has no embedding touchpoint; voyage/ollama have no chat) and never gates on the model id. Recipe `models:` arrays are informational — default-model selection (`models[0]` for `--model <provider>` shorthand and env-ready pickers), guard-test fixtures for the repo's own hardcoded defaults, and `gbrain providers list` display — NOT a runtime allowlist, so frontier models newer than a recipe work without a recipe PR. A nonexistent id surfaces as the provider's own `model_not_found` at call time; `gbrain models doctor` live-probes the configured models for a pre-flight check. Exception: `gateway.rerank()` keeps its own model-list check because each listed reranker id maps to a known request/response wire shape. `embeddingDimsForModel` matches recipe `model_dims` keys exactly first, then case-insensitively with BOTH sides folded (configured ids arrive cased, and user-editable recipe tables can carry cased keys; without the fold a cased id would fall through to `default_dims` and `gbrain init` would build a wrong-width column), before falling back to `default_dims`.
diff --git a/docs/integrations/embedding-providers.md b/docs/integrations/embedding-providers.md
index 97004af01f..af722ee598 100644
--- a/docs/integrations/embedding-providers.md
+++ b/docs/integrations/embedding-providers.md
@@ -40,6 +40,7 @@ The resolved provider + dimensions get persisted to `~/.gbrain/config.json` atom
| `anthropic` | (no embedding model — chat only) | — | — | — | — |
| `deepseek` | (no embedding model — chat only) | — | — | — | — |
| `groq` | (no embedding model — chat only) | — | — | — | — |
+| `particle` | (no embedding model — chat only: `particle:particle-1`, `PARTICLE_API_KEY`) | — | — | — | — |
**Note on local providers.** Ollama, llama-server and LM Studio have no required API key, so they don't show up in env-detection auto-pick. Pick them explicitly with `--embedding-model ollama:<model>` to avoid silently routing to a daemon that may not be running. Ollama can also run local chat/expansion models; set those routes explicitly with `gbrain config set models.chat ollama:<model>` and related per-task model keys.
diff --git a/plugin-variants/gbrain-daily/skills/daily-task-manager/SKILL.md b/plugin-variants/gbrain-daily/skills/daily-task-manager/SKILL.md
index 449f0cccab..8d050dc503 100644
--- a/plugin-variants/gbrain-daily/skills/daily-task-manager/SKILL.md
+++ b/plugin-variants/gbrain-daily/skills/daily-task-manager/SKILL.md
@@ -26,7 +26,7 @@ when_to_use: "Use when the user asks: \"add task\", \"complete task\", \"what ar
## Contract
This skill guarantees:
-- Tasks stored as a brain page (`ops/tasks.md`) with structured format and a stable `id` per task
+- Tasks stored as a brain page (slug `ops/tasks`, file `ops/tasks.md`) with structured format and a stable `id` per task
- Task lifecycle: add → in-progress → complete | defer | remove
- Priority levels: P0 (urgent), P1 (today), P2 (this week), P3 (backlog)
- Completed tasks archived with completion date; deferred tasks carry a target date + reason
@@ -38,14 +38,14 @@ This skill guarantees:
After every action, report a structured result so callers (including sub-agents) can chain reliably:
```
-{action, task_id, status: ok|not_found|ambiguous|needs_confirmation, priority, date, page: "ops/tasks.md", saved: true|false}
+{action, task_id, status: ok|not_found|ambiguous|needs_confirmation, priority, date, page: "ops/tasks", saved: true|false}
```
For `review`, return the grouped active-task list instead of a single task_id. When invoked with the trigger "task list json", return a JSON array of task objects `{id, description, priority, due, status}` instead of markdown.
## Tool Interface
-Use ONLY the declared tools. `get_page("ops/tasks.md")` to read, `put_page("ops/tasks.md", …)` to write, `add_timeline_entry` for the audit trail, `search` for cross-referencing. Do not shell out to `gbrain` CLI verbs from this skill; the tools are the interface. (When the user runs this manually outside an agent, the CLI equivalents are `gbrain get ops/tasks` / `gbrain put ops/tasks` — equivalents only, not the skill's interface.)
+Use ONLY the declared tools. `get_page("ops/tasks")` to read, `put_page("ops/tasks", …)` to write, `add_timeline_entry` for the audit trail, `search` for cross-referencing. Do not shell out to `gbrain` CLI verbs from this skill; the tools are the interface. (When the user runs this manually outside an agent, the CLI equivalents are `gbrain get ops/tasks` / `gbrain put ops/tasks` — equivalents only, not the skill's interface.)
## Action Routing
@@ -58,7 +58,7 @@ Map user intent deterministically before touching state:
## Phases
-1. **Load.** `get_page("ops/tasks.md")`. **First run:** if the page does not exist, create it from the Output Format template, then proceed.
+1. **Load.** `get_page("ops/tasks")`. **First run:** if the page does not exist, create it from the Output Format template, then proceed.
2. **Validate.** Determine the action via Action Routing. If required fields are missing (see per-action rules), ask ONE concise clarification before mutating state. Never fabricate priorities, due dates, or defer reasons.
3. **Identify the target task** (complete/defer/remove): match by `id` when given; otherwise fuzzy-match description against ACTIVE tasks only. Zero matches → return `not_found`, do not mutate. Multiple matches → list candidates with IDs, return `ambiguous`, do not mutate.
4. **Execute:**
@@ -67,16 +67,16 @@ Map user intent deterministically before touching state:
- **Defer:** Require a target date/timeframe AND a reason; ask if missing. Move to Deferred preserving original text, ID, and priority unless the user changes them.
- **Remove:** Destructive — require explicit confirmation unless the user's message already contains it. Prefer suggesting complete or defer.
- **Review:** Read-only. Never mutates. Active tasks grouped by priority, IDs shown.
-5. **Save.** `put_page("ops/tasks.md")` after any mutation. Diff-mindset: touch only the affected lines; preserve all other content, including sections this skill doesn't recognize.
+5. **Save.** `put_page("ops/tasks")` after any mutation. Diff-mindset: touch only the affected lines; preserve all other content, including sections this skill doesn't recognize.
## Edge Cases
- **First run:** page missing → create from template before acting; `status: ok`, note "initialized".
-- **Malformed page:** if `ops/tasks.md` exists but doesn't match the schema, do NOT rewrite it wholesale. Append/edit within it minimally, preserve unknown content verbatim, and flag the malformation in the reply.
+- **Malformed page:** if `ops/tasks` exists but doesn't match the schema, do NOT rewrite it wholesale. Append/edit within it minimally, preserve unknown content verbatim, and flag the malformation in the reply.
- **Retry/duplicate add:** if an identical description already exists in active tasks, do not add a duplicate — report the existing task ID instead.
- **Dates:** ISO 8601 (`YYYY-MM-DD`) everywhere. Compute "today"/"next week" with code/clock, never guess.
-- **Page identifier:** always `ops/tasks.md` (with extension) in tool calls; this is the single canonical location.
-- **Single-writer assumption (concurrency limitation).** The task cycle is read-modify-write: `get_page("ops/tasks.md")` → edit → `put_page("ops/tasks.md")`. `put_page` replaces the WHOLE page and has no compare-and-swap, so two mutations that interleave are last-writer-wins: the second `put_page` overwrites the first's change (a completed task reappears, an added task vanishes), and the `t-YYYYMMDD-NN` minting can hand the same ordinal to two concurrent adds (duplicate IDs). Serialize task edits — never run parallel task mutations (multiple subagents, concurrent chat turns) against `ops/tasks.md`. If a mutation might race, re-`get_page` immediately before `put_page` and re-derive the next free ordinal from the freshly-read page.
+- **Page identifier:** always the slug `ops/tasks` (no `.md`) in tool calls; this is the single canonical location (`ops/tasks.md` is a different slug and misses it).
+- **Single-writer assumption (concurrency limitation).** The task cycle is read-modify-write: `get_page("ops/tasks")` → edit → `put_page("ops/tasks")`. `put_page` replaces the WHOLE page and has no compare-and-swap, so two mutations that interleave are last-writer-wins: the second `put_page` overwrites the first's change (a completed task reappears, an added task vanishes), and the `t-YYYYMMDD-NN` minting can hand the same ordinal to two concurrent adds (duplicate IDs). Serialize task edits — never run parallel task mutations (multiple subagents, concurrent chat turns) against `ops/tasks`. If a mutation might race, re-`get_page` immediately before `put_page` and re-derive the next free ordinal from the freshly-read page.
## Output Format
@@ -114,7 +114,7 @@ After a mutation: one concise line — action, task ID, priority/status, relevan
Follow the [agent operator protocol](../conventions/agent-operator-protocol.md) for any gbrain error `code`, exit code, `[AGENT]` block or notice block. Specific to this skill:
-- The tasks page update returns `revision_conflict`: re-read `ops/tasks.md`, re-apply the one task change, and save; never overwrite the whole list from an old read.
+- The tasks page update returns `revision_conflict`: re-read `ops/tasks`, re-apply the one task change, and save; never overwrite the whole list from an old read.
- `write_pending` (exit 10): report `saved: false` with the pending receipt and poll `gbrain write-request <request_id>`; do not tell the user the task is recorded yet.
- Ambiguous or missing task id: return `ambiguous` / `not_found` and ask which task; never mutate the closest match.
@@ -130,12 +130,12 @@ Each with its corrective action:
- Using undeclared tools or CLI verbs → `get_page`/`put_page`/`search`/`add_timeline_entry` only.
- Fabricating due dates, priorities, or reasons → never invent required fields; ask.
- Unbounded list growth → when Backlog exceeds ~20 items, prompt a weekly review.
-- Storing tasks outside the brain page → everything lives in `ops/tasks.md` (searchable).
-- Running parallel task mutations against `ops/tasks.md` → last-writer-wins whole-page `put_page` silently loses updates and mints duplicate IDs; serialize edits, re-read immediately before writing.
+- Storing tasks outside the brain page → everything lives in `ops/tasks` (searchable).
+- Running parallel task mutations against `ops/tasks` → last-writer-wins whole-page `put_page` silently loses updates and mints duplicate IDs; serialize edits, re-read immediately before writing.
## Design Rationale (failure modes this version closes)
- **Interface drift:** an earlier version declared `get_page`/`put_page` as tools but instructed CLI verbs in the body — models picked one at random. The declared tools are now the interface; CLI is relegated to a human-equivalent note.
- **Unmatchable tasks:** without task IDs, "complete the deploy task" against two similar tasks silently mutated the wrong one. Stable `t-YYYYMMDD-NN` IDs + fail-closed ambiguity handling fix this.
-- **First-run crash:** assuming `ops/tasks.md` exists made a missing page undefined behavior. Create-from-template on first run fixes this.
+- **First-run crash:** assuming `ops/tasks` exists made a missing page undefined behavior. Create-from-template on first run fixes this.
- **Wholesale overwrite risk:** "write updated task list" invited full-page rewrites that drop concurrent edits. Minimal-diff mandate + preserve-unknown-content rule fix this.
diff --git a/plugin/skills/daily-task-manager/SKILL.md b/plugin/skills/daily-task-manager/SKILL.md
index 449f0cccab..8d050dc503 100644
--- a/plugin/skills/daily-task-manager/SKILL.md
+++ b/plugin/skills/daily-task-manager/SKILL.md
@@ -26,7 +26,7 @@ when_to_use: "Use when the user asks: \"add task\", \"complete task\", \"what ar
## Contract
This skill guarantees:
-- Tasks stored as a brain page (`ops/tasks.md`) with structured format and a stable `id` per task
+- Tasks stored as a brain page (slug `ops/tasks`, file `ops/tasks.md`) with structured format and a stable `id` per task
- Task lifecycle: add → in-progress → complete | defer | remove
- Priority levels: P0 (urgent), P1 (today), P2 (this week), P3 (backlog)
- Completed tasks archived with completion date; deferred tasks carry a target date + reason
@@ -38,14 +38,14 @@ This skill guarantees:
After every action, report a structured result so callers (including sub-agents) can chain reliably:
```
-{action, task_id, status: ok|not_found|ambiguous|needs_confirmation, priority, date, page: "ops/tasks.md", saved: true|false}
+{action, task_id, status: ok|not_found|ambiguous|needs_confirmation, priority, date, page: "ops/tasks", saved: true|false}
```
For `review`, return the grouped active-task list instead of a single task_id. When invoked with the trigger "task list json", return a JSON array of task objects `{id, description, priority, due, status}` instead of markdown.
## Tool Interface
-Use ONLY the declared tools. `get_page("ops/tasks.md")` to read, `put_page("ops/tasks.md", …)` to write, `add_timeline_entry` for the audit trail, `search` for cross-referencing. Do not shell out to `gbrain` CLI verbs from this skill; the tools are the interface. (When the user runs this manually outside an agent, the CLI equivalents are `gbrain get ops/tasks` / `gbrain put ops/tasks` — equivalents only, not the skill's interface.)
+Use ONLY the declared tools. `get_page("ops/tasks")` to read, `put_page("ops/tasks", …)` to write, `add_timeline_entry` for the audit trail, `search` for cross-referencing. Do not shell out to `gbrain` CLI verbs from this skill; the tools are the interface. (When the user runs this manually outside an agent, the CLI equivalents are `gbrain get ops/tasks` / `gbrain put ops/tasks` — equivalents only, not the skill's interface.)
## Action Routing
@@ -58,7 +58,7 @@ Map user intent deterministically before touching state:
## Phases
-1. **Load.** `get_page("ops/tasks.md")`. **First run:** if the page does not exist, create it from the Output Format template, then proceed.
+1. **Load.** `get_page("ops/tasks")`. **First run:** if the page does not exist, create it from the Output Format template, then proceed.
2. **Validate.** Determine the action via Action Routing. If required fields are missing (see per-action rules), ask ONE concise clarification before mutating state. Never fabricate priorities, due dates, or defer reasons.
3. **Identify the target task** (complete/defer/remove): match by `id` when given; otherwise fuzzy-match description against ACTIVE tasks only. Zero matches → return `not_found`, do not mutate. Multiple matches → list candidates with IDs, return `ambiguous`, do not mutate.
4. **Execute:**
@@ -67,16 +67,16 @@ Map user intent deterministically before touching state:
- **Defer:** Require a target date/timeframe AND a reason; ask if missing. Move to Deferred preserving original text, ID, and priority unless the user changes them.
- **Remove:** Destructive — require explicit confirmation unless the user's message already contains it. Prefer suggesting complete or defer.
- **Review:** Read-only. Never mutates. Active tasks grouped by priority, IDs shown.
-5. **Save.** `put_page("ops/tasks.md")` after any mutation. Diff-mindset: touch only the affected lines; preserve all other content, including sections this skill doesn't recognize.
+5. **Save.** `put_page("ops/tasks")` after any mutation. Diff-mindset: touch only the affected lines; preserve all other content, including sections this skill doesn't recognize.
## Edge Cases
- **First run:** page missing → create from template before acting; `status: ok`, note "initialized".
-- **Malformed page:** if `ops/tasks.md` exists but doesn't match the schema, do NOT rewrite it wholesale. Append/edit within it minimally, preserve unknown content verbatim, and flag the malformation in the reply.
+- **Malformed page:** if `ops/tasks` exists but doesn't match the schema, do NOT rewrite it wholesale. Append/edit within it minimally, preserve unknown content verbatim, and flag the malformation in the reply.
- **Retry/duplicate add:** if an identical description already exists in active tasks, do not add a duplicate — report the existing task ID instead.
- **Dates:** ISO 8601 (`YYYY-MM-DD`) everywhere. Compute "today"/"next week" with code/clock, never guess.
-- **Page identifier:** always `ops/tasks.md` (with extension) in tool calls; this is the single canonical location.
-- **Single-writer assumption (concurrency limitation).** The task cycle is read-modify-write: `get_page("ops/tasks.md")` → edit → `put_page("ops/tasks.md")`. `put_page` replaces the WHOLE page and has no compare-and-swap, so two mutations that interleave are last-writer-wins: the second `put_page` overwrites the first's change (a completed task reappears, an added task vanishes), and the `t-YYYYMMDD-NN` minting can hand the same ordinal to two concurrent adds (duplicate IDs). Serialize task edits — never run parallel task mutations (multiple subagents, concurrent chat turns) against `ops/tasks.md`. If a mutation might race, re-`get_page` immediately before `put_page` and re-derive the next free ordinal from the freshly-read page.
+- **Page identifier:** always the slug `ops/tasks` (no `.md`) in tool calls; this is the single canonical location (`ops/tasks.md` is a different slug and misses it).
+- **Single-writer assumption (concurrency limitation).** The task cycle is read-modify-write: `get_page("ops/tasks")` → edit → `put_page("ops/tasks")`. `put_page` replaces the WHOLE page and has no compare-and-swap, so two mutations that interleave are last-writer-wins: the second `put_page` overwrites the first's change (a completed task reappears, an added task vanishes), and the `t-YYYYMMDD-NN` minting can hand the same ordinal to two concurrent adds (duplicate IDs). Serialize task edits — never run parallel task mutations (multiple subagents, concurrent chat turns) against `ops/tasks`. If a mutation might race, re-`get_page` immediately before `put_page` and re-derive the next free ordinal from the freshly-read page.
## Output Format
@@ -114,7 +114,7 @@ After a mutation: one concise line — action, task ID, priority/status, relevan
Follow the [agent operator protocol](../conventions/agent-operator-protocol.md) for any gbrain error `code`, exit code, `[AGENT]` block or notice block. Specific to this skill:
-- The tasks page update returns `revision_conflict`: re-read `ops/tasks.md`, re-apply the one task change, and save; never overwrite the whole list from an old read.
+- The tasks page update returns `revision_conflict`: re-read `ops/tasks`, re-apply the one task change, and save; never overwrite the whole list from an old read.
- `write_pending` (exit 10): report `saved: false` with the pending receipt and poll `gbrain write-request <request_id>`; do not tell the user the task is recorded yet.
- Ambiguous or missing task id: return `ambiguous` / `not_found` and ask which task; never mutate the closest match.
@@ -130,12 +130,12 @@ Each with its corrective action:
- Using undeclared tools or CLI verbs → `get_page`/`put_page`/`search`/`add_timeline_entry` only.
- Fabricating due dates, priorities, or reasons → never invent required fields; ask.
- Unbounded list growth → when Backlog exceeds ~20 items, prompt a weekly review.
-- Storing tasks outside the brain page → everything lives in `ops/tasks.md` (searchable).
-- Running parallel task mutations against `ops/tasks.md` → last-writer-wins whole-page `put_page` silently loses updates and mints duplicate IDs; serialize edits, re-read immediately before writing.
+- Storing tasks outside the brain page → everything lives in `ops/tasks` (searchable).
+- Running parallel task mutations against `ops/tasks` → last-writer-wins whole-page `put_page` silently loses updates and mints duplicate IDs; serialize edits, re-read immediately before writing.
## Design Rationale (failure modes this version closes)
- **Interface drift:** an earlier version declared `get_page`/`put_page` as tools but instructed CLI verbs in the body — models picked one at random. The declared tools are now the interface; CLI is relegated to a human-equivalent note.
- **Unmatchable tasks:** without task IDs, "complete the deploy task" against two similar tasks silently mutated the wrong one. Stable `t-YYYYMMDD-NN` IDs + fail-closed ambiguity handling fix this.
-- **First-run crash:** assuming `ops/tasks.md` exists made a missing page undefined behavior. Create-from-template on first run fixes this.
+- **First-run crash:** assuming `ops/tasks` exists made a missing page undefined behavior. Create-from-template on first run fixes this.
- **Wholesale overwrite risk:** "write updated task list" invited full-page rewrites that drop concurrent edits. Minimal-diff mandate + preserve-unknown-content rule fix this.
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 88e94a2cb9..7f09a8b359 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -11,7 +11,7 @@ src/commands/extract-conversation-facts.ts 1949 ratchet grown v0.46.x per-provid
src/commands/extract.ts 2700 ratchet +8 GBRA-130 A-1: extract --stale --retry-held flag, help lines and the managed result failure fields (logic in core/persistence/links-maintenance.ts and links-extraction-holds.ts); grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page; +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale; +25 GBRA-69: extract --source db reads snapshots and publishes derived links BATCH_SIZE pages at a time (readPageSnapshotsBatch in core/page-snapshot-batch.ts, replay in derived-links.ts replaceDerivedLinksBatchOrReplay); +2 GBRA-75 w7: the --source db links walk refreshes planner statistics (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 13 P2.16 (#6272): both unmanaged DB link drains defer and count a page a concurrent writer moved (skipped_concurrent_write) instead of aborting the run (classifier and skip line in core/derived-links.ts); +3 fix wave 13 P2.18 (S4): extract all --source db stamps the pages both phases completed at one revision, in a finally (stampCompletedIntersection), instead of every links-phase page; +1 fix wave 13 P2.15 (#6273): --from-meetings exits non-zero while managed entity pages are still pending; +7 fix wave 13 PR2: extractFromDB split out of runExtract so runExtract stays under its function-size baseline; Wave B PR 2 (kept at the master 4e29d0904 merge): +3 PR 2 fix lane J1: extract --stale reads a segmented page block by block (extractSegmentedPageLinks, segmentedTimelineText) now that the stale list includes it; integrated at the master 4e29d0904 merge: 2635 measured; +23 fix wave 20 #6954: the fs walks and the slug-scoped extract collect lost link/timeline writes, stamp only the pages whose writes landed and throw extract_write_lost (helpers in core/extract-watermark.ts); fix wave 20 integration: lane 1 (#6808, +11) and lane 2 (#6954, +23) compose at 2677 measured; +16 #7394: --type/--since/--infer-dates on the file walk refuse with the --source db command beside the other --source db refusals, and the help says so; +5 GBRA-161 PR 5 (T-2, L-6): timeline retraction and the mention rebuild sweep are bound to the revision they read (PageRevisionConflictError import, the scanned-revision read and its FOR SHARE check); +2 GBRA-133: ExtractOpts.timeBudgetMs, forwarded to the managed stale-page pass so the cycle bounds a pass with no slug list
src/commands/jobs.ts 693 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codes; +1 #7142: doctor-refresh handler registration (logic in doctor/last-known.ts); +20 #7242 jobs wait: subcommand row, import, usage lines and its --help text with the exit codes (logic in jobs/wait.ts); +6 GBRA-283 B3a: runJobs enters the local scope (withLocalScope; scope store in core/engine-scope-store.ts), the entry wrapper and its import cannot move
src/commands/serve-http.ts 947 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts); +1 #6589: imports loadServeConfigs (operations see the DB-plane config read once at startup; logic in mcp/serve-config.ts); +5 #6858 ask 6: on-commit HEAD watcher start/stop (watcher in core/serve-head-watcher.ts); +4 GBRA-199: serve --http --advertise parse, help line and pass-through (logic in mcp/surface.ts parseAdvertiseFlag); +6 GBRA-283 B3a: runServeHttp enters the local scope (withLocalScope; scope store in core/engine-scope-store.ts), the entry wrapper and its import cannot move
-src/core/ai/gateway.ts 4571 ratchet +5 GBRA-274 B1.3: withoutBudgetTracker export (runs a rollout hook outside the run's budget scope; the budget AsyncLocalStorage is gateway-private, so it cannot move); +2 #6997: ChatResult.fallbackReason (interface field + doc; recorded in ai/chat-fallback.ts); +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same text; +5 #7176: expand() writes its chat_usage_log row (phase expansion) beside the budget record, and the guardedExpansion instance that names its invocation gateway.expand (ledger in ai/chat-usage.ts); +2 PR 4 (Wave B incremental derivation, transcripts) 4b round 4: chat() forwards a metered page step's providerRetries (BudgetTracker) as the SDK's maxRetries, so every attempt is one it reserved for; +24 GBRA-283 B2 (#8456): per-engine gateway state, the gw() accessor every config and model-cache read goes through (an embedded engine state or the process state), configure split into gatewayConfigOf, and configFor at the provider-resolution sites so a provider the engine lacks refuses before any call (state and refusal live in ai/engine-gateway.ts); +1 GBRA-283 B2: embedding diagnosis refuses a provider the embedded engine was not given; +1 GBRA-283 B2 (#8499 item 1): requireConfig refuses an unscoped call in a process holding embedded engines (engine_scope_missing; predicate in engine-scope.ts); +7 GBRA-283 B3a: every embed/chat/expand/rerank/toolLoop entry and requireConfig/configFor call refuseUnscoped (predicate and refusal in ai/engine-gateway.ts), the unscoped state, and the shrink/no_key/structured-output memory read through gw() (state in ai/engine-gateway.ts GatewayState)
+src/core/ai/gateway.ts 4573 ratchet +2 #7662 (from #8324): configureGateway hands base_urls to ai/thinking-off.ts and clearGatewayState clears them (the native-route check lives there); +5 GBRA-274 B1.3: withoutBudgetTracker export (runs a rollout hook outside the run's budget scope; the budget AsyncLocalStorage is gateway-private, so it cannot move); +2 #6997: ChatResult.fallbackReason (interface field + doc; recorded in ai/chat-fallback.ts); +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same text; +5 #7176: expand() writes its chat_usage_log row (phase expansion) beside the budget record, and the guardedExpansion instance that names its invocation gateway.expand (ledger in ai/chat-usage.ts); +2 PR 4 (Wave B incremental derivation, transcripts) 4b round 4: chat() forwards a metered page step's providerRetries (BudgetTracker) as the SDK's maxRetries, so every attempt is one it reserved for; +24 GBRA-283 B2 (#8456): per-engine gateway state, the gw() accessor every config and model-cache read goes through (an embedded engine state or the process state), configure split into gatewayConfigOf, and configFor at the provider-resolution sites so a provider the engine lacks refuses before any call (state and refusal live in ai/engine-gateway.ts); +1 GBRA-283 B2: embedding diagnosis refuses a provider the embedded engine was not given; +1 GBRA-283 B2 (#8499 item 1): requireConfig refuses an unscoped call in a process holding embedded engines (engine_scope_missing; predicate in engine-scope.ts); +7 GBRA-283 B3a: every embed/chat/expand/rerank/toolLoop entry and requireConfig/configFor call refuseUnscoped (predicate and refusal in ai/engine-gateway.ts), the unscoped state, and the shrink/no_key/structured-output memory read through gw() (state in ai/engine-gateway.ts GatewayState)
src/commands/sync.ts 566 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals); +13 #5984: SyncResult.drain / managedCursor and SyncOpts.drain / drainStartedAt interface fields (drain loop lives in persistence/sync-drain.ts); +1 #5984: SyncOpts.noBulk / bulk interface fields; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (510 measured); +2 #5984 lanes: SyncOpts.lanes field and the lanes progress-event field; +2 #6278: SyncResult.breaker interface field (the preparation-stall breaker verdict); +1 fix wave 13 P4.3 #6386: the JSON-output comment names writeJsonDocument for sync status/unblock; +2 fix wave 13 PR2: the transaction-pooler stderr line (P2.2) and the staged catch-up result field (P2.14, loop in commands/sync/perform.ts); +2 fix wave 15 P4.5 (#5459 adjacent): SyncResult.working_tree_kept interface field (the tree-walk keep lives in persistence/sync-discovery.ts); +4 #6643: SyncResult.retryWait / knockOns interface fields (recovery lives in persistence/sync-run.ts, sync-knock-on.ts); +2 #6696 (A7): SyncOpts.capacityPreflight interface field (preflight lives in persistence/sync-capacity-preflight.ts); +2 #6696 C1: SyncOpts.embedDeferred interface field (the cost gate's runtime embed deferral; an interface field cannot move), composed with PR A's SyncOpts.capacityPreflight; +2 #6693: SyncResult.replayedRemembers interface field (the post-sync replay lives in commands/sync/perform.ts and repair/failed-writes.ts); +12 #6712 PR 1: SyncResult.leaseHeld / inherited_options / cursorAdopted / cursorFanIn and SyncOpts.drainHolder / followDrainLease interface fields (the lease lives in persistence/sync-lease.ts, adoption in persistence/sync-cursor-key.ts and sync-admitted.ts); +2 #6712 PR 2 (L5): SyncResult.tail interface field (the tail lives in persistence/sync-tail.ts); +2 #6712 PR 2 integration: L4 ghostPages and L5 tail SyncResult interface fields both land (each lane raised 542->544 alone); +2 #6948: SyncResult.origin_twins_resolved interface field (the heal lives in repair/origin-twins-heal.ts); +5 #6712 PR 4b: SyncResult.pass / reconcile and SyncOpts.costApproved interface fields (an interface field cannot move; the pass summary and the pass reason union live in persistence/sync-pass-row.ts, the remote reconcile in sync-pass-apply.ts); lowered to 546 #6712 PR 4b lane C: SyncResult.cursorAdopted / cursorFanIn retired with the cursor engine; +2 #7167: SyncResult.writer interface field (a managed dry run reports the writer instead of waiting on it; the read lives in persistence/sync-dry-run-writer.ts); +6 G8a git-canonical: SyncOpts.canonicalOverride interface field and its doc comment (internal: only the conversion apply in persistence/git-conversion.ts passes it; applied in persistence/sync-discovery.ts); +2 #7866: SyncOpts.fullRound interface field and its doc comment (internal: the conversion strict passes in persistence/git-conversion.ts set it; read in persistence/sync-pass-run.ts); +1 #8007: SyncResult.storage_invalid_kept interface field (the keep lives in persistence/sync-discovery.ts); +2 GBRA-287: SyncResult.reexport_failures interface field (the re-export lives in commands/sync/full.ts); re-summed at the memory train #8481 merge with v0.60.576.0 (564 measured); +2 convergence PR A: SyncOpts.conversionBinding interface field and its doc comment (internal: only the conversion apply in persistence/git-conversion.ts passes it; applied in persistence/sync-pass.ts bindConversion)
src/core/cycle.ts 3351 ratchet +2 GBRA-130 C-2 (#6946): the sync phase reads an owned clone's pull block and reports it as pull_blocked (logic in url-clone.ts urlClonePullBlock/urlClonePullBlockSummary); +6 GBRA-130 A-1: the extract phase warns on failed or breaker-stopped stale drain pages (logic in cycle/connector-extract.ts staleDrainFailures); +1 W1 belief ledger: the extract phase runs the sampled belief drift reconcile (logic in belief/coverage-report.ts); +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence); +5 #6865: unindexed_files phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its line in the REPAIR_LANE_PHASES dispatch helper (logic in cycle/unindexed-files.ts); +2 fix wave 20 #6954: the extract phase warns on extract_write_lost and its stale drain retries the pages left due; +5 #7241: CycleOpts.onPhaseStart and its best-effort call in timePhase, so the autopilot-cycle job writes its current phase to minion_jobs.progress; +1 GBRA-133: the extract phase passes the stale-drain budget to its targeted pass when sync gave no slug list; +7 #7630 (GBRA-207): the sync phase refuses sync_anchor_relative when no source matches its directory and default's local_path is relative; re-summed at the memory train #8481 merge with v0.60.576.0 (3348 measured); +3 GST-1856: the purge phase drops applied-capture records past 90 days (logic in ingestion/applied-captures.ts purgeStaleAppliedCaptures)
src/core/cycle/synthesize.ts 3244 ratchet +3 #7805: each captured session synthesizes only into its own frozen source (routing import, the outer wrapper, the routing parameter; logic in cycle/synthesize-source-routing.ts); +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import); +3 wave 17 #6616: slug discovery and postprocessing share the canonical committed child outputs (loadCommittedSynthesisOutputs in synthesize-postprocess.ts; one call-site line, one parameter, one lookup line); lowered to 3224 by wave 17 #6642: the summary provenance section moved to summaryProvenanceLines in dream-provenance.ts; +6 GBRA-130 B-6 (#6860): surrogate-safe triage cuts (truncateUtf8) and the per-transcript verdict-cache write call site (logic in triage-backoff.ts VerdictCacheWrites); +2 GBRA-161 PR 4 (#7065): the synthesize phase activates each synthesized transcript's outputs as its generation (activateSynthesisGenerations import and call site; logic in cycle/synthesize-generations.ts); +8 GBRA-161 PR 5 (S-2): the dream summary publishes as a single-item dream_summary generation bound to its pre-run revision (publishSinglePage with a generation_fenced skip); +1 GBRA-60: a managed synthesis child carries dream_output (verify and stamp before put_page; cycle/synthesize-child-verify.ts)
diff --git a/scripts/setup-in-agent.sh b/scripts/setup-in-agent.sh
index 9463c3ae31..0f4ca7091a 100644
--- a/scripts/setup-in-agent.sh
+++ b/scripts/setup-in-agent.sh
@@ -92,7 +92,7 @@ chmod 700 "$gbrain_work/bundle/bun"
# recipe-coverage/parity test pins the standalone trampoline's literal pattern.
for gbrain_env_name in $(compgen -e); do
case "$gbrain_env_name" in
- GBRAIN_*|ANTHROPIC_*|AZURE_OPENAI_*|DASHSCOPE_*|DEEPSEEK_*|GEMINI_*|GOOGLE_GENERATIVE_AI_*|GROQ_*|LITELLM_*|LLAMA_SERVER_*|LMSTUDIO_*|MINIMAX_*|MISTRAL_*|MOONSHOT_*|NAN_*|NVIDIA_*|OLLAMA_*|OPENAI_*|OPENROUTER_*|PERPLEXITY_*|TOGETHER_*|VOYAGE_*|ZHIPUAI_*|DATABASE_URL|BUN_OPTIONS|NODE_OPTIONS|CLAUDE_CODE_OAUTH_TOKEN|*_API_KEY|*_API_TOKEN|*_CLIENT_SECRET) unset "$gbrain_env_name" ;;
+ GBRAIN_*|ANTHROPIC_*|AZURE_OPENAI_*|DASHSCOPE_*|DEEPSEEK_*|GEMINI_*|GOOGLE_GENERATIVE_AI_*|GROQ_*|LITELLM_*|LLAMA_SERVER_*|LMSTUDIO_*|MINIMAX_*|MISTRAL_*|MOONSHOT_*|NAN_*|NVIDIA_*|OLLAMA_*|OPENAI_*|OPENROUTER_*|PARTICLE_*|PERPLEXITY_*|TOGETHER_*|VOYAGE_*|ZHIPUAI_*|DATABASE_URL|BUN_OPTIONS|NODE_OPTIONS|CLAUDE_CODE_OAUTH_TOKEN|*_API_KEY|*_API_TOKEN|*_CLIENT_SECRET) unset "$gbrain_env_name" ;;
esac
done
export GBRAIN_HOME="$gbrain_work/setup-home" GBRAIN_SKIP_STARTUP_HOOKS=1
diff --git a/skills/daily-task-manager/SKILL.md b/skills/daily-task-manager/SKILL.md
index c5a2a14ccc..994a5809e1 100644
--- a/skills/daily-task-manager/SKILL.md
+++ b/skills/daily-task-manager/SKILL.md
@@ -25,7 +25,7 @@ upstream: daily-task-manager@fc834ee
## Contract
This skill guarantees:
-- Tasks stored as a brain page (`ops/tasks.md`) with structured format and a stable `id` per task
+- Tasks stored as a brain page (slug `ops/tasks`, file `ops/tasks.md`) with structured format and a stable `id` per task
- Task lifecycle: add → in-progress → complete | defer | remove
- Priority levels: P0 (urgent), P1 (today), P2 (this week), P3 (backlog)
- Completed tasks archived with completion date; deferred tasks carry a target date + reason
@@ -37,14 +37,14 @@ This skill guarantees:
After every action, report a structured result so callers (including sub-agents) can chain reliably:
```
-{action, task_id, status: ok|not_found|ambiguous|needs_confirmation, priority, date, page: "ops/tasks.md", saved: true|false}
+{action, task_id, status: ok|not_found|ambiguous|needs_confirmation, priority, date, page: "ops/tasks", saved: true|false}
```
For `review`, return the grouped active-task list instead of a single task_id. When invoked with the trigger "task list json", return a JSON array of task objects `{id, description, priority, due, status}` instead of markdown.
## Tool Interface
-Use ONLY the declared tools. `get_page("ops/tasks.md")` to read, `put_page("ops/tasks.md", …)` to write, `add_timeline_entry` for the audit trail, `search` for cross-referencing. Do not shell out to `gbrain` CLI verbs from this skill; the tools are the interface. (When the user runs this manually outside an agent, the CLI equivalents are `gbrain get ops/tasks` / `gbrain put ops/tasks` — equivalents only, not the skill's interface.)
+Use ONLY the declared tools. `get_page("ops/tasks")` to read, `put_page("ops/tasks", …)` to write, `add_timeline_entry` for the audit trail, `search` for cross-referencing. Do not shell out to `gbrain` CLI verbs from this skill; the tools are the interface. (When the user runs this manually outside an agent, the CLI equivalents are `gbrain get ops/tasks` / `gbrain put ops/tasks` — equivalents only, not the skill's interface.)
## Action Routing
@@ -57,7 +57,7 @@ Map user intent deterministically before touching state:
## Phases
-1. **Load.** `get_page("ops/tasks.md")`. **First run:** if the page does not exist, create it from the Output Format template, then proceed.
+1. **Load.** `get_page("ops/tasks")`. **First run:** if the page does not exist, create it from the Output Format template, then proceed.
2. **Validate.** Determine the action via Action Routing. If required fields are missing (see per-action rules), ask ONE concise clarification before mutating state. Never fabricate priorities, due dates, or defer reasons.
3. **Identify the target task** (complete/defer/remove): match by `id` when given; otherwise fuzzy-match description against ACTIVE tasks only. Zero matches → return `not_found`, do not mutate. Multiple matches → list candidates with IDs, return `ambiguous`, do not mutate.
4. **Execute:**
@@ -66,16 +66,16 @@ Map user intent deterministically before touching state:
- **Defer:** Require a target date/timeframe AND a reason; ask if missing. Move to Deferred preserving original text, ID, and priority unless the user changes them.
- **Remove:** Destructive — require explicit confirmation unless the user's message already contains it. Prefer suggesting complete or defer.
- **Review:** Read-only. Never mutates. Active tasks grouped by priority, IDs shown.
-5. **Save.** `put_page("ops/tasks.md")` after any mutation. Diff-mindset: touch only the affected lines; preserve all other content, including sections this skill doesn't recognize.
+5. **Save.** `put_page("ops/tasks")` after any mutation. Diff-mindset: touch only the affected lines; preserve all other content, including sections this skill doesn't recognize.
## Edge Cases
- **First run:** page missing → create from template before acting; `status: ok`, note "initialized".
-- **Malformed page:** if `ops/tasks.md` exists but doesn't match the schema, do NOT rewrite it wholesale. Append/edit within it minimally, preserve unknown content verbatim, and flag the malformation in the reply.
+- **Malformed page:** if `ops/tasks` exists but doesn't match the schema, do NOT rewrite it wholesale. Append/edit within it minimally, preserve unknown content verbatim, and flag the malformation in the reply.
- **Retry/duplicate add:** if an identical description already exists in active tasks, do not add a duplicate — report the existing task ID instead.
- **Dates:** ISO 8601 (`YYYY-MM-DD`) everywhere. Compute "today"/"next week" with code/clock, never guess.
-- **Page identifier:** always `ops/tasks.md` (with extension) in tool calls; this is the single canonical location.
-- **Single-writer assumption (concurrency limitation).** The task cycle is read-modify-write: `get_page("ops/tasks.md")` → edit → `put_page("ops/tasks.md")`. `put_page` replaces the WHOLE page and has no compare-and-swap, so two mutations that interleave are last-writer-wins: the second `put_page` overwrites the first's change (a completed task reappears, an added task vanishes), and the `t-YYYYMMDD-NN` minting can hand the same ordinal to two concurrent adds (duplicate IDs). Serialize task edits — never run parallel task mutations (multiple subagents, concurrent chat turns) against `ops/tasks.md`. If a mutation might race, re-`get_page` immediately before `put_page` and re-derive the next free ordinal from the freshly-read page.
+- **Page identifier:** always the slug `ops/tasks` (no `.md`) in tool calls; this is the single canonical location (`ops/tasks.md` is a different slug and misses it).
+- **Single-writer assumption (concurrency limitation).** The task cycle is read-modify-write: `get_page("ops/tasks")` → edit → `put_page("ops/tasks")`. `put_page` replaces the WHOLE page and has no compare-and-swap, so two mutations that interleave are last-writer-wins: the second `put_page` overwrites the first's change (a completed task reappears, an added task vanishes), and the `t-YYYYMMDD-NN` minting can hand the same ordinal to two concurrent adds (duplicate IDs). Serialize task edits — never run parallel task mutations (multiple subagents, concurrent chat turns) against `ops/tasks`. If a mutation might race, re-`get_page` immediately before `put_page` and re-derive the next free ordinal from the freshly-read page.
## Output Format
@@ -113,7 +113,7 @@ After a mutation: one concise line — action, task ID, priority/status, relevan
Follow the [agent operator protocol](../conventions/agent-operator-protocol.md) for any gbrain error `code`, exit code, `[AGENT]` block or notice block. Specific to this skill:
-- The tasks page update returns `revision_conflict`: re-read `ops/tasks.md`, re-apply the one task change, and save; never overwrite the whole list from an old read.
+- The tasks page update returns `revision_conflict`: re-read `ops/tasks`, re-apply the one task change, and save; never overwrite the whole list from an old read.
- `write_pending` (exit 10): report `saved: false` with the pending receipt and poll `gbrain write-request <request_id>`; do not tell the user the task is recorded yet.
- Ambiguous or missing task id: return `ambiguous` / `not_found` and ask which task; never mutate the closest match.
@@ -129,12 +129,12 @@ Each with its corrective action:
- Using undeclared tools or CLI verbs → `get_page`/`put_page`/`search`/`add_timeline_entry` only.
- Fabricating due dates, priorities, or reasons → never invent required fields; ask.
- Unbounded list growth → when Backlog exceeds ~20 items, prompt a weekly review.
-- Storing tasks outside the brain page → everything lives in `ops/tasks.md` (searchable).
-- Running parallel task mutations against `ops/tasks.md` → last-writer-wins whole-page `put_page` silently loses updates and mints duplicate IDs; serialize edits, re-read immediately before writing.
+- Storing tasks outside the brain page → everything lives in `ops/tasks` (searchable).
+- Running parallel task mutations against `ops/tasks` → last-writer-wins whole-page `put_page` silently loses updates and mints duplicate IDs; serialize edits, re-read immediately before writing.
## Design Rationale (failure modes this version closes)
- **Interface drift:** an earlier version declared `get_page`/`put_page` as tools but instructed CLI verbs in the body — models picked one at random. The declared tools are now the interface; CLI is relegated to a human-equivalent note.
- **Unmatchable tasks:** without task IDs, "complete the deploy task" against two similar tasks silently mutated the wrong one. Stable `t-YYYYMMDD-NN` IDs + fail-closed ambiguity handling fix this.
-- **First-run crash:** assuming `ops/tasks.md` exists made a missing page undefined behavior. Create-from-template on first run fixes this.
+- **First-run crash:** assuming `ops/tasks` exists made a missing page undefined behavior. Create-from-template on first run fixes this.
- **Wholesale overwrite risk:** "write updated task list" invited full-page rewrites that drop concurrent edits. Minimal-diff mandate + preserve-unknown-content rule fix this.
diff --git a/skills/skills.lock.history.json b/skills/skills.lock.history.json
index 47340be644..49f66c44d3 100644
--- a/skills/skills.lock.history.json
+++ b/skills/skills.lock.history.json
@@ -387,6 +387,7 @@
"fc00a04e2ff9f498bee9b0b636bceba9dcfdc869c35d9a983109f408170f0807"
],
"daily-task-manager/SKILL.md": [
+ "8ea2f89afcdd3cc84e0dc01ed4b5f6f1bae8c525bf717063e14cd2e15c3af23c",
"a0e019eb2b0c8aff5bf97889f30a3f13e61c0052289a79d00effd7b84177f4b0",
"cbec93c0d90829a9c3772722d69056616d3eddf13db6216f21f5b43c57282f40",
"e616f74a6befffc7bb64c0e29b2d2caa37c51bc470bca96df70101c772429d83",
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index c1c18d1808..45bd99692e 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -68,7 +68,7 @@
"correction-pipeline/routing-eval.jsonl": "7f8d96606a8d7bed3d79fdcee6904764c8abb9fa0b506adb414b5c4805b69d0b",
"cron-scheduler/SKILL.md": "0f5c3148ca419efe6c3e3c781e3bac4e107732b9bf7d55c05c2385686acfa7fd",
"cross-modal-review/SKILL.md": "fc00a04e2ff9f498bee9b0b636bceba9dcfdc869c35d9a983109f408170f0807",
- "daily-task-manager/SKILL.md": "e93264a83b5fd0a19b2f06a322b3a4ad92d418f6a968c1cd51f4bea79cbca4d9",
+ "daily-task-manager/SKILL.md": "8ea2f89afcdd3cc84e0dc01ed4b5f6f1bae8c525bf717063e14cd2e15c3af23c",
"daily-task-manager/routing-eval.jsonl": "e98b2592e65c26952242436a960d8b2061e375b269004a18c230cbcf1d692ff9",
"daily-task-prep/SKILL.md": "5ea839012b48761ed8d7a9bab056a2566587d6f7fe044e3907d77b20f8eec5ac",
"data-loss-gate/SKILL.md": "c1736e0985121e60ffeba993b68b5c722c9285220057b5ef72059f111aabcb18",
@@ -225,7 +225,7 @@
"skillpack-check/SKILL.md": "0d2d2d201ed72e19b47d7e3743b5bbdfb5c2655d1f34d29447c601fca3908f9e",
"skillpack-harvest/SKILL.md": "0f86314b58d25b5511809f567c04aedc3fba6fe35ed642ac52d8216ae365b6eb",
"skillpack-harvest/routing-eval.jsonl": "cb4783288e95af3132b32ecb40a54cffc095f57b36240f96a25c2d2adf5e68c6",
- "skills.lock.history.json": "a487a93c512dec8c6fab524e92363daca8041c40a54aa2a16a5c384aaa06e5a8",
+ "skills.lock.history.json": "db698bc81e97477c3e245b83708113aa7110b97b191d1a530c4e8a894298663b",
"smoke-test/SKILL.md": "f5099e1d2ab9dc6827096249e68414f7ae357c29b39fb069a54bb7fb74f414a5",
"soul-audit/SKILL.md": "7a48e180849f7502d332878c443397f90a3756f45caa94f76bcfcc7c997469c8",
"strategic-reading/SKILL.md": "ab2cd3adc79289374cfbc5cb3d5ee17f962fd8f7f3c997a1da708da0ed67797c",
diff --git a/src/commands/migrate-embeddings.ts b/src/commands/migrate-embeddings.ts
index e07ac2e254..f1be5849bd 100644
--- a/src/commands/migrate-embeddings.ts
+++ b/src/commands/migrate-embeddings.ts
@@ -348,8 +348,16 @@ export async function probeTargetReranker(
export async function persistEmbeddingFileConfig(
toModel: string,
toDims: number,
+ engine?: BrainEngine,
): Promise<void> {
- const { loadConfig, loadConfigFileOnly, saveConfig } = await import('../core/config.ts');
+ const { loadConfig, loadConfigFileOnly, loadConfigWithEngine, saveConfig } = await import('../core/config.ts');
+ // #7666: the gateway this process embeds with after apply must keep the
+ // DB-plane overlay (provider_base_urls.*, DB-plane credentials) the probe
+ // ran against; file/env still win per key, and nothing DB-sourced is saved.
+ const effective = async () => {
+ const fileEnv = loadConfig();
+ return engine && fileEnv ? await loadConfigWithEngine(engine, fileEnv) : fileEnv;
+ };
const { configureGateway } = await import('../core/ai/gateway.ts');
const { buildGatewayConfig } = await import('../core/ai/build-gateway-config.ts');
// Round-2 #2: read the FILE plane, not env-merged loadConfig(). Persisting
@@ -368,7 +376,7 @@ export async function persistEmbeddingFileConfig(
const envPinsTarget = envFullyPinsTarget(toModel, toDims);
if (envPinsTarget) {
serr(' [migrate] no ~/.gbrain/config.json — env-canonical mode: GBRAIN_EMBEDDING_* pins the target; keep it set for every gbrain process.');
- const merged = loadConfig();
+ const merged = await effective();
if (merged) configureGateway(buildGatewayConfig(merged));
return;
}
@@ -393,7 +401,7 @@ export async function persistEmbeddingFileConfig(
// Reconfigure the in-process gateway from the MERGED view (env still wins
// at runtime; when env is set it matches the target — the ≠ case was
// refused before apply).
- const merged = loadConfig();
+ const merged = await effective();
configureGateway(buildGatewayConfig(merged ?? fileCfg));
}
@@ -707,7 +715,7 @@ export async function executeMigrationFlow(
const applied = await applyEmbeddingMigration(engine, plan, {
ignoreEnvOverride: opts.ignoreEnvOverride,
- persistConfig: (m, d) => persistEmbeddingFileConfig(m, d),
+ persistConfig: (m, d, tx) => persistEmbeddingFileConfig(m, d, tx),
assertOwned,
});
if (applied.status === 'refused') return { status: 'refused_env', warning: applied.warning };
diff --git a/src/core/agent-install/environment.ts b/src/core/agent-install/environment.ts
index 69ee009a7b..3a476deb57 100644
--- a/src/core/agent-install/environment.ts
+++ b/src/core/agent-install/environment.ts
@@ -6,7 +6,7 @@ export const AGENT_PROVIDER_ENV_PREFIXES = [
'ANTHROPIC_', 'AZURE_OPENAI_', 'DASHSCOPE_', 'DEEPSEEK_', 'GEMINI_',
'GOOGLE_GENERATIVE_AI_', 'GROQ_', 'LITELLM_', 'LLAMA_SERVER_', 'LMSTUDIO_',
'MINIMAX_', 'MISTRAL_', 'MOONSHOT_', 'NAN_', 'NVIDIA_', 'OLLAMA_',
- 'OPENAI_', 'OPENROUTER_', 'PERPLEXITY_', 'TOGETHER_', 'VOYAGE_',
+ 'OPENAI_', 'OPENROUTER_', 'PARTICLE_', 'PERPLEXITY_', 'TOGETHER_', 'VOYAGE_',
'ZHIPUAI_',
] as const;
diff --git a/src/core/ai/decide/index.ts b/src/core/ai/decide/index.ts
index 904375a645..491a210c4f 100644
--- a/src/core/ai/decide/index.ts
+++ b/src/core/ai/decide/index.ts
@@ -223,9 +223,13 @@ async function runTypesafe(req: DecideRequest, ctx: DecideContext, cfg: DecideCo
Object.assign(answers, parsed.answers);
} catch (err) {
if (!charged) {
- inputTokens += batch.estimatedInputTokens;
+ // #7272: a 4xx refusal (402 billing, 401/403 auth, 400/404 model) never ran, so it costs
+ // nothing; 408 and 429 are not refusals of the request itself and 429 is charged above.
+ const refused = err instanceof DecideError && err.status !== undefined && err.status >= 400 && err.status < 500 && err.status !== 408 && err.status !== 429;
+ const tokens = refused ? 0 : batch.estimatedInputTokens;
+ inputTokens += tokens;
const reason = err instanceof DecideError ? err.reason : signal.aborted ? 'timeout' : 'failed';
- spendRow(batch.estimatedInputTokens, reason === 'timeout' ? 'timeout' : reason === 'malformed_response' ? 'malformed' : 'failed');
+ spendRow(tokens, reason === 'timeout' ? 'timeout' : reason === 'malformed_response' ? 'malformed' : 'failed');
}
if (err instanceof RateLimitedError) throw err;
throw asDecideError(err, signal, req.signal);
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index a56cc5874b..b52543a6d3 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -39,7 +39,7 @@ import { BudgetTracker, type BudgetReservation } from '../budget/budget-tracker.
import { failedCallUsage, recordOnTracker } from './budget-record.ts';
import { estimateChatInputTokens } from './chat-input-estimate.ts';
import { chatWithFallback, normalizeChatFallbackChain } from './chat-fallback.ts';
-import { applyThinkingOff, thinkingOffMaxOutputTokens } from './thinking-off.ts';
+import { applyThinkingOff, setThinkingOffBaseUrls, thinkingOffMaxOutputTokens } from './thinking-off.ts';
import type {
AIGatewayConfig,
EmbedMultimodalOpts,
@@ -470,6 +470,7 @@ export function recipeSupportsStructuredOutputs(recipe: Recipe): boolean {
export function configureGateway(config: AIGatewayConfig): void {
processState.config = gatewayConfigOf(config);
stashGatewayAnthropicKeyFromEnv(config.env ?? {}); // #2119: filter + rationale in anthropic-key.ts
+ setThinkingOffBaseUrls(config.base_urls);
processState.modelCache.clear();
clearQueryEmbedCache();
processState.shrink.clear();
@@ -731,6 +732,7 @@ export function __setGatewayResetBaselineForTests(
/** Clear every piece of module state. Shared by both reset flavors. */
function clearGatewayState(): void {
processState.config = null;
+ setThinkingOffBaseUrls(undefined);
_discoveryEngine = null;
_discovery = null;
clearGatewayModelSources();
diff --git a/src/core/ai/recipes/index.ts b/src/core/ai/recipes/index.ts
index cd65088f6d..07c5575b1d 100644
--- a/src/core/ai/recipes/index.ts
+++ b/src/core/ai/recipes/index.ts
@@ -30,6 +30,7 @@ import { moonshot } from './moonshot.ts';
import { mistral } from './mistral.ts';
import { nvidia } from './nvidia.ts';
import { perplexity } from './perplexity.ts';
+import { particle } from './particle.ts';
import { typesafe } from './typesafe.ts';
const ALL: Recipe[] = [
@@ -57,6 +58,7 @@ const ALL: Recipe[] = [
mistral,
nvidia,
perplexity,
+ particle,
typesafe,
];
diff --git a/src/core/ai/recipes/particle.ts b/src/core/ai/recipes/particle.ts
new file mode 100644
index 0000000000..58323119d4
--- /dev/null
+++ b/src/core/ai/recipes/particle.ts
@@ -0,0 +1,43 @@
+import type { Recipe } from '../types.ts';
+
+/**
+ * Particle exposes an OpenAI-compatible /v1/chat/completions endpoint. Its
+ * Responses API is WebSocket-only, so gbrain uses Chat Completions alone.
+ * Requests name `particle-1`; responses and /v1/models report
+ * `particle-ai/particle-1`, so both ids are listed. Thinking is on by
+ * default and bills as output; `reasoning_effort: 'none'` turns it off
+ * (thinking-off.ts). Reasoning arrives in `reasoning_content`, which the
+ * openai-compatible adapter keeps out of the answer text; no compat shim
+ * promotes it. US-only traffic can point `provider_base_urls.particle` at
+ * https://us.api.particle.ai/v1.
+ */
+export const particle: Recipe = {
+ id: 'particle',
+ name: 'Particle',
+ tier: 'openai-compat',
+ implementation: 'openai-compatible',
+ base_url_default: 'https://api.particle.ai/v1',
+ auth_env: {
+ required: ['PARTICLE_API_KEY'],
+ setup_url: 'https://platform.particle.ai',
+ },
+ touchpoints: {
+ expansion: {
+ models: ['particle-1', 'particle-ai/particle-1'],
+ cost_per_1m_tokens_usd: 0.25,
+ price_last_verified: '2026-10-31',
+ },
+ chat: {
+ models: ['particle-1', 'particle-ai/particle-1'],
+ supports_tools: true,
+ supports_subagent_loop: true,
+ supports_prompt_cache: true,
+ thinking_by_default: true,
+ max_context_tokens: 1_048_576,
+ cost_per_1m_input_usd: 0.25,
+ cost_per_1m_output_usd: 1.00,
+ price_last_verified: '2026-10-31',
+ },
+ },
+ setup_hint: 'Get an API key at https://platform.particle.ai, then `export PARTICLE_API_KEY=...` and use `particle:particle-1`.',
+};
diff --git a/src/core/ai/thinking-off.ts b/src/core/ai/thinking-off.ts
index bcfbe9d240..7f6c708d0b 100644
--- a/src/core/ai/thinking-off.ts
+++ b/src/core/ai/thinking-off.ts
@@ -19,6 +19,8 @@
* - Gemini 2.5 Flash and Flash-Lite: `thinkingConfig: { thinkingBudget: 0 }`
* - OpenAI models that accept `reasoningEffort: 'none'` (gpt-5.1, 5.2, 5.4,
* 5.5 and the 5.6 family)
+ * - Particle (`particle`; thinking is on by default): `reasoningEffort:
+ * 'none'`, sent as `reasoning_effort` on Chat Completions
* Routes that cannot turn reasoning off send their floor and get the
* thinking-model output headroom, because reasoning bills against the cap and
* a judge-sized cap could come back empty:
@@ -41,7 +43,11 @@
* alone is not an off switch: only the native recipes listed here get an
* option. Every other route is untouched; when it still thinks by default
* (`isThinkingModel`: Claude 5 behind claude-cli, a local reasoning family,
- * GLM) its cap gets the headroom.
+ * GLM) its cap gets the headroom. A `deepseek` prefix whose configured
+ * `provider_base_urls.deepseek` names another origin (an OpenAI-compatible
+ * proxy such as Ollama Cloud) is not the native route (#7662): it gets no
+ * option, since that server does not honour DeepSeek's switch, and its cap
+ * gets the headroom like any other route that thinks by default.
*
* Gemini rows follow Google's generateContent thinking docs; OpenAI rows
* follow the reasoning guide. Both were checked live on 2026-10-07
@@ -49,6 +55,20 @@
*/
import { splitProviderModelId } from '../model-id.ts';
+import { deepseek } from './recipes/deepseek.ts';
+
+let configuredBaseUrls: Readonly<Record<string, string>> | undefined;
+
+/** The gateway's configured `base_urls`, set by configureGateway and cleared with its state (#7662). */
+export function setThinkingOffBaseUrls(urls: Readonly<Record<string, string>> | undefined): void {
+ configuredBaseUrls = urls;
+}
+
+function nativeDeepseekRoute(): boolean {
+ const url = configuredBaseUrls?.deepseek;
+ if (!url) return true;
+ try { return new URL(url).origin === new URL(deepseek.base_url_default!).origin; } catch { return false; }
+}
export interface ThinkingOffControl {
/** The provider-options namespace and the keys set there; absent when the route has no per-call option. */
@@ -112,11 +132,13 @@ function openaiControl(model: string): ThinkingOffControl | undefined {
export function thinkingOffControl(modelStr: string): ThinkingOffControl | undefined {
const { provider, model: rawModel } = splitProviderModelId(modelStr);
if (!provider) return undefined;
+ if (provider === 'deepseek' && !nativeDeepseekRoute()) return undefined;
const model = rawModel.trim().toLowerCase();
if (provider === 'anthropic' || provider === 'deepseek') return { set: { namespace: provider, options: THINKING_DISABLED }, disables: true };
if (provider === 'openrouter') return model.startsWith('deepseek/') ? { set: { namespace: provider, options: THINKING_DISABLED }, disables: true } : undefined;
if (provider === 'google') return googleControl(model);
if (provider === 'openai') return openaiControl(model);
+ if (provider === 'particle') return { set: { namespace: provider, options: { reasoningEffort: 'none' } }, disables: true };
return undefined;
}
diff --git a/src/core/bootstrap/interview.ts b/src/core/bootstrap/interview.ts
index dbb5b39017..b25ec8a36f 100644
--- a/src/core/bootstrap/interview.ts
+++ b/src/core/bootstrap/interview.ts
@@ -501,14 +501,15 @@ export function show(workspaceDir: string):
// Config sink routing [CX2-13]
// ---------------------------------------------------------------------------
-/** Provider detection by key shape. Order matters: `sk-ant-` before `sk-`. */
+/** Provider detection by key shape. Order matters: `sk-ant-` and `sk-or-v1-` before `sk-`. */
const PROVIDER_KEY_SHAPES: Array<{ prefix: string; configKey: ProviderConfigKey; label: string }> = [
{ prefix: 'sk-ant-', configKey: 'anthropic_api_key', label: 'Anthropic (sk-ant-…)' },
+ { prefix: 'sk-or-v1-', configKey: 'openrouter_api_key', label: 'OpenRouter (sk-or-v1-…)' },
{ prefix: 'sk-', configKey: 'openai_api_key', label: 'OpenAI (sk-…)' },
{ prefix: 'pa-', configKey: 'voyage_api_key', label: 'Voyage (pa-…)' },
];
-export type ProviderConfigKey = 'anthropic_api_key' | 'openai_api_key' | 'voyage_api_key';
+export type ProviderConfigKey = 'anthropic_api_key' | 'openrouter_api_key' | 'openai_api_key' | 'voyage_api_key';
/**
* Route an interview-provided provider key to the 0600 config file — the ONLY
diff --git a/src/core/embedding-pricing.ts b/src/core/embedding-pricing.ts
index 961b58a6dd..a931ba7435 100644
--- a/src/core/embedding-pricing.ts
+++ b/src/core/embedding-pricing.ts
@@ -97,10 +97,13 @@ export type PriceLookupResult =
* so `azure-openai:<model>` falls back to the `openai:<model>` row. An alias
* (not duplicated rows) so new openai entries never drift from their Azure
* twins. A model with no twin in the alias target stays `unknown` — fail
- * closed rather than fabricate a rate.
+ * closed rather than fabricate a rate. OpenRouter names Voyage's models
+ * `voyageai/<model>` and bills Voyage's rates (#7034), so the nested
+ * `voyageai` vendor falls back to the `voyage:<model>` row.
*/
const EMBEDDING_PROVIDER_ALIASES: Record<string, string> = {
'azure-openai': 'openai',
+ voyageai: 'voyage',
};
/**
diff --git a/src/core/model-pricing.ts b/src/core/model-pricing.ts
index c4cfd5b09e..a58dbbb4f9 100644
--- a/src/core/model-pricing.ts
+++ b/src/core/model-pricing.ts
@@ -238,6 +238,14 @@ export const CANONICAL_PRICING: Record<string, ModelPricing> = {
'deepseek:deepseek-flash': { input: 0.30, output: 1.20 },
'deepseek:deepseek-v4-flash': { input: 0.30, output: 1.20 },
'deepseek:deepseek-v4-pro': { input: 1.32, output: 3.96 },
+ // Particle (read 2026-10-31 at https://platform.particle.ai): reasoning
+ // bills as output. Requests name `particle-1`; responses report
+ // `particle-ai/particle-1`, so both ids price. Particle lists cached input
+ // at $0.03/M; like other non-Anthropic rows this one carries no cache
+ // field until that rate is verified, so caps price cached input at the
+ // input rate, an upper bound.
+ 'particle:particle-1': { input: 0.25, output: 1.00 },
+ 'particle:particle-ai/particle-1': { input: 0.25, output: 1.00 },
// ── Z.ai / GLM (via LiteLLM proxy) ───────────────────────────────────
// GLM-5.2 from Z.ai: $1.40/M input, $4.40/M output (verified 2026-08-16
// against OpenRouter provider listings — z.ai's own direct rates).
diff --git a/test/ai/chat-thinking-off.test.ts b/test/ai/chat-thinking-off.test.ts
index 9a2614c9b8..388fa7cfc2 100644
--- a/test/ai/chat-thinking-off.test.ts
+++ b/test/ai/chat-thinking-off.test.ts
@@ -28,6 +28,15 @@ const realFetch = globalThis.fetch;
beforeAll(() => {
globalThis.fetch = (async (input: any, init?: any) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
+ if (url.startsWith('https://api.deepseek.com/')) {
+ const body = JSON.parse(String(init?.body));
+ bodies.push(body);
+ return Response.json({
+ id: 'chatcmpl_stub', object: 'chat.completion', created: 0, model: body.model,
+ choices: [{ index: 0, message: { role: 'assistant', content: '{"ok":true}' }, finish_reason: 'stop' }],
+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
+ });
+ }
if (!url.startsWith('https://generativelanguage.googleapis.com/')) return realFetch(input, init);
bodies.push(JSON.parse(String(init?.body)));
return Response.json({
@@ -79,8 +88,10 @@ beforeEach(() => {
resetGateway();
});
-function configure(model: string, providerChatOptions?: Record<string, Record<string, unknown>>): void {
+function configure(model: string, providerChatOptions?: Record<string, Record<string, unknown>>, baseUrls: Record<string, string | undefined> = {}): void {
const base = `http://127.0.0.1:${server.port}/v1`;
+ const urls = Object.fromEntries(Object.entries({ deepseek: base, openrouter: base, zhipu: base, groq: base, ...baseUrls })
+ .filter((e): e is [string, string] => e[1] !== undefined));
configureGateway({
chat_model: model,
env: {
@@ -88,7 +99,7 @@ function configure(model: string, providerChatOptions?: Record<string, Record<st
OPENAI_API_KEY: 'stub', OPENAI_BASE_URL: base, GOOGLE_GENERATIVE_AI_API_KEY: 'stub',
DEEPSEEK_API_KEY: 'stub', OPENROUTER_API_KEY: 'stub', ZHIPUAI_API_KEY: 'stub', GROQ_API_KEY: 'stub',
},
- base_urls: { deepseek: base, openrouter: base, zhipu: base, groq: base },
+ base_urls: urls,
...(providerChatOptions ? { provider_chat_options: providerChatOptions } : {}),
});
}
@@ -127,8 +138,8 @@ describe("chat({ thinking: 'off' }) request bodies (#5331)", () => {
expect(bodies[0].thinking).toEqual({ type: 'enabled', budget_tokens: 4000 });
});
- test('DeepSeek (thinks by default) gets its documented thinking switch', async () => {
- configure('deepseek:deepseek-v4-flash');
+ test('native DeepSeek (thinks by default) gets its documented thinking switch', async () => {
+ configure('deepseek:deepseek-v4-flash', undefined, { deepseek: undefined });
await judgeCall('deepseek:deepseek-v4-flash');
@@ -136,6 +147,24 @@ describe("chat({ thinking: 'off' }) request bodies (#5331)", () => {
expect(bodies[0].max_tokens).toBe(2000);
});
+ test('a provider_base_urls.deepseek path on the DeepSeek origin is still the native route', async () => {
+ configure('deepseek:deepseek-v4-flash', undefined, { deepseek: 'https://api.deepseek.com/beta' });
+
+ await judgeCall('deepseek:deepseek-v4-flash');
+
+ expect(bodies[0].thinking).toEqual({ type: 'disabled' });
+ expect(bodies[0].max_tokens).toBe(2000);
+ });
+
+ test('#7662: provider_base_urls.deepseek on another origin gets no DeepSeek switch and keeps the thinking headroom', async () => {
+ configure('deepseek:deepseek-v4-flash');
+
+ await judgeCall('deepseek:deepseek-v4-flash');
+
+ expect('thinking' in bodies[0]).toBe(false);
+ expect(bodies[0].max_tokens).toBe(THINKING_MODEL_MAX_OUTPUT_TOKENS);
+ });
+
test('OpenRouter-hosted DeepSeek gets the same switch', async () => {
configure('openrouter:deepseek/deepseek-v4-flash-0731');
@@ -298,7 +327,7 @@ describe('judge preflight estimates price the cap chat() sends (W9F item 5)', ()
const sent: Record<string, number> = {};
for (const slot of [...cm.DEFAULT_SLOTS, { id: 'X', model: 'openai:gpt-5' }]) {
bodies = [];
- configure(slot.model);
+ configure(slot.model, undefined, { deepseek: undefined });
await judgeCall(slot.model, { maxTokens: 4000 });
sent[slot.model] = sentCap(bodies[0]);
const p = canonicalLookup(slot.model)!;
diff --git a/test/ai/gateway-chat.test.ts b/test/ai/gateway-chat.test.ts
index 25c7a36848..2e5098ff51 100644
--- a/test/ai/gateway-chat.test.ts
+++ b/test/ai/gateway-chat.test.ts
@@ -73,7 +73,8 @@ describe('chat touchpoint — recipe registry', () => {
// predicate: Claude Code caches automatically on every model it routes,
// `--print` runs included. See the recipe for the measurement and
// test/ai/recipe-claude-cli-prompt-cache.test.ts for the behavior.
- const ALWAYS_CACHES = new Set(['anthropic', 'deepseek', 'llama-server', 'claude-cli']);
+ // Particle caches prompts server-side and bills cached input separately.
+ const ALWAYS_CACHES = new Set(['anthropic', 'deepseek', 'llama-server', 'claude-cli', 'particle']);
for (const r of listRecipes()) {
if (!r.touchpoints.chat) continue;
const flag = r.touchpoints.chat.supports_prompt_cache;
diff --git a/test/ai/recipe-particle.test.ts b/test/ai/recipe-particle.test.ts
new file mode 100644
index 0000000000..1581ad9aea
--- /dev/null
+++ b/test/ai/recipe-particle.test.ts
@@ -0,0 +1,136 @@
+/**
+ * Particle recipe (GST-651): an OpenAI-compatible chat provider whose requests
+ * name `particle-1` while responses report `particle-ai/particle-1`.
+ *
+ * Drives the real gateway against an intercepted fetch at Particle's default
+ * base URL (no live calls) and asserts what leaves gbrain: the endpoint, the
+ * bearer key, the model id, `reasoning_effort: 'none'` for a thinking-off
+ * call, and that reasoning text never becomes answer text.
+ */
+
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { getRecipe } from '../../src/core/ai/recipes/index.ts';
+import { chat, configureGateway, defaultResolveAuth, resetGateway } from '../../src/core/ai/gateway.ts';
+import { assertTouchpoint } from '../../src/core/ai/model-resolver.ts';
+import { AIConfigError } from '../../src/core/ai/errors.ts';
+import { applyThinkingOff, thinkingOffMaxOutputTokens } from '../../src/core/ai/thinking-off.ts';
+import { canonicalLookup } from '../../src/core/model-pricing.ts';
+
+type Captured = { url: string; auth: string | null; body: any };
+let captured: Captured[] = [];
+let reply: Record<string, unknown> = {};
+const realFetch = globalThis.fetch;
+
+beforeAll(() => {
+ globalThis.fetch = (async (input: any, init?: any) => {
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
+ if (!url.startsWith('https://api.particle.ai/')) return realFetch(input, init);
+ const headers = new Headers(init?.headers);
+ const body = JSON.parse(String(init?.body));
+ captured.push({ url, auth: headers.get('authorization'), body });
+ return Response.json({
+ id: 'chatcmpl_stub', object: 'chat.completion', created: 0, model: 'particle-ai/particle-1',
+ choices: [{ index: 0, message: { role: 'assistant', content: '{"ok":true}', ...reply }, finish_reason: 'stop' }],
+ usage: { prompt_tokens: 3, completion_tokens: 2, total_tokens: 5 },
+ });
+ }) as typeof fetch;
+});
+
+afterAll(() => {
+ globalThis.fetch = realFetch;
+ resetGateway();
+});
+
+beforeEach(() => {
+ captured = [];
+ reply = {};
+ resetGateway();
+ configureGateway({ chat_model: 'particle:particle-1', env: { PARTICLE_API_KEY: 'fake-particle-key' } });
+});
+
+const ask = (model: string, extra: Record<string, unknown> = {}) => chat({
+ model,
+ messages: [{ role: 'user', content: 'score this' }],
+ maxTokens: 2000,
+ ...extra,
+});
+
+describe('recipe: particle', () => {
+ test('registered with the expected OpenAI-compatible shape', () => {
+ const r = getRecipe('particle');
+ expect(r).toBeDefined();
+ expect(r!.tier).toBe('openai-compat');
+ expect(r!.implementation).toBe('openai-compatible');
+ expect(r!.base_url_default).toBe('https://api.particle.ai/v1');
+ expect(r!.auth_env?.required).toEqual(['PARTICLE_API_KEY']);
+ expect(r!.compat?.fetch).toBeUndefined();
+ const c = r!.touchpoints.chat!;
+ expect(c.models).toEqual(['particle-1', 'particle-ai/particle-1']);
+ expect(c.supports_tools).toBe(true);
+ expect(c.supports_subagent_loop).toBe(true);
+ expect(c.supports_prompt_cache).toBe(true);
+ expect(c.thinking_by_default).toBe(true);
+ expect(c.max_context_tokens).toBe(1_048_576);
+ expect(c.cost_per_1m_input_usd).toBe(0.25);
+ expect(c.cost_per_1m_output_usd).toBe(1.00);
+ });
+
+ test('both model ids pass chat and expansion validation', () => {
+ const r = getRecipe('particle')!;
+ for (const id of ['particle-1', 'particle-ai/particle-1']) {
+ expect(() => assertTouchpoint(r, 'chat', id)).not.toThrow();
+ expect(() => assertTouchpoint(r, 'expansion', id)).not.toThrow();
+ }
+ });
+
+ test('default auth: PARTICLE_API_KEY -> Bearer token; missing -> AIConfigError', () => {
+ const r = getRecipe('particle')!;
+ const auth = defaultResolveAuth(r, { PARTICLE_API_KEY: 'fake-particle-key' }, 'chat');
+ expect(auth.headerName).toBe('Authorization');
+ expect(auth.token).toBe('Bearer fake-particle-key');
+ expect(() => defaultResolveAuth(r, {}, 'chat')).toThrow(AIConfigError);
+ });
+
+ test('both ids price at $0.25 input and $1.00 output per 1M', () => {
+ for (const id of ['particle:particle-1', 'particle:particle-ai/particle-1']) {
+ expect(canonicalLookup(id)).toEqual({ input: 0.25, output: 1.00 });
+ }
+ });
+});
+
+describe('particle chat over Chat Completions', () => {
+ test('posts to the default base URL with the bearer key and the requested model id', async () => {
+ const res = await ask('particle:particle-1');
+
+ expect(captured).toHaveLength(1);
+ expect(captured[0]!.url).toBe('https://api.particle.ai/v1/chat/completions');
+ expect(captured[0]!.auth).toBe('Bearer fake-particle-key');
+ expect(captured[0]!.body.model).toBe('particle-1');
+ expect(captured[0]!.body.reasoning_effort).toBeUndefined();
+ expect(res.text).toBe('{"ok":true}');
+ expect(res.responseModel).toBe('particle-ai/particle-1');
+ });
+
+ test('the response-side id is accepted as the request model', async () => {
+ await ask('particle:particle-ai/particle-1');
+
+ expect(captured[0]!.body.model).toBe('particle-ai/particle-1');
+ });
+
+ test("thinking: 'off' sends reasoning_effort none and keeps the requested cap", async () => {
+ await ask('particle:particle-1', { thinking: 'off' });
+
+ expect(captured[0]!.body.reasoning_effort).toBe('none');
+ expect(captured[0]!.body.max_tokens).toBe(2000);
+ expect(applyThinkingOff({}, 'particle:particle-ai/particle-1')).toEqual({ particle: { reasoningEffort: 'none' } });
+ expect(thinkingOffMaxOutputTokens('particle:particle-1', 2000, true, 16000)).toBe(2000);
+ });
+
+ test('reasoning_content stays out of the answer text', async () => {
+ reply = { content: 'the answer', reasoning_content: 'private chain of thought' };
+ expect((await ask('particle:particle-1')).text).toBe('the answer');
+
+ reply = { content: '', reasoning_content: 'private chain of thought' };
+ expect((await ask('particle:particle-1')).text).toBe('');
+ });
+});
diff --git a/test/bootstrap-interview.serial.test.ts b/test/bootstrap-interview.serial.test.ts
index 2af39618df..de2140905f 100644
--- a/test/bootstrap-interview.serial.test.ts
+++ b/test/bootstrap-interview.serial.test.ts
@@ -462,6 +462,17 @@ describe('routeProviderKeyToConfig (0600 config sink)', () => {
expect(statSync(configPath()).mode & 0o777).toBe(0o600);
});
+ test('an OpenRouter key (sk-or-v1-) is saved as openrouter_api_key, never openai_api_key (#7977)', () => {
+ seedConfig();
+ const key = `sk-or-v1-${'a1'.repeat(32)}`;
+ const r = routeProviderKeyToConfig(key);
+ expect(r.ok).toBe(true);
+ if (r.ok) expect(r.configKey).toBe('openrouter_api_key');
+ const cfg = JSON.parse(readFileSync(configPath(), 'utf8'));
+ expect(cfg.openrouter_api_key).toBe(key);
+ expect(cfg.openai_api_key).toBeUndefined();
+ });
+
test('unrecognized key shape → error that never echoes the value', () => {
seedConfig();
const r = routeProviderKeyToConfig('xoxb-not-a-supported-provider');
diff --git a/test/daily-task-manager-slug-7932.test.ts b/test/daily-task-manager-slug-7932.test.ts
new file mode 100644
index 0000000000..a034d95aac
--- /dev/null
+++ b/test/daily-task-manager-slug-7932.test.ts
@@ -0,0 +1,31 @@
+/**
+ * #7932 — daily-task-manager names the task page by its slug, `ops/tasks`, in
+ * every page-tool call. The page tools do an exact slug lookup, so
+ * `get_page("ops/tasks.md")` missed the existing `ops/tasks` page, and the
+ * skill's first-run rule could then start a second list at slug
+ * `ops/tasks.md` that sync, `resolveTodayTasks()` and `gbrain get ops/tasks`
+ * never read. Checked in the source skill and both generated copies.
+ */
+import { describe, expect, test } from 'bun:test';
+import { readFileSync } from 'fs';
+import { join } from 'path';
+
+const ROOT = join(import.meta.dir, '..');
+const COPIES = [
+ 'skills/daily-task-manager/SKILL.md',
+ 'plugin/skills/daily-task-manager/SKILL.md',
+ 'plugin-variants/gbrain-daily/skills/daily-task-manager/SKILL.md',
+];
+
+describe('#7932: daily-task-manager page-tool calls use the slug ops/tasks', () => {
+ for (const rel of COPIES) {
+ test(rel, () => {
+ const text = readFileSync(join(ROOT, rel), 'utf8');
+ expect(text).not.toMatch(/(?:get_page|put_page)\(\s*"[^"]*\.md"/);
+ expect(text).toContain('get_page("ops/tasks")');
+ expect(text).toContain('put_page("ops/tasks"');
+ expect(text).toContain('page: "ops/tasks"');
+ expect(text).not.toMatch(/always `ops\/tasks\.md` \(with extension\) in tool calls/);
+ });
+ }
+});
diff --git a/test/decide/refused-calls-no-spend-7272.test.ts b/test/decide/refused-calls-no-spend-7272.test.ts
new file mode 100644
index 0000000000..0f768f89a2
--- /dev/null
+++ b/test/decide/refused-calls-no-spend-7272.test.ts
@@ -0,0 +1,103 @@
+/**
+ * #7272 — a TypeSafe call the provider refuses with a 4xx (402 billing_error,
+ * 401/403 auth, 400/404 model) never ran, so it is not decide spend.
+ *
+ * Before the fix every failed batch was charged its estimated input tokens, so
+ * a provider refusing every call for lack of credits filled the daily budget
+ * with calls that never ran: `decide status` and doctor then reported
+ * "budget exhausted" and every slot stopped with `budget_exhausted` instead of
+ * the provider's `provider_error`. A refused call still leaves a `failed` row
+ * (the error rate stays visible) at $0. A 429 and a 5xx or transport failure
+ * keep their existing charge.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { resetPgliteState } from '../helpers/reset-pglite.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { serializeMarkdown } from '../../src/core/markdown.ts';
+import { configureGateway, resetGateway, __setDecideTransportForTests } from '../../src/core/ai/gateway.ts';
+import { readDecideConfig } from '../../src/core/ai/decide/config.ts';
+import { runDecide } from '../../src/core/ai/decide/index.ts';
+import { dailySpend, flushDecideWrites, __resetDecideStoreForTests } from '../../src/core/ai/decide/store.ts';
+import type { DecideQuestion, EvidenceItem } from '../../src/core/ai/decide/types.ts';
+
+let engine: PGLiteEngine;
+
+const PROVIDER = 'typesafe:jev-1.13.0';
+const cand = (slug: string): EvidenceItem => ({ text: `text of ${slug}`, class: 'candidates', slug, source_id: 'default' });
+const q = (id: string): DecideQuestion => ({ id, kind: 'noul', instructions: 'Is `c` evidence?', inputs: { c: cand('notes/world') } });
+const CONSENT = {
+ 'decide.provider': PROVIDER,
+ 'decide.egress.typesafe.query': 'allow', 'decide.egress.typesafe.candidates': 'allow',
+ 'decide.egress.typesafe.facts': 'allow', 'decide.egress.typesafe.conversation': 'allow',
+};
+const STATE = { query: { text: 'q', class: 'query' as const } };
+
+function respondWith(status: number, body: unknown) {
+ let calls = 0;
+ __setDecideTransportForTests(async () => {
+ calls++;
+ return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
+ });
+ return () => calls;
+}
+
+async function spendRows() {
+ await flushDecideWrites();
+ return engine.executeRaw<{ outcome: string; cost_usd: number }>('SELECT outcome, cost_usd FROM decide_spend ORDER BY created_at');
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ __setDecideTransportForTests(null);
+ resetGateway();
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+ __resetDecideStoreForTests();
+ configureGateway({ env: { TYPESAFE_API_KEY: 'sk-test' } });
+ const r = await importFromContent(engine, 'notes/world', serializeMarkdown({}, 'body of notes/world', '', { type: 'note', title: 'notes/world', tags: [] }), { noEmbed: true, forceRechunk: true });
+ expect(r.status).toBe('imported');
+});
+
+describe('#7272: a provider-refused decide call is not spend', () => {
+ test.each([402, 401, 403, 400, 404])('HTTP %d leaves a $0 failed row and no daily spend', async (status) => {
+ respondWith(status, { error: { type: 'billing_error', message: 'no credits' } });
+ await expect(runDecide({ slot: 'evidence', callSite: 'search', state: STATE, questions: [q('w')] }, { engine, config: readDecideConfig(CONSENT) }))
+ .rejects.toMatchObject({ status });
+ const rows = await spendRows();
+ expect(rows).toHaveLength(1);
+ expect(rows[0]!.outcome).toBe('failed');
+ expect(Number(rows[0]!.cost_usd)).toBe(0);
+ expect((await dailySpend(engine)).total).toBe(0);
+ });
+
+ test('repeated 402 refusals never exhaust the daily budget: the next call still reports the provider error', async () => {
+ // One batch here is estimated at about $0.00009, so on the old charge two refusals filled this budget.
+ const calls = respondWith(402, { error: { type: 'billing_error', message: 'no credits' } });
+ const config = readDecideConfig({ ...CONSENT, 'decide.budget.daily_usd': '0.0002' });
+ for (let i = 0; i < 5; i++) {
+ await expect(runDecide({ slot: 'evidence', callSite: 'search', state: STATE, questions: [q(`w${i}`)] }, { engine, config }))
+ .rejects.toMatchObject({ reason: 'provider_error', status: 402 });
+ await flushDecideWrites();
+ }
+ expect(calls()).toBe(5);
+ expect((await dailySpend(engine)).total).toBe(0);
+ });
+
+ test('a 5xx keeps its estimated charge (the provider may have run it)', async () => {
+ respondWith(500, { error: 'internal' });
+ await expect(runDecide({ slot: 'evidence', callSite: 'search', state: STATE, questions: [q('w')] }, { engine, config: readDecideConfig(CONSENT) }))
+ .rejects.toMatchObject({ reason: 'provider_error', status: 500 });
+ const rows = await spendRows();
+ expect(rows).toHaveLength(1);
+ expect(Number(rows[0]!.cost_usd)).toBeGreaterThan(0);
+ });
+});
diff --git a/test/embedding-pricing.test.ts b/test/embedding-pricing.test.ts
index 92263c7c98..07ca0eb10b 100644
--- a/test/embedding-pricing.test.ts
+++ b/test/embedding-pricing.test.ts
@@ -112,6 +112,27 @@ describe('lookupEmbeddingPrice — azure-openai alias (#4032)', () => {
});
});
+describe('lookupEmbeddingPrice — voyageai alias for the OpenRouter slug (#7034)', () => {
+ // OpenRouter names Voyage's models voyageai/<model> and bills Voyage's rates.
+ test.each([
+ ['openrouter:voyageai/voyage-4', 0.06, 'voyage:voyage-4'],
+ ['openrouter:voyageai/voyage-4-large', 0.12, 'voyage:voyage-4-large'],
+ ['openrouter:voyageai/voyage-4-lite', 0.02, 'voyage:voyage-4-lite'],
+ ['openrouter:voyageai/voyage-code-4', 0.12, 'voyage:voyage-code-4'],
+ ])('%s resolves via the voyage row', (model, expected, key) => {
+ const r = lookupEmbeddingPrice(model as string);
+ expect(r.kind).toBe('known');
+ if (r.kind === 'known') {
+ expect(r.pricePerMTok).toBe(expected as number);
+ expect(r.key).toBe(key as string);
+ }
+ });
+
+ test('voyageai model with no voyage twin stays unknown', () => {
+ expect(lookupEmbeddingPrice('openrouter:voyageai/voyage-4-nano').kind).toBe('unknown');
+ });
+});
+
describe('lookupEmbeddingPrice — nested gateway ids (#2504)', () => {
// Router providers (openrouter, generic gateways) wrap the upstream vendor
// in the model segment. The router bills the vendor's per-token rate, so
diff --git a/test/helpers/provider-env.ts b/test/helpers/provider-env.ts
index 038a06f640..35bb76359d 100644
--- a/test/helpers/provider-env.ts
+++ b/test/helpers/provider-env.ts
@@ -16,7 +16,7 @@ export const PROVIDER_ENV_KEYS = [
'OLLAMA_API_KEY', 'OLLAMA_BASE_URL',
'OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_ORG_ID', 'OPENAI_PROJECT',
'OPENROUTER_API_KEY', 'OPENROUTER_BASE_URL', 'OPENROUTER_REFERER', 'OPENROUTER_TITLE',
- 'PERPLEXITY_API_KEY', 'TOGETHER_API_KEY', 'TYPESAFE_API_KEY', 'JEV_TYPESAFE_API_KEY', 'VOYAGE_API_KEY',
+ 'PARTICLE_API_KEY', 'PERPLEXITY_API_KEY', 'TOGETHER_API_KEY', 'TYPESAFE_API_KEY', 'JEV_TYPESAFE_API_KEY', 'VOYAGE_API_KEY',
'WAKESHIFT_API_KEY', 'ZHIPUAI_API_KEY',
] as const;
diff --git a/test/migrate-embeddings-hardening.serial.test.ts b/test/migrate-embeddings-hardening.serial.test.ts
index a984d2624a..c9cd922501 100644
--- a/test/migrate-embeddings-hardening.serial.test.ts
+++ b/test/migrate-embeddings-hardening.serial.test.ts
@@ -46,6 +46,7 @@ const OUTGOING_RERANKER = 'fixture-provider:reranker-v1';
import {
configureGateway,
resetGateway,
+ requireConfig,
__setEmbedTransportForTests,
} from '../src/core/ai/gateway.ts';
import { runEmbedCore } from '../src/commands/embed.ts';
@@ -722,6 +723,26 @@ describe('config-plane hygiene (env leak + env-canonical gates)', () => {
}
}, 30000);
+ test('#7666: the post-apply gateway keeps a DB-plane provider_base_urls override, and the file plane never gains it', async () => {
+ const cfgPath = join(tmpHome, '.gbrain', 'config.json');
+ const url = 'http://127.0.0.1:11435/v1';
+ await engine.setConfig('provider_base_urls.ollama', url);
+ try {
+ await persistEmbeddingFileConfig('openai:text-embedding-3-small', TO_DIMS, engine);
+ expect(requireConfig().base_urls?.ollama).toBe(url);
+ expect(readFileSync(cfgPath, 'utf-8')).not.toContain(url);
+ } finally {
+ await engine.executeRaw(`DELETE FROM config WHERE key = 'provider_base_urls.ollama'`);
+ writeFileConfig('openai:text-embedding-3-small', TO_DIMS);
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-small',
+ embedding_dimensions: TO_DIMS,
+ env: { OPENAI_API_KEY: 'sk-test-fake', VOYAGE_API_KEY: 'pa-test-fake' },
+ });
+ installTransport();
+ }
+ }, 30000);
+
test('dims-only env never fully pins the target; a no-file-plane run refuses at apply', async () => {
// Unit: the MODEL var is required — dims alone must not pin (#1421 class).
expect(envFullyPinsTarget('openai:text-embedding-3-small', TO_DIMS, {