Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.60.113.0 fix(mcp,doctor): wave 0 repair batch (10x memory advantage plan)

garrytan8afb109fa661
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 0a963779ac..c69c7af0d9 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -25,7 +25,7 @@
"args": [
"serve",
"--surface",
- "starter",
+ "full",
"--source-guard"
],
"cwd": "${CLAUDE_PLUGIN_ROOT}"
diff --git a/.codex-plugin/mcp.json b/.codex-plugin/mcp.json
index 3f3f699c33..acca85b10c 100644
--- a/.codex-plugin/mcp.json
+++ b/.codex-plugin/mcp.json
@@ -5,7 +5,7 @@
"args": [
"serve",
"--surface",
- "starter",
+ "full",
"--source-guard"
],
"cwd": ".",
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index 764837672f..04d9250456 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -91,17 +91,18 @@ registration only with `--mcp-even-if-plugin`.
Then `gbrain bootstrap status` — it is idempotent and resume-aware; after any
partial failure, re-run it and continue where it points.
2. **Engine.** Two lanes; default to the first:
- - **PGLite (default):** `gbrain init --pglite` (2 seconds, no server). This is
- the lane that keeps the per-turn hook context injection working — the hook
- IPC listener is PGLite-only today.
+ - **PGLite (default):** `gbrain init --pglite` (2 seconds, no server). The
+ per-turn hook context injection works whenever a `gbrain serve` for the
+ brain is running.
- **Postgres-first (harness installs):** `gbrain init --prefer-postgres` walks
a 5-rung ladder (env URL → Supabase token discovery → local Postgres →
`--allow-docker` → PGLite floor) for installs that want concurrent
- connections or multi-machine access. Tradeoff, stated plainly: a Postgres
- brain gets MCP tools every session plus the pull protocol, but gives up the
- per-turn hook lane until the engine-uniform listener lands (the degradation
- matrix in `docs/guides/bootstrap.md` carries the row; INSTALL_FOR_AGENTS.md
- "Engine preference for harness installs" carries the ladder detail).
+ connections or multi-machine access. A Postgres brain keeps the per-turn
+ hook lane too: the IPC listener is engine-uniform and keys its socket off
+ the connection URL, so the hooks fire whenever a `gbrain serve` for the
+ brain is running, same as PGLite (the degradation matrix in
+ `docs/guides/bootstrap.md` carries the row; INSTALL_FOR_AGENTS.md "Engine
+ preference for harness installs" carries the ladder detail).
Search mode is
auto-selected silently (conservative when keyless, tokenmax with an
diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.md
index 960e79318f..dd35665595 100644
--- a/INSTALL_FOR_AGENTS.md
+++ b/INSTALL_FOR_AGENTS.md
@@ -179,9 +179,11 @@ lane; moving engines is `gbrain migrate`'s.
`--json` emits `{status, engine, ladder_rung, url_source}` as the ONLY stdout
content so a scripted install can `| jq` it. The access token is never
persisted, logged, or echoed.
-Tradeoff to know before choosing: Postgres brains get MCP tools every session plus
-the pull protocol, but NOT the PGLite-only per-turn bootstrap hook lane (see
-`BOOTSTRAP_FOR_AGENTS.md` and the degradation matrix in `docs/guides/bootstrap.md`).
+Postgres brains get MCP tools every session plus the pull protocol, and keep the
+per-turn bootstrap hook lane: the IPC listener is engine-uniform (it keys its
+socket off the connection URL), so the hooks fire whenever a `gbrain serve` for
+the brain is running, same as PGLite (see the degradation matrix in
+`docs/guides/bootstrap.md`).
**Runtime failure loop (how the harness self-heals).** When Postgres access
breaks at runtime, gbrain emits a machine marker: `GBRAIN_DB_ACCESS <reason>`
@@ -362,9 +364,9 @@ policy. Memory write access is not
including the parent, needs its own principal and private handoff.
Discover with `list_skills` using `schema_version: 2`, then fetch only relevant
-`get_skill` revisions and approved `get_skill_asset` dependencies. Starter
-supports these tools subject to grants; the `--surface verbs` examples below
-are deliberately memory-only. MCP resources at `gbrain://skills` offer the same
+`get_skill` revisions and approved `get_skill_asset` dependencies. The
+`--surface full` registrations below serve these tools subject to grants (the
+narrower `--surface verbs` is deliberately memory-only). MCP resources at `gbrain://skills` offer the same
authorized catalog, not a promise that every client loads native skills.
Managed Claude Code/Codex/opencode routers report `restart_required` and native
@@ -419,7 +421,7 @@ model gbrain removed in v0.33, needs `gbrain skillpack migrate-fence` once.)
**If you are Hermes:** register gbrain as your MCP server:
```bash
-printf 'Y\n' | hermes mcp add gbrain --env GBRAIN_HOME=$HOME --connect-timeout 60 --command $(which gbrain) --args serve
+printf 'Y\n' | hermes mcp add gbrain --env GBRAIN_HOME=$HOME --connect-timeout 60 --command $(which gbrain) --args serve --surface full
```
Keep `--args` last (everything after it becomes server argv) and verify with
@@ -429,12 +431,12 @@ Keep `--args` last (everything after it becomes server argv) and verify with
**If you are Grok Build** (xAI's `grok` CLI): register gbrain as your MCP server:
```bash
-grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- "$(command -v gbrain)" serve --surface verbs
+grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- "$(command -v gbrain)" serve --surface full
```
The add is lazy (exit 0 without connecting) — verify with
-`grok mcp doctor gbrain`, which spawns the server and must report
-`7 tools discovered`. This is the brain-only install; the `gbrain bootstrap`
+`grok mcp doctor gbrain`, which spawns the server and must report the tools it
+discovered (the full surface). This is the brain-only install; the `gbrain bootstrap`
personal-agent path does not support Grok yet (Claude Code, Codex, and opencode only).
Verified against Grok Build v1.0.4. Full reference:
[docs/mcp/GROK.md](docs/mcp/GROK.md).
@@ -445,7 +447,7 @@ install, follow `BOOTSTRAP_FOR_AGENTS.md` instead of this page. For the
brain-only MCP registration:
```bash
-opencode mcp add gbrain --env GBRAIN_HOME=$HOME -- "$(command -v gbrain)" serve --surface verbs
+opencode mcp add gbrain --env GBRAIN_HOME=$HOME -- "$(command -v gbrain)" serve --surface full
```
The add is lazy (exit 0 without connecting) — verify with `opencode mcp list`,
diff --git a/README.md b/README.md
index c676838fa1..8e1e402ab9 100644
--- a/README.md
+++ b/README.md
@@ -173,11 +173,11 @@ The agent starts with keyless memory and verifies it. API keys, automatic captur
### Lighter ways in
-**Just want a memory for your coding agent — no identity, no repo.** Spin up a local brain and connect it in two commands — zero server, zero token, zero tunnel. `--surface verbs` gives your agent the seven-verb memory protocol (`recall`, `remember`, `entity`, `synthesize`, `forget`, `context_pack`, `delta` — [MEMORY_VERBS v1](docs/protocol/MEMORY_VERBS_v1.md), frozen + additive-forever) instead of the full tool wall; drop the flag for every operation:
+**Just want a memory for your coding agent — no identity, no repo.** Spin up a local brain and connect it in two commands — zero server, zero token, zero tunnel. `--surface full` (the registration default) serves every operation, the seven-verb memory protocol ([MEMORY_VERBS v1](docs/protocol/MEMORY_VERBS_v1.md)) and `put_pages` included; a harness that caps its tool count can register `--surface verbs` or `--surface starter`:
```bash
gbrain init --pglite --no-embedding # keyless local brain (no Docker)
-claude mcp add gbrain -- "$(command -v gbrain)" serve --surface verbs # or: codex mcp add gbrain -- "$(command -v gbrain)" serve --surface verbs
+claude mcp add gbrain -- "$(command -v gbrain)" serve --surface full # or: codex mcp add gbrain -- "$(command -v gbrain)" serve --surface full
```
If `claude` is not found, install Claude Code first — or use the per-harness blocks in the [protocol doc](docs/protocol/MEMORY_VERBS_v1.md). Heads-up: memories agents save default to brain-wide visibility (every connected agent can recall them); pass `visibility: "private"` for local-only facts.
@@ -211,7 +211,7 @@ to keep daemon installation and paid reindexing opt-in.
### Connect GBrain to your AI client (MCP)
-For a hosted brain, start with the [native OAuth and private machine connection guide](docs/guides/hosted-harness-access.md). To open the dashboard, register clients, edit access, or invalidate tokens, use [MCP administration](docs/mcp/ADMIN.md). A **profile** controls MCP authority; a **surface** controls which granted tools are visible. Neither grants owner dashboard access. New memory profiles use the starter surface. `--surface verbs` retains exactly the seven memory verbs, with orientation available through `gbrain://capabilities`. Thin CLI connections use the full surface and remain restricted by their grants.
+For a hosted brain, start with the [native OAuth and private machine connection guide](docs/guides/hosted-harness-access.md). To open the dashboard, register clients, edit access, or invalidate tokens, use [MCP administration](docs/mcp/ADMIN.md). A **profile** controls MCP authority; a **surface** controls which granted tools are visible. Neither grants owner dashboard access. New memory profiles use the full surface. `--surface verbs` retains exactly the seven memory verbs, with orientation available through `gbrain://capabilities`. Thin CLI connections use the full surface and remain restricted by their grants.
Choose the connection instructions for your actual product:
@@ -224,12 +224,12 @@ commands, embedding costs, and the restrictions that remain after rebuilding.
- **[Claude Code](docs/mcp/CLAUDE_CODE.md)** — plugin: `/plugin marketplace add garrytan/gbrain` + `/plugin install gbrain@gbrain` (MCP + skills; persona variants `gbrain-coding` / `gbrain-daily` install curated subsets; pick one). Marketplace-free skills: `gbrain skillpack scaffold --harness claude-code` copies a persona-curated skill set into your user-scope skills dir. Or local one-liner: `claude mcp add gbrain -- "$(command -v gbrain)" serve`. Remote with just a bearer token: `gbrain connect https://your-host/mcp --token gbrain_xxx` prints a paste-ready block (or `--install` wires it up and smoke-tests the token).
- **[Codex](docs/mcp/CODEX.md)** — plugin (recommended): `codex plugin marketplace add garrytan/gbrain@codex-plugin` + `codex plugin add gbrain@gbrain` installs the MCP server AND the curated skill set. Or connect-only: `gbrain connect https://your-host/mcp --token gbrain_xxx --agent codex` (or `--install`); the token path reads `$GBRAIN_REMOTE_TOKEN` at runtime, while the private-handoff installer writes a private managed HTTP header so the connection survives a new shell.
-- **[Cursor / Windsurf / any stdio MCP client](docs/mcp/CLAUDE_CODE.md)** — same shape, add `{"command": "gbrain", "args": ["serve"]}` to your MCP config.
-- **[Hermes](docs/mcp/HERMES.md)** — `printf 'Y\n' | hermes mcp add gbrain --env GBRAIN_HOME=$HOME --connect-timeout 60 --command $(which gbrain) --args serve`. Keep `--args` last, and verify with `hermes mcp test gbrain` (the add exits 0 even on failure).
+- **[Cursor / Windsurf / any stdio MCP client](docs/mcp/CLAUDE_CODE.md)** — same shape, add `{"command": "gbrain", "args": ["serve", "--surface", "full"]}` to your MCP config.
+- **[Hermes](docs/mcp/HERMES.md)** — `printf 'Y\n' | hermes mcp add gbrain --env GBRAIN_HOME=$HOME --connect-timeout 60 --command $(which gbrain) --args serve --surface full`. Keep `--args` last, and verify with `hermes mcp test gbrain` (the add exits 0 even on failure).
- **[Grok Bot](docs/guides/grok-bot.md)** — recommended: keep the brain on your computer, publish it with `gbrain mcp expose --funnel`, grant the Bot a `memory-writer` client and install the thin CLI at `/workspace/gbrain`; or install memory inside the Bot computer when no machine of yours stays online. Bots share local files and credentials; sources organize memory without isolating Bots. **Say to your agent:** *"connect grok bot to my brain"*.
- **[Muse personal agent](docs/guides/muse.md)** — first verify its durable user-files location; then either connect it to your published brain (`gbrain mcp expose --funnel` + thin CLI) or install the local CLI there. Native MCP configuration and skill activation are not assumed. **Say to your agent:** *"connect muse to my brain"*.
-- **[Grok Build](docs/mcp/GROK.md)** — `grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- "$(command -v gbrain)" serve --surface verbs`. The add is lazy (exit 0 without connecting) — verify with `grok mcp doctor gbrain`, which spawns the server and reports `7 tools discovered`. Verified against Grok Build v1.0.4.
-- **[opencode](docs/mcp/OPENCODE.md)** (opencode.ai / SST — not OpenClaw) — `opencode mcp add gbrain --env GBRAIN_HOME=$HOME -- "$(command -v gbrain)" serve --surface verbs`, or let `gbrain bootstrap hooks --harness opencode` write the config for you (opencode is a bootstrap-supported harness — it reads AGENTS.md natively). The add is lazy — verify with `opencode mcp list`, which spawns the server (`✓ gbrain connected`). Remote: `gbrain connect https://your-host/mcp --token gbrain_xxx --agent opencode [--install]` — the config stores only the `{env:GBRAIN_REMOTE_TOKEN}` interpolation. Verified against opencode v1.18.18.
+- **[Grok Build](docs/mcp/GROK.md)** — `grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- "$(command -v gbrain)" serve --surface full`. The add is lazy (exit 0 without connecting) — verify with `grok mcp doctor gbrain`, which spawns the server. Verified against Grok Build v1.0.4.
+- **[opencode](docs/mcp/OPENCODE.md)** (opencode.ai / SST — not OpenClaw) — `opencode mcp add gbrain --env GBRAIN_HOME=$HOME -- "$(command -v gbrain)" serve --surface full`, or let `gbrain bootstrap hooks --harness opencode` write the config for you (opencode is a bootstrap-supported harness — it reads AGENTS.md natively). The add is lazy — verify with `opencode mcp list`, which spawns the server (`✓ gbrain connected`). Remote: `gbrain connect https://your-host/mcp --token gbrain_xxx --agent opencode [--install]` — the config stores only the `{env:GBRAIN_REMOTE_TOKEN}` interpolation. Verified against opencode v1.18.18.
- **[OpenClaw](docs/mcp/OPENCLAW.md)** — the ClawHub bundle plugin registers gbrain automatically (`openclaw.plugin.json` ships in this repo), or register the stdio server with `openclaw mcp add gbrain --command "$(command -v gbrain)" --arg serve --env GBRAIN_HOME=$HOME` (absolute path: the launchd gateway PATH lacks `~/.bun/bin`); verify with `openclaw mcp list`.
- **[Claude Desktop (Cowork)](docs/mcp/CLAUDE_DESKTOP.md)** — Settings → Integrations → add the URL of your HTTP server. Remote only; the local `claude_desktop_config.json` does not work for remote servers.
- **[Claude Cowork (team plan)](docs/mcp/CLAUDE_COWORK.md)** — org Owner adds the connector under Organization Settings → Connectors.
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index f388124434..aa0fe00b56 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -128,17 +128,16 @@ gbrain autopilot --install # background daemon for nightly enrichment
**Wire this same local brain into your coding agent** — zero server, zero token:
```bash
-claude mcp add gbrain -- "$(command -v gbrain)" serve --surface verbs # Claude Code
-codex mcp add gbrain -- "$(command -v gbrain)" serve --surface verbs # Codex
+claude mcp add gbrain -- "$(command -v gbrain)" serve --surface full # Claude Code
+codex mcp add gbrain -- "$(command -v gbrain)" serve --surface full # Codex
```
-The agent spawns `gbrain serve` as a stdio subprocess against your local brain. `--surface verbs` gives the agent the seven-verb memory protocol (`recall`, `remember`, `entity`, `synthesize`, `forget`, `context_pack`, `delta` — [MEMORY_VERBS v1](protocol/MEMORY_VERBS_v1.md)) instead of the full tool catalog; `--surface starter` adds the daily-driver set on top of the verbs (~27 ops total); drop the flag (default `full`) for every operation. Full walkthrough (both this local path and connecting to a remote brain), plus the brain-first protocol to paste into `CLAUDE.md` / `AGENTS.md`: **[Give your coding agent a memory](tutorials/connect-coding-agent.md)**.
+The agent spawns `gbrain serve` as a stdio subprocess against your local brain. `--surface full` (what every registration gbrain writes pins) serves every operation, the seven-verb memory protocol ([MEMORY_VERBS v1](protocol/MEMORY_VERBS_v1.md)) included; a harness that caps its tool count can register `--surface starter` (the verbs plus the daily-driver set, 40 ops) or `--surface verbs` (only the seven verbs). Full walkthrough (both this local path and connecting to a remote brain), plus the brain-first protocol to paste into `CLAUDE.md` / `AGENTS.md`: **[Give your coding agent a memory](tutorials/connect-coding-agent.md)**.
## 3. MCP server (any MCP client)
```bash
-gbrain serve # stdio MCP (Claude Desktop / Code / Cursor)
-gbrain serve --surface verbs # stdio MCP, just the 7 memory verbs (quickstart)
+gbrain serve --surface full # stdio MCP (Claude Desktop / Code / Cursor), every operation
gbrain serve --http # HTTP MCP with OAuth 2.1 + admin dashboard
gbrain mcp expose # publish serve --http on your Tailscale tailnet (HTTPS + user service)
```
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.md
index c20a157e54..a9324190eb 100644
--- a/docs/architecture/key-files/commands-1.md
+++ b/docs/architecture/key-files/commands-1.md
@@ -8,7 +8,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/agent-logs.ts` — `gbrain agent logs <job> [--follow] [--since]`. Merges JSONL heartbeat audit + `subagent_messages` into a chronological timeline. `parseSince` accepts ISO-8601 or relative (`5m`, `1h`, `2d`). Transcript tail renders only for terminal jobs.
-- `src/commands/agent-register.ts` — `gbrain agent register <name> --harness claude-code|codex|opencode|openclaw`: mints a scoped OAuth client + access token and prints the exact harness wiring in one step (CLI-only, never an MCP op). Composes existing parts — `registerScopedClient` (auth.ts), `exchangeClientCredentials`, the mcp-registration argv builders, `renderCodexHttpServerBlock`, `openclawThinClientBlock` — no new auth machinery. Order is load-bearing: cli.ts pre-connect guards (thin-client refusal + PGLite live-serve probe) → pure parse (exit 2) → preset resolve → source validation (existence + not-archived, engine lane `ANY($1::text[])`) → column pre-flight OUTSIDE any tx (25P02 forbids in-tx degrade) → ONE `engine.transaction` (name-scoped `pg_advisory_xact_lock` → duplicate-name pre-check → `ensureWorkspaceSource` create-or-reuse-only-when-truly-empty (refuses page-, fact-, or file-bearing and archived sources) → `registerScopedClient` with ttl + surface) → COMMIT → post-commit fail-open surface audit → token exchange on the OUTER engine (the tx sql is dead) → serve probe (`probeServeHealth` + the unconditional `SCOPES_MIN_SERVE_VERSION` floor line): a probe-PROVEN pre-scopes serve REFUSES registration (`serve_too_old`) unless `--allow-old-serve` — such a serve verifies scoped tokens as full access; an unreachable serve stays a warning, and the reissue lane warns instead of refusing (the secret is already rotated by that point) → render + print (human, or ONE JSON doc carrying `probe_note` + `serve_warning` from the probe; secrets redacted unless `--show-token`). Presets: `daily-driver` (write one source; federated reads = SNAPSHOT of non-archived sources at registration, EXCLUDING other agents' `*-workspace` scratch sources — a workspace named explicitly in `--federated-read` is still granted, and the print counts the exclusions) and `coding-agent` (write-isolated derived `<name>-workspace` DB-only source; requires `--federated-read`); both default the client to the `starter` surface — override with `--surface` at registration or widen per client via `gbrain auth rescope-client`. Always writes `token_ttl` (default 30 days — the server default is 1 hour and would kill a pasted config). `--url|--port` required (every block embeds the brain URL). A scope blocklist keeps operator-grade scopes on `auth register-client`. `--reissue <client-id>` rotates the secret under the same advisory lock and reprints the block (headed by the stored client_name); rotation is not revocation — outstanding tokens live until expiry. Failure after COMMIT prints the client_id + the exact revoke command (never a false "nothing was created"). openclaw renders the honest thin-client CLI block (no native remote-MCP client upstream yet). Pinned by `test/agent-register.test.ts`.
+- `src/commands/agent-register.ts` — `gbrain agent register <name> --harness claude-code|codex|opencode|openclaw`: mints a scoped OAuth client + access token and prints the exact harness wiring in one step (CLI-only, never an MCP op). Composes existing parts — `registerScopedClient` (auth.ts), `exchangeClientCredentials`, the mcp-registration argv builders, `renderCodexHttpServerBlock`, `openclawThinClientBlock` — no new auth machinery. Order is load-bearing: cli.ts pre-connect guards (thin-client refusal + PGLite live-serve probe) → pure parse (exit 2) → preset resolve → source validation (existence + not-archived, engine lane `ANY($1::text[])`) → column pre-flight OUTSIDE any tx (25P02 forbids in-tx degrade) → ONE `engine.transaction` (name-scoped `pg_advisory_xact_lock` → duplicate-name pre-check → `ensureWorkspaceSource` create-or-reuse-only-when-truly-empty (refuses page-, fact-, or file-bearing and archived sources) → `registerScopedClient` with ttl + surface) → COMMIT → post-commit fail-open surface audit → token exchange on the OUTER engine (the tx sql is dead) → serve probe (`probeServeHealth` + the unconditional `SCOPES_MIN_SERVE_VERSION` floor line): a probe-PROVEN pre-scopes serve REFUSES registration (`serve_too_old`) unless `--allow-old-serve` — such a serve verifies scoped tokens as full access; an unreachable serve stays a warning, and the reissue lane warns instead of refusing (the secret is already rotated by that point) → render + print (human, or ONE JSON doc carrying `probe_note` + `serve_warning` from the probe; secrets redacted unless `--show-token`). Presets: `daily-driver` (write one source; federated reads = SNAPSHOT of non-archived sources at registration, EXCLUDING other agents' `*-workspace` scratch sources — a workspace named explicitly in `--federated-read` is still granted, and the print counts the exclusions) and `coding-agent` (write-isolated derived `<name>-workspace` DB-only source; requires `--federated-read`); both default the client to the `full` surface (S0/D4) — pass `--surface starter|verbs` at registration for a capped harness, or narrow per client via `gbrain auth rescope-client`. Always writes `token_ttl` (default 30 days — the server default is 1 hour and would kill a pasted config). `--url|--port` required (every block embeds the brain URL). A scope blocklist keeps operator-grade scopes on `auth register-client`. `--reissue <client-id>` rotates the secret under the same advisory lock and reprints the block (headed by the stored client_name); rotation is not revocation — outstanding tokens live until expiry. Failure after COMMIT prints the client_id + the exact revoke command (never a false "nothing was created"). openclaw renders the honest thin-client CLI block (no native remote-MCP client upstream yet). Pinned by `test/agent-register.test.ts`.
- `src/commands/agent.ts` — `gbrain agent run|logs|register` dispatcher. `run` submits `subagent` (or N children + 1 aggregator) under `{allowProtectedSubmit: true}`; single-entry `--fanout-manifest` short-circuits; children get `on_child_fail: 'continue'` + `max_stalled: 3`; `--follow` is the default on TTY (streams logs + polls `waitForCompletion` in parallel; Ctrl-C detaches, does not cancel). `logs` delegates to `agent-logs.ts`; `register` lazy-imports `agent-register.ts`. Subcommand-aware help is answered BEFORE any engine or queue work and STOPS at the `--` terminator (`agent run -- --help` submits the LITERAL prompt); on a brainless machine (null engine) help still prints while real `run`/`logs` invocations refuse with an init hint.
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index 201937a2dd..90d395b23c 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -40,7 +40,7 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers the façade: re-exports, `Check`/`DoctorReport` and report scoring, the `buildChecks` flag parse, `runDoctor`, output rendering and `--locks`; every check block lives in a registry entry under `doctor/checks/*` (refactor wave 1 W4 doctor), remediation in `doctor/remediate.ts`, wave checks in `doctor/wave-checks.ts`.
- `src/commands/doctor/check-fix.ts` (+ `heartbeat.ts`, `checks/harness-wiring.ts`, `checks/agent-contract.ts`) — doctor speaks agent contract v1. `Check` carries optional `fix` (stored `Action`; `computeDoctorReport` renders it for the report's transport via `finalizeCheckFixes`, redacted on http), `fix_unavailable_reason` (`check_errored`, `operator_judgement`, `no_safe_automatic_fix`, `unstructured` for legacy prose-only warns), `severity: 'info'` and `readiness_state`; `schema_version` stays 2 and status stays `ok | warn | fail`. Capabilities that are off by choice or not applicable yet (keyless embeddings and their staleness/vector checks, opt-in takes, no serve running, 0 pages, never-cycled empty or <24 h sources, backup before 25 pages+facts or 7 days via `backupCoachingDue`) report `ok` + `info` with the enable command as `fix`; the report adds `capped_by: ['embeddings_disabled']` and, when the `connection` check is present and not ok, `unknown_scores: ['brain']`. `top_issues[]` gain `action` (the rendered fix) beside the legacy `fix` string. `checkError(name, what, err)` is the one "Could not …" shape (a `gbrain db-repair` fix when the error classifies as DB access). `gbrain doctor --only <check>[,…] [--json]` (`parseOnlyChecks`, `onlyNeedsEngine`, CLI `runDoctorOnly`) runs only the entries that emit those names plus the connection lane, engine-free when every name is a filesystem check, else `connectEngine({ probeOnly: true })`; unknown names exit 2 with the valid list; a requested check that produced nothing reports `info`/`not_applicable` (or `check_errored` after an early stop). It is every doctor fix's `verify`. `harness_wiring` reads the gbrain registration from `~/.claude.json`, Codex `config.toml` and `opencode.json`; under `--only harness_wiring` it smoke-tests it (live serve lock owner → `wired_running`; else spawn the registered argv, 15 s, initialize + tools/list + `recall`; `gbrain_status` replies reported with their reason/fix); it writes nothing. `agent_contract` reads `readAgentContractEvents()` (7 days) and warns on `internal_error`/suggestion-less envelopes, consent refusals, `derived_cap_exhausted` and `json_document_missing`, with the user-only `consent.preapprove.*` command as fix. `throttleDoctorHeartbeat`: piped doctor progress emits at most one heartbeat per 5 s. Tests: `test/doctor-status-set.test.ts`, `test/doctor-harness-smoke.test.ts`, `test/doctor-day-zero.test.ts` (keyless init then doctor: 0 WARN, health ≥ 90), `test/doctor-remote-parity.test.ts` (run_doctor and CLI agree per shared check; run_doctor renders fixes for its transport). `harness_wiring` with no registration drops every detected harness an enabled plugin lane covers (`enabledPluginLanes`): all covered → `ok`, `reason: plugin_lane_enabled` with the plugins, harnesses and a verify hint (plugin lanes are not smoke-tested); partly covered → the missing-registration warning for the uncovered harnesses only. Claude Code detection also honors `CLAUDE_CONFIG_DIR`.
-- `src/commands/doctor/registry.ts` + `src/commands/doctor/context.ts` — the doctor check registry (refactor wave 1, W4 doctor). `DOCTOR_CHECK_REGISTRY` lists 67 `DoctorEntry` records `{ name, emits, run(ctx) -> Promise<Check[] | STOP_DOCTOR> }` in output order; `runDoctorRegistry(ctx)` runs them, returns the checks gathered so far on `STOP_DOCTOR`, and otherwise finishes the DB-checks progress phase. Execution groups: filesystem-first entries (the resolver-health entry applies `--fix` before it scans), the no-engine connection lane plus a STOP when `--fast` or no engine, the live connection entry plus a STOP when `getStats` failed, then the DB entries, which take the engine via `connectedEngine(ctx)`. `DoctorContext` carries the parsed flags (`jsonOutput`, `fastMode`, `doFix`, `dryRun`, `scope`, `orphanRatioSourceId`, `args`), `engine`, `dbSource`, `connectError`, `progress`, the skills-dir resolution and the cross-entry values `autoFixReport`, `schemaVersion`, `connectionFailed`, each written by the entry that computes it. Entry modules (one `run*` function per former `buildChecks` block, moved verbatim): `checks/skill-group.ts`, `local-runtime.ts`, `supervisor-health.ts`, `local-audits.ts`, `db-connection.ts` (also `pgbouncerPrepareCheck`, `classifiedConnectionCheck` and the two STOP gates), `schema-health.ts`, `embedding-health.ts`, `graph-health.ts`, `data-integrity.ts`, `content-quality.ts`, `knowledge-health.ts`, `queue-assets.ts`, `sync-search.ts`; `checks/legacy-token-grants.ts` (F3) emits `legacy_token_grant_shape` (info: active tokens still on the JSONB-only grant shape, fix `gbrain auth rescope --migrate-legacy`) and `legacy_token_grant_drift` (warn: per-token drifted axes with the two adopt commands); `checks/upgrade-health.ts` holds `checkUpgradeErrors` / `checkSelfUpgradeHealth` / `upgradeErrorResolved` (re-exported by the façade). To add a check: add an entry in the topic module, place it in `DOCTOR_CHECK_REGISTRY` where its output belongs, and categorize every emitted name in `src/core/doctor-categories.ts`. Tests: `test/doctor-registry.test.ts` (category contract with FAIL/Why/Fix/See, `emits[]` equals the AST walk, STOP positions), `test/doctor-mode-matrix.serial.test.ts` (entries run, STOP point, engine calls and `--fix` mutations per mode), and the W0 goldens `test/doctor-registry-golden.test.ts` (the AST walker follows `runDoctorRegistry` into the registry), `test/doctor-early-stop-golden.serial.test.ts`, `test/doctor-json-golden.test.ts`.
+- `src/commands/doctor/registry.ts` + `src/commands/doctor/context.ts` — the doctor check registry (refactor wave 1, W4 doctor). `DOCTOR_CHECK_REGISTRY` lists 67 `DoctorEntry` records `{ name, emits, run(ctx) -> Promise<Check[] | STOP_DOCTOR> }` in output order; `runDoctorRegistry(ctx)` runs them, returns the checks gathered so far on `STOP_DOCTOR`, and otherwise finishes the DB-checks progress phase. Execution groups: filesystem-first entries (the resolver-health entry applies `--fix` before it scans), the no-engine connection lane plus a STOP when `--fast` or no engine, the live connection entry plus a STOP when `getStats` failed, then the DB entries, which take the engine via `connectedEngine(ctx)`. `DoctorContext` carries the parsed flags (`jsonOutput`, `fastMode`, `doFix`, `dryRun`, `scope`, `orphanRatioSourceId`, `args`), `engine`, `dbSource`, `connectError`, `progress`, the skills-dir resolution and the cross-entry values `autoFixReport`, `schemaVersion`, `connectionFailed`, each written by the entry that computes it. Entry modules (one `run*` function per former `buildChecks` block, moved verbatim): `checks/skill-group.ts`, `local-runtime.ts`, `supervisor-health.ts`, `local-audits.ts`, `db-connection.ts` (also `pgbouncerPrepareCheck`, `classifiedConnectionCheck` and the two STOP gates), `schema-health.ts`, `embedding-health.ts`, `graph-health.ts`, `data-integrity.ts`, `content-quality.ts`, `knowledge-health.ts`, `queue-assets.ts`, `sync-search.ts`; `checks/legacy-token-grants.ts` (F3) emits `legacy_token_grant_shape` (info: active tokens still on the JSONB-only grant shape, fix `gbrain auth rescope --migrate-legacy`) and `legacy_token_grant_drift` (warn: per-token drifted axes with the two adopt commands); `checks/grant-new-ops.ts` (D4) emits `grant_new_ops_available` (warn: active clients and tokens whose operation snapshot or stored surface keeps operations their scopes allow out of reach, with proven blockers apart from inferred grant age, per-grant names in details, and an ask_user fix whose rescope argv differs for tokens and clients; `--operations all` is a disclosed choice, never the fix); `checks/upgrade-health.ts` holds `checkUpgradeErrors` / `checkSelfUpgradeHealth` / `upgradeErrorResolved` (re-exported by the façade). To add a check: add an entry in the topic module, place it in `DOCTOR_CHECK_REGISTRY` where its output belongs, and categorize every emitted name in `src/core/doctor-categories.ts`. Tests: `test/doctor-registry.test.ts` (category contract with FAIL/Why/Fix/See, `emits[]` equals the AST walk, STOP positions), `test/doctor-mode-matrix.serial.test.ts` (entries run, STOP point, engine calls and `--fix` mutations per mode), and the W0 goldens `test/doctor-registry-golden.test.ts` (the AST walker follows `runDoctorRegistry` into the registry), `test/doctor-early-stop-golden.serial.test.ts`, `test/doctor-json-golden.test.ts`.
- `src/commands/doctor/checks/git-convergence.ts` — `git_convergence` (#5063, brain category, after `sync_freshness`): for every non-archived filesystem source root plus `sync.repo_path` (connector sources skipped), `git status --porcelain -z` and `rev-list --left-right --count @{u}...HEAD` against the local upstream ref, never a fetch, each call bounded at 5 s and at most 50 roots. Commits not on the upstream warn after 6 h and fail after 24 h (oldest unpushed commit time); uncommitted changes warn once the oldest changed file is older than 6 h; behind is reported, not judged. Emits nothing when no probed root has an upstream. `bootstrap-checks.ts` `bootstrap_push_health` also warns, instead of `ok`, when a recent successful push leaves the receipt workspace ahead of `origin/<branch>`. `scripts/smoke-test.sh` accepts a configured database URL (`engine status` `db_url_source`) and trusts doctor `embedding_provider` over raw OpenAI/Voyage keys. Tests: `doctor-git-convergence-5063.test.ts`, `bootstrap-doctor-checks.test.ts`, `smoke-test-worker.test.ts`.
- `src/commands/doctor/` — the doctor module directory (the meat behind the `doctor.ts` façade). `checks/` holds the check-function library in bundles grouped by concern (`core-health.ts`, `queue-jobs.ts`, `extraction-sync.ts` (its `sync_freshness` check excludes sources disabled by `isSyncDisabledConfig` and adds `--no-pull` to its sync hint on a managed brain; `content_hash_duplicates` prescribes `GBRAIN_SOURCE=<id> gbrain delete <bare-slug> --force` per wrong-root pair, naming each source when pairs span several, and never a hard purge; `cycle_freshness` in `consolidation-cycle.ts` still monitors their maintenance; its `atom_provenance_drift` check scopes drift to page-bound atoms and splits it into `source_changed` / `source_gone`; atoms with no `source_slug` — transcript-origin `source_path`-only rows, whose hash is over a file and whose page liveness cannot be resolved by slug — are reported as their own `slug_unbound` count and never enter the drift total or the WARN ratio), `graph-embedding.ts`, `search-eval.ts`, `calibration.ts`, `consolidation-cycle.ts`, `pglite-worker.ts`, `routing-federation.ts` (`source_routing_health` exempts zero-page skill-pack sources), `verbs-reflex.ts`, `stale-mentions.ts`, `timeline-history.ts` (`timeline_history`: database-only timeline rows, bounded to 2,000 pages / 10 s per run with a cursor kept in config `doctor.timeline_history.scan:<sources>` so successive runs finish a pass (a clean finished pass stays `ok` until a newer timeline row; `doctor-timeline-history-cursor-5821.test.ts`), exact-or-lower-bound counts, kept non-round-trippable rows informational, repair `gbrain repair timeline`), `derived-visibility.ts` (`derived_visibility`: atoms and synthesized concepts without explicit visibility or looser than their origin, one exact aggregate, repair `gbrain repair visibility`), `engine-fit.ts` — the last carrying `pglite_scale` + the engine-free `db_repair_recurrence` over the db-repair receipts); `schema-pack-checks.ts`, `report-remote.ts`, `bootstrap-checks.ts`, and `skill-checks.ts` are the four tail-cluster modules (schema-pack checks, the remote/thin-client doctor report, bootstrap checks, skill checks). `harness-hook-checks.ts` (`harnessHookCarrierChecks`, called from `bootstrap_harness_health`) reads each receipt-named Claude Code hook carrier read-only: an event wired more than once by this install warns `harness_hook_duplicates` with a consented re-run carrying the install's `--project`/`--no-capture` choices, a lookalike it did not write warns `harness_hook_unowned` (operator judgement), an unparseable carrier warns naming the file, and entries the host stripped of their marker are an `ok` info row; `plugin_lane_collision` iterates `enabledPluginLanes`. `multiSourceDriftCheck` is the one local/remote `multi_source_drift` verdict: on a managed brain (`managedPersistenceEnabled`) its sync advice names `--no-pull` and drops `--include-gitignored`, unmanaged wording is unchanged, and any skipped source keeps it warn/not_verified. `src/core/multi-source-drift.ts` derives a `git-root`-pinned source's slug prefix from its git toplevel (realpaths, empty at the repo root) and skips only a source whose toplevel cannot be resolved (`git_root_skipped`). `graph-health.ts` `graph_coverage`, like onboard's link and timeline coverage, is `ok` (not applicable, with the count) below `MIN_ENTITY_PAGES_FOR_COVERAGE` (5) eligible entity pages. All are re-exported by the façade. Structural guards that pin doctor source text load it through `test/helpers/doctor-source.ts`: `doctorSource()` concatenates the façade plus every `src/commands/doctor/**/*.ts` (façade first, then sorted) so a module move can never take a pinned string out of a guard's sight; `doctorFileSource(rel)` reads one named file for positional/ordering assertions; the helper also feeds the `doctor-source-helper` detector in `scripts/classify-tests.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` keeps this directory on the doctor command's flag-scan surface. Two read-only derived-data checks live beside them: `timeline-orphans.ts` (`timeline_orphans`, samples 500 pages for rows an earlier page version produced that the current text no longer does; fix is `gbrain extract timeline --prune-orphans`) and `slug-collisions.ts` (`slug_collisions`, walks each live source checkout with `collectSyncableFiles` and reports paths that map to one slug plus the indexed one; sources without a checkout are skipped). `checks/graph-embedding.ts` `checkJunkEntityHubs` (#6158) splits connector contact pages (frontmatter `google_contact_id` or a connector source kind) into `details.connector_twins` with their main-brain `canonical_twin`, never calls them extractor-minted or offers `junk_hub_exempt`, and carries `fix_unavailable_reason: 'operator_judgement'` while the defer-to-twin policy is open.
diff --git a/docs/architecture/key-files/evaluation.md b/docs/architecture/key-files/evaluation.md
index e2108d8134..b425340a00 100644
--- a/docs/architecture/key-files/evaluation.md
+++ b/docs/architecture/key-files/evaluation.md
@@ -5,7 +5,7 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/eval/longmemeval/reader.ts` + `gateway-client.ts` — the LongMemEval answer request seam, exported as `gbrain/eval/longmemeval/reader`. `resolveReaderConfig` selects notes-first/1024 by default or the frozen direct-v3/512 baseline; `buildReaderRequest` changes only the system instruction and budget, retaining the same full-session sanitizer, evidence order and dates. `readerConfigHash` pins mode, system-prompt version/sha, requested model and token budget. `generateAnswer` reports the provider finish reason and joins every text block. The command records `reader_partial_output` as a diagnostic, never a completed hypothesis, when the reader stops at the limit or returns empty/unknown completion; those failures count in the judged headline denominator and fail the run without automatic paid retries. Tests: `test/longmemeval-reader.test.ts`, `test/eval-longmemeval-reader-mode.slow.test.ts`, `test/eval-answer-packet.test.ts` (historical explicit direct baseline).
+- `src/eval/longmemeval/reader.ts` + `gateway-client.ts` — the LongMemEval answer request seam, exported as `gbrain/eval/longmemeval/reader`. `resolveReaderConfig` selects notes-first/1024 by default or the frozen direct-v3/512 baseline; `buildReaderRequest` changes only the system instruction and budget, retaining the same full-session sanitizer, evidence order and dates. `readerConfigHash` pins mode, system-prompt version/sha, requested model and token budget. `generateAnswer` reports the provider finish reason, joins every text block and keeps the call's provider-normalized `usage` (A1: `ReaderUsage` with total, uncached, cache-read and cache-write input, output and reasoning tokens; the cache counts are subsets of the total), which the command writes as `reader_usage` on every answered row (null when no reader call ran). `readerUsageFromMessage` reads the gateway adapter's `gbrain_usage` record or the Anthropic Messages convention. The command records `reader_partial_output` as a diagnostic, never a completed hypothesis, when the reader stops at the limit or returns empty/unknown completion; those failures count in the judged headline denominator and fail the run without automatic paid retries. Tests: `test/longmemeval-reader.test.ts`, `test/eval-longmemeval-reader-mode.slow.test.ts`, `test/eval-answer-packet.test.ts` (historical explicit direct baseline).
- `evals/brainbench/` — the committed BrainBench corpus: 141 fixtures (135 generated + 6 hand-authored spike) / 241 gold-annotated turns across 7 categories (kta-pos/kta-neg/push/write-back/continuity/multi-source/adversarial), ~15% holdout (excluded from the CI gate, scored in published `--include-holdout` runs). `generator/gen.ts` rebuilds the corpus byte-identically (Mulberry32, seed 42; whole-cloth fictional universe from curated synthetic name pools so scenario privacy is structural; prose is template-synthesized with PRNG-selected variants — deliberately no LLM pass, difficulty stays controlled; several know-to-ask variants intentionally exercise documented v1 reflex limits so the baseline measures the roadmap). `gold/` is sealed; `schema/` is the foreign-runner contract (gbrain-evals drives the suite as a subprocess via `--fixtures DIR --gold DIR --json --out FILE`); `baselines/main.json` is the committed gate baseline; `_ledger.json` records counts/seed/rebuild command. CI: the `.github/workflows/test.yml` `brainbench` job + `scripts/ci-brainbench-gate.sh` (fetches MAIN's baseline via `git show origin/master:…` — a PR cannot rewrite what it's compared against; first-landing path runs ungated) + `scripts/render-brainbench-delta.ts` (compact step-summary/PR-body delta block from the `--out` artifact). Privacy: `scripts/check-synthetic-corpus-privacy.sh` scans `evals/brainbench/{fixtures,gold}` in `bun run verify`.
diff --git a/docs/architecture/key-files/google-and-loops.md b/docs/architecture/key-files/google-and-loops.md
index 8f76120664..09e637745a 100644
--- a/docs/architecture/key-files/google-and-loops.md
+++ b/docs/architecture/key-files/google-and-loops.md
@@ -44,7 +44,7 @@ Historical Gmail repair selects explicit nested MIME metadata fields, excluding
- `src/core/harness/credentials.ts` + `delivery.ts` + `install.ts` — Private credential handoff and host delivery journal, ownership-preserving native configuration and isolated thin launchers. A committed active client and matching current secret are prerequisites for recovery. Machine handoffs preserve optional POST/Basic authentication methods. Native setup is a distinct nested-client artifact; metadata reads never access journals or SDK client objects containing hashes. Configuration removal and server revocation are separate actions.
- `src/core/harness/oauth-setup.ts` + `client-setup.ts` — explicit client metadata projection, flow selection, native OAuth setup/private-file validation, and live-row-locked secret delivery recovery. Public PKCE needs no journal; confidential exports validate the retained secret against current registration, and machine exports discard cached tokens. Unknown/mixed flows refuse until an explicit supported flow is selected.
-- `src/core/harness/capabilities.ts` + `src/mcp/capabilities.ts` — Shared effective-grant orientation for OAuth whoami and authenticated `gbrain://capabilities`. A stored client token lifetime outside 60 to 7,776,000 seconds (`AuthInfo.tokenTtlSeconds`) reports `token_ttl_invalid`, and the delegation repair template then includes a `--token-ttl <APPROVED_TTL_SECONDS>` choice, since every grant write validates the merged lifetime. The resource preserves the exact seven-tool surface; source, operation, scope, fence and server-gate restrictions remain enforced at dispatch. No worker probe or per-tool database query during discovery. Shared administration guidance explains separate owner authority, links the MCP admin runbook, and exposes an admin URL only for a configured credential-free HTTP MCP endpoint. Stdio never infers an HTTP address.
+- `src/core/harness/capabilities.ts` + `src/mcp/capabilities.ts` — Shared effective-grant orientation for OAuth whoami and authenticated `gbrain://capabilities`. A stored client token lifetime outside 60 to 7,776,000 seconds (`AuthInfo.tokenTtlSeconds`) reports `token_ttl_invalid`, and the delegation repair template then includes a `--token-ttl <APPROVED_TTL_SECONDS>` choice, since every grant write validates the merged lifetime. The resource preserves the exact seven-tool surface; source, operation, scope, fence and server-gate restrictions remain enforced at dispatch. `grant_diagnosis` (shared with doctor `grant_new_ops_available` through `grantOperationGaps`, `grantAge` and `grantRescopeArgvs`) counts the operations the grant's scopes allow but its operation snapshot, its client pin or the server ceiling block, names none of them, keeps inferred grant age apart (`intent_unknown` without catalog provenance), and builds host commands only from the verifier's principal. No worker probe or per-tool database query during discovery (one audit read for provenance when a snapshot excludes operations). Shared administration guidance explains separate owner authority, links the MCP admin runbook, and exposes an admin URL only for a configured credential-free HTTP MCP endpoint. Stdio never infers an HTTP address.
- `src/commands/mcp.ts` + `mcp-provision.ts` + `harness-connect.ts` — Host-side grant/preview/CAS and recoverable private delivery, followed by installation inside the intended harness. Codex, Claude Code and opencode installs (`src/core/harness/install.ts`) store the bearer token inline in the harness config; `inlineTokenReceipt` adds `token_storage`, `config_path`, `renew_command`, `if_exposed` (invalidate-tokens preview/apply, renew, reload; `renew_command` carries `--fresh-token` for renewable handoffs so it always exchanges a new token) and a `token_warning` when a Git working tree would commit the file, and `harness-connect.ts` repeats them on stderr in human mode without printing the token (#5775; `test/harness-token-receipt.test.ts`). Running PGLite hosts are administered through their authenticated API, never by opening a second database process. CLI status uses the delivery-aware exit verdict. `mcp-admin.ts` and `mcp-admin-http.ts` provide engine-free owner commands with explicit-file/env credential precedence, in-memory sessions, private native exports, versioned lifecycle previews, and safe stage/outcome/remedy receipts. Unknown mutation outcomes require inspection instead of automatic repetition. `runMcp` also dispatches `gbrain mcp expose` to `runMcpExpose` (dynamic import of `./mcp-expose.ts`; HELP carries the expose lines so the flag registry harvests them) and sets the CLI exit verdict from its returned code. `mcpNeedsEngine(args)` is true only for `grant` without an owner credential (`--admin-token-file` or `GBRAIN_ADMIN_BOOTSTRAP_TOKEN`) and outside help; `admin`, `expose`, and `verify` never open the database.
- `src/commands/mcp-expose.ts` — `gbrain mcp expose [--port N] [--funnel] [--surface] [--enable-dcr] [--no-tailscale] [--no-service] [--no-install] [--force] [--dry-run] [--yes] [--json]` / `--status` / `--remove`: publishes `gbrain serve --http` on the user's Tailscale tailnet (Serve by default, Funnel only with the explicit flag) and keeps it running as a user service. `runMcpExpose(args, deps?)` returns the exit code (0 done, 1 failed, 2 needs `--yes`, the prompt was declined, or a step is pending — a tailnet feature to enable, Tailscale login, tailnet certificate). Arg validation via `validateHarnessArguments` (exclusive pairs `--status`/`--remove`, `--funnel`/`--no-tailscale`, `--dry-run`/`--status`); the help text names every flag and the `verify.local` / `verify.tailnet` checks. Ordered named checks — `plan` (platform, execution environment, engine kind from `loadConfig()`; thin clients are refused with "run on the brain host"; `engine === 'unknown'` — no config or an unreadable one — without `--no-service` is refused as `no_brain_config` / exit 1 with next action `gbrain init` BEFORE consent, because a service around a missing brain only crash-loops, while `--dry-run` still prints the plan with the refusal marked and exits 0; on a PGLite engine `deps.pgliteHolder` (default `probeLivePgliteHolder` from `src/core/bootstrap/uninstall.ts`, a read-only lock-file probe) is consulted with `cfg.database_path`, and a live holder that is not our own managed service — receipt present with `service.state` `running`/`loaded` — adds a `Lock` plan line plus a `pglite_lock` check with status `warn` (never a stop); `--no-tailscale` over an existing receipt whose `tailscale.dns_name` is set (a live Serve/Funnel mapping) is refused BEFORE consent as `tailscale_receipt_present` / exit 1 with next actions `gbrain mcp expose --remove --yes` and the re-run without the flag — `--dry-run` marks it `WOULD BE REFUSED`; then probes `127.0.0.1:<port>` with `probeOccupied(d, port, url)` — occupied when EITHER the injectable `deps.tcpProbe` (default `defaultTcpProbe`, one `node:net` connect, socket destroyed on every outcome; true on connect, false on refusal / timeout / throw) accepts a TCP connect OR the `/health` fetch RESOLVES with ANY status (2xx, 404, 500), so a non-HTTP listener counts too; only both rejecting is free — and refuses a foreign listener with no receipt claiming that port as `foreign_listener` BEFORE anything is published unless `--no-service`; the message names the interrupted-run escape hatch `gbrain mcp expose --remove --yes`; `probeHealth` (`res.ok`) stays the bar for `verify.local` / `verify.tailnet` / `--status`), `consent` (shared `confirmOrFinish` for publish and `--remove`: one stderr y/N prompt on a TTY; declining is `pending` / exit 2 / `declined` with "Nothing changed. Re-run with --yes to confirm."; non-interactive without `--yes` prints the plan and exits 2 / `confirmation_required`; every re-run hint is rendered by `rerunCommand(opts)` — the user's publish flags + `--yes`), `tailscale.binary` (install plan: brew cask on macOS — then `open -a Tailscale` and a bounded poll of `tailscale status --json`, up to 20 attempts 1s apart, breaking as soon as the app's daemon answers and otherwise falling through to the login step's daemon-not-running handling — official installer on Linux, `--no-install` → exit 1), `tailscale.login` (Linux `sudo tailscale set --operator=<user>` non-fatal then flagless `sudo tailscale up` — `sudo` is put in front of the binary ONLY when `isSystemTailscaleBinary(binary)` holds (one of `TAILSCALE_BINARY_CANDIDATES`, literally or via `realpathSync`); a user-writable `tailscale` found on PATH stops the step as `pending` / exit 2 / `tailscale_login_manual` with the message "tailscale at <path> is not a system install, so gbrain will not run it with sudo. If you trust that binary, sign in yourself (this runs it as root): `sudo <path> set --operator=$USER && sudo <path> up`, then re-run: <rerun>" — the command is `tailscaleManualLoginCommand(binary)`, naming the discovered path shell-quoted, because a binary outside sudo's `secure_path` is exactly this case — and never spawns `sudo`; macOS `tailscale up`; bounded wait via `GBRAIN_TAILSCALE_LOGIN_TIMEOUT_MS`), `tailscale.identity` (MagicDNS name → `public_url`; pre-checks so `tailscale serve`/`funnel` — which wait interactively instead of failing when a feature is off — are never started blind: empty `CertDomains` → `pending` / exit 2 / `tailscale_https_not_enabled` with `TAILSCALE_ADMIN_DNS_URL`; `--funnel` with `funnelCapable === false` → `tailscale_funnel_not_enabled` with the ACL admin + Funnel KB URLs; `funnelCapable === null` proceeds), `tailscale.publish` (reads the serve config through `readServeView`, which FAILS CLOSED — it returns `{ view: ServeStatusView | null, stderr, status }` with `view: null` when `tailscale serve status --json` exits non-zero / is killed (`status: null`) or when stdout is not a JSON object per `parseServeStatusStrict`; an empty document / `{}` / `null` from exit 0 is the legitimately empty view — a null view before `--bg` is described once by `describeServeReadFailure` (`{ kind, detail, fix }` from one `classifyTailscaleError` call), records `tailscale.publish` = fail and returns exit 1 with reason `tailscale_<kind>` without publishing; a null view after `--bg` is `tailscale_publish_unconfirmed` naming the read failure; refuses a `/` handler proxying a different port, a foreground session or a raw TCP forward without `--force` as `foreign_serve_config` — `next_actions` says `tailscale serve status`, only `message` explains `--force`; `PUBLISH_TIMEOUT_MS` (60s) bounds `--bg`, `SERVE_OFF_TIMEOUT_MS` (30s) every `--https=443 --set-path=/ off` and `STATUS_READ_TIMEOUT_MS` (15s) both status reads; a `status: null` timeout is `unknown` with a run-by-hand hint; stderr classified by `classifyTailscaleError` as the second line of defense; switching our own handler's shape pre-clears ONLY in the funnel → tailnet direction (`funnel --https=443 --set-path=/ off` before `serve --bg`, because `serve --bg` over a Funnel mount keeps `AllowFunnel`; tailnet → funnel is one atomic `funnel --bg`), and when that pre-off was followed by a failed publish (non-zero, timeout, or unconfirmed) `restorePrevious` best-effort re-publishes the previous shape with `tailscaleServeArgv(port, { funnel: true })`, re-reads the view, and appends to the `tailscale.publish` detail whether "the previous funnel handler was restored" or "could NOT be restored"; the existing receipt is never touched on those paths), `admin_token` (ensure the 0600 token file, never printed), `service` (launchd / systemd user unit / `manual` fallback with the exact foreground and `nohup` commands; a `--no-service` re-run carries the existing receipt's service block unchanged and does not rewrite the wrapper; `service_install_failed` still writes the receipt with `service.state: 'stopped'` before exit 1 so `--status`/`--remove` can clean up the published handler; the receipt is ALSO written right after a successful service step — service state as probed at that moment — before verify runs, so a kill during verify always leaves `--status`/`--remove` something to find), `verify.local` (wall-clock `/health` polling up to 20s, timeout → `warn`, exit 2, `verify.tailnet` skipped), `verify.tailnet` (up to 30s, `pending` is exit 2 — EXCEPT when the last probe's rejection was a name-resolution failure per `mcp-expose-probe.ts`: Bun's `fetch` rejects an unresolvable host and a refused connection with the same "Unable to connect. Is the computer able to access the url?" / `ConnectionRefused`, so after a rejected fetch the URL's hostname (never an IP literal or `localhost`) is handed to `deps.lookup` — default `dns.promises.lookup`, bounded by the probe timeout — and a rejection with code `ENOTFOUND` / `EAI_AGAIN` / `EAI_NONAME` / `EAI_NODATA` / `DNS_ENOTFOUND` (or a message naming one) is the verdict, the fetch-message regex staying a secondary hint; a name that resolves but does not answer stays `pending`: then the check is `warn` with `unresolvedDetail(dnsName)` — "this host cannot resolve <name> (MagicDNS may be off here: `tailscale set --accept-dns=true`); devices that do resolve it may already reach the server" — and the run exits 0, since this host's resolver says nothing about the server), `receipt` (rewrites the early receipt with the settled state — the supervisor is re-probed once verify.local ran — keeping `created_at`). The admin-token, service and verify steps run inside one try: a THROW there after this run's `--bg` succeeded but BEFORE the early receipt is rolled back by `rollbackAfterThrow(d, s, opts, published, error, receiptWritten)` — the fresh handler is turned off again with `tailscaleServeOffArgv({ funnel })` only when no `/` handler for our port existed before the run (a pre-existing one is left in place), a `rollback` check records what happened — "turned off again" is claimed only when a re-read of the serve view after an exit-0 `off` no longer shows our port; an exit-0 `off` whose re-read still shows it is a `warn` "NOT turned off (… the handler is still present)", an unreadable re-read is a `warn` "state unknown", and an `off` that exits non-zero or throws is a `warn` whose message says the handler was NOT turned off — no receipt is written, and the error is re-thrown so the outer catch reports `mcp_expose_failed` with a message naming the handler state; once the early receipt is on disk (`receiptWritten`, checked first) a throw tears nothing down (`rollback` = skipped pointing at `--status` / `--remove --yes`), because the receipt makes everything findable (the non-throwing `service_install_failed` path keeps its partial receipt). Success banner and `next_actions` gate the local-agent line on the engine: Postgres → `gbrain bootstrap harness --yes --port N`; PGLite → pre-mint (`gbrain auth create … --scopes read,write` before the service runs) + `--token`, or the scoped `mcp grant … --url http://127.0.0.1:N/mcp --admin-token-file …` + `gbrain connect … --install` path, and "host-side commands fail with `live_serve` — administer through the running server". `--json` emits one stdout document `{ status, receipt, checks[], next_actions, reason?, message? }` with prose on stderr; every `inherit` subprocess redirects its stdout to stderr under `--json`. `--status` and `--remove` read the receipt through `readExposeReceipt`'s shape guard (a partial receipt is `not_exposed` / "nothing to remove", never a crash) and execute the tailscale binary from `resolveReceiptBinary`: the receipt's recorded path is honored only when it still exists AND is either what `findTailscaleBinary` finds now or one of `TAILSCALE_BINARY_CANDIDATES`, otherwise discovery wins — a path in a receipt is data, never a licence to run it. the probes — `probeHealth` (`res.ok`), `probeOccupied` (any response, or an accepted TCP connect), the bounded never-throwing `tryFetch` → `FetchOutcome { res, unresolved }`, `pollHealth` → `{ ok, unresolved }` with the LAST probe's resolution verdict, `unresolvedDetail`, `defaultTcpProbe`, `defaultLookup` — live in `src/commands/mcp-expose-probe.ts` and take the narrow `ProbeDeps` slice of the resolved deps (`fetch`, `tcpProbe`, `lookup`, `now`, `sleep`, `healthIntervalMs`); `defaultTcpProbe` is re-exported here so its import site never moved; `isLiveService(state)` is the one definition of "the supervisor reports our service" (`running` or `loaded`) used by the lock-holder exemption, the service check, `--status` and both `--remove` paths; `serviceLabel` builds on `serviceKindLabel` (`launchd <label>` / `systemd (user) <unit>`). `--status` runs its four independent probes (serve config, supervisor state, local and tailnet `/health`) concurrently with `Promise.all` and still reports the checks in the fixed order `receipt`, `tailscale.publish`, `service`, `verify.local`, `verify.tailnet`; an unreadable serve config (null view) is a FAILED `tailscale.publish` check / exit 1, never "handler present"; a tailnet `/health` rejected for name resolution is `verify.tailnet` = warn (same `unresolvedDetail`), not `pending`, and does not by itself make the exit non-zero. `--status` with NO receipt is `runStatusWithoutReceipt`: it runs the read-only `probeLeftovers(d, opts.port)` (`--port` is honored) and, when the wrapper, the plist / unit or a live service, or a `/` handler on `:443` proxying the port is found, emits one `warn` check per artifact (`receipt`, `service`, `tailscale.publish`, `files`), pushes `recoveryCommand(port, force)` (`gbrain mcp expose --remove --yes`, `--force` only when a handler stands alone with no wrapper / service corroborating it, `--port N` when non-default) to `next_actions`, and finishes `error` / exit 1 / `leftovers_without_receipt` (also under `--json`); an unreadable serve status alone is a caveat warn, not a leftover; nothing found keeps the `not_exposed` answer (exit 0, `--json` exit 2). `--remove` (consent; decline is `pending` / exit 2) probes the supervisor and removes a service that exists even when the receipt says skipped — `recordServiceUninstall` prints the uninstall notes, and when `launchdBootoutFailed(result)` (a `launchctl bootout failed: …` / `unload failed: …` note, i.e. a non-"not loaded" failure) the `service` check is `warn` pointing at `launchctl print gui/$(id -u)/com.gbrain.serve` and "the launchd job (bootout failed)" is added to "Left in place"; it returns the one-line service summary quoted below — then clears only gbrain's own serve/funnel handler through `turnOffOurHandler` (Funnel off first; every `off` is `--https=443 --set-path=/ off`, scoped to our `/` mount; the serve config is re-read only after an `off` command ran, otherwise the view already read is reused; a failed re-read is reported as `unknown` — a warn, never "gone"; a foreign port on `:443` gets "nothing to turn off"). `--remove` never reports success while our handler survives: when `turnOffOurHandler` returns `remaining` as a handler (`tailscale.publish` = fail) or `'unknown'` (= warn), `finishHandlerNotRemoved` keeps the receipt AND the wrapper (mirroring the unreadable-status branch), records `receipt` = skipped "kept: …", pushes `tailscale serve status` + the re-run to `next_actions`, says which service outcome already happened, and exits 1 with reason `handler_not_removed`; `--remove` never runs `tailscale serve reset`, never uninstalls or logs out, keeps the admin token unless `--force` (deleted through the same `unlinkQuietly` as the wrapper and receipt), and unlinks the wrapper / receipt / token ONLY when the path's directory is the serve directory — a receipt path elsewhere is left untouched and named in "Left in place" (also in the plan). The receipt's recorded `plist_path` / `unit_path` are data, never a licence: `uninstallServeService` is always handed the computed `d.plistPath` / `d.unitPath` (home + the fixed label / unit name), and a recorded path that differs is not touched and is named in "Left in place" as "recorded in the receipt but not the expected location". A null serve view during `--remove` fails closed: `tailscale.publish` = fail "could not read tailscale serve status; handler left as is", reason `tailscale_serve_status_unreadable`, exit 1, and the receipt AND wrapper are kept so a re-run finishes the job. With NO receipt, `runRemoveWithoutReceipt` recovers from what is on disk through the same `probeLeftovers` `--status` uses (`wrapperPath(serveDir)`, the launchd plist / systemd unit or a `running`/`loaded` service, a `/` handler on `:443` proxying `opts.port` — `--port` may accompany `--remove`, default 3131); inside it the supervisor chain (`probeServiceTarget` → `serveServiceState`) and the `readServeView` read run concurrently under `Promise.all` (the binary is resolved synchronously first) and the plan / checks are emitted in the fixed order afterwards; the re-run hints come from `recoveryCommand`. The handler is turned off only with corroborating gbrain evidence — the wrapper present, our unit/plist present, or the supervisor reporting our service live — or with `--force`, because another tool may proxy `:443` to the same port: a handler standing alone is reported (`tailscale.publish` = warn naming the proxy target and `--force`, next action `gbrain mcp expose --remove --yes --force`) and left in place on the "not exposed — nothing to remove" exit-0 path; with `--force` the plan line says so. Otherwise it prints a "Recovering without a receipt" plan (`receipt` check = warn), takes consent as usual, removes exactly those artifacts (service via the supervisor — the same `recordServiceUninstall` bootout-failure warn applies — wrapper, the handler — funnel off first when `AllowFunnel` lists the host), leaves the admin token file, and finishes `removed` with reason `recovered_without_receipt`; a handler that survives the `off` is `handler_not_removed` / exit 1 here too, with the wrapper deliberately KEPT as the corroboration the re-run needs (`files` = skipped "kept: the wrapper"; the re-run hint carries `--force` when no wrapper is left); an unreadable serve status on this path (gbrain evidence present, `serveUnreadable` set) fails closed exactly like the receipt path — the service, when found, is still uninstalled, the plan says the handler cannot be checked and the wrapper is kept, `tailscale.publish` = fail "…; handler state unknown", `files` = skipped "kept: the wrapper" (or "nothing (no wrapper was found)"), `next_actions` = `tailscale serve status --json` + the recovery command (`--force` when no wrapper is left), exit 1 with reason `tailscale_serve_status_unreadable` and message "could not read tailscale serve status; handler state unknown"; when nothing of ours is found the answer stays "not exposed — nothing to remove", exit 0 (an unreadable serve status is then only the caveat warn — there is nothing to keep and a handler alone would not be touched anyway). Every filesystem/exec effect goes through injectable deps so tests run against a fake runner in a tmpdir. Success guidance separates owner login, native OAuth registration, and machine grant/install. It uses the expose-managed owner file only when installing or keeping that service; publication with `--no-service` and no managed service instead requires the existing server's independently configured owner credential. Publishing receipts and health checks do not certify client authorization or native activation.
diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.md
index 4510001f4b..49b958b759 100644
--- a/docs/architecture/key-files/mcp.md
+++ b/docs/architecture/key-files/mcp.md
@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)`, `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts` — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash, so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness; every mutating op, successful or not, drops the engine's entries via `invalidateHotMemoryForEngine`, a build that raced it is not stored, and each hit revalidates the source's `fact_withdrawals` watermark so a forget from any process is never served), each producer isolated so one failure never drops another's key; A successful result's content[0] is compact `JSON.stringify(result)` (error envelopes stay indented); `opts.resultRows` threads the transport's row-shape choice into `OperationContext.resultRows`. empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. `retrievalNoticeBlocks` caps the saved-facts block at 1,500 characters and the other-names block at 400 (header included) with whole items only: the first item always shows, later items that would cross the ceiling are counted in a `(+N more…)` marker (pinned by `test/mcp-notice-ceilings.test.ts`). Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier: true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `accepted_pending` (a `write_pending` with an admitted non-terminal receipt, kept out of the admin error rate; `acceptedPendingReceipt` returns its receipt so serve-http logs the opaque `write_request_id`) / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). Logging paths route through this helper, not `JSON.stringify(params)`. Agent contract v1: every failure (unknown tool, source guard, validation, strict params, missing source scope, handler throws) goes through `errorResult` → `toAgentError` → exactly one content block; handlers emit advice through `ctx.emitNotice` and the empty-retrieval, unknown-param and backup-coverage blocks ride that channel (prefixed `[gbrain notice <code> kind=<kind>]` blocks + `_meta.gbrain_notices`), filtered by the notice ledger (`opts.noticeLedger` on HTTP). `dispatchRenderContext` binds `isCallable` for fixes; `unknownToolEnvelope(name, opts, 'unknown_operation')` keeps serve-http's frozen value; `localCallErrorEnvelope` is `gbrain call`'s envelope. `sessionSafetyNotices` adds the one-time `behavior_changes` disclosure (stdio: once per brain; HTTP: once per authenticated client, remote view) and, on stdio only, the queued `chat_fallback_hop` notice, on success and failure results alike. `requestMetaSessionId(request.params)` is the one reader of the request-level `_meta.session_id` (beside `arguments`); stdio (`server.ts`) and HTTP (`serve-http-mcp.ts`) both pass it as `opts.sessionId`, which wins over an arguments-level `_meta` and is clamped to `SESSION_ID_MAX_CHARS` (256). Caches keyed on it stay bounded: the hot-memory cache at `HOT_MEMORY_CACHE_MAX_ENTRIES` (1000) and the facts queue's per-session counter, deleted at zero. `retrievalNoticeBlocks` also appends the rate line for a rateable answer (`_meta.retrieval.answer_id` with `feedback.rateable`): `Rate after use: rate_answer { answer_id, rating: 1-5 }`, or the fuller wording when `how_to_rate` fired, capped at `RATE_LINE_MAX_CHARS` = 160 (#6192; `test/mcp-feedback-visible-answer-id.test.ts`).
-- `src/mcp/instructions.ts` — canonical MCP initialize-time agent operating contract, compile-time source text (no runtime filesystem dependency) shared by the stdio SDK server, the OAuth HTTP SDK server and the legacy raw HTTP initialize path. `buildMcpInstructions({writeback?, tools?})` GENERATES the contract from the caller's callable set (`tools.callable`, the tools/list predicate): a clause naming a tool (search/query/get_page, skills catalog, put_page, whoami, join/sync skills, put/delete skill, the memory loop's `context_pack`/`volunteer_context`/`remember`/`forget`) appears only when that tool is listed, so every tool named is in that surface's tools/list (`test/mcp-initialize-instructions.test.ts`). It always carries the error protocol (follow `fix.next`, then `fix.verify`) and the notice prefix, then the optional status-only line (F4), the opt-in ambient-writeback section (`src/core/facts/writeback-instructions.ts`) and the readiness tail (top two `missing`/`degraded` gaps among embeddings, chat_llm, migrations, worker — never a by-choice state). With no `tools` and no writeback it equals `GBRAIN_MCP_INSTRUCTIONS` (the every-tool rendering bootstrap writes to GBRAIN-INSTRUCTIONS.md). `resolveMcpInstructions(config, env?, opts)` appends the operator-set deployment identity LAST under `Deployment identity:` (`GBRAIN_MCP_INSTRUCTIONS` env when non-blank, else file-plane `mcp.instructions`). `installInstructionsResolver(server, compute)` swaps the SDK Server's initialize handler so the stdio and OAuth servers compute the contract (callable set + readiness tail via `src/mcp/initialize-context.ts`) when the client initializes; the constructor value stays the fallback on a throw. The legacy bearer transport builds it inline per initialize. Transport tests compare against the contract for that connection's own tools/list (`test/helpers/instructions-parity.ts`): `test/serve-stdio-roundtrip.test.ts`, `test/http-transport.test.ts`, `test/connect-bearer.test.ts`, `test/mcp-instructions-writeback.test.ts`; identity composition in `test/mcp-server-identity.test.ts` + `test/config-set-mcp-instructions.test.ts`. #6170: `contractClauses(c, writeback)` puts the short `Ambient writeback is ON (<mode>)` line (with `visibility "private"` under a private posture) in the memory clause when writeback is on, follows the data-not-instructions clause with the shortened error protocol and moves the forget caveat after the scope clause, so the writeback line, `Follow \`fix.next\``, `[gbrain notice`, `context_pack`, `put_page REPLACES` and `Writing:` end inside the first 2,048 characters on every surface (pinned per surface × mode × extract_facts × visibility in `test/mcp-initialize-instructions.test.ts`); the full writeback section stays appended last. Cat 40's measured "Answering from the brain" clause is verbatim; the change needs the D12 Cat 40 smoke before merge.
+- `src/mcp/instructions.ts` — canonical MCP initialize-time agent operating contract, compile-time source text (no runtime filesystem dependency) shared by the stdio SDK server, the OAuth HTTP SDK server and the legacy raw HTTP initialize path. `buildMcpInstructions({writeback?, tools?})` GENERATES the contract from the caller's callable set (`tools.callable`, the tools/list predicate): a clause naming a tool (search/query/get_page, skills catalog, put_page, whoami, join/sync skills, put/delete skill, the memory loop's `context_pack`/`volunteer_context`/`remember`/`forget`) appears only when that tool is listed, so every tool named is in that surface's tools/list (`test/mcp-initialize-instructions.test.ts`). When callable tools are left out of the listed set (`hiddenCallable`) and `request_tools` is callable, the hidden-tool sentence leads the contract, inside the 2,048 characters capped harnesses read (D1). It always carries the error protocol (follow `fix.next`, then `fix.verify`) and the notice prefix, then the optional status-only line (F4), the opt-in ambient-writeback section (`src/core/facts/writeback-instructions.ts`) and the readiness tail (top two `missing`/`degraded` gaps among embeddings, chat_llm, migrations, worker — never a by-choice state). With no `tools` and no writeback it equals `GBRAIN_MCP_INSTRUCTIONS` (the every-tool rendering bootstrap writes to GBRAIN-INSTRUCTIONS.md). `resolveMcpInstructions(config, env?, opts)` appends the operator-set deployment identity LAST under `Deployment identity:` (`GBRAIN_MCP_INSTRUCTIONS` env when non-blank, else file-plane `mcp.instructions`). `installInstructionsResolver(server, compute)` swaps the SDK Server's initialize handler so the stdio and OAuth servers compute the contract (callable set + readiness tail via `src/mcp/initialize-context.ts`) when the client initializes; the constructor value stays the fallback on a throw. The legacy bearer transport builds it inline per initialize. Transport tests compare against the contract for that connection's own tools/list (`test/helpers/instructions-parity.ts`): `test/serve-stdio-roundtrip.test.ts`, `test/http-transport.test.ts`, `test/connect-bearer.test.ts`, `test/mcp-instructions-writeback.test.ts`; identity composition in `test/mcp-server-identity.test.ts` + `test/config-set-mcp-instructions.test.ts`. #6170: `contractClauses(c, writeback)` puts the short `Ambient writeback is ON (<mode>)` line (with `visibility "private"` under a private posture) in the memory clause when writeback is on, follows the data-not-instructions clause with the shortened error protocol and moves the forget caveat after the scope clause, so the writeback line, `Follow \`fix.next\``, `[gbrain notice`, `context_pack`, `put_page REPLACES` and `Writing:` end inside the first 2,048 characters on every surface (pinned per surface × mode × extract_facts × visibility in `test/mcp-initialize-instructions.test.ts`); the full writeback section stays appended last. Cat 40's measured "Answering from the brain" clause is verbatim; the change needs the D12 Cat 40 smoke before merge.
- `src/mcp/publish-gates.ts` — publish-gate resolution for the honest tools/list. `readPublishGate(engine, config, key)`: dual-plane (DB > file > false), never throws — a FAILED read resolves false (hide-on-doubt matches the default-off consent posture). `disabledOpsForPublishGates(engine, config)`: the op-name set tools/list subtracts; one getConfig read per distinct gate key per call, deliberately NOT memoized so `gbrain config set mcp.publish_skills true` takes effect on the next list without a restart. Call-time gates inside the handlers stay as the fail-closed backstop (their denials carry `detail: 'config_key=<key>'` — the machine-readable denial grammar). Pinned by test/publish-gates.test.ts. `PUBLISH_GATE_KEYS` (every operation's gate key) is the set `gbrain config get` resolves DB-first, matching this resolver (`test/config-get-plane.test.ts`).
@@ -19,8 +19,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/mcp/source-preflight.ts` — `assertStdioSourceBindable(engine, env?)`: stdio-lane boot preflight called first thing in `startMcpServer`, before any transport attaches. A well-formed `GBRAIN_SOURCE` that names no ACTIVE source row (`SELECT id FROM sources WHERE id = $1 AND archived = false`, the same predicate as `assertSourceExists` in `src/core/source-resolver.ts`) throws a message naming the value and the fix (`gbrain sources list`), so serve exits 1 instead of binding every call to a phantom scope where reads return `[]` and writes die on the sources FK while health stays green. An inherited `__all__` emits an engine-free stderr warning with a source-binding recovery action, without widening its fail-closed scope. Unset env and malformed values are left to the resolver; an engine error fail-opens (guards config, not connectivity); a degraded engine (`isEngineDegraded`) is never touched so the boot does not spend the proxy's reconnect attempt. HTTP is out of scope (tokens carry their own source grant). Pinned by `test/mcp-stdio-source-preflight.test.ts` and real PostgreSQL/PGLite processes in `test/e2e/mcp-search-transport-matrix.test.ts`.
-- `src/core/mcp-registration.ts` — `REGISTRATION_SURFACE` (`starter`), `stdioServeArgv(bin, surface = REGISTRATION_SURFACE)` (`null` → bare `serve`) and `registeredSurface(text)` (an existing entry's pinned surface, `null` for bare, `undefined` when no serve command is visible): every stdio registration gbrain writes builds from them (readiness `harness_wiring`, init's quickstart, `bootstrap hooks` for Claude Code / Codex / opencode, the plugin generator, which also refuses root plugin manifests pinned elsewhere). The OpenClaw manifest stays a bare `serve`. Also the HTTP+bearer wiring helpers `connect.ts` re-exports. Test: `test/mcp-registration.test.ts`.
-- `src/core/ops/request-tools.ts` — `request_tools`: catalog (no args), descriptors (`{tools}`), and `{surface}`: per OAuth client on HTTP (ceiling, operator lock, rate limit, audit), and on the owner's stdio pipe `widenStdioSession` widens `ctx.stdioSurface` for the session (refused with the persistent route when `mcp.allow_session_widen` is off; clamped by `GBRAIN_MCP_FORCE_SURFACE`; returns `persisted:false, scope:'session'` and the new tools' schemas). A widenable stdio session's catalog lists the full surface. Tests: `test/request-tools.test.ts`, `test/request-tools-stdio.test.ts`.
+- `src/core/mcp-registration.ts` — `REGISTRATION_SURFACE` (`full` since S0, wave 0: callable and advertised; README, docs/mcp, INSTALL_FOR_AGENTS.md and the plugin manifests name the same value, which the S0 grep test in `test/mcp-registration.test.ts` keeps so), `stdioServeArgv(bin, surface = REGISTRATION_SURFACE)` (`null` → bare `serve`) and `registeredSurface(text)` (an existing entry's pinned surface, `null` for bare, `undefined` when no serve command is visible): every stdio registration gbrain writes builds from them (readiness `harness_wiring`, init's quickstart, `bootstrap hooks` for Claude Code / Codex / opencode, the plugin generator, which also refuses root plugin manifests pinned elsewhere). The OpenClaw manifest stays a bare `serve`. Also the HTTP+bearer wiring helpers `connect.ts` re-exports. Test: `test/mcp-registration.test.ts`.
+- `src/core/ops/request-tools.ts` — `request_tools`: catalog (no args), descriptors (`{tools}`; D1: an empty list or one with no caller-visible name returns the catalog plus `did_you_mean` drawn only from `visibleOpsForCaller`, never echoing the requested names, so an invisible existing op and a nonexistent one answer byte-identically), and `{surface}`: per OAuth client on HTTP (ceiling, operator lock, rate limit, audit), and on the owner's stdio pipe `widenStdioSession` widens `ctx.stdioSurface` for the session (refused with the persistent route when `mcp.allow_session_widen` is off; clamped by `GBRAIN_MCP_FORCE_SURFACE`; returns `persisted:false, scope:'session'` and the new tools' schemas). A widenable stdio session's catalog lists the full surface. Tests: `test/request-tools.test.ts`, `test/request-tools-stdio.test.ts`.
- `src/mcp/surface.ts` — MCP tool-surface modes: `'verbs'` (exactly the ops marked `verb: true`) | `'starter'` (the ~27-op daily-driver set) | `'full'` (default — identity; existing installs unchanged). `STARTER_OPS` is composed PROGRAMMATICALLY: a spread of `VERB_NAMES` (never a hand-count) + the fallback daily slice (`BRAIN_TOOL_ALLOWLIST` + the agent lane `submit_agent`/`get_agent_job`) + `whoami` + `request_tools` + `capture` (a DIRECT literal, deliberately NOT via the allowlist); re-derived from production usage via `scripts/derive-starter-ops.ts` (paste-in proposal, never an auto-edit). `ALWAYS_INCLUDED_STARTER_OPS` (verbs + `whoami` + `request_tools` + the agent lane + `capture`) is the exported always-set consumed by BOTH `derive-starter-ops.ts` and the advisor starter-fit collector, so neither re-types the composition. `parseSurfaceFlag` (strict, loud reject), `resolveSurface`/`resolveSurfaceWithSource` (flag > config `mcp_surface` > full, the `serve --http` order), `resolveStdioSurface` (stdio: `GBRAIN_SURFACE` > flag > config > full; an invalid env value is returned as `invalidEnv`, never fatal; `surfaceEnvInvalidNotice` builds its notice), `SURFACE_SOURCE_LABEL`, `filterOpsForSurface`, `allowedOpNames`, `createStdioSurfaceState` (the stdio session's one mutable allow-set; `widen(to)` recomputes it, read-only stays read-only), `sessionWidenAllowed` (`mcp.allow_session_widen`, DB > file, default true). `STARTER_OPS` also carries `mute_notice`, the dismissal for the coaching notices starter sessions receive. Enforcement is TWO-layer and fail-closed: the advertised list AND `dispatchToolCall`'s `allowedOps` set (a hidden op returns `unknown_tool` even when called by name) — applied on stdio (server.ts) and BOTH HTTP paths (serve-http.ts after `!localOnly`, and the second transport http-transport.ts). Per-client ceiling machinery (OAuth transport only): `effectiveSurfaceForClient` is the pure composition `clamp(min(server ceiling, client row surface ?? mcp.default_surface_dcr ?? ceiling))`; the per-REQUEST application lives in serve-http.ts's `resolveEffectiveSurface`, which short-circuits a `verbs` ceiling (min() cannot go lower, so the config read is skipped) and, on a default-surface read failure, applies the LAST successfully read default (held per process, fail-closed) so a transient config outage cannot silently widen a NULL-surface client to the ceiling; `resolveClientRowSurface` ignores unknown row values with a bounded warn-once (the column's value space is documented OPEN for future tier names); `resolveDefaultClientSurface` reads the DCR default dual-plane (DB > file > null) and never throws; `clampSurface`/`readForceSurfaceEnv` fold in the `GBRAIN_MCP_FORCE_SURFACE` kill switch — NARROW-ONLY by construction (min(); can never widen past the ceiling). `minSurface`/`surfaceWiderThan` own the verbs < starter < full rank math. Pinned by test/mcp-surface.test.ts (membership, monotonicity verbs ⊆ starter ⊆ full, ceiling + force-narrow cases). `--access read-only` (`parseAccessFlag`, stdio only; HTTP refuses it) intersects the surface with `isReadOnlyOperation` (read scope, not mutating, no required capability scope); `src/mcp/server.ts` uses that one set for tools/list, the capabilities resource (`access`), skill resources and dispatch `allowedOps`. Pinned by `test/serve-stdio-read-only.test.ts`. `mcp.advertised_surface` (`resolveAdvertisedSurface`, DB plane > file plane) narrows only what `tools/list` shows (`advertisedOps`, never wider than the callable set); dispatch keeps the ceiling. Stdio lists the advertised set plus tools `request_tools` described in this session (`OperationContext.revealTools` → `tools/list_changed`); the OAuth HTTP server lists a client's own row surface in full and otherwise the advertised set; the simple bearer transport reads the file plane once at startup. Initialize instructions carry `hiddenCallable` and name `request_tools` when tools are unlisted. `NEW_INSTALL_ADVERTISED_SURFACE` is what a fresh `gbrain init` writes (`'full'` writes nothing; the held-out agent benchmark picks verbs or starter). Pinned by `test/mcp-advertised-surface.test.ts`. Once a session widens (`request_tools {surface}`), the whole widened surface is listed.
- `src/mcp/tool-catalog.ts` — `renderToolCatalogMarkdown()`: the docs/TOOL_CATALOG.md renderer. Config-independent + deterministic (no engine/config reads, no timestamps): non-localOnly ops grouped one section per `Operation.area`, per-op first-sentence description (from `buildToolDefs`'s non-strict shape), scope, STARTER_OPS membership, publish-gate key. Generated by `scripts/generate-tool-catalog.ts`; freshness-guarded by `scripts/check-tool-catalog-fresh.sh` in `bun run verify` (the METRIC_GLOSSARY pattern). Pinned by test/tool-catalog.test.ts.
diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.md
index 25243bff10..b590aab253 100644
--- a/docs/architecture/key-files/security.md
+++ b/docs/architecture/key-files/security.md
@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/env-trust.ts` — Trust boundary for environment variables Bun auto-loaded from the cwd `.env` family. `CWD_DOTENV_FILES` (the eight names Bun auto-loads across NODE_ENV values), `splitDotenvLines` (Bun's line grammar: `\n`, `\r\n` AND a bare `\r` terminate a line, leading BOM stripped — shared with gbrain-env-file.ts), `dotenvValuesForKey(key, dir)` (value set across all assignments; the #427 `DATABASE_URL` value-match guard in config.ts, which re-exports both), `cwdDotenvAssignsKey(key, dir | assignments)` (KEY-PRESENCE predicate; an empty assignment counts) and `parseCwdDotenv(dir)` → `DotenvAssignment[]` (one read the two preflight consumers share). The assignment RHS is matched as `([^\r\n]*)`, never `.*$`. Protection is one predicate, `isCwdDotenvProtectedKey(key)`: `CWD_DOTENV_PROTECTED_KEYS` (code-loading / exec-target / root- and endpoint-redirect incl. `GBRAIN_DATABASE_URL` (key-presence; the #427 config.ts VALUE guard is separate and covers only bare `DATABASE_URL`), `GBRAIN_DIRECT_DATABASE_URL`, `GBRAIN_REMOTE_MCP_URL`, `GBRAIN_REMOTE_ISSUER_URL`, `GBRAIN_OAUTH_RELAY_URL` / posture-widening `GBRAIN_*`, plus the re-run marker `GBRAIN_CWD_ENV_QUARANTINED`; one why-comment per key, plus the deliberate exclusions and deferrals) PLUS `CWD_DOTENV_PROTECTED_PREFIXES` (`LD_`, `DYLD_`, `GIT_`, `BUN_`, `NPM_CONFIG_`, `npm_config_`, `BASH_FUNC_`) and `CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS` (NODE_OPTIONS/NODE_PATH/CA/TLS, SSH_ASKPASS*, XDG_CONFIG/DATA/CACHE_HOME, GNUPGHOME, SSL_CERT_FILE/DIR, CURL_CA_BUNDLE, REQUESTS_CA_BUNDLE, OPENSSL_CONF/ENGINES/MODULES, TMPDIR/TMP/TEMP, HOME/USERPROFILE, the shell-startup / interpreter-home group BASH_ENV, SHELLOPTS, PS4, BASHOPTS, PROMPT_COMMAND, ZDOTDIR, PYTHONHOME, PERLLIB, GCONV_PATH (sh/ksh `ENV` deliberately excluded: interactive-only and a routine project key), EDITOR/VISUAL/PAGER, PYTHON/PERL/RUBY preload, proxy vars both spellings, CLAUDE_CONFIG_DIR, ANTHROPIC_*/OPENAI/OPENROUTER/LITELLM/OLLAMA/LMSTUDIO/LLAMA_SERVER(_RERANKER)_BASE_URL) — the families a cwd .env could plant for the programs gbrain spawns; a denylist that grows as families are identified. `quarantineCwdDotenv(env = process.env, dir = process.cwd(), { warn, assignments })` iterates the keys the cwd .env files ASSIGN, deletes each protected one present in `env`, prints ONE stderr line (`formatQuarantineWarning`, composed from the exported `CWD_DOTENV_REMEDIATION` that guardrails.ts reuses) naming them sorted, returns them sorted. INVARIANTS: key presence, never value match; the parser accepts every line shape Bun's loader does; in-process only — children spawned without an explicit `env` see Bun's startup snapshot, which is why `cli-preflight.ts` re-runs gbrain from a neutral cwd whenever the list is non-empty; fs/path only, no config import. Pinned by `test/env-trust.test.ts`; the GBRAIN list is guarded against rot by the structural `test/env-trust-protected-keys.test.ts` (every `process.env.GBRAIN_*` / `Bun.env.GBRAIN_*` / `env.GBRAIN_*` read in src/ whose name matches `_BIN|_CLI|_MODULE|_PATH|_HOME|_URL` suffix or `GBRAIN_ALLOW_` prefix must be on the list or carry a `cwd-dotenv-ok: <why>` annotation).
-- `src/core/grants/` — canonical OAuth client grant model shared by CLI, admin HTTP, provisioning, and worker admission. `model.ts` validates active sources, independent direct/delegated fences, explicit reviewed tools, namespaces, concurrency, spend, and TTL; `host`/`current` brain aliases normalize to the serving brain (`null`), while other IDs need independently verified host identity. `profiles.ts` snapshots current eligible operation names for six explicit profiles; new defaults are renewable 1 hour (static 30 days), concurrency 1, and unlimited delegated spend. `allowed_operations = NULL` preserves legacy scope-based behavior; a new profile missing its snapshot fails closed. `service.ts` locks the client, checks `grant_revision`, and commits the grant, secret-free audit, and original ceilings for pending/active legacy jobs atomically; stale edits fail, repeated repair is a no-op, and repair preserves populated limits. Issued scopes intersect live scopes on access and refresh; source/path/operation/delegation changes are live, newly added scopes require new issuance, and TTL changes do not rewrite existing expiry. `migration.ts` splits legacy fences and removes only invalid `agent` grants with repair reasons; it loads registry validation lazily only after locking existing delegated clients, so empty engine imports and cold migrations do not register unrelated background sinks. This justified engine-live import is line-marked; constraints still install when no clients exist. F3 one grant shape: `model.ts` also holds `PrincipalGrant` (`GrantSources` = `default` | `scalar` | `federated` | `none`), `grantFromTokenRow` (unified rows read the `access_tokens` grant columns and any axis whose `permissions` mirror disagrees evaluates deny-all and is listed in `drift`; an unconverted `source_grant IS NULL` row reads as the conversion `migrateLegacyTokens` would write, and a malformed `permissions` value denies every axis), `GRANT_MIRROR_WINDOW_ENDS` (the date until which the `permissions` mirror is written and drift is enforced; doctor reports it), `authSourcesFromGrant` (the AuthInfo source fields every token reader uses: both HTTP transports, publication `authority.ts`, job admission, shared-skill membership and policy), `grantFromClient`, `validatePrincipalGrant` (tokens and clients may hold `none`); `ClientGrant.sourcesNone` (`oauth_clients.source_grant = 'none'`: NULL `source_id`, empty `federated_read`, verified as `NO_SOURCES`) and `ClientGrant.takesHolders` (`oauth_clients.takes_holders`, NULL = `['world']`; read by `verifyAccessToken` and `authorizeTakeHolder`), both added by migration v203 (fragment `oauth-client-axes-schema.ts`) and set through `auth rescope --client --sources none|--takes-holders` and `permissionsMirror`. `access-token-schema.ts` is the column fragment (migration `f3_access_token_grants`); v202 (`legacy_token_grant_conversion`) converts every legacy grant in bulk. Tests: `test/legacy-token-grant-conversion.test.ts`. `legacy-token.ts` is the token grant editor behind `gbrain auth rescope --token` (aliases `rescope-token`, `permissions set-takes-holders`): one `FOR UPDATE` transaction that writes the columns, bumps `grant_revision` (`--if-version` compare-and-set) and rewrites `permissions` as a mirror with every other key preserved; `none` = explicit empty list; refresh previews and widens only by named operations; a drifted token refuses edits until `--adopt-permissions` or `--adopt-columns`; `migrateLegacyTokens` (`--migrate-legacy` and schema migration v202) writes the columns for every unmigrated token without changing a grant and skips malformed JSONB; `resolveTokenGrant` is the HTTP auth read (both transports): a legacy-shape row converts on that read with one `source_grant IS NULL`-guarded UPDATE (concurrent first reads convert once; a failed write such as a read-only role authorizes with the identical in-memory conversion); `resolveRescopeTarget` refuses a bare name that matches a token and a client. `cli.ts` splits `auth rescope` targets and maps the unified client flags onto `auth rescope-client`'s patch. An explicit empty `permissions.source_id` decodes (`parseLegacyTokenScope` in `src/core/legacy-token-scope.ts`) to the `NO_SOURCES` sentinel, which `sourceScopeOpts`, the dispatch fence (`enforceBoundClientOpAllowList`, `fence=no_source_grant`), `submissionAuthority` and `POST /ingest` refuse and publication reauthorization rejects; it never regains the `default` floor. `schema.ts` supplies migration147/bootstrap columns and invariants for both engines. SQL JSON passes through `text::jsonb` for driver parity. Tests: `test/client-grants.test.ts`, OAuth compatibility suites, and `test/e2e/client-grants.test.ts` (Postgres CAS, job ceilings, and actual HTTP preview/edit).
+- `src/core/grants/` — canonical OAuth client grant model shared by CLI, admin HTTP, provisioning, and worker admission. `model.ts` validates active sources, independent direct/delegated fences, explicit reviewed tools, namespaces, concurrency, spend, and TTL; `host`/`current` brain aliases normalize to the serving brain (`null`), while other IDs need independently verified host identity. `profiles.ts` snapshots current eligible operation names for six explicit profiles; new defaults are renewable 1 hour (static 30 days), concurrency 1, unlimited delegated spend, and an operator-set `full` surface for every profile except `delegating-agent` (`starter`); only an explicit profile application changes an existing client's surface. `catalogProvenance()` is the operation catalog a snapshot is written against: `service.ts` adds it as `catalogProvenance` to the audit document of every write that sets a new snapshot (registration included), and `readClientCatalogProvenance` returns it only while that audit row's snapshot is still the client's snapshot (null for grants written without it; never synthesized). `allowed_operations = NULL` preserves legacy scope-based behavior; a new profile missing its snapshot fails closed. `service.ts` locks the client, checks `grant_revision`, and commits the grant, secret-free audit, and original ceilings for pending/active legacy jobs atomically; stale edits fail, repeated repair is a no-op, and repair preserves populated limits. Issued scopes intersect live scopes on access and refresh; source/path/operation/delegation changes are live, newly added scopes require new issuance, and TTL changes do not rewrite existing expiry. `migration.ts` splits legacy fences and removes only invalid `agent` grants with repair reasons; it loads registry validation lazily only after locking existing delegated clients, so empty engine imports and cold migrations do not register unrelated background sinks. This justified engine-live import is line-marked; constraints still install when no clients exist. F3 one grant shape: `model.ts` also holds `PrincipalGrant` (`GrantSources` = `default` | `scalar` | `federated` | `none`), `grantFromTokenRow` (unified rows read the `access_tokens` grant columns and any axis whose `permissions` mirror disagrees evaluates deny-all and is listed in `drift`; an unconverted `source_grant IS NULL` row reads as the conversion `migrateLegacyTokens` would write, and a malformed `permissions` value denies every axis), `GRANT_MIRROR_WINDOW_ENDS` (the date until which the `permissions` mirror is written and drift is enforced; doctor reports it), `authSourcesFromGrant` (the AuthInfo source fields every token reader uses: both HTTP transports, publication `authority.ts`, job admission, shared-skill membership and policy), `grantFromClient`, `validatePrincipalGrant` (tokens and clients may hold `none`); `ClientGrant.sourcesNone` (`oauth_clients.source_grant = 'none'`: NULL `source_id`, empty `federated_read`, verified as `NO_SOURCES`) and `ClientGrant.takesHolders` (`oauth_clients.takes_holders`, NULL = `['world']`; read by `verifyAccessToken` and `authorizeTakeHolder`), both added by migration v203 (fragment `oauth-client-axes-schema.ts`) and set through `auth rescope --client --sources none|--takes-holders` and `permissionsMirror`. `access-token-schema.ts` is the column fragment (migration `f3_access_token_grants`); v202 (`legacy_token_grant_conversion`) converts every legacy grant in bulk. Tests: `test/legacy-token-grant-conversion.test.ts`. `legacy-token.ts` is the token grant editor behind `gbrain auth rescope --token` (aliases `rescope-token`, `permissions set-takes-holders`): one `FOR UPDATE` transaction that writes the columns, bumps `grant_revision` (`--if-version` compare-and-set) and rewrites `permissions` as a mirror with every other key preserved; `none` = explicit empty list; refresh previews and widens only by named operations; a drifted token refuses edits until `--adopt-permissions` or `--adopt-columns`; `migrateLegacyTokens` (`--migrate-legacy` and schema migration v202) writes the columns for every unmigrated token without changing a grant and skips malformed JSONB; `resolveTokenGrant` is the HTTP auth read (both transports): a legacy-shape row converts on that read with one `source_grant IS NULL`-guarded UPDATE (concurrent first reads convert once; a failed write such as a read-only role authorizes with the identical in-memory conversion); `resolveRescopeTarget` refuses a bare name that matches a token and a client. `cli.ts` splits `auth rescope` targets and maps the unified client flags onto `auth rescope-client`'s patch. An explicit empty `permissions.source_id` decodes (`parseLegacyTokenScope` in `src/core/legacy-token-scope.ts`) to the `NO_SOURCES` sentinel, which `sourceScopeOpts`, the dispatch fence (`enforceBoundClientOpAllowList`, `fence=no_source_grant`), `submissionAuthority` and `POST /ingest` refuse and publication reauthorization rejects; it never regains the `default` floor. `schema.ts` supplies migration147/bootstrap columns and invariants for both engines. SQL JSON passes through `text::jsonb` for driver parity. Tests: `test/client-grants.test.ts`, OAuth compatibility suites, and `test/e2e/client-grants.test.ts` (Postgres CAS, job ceilings, and actual HTTP preview/edit).
- `src/core/grants/lifecycle.ts` + `src/commands/serve-http-clients.ts` — owner-authenticated client inspection, setup, export and lifecycle endpoints. Token invalidation/revoke/delete lock the OAuth client row, require reviewed revisions and explicit application, and commit an audit record atomically. Deletion records a tombstone while preserving request history and spending reservations/settlement; missing clients become terminal delegated denials while transient lookup failures remain retryable.
- `src/commands/serve-http-api-keys.ts` — owner-dashboard legacy API keys (`/admin/api/api-keys`). Mint validates the request (`parseApiKeyMintRequest`: name 1-128 printable characters, registered scopes, active source ids, holder grammar) and goes through `mintLegacyToken`, so keys are born on the unified grant columns; omitted fields take the `gbrain auth create` defaults (scopes `read,write`, never `admin` unless listed; no source grant; holders `['world']`), reported in `defaults_applied` beside the effective grant. Refusals are `invalid_params` agent envelopes with `why` and a `fix`; nothing is minted. The token appears only in the mint response, never in logs or SSE. The list returns ids, scopes, sources and holders through `grantFromTokenRow`; revoke takes the row id (`revokeLegacyTokenById`) and refuses a name. Pinned by `test/serve-http-api-keys.test.ts`.
diff --git a/docs/guides/bootstrap.md b/docs/guides/bootstrap.md
index 448221d9fe..85544eebb8 100644
--- a/docs/guides/bootstrap.md
+++ b/docs/guides/bootstrap.md
@@ -180,7 +180,7 @@ you'd apply to any journal: write what you'd be comfortable persisting.
| Hooks (Claude Code) | pull protocol via AGENTS.md gates | automatic per-turn context + session-end persistence |
| Codex (SessionEnd hook only, no MCP scope flag) | pull protocol + MCP tools + session-end capture (a trust-gated `hooks.json` entry bootstrap manages) | per-turn push (codex hooks are wired for SessionEnd only — per-turn context stays the pull protocol) + the ability to confine MCP reach to one folder (`codex mcp add` is always user-global) |
| opencode (no wired hooks; scope INVERTED: user-global by default) | pull protocol (opencode reads AGENTS.md natively) + MCP tools; project scope available as an explicit opt-in | per-turn push (opencode ships a plugin/event system, but gbrain does not wire it yet). The project-scope default is deliberately NOT offered: opencode spawns project-config servers with no trust prompt, so a committed entry would auto-execute on every collaborator machine |
-| Bootstrap at all (plugin-only install) | MCP tools (`starter` surface, `--source-guard`) + the curated skill set via the codex/claude plugin (docs/mcp/CODEX.md) | identity files, hooks/push protocol, the private-repo body — the plugin is the lightweight lane; bootstrap is the full agent |
+| Bootstrap at all (plugin-only install) | MCP tools (`full` surface, `--source-guard`) + the curated skill set via the codex/claude plugin (docs/mcp/CODEX.md) | identity files, hooks/push protocol (the Codex and Claude Code plugins carry no hooks; the one plugin that pushes is the local OpenClaw context engine, `gbrain-context-engine` — see docs/guides/push-context.md), the private-repo body — the plugin is the lightweight lane; bootstrap is the full agent |
| Memorable relay (declined or never disclosed) | everything — the integration is additive and off by default | replayable cross-session procedures via the third-party Memorable service (`docs/memorable-agents.md`) |
| Ambient memory writeback (left off — the default) | everything — the feature is additive; agents still save when explicitly asked (`remember`) | unprompted capture of directly-stated user facts (instructions section, harness blocks, Stop-hook backstop — `docs/guides/ambient-writeback.md`). On Codex specifically, enabling it still has NO per-turn hook: real-time saves ride the instruction blocks; the SessionEnd→sweep lane is the delayed backstop |
| Second simultaneous session | first session unaffected | second session's brain tools fail politely (one live serve per brain — v1 contract) |
diff --git a/docs/guides/hosted-harness-access.md b/docs/guides/hosted-harness-access.md
index fe0b44e4ab..6cf1c97dda 100644
--- a/docs/guides/hosted-harness-access.md
+++ b/docs/guides/hosted-harness-access.md
@@ -110,16 +110,16 @@ are one principal. See [shared brain skills](shared-brain-skills.md).
| Profile | Access | Native MCP surface |
| --- | --- | --- |
-| `memory-reader` | Read selected memory | Starter |
-| `memory-writer` | Read and write selected memory | Starter |
-| `coding-agent` | Isolated project writes and explicit project reads | Starter |
+| `memory-reader` | Read selected memory | Full |
+| `memory-writer` | Read and write selected memory | Full |
+| `coding-agent` | Isolated project writes and explicit project reads | Full |
| `operator` | Read, write, and eligible brain administration operations | Full |
| `delegating-agent` | Memory plus explicitly bound delegation | Starter |
| `full` | All eligible remote capabilities at grant time, including bound delegation | Full |
A **profile grants authority**. A **surface selects visible tools**. Full surface does not bypass a grant, and `admin` does not imply delegation, the named shared-skill scopes, or owner dashboard/client-management authority. Starter includes authorized skill discovery and membership; the exact seven-tool `verbs` surface is memory-only. Thin CLI adapters use the full surface while retaining their source, operation, and write restrictions. Direct local CLI access is trusted access to the local computer; OAuth profiles do not confine a local shell.
-New grants snapshot operation names and source access. A later server upgrade does not silently give a snapshot-bound client new operations. Explicitly regrant to include them: `gbrain auth rescope-client <client_id> --allowed-operations …` for OAuth clients, or `gbrain auth rescope-token <name> --refresh-operations` (preview) then `--add <op,...>` for legacy tokens. `gbrain auth rescope --client <client_id> --operations all` (alias: `gbrain auth rescope-client <client_id> --allowed-operations all`) stores no snapshot and clears the profile instead, so the scopes and the surface alone decide, including operations later upgrades add. `gbrain auth clients` marks such a client `operations: "all"` with `includes_future_operations: true` and the command that re-pins it. A `bootstrap harness` re-run carries the replaced token's grants and does not widen its snapshot ([legacy token grants](../mcp/ADMIN.md#legacy-token-grants)). Archived sources are excluded. Legacy clients with a `NULL` operation snapshot retain their prior operation behavior.
+Clients granted a memory profile before the full-surface default keep their stored `starter` surface; no migration or repair widens it, and only an explicit `--profile` application regrants it. New grants snapshot operation names and source access. A later server upgrade does not silently give a snapshot-bound client new operations. The connection's own `whoami` reports `grant_diagnosis`: which blocker applies (scope, operation snapshot, client pin or server ceiling) and how many operations it hides, without naming them; `gbrain doctor` on the host reports the same as `grant_new_ops_available` with the commands. A grant written before snapshots recorded their operation catalog says "original intent unknown" rather than claiming it predates the operations. Explicitly regrant to include them: `gbrain auth rescope --client <client_id> --operations <op,...> --surface full --dry-run` (then without `--dry-run`; `--surface full` only when the stored surface also blocks) for OAuth clients, or `gbrain auth rescope-token <name> --refresh-operations` (preview) then `--add <op,...>` for legacy tokens ([grants that cannot reach new operations](../mcp/ADMIN.md#grants-that-cannot-reach-new-operations)). `gbrain auth rescope --client <client_id> --operations all` (alias: `gbrain auth rescope-client <client_id> --allowed-operations all`) stores no snapshot and clears the profile instead, so the scopes and the surface alone decide, including operations later upgrades add. `gbrain auth clients` marks such a client `operations: "all"` with `includes_future_operations: true` and the command that re-pins it. A `bootstrap harness` re-run carries the replaced token's grants and does not widen its snapshot ([legacy token grants](../mcp/ADMIN.md#legacy-token-grants)). Archived sources are excluded. Legacy clients with a `NULL` operation snapshot retain their prior operation behavior.
Snapshot-bound clients write through approved MCP operations such as `remember`, `capture`, or `put_page`. They cannot use the legacy `POST /ingest` webhook, whose queued writes do not yet enforce operation snapshots. Existing webhook clients with a `NULL` snapshot keep their legacy behavior.
diff --git a/docs/guides/push-context.md b/docs/guides/push-context.md
index 3c9dac68e8..02743e9f70 100644
--- a/docs/guides/push-context.md
+++ b/docs/guides/push-context.md
@@ -95,9 +95,10 @@ this channel production-grade rather than spammy-and-invisible:
client-side), the doctor check reconciles the counts against the hook's own
heartbeat and cautions when they diverge.
-The hook lane rides the PGLite serve's IPC socket: on a Postgres brain or a
-thin-client install the hook stays quiet by design (pull-mode retrieval covers
-those; extending the lane is a filed follow-up in TODOS.md).
+The hook lane rides the running serve's IPC socket on PGLite and Postgres alike
+(the listener is engine-uniform and keys its socket off the connection URL), so
+the hook stays quiet only while no `gbrain serve` for the brain is running, and
+on a thin-client install, where pull-mode retrieval covers it.
Kill switch: `GBRAIN_HOOKS=0`. Install/uninstall: `docs/guides/bootstrap.md`.
diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.md
index e2bc4fa8ed..aabcfc0130 100644
--- a/docs/mcp/ADMIN.md
+++ b/docs/mcp/ADMIN.md
@@ -220,6 +220,49 @@ requests. Added scopes require a fresh token; refresh cannot widen the original
token's scope ceiling. Native OAuth clients must reconnect and obtain fresh
owner approval. TTL changes affect future tokens only.
+New `memory-reader`, `memory-writer` and `coding-agent` grants are callable and
+listed on the full surface; their operation snapshot is still the ceiling, so a
+reader still has no write operation. `delegating-agent` grants keep the starter
+surface. Clients granted before this keep their stored surface: no migration or
+repair changes it, and only an explicit `--profile` application regrants it.
+
+### Grants that cannot reach new operations
+
+A grant can be unable to call operations its scopes allow for three proven
+reasons: its operation snapshot excludes them, its stored client surface (the
+pin, for example `starter` on an older profile client) hides them, or the
+server's surface is narrower. The connection itself sees counts, never names,
+in `whoami` (`grant_diagnosis`) and `gbrain://capabilities`; operations outside
+the grant's scopes are never counted. On the host, `gbrain doctor` reports
+`grant_new_ops_available` with each grant's blockers and the operation names.
+
+Grant age is reported apart from those blockers. A snapshot written before
+this release carries no record of the operation catalog it was written
+against, so an old profile snapshot and a deliberate restriction look the
+same: such a grant reports "this grant's snapshot excludes N currently eligible
+operations; original intent unknown". Only a snapshot written with catalog
+provenance (new grants, and any later write that sets a new snapshot) is said
+to predate operations. Identically shaped grants get identical output, and
+nothing is widened automatically: ask the user first.
+
+The commands differ by credential type:
+
+```bash
+# Legacy token: preview the operations added since the snapshot, then add the approved ones
+gbrain auth rescope --token NAME --refresh-operations
+gbrain auth rescope --token NAME --refresh-operations --add put_pages
+
+# OAuth client: no refresh; pass the whole new snapshot, plus --surface full when the pin blocks too
+gbrain auth rescope --client CLIENT_ID --operations OP1,OP2,... --surface full --dry-run
+gbrain auth rescope --client CLIENT_ID --operations OP1,OP2,... --surface full
+```
+
+`--refresh-operations` is token-only (a client gets
+`client_refresh_operations_unsupported`). Removing the snapshot instead is a
+separate, disclosed choice, never the default repair: `--operations all` for a
+client (`--reset-default operations` for a token) stores no snapshot, so the
+scopes and surface allow every operation, including ones later upgrades add.
+
### Access-token lifetime
An access token lives at most 90 days (7,776,000 seconds), whatever a
@@ -481,7 +524,7 @@ registers `gbrain serve --access read-only` as its stdio MCP command.
```bash
claude mcp add gbrain -- "$(command -v gbrain)" serve --access read-only
-gbrain serve --surface starter --access read-only
+gbrain serve --surface full --access read-only
```
`--access read-only` intersects the selected `--surface` with operations that
diff --git a/docs/mcp/CLAUDE_CODE.md b/docs/mcp/CLAUDE_CODE.md
index 4ced7b0048..ae3a0bd210 100644
--- a/docs/mcp/CLAUDE_CODE.md
+++ b/docs/mcp/CLAUDE_CODE.md
@@ -43,7 +43,7 @@ into your user-scope skills dir with a local-edit-respecting update lens
`claude plugin install gbrain@gbrain`.) Prerequisites and behavior match the
[Codex plugin](CODEX.md#install-as-a-codex-plugin-recommended): the gbrain CLI
installed (`bun install -g github:garrytan/gbrain#latest-stable`), a brain
-(`gbrain init`), `starter` MCP surface with `--source-guard`, and the same
+(`gbrain init`), `full` MCP surface with `--source-guard`, and the same
routing rules (`GBRAIN_SOURCE`/`GBRAIN_BRAIN_ID` env — dotfiles don't apply
to a plugin-launched serve). Positioning: the plugin is the lightweight
brain+skills path; `gbrain bootstrap` remains the deep lane (identity, hooks,
@@ -54,7 +54,7 @@ tools use the plugin lane's own approval flow.
## Option 1: Local (recommended, zero server needed)
```bash
-claude mcp add gbrain -- "$(command -v gbrain)" serve --surface verbs
+claude mcp add gbrain -- "$(command -v gbrain)" serve --surface full
```
That's it. Claude Code spawns `gbrain serve` as a stdio subprocess. No server, no
@@ -72,13 +72,14 @@ tunnel, no token needed. Works with both PGLite and Supabase engines.
> connections. Details:
> [serve ↔ sync concurrency](../architecture/serve-sync-concurrency.md).
-`--surface verbs` exposes the seven-verb memory protocol (`recall`, `remember`,
-`entity`, `synthesize`, `forget`, `context_pack`, `delta` —
-[MEMORY_VERBS v1](../protocol/MEMORY_VERBS_v1.md)),
-the surface built for agents and quickstarts. `--surface starter` adds the
-daily-driver set on top (core page/search/graph ops + capture). Drop the flag for the full
-operation catalog (`get_page`, `put_page`, `search`, graph ops, …) — `full` is
-the default and what existing installs already run.
+`--surface full` serves the whole operation catalog (`get_page`, `put_page`,
+`put_pages`, `search`, graph ops, …), the seven-verb memory protocol (`recall`,
+`remember`, `entity`, `synthesize`, `forget`, `context_pack`, `delta` —
+[MEMORY_VERBS v1](../protocol/MEMORY_VERBS_v1.md)) included; it is the surface
+every registration gbrain writes pins and what a bare `serve` defaults to. A
+harness that caps its tool count can register `--surface starter` (the verbs
+plus the daily-driver page/search/graph ops and capture) or `--surface verbs`
+(only the seven verbs).
## Option 2: Remote, one command (fastest from a bearer token)
diff --git a/docs/mcp/CODEX.md b/docs/mcp/CODEX.md
index 32b9617123..ec46b44435 100644
--- a/docs/mcp/CODEX.md
+++ b/docs/mcp/CODEX.md
@@ -43,17 +43,17 @@ brain (`gbrain init` — zero-config local PGLite by default). The bundled
that exact install one-liner on stderr; with no brain, it exits with
"No brain configured. Run: gbrain init". Unix (macOS/Linux) only.
-**What ships.** The MCP server runs `gbrain serve --surface starter
+**What ships.** The MCP server runs `gbrain serve --surface full
--source-guard` through the bundled launcher (`.agents/gbrain-launcher`,
resolution order: `$GBRAIN_BIN` → `~/.bun/bin/gbrain` → `gbrain` on PATH — the
sanctioned install location is preferred over PATH so a stray `gbrain` earlier
on PATH can't shadow it).
-`starter` is the daily-driver surface (the seven memory verbs + daily
-brain ops) — the curated skills drive everything else through the `gbrain`
-CLI. Widen one session with `request_tools {"surface":"full"}` (no restart,
-nothing is written), or every new session on this machine with
-`GBRAIN_SURFACE=full` in the env that launches Codex, or use the bootstrap
-lane below. Unlike the OpenClaw bundle, the plugin ships the host-side skills
+`full` is every operation (the seven memory verbs, page and bulk writes
+such as `put_pages`, graph and skill tools), the surface every registration
+gbrain writes pins; the curated skills drive host-side work through the
+`gbrain` CLI. A harness that caps its tool count can narrow every new session
+on this machine with `GBRAIN_SURFACE=starter` (or `verbs`) in the env that
+launches Codex, or use the bootstrap lane below. Unlike the OpenClaw bundle, the plugin ships the host-side skills
too (setup, migrate, smoke-test, gbrain-upgrade, schema authoring) — a plugin
user IS the brain host.
@@ -204,11 +204,11 @@ codex mcp remove gbrain
- The token is a long-lived, full-access secret. Keep `GBRAIN_REMOTE_TOKEN` out of
version control and prefer a scoped token if your host supports one.
- Local stdio also works if you run the brain on the same machine:
- `codex mcp add gbrain -- "$(command -v gbrain)" serve --surface starter` — the
- memory verbs ([MEMORY_VERBS v1](../protocol/MEMORY_VERBS_v1.md)) plus page,
- timeline-write and skill tools, the surface every registration gbrain writes
- pins; `--surface full` for the whole operation catalog. A `GBRAIN_SURFACE`
- value in the Codex server entry's `env` table overrides the flag.
+ `codex mcp add gbrain -- "$(command -v gbrain)" serve --surface full` — the
+ whole operation catalog, memory verbs ([MEMORY_VERBS v1](../protocol/MEMORY_VERBS_v1.md))
+ included, the surface every registration gbrain writes pins. A
+ `GBRAIN_SURFACE` value in the Codex server entry's `env` table overrides the
+ flag (`starter` or `verbs` for a harness that caps its tool count).
- **PGLite brains are single-process.** PGLite is a single-writer embedded
Postgres: the first running `gbrain serve` (the plugin's, or a stdio
registration) owns the brain's data directory via the data-dir lock. A
@@ -225,5 +225,5 @@ codex mcp remove gbrain
`context_pack(entities, budget_tokens)` to warm the standing entities; on a
periodic wake call `delta(session_id, budget_tokens)` for "what changed since
my last wake" (deduped per session). Both are zero-LLM, sub-second, world-only
- by default, and on `--surface verbs`. See
+ by default, and on every surface, `--surface verbs` included. See
[ambient recall](../guides/ambient-recall.md) for the placement frontier.
diff --git a/docs/mcp/DEPLOY.md b/docs/mcp/DEPLOY.md
index a41c4e8dc1..ff9a8a9215 100644
--- a/docs/mcp/DEPLOY.md
+++ b/docs/mcp/DEPLOY.md
@@ -59,17 +59,16 @@ the OAuth request when issuing my owner login link."*
### Local stdio (zero setup)
```bash
-gbrain serve # full operation catalog (default)
-gbrain serve --surface verbs # just the 7 memory verbs (quickstart surface)
+gbrain serve --surface full # full operation catalog (what registrations pin; also the bare-serve default)
```
Works with Claude Code, Cursor, Windsurf, and any MCP client that supports stdio.
No server, no tunnel, no token needed. Works on both PGLite and Postgres engines.
-`--surface verbs` exposes exactly the seven-verb memory protocol (`recall`,
-`remember`, `entity`, `synthesize`, `forget`, `context_pack`, `delta` —
-[MEMORY_VERBS v1](../protocol/MEMORY_VERBS_v1.md)) instead of the full catalog;
-`--surface starter` sits between (~27 ops: the verbs plus the daily-driver set);
-omit the flag (default `full`) for every operation.
+`--surface full` serves every operation. For a client that cannot hold the full
+catalog, `--surface verbs` exposes exactly the seven-verb memory protocol
+(`recall`, `remember`, `entity`, `synthesize`, `forget`, `context_pack`,
+`delta` — [MEMORY_VERBS v1](../protocol/MEMORY_VERBS_v1.md)) and `--surface
+starter` sits between (40 ops: the verbs plus the daily-driver set).
`--surface` is the callable ceiling. To keep every operation callable while
listing fewer tools to the agent, set `mcp.advertised_surface`:
diff --git a/docs/mcp/GROK.md b/docs/mcp/GROK.md
index 6f3c2da190..1609b04019 100644
--- a/docs/mcp/GROK.md
+++ b/docs/mcp/GROK.md
@@ -18,13 +18,15 @@ tunnel, no token needed. Works with both PGLite and Supabase engines.
## Register (recommended)
```bash
-grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- "$(command -v gbrain)" serve --surface verbs
+grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- "$(command -v gbrain)" serve --surface full
```
-`--surface verbs` exposes the seven-verb memory protocol (`recall`,
-`remember`, `entity`, `synthesize`, `forget`, `context_pack`, `delta` —
-[MEMORY_VERBS v1](../protocol/MEMORY_VERBS_v1.md)) instead of the full
-100+-op catalog — the recommended starting surface for coding agents.
+`--surface full` serves the whole operation catalog, the seven-verb memory
+protocol (`recall`, `remember`, `entity`, `synthesize`, `forget`,
+`context_pack`, `delta` — [MEMORY_VERBS v1](../protocol/MEMORY_VERBS_v1.md))
+included; it is the surface every registration gbrain writes pins. A harness
+that caps its tool count can register `--surface starter` or `--surface verbs`
+(only the seven verbs) instead.
Three facts about `grok mcp add`, all observed:
- **The env flag is repeatable, one `KEY=value` per flag** (`-e A=1 -e B=2`).
@@ -78,8 +80,8 @@ grok mcp doctor gbrain # THE real probe: spawns the server
```
`grok mcp doctor gbrain` performs the actual handshake — expect the checks
-`command found`, `server started`, `handshake OK`, and `7 tools discovered`
-(the seven verbs), exit 0. A broken registration exits 1 with a failing
+`command found`, `server started`, `handshake OK`, and `N tools discovered`
+(the full surface; 7 on `--surface verbs`), exit 0. A broken registration exits 1 with a failing
check and a hint. Then one real round-trip:
```bash
diff --git a/docs/mcp/OPENCODE.md b/docs/mcp/OPENCODE.md
index 97937817fd..523418d1e3 100644
--- a/docs/mcp/OPENCODE.md
+++ b/docs/mcp/OPENCODE.md
@@ -21,13 +21,15 @@ brain contract loads with zero extra configuration.
## Register (recommended)
```bash
-opencode mcp add gbrain --env GBRAIN_HOME=$HOME -- "$(command -v gbrain)" serve --surface verbs
+opencode mcp add gbrain --env GBRAIN_HOME=$HOME -- "$(command -v gbrain)" serve --surface full
```
-`--surface verbs` exposes the seven-verb memory protocol (`recall`,
-`remember`, `entity`, `synthesize`, `forget`, `context_pack`, `delta` —
-[MEMORY_VERBS v1](../protocol/MEMORY_VERBS_v1.md)) instead of the full
-100+-op catalog — the recommended starting surface for coding agents.
+`--surface full` serves the whole operation catalog, the seven-verb memory
+protocol (`recall`, `remember`, `entity`, `synthesize`, `forget`,
+`context_pack`, `delta` — [MEMORY_VERBS v1](../protocol/MEMORY_VERBS_v1.md))
+included; it is the surface every registration gbrain writes pins. A harness
+that caps its tool count can register `--surface starter` or `--surface verbs`
+(only the seven verbs) instead.
Three facts about `opencode mcp add`, all observed:
- **The local-command form is `-- <command> [args...]` after the flags** —
diff --git a/docs/mcp/TOOL_REFERENCE.md b/docs/mcp/TOOL_REFERENCE.md
index 7d65e54f52..1590ceb7da 100644
--- a/docs/mcp/TOOL_REFERENCE.md
+++ b/docs/mcp/TOOL_REFERENCE.md
@@ -357,7 +357,7 @@ MEMORY VERB (v1): save one fact to durable agent memory — the protocol write v
## `request_tools`
-Discover this brain's tool catalog and optionally unlock a wider tool surface for your client. No arguments → the catalog visible to YOUR credentials, grouped by area (tool names + one-line summaries). {tools: ["name", ...]} → full read-only schemas for the visible subset of those names (unknown/hidden names are silently omitted). {surface: "verbs"|"starter"|"full"} → persist that tool surface for this client (bounded by the server ceiling; denied when an operator pinned the surface; ~5 changes/hour), then re-issue tools/list to see the new catalog.
+Discover this brain's tool catalog and optionally unlock a wider tool surface for your client. No arguments → the catalog visible to YOUR credentials, grouped by area (tool names + one-line summaries). {tools: ["name", ...]} → full read-only schemas for the visible subset of those names (unknown/hidden names are silently omitted; an empty list, or one with no name you can call, returns the catalog plus `did_you_mean`, the closest names you can call). {surface: "verbs"|"starter"|"full"} → persist that tool surface for this client (bounded by the server ceiling; denied when an operator pinned the surface; ~5 changes/hour), then re-issue tools/list to see the new catalog.
| Parameter | Type | Guidance |
| --- | --- | --- |
diff --git a/docs/protocol/AGENT_OPERATOR_v1.md b/docs/protocol/AGENT_OPERATOR_v1.md
index bf7c7bdb76..2794761e41 100644
--- a/docs/protocol/AGENT_OPERATOR_v1.md
+++ b/docs/protocol/AGENT_OPERATOR_v1.md
@@ -361,7 +361,7 @@ stdout (`--json`):
"options": [
{
"id": "wire",
- "label": "Register `<absolute path to gbrain> serve --surface starter` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "label": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
{
"id": "skip",
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index f67c26a630..7583934f99 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -49,7 +49,7 @@ the same registry.
```bash
gbrain init --pglite # 2-second local brain
-claude mcp add gbrain -- "$(command -v gbrain)" serve --surface starter # the verbs plus page tools
+claude mcp add gbrain -- "$(command -v gbrain)" serve --surface full # every operation, the verbs included
gbrain remember "gbrain install check" --provenance install-check
gbrain recall --query "gbrain install check" # …now ask your agent in a NEW session
```
@@ -64,28 +64,28 @@ If `claude` is not found: install Claude Code first, or use a block below.
**Codex**
```bash
-codex mcp add gbrain -- "$(command -v gbrain)" serve --surface starter
+codex mcp add gbrain -- "$(command -v gbrain)" serve --surface full
```
**Grok Build** (verify with `grok mcp doctor gbrain` — the add is lazy)
```bash
-grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- "$(command -v gbrain)" serve --surface starter
+grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- "$(command -v gbrain)" serve --surface full
```
**opencode** (verify with `opencode mcp list` — the add is lazy, and list SPAWNS the server)
```bash
-opencode mcp add gbrain --env GBRAIN_HOME=$HOME -- "$(command -v gbrain)" serve --surface starter
+opencode mcp add gbrain --env GBRAIN_HOME=$HOME -- "$(command -v gbrain)" serve --surface full
```
**OpenClaw / any stdio MCP host** — register the server command
-`gbrain serve --surface starter`. Remote brains: `gbrain serve --http` on the
+`gbrain serve --surface full`. Remote brains: `gbrain serve --http` on the
host, then `gbrain connect https://host/mcp --token gbrain_xxx --install` on
each client.
**Surface modes:** `--surface verbs` exposes EXACTLY the seven verbs —
advertised list AND dispatch are filtered fail-closed (a hidden op returns
`unknown_tool` even when called by name). `--surface starter` exposes the
-~27-op daily-driver set (`STARTER_OPS` in `src/mcp/surface.ts`): the seven
+40-op daily-driver set (`STARTER_OPS` in `src/mcp/surface.ts`): the seven
verbs plus the daily brain-tool slice, the agent lane, `whoami`, `capture`, and the
`request_tools` discovery meta-op (re-derivable from production usage via
`scripts/derive-starter-ops.ts`). Monotonic by construction: verbs ⊆ starter ⊆ full
@@ -93,8 +93,9 @@ verbs plus the daily brain-tool slice, the agent lane, `whoami`, `capture`, and
verb semantics. `--surface full` (the default for a bare `serve`) exposes
every operation, verbs included. Every stdio registration gbrain writes
(`gbrain init`'s quickstart, readiness, `gbrain bootstrap hooks`, the plugins)
-pins `starter`, because `verbs` lacks the page reads and writes bootstrap's
-instructions use and `full` puts the whole catalogue in front of the model.
+pins `full`, callable and advertised: in the held-out agent benchmark, listing
+only `starter` or `verbs` lowered task success and saved no tokens. A harness
+that caps its tool count can register `--surface starter` or `--surface verbs`.
Persist a default for bare `serve` with `gbrain config set mcp_surface verbs`.
On stdio, `GBRAIN_SURFACE` in the server's env overrides `--surface`; a
session widens itself with `request_tools {"surface":"full"}` (see
diff --git a/docs/tutorials/company-brain.md b/docs/tutorials/company-brain.md
index 4d44a86347..db31af83a5 100644
--- a/docs/tutorials/company-brain.md
+++ b/docs/tutorials/company-brain.md
@@ -275,7 +275,7 @@ Two presets cover the common shapes, with semantics worth knowing honestly:
- **`daily-driver`** — a personal assistant agent: writes to one source, reads broadly. The read grant is a **snapshot** of all non-archived sources at registration time, excluding other agents' `*-workspace` scratch sources (name one explicitly in `--federated-read` to share it) — a source you add next month is NOT automatically readable; re-grant with `gbrain auth rescope-client <client_id> --federated-read <updated list>`.
- **`coding-agent`** — a write-isolated project agent: its writes land in an auto-created, DB-only `<name>-workspace` source (so a misbehaving agent can't scribble on your wiki), and it reads only the project sources you name via `--federated-read` (required — a coding agent that can read nothing but its own scratch space is a misconfiguration).
-Both presets start the client on the **starter** tool surface (the ~27-op daily set, not the full brain-admin surface). Override at registration with `--surface`, or widen a specific client later with `gbrain auth rescope-client <client_id> --surface full`.
+Both presets start the client on the **full** tool surface; its grant (scopes, sources and write fence) still bounds what it can do. A harness that caps its tool count can register with `--surface starter`, or narrow a specific client later with `gbrain auth rescope-client <client_id> --surface starter`.
A worked example — a coding agent for alice-example's widget project, wired into Claude Code:
diff --git a/docs/tutorials/connect-coding-agent.md b/docs/tutorials/connect-coding-agent.md
index 44c252dd43..fad913c084 100644
--- a/docs/tutorials/connect-coding-agent.md
+++ b/docs/tutorials/connect-coding-agent.md
@@ -83,19 +83,20 @@ Configure the agent you are using:
```bash
# Claude Code
-claude mcp add gbrain -- "$(command -v gbrain)" serve --surface verbs
+claude mcp add gbrain -- "$(command -v gbrain)" serve --surface full
# Codex
-codex mcp add gbrain -- "$(command -v gbrain)" serve --surface verbs
+codex mcp add gbrain -- "$(command -v gbrain)" serve --surface full
```
These launch a local stdio MCP process. Use the same intended brain and source
you inspected above; if an isolated installation already provided an absolute
launcher, use that command in place of the bare `gbrain`.
-The verbs surface exposes exactly `recall`, `remember`, `entity`,
-`synthesize`, `forget`, `context_pack`, and `delta`.
-Start with keyless recall and remembering. Server-side synthesis and semantic
+The full surface serves every operation, including the seven memory verbs
+(`recall`, `remember`, `entity`, `synthesize`, `forget`, `context_pack`,
+`delta`); a harness that caps its tool count can register `--surface verbs`
+for exactly those seven. Start with keyless recall and remembering. Server-side synthesis and semantic
retrieval may require separately configured capabilities.
PGLite allows one process to own its database at a time. Do not launch two
diff --git a/llms-full.txt b/llms-full.txt
index 232ec11a14..2c132bab27 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -1456,16 +1456,16 @@ are one principal. See [shared brain skills](shared-brain-skills.md).
| Profile | Access | Native MCP surface |
| --- | --- | --- |
-| `memory-reader` | Read selected memory | Starter |
-| `memory-writer` | Read and write selected memory | Starter |
-| `coding-agent` | Isolated project writes and explicit project reads | Starter |
+| `memory-reader` | Read selected memory | Full |
+| `memory-writer` | Read and write selected memory | Full |
+| `coding-agent` | Isolated project writes and explicit project reads | Full |
| `operator` | Read, write, and eligible brain administration operations | Full |
| `delegating-agent` | Memory plus explicitly bound delegation | Starter |
| `full` | All eligible remote capabilities at grant time, including bound delegation | Full |
A **profile grants authority**. A **surface selects visible tools**. Full surface does not bypass a grant, and `admin` does not imply delegation, the named shared-skill scopes, or owner dashboard/client-management authority. Starter includes authorized skill discovery and membership; the exact seven-tool `verbs` surface is memory-only. Thin CLI adapters use the full surface while retaining their source, operation, and write restrictions. Direct local CLI access is trusted access to the local computer; OAuth profiles do not confine a local shell.
-New grants snapshot operation names and source access. A later server upgrade does not silently give a snapshot-bound client new operations. Explicitly regrant to include them: `gbrain auth rescope-client <client_id> --allowed-operations …` for OAuth clients, or `gbrain auth rescope-token <name> --refresh-operations` (preview) then `--add <op,...>` for legacy tokens. `gbrain auth rescope --client <client_id> --operations all` (alias: `gbrain auth rescope-client <client_id> --allowed-operations all`) stores no snapshot and clears the profile instead, so the scopes and the surface alone decide, including operations later upgrades add. `gbrain auth clients` marks such a client `operations: "all"` with `includes_future_operations: true` and the command that re-pins it. A `bootstrap harness` re-run carries the replaced token's grants and does not widen its snapshot ([legacy token grants](../mcp/ADMIN.md#legacy-token-grants)). Archived sources are excluded. Legacy clients with a `NULL` operation snapshot retain their prior operation behavior.
+Clients granted a memory profile before the full-surface default keep their stored `starter` surface; no migration or repair widens it, and only an explicit `--profile` application regrants it. New grants snapshot operation names and source access. A later server upgrade does not silently give a snapshot-bound client new operations. The connection's own `whoami` reports `grant_diagnosis`: which blocker applies (scope, operation snapshot, client pin or server ceiling) and how many operations it hides, without naming them; `gbrain doctor` on the host reports the same as `grant_new_ops_available` with the commands. A grant written before snapshots recorded their operation catalog says "original intent unknown" rather than claiming it predates the operations. Explicitly regrant to include them: `gbrain auth rescope --client <client_id> --operations <op,...> --surface full --dry-run` (then without `--dry-run`; `--surface full` only when the stored surface also blocks) for OAuth clients, or `gbrain auth rescope-token <name> --refresh-operations` (preview) then `--add <op,...>` for legacy tokens ([grants that cannot reach new operations](../mcp/ADMIN.md#grants-that-cannot-reach-new-operations)). `gbrain auth rescope --client <client_id> --operations all` (alias: `gbrain auth rescope-client <client_id> --allowed-operations all`) stores no snapshot and clears the profile instead, so the scopes and the surface alone decide, including operations later upgrades add. `gbrain auth clients` marks such a client `operations: "all"` with `includes_future_operations: true` and the command that re-pins it. A `bootstrap harness` re-run carries the replaced token's grants and does not widen its snapshot ([legacy token grants](../mcp/ADMIN.md#legacy-token-grants)). Archived sources are excluded. Legacy clients with a `NULL` operation snapshot retain their prior operation behavior.
Snapshot-bound clients write through approved MCP operations such as `remember`, `capture`, or `put_page`. They cannot use the legacy `POST /ingest` webhook, whose queued writes do not yet enforce operation snapshots. Existing webhook clients with a `NULL` snapshot keep their legacy behavior.
@@ -2654,9 +2654,11 @@ lane; moving engines is `gbrain migrate`'s.
`--json` emits `{status, engine, ladder_rung, url_source}` as the ONLY stdout
content so a scripted install can `| jq` it. The access token is never
persisted, logged, or echoed.
-Tradeoff to know before choosing: Postgres brains get MCP tools every session plus
-the pull protocol, but NOT the PGLite-only per-turn bootstrap hook lane (see
-`BOOTSTRAP_FOR_AGENTS.md` and the degradation matrix in `docs/guides/bootstrap.md`).
+Postgres brains get MCP tools every session plus the pull protocol, and keep the
+per-turn bootstrap hook lane: the IPC listener is engine-uniform (it keys its
+socket off the connection URL), so the hooks fire whenever a `gbrain serve` for
+the brain is running, same as PGLite (see the degradation matrix in
+`docs/guides/bootstrap.md`).
**Runtime failure loop (how the harness self-heals).** When Postgres access
breaks at runtime, gbrain emits a machine marker: `GBRAIN_DB_ACCESS <reason>`
@@ -2837,9 +2839,9 @@ policy. Memory write access is not
including the parent, needs its own principal and private handoff.
Discover with `list_skills` using `schema_version: 2`, then fetch only relevant
-`get_skill` revisions and approved `get_skill_asset` dependencies. Starter
-supports these tools subject to grants; the `--surface verbs` examples below
-are deliberately memory-only. MCP resources at `gbrain://skills` offer the same
+`get_skill` revisions and approved `get_skill_asset` dependencies. The
+`--surface full` registrations below serve these tools subject to grants (the
+narrower `--surface verbs` is deliberately memory-only). MCP resources at `gbrain://skills` offer the same
authorized catalog, not a promise that every client loads native skills.
Managed Claude Code/Codex/opencode routers report `restart_required` and native
@@ -2894,7 +2896,7 @@ model gbrain removed in v0.33, needs `gbrain skillpack migrate-fence` once.)
**If you are Hermes:** register gbrain as your MCP server:
```bash
-printf 'Y\n' | hermes mcp add gbrain --env GBRAIN_HOME=$HOME --connect-timeout 60 --command $(which gbrain) --args serve
+printf 'Y\n' | hermes mcp add gbrain --env GBRAIN_HOME=$HOME --connect-timeout 60 --command $(which gbrain) --args serve --surface full
```
Keep `--args` last (everything after it becomes server argv) and verify with
@@ -2904,12 +2906,12 @@ Keep `--args` last (everything after it becomes server argv) and verify with
**If you are Grok Build** (xAI's `grok` CLI): register gbrain as your MCP server:
```bash
-grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- "$(command -v gbrain)" serve --surface verbs
+grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- "$(command -v gbrain)" serve --surface full
```
The add is lazy (exit 0 without connecting) — verify with
-`grok mcp doctor gbrain`, which spawns the server and must report
-`7 tools discovered`. This is the brain-only install; the `gbrain bootstrap`
+`grok mcp doctor gbrain`, which spawns the server and must report the tools it
+discovered (the full surface). This is the brain-only install; the `gbrain bootstrap`
personal-agent path does not support Grok yet (Claude Code, Codex, and opencode only).
Verified against Grok Build v1.0.4. Full reference:
[docs/mcp/GROK.md](docs/mcp/GROK.md).
@@ -2920,7 +2922,7 @@ install, follow `BOOTSTRAP_FOR_AGENTS.md` instead of this page. For the
brain-only MCP registration:
```bash
-opencode mcp add gbrain --env GBRAIN_HOME=$HOME -- "$(command -v gbrain)" serve --surface verbs
+opencode mcp add gbrain --env GBRAIN_HOME=$HOME -- "$(command -v gbrain)" serve --surface full
```
The add is lazy (exit 0 without connecting) — verify with `opencode mcp list`,
@@ -3522,7 +3524,7 @@ stdout (`--json`):
"options": [
{
"id": "wire",
- "label": "Register `<absolute path to gbrain> serve --surface starter` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "label": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
{
"id": "skip",
@@ -4753,11 +4755,11 @@ The agent starts with keyless memory and verifies it. API keys, automatic captur
### Lighter ways in
-**Just want a memory for your coding agent — no identity, no repo.** Spin up a local brain and connect it in two commands — zero server, zero token, zero tunnel. `--surface verbs` gives your agent the seven-verb memory protocol (`recall`, `remember`, `entity`, `synthesize`, `forget`, `context_pack`, `delta` — [MEMORY_VERBS v1](docs/protocol/MEMORY_VERBS_v1.md), frozen + additive-forever) instead of the full tool wall; drop the flag for every operation:
+**Just want a memory for your coding agent — no identity, no repo.** Spin up a local brain and connect it in two commands — zero server, zero token, zero tunnel. `--surface full` (the registration default) serves every operation, the seven-verb memory protocol ([MEMORY_VERBS v1](docs/protocol/MEMORY_VERBS_v1.md)) and `put_pages` included; a harness that caps its tool count can register `--surface verbs` or `--surface starter`:
```bash
gbrain init --pglite --no-embedding # keyless local brain (no Docker)
-claude mcp add gbrain -- "$(command -v gbrain)" serve --surface verbs # or: codex mcp add gbrain -- "$(command -v gbrain)" serve --surface verbs
+claude mcp add gbrain -- "$(command -v gbrain)" serve --surface full # or: codex mcp add gbrain -- "$(command -v gbrain)" serve --surface full
```
If `claude` is not found, install Claude Code first — or use the per-harness blocks in the [protocol doc](docs/protocol/MEMORY_VERBS_v1.md). Heads-up: memories agents save default to brain-wide visibility (every connected agent can recall them); pass `visibility: "private"` for local-only facts.
@@ -4791,7 +4793,7 @@ to keep daemon installation and paid reindexing opt-in.
### Connect GBrain to your AI client (MCP)
-For a hosted brain, start with the [native OAuth and private machine connection guide](docs/guides/hosted-harness-access.md). To open the dashboard, register clients, edit access, or invalidate tokens, use [MCP administration](docs/mcp/ADMIN.md). A **profile** controls MCP authority; a **surface** controls which granted tools are visible. Neither grants owner dashboard access. New memory profiles use the starter surface. `--surface verbs` retains exactly the seven memory verbs, with orientation available through `gbrain://capabilities`. Thin CLI connections use the full surface and remain restricted by their grants.
+For a hosted brain, start with the [native OAuth and private machine connection guide](docs/guides/hosted-harness-access.md). To open the dashboard, register clients, edit access, or invalidate tokens, use [MCP administration](docs/mcp/ADMIN.md). A **profile** controls MCP authority; a **surface** controls which granted tools are visible. Neither grants owner dashboard access. New memory profiles use the full surface. `--surface verbs` retains exactly the seven memory verbs, with orientation available through `gbrain://capabilities`. Thin CLI connections use the full surface and remain restricted by their grants.
Choose the connection instructions for your actual product:
@@ -4804,12 +4806,12 @@ commands, embedding costs, and the restrictions that remain after rebuilding.
- **[Claude Code](docs/mcp/CLAUDE_CODE.md)** — plugin: `/plugin marketplace add garrytan/gbrain` + `/plugin install gbrain@gbrain` (MCP + skills; persona variants `gbrain-coding` / `gbrain-daily` install curated subsets; pick one). Marketplace-free skills: `gbrain skillpack scaffold --harness claude-code` copies a persona-curated skill set into your user-scope skills dir. Or local one-liner: `claude mcp add gbrain -- "$(command -v gbrain)" serve`. Remote with just a bearer token: `gbrain connect https://your-host/mcp --token gbrain_xxx` prints a paste-ready block (or `--install` wires it up and smoke-tests the token).
- **[Codex](docs/mcp/CODEX.md)** — plugin (recommended): `codex plugin marketplace add garrytan/gbrain@codex-plugin` + `codex plugin add gbrain@gbrain` installs the MCP server AND the curated skill set. Or connect-only: `gbrain connect https://your-host/mcp --token gbrain_xxx --agent codex` (or `--install`); the token path reads `$GBRAIN_REMOTE_TOKEN` at runtime, while the private-handoff installer writes a private managed HTTP header so the connection survives a new shell.
-- **[Cursor / Windsurf / any stdio MCP client](docs/mcp/CLAUDE_CODE.md)** — same shape, add `{"command": "gbrain", "args": ["serve"]}` to your MCP config.
-- **[Hermes](docs/mcp/HERMES.md)** — `printf 'Y\n' | hermes mcp add gbrain --env GBRAIN_HOME=$HOME --connect-timeout 60 --command $(which gbrain) --args serve`. Keep `--args` last, and verify with `hermes mcp test gbrain` (the add exits 0 even on failure).
+- **[Cursor / Windsurf / any stdio MCP client](docs/mcp/CLAUDE_CODE.md)** — same shape, add `{"command": "gbrain", "args": ["serve", "--surface", "full"]}` to your MCP config.
+- **[Hermes](docs/mcp/HERMES.md)** — `printf 'Y\n' | hermes mcp add gbrain --env GBRAIN_HOME=$HOME --connect-timeout 60 --command $(which gbrain) --args serve --surface full`. Keep `--args` last, and verify with `hermes mcp test gbrain` (the add exits 0 even on failure).
- **[Grok Bot](docs/guides/grok-bot.md)** — recommended: keep the brain on your computer, publish it with `gbrain mcp expose --funnel`, grant the Bot a `memory-writer` client and install the thin CLI at `/workspace/gbrain`; or install memory inside the Bot computer when no machine of yours stays online. Bots share local files and credentials; sources organize memory without isolating Bots. **Say to your agent:** *"connect grok bot to my brain"*.
- **[Muse personal agent](docs/guides/muse.md)** — first verify its durable user-files location; then either connect it to your published brain (`gbrain mcp expose --funnel` + thin CLI) or install the local CLI there. Native MCP configuration and skill activation are not assumed. **Say to your agent:** *"connect muse to my brain"*.
-- **[Grok Build](docs/mcp/GROK.md)** — `grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- "$(command -v gbrain)" serve --surface verbs`. The add is lazy (exit 0 without connecting) — verify with `grok mcp doctor gbrain`, which spawns the server and reports `7 tools discovered`. Verified against Grok Build v1.0.4.
-- **[opencode](docs/mcp/OPENCODE.md)** (opencode.ai / SST — not OpenClaw) — `opencode mcp add gbrain --env GBRAIN_HOME=$HOME -- "$(command -v gbrain)" serve --surface verbs`, or let `gbrain bootstrap hooks --harness opencode` write the config for you (opencode is a bootstrap-supported harness — it reads AGENTS.md natively). The add is lazy — verify with `opencode mcp list`, which spawns the server (`✓ gbrain connected`). Remote: `gbrain connect https://your-host/mcp --token gbrain_xxx --agent opencode [--install]` — the config stores only the `{env:GBRAIN_REMOTE_TOKEN}` interpolation. Verified against opencode v1.18.18.
+- **[Grok Build](docs/mcp/GROK.md)** — `grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- "$(command -v gbrain)" serve --surface full`. The add is lazy (exit 0 without connecting) — verify with `grok mcp doctor gbrain`, which spawns the server. Verified against Grok Build v1.0.4.
+- **[opencode](docs/mcp/OPENCODE.md)** (opencode.ai / SST — not OpenClaw) — `opencode mcp add gbrain --env GBRAIN_HOME=$HOME -- "$(command -v gbrain)" serve --surface full`, or let `gbrain bootstrap hooks --harness opencode` write the config for you (opencode is a bootstrap-supported harness — it reads AGENTS.md natively). The add is lazy — verify with `opencode mcp list`, which spawns the server (`✓ gbrain connected`). Remote: `gbrain connect https://your-host/mcp --token gbrain_xxx --agent opencode [--install]` — the config stores only the `{env:GBRAIN_REMOTE_TOKEN}` interpolation. Verified against opencode v1.18.18.
- **[OpenClaw](docs/mcp/OPENCLAW.md)** — the ClawHub bundle plugin registers gbrain automatically (`openclaw.plugin.json` ships in this repo), or register the stdio server with `openclaw mcp add gbrain --command "$(command -v gbrain)" --arg serve --env GBRAIN_HOME=$HOME` (absolute path: the launchd gateway PATH lacks `~/.bun/bin`); verify with `openclaw mcp list`.
- **[Claude Desktop (Cowork)](docs/mcp/CLAUDE_DESKTOP.md)** — Settings → Integrations → add the URL of your HTTP server. Remote only; the local `claude_desktop_config.json` does not work for remote servers.
- **[Claude Cowork (team plan)](docs/mcp/CLAUDE_COWORK.md)** — org Owner adds the connector under Organization Settings → Connectors.
@@ -7821,9 +7823,10 @@ this channel production-grade rather than spammy-and-invisible:
client-side), the doctor check reconciles the counts against the hook's own
heartbeat and cautions when they diverge.
-The hook lane rides the PGLite serve's IPC socket: on a Postgres brain or a
-thin-client install the hook stays quiet by design (pull-mode retrieval covers
-those; extending the lane is a filed follow-up in TODOS.md).
+The hook lane rides the running serve's IPC socket on PGLite and Postgres alike
+(the listener is engine-uniform and keys its socket off the connection URL), so
+the hook stays quiet only while no `gbrain serve` for the brain is running, and
+on a thin-client install, where pull-mode retrieval covers it.
Kill switch: `GBRAIN_HOOKS=0`. Install/uninstall: `docs/guides/bootstrap.md`.
@@ -8148,7 +8151,7 @@ the same registry.
```bash
gbrain init --pglite # 2-second local brain
-claude mcp add gbrain -- "$(command -v gbrain)" serve --surface starter # the verbs plus page tools
+claude mcp add gbrain -- "$(command -v gbrain)" serve --surface full # every operation, the verbs included
gbrain remember "gbrain install check" --provenance install-check
gbrain recall --query "gbrain install check" # …now ask your agent in a NEW session
```
@@ -8163,28 +8166,28 @@ If `claude` is not found: install Claude Code first, or use a block below.
**Codex**
```bash
-codex mcp add gbrain -- "$(command -v gbrain)" serve --surface starter
+codex mcp add gbrain -- "$(command -v gbrain)" serve --surface full
```
**Grok Build** (verify with `grok mcp doctor gbrain` — the add is lazy)
```bash
-grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- "$(command -v gbrain)" serve --surface starter
+grok mcp add gbrain -e "GBRAIN_HOME=$HOME" -- "$(command -v gbrain)" serve --surface full
```
**opencode** (verify with `opencode mcp list` — the add is lazy, and list SPAWNS the server)
```bash
-opencode mcp add gbrain --env GBRAIN_HOME=$HOME -- "$(command -v gbrain)" serve --surface starter
+opencode mcp add gbrain --env GBRAIN_HOME=$HOME -- "$(command -v gbrain)" serve --surface full
```
**OpenClaw / any stdio MCP host** — register the server command
-`gbrain serve --surface starter`. Remote brains: `gbrain serve --http` on the
+`gbrain serve --surface full`. Remote brains: `gbrain serve --http` on the
host, then `gbrain connect https://host/mcp --token gbrain_xxx --install` on
each client.
**Surface modes:** `--surface verbs` exposes EXACTLY the seven verbs —
advertised list AND dispatch are filtered fail-closed (a hidden op returns
`unknown_tool` even when called by name). `--surface starter` exposes the
-~27-op daily-driver set (`STARTER_OPS` in `src/mcp/surface.ts`): the seven
+40-op daily-driver set (`STARTER_OPS` in `src/mcp/surface.ts`): the seven
verbs plus the daily brain-tool slice, the agent lane, `whoami`, `capture`, and the
`request_tools` discovery meta-op (re-derivable from production usage via
`scripts/derive-starter-ops.ts`). Monotonic by construction: verbs ⊆ starter ⊆ full
@@ -8192,8 +8195,9 @@ verbs plus the daily brain-tool slice, the agent lane, `whoami`, `capture`, and
verb semantics. `--surface full` (the default for a bare `serve`) exposes
every operation, verbs included. Every stdio registration gbrain writes
(`gbrain init`'s quickstart, readiness, `gbrain bootstrap hooks`, the plugins)
-pins `starter`, because `verbs` lacks the page reads and writes bootstrap's
-instructions use and `full` puts the whole catalogue in front of the model.
+pins `full`, callable and advertised: in the held-out agent benchmark, listing
+only `starter` or `verbs` lowered task success and saved no tokens. A harness
+that caps its tool count can register `--surface starter` or `--surface verbs`.
Persist a default for bare `serve` with `gbrain config set mcp_surface verbs`.
On stdio, `GBRAIN_SURFACE` in the server's env overrides `--surface`; a
session widens itself with `request_tools {"surface":"full"}` (see
diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index c42f746e76..c7dc63dc55 100644
--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
@@ -25,7 +25,7 @@
"args": [
"serve",
"--surface",
- "starter",
+ "full",
"--source-guard"
],
"cwd": "${CLAUDE_PLUGIN_ROOT}"
diff --git a/plugin-variants/gbrain-coding/.codex-plugin/mcp.json b/plugin-variants/gbrain-coding/.codex-plugin/mcp.json
index 3f3f699c33..acca85b10c 100644
--- a/plugin-variants/gbrain-coding/.codex-plugin/mcp.json
+++ b/plugin-variants/gbrain-coding/.codex-plugin/mcp.json
@@ -5,7 +5,7 @@
"args": [
"serve",
"--surface",
- "starter",
+ "full",
"--source-guard"
],
"cwd": ".",
diff --git a/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md b/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md
index 6f8260871a..f779484e6e 100644
--- a/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/brain-ops/SKILL.md
@@ -280,13 +280,3 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- `add_timeline_entry` — record events
- `get_backlinks` — check who references an entity
- `sync_brain` — sync changes to the index
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `add_link` → `gbrain link`
-- `sync_brain` → `gbrain sync`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md b/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md
index da4f50ba27..f5a7ebabf3 100644
--- a/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md
+++ b/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md
@@ -363,7 +363,7 @@ stdout (`--json`):
"options": [
{
"id": "wire",
- "label": "Register `<absolute path to gbrain> serve --surface starter` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "label": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
{
"id": "skip",
diff --git a/plugin-variants/gbrain-coding/skills/enrich/SKILL.md b/plugin-variants/gbrain-coding/skills/enrich/SKILL.md
index 76135ffa1b..35a0912ac6 100644
--- a/plugin-variants/gbrain-coding/skills/enrich/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/enrich/SKILL.md
@@ -381,12 +381,3 @@ Both page types have bidirectional back-links to every entity they mention.
- Retrieve raw data from gbrain (get_raw_data)
- Link entities in gbrain (add_link)
- Check backlinks in gbrain (get_backlinks)
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `add_link` → `gbrain link`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin-variants/gbrain-coding/skills/idea-ingest/SKILL.md b/plugin-variants/gbrain-coding/skills/idea-ingest/SKILL.md
index 2b8567f86f..f473d2a17f 100644
--- a/plugin-variants/gbrain-coding/skills/idea-ingest/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/idea-ingest/SKILL.md
@@ -141,13 +141,3 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- Hallucinating connections to brain knowledge — only cite connections you verified via search/query
- Creating generic slugs like `concepts/strategy` — be specific: `concepts/flywheel-effects`
- Assuming the fetch succeeded without verifying content was actually retrieved
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `add_link` → `gbrain link`
-- `file_upload` → `gbrain call file_upload <params_json>`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin-variants/gbrain-coding/skills/idea-lineage/SKILL.md b/plugin-variants/gbrain-coding/skills/idea-lineage/SKILL.md
index 15faa42743..e89cd383a6 100644
--- a/plugin-variants/gbrain-coding/skills/idea-lineage/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/idea-lineage/SKILL.md
@@ -228,14 +228,3 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- `takes_search` - holder-attributed beliefs, bets, hunches, and facts.
- `find_contradictions` - cached contradiction findings when relevant.
- `find_trajectory` - optional structured entity trajectory side-channel.
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `find_contradictions` → `gbrain find-contradictions`
-- `find_trajectory` → `gbrain find-trajectory`
-- `takes_search` → `gbrain takes-search`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin-variants/gbrain-coding/skills/ingest/SKILL.md b/plugin-variants/gbrain-coding/skills/ingest/SKILL.md
index 74048a61bf..8687316d33 100644
--- a/plugin-variants/gbrain-coding/skills/ingest/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/ingest/SKILL.md
@@ -326,13 +326,3 @@ Raw source: [preserved at path / uploaded to cloud]
- Tag a page in gbrain (add_tag)
- Store raw data in gbrain (put_raw_data)
- Check backlinks in gbrain (get_backlinks)
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `add_link` → `gbrain link`
-- `sync_brain` → `gbrain sync`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin-variants/gbrain-coding/skills/maintain/SKILL.md b/plugin-variants/gbrain-coding/skills/maintain/SKILL.md
index d3cecb5b9b..934c3dd01c 100644
--- a/plugin-variants/gbrain-coding/skills/maintain/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/maintain/SKILL.md
@@ -573,13 +573,3 @@ The maintenance report follows this structure:
- Tag a page in gbrain (add_tag)
- Remove a tag in gbrain (remove_tag)
- View timeline in gbrain (get_timeline)
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `add_link` → `gbrain link`
-- `get_health` → `gbrain doctor --json`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin-variants/gbrain-coding/skills/mcp-access/SKILL.md b/plugin-variants/gbrain-coding/skills/mcp-access/SKILL.md
index 25fb0c7fbb..06e14201d3 100644
--- a/plugin-variants/gbrain-coding/skills/mcp-access/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/mcp-access/SKILL.md
@@ -115,6 +115,7 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- `insufficient_scope` / `invalid_token` on an MCP call: this is a grant problem only the owner can change. Do not try successively broader OAuth scopes; tell the user which scope is missing.
- A failed transport after a mutation was sent means the outcome is unknown: re-read the client list before retrying, never re-send blind.
- A list call fails: a failed list is not an empty list; report the error.
+- A tool the grant should reach is missing (`unknown_tool`, or a write such as `put_pages` absent): read `grant_diagnosis` from `whoami` or `gbrain://capabilities`. It names the blocker (scope, operation snapshot, client pin or server ceiling) and counts the operations it hides without naming them. Relay its `fix` (`next: tell_user_to_run`) to the brain owner; on the host, `gbrain doctor` check `grant_new_ops_available` shows the exact commands. New memory-profile grants are on the full surface; older ones keep their stored surface until the owner changes it. An "original intent unknown" grant may be restricted on purpose: never widen it unasked, and offer `--operations all` (no snapshot, including operations later upgrades add) only as the user's explicit choice.
## Anti-Patterns
diff --git a/plugin-variants/gbrain-coding/skills/query/SKILL.md b/plugin-variants/gbrain-coding/skills/query/SKILL.md
index 92820369d6..dace517f2b 100644
--- a/plugin-variants/gbrain-coding/skills/query/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/query/SKILL.md
@@ -225,12 +225,3 @@ If search results seem off (wrong results, missing known pages, irrelevant hits)
- Check backlinks in gbrain (get_backlinks)
- Traverse the link graph in gbrain (traverse_graph)
- View timeline entries in gbrain (get_timeline)
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `get_timeline` → `gbrain timeline`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin-variants/gbrain-coding/skills/signal-detector/SKILL.md b/plugin-variants/gbrain-coding/skills/signal-detector/SKILL.md
index 1ef3d9fba9..250756adbd 100644
--- a/plugin-variants/gbrain-coding/skills/signal-detector/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/signal-detector/SKILL.md
@@ -169,12 +169,3 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- `put_page` — create/update brain pages
- `add_link` — cross-reference entities
- `add_timeline_entry` — record events on entity timelines
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `add_link` → `gbrain link`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index cd55208911..1addf1161a 100644
--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
@@ -25,7 +25,7 @@
"args": [
"serve",
"--surface",
- "starter",
+ "full",
"--source-guard"
],
"cwd": "${CLAUDE_PLUGIN_ROOT}"
diff --git a/plugin-variants/gbrain-daily/.codex-plugin/mcp.json b/plugin-variants/gbrain-daily/.codex-plugin/mcp.json
index 3f3f699c33..acca85b10c 100644
--- a/plugin-variants/gbrain-daily/.codex-plugin/mcp.json
+++ b/plugin-variants/gbrain-daily/.codex-plugin/mcp.json
@@ -5,7 +5,7 @@
"args": [
"serve",
"--surface",
- "starter",
+ "full",
"--source-guard"
],
"cwd": ".",
diff --git a/plugin-variants/gbrain-daily/skills/briefing/SKILL.md b/plugin-variants/gbrain-daily/skills/briefing/SKILL.md
index 5a7b5c8dfb..9d29096465 100644
--- a/plugin-variants/gbrain-daily/skills/briefing/SKILL.md
+++ b/plugin-variants/gbrain-daily/skills/briefing/SKILL.md
@@ -215,12 +215,3 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- List pages in gbrain by type (list_pages)
- Check gbrain health (get_health)
- View timeline entries in gbrain (get_timeline)
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `get_timeline` → `gbrain timeline`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md b/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md
index da4f50ba27..f5a7ebabf3 100644
--- a/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md
+++ b/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md
@@ -363,7 +363,7 @@ stdout (`--json`):
"options": [
{
"id": "wire",
- "label": "Register `<absolute path to gbrain> serve --surface starter` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "label": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
{
"id": "skip",
diff --git a/plugin-variants/gbrain-daily/skills/daily-task-prep/SKILL.md b/plugin-variants/gbrain-daily/skills/daily-task-prep/SKILL.md
index da003c54e2..146e486613 100644
--- a/plugin-variants/gbrain-daily/skills/daily-task-prep/SKILL.md
+++ b/plugin-variants/gbrain-daily/skills/daily-task-prep/SKILL.md
@@ -67,12 +67,3 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- Listing meetings without loading attendee context from brain
- Ignoring yesterday's unresolved threads
- Presenting tasks without priority ordering
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `get_timeline` → `gbrain timeline`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin-variants/gbrain-daily/skills/data-research/SKILL.md b/plugin-variants/gbrain-daily/skills/data-research/SKILL.md
index c046cf69eb..9059c1ac40 100644
--- a/plugin-variants/gbrain-daily/skills/data-research/SKILL.md
+++ b/plugin-variants/gbrain-daily/skills/data-research/SKILL.md
@@ -149,14 +149,3 @@ Each entry links to its raw source. Running totals at the bottom of each section
## Conventions
References `skills/conventions/quality.md` for citation and back-linking rules.
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `add_link` → `gbrain link`
-- `file_upload` → `gbrain call file_upload <params_json>`
-- `put_raw_data` → `gbrain call put_raw_data <params_json>`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin-variants/gbrain-daily/skills/gbrain-advisor/SKILL.md b/plugin-variants/gbrain-daily/skills/gbrain-advisor/SKILL.md
index 4f19eaeb76..f5d0a52f8e 100644
--- a/plugin-variants/gbrain-daily/skills/gbrain-advisor/SKILL.md
+++ b/plugin-variants/gbrain-daily/skills/gbrain-advisor/SKILL.md
@@ -125,12 +125,3 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- **Calling the MCP `advisor` op for workspace install state.** Over MCP the
advisor returns brain-state signals only; uninstalled-skill findings are a
local-CLI concern.
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `advisor` → `gbrain advisor`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin-variants/gbrain-daily/skills/ingest/SKILL.md b/plugin-variants/gbrain-daily/skills/ingest/SKILL.md
index 74048a61bf..8687316d33 100644
--- a/plugin-variants/gbrain-daily/skills/ingest/SKILL.md
+++ b/plugin-variants/gbrain-daily/skills/ingest/SKILL.md
@@ -326,13 +326,3 @@ Raw source: [preserved at path / uploaded to cloud]
- Tag a page in gbrain (add_tag)
- Store raw data in gbrain (put_raw_data)
- Check backlinks in gbrain (get_backlinks)
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `add_link` → `gbrain link`
-- `sync_brain` → `gbrain sync`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin-variants/gbrain-daily/skills/mcp-access/SKILL.md b/plugin-variants/gbrain-daily/skills/mcp-access/SKILL.md
index 25fb0c7fbb..06e14201d3 100644
--- a/plugin-variants/gbrain-daily/skills/mcp-access/SKILL.md
+++ b/plugin-variants/gbrain-daily/skills/mcp-access/SKILL.md
@@ -115,6 +115,7 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- `insufficient_scope` / `invalid_token` on an MCP call: this is a grant problem only the owner can change. Do not try successively broader OAuth scopes; tell the user which scope is missing.
- A failed transport after a mutation was sent means the outcome is unknown: re-read the client list before retrying, never re-send blind.
- A list call fails: a failed list is not an empty list; report the error.
+- A tool the grant should reach is missing (`unknown_tool`, or a write such as `put_pages` absent): read `grant_diagnosis` from `whoami` or `gbrain://capabilities`. It names the blocker (scope, operation snapshot, client pin or server ceiling) and counts the operations it hides without naming them. Relay its `fix` (`next: tell_user_to_run`) to the brain owner; on the host, `gbrain doctor` check `grant_new_ops_available` shows the exact commands. New memory-profile grants are on the full surface; older ones keep their stored surface until the owner changes it. An "original intent unknown" grant may be restricted on purpose: never widen it unasked, and offer `--operations all` (no snapshot, including operations later upgrades add) only as the user's explicit choice.
## Anti-Patterns
diff --git a/plugin-variants/gbrain-daily/skills/media-ingest/SKILL.md b/plugin-variants/gbrain-daily/skills/media-ingest/SKILL.md
index e0711e6a94..f6caf212e1 100644
--- a/plugin-variants/gbrain-daily/skills/media-ingest/SKILL.md
+++ b/plugin-variants/gbrain-daily/skills/media-ingest/SKILL.md
@@ -153,13 +153,3 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- Filing **raw ingest** by format (all videos in `media/videos/`) instead of by subject. Note: format-prefixed paths under `media/<format>/<slug>` ARE sanctioned for **synthesized one-of-one output** like book-mirror's `media/books/<slug>-personalized.md`. The anti-pattern is for raw ingest, not for sui generis synthesis. See `skills/_brain-filing-rules.md` "Sanctioned exception: synthesis output is sui generis."
- Not preserving raw source files
- Creating stub pages without meaningful content
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `add_link` → `gbrain link`
-- `file_upload` → `gbrain call file_upload <params_json>`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin-variants/gbrain-daily/skills/meeting-ingestion/SKILL.md b/plugin-variants/gbrain-daily/skills/meeting-ingestion/SKILL.md
index fbc74d2b81..594523bd86 100644
--- a/plugin-variants/gbrain-daily/skills/meeting-ingestion/SKILL.md
+++ b/plugin-variants/gbrain-daily/skills/meeting-ingestion/SKILL.md
@@ -587,14 +587,3 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
transit between them
- Re-checking substance in the sequence pass (or order in V1–V5) — the axes
are orthogonal by design
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `add_link` → `gbrain link`
-- `chronicle_day` → `gbrain day`
-- `get_timeline` → `gbrain timeline`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin-variants/gbrain-daily/skills/query/SKILL.md b/plugin-variants/gbrain-daily/skills/query/SKILL.md
index 92820369d6..dace517f2b 100644
--- a/plugin-variants/gbrain-daily/skills/query/SKILL.md
+++ b/plugin-variants/gbrain-daily/skills/query/SKILL.md
@@ -225,12 +225,3 @@ If search results seem off (wrong results, missing known pages, irrelevant hits)
- Check backlinks in gbrain (get_backlinks)
- Traverse the link graph in gbrain (traverse_graph)
- View timeline entries in gbrain (get_timeline)
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `get_timeline` → `gbrain timeline`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin/README.md b/plugin/README.md
index 95b569a71c..da4e413ceb 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -8,16 +8,13 @@ addition/exclusion).
## MCP surface note (read once)
-The plugin's MCP server runs `gbrain serve --surface starter` — the
-40-op daily-driver surface (the seven memory verbs + daily
-brain ops + capture), the same surface every stdio registration gbrain writes
-pins. 22
-bundled skills reference gbrain operations beyond that surface; every one of
-them has a first-class `gbrain` CLI path, which is the primary way skills
-drive gbrain. When a skill step names an operation your MCP tool list doesn't
-carry, call `request_tools {"surface":"full"}` to add it to this session, run
-the equivalent `gbrain` CLI command, or widen this machine's plugin surface
-with `GBRAIN_SURFACE=full` (the server honors it; new sessions pick it up).
+The plugin's MCP server runs `gbrain serve --surface full` — 161
+operations, the same surface every stdio registration gbrain writes pins.
+Every gbrain operation the bundled skills name is on it. A harness that caps
+its tool count can narrow this machine's plugin surface with
+`GBRAIN_SURFACE=starter` (or `verbs`); the server honors it and new sessions
+pick it up. Skills keep their first-class `gbrain` CLI paths for anything a
+narrowed list leaves out.
## Requirements
diff --git a/plugin/skills/brain-ops/SKILL.md b/plugin/skills/brain-ops/SKILL.md
index 6f8260871a..f779484e6e 100644
--- a/plugin/skills/brain-ops/SKILL.md
+++ b/plugin/skills/brain-ops/SKILL.md
@@ -280,13 +280,3 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- `add_timeline_entry` — record events
- `get_backlinks` — check who references an entity
- `sync_brain` — sync changes to the index
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `add_link` → `gbrain link`
-- `sync_brain` → `gbrain sync`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin/skills/briefing/SKILL.md b/plugin/skills/briefing/SKILL.md
index 5a7b5c8dfb..9d29096465 100644
--- a/plugin/skills/briefing/SKILL.md
+++ b/plugin/skills/briefing/SKILL.md
@@ -215,12 +215,3 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- List pages in gbrain by type (list_pages)
- Check gbrain health (get_health)
- View timeline entries in gbrain (get_timeline)
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `get_timeline` → `gbrain timeline`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin/skills/cold-start/SKILL.md b/plugin/skills/cold-start/SKILL.md
index a239634556..051de77f7d 100644
--- a/plugin/skills/cold-start/SKILL.md
+++ b/plugin/skills/cold-start/SKILL.md
@@ -569,13 +569,3 @@ Next: Phase N+1 — [description]. Ready to proceed?
- `add_link` — cross-reference entities
- `add_timeline_entry` — record events on entity timelines
- `sync_brain` — sync changes to the index after each phase
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `add_link` → `gbrain link`
-- `sync_brain` → `gbrain sync`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin/skills/conventions/agent-operator-protocol.md b/plugin/skills/conventions/agent-operator-protocol.md
index da4f50ba27..f5a7ebabf3 100644
--- a/plugin/skills/conventions/agent-operator-protocol.md
+++ b/plugin/skills/conventions/agent-operator-protocol.md
@@ -363,7 +363,7 @@ stdout (`--json`):
"options": [
{
"id": "wire",
- "label": "Register `<absolute path to gbrain> serve --surface starter` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "label": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
{
"id": "skip",
diff --git a/plugin/skills/daily-task-prep/SKILL.md b/plugin/skills/daily-task-prep/SKILL.md
index da003c54e2..146e486613 100644
--- a/plugin/skills/daily-task-prep/SKILL.md
+++ b/plugin/skills/daily-task-prep/SKILL.md
@@ -67,12 +67,3 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- Listing meetings without loading attendee context from brain
- Ignoring yesterday's unresolved threads
- Presenting tasks without priority ordering
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `get_timeline` → `gbrain timeline`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin/skills/data-research/SKILL.md b/plugin/skills/data-research/SKILL.md
index c046cf69eb..9059c1ac40 100644
--- a/plugin/skills/data-research/SKILL.md
+++ b/plugin/skills/data-research/SKILL.md
@@ -149,14 +149,3 @@ Each entry links to its raw source. Running totals at the bottom of each section
## Conventions
References `skills/conventions/quality.md` for citation and back-linking rules.
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `add_link` → `gbrain link`
-- `file_upload` → `gbrain call file_upload <params_json>`
-- `put_raw_data` → `gbrain call put_raw_data <params_json>`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin/skills/eiirp/SKILL.md b/plugin/skills/eiirp/SKILL.md
index 66af6225ce..76547e5141 100644
--- a/plugin/skills/eiirp/SKILL.md
+++ b/plugin/skills/eiirp/SKILL.md
@@ -539,12 +539,3 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
plus undeclared types, the same classification as `schema lint
--with-db`); over MCP, `run_doctor`'s schema_pack_consistency check
carries the same verdict.
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `add_link` → `gbrain link`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin/skills/enrich/SKILL.md b/plugin/skills/enrich/SKILL.md
index 76135ffa1b..35a0912ac6 100644
--- a/plugin/skills/enrich/SKILL.md
+++ b/plugin/skills/enrich/SKILL.md
@@ -381,12 +381,3 @@ Both page types have bidirectional back-links to every entity they mention.
- Retrieve raw data from gbrain (get_raw_data)
- Link entities in gbrain (add_link)
- Check backlinks in gbrain (get_backlinks)
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `add_link` → `gbrain link`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin/skills/gbrain-advisor/SKILL.md b/plugin/skills/gbrain-advisor/SKILL.md
index 4f19eaeb76..f5d0a52f8e 100644
--- a/plugin/skills/gbrain-advisor/SKILL.md
+++ b/plugin/skills/gbrain-advisor/SKILL.md
@@ -125,12 +125,3 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- **Calling the MCP `advisor` op for workspace install state.** Over MCP the
advisor returns brain-state signals only; uninstalled-skill findings are a
local-CLI concern.
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `advisor` → `gbrain advisor`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin/skills/google-loops/SKILL.md b/plugin/skills/google-loops/SKILL.md
index 8da92c2663..1a3eb257d4 100644
--- a/plugin/skills/google-loops/SKILL.md
+++ b/plugin/skills/google-loops/SKILL.md
@@ -194,14 +194,3 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- **Marking loops done for the user.** Close (`gbrain loops done <id>`) only
after the user says it's handled; thread loops self-close on the next sync
when the reply is visible in Gmail.
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `loops_close` → `gbrain loops done`
-- `loops_mute` → `gbrain loops mute`
-- `open_loops` → `gbrain loops list`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin/skills/idea-ingest/SKILL.md b/plugin/skills/idea-ingest/SKILL.md
index 2b8567f86f..f473d2a17f 100644
--- a/plugin/skills/idea-ingest/SKILL.md
+++ b/plugin/skills/idea-ingest/SKILL.md
@@ -141,13 +141,3 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- Hallucinating connections to brain knowledge — only cite connections you verified via search/query
- Creating generic slugs like `concepts/strategy` — be specific: `concepts/flywheel-effects`
- Assuming the fetch succeeded without verifying content was actually retrieved
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `add_link` → `gbrain link`
-- `file_upload` → `gbrain call file_upload <params_json>`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin/skills/idea-lineage/SKILL.md b/plugin/skills/idea-lineage/SKILL.md
index 15faa42743..e89cd383a6 100644
--- a/plugin/skills/idea-lineage/SKILL.md
+++ b/plugin/skills/idea-lineage/SKILL.md
@@ -228,14 +228,3 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- `takes_search` - holder-attributed beliefs, bets, hunches, and facts.
- `find_contradictions` - cached contradiction findings when relevant.
- `find_trajectory` - optional structured entity trajectory side-channel.
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `find_contradictions` → `gbrain find-contradictions`
-- `find_trajectory` → `gbrain find-trajectory`
-- `takes_search` → `gbrain takes-search`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin/skills/ingest/SKILL.md b/plugin/skills/ingest/SKILL.md
index 74048a61bf..8687316d33 100644
--- a/plugin/skills/ingest/SKILL.md
+++ b/plugin/skills/ingest/SKILL.md
@@ -326,13 +326,3 @@ Raw source: [preserved at path / uploaded to cloud]
- Tag a page in gbrain (add_tag)
- Store raw data in gbrain (put_raw_data)
- Check backlinks in gbrain (get_backlinks)
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `add_link` → `gbrain link`
-- `sync_brain` → `gbrain sync`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin/skills/maintain/SKILL.md b/plugin/skills/maintain/SKILL.md
index d3cecb5b9b..934c3dd01c 100644
--- a/plugin/skills/maintain/SKILL.md
+++ b/plugin/skills/maintain/SKILL.md
@@ -573,13 +573,3 @@ The maintenance report follows this structure:
- Tag a page in gbrain (add_tag)
- Remove a tag in gbrain (remove_tag)
- View timeline in gbrain (get_timeline)
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `add_link` → `gbrain link`
-- `get_health` → `gbrain doctor --json`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin/skills/mcp-access/SKILL.md b/plugin/skills/mcp-access/SKILL.md
index 25fb0c7fbb..06e14201d3 100644
--- a/plugin/skills/mcp-access/SKILL.md
+++ b/plugin/skills/mcp-access/SKILL.md
@@ -115,6 +115,7 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- `insufficient_scope` / `invalid_token` on an MCP call: this is a grant problem only the owner can change. Do not try successively broader OAuth scopes; tell the user which scope is missing.
- A failed transport after a mutation was sent means the outcome is unknown: re-read the client list before retrying, never re-send blind.
- A list call fails: a failed list is not an empty list; report the error.
+- A tool the grant should reach is missing (`unknown_tool`, or a write such as `put_pages` absent): read `grant_diagnosis` from `whoami` or `gbrain://capabilities`. It names the blocker (scope, operation snapshot, client pin or server ceiling) and counts the operations it hides without naming them. Relay its `fix` (`next: tell_user_to_run`) to the brain owner; on the host, `gbrain doctor` check `grant_new_ops_available` shows the exact commands. New memory-profile grants are on the full surface; older ones keep their stored surface until the owner changes it. An "original intent unknown" grant may be restricted on purpose: never widen it unasked, and offer `--operations all` (no snapshot, including operations later upgrades add) only as the user's explicit choice.
## Anti-Patterns
diff --git a/plugin/skills/media-ingest/SKILL.md b/plugin/skills/media-ingest/SKILL.md
index e0711e6a94..f6caf212e1 100644
--- a/plugin/skills/media-ingest/SKILL.md
+++ b/plugin/skills/media-ingest/SKILL.md
@@ -153,13 +153,3 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- Filing **raw ingest** by format (all videos in `media/videos/`) instead of by subject. Note: format-prefixed paths under `media/<format>/<slug>` ARE sanctioned for **synthesized one-of-one output** like book-mirror's `media/books/<slug>-personalized.md`. The anti-pattern is for raw ingest, not for sui generis synthesis. See `skills/_brain-filing-rules.md` "Sanctioned exception: synthesis output is sui generis."
- Not preserving raw source files
- Creating stub pages without meaningful content
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `add_link` → `gbrain link`
-- `file_upload` → `gbrain call file_upload <params_json>`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin/skills/meeting-ingestion/SKILL.md b/plugin/skills/meeting-ingestion/SKILL.md
index fbc74d2b81..594523bd86 100644
--- a/plugin/skills/meeting-ingestion/SKILL.md
+++ b/plugin/skills/meeting-ingestion/SKILL.md
@@ -587,14 +587,3 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
transit between them
- Re-checking substance in the sequence pass (or order in V1–V5) — the axes
are orthogonal by design
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `add_link` → `gbrain link`
-- `chronicle_day` → `gbrain day`
-- `get_timeline` → `gbrain timeline`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin/skills/migrate/SKILL.md b/plugin/skills/migrate/SKILL.md
index 0acba07c36..eea2ef60fb 100644
--- a/plugin/skills/migrate/SKILL.md
+++ b/plugin/skills/migrate/SKILL.md
@@ -184,14 +184,3 @@ Verification:
- Get gbrain statistics (get_stats)
- Check gbrain health (get_health)
- Search gbrain (query)
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `add_link` → `gbrain link`
-- `add_tag` → `gbrain tag`
-- `sync_brain` → `gbrain sync`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin/skills/minion-orchestrator/SKILL.md b/plugin/skills/minion-orchestrator/SKILL.md
index b1d30a1076..9b4c897e86 100644
--- a/plugin/skills/minion-orchestrator/SKILL.md
+++ b/plugin/skills/minion-orchestrator/SKILL.md
@@ -553,19 +553,3 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- Get structured progress — `get_job_progress` (MCP)
- Queue stats — `get_job_stats` (MCP; admin scope over HTTP, same as the other
jobs ops here — includes the wedged-queue silent-halt signal) or `gbrain jobs stats` (CLI)
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `get_job` → `gbrain jobs get`
-- `get_job_progress` → `gbrain call get_job_progress <params_json>`
-- `list_jobs` → `gbrain jobs list`
-- `pause_job` → `gbrain call pause_job <params_json>`
-- `replay_job` → `gbrain call replay_job <params_json>`
-- `resume_job` → `gbrain call resume_job <params_json>`
-- `send_job_message` → `gbrain call send_job_message <params_json>`
-- `submit_job` → `gbrain jobs submit`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin/skills/query/SKILL.md b/plugin/skills/query/SKILL.md
index 92820369d6..dace517f2b 100644
--- a/plugin/skills/query/SKILL.md
+++ b/plugin/skills/query/SKILL.md
@@ -225,12 +225,3 @@ If search results seem off (wrong results, missing known pages, irrelevant hits)
- Check backlinks in gbrain (get_backlinks)
- Traverse the link graph in gbrain (traverse_graph)
- View timeline entries in gbrain (get_timeline)
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `get_timeline` → `gbrain timeline`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin/skills/schema-author/SKILL.md b/plugin/skills/schema-author/SKILL.md
index deeb03e56f..29adec30dc 100644
--- a/plugin/skills/schema-author/SKILL.md
+++ b/plugin/skills/schema-author/SKILL.md
@@ -312,20 +312,3 @@ On failure, the error envelope follows the standard `StructuredAgentError` shape
pass `--force` if you know the holder is wedged.
- `permission_denied` (MCP only) → your OAuth client doesn't have `admin`
scope. Re-register with `gbrain auth register-client --scopes admin`.
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `get_active_schema_pack` → `gbrain schema active`
-- `list_schema_packs` → `gbrain schema list`
-- `reload_schema_pack` → `gbrain call reload_schema_pack <params_json>`
-- `schema_apply_mutations` → `gbrain call schema_apply_mutations <params_json>`
-- `schema_explain_type` → `gbrain schema explain`
-- `schema_graph` → `gbrain schema graph`
-- `schema_lint` → `gbrain schema lint`
-- `schema_review_orphans` → `gbrain schema review-orphans`
-- `schema_stats` → `gbrain schema stats`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin/skills/schema-unify/SKILL.md b/plugin/skills/schema-unify/SKILL.md
index 5efa167aea..a52a3bfa74 100644
--- a/plugin/skills/schema-unify/SKILL.md
+++ b/plugin/skills/schema-unify/SKILL.md
@@ -288,12 +288,3 @@ For structured JSON, `gbrain call get_job '{"id": <id>}'` returns the job row; i
- Architecture: https://github.com/garrytan/gbrain/blob/master/docs/architecture/type-taxonomy.md
- Pack-upgrade mechanism: https://github.com/garrytan/gbrain/blob/master/docs/architecture/pack-upgrade-mechanism.md
- Issue: https://github.com/garrytan/gbrain/issues/1479
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `run_onboard` → `gbrain call run_onboard <params_json>`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin/skills/setup/SKILL.md b/plugin/skills/setup/SKILL.md
index 17f46349ee..cd0ea52ec6 100644
--- a/plugin/skills/setup/SKILL.md
+++ b/plugin/skills/setup/SKILL.md
@@ -221,14 +221,3 @@ cleanup. Name pending steps and the exact repair action. Redact credentials.
Only declare observed stages complete. A CLI test, schedule file, fluent
answer, HTTP response, or job ID cannot certify the full native experience.
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `get_health` → `gbrain doctor --json`
-- `get_stats` → `gbrain stats`
-- `sync_brain` → `gbrain sync`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/plugin/skills/signal-detector/SKILL.md b/plugin/skills/signal-detector/SKILL.md
index 1ef3d9fba9..250756adbd 100644
--- a/plugin/skills/signal-detector/SKILL.md
+++ b/plugin/skills/signal-detector/SKILL.md
@@ -169,12 +169,3 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- `put_page` — create/update brain pages
- `add_link` — cross-reference entities
- `add_timeline_entry` — record events on entity timelines
-
-## Tools outside your MCP surface
-
-This plugin serves the starter tool surface. When a step above names one of these tools and your tool list
-does not have it, call request_tools {"surface":"full"} to add it to this session, or run its gbrain CLI equivalent:
-
-- `add_link` → `gbrain link`
-
-To widen every new session, set this machine's plugin surface with GBRAIN_SURFACE=full.
diff --git a/scripts/ci-ubicloud.ts b/scripts/ci-ubicloud.ts
index 0ce2551378..da3bb01f8c 100755
--- a/scripts/ci-ubicloud.ts
+++ b/scripts/ci-ubicloud.ts
@@ -43,8 +43,8 @@
* recorded name is destroyed and polled until it is confirmed gone.
*/
-import { spawn, spawnSync } from "node:child_process";
-import { appendFileSync, createReadStream, createWriteStream, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { spawnSync, type ChildProcess } from "node:child_process";
+import { appendFileSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import {
@@ -61,6 +61,7 @@ import {
type Lane,
type WeightTable,
} from "./ubicloud/schedule.ts";
+import { runScript, type RunScriptOpts } from "./ubicloud/run-script.ts";
const ROOT = resolve(import.meta.dir, "..");
const RUNNER = join(ROOT, "scripts/ubicloud/ubi-runner.sh");
@@ -162,32 +163,11 @@ function sh(cmd: string, args: string[]): string {
}
const lines = (text: string) => text.split(/\s+/).map((l) => l.trim()).filter(Boolean);
-const children = new Map<ReturnType<typeof spawn>, string>();
+const children = new Map<ChildProcess, string>();
-/** Run the runner script; stdout goes to `out` (a path) or is returned. */
-function runner(args: string[], opts: { out?: string; input?: string; timeoutMs?: number } = {}): Promise<{ code: number; stdout: string }> {
- return new Promise((resolvePromise) => {
- const child = spawn("bash", [RUNNER, ...args], { cwd: ROOT, stdio: ["pipe", "pipe", "pipe"] });
- children.set(child, args[0]!);
- let stdout = "";
- let stderr = "";
- const sink = opts.out ? createWriteStream(opts.out) : null;
- child.stdout!.on("data", (chunk) => (sink ? sink.write(chunk) : (stdout += chunk)));
- child.stderr!.on("data", (chunk) => (sink ? sink.write(chunk) : (stderr += chunk)));
- if (opts.input) {
- createReadStream(opts.input).pipe(child.stdin!);
- } else {
- child.stdin!.end();
- }
- const timer = opts.timeoutMs ? setTimeout(() => child.kill("SIGKILL"), opts.timeoutMs) : null;
- child.on("close", (code) => {
- if (timer) clearTimeout(timer);
- children.delete(child);
- const finish = () => resolvePromise({ code: code ?? 1, stdout: sink ? "" : stdout + (code ? stderr : "") });
- if (sink) sink.end(finish);
- else finish();
- });
- });
+/** Run the runner script; output goes to `out` (a path) or is returned (scripts/ubicloud/run-script.ts). */
+function runner(args: string[], opts: Omit<RunScriptOpts, "cwd" | "onSpawn" | "onClose"> = {}): Promise<{ code: number; stdout: string }> {
+ return runScript(RUNNER, args, { ...opts, cwd: ROOT, onSpawn: (child) => children.set(child, args[0]!), onClose: (child) => children.delete(child) });
}
const quote = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`;
@@ -275,7 +255,7 @@ async function main() {
// ── Checkout tarball, packed once while the VMs boot ─────────────────────
const tarball = join(tmpdir(), `gbrain-ci-ubicloud-${process.pid}.tgz`);
- const packed = runner(["pack", ROOT], { out: tarball });
+ const packed = runner(["pack", ROOT], { out: tarball, stdoutOnly: true });
// Faster create and SSH polling than the runner's interactive default.
process.env.UBI_POLL_SECONDS ??= "2";
@@ -445,7 +425,8 @@ async function main() {
// and waits for the marker the upload writes when it lands.
const env = `SLOTS=${opts.slots} BUN_VERSION=${quote(bunVersion)} GITLEAKS=${opts.lanes.has("gitleaks") ? 1 : 0} CHECKOUT=${REMOTE_DIR} CHECKOUT_MARKER=${UNPACKED_MARKER}`;
const setupRun = runner(["ssh", vm.name, `${env} bash -s`], { input: SETUP_SCRIPT, out: `${setupLog}.bootstrap`, timeoutMs: 15 * 60 * 1000 });
- if ((await packed).code !== 0) throw new Error("packing the checkout failed");
+ const pack = await packed;
+ if (pack.code !== 0) throw new Error(`packing the checkout failed: ${pack.stdout.trim().split("\n").slice(-3).join(" | ")}`);
const unpack = await runner(["unpack", vm.name, REMOTE_DIR], { input: tarball });
const marked = unpack.code === 0 ? await runner(["ssh", vm.name, `touch ${UNPACKED_MARKER}`]) : unpack;
if (marked.code !== 0) {
diff --git a/scripts/generate-plugin-tree.ts b/scripts/generate-plugin-tree.ts
index ed9f85ee61..e6ce6dc446 100644
--- a/scripts/generate-plugin-tree.ts
+++ b/scripts/generate-plugin-tree.ts
@@ -21,7 +21,7 @@
*
* Starter-surface gap snapshot: each bundled skill's frontmatter `tools:`
* list is compared against the REGISTRATION_SURFACE op set (the plugin lanes
- * serve `--surface starter`, the surface every stdio registration gbrain
+ * serve `--surface full` today, the surface every stdio registration gbrain
* writes pins; the root plugin manifests must pin the same value). Harness tools (shell/exec/read/write/edit/
* web_search/web_fetch), literal `gbrain` (CLI usage marker), and unknown
* non-op names are not MCP ops; `mcp:`-prefixed names count with the prefix
@@ -298,16 +298,20 @@ addition/exclusion).
## MCP surface note (read once)
-The plugin's MCP server runs \`gbrain serve --surface ${REGISTRATION_SURFACE}\` — the
-${SURFACE_OPS.size}-op daily-driver surface (the seven memory verbs + daily
-brain ops + capture), the same surface every stdio registration gbrain writes
-pins. ${gapSkills}
-bundled skills reference gbrain operations beyond that surface; every one of
+The plugin's MCP server runs \`gbrain serve --surface ${REGISTRATION_SURFACE}\` — ${SURFACE_OPS.size}
+operations, the same surface every stdio registration gbrain writes pins.
+${gapSkills === 0
+ ? `Every gbrain operation the bundled skills name is on it. A harness that caps
+its tool count can narrow this machine's plugin surface with
+\`GBRAIN_SURFACE=starter\` (or \`verbs\`); the server honors it and new sessions
+pick it up. Skills keep their first-class \`gbrain\` CLI paths for anything a
+narrowed list leaves out.`
+ : `${gapSkills} bundled skills reference gbrain operations beyond that surface; every one of
them has a first-class \`gbrain\` CLI path, which is the primary way skills
drive gbrain. When a skill step names an operation your MCP tool list doesn't
carry, call \`request_tools {"surface":"full"}\` to add it to this session, run
the equivalent \`gbrain\` CLI command, or widen this machine's plugin surface
-with \`GBRAIN_SURFACE=full\` (the server honors it; new sessions pick it up).
+with \`GBRAIN_SURFACE=full\` (the server honors it; new sessions pick it up).`}
## Requirements
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 9d6a91a0fd..42b5b913f8 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -11,7 +11,7 @@ src/commands/extract-conversation-facts.ts 2213 ratchet grown v0.46.x per-provid
src/commands/extract.ts 2580 ratchet 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
src/commands/jobs.ts 666 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
src/commands/serve-http.ts 926 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)
-src/core/ai/gateway.ts 4427 ratchet +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)
+src/core/ai/gateway.ts 4430 ratchet +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
src/commands/sync.ts 514 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)
src/core/cycle.ts 3283 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +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)
src/core/cycle/synthesize.ts 3227 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +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)
diff --git a/scripts/persistence/history-fixture.ts b/scripts/persistence/history-fixture.ts
index 0de8dd5156..5f158bdce6 100644
--- a/scripts/persistence/history-fixture.ts
+++ b/scripts/persistence/history-fixture.ts
@@ -65,6 +65,8 @@ export interface HistoryFixtureOptions {
worktrees: number;
/** Scratch directory for the checkouts; a fresh temporary directory by default. */
root?: string;
+ /** Write reply wait for every op (test seam; absent = the operation default, 5 s for agents). */
+ writeWaitMs?: number;
}
export interface HistoryFixtureSource { id: string; root: string; worktree: number }
export interface HistoryFixture {
@@ -208,8 +210,27 @@ export async function prepareTopology(engine: BrainEngine, { sources, worktrees,
}
/** Build a brain with real persistence history. See the module comment for preconditions. */
+/**
+ * A write that outlives its reply wait answers `write_pending` with its
+ * receipt (a loaded CI host can take longer than put_page's 5 s default).
+ * The caller's documented recovery is replaying the same request_id, which
+ * reports the same write's state; settle each op that way before the next op
+ * in its lane reads `$current`. A write still pending at the deadline, or
+ * refused, is reported as it is, so the "every op commits" check stays exact.
+ */
+const HISTORY_COMMIT_DEADLINE_MS = 120_000;
+async function executeCommitted(world: Parameters<typeof executeOp>[0], d: OpDescriptor) {
+ const deadline = Date.now() + HISTORY_COMMIT_DEADLINE_MS;
+ let observation = await executeOp(world, d);
+ while (observation.status === 'pending' && Date.now() < deadline) {
+ await Bun.sleep(100);
+ observation = await executeOp(world, d);
+ }
+ return observation;
+}
+
export async function buildHistoryFixture(engine: BrainEngine,
- { pages, seed, sources, worktrees, root: requestedRoot }: HistoryFixtureOptions): Promise<HistoryFixture> {
+ { pages, seed, sources, worktrees, root: requestedRoot, writeWaitMs }: HistoryFixtureOptions): Promise<HistoryFixture> {
assert(Number.isSafeInteger(pages) && pages >= 1 && pages <= 10_000, 'history fixture: pages must be 1..10000');
assert(Number.isSafeInteger(seed) && seed >= 0 && seed <= 0xFFFFFFFF, 'history fixture: seed must be an unsigned 32-bit integer');
assert(Number.isSafeInteger(worktrees) && worktrees >= 1, 'history fixture: worktrees must be >= 1');
@@ -219,12 +240,13 @@ export async function buildHistoryFixture(engine: BrainEngine,
const topology = await prepareTopology(engine, { sources, worktrees, root });
const { world, checkouts, sources: fixtureSources, accessTokenId, oauthClientId } = topology;
const remotes = world.remotes;
+ if (writeWaitMs !== undefined) world.writeWaitMs = writeWaitMs;
const plan = historyPlan({ pages, seed, sources, worktrees }, fixtureSources.map(s => s.id), remotes);
// Sources publish independently; ops within one source run in plan order.
const lanes = new Map<string, OpDescriptor[]>();
for (const d of plan) lanes.set(d.source, [...(lanes.get(d.source) ?? []), d]);
- await Promise.all([...lanes.values()].map(async lane => { for (const d of lane) await executeOp(world, d); }));
+ await Promise.all([...lanes.values()].map(async lane => { for (const d of lane) await executeCommitted(world, d); }));
const observations = plan.map(d => world.observations.get(d.id)!);
const failed = observations.filter(o => o.status !== 'committed');
assert.deepEqual(failed.map(o => `${o.id} ${o.kind} ${o.code}`), [], 'every history op must commit');
@@ -241,7 +263,7 @@ export async function buildHistoryFixture(engine: BrainEngine,
try {
const delayed = descriptor('delayed-effect', 'put_page', 'local', delayedSource.id,
{ slug: 'notes/delayed-effect', content: pageContent('note', 'Delayed effect', 'Its Git effect waits on a stale index.lock.') });
- assert.equal((await executeOp(world, delayed)).status, 'committed');
+ assert.equal((await executeCommitted(world, delayed)).status, 'committed');
observations.push(world.observations.get('delayed-effect')!);
const deadline = Date.now() + 60_000;
for (;;) {
diff --git a/scripts/persistence/ops.ts b/scripts/persistence/ops.ts
index 14e803836f..dc28f8e9cd 100644
--- a/scripts/persistence/ops.ts
+++ b/scripts/persistence/ops.ts
@@ -102,6 +102,8 @@ export interface World {
connector?: { sourceId: string; root: string };
/** Session drops this robot injects (the pooler_disconnect fault); absent in every other run. */
sessionDrops?: SessionDrops;
+ /** Write reply wait every op context carries; absent = the operation default (a probe shortens it to force `write_pending`). */
+ writeWaitMs?: number;
}
/**
@@ -251,7 +253,7 @@ async function revokeAccess(world: World, actor: string): Promise<void> {
export function contextFor(world: World, actor: string, sourceId: string): OperationContext {
const base = { engine: world.engine, config: world.config, dryRun: false, sourceId,
- logger: { info() {}, warn() {}, error() {} } };
+ logger: { info() {}, warn() {}, error() {} }, ...(world.writeWaitMs !== undefined ? { writeWaitMs: world.writeWaitMs } : {}) };
if (actor === 'local') return { ...base, remote: false };
const auth = world.auth.get(actor);
if (!auth) throw new Error(`op descriptor: actor ${actor} is not an authenticated remote`);
diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsv
index 1e792d463a..d715737e48 100644
--- a/scripts/serial-files.tsv
+++ b/scripts/serial-files.tsv
@@ -85,6 +85,7 @@ test/core/remediation-checkpoint.serial.test.ts R1 R1: mutates process.env (GBRA
test/corpus-retention-uningested.serial.test.ts R1 R1: mutates GBRAIN_HOME for in-process session-end hook runs and the doctor check
test/creds-vault.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
test/cross-modal-hybrid-integration.serial.test.ts global-state global-state: configureGateway changes the process-wide AI gateway
+test/cycle-embed-phase-warn.serial.test.ts global-state global-state: process-wide test seams __setEmbedTransportForTests; configureGateway changes the process-wide AI gateway; mock.module replaces the embed module
test/cycle-lock-release-diagnostic.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)
test/cycle-lock-steal.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME, GBRAIN_CYCLE_LOCK_REFRESH_MS)
test/cycle-patterns-completed-outcome.serial.test.ts R2 R2: mock.module(../src/core/ai/gateway.ts, ../src/core/cycle/synthesize.ts, ../src/core/minions/wait-for-completion.ts) replaces modules for every file in the process
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 596fa9458e..6208fb1b08 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -93,6 +93,7 @@ test/cycle-abort.test.ts CycleOpts.signal contract (v0.20.5) 3 readFileSync
test/cycle-abort.test.ts autopilot-cycle handler contract (v0.20.5) 3 readFileSync,source-surface-helper
test/cycle-drain-renewal.test.ts db-lock heartbeat wiring (structural — issue #6 cancellation) 1 readFileSync
test/cycle-drain-renewal.test.ts drain-loop wiring (structural — the shape guard only covers worker.ts) 2 readFileSync
+test/cycle-embed-phase-warn.serial.test.ts cycle embed phase reports embed failures (E-A) 4 source-surface-helper
test/cycle-legacy-phases.test.ts cycle.lint_exclude (#6134) 4 readFileSync
test/cycle-patterns-deadline-budget.test.ts deadline plumbing wiring (structural) 7 readFileSync,source-surface-helper
test/cycle-patterns.test.ts patterns private-queue keepalive wiring 1 readFileSync
diff --git a/scripts/ubicloud/run-script.ts b/scripts/ubicloud/run-script.ts
new file mode 100644
index 0000000000..26446588ac
--- /dev/null
+++ b/scripts/ubicloud/run-script.ts
@@ -0,0 +1,59 @@
+/**
+ * scripts/ubicloud/run-script.ts — how scripts/ci-ubicloud.ts runs one
+ * ubi-runner.sh subcommand.
+ *
+ * Two invariants the gate depends on:
+ * - With `out` and `stdoutOnly`, only stdout reaches the file. `pack` streams
+ * a tarball to stdout, so a git warning on stderr written to the same file
+ * corrupts the archive every VM unpacks; its stderr is returned instead.
+ * - A child that exits before reading all of `input` (a failed `ssh` during
+ * `unpack`) closes its stdin. The resulting EPIPE is that child's failure,
+ * reported by its exit code; it must never surface as an uncaught error that
+ * kills the orchestrator before it tears its VMs down.
+ */
+
+import { spawn, type ChildProcess } from "node:child_process";
+import { createReadStream, createWriteStream } from "node:fs";
+
+export interface RunScriptOpts {
+ /** Write output here instead of returning it (stdout and stderr, unless `stdoutOnly`). */
+ out?: string;
+ /** With `out`: send only stdout to the file and return stderr. */
+ stdoutOnly?: boolean;
+ /** File streamed to the child's stdin. */
+ input?: string;
+ timeoutMs?: number;
+ cwd?: string;
+ /** Called with the spawned child (the orchestrator tracks children for teardown). */
+ onSpawn?: (child: ChildProcess) => void;
+ onClose?: (child: ChildProcess) => void;
+}
+
+export function runScript(script: string, args: string[], opts: RunScriptOpts = {}): Promise<{ code: number; stdout: string }> {
+ return new Promise((resolvePromise) => {
+ const child = spawn("bash", [script, ...args], { cwd: opts.cwd, stdio: ["pipe", "pipe", "pipe"] });
+ opts.onSpawn?.(child);
+ let stdout = "";
+ let stderr = "";
+ const sink = opts.out ? createWriteStream(opts.out) : null;
+ child.stdout!.on("data", (chunk) => (sink ? sink.write(chunk) : (stdout += chunk)));
+ child.stderr!.on("data", (chunk) => (sink && !opts.stdoutOnly ? sink.write(chunk) : (stderr += chunk)));
+ child.stdin!.on("error", () => {});
+ if (opts.input) {
+ const source = createReadStream(opts.input);
+ source.on("error", () => child.stdin!.destroy());
+ source.pipe(child.stdin!);
+ } else {
+ child.stdin!.end();
+ }
+ const timer = opts.timeoutMs ? setTimeout(() => child.kill("SIGKILL"), opts.timeoutMs) : null;
+ child.on("close", (code) => {
+ if (timer) clearTimeout(timer);
+ opts.onClose?.(child);
+ const text = sink ? (opts.stdoutOnly ? stderr : "") : stdout + (code ? stderr : "");
+ const finish = () => resolvePromise({ code: code ?? 1, stdout: text });
+ if (sink) sink.end(finish);
+ else finish();
+ });
+ });
+}
diff --git a/scripts/ubicloud/ubi-runner.sh b/scripts/ubicloud/ubi-runner.sh
index fc054ad515..ebae7c13b7 100755
--- a/scripts/ubicloud/ubi-runner.sh
+++ b/scripts/ubicloud/ubi-runner.sh
@@ -369,7 +369,9 @@ slim_git() {
specs+=("+refs/remotes/origin/master:refs/remotes/origin/master")
fi
git init -q "$dir" &&
- git -C "$dir" fetch -q --update-shallow --no-tags --no-write-fetch-head "$src" "${specs[@]}" &&
+ # --update-head-ok: the fresh repo's unborn HEAD names init's default branch
+ # (master), which is also the branch a checkout on master fetches into.
+ git -C "$dir" fetch -q --update-head-ok --update-shallow --no-tags --no-write-fetch-head "$src" "${specs[@]}" &&
cp "$common/config" "$dir/.git/config" &&
{ [ ! -f "$git_dir/index" ] || cp "$git_dir/index" "$dir/.git/index"; } &&
if [ -n "$branch" ]; then git -C "$dir" symbolic-ref HEAD "$branch"; else git -C "$dir" update-ref --no-deref HEAD "$(git -C "$src" rev-parse HEAD)"; fi
diff --git a/skills/conventions/agent-operator-protocol.md b/skills/conventions/agent-operator-protocol.md
index da4f50ba27..f5a7ebabf3 100644
--- a/skills/conventions/agent-operator-protocol.md
+++ b/skills/conventions/agent-operator-protocol.md
@@ -363,7 +363,7 @@ stdout (`--json`):
"options": [
{
"id": "wire",
- "label": "Register `<absolute path to gbrain> serve --surface starter` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "label": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
{
"id": "skip",
diff --git a/skills/mcp-access/SKILL.md b/skills/mcp-access/SKILL.md
index b3c2d27114..a18af11b7b 100644
--- a/skills/mcp-access/SKILL.md
+++ b/skills/mcp-access/SKILL.md
@@ -114,6 +114,7 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- `insufficient_scope` / `invalid_token` on an MCP call: this is a grant problem only the owner can change. Do not try successively broader OAuth scopes; tell the user which scope is missing.
- A failed transport after a mutation was sent means the outcome is unknown: re-read the client list before retrying, never re-send blind.
- A list call fails: a failed list is not an empty list; report the error.
+- A tool the grant should reach is missing (`unknown_tool`, or a write such as `put_pages` absent): read `grant_diagnosis` from `whoami` or `gbrain://capabilities`. It names the blocker (scope, operation snapshot, client pin or server ceiling) and counts the operations it hides without naming them. Relay its `fix` (`next: tell_user_to_run`) to the brain owner; on the host, `gbrain doctor` check `grant_new_ops_available` shows the exact commands. New memory-profile grants are on the full surface; older ones keep their stored surface until the owner changes it. An "original intent unknown" grant may be restricted on purpose: never widen it unasked, and offer `--operations all` (no snapshot, including operations later upgrades add) only as the user's explicit choice.
## Anti-Patterns
diff --git a/skills/plugin-lanes.json b/skills/plugin-lanes.json
index 0e582bfe74..25972eb8c9 100644
--- a/skills/plugin-lanes.json
+++ b/skills/plugin-lanes.json
@@ -1,6 +1,6 @@
{
"_comment": "Curation record for the Codex + Claude Code plugin lanes (the committed plugin/ tree). Lane set = (openclaw.plugin.json#skills minus base_exclusions) plus additions. Every entry is a recorded publication decision with a reason — scripts/generate-plugin-tree.ts validates this file and test/codex-plugin-manifest.test.ts pins membership. The openclaw lane's own curation (openclaw.plugin.json + skills/plugin-exclusions.json) is untouched: a skill can be openclaw-excluded and plugin-lane-included because plugin users ARE the brain host (the downstream-vs-host inversion). starter_gaps is a generated snapshot (refresh: bun run scripts/generate-plugin-tree.ts --out plugin --write-gaps): per-skill gbrain MCP ops declared in frontmatter tools: that sit beyond the starter serve surface — every one has a first-class gbrain CLI path (see plugin/README.md), and a change here is a review-visible curation event, not silent drift.",
- "starter_policy": "cli-primary: bundled skills drive gbrain through the CLI when an op is beyond the starter MCP surface; users can widen a machine with GBRAIN_SURFACE=full (launcher-honored).",
+ "starter_policy": "cli-primary: bundled skills drive gbrain through the CLI when an op is beyond the plugin MCP surface (REGISTRATION_SURFACE, full since S0); a machine narrowed with GBRAIN_SURFACE=starter|verbs (launcher-honored) keeps those CLI paths.",
"additions": {
"setup": "the plugin lane's own onboarding path (install + gbrain init + first import); swept 2026-08-15 — install command, privacy names, daemon-only prose, and repo-relative doc refs fixed for plugin consumers",
"gbrain-upgrade": "binary upgrade path — plugin users own the gbrain install; swept clean (one daemon-convention mention generalized)",
@@ -76,105 +76,5 @@
}
}
},
- "starter_gaps": {
- "brain-ops": [
- "add_link",
- "sync_brain"
- ],
- "briefing": [
- "get_timeline"
- ],
- "cold-start": [
- "add_link",
- "sync_brain"
- ],
- "daily-task-prep": [
- "get_timeline"
- ],
- "data-research": [
- "add_link",
- "file_upload",
- "put_raw_data"
- ],
- "eiirp": [
- "add_link"
- ],
- "enrich": [
- "add_link"
- ],
- "gbrain-advisor": [
- "advisor"
- ],
- "google-loops": [
- "loops_close",
- "loops_mute",
- "open_loops"
- ],
- "idea-ingest": [
- "add_link",
- "file_upload"
- ],
- "idea-lineage": [
- "find_contradictions",
- "find_trajectory",
- "takes_search"
- ],
- "ingest": [
- "add_link",
- "sync_brain"
- ],
- "maintain": [
- "add_link",
- "get_health"
- ],
- "media-ingest": [
- "add_link",
- "file_upload"
- ],
- "meeting-ingestion": [
- "add_link",
- "chronicle_day",
- "get_timeline"
- ],
- "migrate": [
- "add_link",
- "add_tag",
- "sync_brain"
- ],
- "minion-orchestrator": [
- "get_job",
- "get_job_progress",
- "list_jobs",
- "pause_job",
- "replay_job",
- "resume_job",
- "send_job_message",
- "submit_job"
- ],
- "query": [
- "get_timeline"
- ],
- "schema-author": [
- "get_active_schema_pack",
- "list_schema_packs",
- "reload_schema_pack",
- "schema_apply_mutations",
- "schema_explain_type",
- "schema_graph",
- "schema_lint",
- "schema_review_orphans",
- "schema_stats"
- ],
- "schema-unify": [
- "run_onboard"
- ],
- "setup": [
- "get_health",
- "get_stats",
- "sync_brain"
- ],
- "signal-detector": [
- "add_link"
- ]
- }
+ "starter_gaps": {}
}
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 111aa80d80..453b70c2a0 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -44,7 +44,7 @@
"concept-synthesis/routing-eval.jsonl": "96dbd7d9c1b606e9e06262d0c06282399741e2bccb8eeb7b9ca88c20f44cda0e",
"context-audit/SKILL.md": "6d786629d40544ddaab4f4e6e333569d270bcb8b581589dc16fb9f8bcb4f6207",
"context-audit/routing-eval.jsonl": "fb1832e24cc1b04163a74c5cde72bca53050a66246ca902e1a5f40303f52b5ab",
- "conventions/agent-operator-protocol.md": "57b71aac90727684d3f66ed9d252c2fe357f6bb469549e3eb4480b0bf31cdd45",
+ "conventions/agent-operator-protocol.md": "e54e9d63da45c852b2897303a97e37a5e67ecba749c45311703059e51524331a",
"conventions/brain-first.md": "d9b18321150830d38586f5bd23ce9de735f08ac3b54d7ac63bc3184a61e17ef1",
"conventions/brain-routing.md": "392998d9a109b330c9225af4ca5c8798b0ff02eba4d441c93fdb7c263687d0c6",
"conventions/calibration.md": "500dc26bd7c8400f50dc4c16fd83f1a588f3e7e68c59050a21fd8a0f69e4d198",
@@ -96,7 +96,7 @@
"ingest/SKILL.md": "1acc220ce6e9e65876fa2ccede6ce11f9c75457feb6695ef904955f8debecaae",
"maintain/SKILL.md": "619762cf3bc4553d1d73dbcf7fa9629dd335ed61012057df2587f15cf9672fde",
"manifest.json": "357aa185d380f0a357cb15cd513317e290cbc5fcf5ca4e3860b0e829fdcbf1e4",
- "mcp-access/SKILL.md": "77f67fb2c07e891e945a5466ae075a3f9d488ef31e86150a99ed5341a782f73f",
+ "mcp-access/SKILL.md": "c2ff223b4461ba5817c6c0e7b50a1006866204b6c1d4bd905e52809350ecd092",
"measure-before-you-fix/SKILL.md": "11906da29a1a31976b13d4796b686d9a9981825737846a85f32d88bf431b9b36",
"measure-before-you-fix/routing-eval.jsonl": "0661df9974a9cfe31216d574b1db0ef341945c2eb844ebf4ab6920fcbbc90d6c",
"media-ingest/SKILL.md": "d70374d3df21397380203f541ebdcc90c0bc6bc7207234349594a081e98f2719",
@@ -189,7 +189,7 @@
"perplexity-research/SKILL.md": "1d6cf9f752b4a1618a04789a2f24a7f18d6feaa4ada578515842860bd5869997",
"perplexity-research/routing-eval.jsonl": "f1a40d87e710d5d2acd602a372d83f46c95da022b6e635228fffeaacb3bb2b27",
"plugin-exclusions.json": "797782fd0647e06763febcbe6b8cb6715c717504628af84185cc345804087d35",
- "plugin-lanes.json": "ec7fc44821c6a9b40c582db9b39026c84677d3fdd94657d983b7c5ea6216124e",
+ "plugin-lanes.json": "52dc5ac59547d4d9993da3d74796bd3e27a3b09752f97ec25451d2fd8a3f71f7",
"postgres-adopt/SKILL.md": "8cf801e2e0d29da525a8c4ba275b91e6caffc8aae8e648cbcc8bceaab865c890",
"postgres-adopt/routing-eval.jsonl": "db91c1fae408a45082979c402c11eff413277ace6cf746297cc86009dcaefe06",
"publish/SKILL.md": "271bd9ba87279429cd934509071dd032b859d59264038c38829c9af46f15c13b",
diff --git a/src/commands/agent-register.ts b/src/commands/agent-register.ts
index 51185b3fe0..dd982f590e 100644
--- a/src/commands/agent-register.ts
+++ b/src/commands/agent-register.ts
@@ -293,8 +293,8 @@ export function resolvePreset(flags: AgentRegisterArgs): ResolvedPreset {
scopes: explicit(flags.scopes, 'read write'),
writeSource: explicit(flags.source, 'default'),
federatedRead: flags.federatedRead ?? 'snapshot',
- // starter is literally "the ~20-op daily-driver set" (mcp/surface.ts).
- surface: explicit(flags.surface, 'starter'),
+ // S0/D4: no narrowing on any install path; pass --surface starter for a capped harness.
+ surface: explicit(flags.surface, 'full'),
workspaceDerived: false,
};
case 'coding-agent': {
@@ -318,10 +318,10 @@ export function resolvePreset(flags: AgentRegisterArgs): ResolvedPreset {
scopes: explicit(flags.scopes, 'read write'),
writeSource,
federatedRead: [writeSource, ...flags.federatedRead.filter(s => s !== writeSource)],
- // starter, not full: `full` exposes brain-wide unscoped code-intel
- // reads to a scoped client. Widen per client via
- // `gbrain auth rescope-client --surface full`.
- surface: explicit(flags.surface, 'starter'),
+ // S0/D4: full like every other install path. Code-intel reads are
+ // source-scoped for remote callers (readPolicyOpts / routeCodeIntelScope),
+ // so full no longer reaches past the client's grant.
+ surface: explicit(flags.surface, 'full'),
workspaceDerived,
};
}
@@ -948,10 +948,10 @@ PRESETS
SNAPSHOT of all current non-archived sources EXCLUDING other
agents' *-workspace sources (agent scratch — share one via an
explicit --federated-read). New sources need a re-grant via
- \`gbrain auth rescope-client\`. Surface: starter.
+ \`gbrain auth rescope-client\`. Surface: full.
coding-agent write-isolated: writes land in <name>${WORKSPACE_SUFFIX} (auto-created,
DB-only). Requires --federated-read (the project sources it may
- read). Surface: starter.
+ read). Surface: full.
NOTES
Runs on the BRAIN HOST (a thin client is refused). Every block embeds the
diff --git a/src/commands/bootstrap.ts b/src/commands/bootstrap.ts
index 491359a64c..01e09a82fc 100644
--- a/src/commands/bootstrap.ts
+++ b/src/commands/bootstrap.ts
@@ -204,7 +204,7 @@ const SUBCOMMAND_HELP: Record<string, string> = {
hooks:
'gbrain bootstrap hooks [--harness claude-code|codex|opencode] [--repair] [--no-hooks] [--gbrain-bin <path>]\n' +
' [--seat <label> | --no-seat] [--surface verbs|starter|full]\n' +
- ' Register MCP (--surface starter unless given; a replaced entry keeps its surface) (+ per-turn hooks on Claude Code, ON by default; --no-hooks opts out).\n' +
+ ' Register MCP (--surface full unless given; a replaced entry keeps its surface) (+ per-turn hooks on Claude Code, ON by default; --no-hooks opts out).\n' +
' --seat credits captured sessions to this agent seat (kept on re-install; --no-seat clears it; --seat off records none).',
verify:
'gbrain bootstrap verify [--json]\n' +
diff --git a/src/commands/doctor/checks/grant-new-ops.ts b/src/commands/doctor/checks/grant-new-ops.ts
new file mode 100644
index 0000000000..25f5ee07e5
--- /dev/null
+++ b/src/commands/doctor/checks/grant-new-ops.ts
@@ -0,0 +1,156 @@
+/**
+ * D4 `grant_new_ops_available` (warn when non-zero): active OAuth clients and
+ * legacy tokens that cannot call operations their scopes allow.
+ *
+ * Proven blockers come from the stored grant: the operation snapshot, the
+ * client's own stored surface (pin) and the configured server surface. They
+ * are reported apart from inferred grant age: a snapshot that excludes
+ * eligible operations proves exclusion, not age, so a grant without catalog
+ * provenance says "original intent unknown", and only a snapshot written with
+ * provenance can be said to predate operations. Identically shaped grants get
+ * identical output, and nothing widens automatically: the fix asks the user
+ * and carries the rescope commands, which differ by credential type. The
+ * no-snapshot `--operations all` choice is disclosed, never the default.
+ *
+ * Host-side only (not in the remote doctor): details name the operations.
+ */
+import type { Action } from '../../../core/agent-output.ts';
+import type { BrainEngine } from '../../../core/engine.ts';
+import { loadConfig, type GBrainConfig } from '../../../core/config.ts';
+import { grantFromRow, grantFromTokenRow } from '../../../core/grants/model.ts';
+import { readClientCatalogProvenance } from '../../../core/grants/service.ts';
+import { ALL_OPERATIONS_CHOICE, grantAge, grantBlockers, grantOperationGaps, grantRescopeArgvs, type GrantGaps, type RescopeTarget } from '../../../core/harness/capabilities.ts';
+import { clampSurface, isMcpSurface, minSurface, resolveDefaultClientSurface, resolveSurface, surfaceWiderThan, type McpSurface } from '../../../mcp/surface.ts';
+import { disabledOpsForPublishGates } from '../../../mcp/publish-gates.ts';
+import type { Check } from '../../doctor.ts';
+import { checkError, doctorVerify } from '../check-fix.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+
+const DOCS = 'docs/mcp/ADMIN.md#grants-that-cannot-reach-new-operations';
+const BULK_WRITE = 'put_pages';
+
+interface GrantFinding {
+ kind: 'oauth_client' | 'legacy_token';
+ id: string;
+ name: string;
+ profile: string | null;
+ blockers: Array<Record<string, unknown>>;
+ excluded_operations: { operation_snapshot: string[]; client_pin: string[]; server_ceiling: string[] };
+ grant_age: ReturnType<typeof grantAge>;
+ preview_argv: string[];
+ argv: string[];
+ all_operations_argv: string[];
+}
+
+function finding(kind: GrantFinding['kind'], id: string, name: string, profile: string | null, gaps: GrantGaps, target: RescopeTarget,
+ snapshot: readonly string[] | null, age: ReturnType<typeof grantAge>, surfaces: { client: McpSurface | null; clientSetBy: string | null; server: McpSurface | null }): GrantFinding {
+ const bulk = gaps.snapshotExcluded.includes(BULK_WRITE);
+ const operations = !bulk ? null : kind === 'legacy_token' ? BULK_WRITE : [...new Set([...(snapshot ?? []), BULK_WRITE])].sort().join(',');
+ const argvs = grantRescopeArgvs(target, gaps, operations);
+ const blockers = grantBlockers(gaps, { clientSurface: surfaces.client, clientSurfaceSetBy: surfaces.clientSetBy, serverSurface: surfaces.server });
+ return {
+ kind, id, name, profile, blockers,
+ excluded_operations: { operation_snapshot: gaps.snapshotExcluded, client_pin: gaps.pinExcluded, server_ceiling: gaps.serverExcluded },
+ grant_age: age, preview_argv: argvs.preview, argv: argvs.apply, all_operations_argv: argvs.all_operations,
+ };
+}
+
+/** A command for prose: a spelled-out operation list is summarized; details carry the exact argv. */
+function shownCommand(argv: string[]): string {
+ return argv.map(arg => arg.length > 80 ? `<${arg.split(',').length} operations: see details.grants>` : arg).join(' ');
+}
+
+function describeFinding(f: GrantFinding): string {
+ const label = f.kind === 'oauth_client' ? `client ${f.name} (${f.id})` : `token ${f.name}`;
+ const parts = f.blockers.filter(b => b.blocker !== 'scope').map(b => b.blocker === 'operation_snapshot' ? `its operation snapshot excludes ${b.excluded_count}`
+ : b.blocker === 'client_pin' ? `its stored ${b.surface} surface excludes ${b.excluded_count}`
+ : `the configured ${b.surface} server surface excludes ${b.excluded_count}`);
+ const age = 'statement' in f.grant_age ? ` ${f.grant_age.statement}` : '';
+ return `${label}: ${parts.join(', ')}.${age} Preview: ${shownCommand(f.preview_argv)}`;
+}
+
+export async function checkGrantNewOps(engine: BrainEngine, opts: { cfg?: GBrainConfig | null } = {}): Promise<Check> {
+ try {
+ let cfg = opts.cfg;
+ if (cfg === undefined) { try { cfg = loadConfig(); } catch { cfg = null; } }
+ const disabled = await disabledOpsForPublishGates(engine, cfg);
+ const ceiling = clampSurface(resolveSurface(null, cfg), () => {});
+ const dcrDefault = await resolveDefaultClientSurface(engine, cfg);
+ const findings: GrantFinding[] = [];
+
+ const clients = await engine.executeRaw<Record<string, unknown>>('SELECT * FROM oauth_clients WHERE deleted_at IS NULL ORDER BY client_id');
+ for (const row of clients) {
+ const grant = grantFromRow(row);
+ const client = isMcpSurface(grant.surface) ? grant.surface : null;
+ const server = client ? ceiling : minSurface(ceiling, dcrDefault ?? ceiling);
+ const gaps = await grantOperationGaps({
+ scopes: grant.scopes, allowedOperations: grant.allowedOperations, boundSlugPrefixes: grant.boundSlugPrefixes ?? undefined,
+ clientSurface: client, serverSurface: server, disabled,
+ });
+ if (!gaps.snapshotExcluded.length && !gaps.pinExcluded.length) continue;
+ const provenance = gaps.snapshotExcluded.length && grant.allowedOperations
+ ? await readClientCatalogProvenance(engine, grant.clientId, grant.allowedOperations) : null;
+ findings.push(finding('oauth_client', grant.clientId, grant.clientName, grant.profile, gaps, { kind: 'oauth_client', id: grant.clientId },
+ grant.allowedOperations, grantAge(gaps.snapshotExcluded, grant.allowedOperations !== null, provenance),
+ { client, clientSetBy: grant.surfaceSetBy, server }));
+ }
+
+ const tokens = await engine.executeRaw<Record<string, unknown>>('SELECT * FROM access_tokens WHERE revoked_at IS NULL ORDER BY created_at, id');
+ const nameCounts = new Map<string, number>();
+ for (const row of tokens) nameCounts.set(String(row.name), (nameCounts.get(String(row.name)) ?? 0) + 1);
+ for (const row of tokens) {
+ const grant = grantFromTokenRow(row);
+ // A drifted or malformed operations axis denies everything; legacy_token_grant_drift owns that report.
+ if (grant.permissionsMalformed || grant.drift.includes('operations') || grant.allowedOperations === null) continue;
+ const gaps = await grantOperationGaps({ scopes: grant.scopes, allowedOperations: grant.allowedOperations, clientSurface: null,
+ serverSurface: ceiling, disabled });
+ if (!gaps.snapshotExcluded.length) continue;
+ const name = String(row.name);
+ const flag: ['--token' | '--id', string] = nameCounts.get(name) === 1 ? ['--token', name] : ['--id', grant.principal.id];
+ findings.push(finding('legacy_token', grant.principal.id, name, null, gaps, { kind: 'legacy_token', flag },
+ grant.allowedOperations, grantAge(gaps.snapshotExcluded, true, null), { client: null, clientSetBy: null, server: ceiling }));
+ }
+
+ const ceilingNote = surfaceWiderThan('full', ceiling)
+ ? ` The configured server surface is ${ceiling} (config mcp_surface or GBRAIN_MCP_FORCE_SURFACE); a rescope cannot lift it.` : '';
+ if (!findings.length) {
+ return { name: 'grant_new_ops_available', status: 'ok', message: `Every active client and token can call the operations its scopes allow.${ceilingNote}`,
+ details: { grants: [], server_surface: ceiling, docs: DOCS } };
+ }
+ const first = findings[0];
+ const placeholder = first.argv.includes('<OPERATIONS>');
+ const fix: Action = {
+ preview_argv: first.preview_argv, argv: first.argv, consent: ['credentials'], actor: 'agent', requires_exclusive: false, docs: DOCS,
+ verify: doctorVerify('grant_new_ops_available'),
+ why: 'An operation snapshot or a stored client surface keeps this grant from operations its scopes allow; changing it widens what that credential can do.',
+ user_message: `${findings.length} connection grant(s) cannot call operations their scopes allow (first: ${first.name}). `
+ + `For ${first.name}: preview the change with ${shownCommand(first.preview_argv)}, then apply it; or leave it as it is; `
+ + `or remove its snapshot with ${first.all_operations_argv.join(' ')} (${ALL_OPERATIONS_CHOICE}). Which do you want?`,
+ ...(placeholder ? { inputs: [{ name: 'OPERATIONS', how: `The operations the user approves for ${first.name}, comma-separated (clients: the whole new snapshot, i.e. the current one plus the approved additions; details.grants[0].excluded_operations lists the candidates).` }] } : {}),
+ };
+ return {
+ name: 'grant_new_ops_available', status: 'warn',
+ message: `${findings.length} active grant(s) cannot call operations their scopes allow. `
+ + findings.slice(0, 5).map(describeFinding).join('; ')
+ + `${findings.length > 5 ? `; and ${findings.length - 5} more in details.grants` : ''}. `
+ + `Ask the user before changing any grant; nothing widens automatically, and --operations all (${ALL_OPERATIONS_CHOICE}) is a separate choice, not the default repair.`
+ + `${ceilingNote} See ${DOCS}.`,
+ details: { grants: findings, server_surface: ceiling, all_operations_choice: ALL_OPERATIONS_CHOICE, docs: DOCS },
+ fix,
+ };
+ } catch (e) {
+ return checkError('grant_new_ops_available', 'read client and token grants', e);
+ }
+}
+
+async function runGrantNewOps(ctx: DoctorContext): Promise<Check[]> {
+ const checks: Check[] = [];
+ checks.push(await checkGrantNewOps(connectedEngine(ctx)));
+ return checks;
+}
+
+export const grantNewOpsEntry: DoctorEntry = {
+ name: 'grant_new_ops_available',
+ emits: ['grant_new_ops_available'],
+ run: runGrantNewOps,
+};
diff --git a/src/commands/doctor/checks/schema-health.ts b/src/commands/doctor/checks/schema-health.ts
index 2c856a8667..fc710cf1bc 100644
--- a/src/commands/doctor/checks/schema-health.ts
+++ b/src/commands/doctor/checks/schema-health.ts
@@ -22,8 +22,10 @@ import { checkPersistenceCapacity } from './persistence-capacity.ts';
import { checkPostgresCancellationDriver } from './postgres-cancellation.ts';
import { checkProjectionReadiness } from './projection-readiness.ts';
import type { Check } from '../../doctor.ts';
+import type { BrainEngine } from '../../../core/engine.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
import { embeddingsDisabled } from '../../../core/embedding-disabled.ts';
+import { quoteIdentifier, resolveActiveEmbeddingColumnFromEngine } from '../../../core/search/embedding-column.ts';
import { checkError, infoCheck, keylessEnablementFix } from '../check-fix.ts';
async function runPgvector(ctx: DoctorContext): Promise<Check[]> {
@@ -336,6 +338,49 @@ export const rlsEventTriggerEntry: DoctorEntry = {
run: runRlsEventTrigger,
};
+/**
+ * A backlog warns only when it is both large (over 1,000 chunks or 1% of
+ * embeddable chunks) and old: its oldest pending chunk has waited longer than
+ * this. A fresh brain draining its first embed, an edited page and a model
+ * swap re-embed all start their wait at the moment the vector went missing
+ * (`content_chunks.embedding_pending_since`), so they stay `ok` while they
+ * drain inside the window.
+ */
+export const EMBEDDING_BACKLOG_MAX_AGE_S = 24 * 60 * 60;
+const EMBEDDING_BACKLOG_MIN_CHUNKS = 1_000;
+const EMBEDDING_BACKLOG_MIN_SHARE = 0.01;
+
+interface BacklogAge { oldest_pending_age_s: number; backfilled: boolean }
+
+/**
+ * Age of the oldest chunk the health counters call missing (live, not
+ * embed_skip, registry-active vector NULL). Null when it cannot be read: the
+ * column is absent, or a pending chunk carries no pending-since stamp.
+ */
+async function readBacklogAge(engine: BrainEngine): Promise<BacklogAge | null> {
+ try {
+ const column = quoteIdentifier((await resolveActiveEmbeddingColumnFromEngine(engine, { fallbackToLegacy: true })).name);
+ const [row] = await engine.executeRaw<{ age_s: number | null; unaged: number; backfilled: boolean | null }>(
+ `SELECT EXTRACT(EPOCH FROM now() - min(cc.embedding_pending_since))::float8 AS age_s,
+ count(*) FILTER (WHERE cc.embedding_pending_since IS NULL)::int AS unaged,
+ min(cc.embedding_pending_since) <= (SELECT value::timestamptz FROM config
+ WHERE key = 'embedding_pending_since_backfilled_at') AS backfilled
+ FROM content_chunks cc JOIN pages p ON p.id = cc.page_id
+ WHERE cc.${column} IS NULL AND p.deleted_at IS NULL
+ AND NOT jsonb_exists(COALESCE(p.frontmatter, '{}'::jsonb), 'embed_skip')`);
+ if (!row || row.age_s === null || Number(row.unaged) > 0) return null;
+ return { oldest_pending_age_s: Math.max(0, Math.round(Number(row.age_s))), backfilled: row.backfilled === true };
+ } catch {
+ return null;
+ }
+}
+
+function formatWait(seconds: number): string {
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m`;
+ if (seconds < 172_800) return `${Math.floor(seconds / 3600)}h`;
+ return `${Math.floor(seconds / 86_400)}d`;
+}
+
async function runEmbeddings(ctx: DoctorContext): Promise<Check[]> {
const { progress } = ctx;
const engine = connectedEngine(ctx);
@@ -366,24 +411,39 @@ async function runEmbeddings(ctx: DoctorContext): Promise<Check[]> {
} catch {
// Config read is best-effort; the coverage numbers stand alone.
}
+ const backlog = health.missing_embeddings;
+ const age = backlog > 0 ? await readBacklogAge(engine) : null;
+ const ageDetails = {
+ backlog,
+ oldest_pending_age_s: age?.oldest_pending_age_s ?? null,
+ age_threshold_s: EMBEDDING_BACKLOG_MAX_AGE_S,
+ ...(age?.backfilled ? { age_source: 'created_at_backfill' } : {}),
+ };
+ if (backlog === 0) {
+ checks.push({ name: 'embeddings', status: 'ok', message: `${pct}% coverage, ${backlog} missing${carveOut}`, details: ageDetails });
+ return checks;
+ }
// The backlog's fix is the catch-up drain: a plain `embed --stale` stops
// at its 30-minute budget, which on a large brain leaves most of the
// backlog behind (52k documents: 51,910 chunks after one run).
- const backlog = health.missing_embeddings;
const fix = 'gbrain embed --stale --catch-up';
- const backlogDetails = { code: 'embedding_backlog', backlog, fix, requires_user_approval: 'paid embedding calls',
+ const details = { code: 'embedding_backlog', ...ageDetails, fix, requires_user_approval: 'paid embedding calls',
docs: 'docs/operations/backfill-pacing.md#large-brain-deadlines' };
const fixText = `Fix: ${fix} (runs until the backlog is empty; a plain gbrain embed --stale stops after its 30-minute budget). ` +
'It makes paid embedding calls: confirm with the user unless embedding spend is already approved.';
- if (health.embed_coverage >= 0.9) {
- checks.push(backlog > 0
- ? { name: 'embeddings', status: 'ok', message: `${pct}% coverage, ${backlog} missing${carveOut}. Backlog: ${backlog} chunk(s) without embeddings. ${fixText}`, details: backlogDetails, fix: embedBackfillFix({ backlog, verifyCheck: 'embeddings' }) }
- : { name: 'embeddings', status: 'ok', message: `${pct}% coverage, ${backlog} missing${carveOut}` });
- } else if (health.embed_coverage > 0) {
- checks.push({ name: 'embeddings', status: 'warn', message: `${pct}% coverage, ${backlog} missing${carveOut}. Backlog: ${backlog} chunk(s) without embeddings. ${fixText}`, details: backlogDetails, fix: embedBackfillFix({ backlog, verifyCheck: 'embeddings' }) });
- } else {
- checks.push({ name: 'embeddings', status: 'warn', message: `No embeddings yet${carveOut}. Backlog: ${backlog} chunk(s) without embeddings. ${fixText}`, details: backlogDetails, fix: embedBackfillFix({ backlog, verifyCheck: 'embeddings' }) });
- }
+ // Without a readable age (pre-migration schema, unstamped rows) the
+ // coverage rule decides: warn below 90%.
+ const stale = age
+ ? (backlog > EMBEDDING_BACKLOG_MIN_CHUNKS || 1 - health.embed_coverage > EMBEDDING_BACKLOG_MIN_SHARE)
+ && age.oldest_pending_age_s > EMBEDDING_BACKLOG_MAX_AGE_S
+ : health.embed_coverage < 0.9;
+ const waited = age
+ ? ` Oldest pending chunk has waited ${formatWait(age.oldest_pending_age_s)}${age.backfilled ? ' (backfilled from its creation time)' : ''}; a large backlog warns after ${formatWait(EMBEDDING_BACKLOG_MAX_AGE_S)}.`
+ : '';
+ const summary = health.embed_coverage > 0 ? `${pct}% coverage, ${backlog} missing` : 'No embeddings yet';
+ checks.push({ name: 'embeddings', status: stale ? 'warn' : 'ok',
+ message: `${summary}${carveOut}. Backlog: ${backlog} chunk(s) without embeddings.${waited} ${fixText}`,
+ details, fix: embedBackfillFix({ backlog, verifyCheck: 'embeddings' }) });
} catch {
checks.push(checkError('embeddings', 'check embedding health'));
}
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index 8219954d4e..744771893b 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -82,6 +82,7 @@ import { queueHealthEntry, indexAuditEntry, imageAssetsEntry } from './checks/qu
import { globalMaintenanceTimeoutsEntry } from './checks/global-maintenance-timeouts.ts';
import { legacyJobAuthorityEntry } from './checks/legacy-job-authority.ts';
import { legacyTokenGrantsEntry } from './checks/legacy-token-grants.ts';
+import { grantNewOpsEntry } from './checks/grant-new-ops.ts';
import { syncFreshnessEntry, searchModeEntry } from './checks/sync-search.ts';
import { gitConvergenceEntry } from './checks/git-convergence.ts';
import { retrievalFeedbackEntry } from './checks/retrieval-feedback.ts';
@@ -160,6 +161,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
globalMaintenanceTimeoutsEntry,
legacyJobAuthorityEntry,
legacyTokenGrantsEntry,
+ grantNewOpsEntry,
indexAuditEntry,
imageAssetsEntry,
syncFreshnessEntry,
diff --git a/src/commands/eval-longmemeval.ts b/src/commands/eval-longmemeval.ts
index 7404abb78c..80ab0a6bdd 100644
--- a/src/commands/eval-longmemeval.ts
+++ b/src/commands/eval-longmemeval.ts
@@ -1471,7 +1471,7 @@ async function runOneQuestion(
reader_prompt_sha: ctx.readerConfig.promptSha,
reader_max_tokens: ctx.readerConfig.maxTokens,
reader_config_hash: ctx.readerHash,
- reader_finish_reason: answer.finish_reason,
+ reader_finish_reason: answer.finish_reason, reader_usage: answer.usage,
...(readerError ? { error: readerError } : {}),
...(readerError && answer.text ? { reader_partial_output: answer.text } : {}),
reader_context_chars: answer.context_chars,
diff --git a/src/commands/init-first-run.ts b/src/commands/init-first-run.ts
index 01186485c3..cfcb66166f 100644
--- a/src/commands/init-first-run.ts
+++ b/src/commands/init-first-run.ts
@@ -142,7 +142,7 @@ export function firstRunJson(bundle: Notice[]): { notices?: unknown[]; contract_
/**
* The harness registration line for init's quickstart: the readiness
- * `harness_wiring` fix (absolute binary, `--surface starter` unless
+ * `harness_wiring` fix (absolute binary, `--surface full` unless
* `gbrain init --surface` names another) for the detected harness, else the
* Claude Code registration built the same way. Null when the gbrain binary
* has no absolute path (never registered bare).
diff --git a/src/commands/init.ts b/src/commands/init.ts
index 5f6ce82798..35ce79ea73 100644
--- a/src/commands/init.ts
+++ b/src/commands/init.ts
@@ -1314,7 +1314,7 @@ const INIT_EMBEDDING_HINT = 'Pick an embedding model whose dimensions match (`gb
* MEMORY_VERBS v1 quickstart funnel (E3 + D4B + T1 consent). Printed LAST in
* both init epilogues as the ONE primary action. The copy-next block is
* three commands (codex DX 9): wire the harness (the readiness
- * `harness_wiring` fix: absolute binary, `--surface starter` or init's `--surface`), save an
+ * `harness_wiring` fix: absolute binary, `--surface full` or init's `--surface`), save an
* install-check marker (never a made-up fact about the user), and recall it.
* The demo uses the facts arm only, so it works with NO embedding key [F-B]. Secondary paths (import, migrate) ride a single terse
* "More:" footer so they never compete with the primary action.
@@ -1855,7 +1855,7 @@ OPTIONS
--chat-model <PROVIDER:MODEL>
Default subagent driver (v0.27+)
--no-embedding Defer embedding setup (skips the embedding-key check)
- --surface <verbs|starter|full> Tool surface the printed harness registration pins (default starter)
+ --surface <verbs|starter|full> Tool surface the printed harness registration pins (default full)
--skip-embed-check Skip the init-time embedding-key validation (config +
live test-embed). Also via GBRAIN_INIT_SKIP_EMBED_CHECK=1
diff --git a/src/core/ai/chat-usage.ts b/src/core/ai/chat-usage.ts
index 1579210f82..62d25298bc 100644
--- a/src/core/ai/chat-usage.ts
+++ b/src/core/ai/chat-usage.ts
@@ -142,7 +142,11 @@ export function estimateChatCostUsd(
/**
* Called by gateway.chat() at its success boundary. Never throws; the sink
- * runs fire-and-forget with errors swallowed.
+ * runs fire-and-forget with errors swallowed. `usage` is the gateway's
+ * `ChatResult.usage` (AI SDK convention): `input_tokens` is the TOTAL input,
+ * and the cache read/write counts are subsets of it, so the call is priced as
+ * (input - cache) at the input rate plus each cache bucket at its own rate,
+ * never the cache tokens a second time on top of the total.
*/
export function recordChatUsage(input: {
model: string;
@@ -160,13 +164,14 @@ export function recordChatUsage(input: {
const pricedMeter = meter && meter.cost_usd !== undefined ? meter : null;
if (!sink && !pricedMeter) return;
try {
- const cost_usd = estimateChatCostUsd(input.model, input.usage);
+ const { input_tokens, output_tokens, cache_read_tokens = 0, cache_write_tokens = 0 } = input.usage;
+ const uncached = Math.max(0, input_tokens - cache_read_tokens - cache_write_tokens);
+ const cost_usd = estimateChatCostUsd(input.model, { ...input.usage, input_tokens: uncached });
if (pricedMeter) {
const price = priceFor(input.model, 'chat', pricedMeter.pricing_overrides);
- const { input_tokens, output_tokens, cache_read_tokens = 0, cache_write_tokens = 0 } = input.usage;
const meterCost = price === null ? null
: price.source === 'table' && cost_usd !== null ? cost_usd
- : ((input_tokens + cache_read_tokens + cache_write_tokens) * price.pricing.input + output_tokens * price.pricing.output) / 1_000_000;
+ : (input_tokens * price.pricing.input + output_tokens * price.pricing.output) / 1_000_000;
if (meterCost === null) pricedMeter.unpriced_calls = (pricedMeter.unpriced_calls ?? 0) + 1;
else pricedMeter.cost_usd = (pricedMeter.cost_usd ?? 0) + meterCost;
}
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index 9ec3a8cee9..42a99ed115 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -2993,6 +2993,8 @@ export interface ChatResult {
output_tokens: number;
cache_read_tokens: number;
cache_creation_tokens: number;
+ /** A1: the reasoning subset of output_tokens, when the provider reported one. */
+ reasoning_tokens?: number;
};
/** "provider:modelId" string of the model that actually answered. */
model: string;
@@ -3723,6 +3725,7 @@ async function chatAdmitted(opts: ChatOpts, admitted: {
const { inputTokens: inTok, outputTokens: outTok } = normalizeSdkUsage(usage);
_recordBudget({ inputTokens: inTok, outputTokens: outTok });
+ const reasoningTokens = usage.outputTokenDetails?.reasoningTokens ?? usage.reasoningTokens;
const usageOut = {
input_tokens: inTok,
output_tokens: outTok,
@@ -3731,6 +3734,7 @@ async function chatAdmitted(opts: ChatOpts, admitted: {
// prompt_tokens_details.cached_tokens) surface cache hits.
cache_read_tokens: Number(anthropicCache.cacheReadInputTokens ?? anthropicCache.cache_read_input_tokens ?? usage.cachedInputTokens ?? 0),
cache_creation_tokens: Number(anthropicCache.cacheCreationInputTokens ?? anthropicCache.cache_creation_input_tokens ?? 0),
+ ...(typeof reasoningTokens === 'number' && Number.isFinite(reasoningTokens) ? { reasoning_tokens: reasoningTokens } : {}),
};
// #4218 success boundary: durable usage ledger (fire-and-forget, fail-open).
recordChatUsage({
diff --git a/src/core/ai/providers/claude-cli-language-model.ts b/src/core/ai/providers/claude-cli-language-model.ts
index 6d17dd74f1..d3ac7e2f69 100644
--- a/src/core/ai/providers/claude-cli-language-model.ts
+++ b/src/core/ai/providers/claude-cli-language-model.ts
@@ -681,17 +681,18 @@ export class ClaudeCliLanguageModel implements LanguageModelV2 {
}
const finishReason = claudeCliFinishReason(result.stop_reason, toolCalls.length > 0);
- const inputTokens = result.usage?.input_tokens;
- const outputTokens = result.usage?.output_tokens;
- const totalTokens = (inputTokens ?? 0) + (outputTokens ?? 0);
- // `cache_creation_input_tokens` is deliberately NOT surfaced here — the AI
- // SDK's LanguageModelV2Usage has no corresponding field, and folding it in
- // would need a claude-cli-specific branch in the gateway's usage assembly
- // (src/core/ai/gateway.ts). Out of scope for this fix.
+ // The CLI reports Anthropic's separate buckets; LanguageModelV2Usage wants
+ // the TOTAL input with the cache read as a subset (what every SDK provider
+ // reports), so the gateway prices cache tokens once. Cache creation has no
+ // V2 field: it stays inside the total at the input rate.
const cachedInputTokens =
result.usage?.cache_read_input_tokens !== undefined
? Number(result.usage.cache_read_input_tokens)
: undefined;
+ const inputTokens = result.usage?.input_tokens === undefined ? undefined
+ : result.usage.input_tokens + (cachedInputTokens ?? 0) + Number(result.usage.cache_creation_input_tokens ?? 0);
+ const outputTokens = result.usage?.output_tokens;
+ const totalTokens = (inputTokens ?? 0) + (outputTokens ?? 0);
return {
content,
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 96940f1315..eb2cf90237 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -323,6 +323,10 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.112.0', text: 'New keys `persistence.sync_preparation_ms` (120000), `persistence.maintenance_preparation_ms` (120000), `persistence.preparation_ceiling_ms` (600000) and `persistence.max_preparation_attempts` (2) bound write preparation, and `gbrain config set` refuses a value out of range; the `preparation_deadlines` write switch (`gbrain config set persistence.preparation_deadlines false`) restores the old behavior exactly (only `remember`, `put_page` and `edit_page` keep a 30 s budget; nothing is counted or held). `persistence.max_claim_ms` keeps its doctor meaning. Migration v220 adds `persistence_requests.preparation_attempts`; restart every `gbrain serve`, jobs worker and autopilot on the new version, because an older owner never gives up a stuck preparation.' },
{ since: '0.60.112.0', text: 'Fact-fence adoption (the extract_facts cycle phase and the v0.32.2 backfill) now writes the fence\'s parsed text back into `facts.fact`: a legacy claim with surrounding whitespace or CRLF line endings is adopted with that whitespace trimmed and its line endings folded to LF (the row keeps its id, vectors and provenance). A claim the fence codec would change further (whitespace-only, `~~x~~`, a literal `<br>`) or one its page already carries stays a legacy row, active and searchable, and is reported as `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: …)` and under doctor `fence_integrity` `unrenderable_legacy_facts`. Only the pages still holding such rows skip destructive fact reconciliation (the whole source skipped before), and the cycle summary names them while keeping the reconcile counts of the other pages.' },
{ since: '0.60.112.0', text: 'A managed maintenance write on a page whose body or timeline already carries a fence defect no adoption clears (for example a second facts fence in the timeline) is now refused at submission with its fence reason, so the cycle skips that page in `failed_pages` instead of failing a request on every pass; doctor `fence_integrity` counts the stored defect as a repair candidate.' },
+ // Wave 0 (GBRA-60): `since` is provisional (master's VERSION); restamp at the merge slot.
+ { since: '0.60.112.0', text: 'New stdio registrations gbrain writes (`gbrain bootstrap hooks`, the readiness and `gbrain init` registration lines) and the Codex and Claude Code plugins, and the `gbrain agent register` daily-driver and coding-agent presets, now use `--surface full`, every operation including `put_pages`, instead of `starter`; an existing registration or client keeps its surface. A harness that caps its tool count can register `--surface starter` or set `GBRAIN_SURFACE=starter` in the server entry\'s env.' },
+ { since: '0.60.112.0', text: 'New memory-reader, memory-writer and coding-agent grants (`gbrain mcp grant`, the admin dashboard, `auth rescope --profile`) are callable and listed on the full MCP surface instead of starter; their operation snapshot is still the ceiling, so a reader still cannot write. Existing clients keep their stored surface until the owner re-applies a profile. `whoami` and `gbrain://capabilities` now report `grant_diagnosis`, and `gbrain doctor` adds `grant_new_ops_available`, which lists grants whose snapshot or stored surface keeps operations their scopes allow out of reach, with the rescope commands.' },
+ { since: '0.60.112.0', text: 'Doctor `embeddings` now warns on an embedding backlog only when it is large (over 1,000 chunks or 1% of chunks) and its oldest pending chunk has waited more than 24 hours, read from the new `content_chunks.embedding_pending_since` column; a backlog draining inside that window reads `ok` even below 90% coverage, an old one warns even above 90%, and `details` always carries `backlog`, `oldest_pending_age_s` and `age_threshold_s`. Check with `gbrain doctor --only embeddings --json`.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/bootstrap/hooks.ts b/src/core/bootstrap/hooks.ts
index a1b7831c87..c8dd2839ba 100644
--- a/src/core/bootstrap/hooks.ts
+++ b/src/core/bootstrap/hooks.ts
@@ -1089,9 +1089,9 @@ export type CodexMcpRegistration = Omit<ClaudeMcpRegistration, 'scope'>;
* (binary first) — the dispatcher execs them; nothing here touches the
* filesystem or the network. Shape per TARGETS['claude-code-2026-08'].
*
- * The serve argv comes from `stdioServeArgv`: `--surface starter` by default
- * (bootstrap's contract — put_page, get_page, add_timeline_entry, search,
- * query — is in it, and a pre-existing `mcp_surface: verbs` config row cannot
+ * The serve argv comes from `stdioServeArgv`: `--surface full` by default
+ * (REGISTRATION_SURFACE; bootstrap's contract — put_page, get_page,
+ * add_timeline_entry, search, query — is in it, and a pre-existing `mcp_surface: verbs` config row cannot
* narrow a pinned registration); `surface` carries an existing entry's form
* over on replacement or applies `--surface`.
*/
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index bfd7d368ed..3422eb9319 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -47,7 +47,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--json', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--access', '--add', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-confirm', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all-applied', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@ -72,7 +72,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],
'import': ['--accept-pending', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],
- 'init': ['--access', '--allow-create-db', '--allow-docker', '--apply', '--auto', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--content-root', '--db-only', '--dest', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--facts', '--fix', '--force', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--provenance', '--query', '--quiet', '--reference-date', '--remediate', '--remove', '--reset', '--save', '--schema-pack', '--scope', '--scopes', '--section', '--show-toplevel', '--skip-embed-check', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--workspace', '--yes'],
+ 'init': ['--access', '--allow-create-db', '--allow-docker', '--apply', '--auto', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--content-root', '--db-only', '--dest', '--dim', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--facts', '--fix', '--force', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--query', '--quiet', '--reference-date', '--remediate', '--remove', '--reset', '--save', '--schema-pack', '--scope', '--scopes', '--section', '--show-toplevel', '--skip-embed-check', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],
'jobs': ['--abbrev-ref', '--access', '--add', '--admin-intent', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-quiesced', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index d27cbcd801..a4d4012d22 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -56,7 +56,7 @@ import { managedPullWarning, type UpstreamRefresh } from './sync-upstream.ts';
import { assertValidSourceId } from './source-id.ts';
import { PHASE_SCOPE, SOURCE_FRESHNESS_PHASES, type PhaseScope } from './cycle/phase-scope.ts';
import { acquireLeaseSet, maintenanceLockBusySkip, MAINTENANCE_LEASE_ID } from './cycle/lock-set.ts';
-import { assertEmbedNotStalled } from './embed-stall.ts';
+import { assertEmbedNotStalled } from './embed-stall.ts'; import { embedBackfillFix } from './embed-consent.ts';
import { anyAbortSignal } from './abort-signals.ts';
import { maybeRefreshPlannerStats } from './planner-stats.ts';
@@ -1626,13 +1626,11 @@ async function runPhaseEmbed(engine: BrainEngine, dryRun: boolean, signal?: Abor
const result = await runEmbedCore(engine, { stale: true, dryRun, signal, quiet: true });
assertEmbedNotStalled(result); // #4599: a watchdog-aborted drain is a failed phase, not 'ok'
const embeddedCount = dryRun ? result.would_embed : result.embedded;
+ const failed = result.failures > 0 && !result.lock_skipped; // E-A: blocked pages are a warn; another backfill's lock is not
+ const counts = dryRun ? `${result.would_embed} chunk(s) would be embedded (dry-run)` : `${result.embedded} chunk(s) newly embedded (${result.skipped} already had embeddings)`;
return {
- phase: 'embed',
- status: 'ok',
- duration_ms: 0,
- summary: dryRun
- ? `${result.would_embed} chunk(s) would be embedded (dry-run)`
- : `${result.embedded} chunk(s) newly embedded (${result.skipped} already had embeddings)`,
+ phase: 'embed', status: failed ? 'warn' : 'ok', duration_ms: 0,
+ summary: failed ? `${counts}; ${result.failures} chunk(s) could not be embedded this run` : counts,
details: {
embedded: result.embedded,
skipped: result.skipped,
@@ -1644,6 +1642,8 @@ async function runPhaseEmbed(engine: BrainEngine, dryRun: boolean, signal?: Abor
// In dry-run, this counts pages with stale chunks that would
// have been processed (same semantic as a real run).
pages_embedded_count: dryRun ? result.pages_processed : embeddedCount > 0 ? result.pages_processed : 0,
+ failures: result.failures,
+ ...(failed ? { failure_samples: result.failure_samples, fix: embedBackfillFix({ backlog: result.failures, verifyCheck: 'embeddings' }) } : {}),
},
};
} catch (e) {
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 0343dd14a7..a0bfc86d7e 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -275,6 +275,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
'legacy_token_grant_drift',
// Lane E: tokens minted without scopes (grandfathered read+write+admin).
'legacy_token_null_scope',
+ // D4: grants whose operation snapshot or stored surface keeps operations their scopes allow out of reach.
+ 'grant_new_ops_available',
'reranker_health',
'rls',
'rls_event_trigger',
diff --git a/src/core/embedding-dim-check.ts b/src/core/embedding-dim-check.ts
index 97dc2422b2..cd608091f0 100644
--- a/src/core/embedding-dim-check.ts
+++ b/src/core/embedding-dim-check.ts
@@ -268,7 +268,7 @@ export function embeddingMismatchMessage(opts: EmbeddingMismatchOpts): string {
` DROP INDEX IF EXISTS idx_chunks_embedding;`,
` -- NULL embeddings BEFORE the alter: pgvector refuses to cast existing`,
` -- vectors across dimensions and aborts the transaction. NULLs cast fine.`,
- ` UPDATE content_chunks SET embedding = NULL, embedded_at = NULL;`,
+ ` UPDATE content_chunks SET embedding = NULL, embedded_at = NULL, embedding_pending_since = now();`,
` ALTER TABLE content_chunks ALTER COLUMN embedding TYPE vector(${requestedDims});`,
` ${reindexLine.split('\n').join('\n ')}`,
` COMMIT;`,
diff --git a/src/core/embedding-invalidation.ts b/src/core/embedding-invalidation.ts
index 6a8f12afa4..a9ae56e996 100644
--- a/src/core/embedding-invalidation.ts
+++ b/src/core/embedding-invalidation.ts
@@ -199,7 +199,7 @@ export async function invalidateStaleSignatureEmbeddingsGuarded(
: `p.embedding_signature IS NOT NULL AND p.embedding_signature <> $1`;
const rows = await tx.executeRaw<{ page_id: number }>(
`UPDATE content_chunks cc
- SET ${colId} = NULL, embedded_at = NULL
+ SET ${colId} = NULL, embedded_at = NULL, embedding_pending_since = now()
FROM pages p
WHERE cc.page_id = p.id
AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived)
diff --git a/src/core/embedding-migration.ts b/src/core/embedding-migration.ts
index 56362a6090..956aa1d0b6 100644
--- a/src/core/embedding-migration.ts
+++ b/src/core/embedding-migration.ts
@@ -202,8 +202,8 @@ export async function runSchemaTransition(engine: BrainEngine, targetDim: number
// embedding_is_null), so this clear is belt-and-braces, DELIBERATELY outside
// the DDL transaction: a ~1M-row UPDATE inside the ACCESS EXCLUSIVE window
// would hold the exclusive lock through row churn (the pooler-contention
- // class pace-mode exists for), and a crash mid-batch leaves only
- // redundant-lie rows that nothing reads. Batched with an event-loop yield
+ // class pace-mode exists for). It also stamps embedding_pending_since (kept when already
+ // pending) for doctor's backlog age; a row a crash skipped has none. Batched with an event-loop yield
// between batches (setTimeout(0), NOT setImmediate — Bun starves the timers
// phase under a tight setImmediate loop) so lock heartbeats keep firing.
try {
@@ -217,10 +217,10 @@ export async function runSchemaTransition(engine: BrainEngine, targetDim: number
const res = await engine.executeRaw<{ n: number; max_id: number | null }>(
`WITH b AS (
SELECT id FROM content_chunks
- WHERE id > $1 AND embedded_at IS NOT NULL
+ WHERE id > $1 AND (embedded_at IS NOT NULL OR embedding_pending_since IS NULL)
ORDER BY id LIMIT 50000
),
- u AS (UPDATE content_chunks c SET embedded_at = NULL FROM b WHERE c.id = b.id RETURNING b.id)
+ u AS (UPDATE content_chunks c SET embedded_at = NULL, embedding_pending_since = COALESCE(c.embedding_pending_since, now()) FROM b WHERE c.id = b.id RETURNING b.id)
SELECT count(*)::int AS n, max(id)::int AS max_id FROM u`,
[cursor],
);
diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.ts
index 810eb56d4a..5bbded8c57 100644
--- a/src/core/engine-sql/chunks.ts
+++ b/src/core/engine-sql/chunks.ts
@@ -172,7 +172,7 @@ export async function upsertChunksOnce(
// #4246: embedded_text_hash records md5(chunk_text) AT EMBED TIME so a
// later text rewrite that keeps the vector is detectable as content
// drift (invalidateContentDriftEmbeddings). NULL when no embedding lands.
- const cols = `(page_id, chunk_index, chunk_text, chunk_source, ${writeColId}, model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image)`;
+ const cols = `(page_id, chunk_index, chunk_text, chunk_source, ${writeColId}, model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image, embedding_pending_since)`;
let resolvedModel: string | null = gatewayModel;
if (!resolvedModel) resolvedModel = (await modelRows)?.[0]?.value ?? null;
resolvedModel = writeCol.embeddingModel || resolvedModel;
@@ -243,12 +243,17 @@ export async function upsertChunksOnce(
// #4246: embedded_text_hash is md5(chunk_text) in SQL (not JS) so stamp + drift
// comparison share ONE md5 implementation; it, embedded_at and the input hash
// are set only when the row carries a vector.
+ //
+ // embedding_pending_since follows the vector that wins: NULL when one
+ // lands, kept while the row stays without one, now() when this write
+ // NULLs it (doctor ages the embedding backlog from it).
const { text, params } = renderFragment(sqlFragment`INSERT INTO content_chunks ${trustedSql(cols)}
SELECT ${pageId}::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding${trustedSql(writeCast)}, c.model, c.token_count,
CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END,
CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END,
c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line,
- c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector
+ c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector,
+ CASE WHEN c.embedding IS NULL THEN now() ELSE NULL END
FROM jsonb_to_recordset(${JSON.stringify(incoming)}::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text,
embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text,
start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text)
@@ -305,7 +310,13 @@ export async function upsertChunksOnce(
doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END,
symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END,
modality = EXCLUDED.modality,
- embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image)`);
+ embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image),
+ embedding_pending_since = CASE
+ WHEN EXCLUDED.${col} IS NOT NULL THEN NULL
+ WHEN content_chunks.${col} IS NULL THEN COALESCE(content_chunks.embedding_pending_since, now())
+ WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN now()
+ ELSE content_chunks.embedding_pending_since
+ END`);
if (sealed === undefined) { await exec.query(text, params); return; }
const [{ rows }] = await pipelined({ kind: exec.dialect }, [sealPage, () => exec.query(text, params)]) as [{ rows: Array<{ id: number }> }];
if (rows.length === 0) throw new Error(`Page not found: ${slug} (source=${sourceId})`);
@@ -438,7 +449,7 @@ export async function invalidateStaleSignatureEmbeddings(
return inTransaction(async tx => {
const sources = await lockEmbeddingSources(tx, opts.sourceId);
const { text, params } = renderFragment(sqlFragment`UPDATE content_chunks cc
- SET ${colId} = NULL, embedded_at = NULL
+ SET ${colId} = NULL, embedded_at = NULL, embedding_pending_since = now()
FROM pages p
WHERE cc.page_id = p.id
AND p.deleted_at IS NULL
@@ -471,7 +482,7 @@ export async function invalidateContentDriftEmbeddings(
return inTransaction(async tx => {
const sources = await lockEmbeddingSources(tx, opts?.sourceId);
const { text, params } = renderFragment(sqlFragment`UPDATE content_chunks cc
- SET ${colId} = NULL, embedded_at = NULL, embedded_text_hash = NULL
+ SET ${colId} = NULL, embedded_at = NULL, embedded_text_hash = NULL, embedding_pending_since = now()
FROM pages p
WHERE cc.page_id = p.id
AND p.source_id=ANY(${sources}::text[])
diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index 046c9748a3..5e0c72bfaf 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -347,7 +347,7 @@ export async function updatePageContextualRetrievalState(
RETURNING p.id, previous.old_mode, previous.skipped
)
UPDATE content_chunks cc SET ${vector}=NULL, embedded_at=NULL,
- embedded_text_hash=NULL, embedding_input_hash=NULL
+ embedded_text_hash=NULL, embedding_input_hash=NULL, embedding_pending_since=now()
FROM changed WHERE cc.page_id=changed.id
AND changed.old_mode IN ('title','per_chunk_synopsis') AND NOT changed.skipped
AND cc.${vector} IS NOT NULL`);
diff --git a/src/core/grants/profiles.ts b/src/core/grants/profiles.ts
index 3ad550ebf9..56ca3b4ed4 100644
--- a/src/core/grants/profiles.ts
+++ b/src/core/grants/profiles.ts
@@ -3,6 +3,7 @@ import { BRAIN_TOOL_ALLOWLIST } from '../minions/tools/brain-allowlist.ts';
import { operationScopesAllowed } from '../scope.ts';
import { opAllowedForBoundClient } from '../ops/context.ts';
import { GrantError, type ClientGrant, type GrantPatch, type GrantProfileId, type GrantValidationContext } from './model.ts';
+import { VERSION } from '../../version.ts';
export const RENEWABLE_GRANT_TTL_SECONDS = 3600;
export const STATIC_GRANT_TTL_SECONDS = 30 * 24 * 3600;
@@ -16,6 +17,18 @@ export function grantCatalog(): Pick<GrantValidationContext, 'operationNames' |
};
}
+/**
+ * The operation catalog an operation snapshot was written against. Stored on
+ * the grant's audit record when a snapshot is written, so a later diagnosis can
+ * tell operations added after the snapshot from ones left out of it. Grants
+ * written before this existed have none, and none is ever synthesized for them.
+ */
+export interface CatalogProvenance { version: 1; gbrain_version: string; operations: string[] }
+
+export function catalogProvenance(): CatalogProvenance {
+ return { version: 1, gbrain_version: VERSION, operations: [...grantCatalog().operationNames].sort() };
+}
+
/** Explicit profile application is a regrant; ordinary repair does not call this. */
export function resolveGrantProfile(opts: {
profile: GrantProfileId;
@@ -45,7 +58,7 @@ export function resolveGrantProfile(opts: {
profile: opts.profile, scopes, sourceId: opts.sourceId,
federatedRead: opts.federatedRead ?? opts.existing?.federatedRead ?? [opts.sourceId],
boundSlugPrefixes: directPrefixes, allowedOperations,
- surface: opts.profile === 'full' || opts.profile === 'operator' ? 'full' : 'starter', surfaceSetBy: 'operator',
+ surface: opts.profile === 'delegating-agent' ? 'starter' : 'full', surfaceSetBy: 'operator',
boundTools: delegated ? opts.boundTools ?? opts.existing?.boundTools ?? null : null,
boundSourceId: delegated ? opts.sourceId : null,
boundBrainId: null,
diff --git a/src/core/grants/service.ts b/src/core/grants/service.ts
index d1d455eceb..603ce79e11 100644
--- a/src/core/grants/service.ts
+++ b/src/core/grants/service.ts
@@ -1,7 +1,7 @@
import type { BrainEngine } from '../engine.ts';
import { sqlQueryForEngine, type SqlQuery } from '../sql-query.ts';
import { GrantError, grantFromRow, normalizeGrantBrain, validateClientGrant, type ClientGrant, type GrantPatch, type GrantValidationContext } from './model.ts';
-import { grantCatalog } from './profiles.ts';
+import { catalogProvenance, grantCatalog, type CatalogProvenance } from './profiles.ts';
export type GrantDatabase = BrainEngine | SqlQuery;
const query = (db: GrantDatabase): SqlQuery => typeof db === 'function' ? db : sqlQueryForEngine(db);
@@ -42,6 +42,39 @@ export interface GrantClientMetadata {
issuedAt: number;
}
+const operationSet = (ops: readonly string[]): string => JSON.stringify([...new Set(ops)].sort());
+
+/**
+ * The audit document for a grant write. A write that sets a new operation
+ * snapshot records the catalog it was written against (`catalogProvenance`);
+ * every other write leaves provenance with the audit row that wrote the snapshot.
+ */
+function auditDocument(after: ClientGrant, before: ClientGrant | null): string {
+ const snapshotWritten = after.allowedOperations !== null
+ && (before?.allowedOperations == null || operationSet(before.allowedOperations) !== operationSet(after.allowedOperations));
+ return JSON.stringify(snapshotWritten ? { ...after, catalogProvenance: catalogProvenance() } : after);
+}
+
+/**
+ * The catalog provenance of a client's CURRENT operation snapshot: the newest
+ * audit row that recorded provenance, only while its snapshot is still the
+ * grant's snapshot. Null for grants written before provenance existed, for a
+ * snapshot changed without it, and when the audit table cannot be read.
+ */
+export async function readClientCatalogProvenance(db: GrantDatabase, clientId: string, snapshot: readonly string[]): Promise<CatalogProvenance | null> {
+ try {
+ const rows = await query(db)`SELECT after_grant FROM oauth_grant_audit
+ WHERE client_id = ${clientId} AND after_grant->'catalogProvenance' IS NOT NULL ORDER BY id DESC LIMIT 1`;
+ const raw = rows[0]?.after_grant;
+ const doc = (typeof raw === 'string' ? JSON.parse(raw) : raw) as { allowedOperations?: unknown; catalogProvenance?: CatalogProvenance } | null;
+ const provenance = doc?.catalogProvenance;
+ if (!Array.isArray(doc?.allowedOperations) || provenance?.version !== 1 || !Array.isArray(provenance.operations)) return null;
+ return operationSet(doc.allowedOperations as string[]) === operationSet(snapshot) ? provenance : null;
+ } catch {
+ return null;
+ }
+}
+
/** Called after validation. Never exposes the credential in the audit document. */
export async function insertClientGrant(sql: SqlQuery, grant: ClientGrant, metadata: GrantClientMetadata, actor = 'operator'): Promise<void> {
await sql`
@@ -66,7 +99,7 @@ export async function insertClientGrant(sql: SqlQuery, grant: ClientGrant, metad
ARRAY(SELECT jsonb_array_elements_text(${JSON.stringify(grant.repairReasons)}::text::jsonb)))
RETURNING client_id
) INSERT INTO oauth_grant_audit (client_id, actor, action, revision, before_grant, after_grant)
- SELECT client_id, ${actor}, 'register', ${grant.revision}, NULL, ${JSON.stringify(grant)}::text::jsonb FROM created
+ SELECT client_id, ${actor}, 'register', ${grant.revision}, NULL, ${auditDocument(grant, null)}::text::jsonb FROM created
`;
}
@@ -151,7 +184,7 @@ export async function persistGrant(sql: SqlQuery, before: ClientGrant, after: Cl
RETURNING j.id
), audited AS (
INSERT INTO oauth_grant_audit (client_id, actor, action, revision, before_grant, after_grant)
- SELECT client_id, ${actor}, ${action}, ${after.revision}, ${JSON.stringify(before)}::text::jsonb, ${JSON.stringify(after)}::text::jsonb FROM updated
+ SELECT client_id, ${actor}, ${action}, ${after.revision}, ${JSON.stringify(before)}::text::jsonb, ${auditDocument(after, before)}::text::jsonb FROM updated
RETURNING client_id
) SELECT client_id FROM audited
`;
@@ -160,4 +193,5 @@ export async function persistGrant(sql: SqlQuery, before: ClientGrant, after: Cl
export { GrantError, grantFromRow, validateClientGrant, delegationReasons, intersectGrantedScopes } from './model.ts';
export type { ClientGrant, GrantPatch, GrantProfileId, GrantValidationContext } from './model.ts';
-export { resolveGrantProfile, grantCatalog, RENEWABLE_GRANT_TTL_SECONDS, STATIC_GRANT_TTL_SECONDS } from './profiles.ts';
+export { resolveGrantProfile, grantCatalog, catalogProvenance, RENEWABLE_GRANT_TTL_SECONDS, STATIC_GRANT_TTL_SECONDS } from './profiles.ts';
+export type { CatalogProvenance } from './profiles.ts';
diff --git a/src/core/harness/capabilities.ts b/src/core/harness/capabilities.ts
index 98e171e8b7..76937a51fc 100644
--- a/src/core/harness/capabilities.ts
+++ b/src/core/harness/capabilities.ts
@@ -4,6 +4,9 @@ import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import { TOKEN_TTL_MAX_SECONDS, TOKEN_TTL_MIN_SECONDS, normalizeGrantBrain, validGrantPrefixes } from '../grants/model.ts';
import { shellQuote } from '../mcp-registration.ts';
+import type { CatalogProvenance } from '../grants/profiles.ts';
+
+type GrantSurface = 'verbs' | 'starter' | 'full';
/** Keep valid bindings implicit so a repair preview cannot replace unrelated
* restrictions. Missing authority is an operator choice, never a default. */
@@ -51,9 +54,189 @@ function delegationRepair(auth: AuthInfo, reasons: readonly string[]) {
};
}
+/** One grant as the diagnosis sees it: the verifier's principal plus the stored axes that decide which operations it can call. */
+export interface GrantGapInput {
+ scopes: readonly string[];
+ /** null = no operation snapshot. */
+ allowedOperations: readonly string[] | null;
+ boundSlugPrefixes?: string[];
+ fenceProjectionDegraded?: boolean;
+ grantProjectionDegraded?: boolean;
+ /** The client's own stored surface (`oauth_clients.surface`); null = none. */
+ clientSurface: GrantSurface | null;
+ /** The narrowest surface the server proves it applies to this grant; null = none proven. */
+ serverSurface: GrantSurface | null;
+ /** Operations a server publish gate disables; never counted as eligible. */
+ disabled: ReadonlySet<string>;
+}
+
+/**
+ * Host-side only: operation NAMES behind each proven blocker. `eligible` is
+ * every remote operation the grant's scopes and direct-write fence allow
+ * (enabled on this server); operations outside the grant's scopes are never
+ * counted, so a writer is not told about admin-only operations. Each blocker
+ * is counted independently over that set. Callers receive counts only
+ * (`describeGrantDiagnosis`).
+ */
+export interface GrantGaps {
+ missingScopes: string[];
+ snapshotExcluded: string[];
+ pinExcluded: string[];
+ serverExcluded: string[];
+ unreachable: string[];
+}
+
+export async function grantOperationGaps(input: GrantGapInput): Promise<GrantGaps> {
+ const [{ operations, opAllowedForBoundClient }, { filterOpsForSurface }] = await Promise.all([
+ import('../operations.ts'), import('../../mcp/surface.ts'),
+ ]);
+ const fence = { boundSlugPrefixes: input.boundSlugPrefixes, fenceProjectionDegraded: input.fenceProjectionDegraded, grantProjectionDegraded: input.grantProjectionDegraded };
+ const eligible = operations.filter(op => !op.localOnly && !input.disabled.has(op.name)
+ && operationScopesAllowed([...input.scopes], op) && opAllowedForBoundClient(fence, op));
+ const outside = (surface: GrantSurface | null): string[] => {
+ if (!surface || surface === 'full') return [];
+ const listed = new Set(filterOpsForSurface(eligible, surface).map(op => op.name));
+ return eligible.filter(op => !listed.has(op.name)).map(op => op.name);
+ };
+ const snapshot = input.allowedOperations ? new Set(input.allowedOperations) : null;
+ const snapshotExcluded = snapshot ? eligible.filter(op => !snapshot.has(op.name)).map(op => op.name) : [];
+ const pinExcluded = outside(input.clientSurface);
+ const serverExcluded = outside(input.serverSurface);
+ const blocked = new Set([...snapshotExcluded, ...pinExcluded, ...serverExcluded]);
+ return {
+ missingScopes: ['read', 'write'].filter(scope => !hasScope([...input.scopes], scope)),
+ snapshotExcluded, pinExcluded, serverExcluded,
+ unreachable: eligible.filter(op => blocked.has(op.name)).map(op => op.name),
+ };
+}
+
+const operationsWord = (n: number): string => `${n} currently eligible operation${n === 1 ? '' : 's'}`;
+
+/**
+ * Inferred grant age, kept apart from the proven blockers. A snapshot that
+ * excludes eligible operations proves exclusion, not age: an old profile
+ * snapshot and a deliberate restriction look the same. Only a snapshot written
+ * with catalog provenance can be said to predate operations.
+ */
+export function grantAge(snapshotExcluded: readonly string[], hasSnapshot: boolean, provenance: CatalogProvenance | null) {
+ if (!hasSnapshot) return { state: 'no_snapshot' as const };
+ const n = snapshotExcluded.length;
+ if (n === 0) return { state: 'snapshot_complete' as const, excluded_count: 0 };
+ if (!provenance) {
+ return { state: 'intent_unknown' as const, excluded_count: n,
+ statement: `This grant's snapshot excludes ${operationsWord(n)}; original intent unknown.` };
+ }
+ const known = new Set(provenance.operations);
+ const predates = snapshotExcluded.filter(name => !known.has(name)).length;
+ const leftOut = n - predates;
+ return {
+ state: 'provenance_recorded' as const, excluded_count: n, predates_count: predates, excluded_at_snapshot_count: leftOut,
+ snapshot_gbrain_version: provenance.gbrain_version,
+ statement: predates
+ ? `This grant predates ${operationsWord(predates)}: they were added after its operation snapshot was written (gbrain ${provenance.gbrain_version}).`
+ + (leftOut ? ` ${leftOut} more existed then and were left out of the snapshot.` : '')
+ : `This grant's snapshot excludes ${operationsWord(n)}; all existed when the snapshot was written (gbrain ${provenance.gbrain_version}) and were left out of it.`,
+ };
+}
+
+/** Who to rescope: an OAuth client by id, a legacy token by `--token <name>` or `--id <uuid>`. */
+export type RescopeTarget = { kind: 'oauth_client'; id: string } | { kind: 'legacy_token'; flag: ['--token' | '--id', string] };
+
+/**
+ * The host commands that lift snapshot and client-pin blockers. They differ by
+ * credential type: tokens refresh their snapshot (`--refresh-operations`
+ * previews, `--add` widens by exactly the named operations); clients have no
+ * refresh, so they take an explicit `--operations` list plus `--surface full`
+ * when their stored surface blocks too. `operations` fills the list; null
+ * leaves the `<OPERATIONS>` placeholder for the owner to choose. `all` is the
+ * disclosed no-snapshot choice, never the default repair.
+ */
+export function grantRescopeArgvs(target: RescopeTarget, gaps: Pick<GrantGaps, 'snapshotExcluded' | 'pinExcluded'>, operations: string | null) {
+ const value = operations ?? '<OPERATIONS>';
+ if (target.kind === 'legacy_token') {
+ const base = ['gbrain', 'auth', 'rescope', ...target.flag];
+ return { preview: [...base, '--refresh-operations'], apply: [...base, '--refresh-operations', '--add', value],
+ all_operations: [...base, '--reset-default', 'operations', '--dry-run'] };
+ }
+ const base = ['gbrain', 'auth', 'rescope', '--client', target.id];
+ const surface = gaps.pinExcluded.length ? ['--surface', 'full'] : [];
+ const apply = [...base, ...(gaps.snapshotExcluded.length ? ['--operations', value] : []), ...surface];
+ return { preview: [...apply, '--dry-run'], apply, all_operations: [...base, '--operations', 'all', ...surface, '--dry-run'] };
+}
+
+/** The proven blockers with counts only. `scope` carries the memory scopes (read, write) the grant lacks, never a count. */
+export function grantBlockers(gaps: GrantGaps, surfaces: { clientSurface: GrantSurface | null; clientSurfaceSetBy: string | null; serverSurface: GrantSurface | null }) {
+ const blockers: Array<Record<string, unknown>> = [];
+ if (gaps.missingScopes.length) blockers.push({ blocker: 'scope', missing_scopes: gaps.missingScopes });
+ if (gaps.snapshotExcluded.length) blockers.push({ blocker: 'operation_snapshot', excluded_count: gaps.snapshotExcluded.length });
+ if (gaps.pinExcluded.length) blockers.push({ blocker: 'client_pin', surface: surfaces.clientSurface, set_by: surfaces.clientSurfaceSetBy, excluded_count: gaps.pinExcluded.length });
+ if (gaps.serverExcluded.length) blockers.push({ blocker: 'server_ceiling', surface: surfaces.serverSurface, excluded_count: gaps.serverExcluded.length });
+ return blockers;
+}
+
+export const ALL_OPERATIONS_CHOICE = 'no snapshot: every operation the scopes and surface allow, including ones later upgrades add';
+
+/**
+ * The caller-safe diagnosis: which proven blockers apply, with counts and no
+ * operation names, plus the inferred grant age. The fix names the host
+ * commands with an `<OPERATIONS>` placeholder: the brain owner chooses.
+ */
+export function describeGrantDiagnosis(gaps: GrantGaps, opts: {
+ hasSnapshot: boolean; provenance: CatalogProvenance | null; clientSurface: GrantSurface | null; clientSurfaceSetBy: string | null;
+ serverSurface: GrantSurface | null; target: RescopeTarget | null;
+}) {
+ const blockers = grantBlockers(gaps, opts);
+ const repairable = opts.target && (gaps.snapshotExcluded.length || gaps.pinExcluded.length);
+ const argvs = repairable ? grantRescopeArgvs(opts.target!, gaps, null) : null;
+ return {
+ blockers,
+ unreachable_count: gaps.unreachable.length,
+ grant_age: grantAge(gaps.snapshotExcluded, opts.hasSnapshot, opts.provenance),
+ fix: argvs ? {
+ next: 'tell_user_to_run' as const, actor: 'host_admin' as const,
+ argv: argvs.preview,
+ then_argv: argvs.apply,
+ ...(argvs.apply.includes('<OPERATIONS>') ? { inputs: [{ name: 'OPERATIONS', how: 'The brain owner chooses: the current operation snapshot plus each operation they approve, comma-separated.' }] } : {}),
+ why: 'This grant cannot call operations its scopes allow until the brain owner changes it; nothing widens automatically.',
+ user_message: `This gbrain connection cannot call ${gaps.unreachable.length} operation(s) its scopes allow. Ask the brain owner to preview the change on the brain host with the command shown, then apply it.`,
+ all_operations: { argv: argvs.all_operations, label: ALL_OPERATIONS_CHOICE },
+ } : null,
+ };
+}
+
+/**
+ * `whoami.grant_diagnosis` for an authenticated connection. Identity is the
+ * verifier's principal (never a display name); provenance is read only for an
+ * OAuth client's current snapshot.
+ */
+export async function resolveGrantDiagnosis(auth: AuthInfo, engine: BrainEngine, config: GBrainConfig, opts: { surfaceCeiling?: GrantSurface; disabled?: ReadonlySet<string> } = {}) {
+ const [{ isMcpSurface, surfaceWiderThan }, { disabledOpsForPublishGates }, { readClientCatalogProvenance }] = await Promise.all([
+ import('../../mcp/surface.ts'), import('../../mcp/publish-gates.ts'), import('../grants/service.ts'),
+ ]);
+ const clientSurface = isMcpSurface(auth.surface) ? auth.surface : null;
+ const effective = isMcpSurface(auth.effectiveSurface) ? auth.effectiveSurface : null;
+ // Server-side narrowing is proven by the transport ceiling, or by an
+ // effective surface that no client pin explains.
+ const serverSurface = !clientSurface ? effective ?? opts.surfaceCeiling ?? null
+ : opts.surfaceCeiling ?? (effective && surfaceWiderThan(clientSurface, effective) ? effective : null);
+ const allowedOperations = Array.isArray(auth.allowedOperations) ? auth.allowedOperations : null;
+ const gaps = await grantOperationGaps({
+ scopes: auth.scopes, allowedOperations, boundSlugPrefixes: auth.boundSlugPrefixes,
+ fenceProjectionDegraded: auth.fenceProjectionDegraded, grantProjectionDegraded: auth.grantProjectionDegraded,
+ clientSurface, serverSurface, disabled: opts.disabled ?? await disabledOpsForPublishGates(engine, config),
+ });
+ const principal = auth.principal;
+ const provenance = principal?.kind === 'oauth_client' && allowedOperations && gaps.snapshotExcluded.length
+ ? await readClientCatalogProvenance(engine, principal.id, allowedOperations) : null;
+ const target: RescopeTarget | null = !principal ? null
+ : principal.kind === 'oauth_client' ? { kind: 'oauth_client', id: principal.id } : { kind: 'legacy_token', flag: ['--id', principal.id] };
+ return describeGrantDiagnosis(gaps, { hasSnapshot: allowedOperations !== null, provenance, clientSurface,
+ clientSurfaceSetBy: auth.surfaceSetBy ?? null, serverSurface, target });
+}
+
/** Same filters as dispatch/tool advertisement, evaluated once per discovery
* request. Imports stay lazy because whoami lives in the operation registry. */
-export async function resolveAuthCapabilities(auth: AuthInfo, engine: BrainEngine, config: GBrainConfig) {
+export async function resolveAuthCapabilities(auth: AuthInfo, engine: BrainEngine, config: GBrainConfig, opts: { surfaceCeiling?: GrantSurface } = {}) {
const [{ operations, opAllowedForBoundClient }, { filterOpsForSurface, isMcpSurface }, { disabledOpsForPublishGates }, { grantCatalog }] = await Promise.all([
import('../operations.ts'), import('../../mcp/surface.ts'), import('../../mcp/publish-gates.ts'), import('../grants/profiles.ts'),
]);
@@ -67,6 +250,7 @@ export async function resolveAuthCapabilities(auth: AuthInfo, engine: BrainEngin
const { configReadiness, readinessHttpView } = await import('../readiness.ts');
return {
...describeAuthCapabilities(auth, { surface, visibleOperations, delegatedTools: grantCatalog().delegateToolNames }),
+ grant_diagnosis: await resolveGrantDiagnosis(auth, engine, config, { surfaceCeiling: opts.surfaceCeiling, disabled }),
readiness: readinessHttpView(configReadiness(config, { transport: 'http' }).entries),
};
}
diff --git a/src/core/mcp-registration.ts b/src/core/mcp-registration.ts
index afc0457e20..6de0b2e738 100644
--- a/src/core/mcp-registration.ts
+++ b/src/core/mcp-registration.ts
@@ -15,12 +15,13 @@ import type { McpSurface } from '../mcp/surface.ts';
export { shellQuote };
/**
- * The surface a new stdio registration pins. `starter` carries the seven
- * memory verbs plus the page reads/writes, timeline write, skills and agent
- * lane bootstrap's instructions name (`get_timeline` is the known gap the F6
- * hint and `request_tools` cover), and stays far below the full catalogue.
+ * The surface a new stdio registration pins: `full`, callable and advertised
+ * (S0, wave 0; the maintainer chose no narrowing). Every install path reads
+ * this one value: README, docs/mcp, INSTALL_FOR_AGENTS.md, the plugin
+ * manifests and every registration gbrain writes. A narrower list, where a
+ * harness caps its tool count, is the user's explicit `--surface starter|verbs`.
*/
-export const REGISTRATION_SURFACE: McpSurface = 'starter';
+export const REGISTRATION_SURFACE: McpSurface = 'full';
/** A registration command's surface value (`verbs`, `starter` or `full`). */
export function isRegistrationSurface(v: unknown): v is McpSurface {
diff --git a/src/core/ops/request-tools.ts b/src/core/ops/request-tools.ts
index b47a621ba1..7e64661b97 100644
--- a/src/core/ops/request-tools.ts
+++ b/src/core/ops/request-tools.ts
@@ -10,13 +10,14 @@
* pattern: by the time a handler runs, operations.ts has finished loading).
*/
-// WP4 (request_tools): the four static imports below are runtime leaves
+// WP4 (request_tools): the static imports below are runtime leaves
// relative to operations.ts (no import cycles back into it). The cyclic
// dependencies — src/mcp/surface.ts (→ brain-allowlist → operations),
// src/mcp/publish-gates.ts (→ operations), and the assembled `operations`
// array itself — are loaded via dynamic import inside the handler instead
// (the verbs.ts house pattern).
import { isUndefinedColumnError } from '../utils.ts';
+import { suggestNearest } from '../levenshtein.ts';
import { hasScope, operationScopesAllowed } from '../scope.ts';
import { RateLimiter } from '../../mcp/rate-limit.ts';
import { writeSurfaceChangeAudit } from '../surface-audit.ts';
@@ -294,6 +295,23 @@ const request_tools: Operation = {
const catalogCeiling = session && session.widenAllowed && !session.readOnly ? clampSurface('full') : ceiling;
const visible = await visibleOpsForCaller(ctx, catalogCeiling);
+ const catalog = () => {
+ const groups = new Map<string, Array<{ name: string; one_line: string }>>();
+ for (const op of visible) {
+ // Area names are non-contractual grouping labels (amendment 22).
+ const area = op.area ?? 'other';
+ const bucket = groups.get(area) ?? [];
+ bucket.push({ name: op.name, one_line: firstSentenceOf(op.description) });
+ groups.set(area, bucket);
+ }
+ return [...groups.entries()]
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([area, tools]) => ({ area, tools }));
+ };
+ const catalogNote = session
+ ? 'Call request_tools {tools: ["name", ...]} for full schemas, or {surface: "starter"|"full"} to add those tools to this session (nothing is written).'
+ : 'Call request_tools {tools: ["name", ...]} for full schemas, or {surface: "starter"|"full"} to persist a wider tool surface for your OAuth client (within the server ceiling), then re-issue tools/list.';
+
// ── descriptor branch (D5: read-only) ───────────────────────────────
if (p.tools !== undefined) {
const requested = (p.tools as unknown[]).filter((t): t is string => typeof t === 'string');
@@ -306,10 +324,25 @@ const request_tools: Operation = {
const op = byName.get(name);
if (op) picked.push(op); // invisible names silently omitted (D5)
}
+ if (picked.length === 0) {
+ // D1: an empty or unknown-only list gets the catalog instead of `{tools: []}`.
+ // Suggestions come only from the caller-visible set and requested names are
+ // never echoed, so an existing-but-invisible name and a nonexistent one
+ // produce the same bytes (no existence oracle).
+ const visibleNames = visible.map(o => o.name);
+ const didYouMean = [...new Set([...seen].map(name => suggestNearest(name, visibleNames)).filter((n): n is string => n !== null))].sort();
+ return {
+ tools: [],
+ ...(didYouMean.length ? { did_you_mean: didYouMean } : {}),
+ catalog: catalog(),
+ total_tools: visible.length,
+ note: `${seen.size ? 'None of the requested names is a tool this connection can call. ' : ''}${didYouMean.length ? 'The closest callable names are in did_you_mean; the' : 'The'} catalog lists every tool you can call. ${catalogNote}`,
+ };
+ }
const { buildToolDefs } = await import('../../mcp/tool-defs.ts');
const { resolveStrictParamsMode } = await import('../../mcp/validate-params.ts');
const strictParams = (await resolveStrictParamsMode(ctx.engine, ctx.config)) === 'reject';
- if (ctx.revealTools && picked.length) {
+ if (ctx.revealTools) {
ctx.revealTools(picked.map(o => o.name));
return { tools: buildToolDefs(picked, { strictParams }), listed: true, note: 'These tools are now in your tool list (tools/list_changed was sent); call them directly.' };
}
@@ -317,24 +350,7 @@ const request_tools: Operation = {
}
// ── catalog branch (no args) ────────────────────────────────────────
- const groups = new Map<string, Array<{ name: string; one_line: string }>>();
- for (const op of visible) {
- // Area names are non-contractual grouping labels (amendment 22).
- const area = op.area ?? 'other';
- const bucket = groups.get(area) ?? [];
- bucket.push({ name: op.name, one_line: firstSentenceOf(op.description) });
- groups.set(area, bucket);
- }
- const catalog = [...groups.entries()]
- .sort(([a], [b]) => a.localeCompare(b))
- .map(([area, tools]) => ({ area, tools }));
- return {
- catalog,
- total_tools: visible.length,
- note: session
- ? 'Call request_tools {tools: ["name", ...]} for full schemas, or {surface: "starter"|"full"} to add those tools to this session (nothing is written).'
- : 'Call request_tools {tools: ["name", ...]} for full schemas, or {surface: "starter"|"full"} to persist a wider tool surface for your OAuth client (within the server ceiling), then re-issue tools/list.',
- };
+ return { catalog: catalog(), total_tools: visible.length, note: catalogNote };
},
};
diff --git a/src/core/ops/sources.ts b/src/core/ops/sources.ts
index 071adc2c24..741d6e0221 100644
--- a/src/core/ops/sources.ts
+++ b/src/core/ops/sources.ts
@@ -11,7 +11,7 @@ import { authTransport, opError } from './contract.ts';
import { hostFix, hostOnlyError, paramUse } from './op-fix.ts';
import { isValidSourceId } from '../source-id.ts';
import { assertSourceInCallerScope, assertSourceInCallerWriteScope, sourceScopeOpts } from './context.ts';
-import { resolveAuthCapabilities } from '../harness/capabilities.ts';
+import { resolveAuthCapabilities, resolveGrantDiagnosis } from '../harness/capabilities.ts';
// --- v0.28: whoami + sources management ---
@@ -81,7 +81,7 @@ const whoami: Operation = {
transport: 'oauth',
client_id: ctx.auth.clientId,
client_name: ctx.auth.clientName ?? ctx.auth.clientId,
- ...await resolveAuthCapabilities(ctx.auth, ctx.engine, ctx.config),
+ ...await resolveAuthCapabilities(ctx.auth, ctx.engine, ctx.config, { surfaceCeiling: ctx.surfaceCeiling }),
};
}
return {
@@ -89,6 +89,7 @@ const whoami: Operation = {
token_name: ctx.auth.clientName ?? ctx.auth.clientId,
scopes: ctx.auth.scopes,
expires_at: null,
+ grant_diagnosis: await resolveGrantDiagnosis(ctx.auth, ctx.engine, ctx.config, { surfaceCeiling: ctx.surfaceCeiling }),
readiness: readiness('http'),
};
},
diff --git a/src/core/page-state/contextual-proof.ts b/src/core/page-state/contextual-proof.ts
index 285f2f1a3f..d49d9d3578 100644
--- a/src/core/page-state/contextual-proof.ts
+++ b/src/core/page-state/contextual-proof.ts
@@ -17,7 +17,7 @@ export async function reconcileContextualEmbeddingInputs(tx: BrainEngine, snapsh
: !acceptedEmbeddingInputHashes(provenance, mode, chunk).includes(hash);
}).map(chunk => Number(chunk.id));
if (stale.length) await tx.executeRaw(`UPDATE content_chunks SET ${quoteIdentifier(target.column.name)}=NULL,
- embedded_at=NULL,embedded_text_hash=NULL,embedding_input_hash=NULL WHERE page_id=$1 AND id=ANY($2::int[])`, [snapshot.page.id, stale]);
+ embedded_at=NULL,embedded_text_hash=NULL,embedding_input_hash=NULL,embedding_pending_since=now() WHERE page_id=$1 AND id=ANY($2::int[])`, [snapshot.page.id, stale]);
const staleIds = new Set(stale);
const raw = chunks.filter(chunk => !chunk.embedding_is_null && !staleIds.has(Number(chunk.id))
&& recorded.get(Number(chunk.id)) == null);
diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.ts
index 7ef326d520..a364030c13 100644
--- a/src/core/page-state/projections.ts
+++ b/src/core/page-state/projections.ts
@@ -187,7 +187,8 @@ export async function installPageProjection(engine: BrainEngine, prepared: Proje
const currentInput = recorded.filter(row => row.embedding_input_hash === null ? mode == null
: acceptedEmbeddingInputHashes(provenance, mode, byIndex.get(Number(row.chunk_index))!).includes(row.embedding_input_hash)).map(row => Number(row.id));
await tx.executeRaw(`UPDATE content_chunks SET ${quoteIdentifier(context.column.name)}=NULL,
- embedded_at=NULL,embedded_text_hash=NULL,embedding_input_hash=NULL WHERE page_id=$1 AND
+ embedded_at=NULL,embedded_text_hash=NULL,embedding_input_hash=NULL,
+ embedding_pending_since=COALESCE(embedding_pending_since,now()) WHERE page_id=$1 AND
(model IS DISTINCT FROM $2 OR embedded_text_hash <> md5(chunk_text) OR NOT(id=ANY($3::int[])))`,
[snapshot.page.id, context.provenanceModel, currentInput]);
} else if (opts.seal) await tx.deleteChunks(slug, { sourceId });
@@ -246,7 +247,8 @@ export async function installPageEmbeddings(engine: BrainEngine, prepared: Proje
${quoteIdentifier(column.name)}=CASE WHEN $2::text IS NULL THEN ${quoteIdentifier(column.name)} ELSE $2${vectorCastSuffix(column)} END,
embedding_image=CASE WHEN $3::text IS NULL THEN embedding_image ELSE $3::vector END,
embedding_input_hash=CASE WHEN $2::text IS NULL THEN embedding_input_hash ELSE $7 END,
- embedded_at=now(),embedded_text_hash=md5(chunk_text),model=COALESCE($4,model)
+ embedded_at=now(),embedded_text_hash=md5(chunk_text),model=COALESCE($4,model),
+ embedding_pending_since=CASE WHEN $2::text IS NULL THEN embedding_pending_since ELSE NULL END
WHERE id=$1 AND page_id=$5 AND chunk_text=$6`,
// Bind the full provider:model captured before the provider call. Keeping
// an old label on a new vector prevents provenance-complete migration.
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index e0521d998f..eafd886bbe 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -354,7 +354,7 @@ async function embedPage(engine: BrainEngine, config: GBrainConfig, effect: Pers
// A refused chunk keeps no vector from an earlier convention, and the page reads as not fully embedded.
const ids = refused.failures.map(f => pending[f.index]?.id).filter((id): id is number => id !== undefined);
await tx.executeRaw(`UPDATE content_chunks SET ${quoteIdentifier(prepared.embeddingColumn.name)}=NULL,embedded_at=NULL,
- embedded_text_hash=NULL,embedding_input_hash=NULL WHERE page_id=$1 AND id=ANY($2::int[])`, [prepared.snapshot.page.id, ids]);
+ embedded_text_hash=NULL,embedding_input_hash=NULL,embedding_pending_since=COALESCE(embedding_pending_since,now()) WHERE page_id=$1 AND id=ANY($2::int[])`, [prepared.snapshot.page.id, ids]);
await tx.executeRaw('UPDATE pages SET embedding_signature=NULL WHERE id=$1', [prepared.snapshot.page.id]);
}
if (installed && !refused) await restampIfDemotedToTitleTier(tx, prepared.snapshot.page, snapshot.page.slug, effect.source_id);
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 4566433c96..4f74b2dd0b 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -317,6 +317,10 @@ CREATE TABLE IF NOT EXISTS content_chunks (
model TEXT NOT NULL DEFAULT 'text-embedding-3-large',
token_count INTEGER,
embedded_at TIMESTAMPTZ,
+ -- v221: embedding_pending_since (when the stored vector last became missing;
+ -- doctor's embeddings check ages the backlog from it, never from created_at)
+ -- is added by migration v221 on every install, after the migration-added
+ -- content_chunks columns, so fresh and upgraded brains share their ordinals.
-- #4246 (v133): md5(chunk_text) at embed time. NULL = no embedding or
-- pre-v133 row (grandfathered by invalidateContentDriftEmbeddings).
embedded_text_hash TEXT,
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index c693ecefee..a76846afd0 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -221,6 +221,7 @@ import { v217 } from './v217-persistence-request-claim-phase.ts';
import { v218 } from './v218-purge-legacy-worktree-manifest-files.ts';
import { v219 } from './v219-pages-reconcile-name-indexes.ts';
import { v220 } from './v220-persistence-request-preparation-attempts.ts';
+import { v221 } from './v221-chunk-embedding-pending-since.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -440,4 +441,5 @@ export const MIGRATIONS: Migration[] = [
v218,
v219,
v220,
+ v221,
];
diff --git a/src/core/schema-migrations/v221-chunk-embedding-pending-since.ts b/src/core/schema-migrations/v221-chunk-embedding-pending-since.ts
new file mode 100644
index 0000000000..85f4230edd
--- /dev/null
+++ b/src/core/schema-migrations/v221-chunk-embedding-pending-since.ts
@@ -0,0 +1,47 @@
+import type { Migration } from './types.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// Embedding backlog age: `embedding_pending_since` is when a chunk's stored
+// vector (the active embedding column) last became missing. Every site that
+// NULLs the vector or inserts a chunk without one sets it, and every vector
+// write clears it beside `embedded_at`. The doctor `embeddings` check reads it
+// instead of `created_at`, which an edit or a model-swap invalidation never
+// resets. Nullable with no default: metadata-only on Postgres 11+ and PGLite.
+// Not in schema.sql's CREATE TABLE: this migration adds it on every install,
+// after the migration-added content_chunks columns, so fresh and upgraded
+// brains share column ordinals (the v180 pattern). No index: only doctor reads
+// it, over the chunks already missing a vector (bootstrap-coverage:
+// column-only, no probe needed).
+//
+// BACKFILL: chunks already missing a vector get their `created_at` once,
+// because nothing recorded when their vector went missing. The active column
+// is `search_embedding_column` when it names an existing column, else
+// `embedding`. When any row was backfilled, config
+// `embedding_pending_since_backfilled_at` records when, so doctor labels an
+// age older than that stamp as a created_at backfill.
+export const v221: Migration = {
+ version: 221,
+ name: 'chunk_embedding_pending_since',
+ idempotent: true,
+ sql: `
+ ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS embedding_pending_since TIMESTAMPTZ;
+ DO $backfill$
+ DECLARE active_column text; backfilled bigint;
+ BEGIN
+ SELECT c.column_name INTO active_column
+ FROM config k
+ JOIN information_schema.columns c
+ ON c.table_schema = current_schema() AND c.table_name = 'content_chunks' AND c.column_name = k.value
+ WHERE k.key = 'search_embedding_column';
+ EXECUTE format('UPDATE content_chunks SET embedding_pending_since = created_at
+ WHERE %I IS NULL AND embedding_pending_since IS NULL', COALESCE(active_column, 'embedding'));
+ GET DIAGNOSTICS backfilled = ROW_COUNT;
+ IF backfilled > 0 THEN
+ INSERT INTO config (key, value) VALUES ('embedding_pending_since_backfilled_at', now()::text)
+ ON CONFLICT (key) DO NOTHING;
+ END IF;
+ END $backfill$;
+ `,
+};
diff --git a/src/eval/longmemeval/decide-lane.ts b/src/eval/longmemeval/decide-lane.ts
index 29a4e2b545..d761a2440c 100644
--- a/src/eval/longmemeval/decide-lane.ts
+++ b/src/eval/longmemeval/decide-lane.ts
@@ -95,5 +95,5 @@ export const LME_ABSTAIN_HYPOTHESIS = 'I cannot answer this: the conversation hi
*/
export function lmeAbstention(run: DecideEvalRun | null | undefined, meta: HybridSearchMeta | undefined): ReaderAnswer | null {
if (run?.slots.answerable !== 'on' || meta?.decide?.answerable?.effective !== 'on' || meta.answerability?.verdict !== 'abstain') return null;
- return { text: LME_ABSTAIN_HYPOTHESIS, finish_reason: 'end_turn', response_model: null, context_chars: 0, context_sessions: 0, sessions_truncated: 0 };
+ return { text: LME_ABSTAIN_HYPOTHESIS, finish_reason: 'end_turn', usage: null, response_model: null, context_chars: 0, context_sessions: 0, sessions_truncated: 0 };
}
diff --git a/src/eval/longmemeval/gateway-client.ts b/src/eval/longmemeval/gateway-client.ts
index 69884ab1f9..2b4bd2142a 100644
--- a/src/eval/longmemeval/gateway-client.ts
+++ b/src/eval/longmemeval/gateway-client.ts
@@ -14,6 +14,7 @@ import type Anthropic from '@anthropic-ai/sdk';
import type { ThinkLLMClient } from '../../core/think/index.ts';
import { chat as gatewayChat } from '../../core/ai/gateway.ts';
import { normalizeModelId } from '../../core/model-id.ts';
+import { readerUsageFromGateway } from './reader.ts';
export function makeGatewayThinkClient(): ThinkLLMClient {
return {
@@ -47,6 +48,8 @@ export function makeGatewayThinkClient(): ThinkLLMClient {
model: result.responseModel ?? result.model,
content: [{ type: 'text', text: result.text }],
usage: { input_tokens: result.usage.input_tokens, output_tokens: result.usage.output_tokens },
+ // A1: the provider-normalized record the reader keeps on every row (cache and reasoning subsets included).
+ gbrain_usage: readerUsageFromGateway(result.usage),
stop_reason: result.stopReason === 'length' ? 'max_tokens' : result.stopReason === 'end' ? 'end_turn' : result.stopReason ?? null,
} as unknown as Anthropic.Message;
},
diff --git a/src/eval/longmemeval/reader.ts b/src/eval/longmemeval/reader.ts
index 343fb5ca6c..fb01a7caf7 100644
--- a/src/eval/longmemeval/reader.ts
+++ b/src/eval/longmemeval/reader.ts
@@ -24,7 +24,9 @@
* official: 500). The budget and mode are explicit receipt pins.
*/
+import type Anthropic from '@anthropic-ai/sdk';
import type { ThinkLLMClient } from '../../core/think/index.ts';
+import type { ChatResult } from '../../core/ai/gateway.ts';
import type { SearchResult } from '../../core/types.ts';
import { renderChatBlock, type ChatSessionForPrompt } from './sanitize.ts';
import { rawSessionId, sessionIdFromSlug, type SlugToRawMap } from './metrics.ts';
@@ -129,9 +131,61 @@ export function buildReaderRequest(input: ReaderUserTextInput, model: string, co
};
}
+/**
+ * A1: provider-normalized reader usage, one record per attempted reader call.
+ * `total_input_tokens` is every input token the provider billed in any bucket;
+ * the cache subsets are inside it, so `uncached + cache_read + cache_write ===
+ * total` and nothing adds them to the total again. `reasoning_tokens` is the
+ * reasoning subset of `output_tokens`, null when the provider reported none.
+ */
+export interface ReaderUsage {
+ total_input_tokens: number;
+ uncached_input_tokens: number;
+ cache_read_input_tokens: number;
+ cache_write_input_tokens: number;
+ output_tokens: number;
+ reasoning_tokens: number | null;
+}
+
+/** The gateway's usage (AI SDK v6 convention: input_tokens is the total, cache counts are subsets of it). */
+export function readerUsageFromGateway(u: ChatResult['usage']): ReaderUsage {
+ const total = u.input_tokens;
+ return {
+ total_input_tokens: total,
+ uncached_input_tokens: Math.max(0, total - u.cache_read_tokens - u.cache_creation_tokens),
+ cache_read_input_tokens: u.cache_read_tokens,
+ cache_write_input_tokens: u.cache_creation_tokens,
+ output_tokens: u.output_tokens,
+ reasoning_tokens: u.reasoning_tokens ?? null,
+ };
+}
+
+/**
+ * The reader message's usage: the gateway adapter's normalized record when
+ * present, else the Anthropic Messages convention (input_tokens excludes the
+ * separate cache buckets). Null when the client reported no usage.
+ */
+export function readerUsageFromMessage(message: Anthropic.Message & { gbrain_usage?: ReaderUsage }): ReaderUsage | null {
+ if (message.gbrain_usage) return message.gbrain_usage;
+ const u = message.usage as (Anthropic.Usage & { cache_read_input_tokens?: number | null; cache_creation_input_tokens?: number | null }) | undefined;
+ if (!u) return null;
+ const read = u.cache_read_input_tokens ?? 0;
+ const write = u.cache_creation_input_tokens ?? 0;
+ return {
+ total_input_tokens: u.input_tokens + read + write,
+ uncached_input_tokens: u.input_tokens,
+ cache_read_input_tokens: read,
+ cache_write_input_tokens: write,
+ output_tokens: u.output_tokens,
+ reasoning_tokens: null,
+ };
+}
+
export interface ReaderAnswer {
text: string;
finish_reason: string | null;
+ /** A1: provider usage for this reader call; null when no call was made or none was reported. */
+ usage: ReaderUsage | null;
/**
* The model id the provider REPORTED for the answer when it differs from
* the requested id (an API snapshot such as `gpt-4o-2024-08-06`); null when
@@ -180,6 +234,6 @@ export async function generateAnswer(
const reported = typeof response.model === 'string' && response.model.length > 0 && response.model !== model
? response.model
: null;
- const receipt = { finish_reason: response.stop_reason ?? null, context_chars: rendered.length, context_sessions: sessions.length, sessions_truncated: truncatedCount };
+ const receipt = { finish_reason: response.stop_reason ?? null, usage: readerUsageFromMessage(response), context_chars: rendered.length, context_sessions: sessions.length, sessions_truncated: truncatedCount };
return { text: response.content.filter(block => block.type === 'text').map(block => block.text).join('').trim(), response_model: reported, ...receipt };
}
diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.ts
index 9c1092126c..886c47430d 100644
--- a/src/mcp/instructions.ts
+++ b/src/mcp/instructions.ts
@@ -109,11 +109,12 @@ function readinessTail(entries: readonly ReadinessEntry[], callable: (op: string
export function buildMcpInstructions(opts?: { writeback?: AmbientWritebackOpts | null; tools?: InstructionTools }): string {
const tools = opts?.tools;
const clauses = contractClauses(tools?.callable ?? ALL, opts?.writeback);
- let text = `GBrain agent operating contract (apply on every cold start):\n${clauses.map((c, i) => `${i + 1}. ${c}`).join('\n')}`;
+ // D1: capped harnesses read the first 2,048 characters, so the hidden-tool sentence leads the contract.
+ const hidden = tools?.hiddenCallable && tools.callable('request_tools')
+ ? `The tool list shows the everyday tools; ${tools.hiddenCallable} more are callable. Call request_tools with no arguments to list them, or with tools: [names] for their schemas, then call them directly.\n`
+ : '';
+ let text = `GBrain agent operating contract (apply on every cold start):\n${hidden}${clauses.map((c, i) => `${i + 1}. ${c}`).join('\n')}`;
if (tools?.statusLine) text += `\n${tools.statusLine}`;
- if (tools?.hiddenCallable && tools.callable('request_tools')) {
- text += `\nThe tool list shows the everyday tools; ${tools.hiddenCallable} more are callable. Call request_tools with no arguments to list them, or with tools: [names] for their schemas, then call them directly.`;
- }
if (opts?.writeback) text += `\n\n${buildAmbientWritebackSection(opts.writeback)}`;
const tail = tools?.readiness ? readinessTail(tools.readiness, tools.callable) : null;
if (tail) text += `\n\n${tail}`;
diff --git a/src/schema.sql b/src/schema.sql
index aebd2e4791..6cfa7db4d7 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -313,6 +313,10 @@ CREATE TABLE IF NOT EXISTS content_chunks (
model TEXT NOT NULL DEFAULT 'text-embedding-3-large',
token_count INTEGER,
embedded_at TIMESTAMPTZ,
+ -- v221: embedding_pending_since (when the stored vector last became missing;
+ -- doctor's embeddings check ages the backlog from it, never from created_at)
+ -- is added by migration v221 on every install, after the migration-added
+ -- content_chunks columns, so fresh and upgraded brains share their ordinals.
-- #4246 (v133): md5(chunk_text) at embed time. NULL = no embedding or
-- pre-v133 row (grandfathered by invalidateContentDriftEmbeddings).
embedded_text_hash TEXT,
diff --git a/test/admin-grant-outcome.serial.test.ts b/test/admin-grant-outcome.serial.test.ts
index e17aca14bd..4455baf401 100644
--- a/test/admin-grant-outcome.serial.test.ts
+++ b/test/admin-grant-outcome.serial.test.ts
@@ -123,7 +123,7 @@ test('permission edits report unknown after lost commit acknowledgement and pres
try {
const { port } = server.address() as { port: number };
const post = (body: Record<string, unknown>) => fetch(`http://127.0.0.1:${port}/admin/api/rescope-client`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ clientId, ...body }) });
- const change = { surface: 'full', expectedRevision: created.grant.revision };
+ const change = { surface: 'starter', expectedRevision: created.grant.revision };
const preview = await post({ ...change, dryRun: true });
expect(preview.status).toBe(503);
const previewReceipt = await preview.json() as any;
@@ -137,12 +137,12 @@ test('permission edits report unknown after lost commit acknowledgement and pres
expect(receipt.next_action).toContain('reload its current grant');
expect(JSON.stringify(receipt)).not.toContain('private_operational_detail');
const current = await readClientGrant(engine, clientId);
- expect(current.surface).toBe('full');
+ expect(current.surface).toBe('starter');
expect(current.revision).toBe(created.grant.revision + 1);
const stale = await post({ ...change, surface: 'verbs', dryRun: true });
expect(stale.status).toBe(409);
expect(await stale.json()).toMatchObject({ code: 'grant_conflict', stage: 'rescope', outcome: 'failed' });
- expect((await readClientGrant(engine, clientId)).surface).toBe('full');
+ expect((await readClientGrant(engine, clientId)).surface).toBe('starter');
const legacy = await post({ federatedRead: [] });
expect(legacy.status).toBe(400);
expect(await legacy.json()).toMatchObject({ code: 'invalid_grant', stage: 'rescope', outcome: 'failed' });
diff --git a/test/agent-register.test.ts b/test/agent-register.test.ts
index 71fb24096c..6974516f80 100644
--- a/test/agent-register.test.ts
+++ b/test/agent-register.test.ts
@@ -171,23 +171,24 @@ describe('resolvePreset', () => {
const flags = (over: Record<string, unknown>) =>
({ showToken: false, json: false, name: 'aurora', harness: 'claude-code', ...over }) as any;
- test('daily-driver: snapshot grant, default write source, starter surface', () => {
+ test('daily-driver: snapshot grant, default write source, full surface (S0/D4)', () => {
const r = resolvePreset(flags({ preset: 'daily-driver' }));
expect(r).toEqual({
scopes: 'read write',
writeSource: 'default',
federatedRead: 'snapshot',
- surface: 'starter',
+ surface: 'full',
workspaceDerived: false,
});
});
- test('coding-agent: derived workspace first in the read list, starter surface', () => {
+ test('coding-agent: derived workspace first in the read list, full surface (S0/D4)', () => {
const r = resolvePreset(flags({ preset: 'coding-agent', federatedRead: ['proj-widget'] }));
expect(r.writeSource).toBe('aurora-workspace');
expect(r.workspaceDerived).toBe(true);
expect(r.federatedRead).toEqual(['aurora-workspace', 'proj-widget']);
- expect(r.surface).toBe('starter');
+ expect(r.surface).toBe('full');
+ expect(resolvePreset(flags({ preset: 'coding-agent', federatedRead: ['proj-widget'], surface: 'starter' })).surface).toBe('starter');
});
test('coding-agent without --federated-read fails loud', () => {
diff --git a/test/bootstrap-codex-door.test.ts b/test/bootstrap-codex-door.test.ts
index 8ea425a312..5b4c6fdfa6 100644
--- a/test/bootstrap-codex-door.test.ts
+++ b/test/bootstrap-codex-door.test.ts
@@ -8,8 +8,8 @@
* 1. The RENDERED AGENTS.md carries Gate 3 ("Entity lookup (brain first)") in
* full — search-the-brain-before-answering with the actual brain tools —
* so a Codex agent with no hooks still pulls context every turn.
- * 2. `registerCodexMcp` argv pins `serve --surface starter` (bootstrap's page,
- * timeline and verb tools, not a narrowed `verbs`) and binds GBRAIN_SOURCE so a
+ * 2. `registerCodexMcp` argv pins `serve --surface full` (REGISTRATION_SURFACE:
+ * bootstrap's page, timeline and verb tools, not a narrowed `verbs`) and binds GBRAIN_SOURCE so a
* GUI-spawned serve (which inherits no shell env) writes to the workspace
* source [G1, CX-P1.4].
*/
@@ -81,10 +81,10 @@ describe('Codex door — rendered AGENTS.md pull protocol (Gate 3)', () => {
});
});
-describe('Codex door — registerCodexMcp argv (--surface starter + GBRAIN_SOURCE)', () => {
+describe('Codex door — registerCodexMcp argv (--surface full + GBRAIN_SOURCE)', () => {
const BIN = '/opt/gbrain/bin/gbrain';
- test('user-global stdio registration binds the source and pins the starter surface', () => {
+ test('user-global stdio registration binds the source and pins the full surface', () => {
const argvs = registerCodexMcp({ gbrainBin: BIN, sourceId: 'workspace' });
expect(argvs.length).toBe(1);
const argv = argvs[0]!;
@@ -92,12 +92,12 @@ describe('Codex door — registerCodexMcp argv (--surface starter + GBRAIN_SOURC
expect(argv).toEqual([
'codex', 'mcp', 'add', 'gbrain',
'--env', 'GBRAIN_SOURCE=workspace',
- '--', BIN, 'serve', '--surface', 'starter',
+ '--', BIN, 'serve', '--surface', 'full',
]);
// The two contracts, asserted independently so a reshuffle can't hide a drop.
const joined = argv.join(' ');
expect(joined).toContain('--env GBRAIN_SOURCE=workspace');
- expect(joined).toContain('serve --surface starter');
+ expect(joined).toContain('serve --surface full');
// `serve` argv must NOT narrow to the verbs surface.
expect(joined).not.toContain('--surface verbs');
});
@@ -108,7 +108,7 @@ describe('Codex door — registerCodexMcp argv (--surface starter + GBRAIN_SOURC
// GBRAIN_HOME is a second --env, GBRAIN_SOURCE still present, surface intact.
expect(argv.filter((a) => a === '--env').length).toBe(2);
expect(argv).toContain('GBRAIN_SOURCE=workspace');
- expect(argv.join(' ')).toContain('serve --surface starter');
+ expect(argv.join(' ')).toContain('serve --surface full');
});
test('a non-absolute gbrain binary is refused (GUI hosts inherit no PATH) [CX-P1.4]', () => {
diff --git a/test/bootstrap-dispatcher.serial.test.ts b/test/bootstrap-dispatcher.serial.test.ts
index dc20856019..05cb90e397 100644
--- a/test/bootstrap-dispatcher.serial.test.ts
+++ b/test/bootstrap-dispatcher.serial.test.ts
@@ -641,16 +641,17 @@ describe('MCP registration verification [FIX7]', () => {
const serveTail = (argv: string[]) => argv.slice(argv.indexOf('--') + 2);
const adds = (calls: string[][]) => calls.filter((c) => c[1] === 'mcp' && c[2] === 'add');
- test('a fresh registration pins the registration surface (starter)', async () => {
+ test('a fresh registration pins the registration surface (full)', async () => {
const { runner, calls } = mcpHost({ initialReg: null });
expect((await runHooks(runner)).result).toBe(0);
- expect(serveTail(adds(calls)[0])).toEqual(['serve', '--surface', 'starter']);
+ expect(serveTail(adds(calls)[0])).toEqual(['serve', '--surface', 'full']);
}, 30_000);
test('never narrow: a replaced entry keeps its pinned surface, a bare serve stays bare, --surface wins', async () => {
- const pinned = mcpHost({ initialReg: FOREIGN });
+ // Pinned to a surface other than the registration default (full), so keeping it is observable.
+ const pinned = mcpHost({ initialReg: FOREIGN.replace('serve --surface full', 'serve --surface starter') });
expect((await runHooks(pinned.runner)).result).toBe(0);
- expect(serveTail(adds(pinned.calls)[1])).toEqual(['serve', '--surface', 'full']);
+ expect(serveTail(adds(pinned.calls)[1])).toEqual(['serve', '--surface', 'starter']);
const bare = mcpHost({ initialReg: `gbrain:\n command: /somewhere/else/gbrain serve\n env: GBRAIN_SOURCE=other-workspace` });
expect((await runHooks(bare.runner)).result).toBe(0);
diff --git a/test/bootstrap-hooks-writers.test.ts b/test/bootstrap-hooks-writers.test.ts
index b0090163ed..d685e018b6 100644
--- a/test/bootstrap-hooks-writers.test.ts
+++ b/test/bootstrap-hooks-writers.test.ts
@@ -256,10 +256,10 @@ describe('removeClaudeHooks [G5]', () => {
});
describe('MCP registration argv builders [G1, CX-P1.4]', () => {
- test('registerClaudeMcp: stdio shape with scope + source env; serve pinned to --surface starter (REGISTRATION_SURFACE)', () => {
+ test('registerClaudeMcp: stdio shape with scope + source env; serve pinned to --surface full (REGISTRATION_SURFACE)', () => {
const cmds = registerClaudeMcp({ gbrainBin: BIN, scope: 'project', sourceId: 'workspace' });
expect(cmds).toEqual([
- ['claude', 'mcp', 'add', 'gbrain', '--scope', 'project', '-e', 'GBRAIN_SOURCE=workspace', '--', BIN, 'serve', '--surface', 'starter'],
+ ['claude', 'mcp', 'add', 'gbrain', '--scope', 'project', '-e', 'GBRAIN_SOURCE=workspace', '--', BIN, 'serve', '--surface', 'full'],
]);
});
@@ -269,14 +269,14 @@ describe('MCP registration argv builders [G1, CX-P1.4]', () => {
});
expect(cmds[0]).toEqual([
'claude', 'mcp', 'add', 'mybrain', '--scope', 'user',
- '-e', 'GBRAIN_SOURCE=s1', '-e', 'GBRAIN_HOME=/ws', '--', BIN, 'serve', '--surface', 'starter',
+ '-e', 'GBRAIN_SOURCE=s1', '-e', 'GBRAIN_HOME=/ws', '--', BIN, 'serve', '--surface', 'full',
]);
});
- test('registerCodexMcp: --env shape, no scope flag; serve pinned to --surface starter (REGISTRATION_SURFACE)', () => {
+ test('registerCodexMcp: --env shape, no scope flag; serve pinned to --surface full (REGISTRATION_SURFACE)', () => {
const cmds = registerCodexMcp({ gbrainBin: BIN, sourceId: 'workspace', gbrainHome: '/ws' });
expect(cmds).toEqual([
- ['codex', 'mcp', 'add', 'gbrain', '--env', 'GBRAIN_SOURCE=workspace', '--env', 'GBRAIN_HOME=/ws', '--', BIN, 'serve', '--surface', 'starter'],
+ ['codex', 'mcp', 'add', 'gbrain', '--env', 'GBRAIN_SOURCE=workspace', '--env', 'GBRAIN_HOME=/ws', '--', BIN, 'serve', '--surface', 'full'],
]);
});
diff --git a/test/bootstrap-opencode-door.serial.test.ts b/test/bootstrap-opencode-door.serial.test.ts
index 087f307628..ad6a52e21d 100644
--- a/test/bootstrap-opencode-door.serial.test.ts
+++ b/test/bootstrap-opencode-door.serial.test.ts
@@ -188,7 +188,7 @@ describe('opencode workspace lane — default scope is USER-GLOBAL', () => {
};
expect(entry.type).toBe('local');
expect(entry.command[0]).toBe(FAKE_BIN); // user scope: absolute path
- expect(entry.command.slice(1)).toEqual(['serve', '--surface', 'starter']);
+ expect(entry.command.slice(1)).toEqual(['serve', '--surface', 'full']);
expect(entry.environment.GBRAIN_SOURCE).toBeDefined();
expect(entry.enabled).toBe(true);
@@ -322,7 +322,7 @@ describe('opencode workspace lane — explicit project opt-in', () => {
const cfgPath = join(ws, 'opencode.json');
const parsed = parseOpencodeConfig(readFileSync(cfgPath, 'utf8'), cfgPath);
const entry = (parsed.mcp as Record<string, unknown>).gbrain as { command: string[] };
- expect(entry.command).toEqual(['gbrain', 'serve', '--surface', 'starter']); // committed-candidate file: PATH-resolved, never absolute
+ expect(entry.command).toEqual(['gbrain', 'serve', '--surface', 'full']); // committed-candidate file: PATH-resolved, never absolute
expect(r.out).toContain('project (explicit opt-in)');
expect(r.err).toContain('SHARING WARNING');
expect(r.err).toContain('"enabled": false');
@@ -383,8 +383,10 @@ describe('opencode never-narrow: a rewritten entry keeps its surface form', () =
return ((parseOpencodeConfig(readFileSync(cfgPath, 'utf8'), cfgPath).mcp as Record<string, { command: string[] }>).gbrain).command;
}
- test('a pinned --surface full stays full, a bare serve stays bare, an explicit --surface wins', async () => {
+ test('a pinned --surface stays pinned, a bare serve stays bare, an explicit --surface wins', async () => {
expect(await rerunWith([FAKE_BIN, 'serve', '--surface', 'full'])).toEqual([FAKE_BIN, 'serve', '--surface', 'full']);
+ // S0: starter differs from the registration default (full), so keeping it is observable.
+ expect(await rerunWith([FAKE_BIN, 'serve', '--surface', 'starter'])).toEqual([FAKE_BIN, 'serve', '--surface', 'starter']);
expect(await rerunWith([FAKE_BIN, 'serve'])).toEqual([FAKE_BIN, 'serve']);
expect(await rerunWith([FAKE_BIN, 'serve', '--surface', 'full'], ['--surface', 'verbs'])).toEqual([FAKE_BIN, 'serve', '--surface', 'verbs']);
}, 60_000);
diff --git a/test/bootstrap-plugin-lane.serial.test.ts b/test/bootstrap-plugin-lane.serial.test.ts
index 9e06330b54..82415871f0 100644
--- a/test/bootstrap-plugin-lane.serial.test.ts
+++ b/test/bootstrap-plugin-lane.serial.test.ts
@@ -242,7 +242,7 @@ describe('runHooks plugin-lane skip (serial: env fixtures)', () => {
expect(r.result).toBe(0);
const add = calls.find((c) => c[0] === 'codex' && c[1] === 'mcp' && c[2] === 'add');
expect(add).toBeDefined();
- expect(add!.join(' ')).toContain('serve --surface starter');
+ expect(add!.join(' ')).toContain('serve --surface full');
}, 30_000);
test('codex + plugin + --mcp-even-if-plugin → registration forced through', async () => {
diff --git a/test/chat-usage.test.ts b/test/chat-usage.test.ts
index c742771486..edf713b7e8 100644
--- a/test/chat-usage.test.ts
+++ b/test/chat-usage.test.ts
@@ -14,7 +14,10 @@ import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } fr
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import {
__setChatTransportForTests,
+ __setGenerateTextTransportForTests,
chat,
+ configureGateway,
+ resetGateway,
type ChatResult,
} from '../src/core/ai/gateway.ts';
import {
@@ -211,7 +214,8 @@ describe('gateway.chat() success boundary — direct vs job callers', () => {
});
__setChatTransportForTests(async () =>
fakeResult({
- usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 2000, cache_creation_tokens: 3000 },
+ // ChatResult convention: input_tokens is the total, the cache buckets are inside it (100 uncached).
+ usage: { input_tokens: 5100, output_tokens: 50, cache_read_tokens: 2000, cache_creation_tokens: 3000 },
}),
);
await chat({ model: 'anthropic:claude-haiku-4-5', messages: [{ role: 'user', content: 'hi' }] });
@@ -389,3 +393,48 @@ describe('engine sink + get_usage op (PGLite, migration v140 schema)', () => {
expect(out.coverage.table_present).toBe(true);
});
});
+
+// A1 follow-up: the gateway reports AI SDK usage, where the input total
+// already contains the cache buckets. A 100-token prompt with 60 tokens read
+// from cache must be priced as 40 uncached + 60 cache-read, whichever
+// convention the provider used; adding the 60 on top of the 100 (master)
+// priced 160 input tokens. The generateText seam replaces only the SDK call,
+// so the gateway's own usage assembly runs.
+describe('cache tokens are subsets of the gateway input total (both provider conventions)', () => {
+ afterEach(() => {
+ __setGenerateTextTransportForTests(null);
+ resetGateway();
+ });
+
+ const CASES = [
+ { model: 'anthropic:claude-haiku-4-5', result: { finishReason: 'stop',
+ usage: { inputTokens: 100, inputTokenDetails: { noCacheTokens: 40, cacheReadTokens: 60, cacheWriteTokens: 0 }, outputTokens: 10 },
+ providerMetadata: { anthropic: { cacheReadInputTokens: 60, cacheCreationInputTokens: 0 } } } },
+ { model: 'openai:gpt-4o', result: { finishReason: 'stop',
+ usage: { inputTokens: 100, inputTokenDetails: { noCacheTokens: 40, cacheReadTokens: 60, cacheWriteTokens: undefined }, outputTokens: 10, cachedInputTokens: 60 } } },
+ ] as const;
+
+ for (const { model, result } of CASES) {
+ test(`${model}: 40 uncached + 60 cache-read, not 100 + 60`, async () => {
+ configureGateway({ env: { ANTHROPIC_API_KEY: 'sk-ant-fake', OPENAI_API_KEY: 'sk-fake' } });
+ __setGenerateTextTransportForTests((async () => ({ content: [{ type: 'text', text: 'ok' }], ...result })) as never);
+ const records: ChatUsageRecord[] = [];
+ setChatUsageSink((r) => { records.push(r); });
+ await chat({ model, messages: [{ role: 'user', content: 'hi' }] });
+ await new Promise((r) => setTimeout(r, 10));
+ expect(records.length).toBe(1);
+ expect(records[0]!.input_tokens).toBe(100);
+ expect(records[0]!.cache_read_tokens).toBe(60);
+ const expected = estimateChatCostUsd(model, { input_tokens: 40, output_tokens: 10, cache_read_tokens: 60 })!;
+ expect(expected).toBeGreaterThan(0);
+ expect(records[0]!.cost_usd).toBeCloseTo(expected, 12);
+ expect(records[0]!.cost_usd).toBeLessThan(estimateChatCostUsd(model, { input_tokens: 100, output_tokens: 10, cache_read_tokens: 60 })!);
+ });
+ }
+
+ test('a priced meter (non-table override) charges the input total once', () => {
+ const meter: ChatCallMeter = { calls: 0, cost_usd: 0, pricing_overrides: { 'acme:override-model': { input: 1, output: 0 } } as never };
+ withChatCallMeter(meter, () => recordChatUsage({ model: 'acme:override-model', usage: { input_tokens: 100, output_tokens: 0, cache_read_tokens: 60 } }));
+ expect(meter.cost_usd).toBeCloseTo(100 / 1e6, 12);
+ });
+});
diff --git a/test/claude-cli-recipe.test.ts b/test/claude-cli-recipe.test.ts
index a61cfa6943..b7e2401e0b 100644
--- a/test/claude-cli-recipe.test.ts
+++ b/test/claude-cli-recipe.test.ts
@@ -159,6 +159,8 @@ describe('claude-cli LanguageModel — text-only round trip', () => {
} as LanguageModelV2CallOptions);
expect(result.usage.cachedInputTokens).toBe(9001);
+ // AI SDK convention: the input total contains the cache read (12 uncached + 9001 read).
+ expect(result.usage.inputTokens).toBe(12 + 9001);
});
});
diff --git a/test/client-grants.test.ts b/test/client-grants.test.ts
index c5406d4074..824e115973 100644
--- a/test/client-grants.test.ts
+++ b/test/client-grants.test.ts
@@ -76,6 +76,20 @@ describe('client capability grants', () => {
expect(JSON.stringify(rows)).not.toContain('client_secret_hash');
});
+ test('new profile registration is full-surface and records the catalog its snapshot was written against', async () => {
+ const created = await memoryClient('provenance-audit-example');
+ const grant = await readClientGrant(engine, created.clientId);
+ expect(grant.surface).toBe('full');
+ expect(grant.surfaceSetBy).toBe('operator');
+ const [row] = await engine.executeRaw('SELECT after_grant FROM oauth_grant_audit WHERE client_id = $1', [created.clientId]);
+ const audit = row.after_grant as { allowedOperations: string[]; catalogProvenance: { version: number; operations: string[] } };
+ expect(audit.catalogProvenance.version).toBe(1);
+ expect(audit.catalogProvenance.operations).toEqual(expect.arrayContaining(audit.allowedOperations));
+ await rescopeClientGrant(engine, created.clientId, { tokenTtlSeconds: 7200 }, { actor: 'test' });
+ const rows = await engine.executeRaw('SELECT after_grant FROM oauth_grant_audit WHERE client_id = $1 ORDER BY id', [created.clientId]);
+ expect((rows[1].after_grant as Record<string, unknown>).catalogProvenance).toBeUndefined();
+ });
+
test('raw agent registration rejects incomplete or unavailable delegation before insert', async () => {
await expect(provider.registerClientManual('missing-bindings-example', ['client_credentials'], 'agent')).rejects.toThrow('delegated_tools_missing');
await expect(provider.registerClientManual('unknown-tools-example', ['client_credentials'], 'agent', [], 'default', undefined, undefined, {
@@ -136,7 +150,7 @@ describe('client capability grants', () => {
test('CAS rejects stale operators without changing grant or credential hash', async () => {
const created = await memoryClient('cas-example');
const before = await readClientGrant(engine, created.clientId);
- await rescopeClientGrant(engine, created.clientId, { surface: 'full' }, { actor: 'first', expectedRevision: before.revision });
+ await rescopeClientGrant(engine, created.clientId, { surface: 'starter' }, { actor: 'first', expectedRevision: before.revision });
await expect(rescopeClientGrant(engine, created.clientId, { scopes: ['admin'] }, { actor: 'stale', expectedRevision: before.revision })).rejects.toThrow('Grant changed');
const after = await readClientGrant(engine, created.clientId);
expect(after.scopes).toEqual(before.scopes);
@@ -209,7 +223,7 @@ describe('client capability grants', () => {
expect(changed.grant.profile).toBe('coding-agent');
expect(changed.grant.allowedOperations).toContain('put_page');
expect(changed.grant.boundSlugPrefixes).toEqual(['existing-example/']);
- expect(changed.grant.surface).toBe('starter');
+ expect(changed.grant.surface).toBe('full');
const cleared = await provisionHarnessGrant(engine, { ...input, profile: 'memory-writer', patch: { boundSlugPrefixes: null } }, 'test');
expect(cleared.grant.boundSlugPrefixes).toBeNull();
expect(cleared.grant.allowedOperations).toContain('remember');
diff --git a/test/codex-plugin-manifest.test.ts b/test/codex-plugin-manifest.test.ts
index e818019e79..6fe03f112b 100644
--- a/test/codex-plugin-manifest.test.ts
+++ b/test/codex-plugin-manifest.test.ts
@@ -3,7 +3,7 @@
*
* Mirrors test/openclaw-plugin-manifest.test.ts for the two new lanes:
* version lockstep across every plugin manifest, exact MCP declarations
- * (starter surface + --source-guard), launcher static AND behavioral
+ * (registration surface + --source-guard), launcher static AND behavioral
* invariants (every resolver branch), marketplace content-equivalence
* (codex reads BOTH marketplace formats — divergence would fork the
* install), curated-tree membership algebra, and the derived env_vars
@@ -15,6 +15,7 @@ import { readFileSync, readdirSync, existsSync, statSync, mkdtempSync, mkdirSync
import { join } from 'path';
import { tmpdir } from 'os';
import { spawnSync } from 'child_process';
+import { REGISTRATION_SURFACE } from '../src/core/mcp-registration.ts';
const ROOT = join(import.meta.dir, '..');
const read = (p: string) => readFileSync(join(ROOT, p), 'utf8');
@@ -30,7 +31,7 @@ const openclawPlugin = json('openclaw.plugin.json');
const lanes = json('skills/plugin-lanes.json');
const LAUNCHER = './.agents/gbrain-launcher';
-const EXPECTED_ARGS = ['serve', '--surface', 'starter', '--source-guard'];
+const EXPECTED_ARGS = ['serve', '--surface', 'full', '--source-guard'];
describe('version lockstep (the merge-drift catcher)', () => {
test('every plugin manifest ships at the repo version', () => {
@@ -314,8 +315,8 @@ describe('launcher (behavioral — every resolver branch, hermetic HOME)', () =>
test('(d) GBRAIN_SURFACE substitutes an existing --surface value', () => {
const { dir, stub } = stubDir();
try {
- const r = run({ GBRAIN_BIN: stub, GBRAIN_SURFACE: 'full' }, EXPECTED_ARGS, dir);
- expect(r.stdout.trim().split('\n')).toEqual(['serve', '--surface', 'full', '--source-guard']);
+ const r = run({ GBRAIN_BIN: stub, GBRAIN_SURFACE: 'starter' }, EXPECTED_ARGS, dir);
+ expect(r.stdout.trim().split('\n')).toEqual(['serve', '--surface', 'starter', '--source-guard']);
} finally {
rmSync(dir, { recursive: true, force: true });
}
@@ -393,19 +394,18 @@ describe('curated tree membership + scanner guard', () => {
// #5858: the generator's only frontmatter change is one `when_to_use:` line built from triggers.
const withoutWhenToUse = (text: string) => text.replace(/^when_to_use: .*\n/m, '');
- test('F6: a starter-gap skill ends with its CLI-equivalent surface note; a gap-free skill is byte-identical', () => {
- const gaps = lanes.starter_gaps as Record<string, string[]>;
- expect(Object.keys(gaps).length).toBeGreaterThan(0);
- for (const [slug, ops] of Object.entries(gaps)) {
+ // S0: the plugin serves REGISTRATION_SURFACE (full), so no bundled skill names
+ // an MCP op beyond it: the gap snapshot is empty and every lane skill ships
+ // byte-identical to its source (no "Tools outside your MCP surface" note).
+ test('F6 under the full registration surface: no starter gaps; every lane skill is byte-identical', () => {
+ expect(REGISTRATION_SURFACE).toBe('full');
+ expect(lanes.starter_gaps).toEqual({});
+ expect(laneSet.size).toBeGreaterThan(0);
+ for (const slug of laneSet) {
const generated = withoutWhenToUse(read(`plugin/skills/${slug}/SKILL.md`));
- expect(generated.startsWith(read(`skills/${slug}/SKILL.md`).replace(/\n*$/, '\n'))).toBe(true);
- expect(generated).toContain('## Tools outside your MCP surface');
- for (const op of ops) expect(generated).toMatch(new RegExp(`- \`${op}\` → \`gbrain [^\`]+\``));
- expect(generated).toContain('GBRAIN_SURFACE=full');
+ expect({ slug, identical: generated === read(`skills/${slug}/SKILL.md`) }).toEqual({ slug, identical: true });
+ expect(generated).not.toContain('## Tools outside your MCP surface');
}
- expect(read('plugin/skills/maintain/SKILL.md')).toContain('- `get_health` → `gbrain doctor --json`');
- const gapFree = [...laneSet].find(slug => !(slug in gaps))!;
- expect(withoutWhenToUse(read(`plugin/skills/${gapFree}/SKILL.md`))).toBe(read(`skills/${gapFree}/SKILL.md`));
});
test('non-skill dirs carry no SKILL.md (the scanner never grows a surprise skill)', () => {
@@ -497,9 +497,10 @@ describe('generator negative fixtures (a guard that cannot fail is not coverage)
});
test('a stale starter_gaps snapshot fails with the refresh instruction', () => {
- // beta declares a beyond-starter MCP op but the recorded snapshot is empty.
+ // The recorded snapshot names gaps the computed set cannot equal on any
+ // registration surface: on starter beta's gap is [add_link], on full none.
const root = fixtureRoot(
- { additions: { beta: 'a reason long enough to pass the length check' } },
+ { additions: { beta: 'a reason long enough to pass the length check' }, starter_gaps: { beta: ['add_link', 'sync_brain'] } },
['add_link'],
);
try {
diff --git a/test/cycle-embed-phase-warn.serial.test.ts b/test/cycle-embed-phase-warn.serial.test.ts
new file mode 100644
index 0000000000..44aba07210
--- /dev/null
+++ b/test/cycle-embed-phase-warn.serial.test.ts
@@ -0,0 +1,115 @@
+/**
+ * E-A (wave 0): the cycle's embed phase must not report `ok` when chunks
+ * could not be embedded.
+ *
+ * Protects: `runEmbedCore` counts pages it cannot embed (a blocked image page
+ * waiting for its importer, #6223/#6269) in `EmbedResult.failures`; the embed
+ * phase turns that into `warn` with the failure samples and the paid
+ * `embedBackfillFix` action, so the cycle reports `partial`. A single-flight
+ * skip (`lock_skipped`) is another backfill already running, not a failure,
+ * and stays `ok`. The autopilot daemon trips its breaker only on `failed`, so
+ * a permanently blocked page keeps the daemon cycling.
+ * Fails when: the phase ignores `failures` again (master returned `ok`).
+ *
+ * Named `.serial.test.ts`: configures the AI gateway and a fake embed
+ * transport for its whole lifecycle, which withEnv() can't wrap.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { installFixtureChunks } from './helpers/page-projection.ts';
+import { surfaceFileSource } from './helpers/source-surface.ts';
+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { runCycle } from '../src/core/cycle.ts';
+import * as embedModule from '../src/commands/embed.ts';
+
+const DIMS = 1536;
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: DIMS,
+ env: { ...process.env, OPENAI_API_KEY: 'sk-test-fake' },
+ });
+ __setEmbedTransportForTests(async ({ values }: { values: string[] }) => ({
+ embeddings: values.map(() => new Array(DIMS).fill(0.001)),
+ usage: { tokens: values.length * 4 },
+ } as never));
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 30000);
+
+afterAll(async () => {
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await resetPgliteState(engine);
+});
+
+async function stalePage(slug: string) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `Synthetic body for ${slug}.` });
+ await installFixtureChunks(engine, slug, [
+ { chunk_index: 0, chunk_text: `Synthetic body for ${slug}.`, chunk_source: 'compiled_truth' },
+ ]);
+}
+
+async function blockedImagePage(slug: string) {
+ await stalePage(slug);
+ await engine.executeRaw("UPDATE pages SET page_kind='image', text_projection_revision=NULL WHERE slug=$1", [slug]);
+}
+
+const embedCycle = () => runCycle(engine, { brainDir: null, phases: ['embed'] });
+
+describe('cycle embed phase reports embed failures (E-A)', () => {
+ test('a blocked image page beside stale chunks: phase warn, cycle partial, paid backfill fix', async () => {
+ await blockedImagePage('images/scan-0001');
+ await stalePage('notes/healthy');
+ const report = await embedCycle();
+ const phase = report.phases.find(p => p.phase === 'embed')!;
+ expect(phase.status).toBe('warn');
+ expect(report.status).toBe('partial');
+ expect(phase.details.embedded).toBe(1);
+ expect(phase.details.failures).toBe(1);
+ expect((phase.details.failure_samples as string[]).join(' ')).toContain('default:images/scan-0001');
+ expect(phase.summary).toContain('1 chunk(s) could not be embedded this run');
+ const fix = phase.details.fix as { argv: string[]; consent: string[]; verify: { argv: string[] } };
+ expect(fix.argv).toEqual(['gbrain', 'embed', '--stale', '--catch-up', '--yes']);
+ expect(fix.consent).toEqual(['paid']);
+ expect(fix.verify.argv).toEqual(['gbrain', 'doctor', '--only', 'embeddings', '--json']);
+ });
+
+ test('a clean drain stays ok with no fix', async () => {
+ await stalePage('notes/healthy');
+ const report = await embedCycle();
+ const phase = report.phases.find(p => p.phase === 'embed')!;
+ expect(phase.status).toBe('ok');
+ expect(phase.details.failures).toBe(0);
+ expect(phase.details.fix).toBeUndefined();
+ });
+
+ test('the autopilot daemon keeps cycling on partial: only failed trips its breaker', () => {
+ const src = surfaceFileSource('autopilot', 'src/commands/autopilot-daemon.ts');
+ const inline = src.slice(src.indexOf('const report = await cyclePromise'), src.indexOf("logError('cycle-inline'"));
+ expect(inline).toContain("if (report.status === 'failed') {\n cycleOk = false;");
+ expect(inline.match(/cycleOk = false/g)?.length).toBe(1);
+ expect(inline).not.toMatch(/status\s*(===|!==)\s*'partial'/);
+ });
+
+ // Last in the file: mock.module replaces the embed module for the rest of
+ // this process (one Bun process per serial file).
+ test('lock_skipped (another backfill holds the source) stays ok', async () => {
+ const lockSkipped: embedModule.EmbedResult = { embedded: 0, skipped: 0, would_embed: 0, total_chunks: 0, pages_processed: 0,
+ failures: 1, failure_samples: ['another backfill is already running'], dryRun: false, chunkless_pages_healed: 0, lock_skipped: true };
+ mock.module('../src/commands/embed.ts', () => ({ ...embedModule, runEmbedCore: async () => lockSkipped }));
+ const report = await embedCycle();
+ const phase = report.phases.find(p => p.phase === 'embed')!;
+ expect(phase.status).toBe('ok');
+ expect(phase.details.fix).toBeUndefined();
+ expect(phase.details.failure_samples).toBeUndefined();
+ });
+});
diff --git a/test/doctor-embedding-backlog.test.ts b/test/doctor-embedding-backlog.test.ts
index bf6d352a47..dfee414b81 100644
--- a/test/doctor-embedding-backlog.test.ts
+++ b/test/doctor-embedding-backlog.test.ts
@@ -12,24 +12,51 @@
* goldens only pin the fully embedded case.
* A keyless brain reports "not applicable" instead of a paid fix.
* Seam: none (a stub engine answering getHealth and getConfig).
+ *
+ * Backlog age (E-B): a large backlog (over 1,000 chunks or 1%) warns only when
+ * its oldest pending chunk has waited longer than EMBEDDING_BACKLOG_MAX_AGE_S,
+ * read from content_chunks.embedding_pending_since, never created_at.
+ * Fails when: the check ages the backlog from created_at (an edited old page
+ * or a model swap reads as a months-old backlog and asks for paid spend on a
+ * brain draining normally), or goes back to "ok at >= 90% coverage whatever
+ * the backlog" (forced probe: 136,314 chunks missing at 90% read ok on master).
+ * The stub probes answer the age query through executeRaw; the PGLite probes
+ * run the real write paths that set and clear the column.
*/
-import { describe, expect, test } from 'bun:test';
-import { embeddingsEntry } from '../src/commands/doctor/checks/schema-health.ts';
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { EMBEDDING_BACKLOG_MAX_AGE_S, embeddingsEntry } from '../src/commands/doctor/checks/schema-health.ts';
import type { DoctorContext } from '../src/commands/doctor/context.ts';
import type { Check } from '../src/commands/doctor.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { invalidateStaleSignatureEmbeddingsGuarded } from '../src/core/embedding-invalidation.ts';
+import { runSchemaTransition } from '../src/core/embedding-migration.ts';
+import { runMigrations } from '../src/core/migrate.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { installFixtureChunks } from './helpers/page-projection.ts';
async function runCheck(ctx: DoctorContext): Promise<Check[]> {
return await embeddingsEntry.run(ctx) as Check[];
}
-function ctxFor(coverage: number, missing: number, config: Record<string, string> = {}): DoctorContext {
+function ctxFor(coverage: number, missing: number, config: Record<string, string> = {}, age?: PendingAge): DoctorContext {
const engine = {
getHealth: async () => ({ embed_coverage: coverage, missing_embeddings: missing }),
getConfig: async (key: string) => config[key] ?? null,
+ ...(age ? {
+ executeRaw: async (sql: string) => sql.includes('embedding_pending_since')
+ ? [{ age_s: age.ageS, unaged: age.unaged ?? 0, backfilled: age.backfilled ?? false }]
+ : [],
+ } : {}),
};
return { engine, progress: { heartbeat() {} } } as unknown as DoctorContext;
}
+/** What the age query answers: the oldest pending chunk's wait, unstamped pending rows, backfill label. */
+interface PendingAge { ageS: number | null; unaged?: number; backfilled?: boolean }
+
+const HOUR = 3600;
+const DAY = 24 * HOUR;
+
describe('embeddings doctor check: backlog', () => {
test('a large backlog warns with the count and the catch-up command', async () => {
const [check] = await runCheck(ctxFor(0.002, 51_910));
@@ -62,6 +89,193 @@ describe('embeddings doctor check: backlog', () => {
test('a fully embedded brain keeps its message and carries no backlog', async () => {
const [check] = await runCheck(ctxFor(1, 0));
- expect(check).toEqual({ name: 'embeddings', status: 'ok', message: '100% coverage, 0 missing' });
+ expect(check).toEqual({ name: 'embeddings', status: 'ok', message: '100% coverage, 0 missing',
+ details: { backlog: 0, oldest_pending_age_s: null, age_threshold_s: EMBEDDING_BACKLOG_MAX_AGE_S } });
+ });
+});
+
+describe('embeddings doctor check: backlog age', () => {
+ test('95% coverage with 50k missing and an old pending chunk warns, with backlog and age in details', async () => {
+ const [check] = await runCheck(ctxFor(0.95, 50_000, {}, { ageS: 3 * DAY }));
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('Backlog: 50000 chunk(s) without embeddings');
+ expect(check.message).toContain('Oldest pending chunk has waited 3d');
+ expect(check.details).toMatchObject({ code: 'embedding_backlog', backlog: 50_000, oldest_pending_age_s: 3 * DAY,
+ age_threshold_s: EMBEDDING_BACKLOG_MAX_AGE_S, fix: 'gbrain embed --stale --catch-up' });
+ expect(check.fix?.consent).toEqual(['paid']);
+ expect(check.fix?.argv).toEqual(['gbrain', 'embed', '--stale', '--catch-up', '--yes']);
+ });
+
+ test('forced probe: 136,314 chunks missing at 90% coverage for days warns (ok on master)', async () => {
+ const [check] = await runCheck(ctxFor(0.9, 136_314, {}, { ageS: 9 * DAY }));
+ expect(check.status).toBe('warn');
+ expect(check.details).toMatchObject({ backlog: 136_314, oldest_pending_age_s: 9 * DAY });
+ });
+
+ test('the audited production shape (89%, 136,314 missing, days old) warns', async () => {
+ const [check] = await runCheck(ctxFor(0.893, 136_314, {}, { ageS: 9 * DAY }));
+ expect(check.status).toBe('warn');
+ });
+
+ test('a fresh brain mid-drain stays ok and still reports backlog, age and threshold', async () => {
+ const [check] = await runCheck(ctxFor(0.5, 40_000, {}, { ageS: 2 * HOUR }));
+ expect(check.status).toBe('ok');
+ expect(check.message).toContain('Backlog: 40000 chunk(s)');
+ expect(check.details).toMatchObject({ backlog: 40_000, oldest_pending_age_s: 2 * HOUR, age_threshold_s: EMBEDDING_BACKLOG_MAX_AGE_S });
+ expect(check.fix?.consent).toEqual(['paid']);
+ });
+
+ test('an old backlog under both size floors stays ok', async () => {
+ const [check] = await runCheck(ctxFor(0.9995, 500, {}, { ageS: 30 * DAY }));
+ expect(check.status).toBe('ok');
+ expect(check.details).toMatchObject({ backlog: 500, oldest_pending_age_s: 30 * DAY });
+ });
+
+ test('a small brain mostly missing for days warns on the 1% floor', async () => {
+ const [check] = await runCheck(ctxFor(0.2, 400, {}, { ageS: 2 * DAY }));
+ expect(check.status).toBe('warn');
+ });
+
+ test('an age backfilled from created_at is labelled as such', async () => {
+ const [check] = await runCheck(ctxFor(0.95, 50_000, {}, { ageS: 40 * DAY, backfilled: true }));
+ expect(check.status).toBe('warn');
+ expect(check.details).toMatchObject({ age_source: 'created_at_backfill' });
+ expect(check.message).toContain('backfilled from its creation time');
+ });
+
+ test('pending chunks without a stamp leave the age unknown and the coverage rule decides', async () => {
+ const low = (await runCheck(ctxFor(0.5, 40_000, {}, { ageS: 2 * HOUR, unaged: 3 })))[0];
+ expect(low.status).toBe('warn');
+ expect(low.details).toMatchObject({ backlog: 40_000, oldest_pending_age_s: null, age_threshold_s: EMBEDDING_BACKLOG_MAX_AGE_S });
+ const high = (await runCheck(ctxFor(0.95, 50_000, {}, { ageS: null })))[0];
+ expect(high.status).toBe('ok');
+ });
+
+ test('a keyless brain is info even with an old backlog', async () => {
+ const [check] = await runCheck(ctxFor(0, 50_000, { embedding_disabled: 'true' }, { ageS: 90 * DAY }));
+ expect(check.status).toBe('ok');
+ expect(check.severity).toBe('info');
+ expect(check.readiness_state).toBe('disabled_by_choice');
+ expect(check.fix?.consent ?? []).not.toContain('paid');
+ });
+});
+
+describe('embeddings doctor check: pending age on a real brain [pglite]', () => {
+ let engine: PGLiteEngine;
+ let dims = 0;
+ const MODEL = 'openai:text-embedding-3-large';
+
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ }, 60_000);
+
+ afterAll(async () => {
+ await engine.disconnect();
+ });
+
+ beforeEach(async () => {
+ await resetPgliteState(engine);
+ const rows = await engine.executeRaw<{ dim: number }>(
+ `SELECT atttypmod AS dim FROM pg_attribute WHERE attrelid = 'content_chunks'::regclass AND attname = 'embedding' AND attnum > 0`);
+ dims = Number(rows[0]?.dim);
+ });
+
+ const doctor = async () => (await runCheck({ engine, progress: { heartbeat() {} } } as unknown as DoctorContext))[0];
+ const vector = () => { const v = new Float32Array(dims); v[0] = 1; return v; };
+
+ /** One sealed page per slug, its chunk embedded through the real upsert, created 90 days ago. */
+ async function seedEmbeddedPages(slugs: string[]): Promise<void> {
+ for (const slug of slugs) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `# ${slug}` });
+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_text: `${slug} body`, chunk_source: 'compiled_truth', model: MODEL }]);
+ await engine.upsertChunks(slug, [{ chunk_index: 0, chunk_text: `${slug} body`, chunk_source: 'compiled_truth', embedding: vector(), model: MODEL }]);
+ }
+ await engine.executeRaw(`UPDATE content_chunks SET created_at = now() - interval '90 days'`);
+ }
+
+ test('an embedded chunk carries no pending stamp; a fresh insert without a vector does', async () => {
+ await seedEmbeddedPages(['notes/embedded-alice-example']);
+ await engine.putPage('notes/fresh-alice-example', { type: 'note', title: 'fresh', compiled_truth: '# fresh' });
+ await installFixtureChunks(engine, 'notes/fresh-alice-example', [{ chunk_index: 0, chunk_text: 'fresh body', chunk_source: 'compiled_truth' }]);
+ const rows = await engine.executeRaw<{ slug: string; pending: boolean }>(
+ `SELECT p.slug, cc.embedding_pending_since IS NOT NULL AS pending FROM content_chunks cc JOIN pages p ON p.id = cc.page_id ORDER BY p.slug`);
+ expect(rows.map(r => [r.slug, r.pending])).toEqual([['notes/embedded-alice-example', false], ['notes/fresh-alice-example', true]]);
+ });
+
+ test('a fresh brain mid-drain stays ok', async () => {
+ for (const slug of ['notes/a-alice-example', 'notes/b-alice-example', 'notes/c-alice-example']) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `# ${slug}` });
+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_text: `${slug} body`, chunk_source: 'compiled_truth' }]);
+ }
+ await engine.upsertChunks('notes/a-alice-example', [{ chunk_index: 0, chunk_text: 'notes/a-alice-example body', chunk_source: 'compiled_truth', embedding: vector(), model: MODEL }]);
+ const check = await doctor();
+ expect(check.status).toBe('ok');
+ expect(check.details).toMatchObject({ backlog: 2, age_threshold_s: EMBEDDING_BACKLOG_MAX_AGE_S });
+ expect((check.details as { oldest_pending_age_s: number }).oldest_pending_age_s).toBeLessThan(HOUR);
+ });
+
+ test('an edited old page stays ok: its wait starts when the edit cleared the vector, not at created_at', async () => {
+ await seedEmbeddedPages(['notes/edited-alice-example']);
+ expect((await doctor()).details).toMatchObject({ backlog: 0 });
+ await engine.upsertChunks('notes/edited-alice-example', [{ chunk_index: 0, chunk_text: 'edited body', chunk_source: 'compiled_truth' }]);
+ const check = await doctor();
+ expect(check.status).toBe('ok');
+ expect(check.details).toMatchObject({ backlog: 1 });
+ expect((check.details as { oldest_pending_age_s: number }).oldest_pending_age_s).toBeLessThan(HOUR);
+ await engine.executeRaw(`UPDATE content_chunks SET embedding_pending_since = now() - interval '2 days'`);
+ expect((await doctor()).status).toBe('warn');
+ });
+
+ test('a model-swap invalidation actively draining stays ok', async () => {
+ await seedEmbeddedPages(['notes/swap-a-alice-example', 'notes/swap-b-alice-example']);
+ const invalidated = await invalidateStaleSignatureEmbeddingsGuarded(engine, { signature: `voyage:voyage-4:${dims}`, includeNullSignature: true });
+ expect(invalidated).toBe(2);
+ let check = await doctor();
+ expect(check.status).toBe('ok');
+ expect(check.details).toMatchObject({ backlog: 2 });
+ expect((check.details as { oldest_pending_age_s: number }).oldest_pending_age_s).toBeLessThan(HOUR);
+ await engine.upsertChunks('notes/swap-a-alice-example', [{ chunk_index: 0, chunk_text: 'notes/swap-a-alice-example body', chunk_source: 'compiled_truth', embedding: vector(), model: MODEL }]);
+ check = await doctor();
+ expect(check.status).toBe('ok');
+ expect(check.details).toMatchObject({ backlog: 1 });
+ });
+
+ test('the migration backfills chunks already missing a vector to created_at once, and doctor labels that age', async () => {
+ await seedEmbeddedPages(['notes/backfill-embedded-alice-example']);
+ await engine.putPage('notes/backfill-pending-alice-example', { type: 'note', title: 'pending', compiled_truth: '# pending' });
+ await installFixtureChunks(engine, 'notes/backfill-pending-alice-example', [{ chunk_index: 0, chunk_text: 'pending body', chunk_source: 'compiled_truth' }]);
+ await engine.executeRaw(`UPDATE content_chunks SET embedding_pending_since = NULL, created_at = now() - interval '40 days'`);
+ await engine.executeRaw(`DELETE FROM config WHERE key = 'embedding_pending_since_backfilled_at'`);
+ await engine.setConfig('version', '219');
+ await runMigrations(engine);
+ const rows = await engine.executeRaw<{ slug: string; backfilled: boolean | null }>(
+ `SELECT p.slug, cc.embedding_pending_since = cc.created_at AS backfilled FROM content_chunks cc JOIN pages p ON p.id = cc.page_id ORDER BY p.slug`);
+ expect(rows.map(r => [r.slug, r.backfilled])).toEqual([['notes/backfill-embedded-alice-example', null], ['notes/backfill-pending-alice-example', true]]);
+ const stamp = await engine.getConfig('embedding_pending_since_backfilled_at');
+ expect(stamp).not.toBeNull();
+ const check = await doctor();
+ expect(check.status).toBe('warn');
+ expect(check.details).toMatchObject({ backlog: 1, age_source: 'created_at_backfill' });
+ await engine.setConfig('version', '219');
+ await runMigrations(engine);
+ expect(await engine.getConfig('embedding_pending_since_backfilled_at')).toBe(stamp);
+ });
+
+ test('a column rebuild stamps every chunk it emptied, keeping an older pending stamp', async () => {
+ await seedEmbeddedPages(['notes/rebuilt-alice-example']);
+ await engine.putPage('notes/waiting-alice-example', { type: 'note', title: 'waiting', compiled_truth: '# waiting' });
+ await installFixtureChunks(engine, 'notes/waiting-alice-example', [{ chunk_index: 0, chunk_text: 'waiting body', chunk_source: 'compiled_truth' }]);
+ await engine.executeRaw(`UPDATE content_chunks SET embedding_pending_since = now() - interval '3 days' WHERE embedding IS NULL`);
+ await runSchemaTransition(engine, dims === 512 ? 256 : 512);
+ const rows = await engine.executeRaw<{ slug: string; waited_s: number; stamped_at_null: boolean }>(
+ `SELECT p.slug, EXTRACT(EPOCH FROM now() - cc.embedding_pending_since)::float8 AS waited_s,
+ cc.embedded_at IS NULL AS stamped_at_null
+ FROM content_chunks cc JOIN pages p ON p.id = cc.page_id ORDER BY p.slug`);
+ expect(rows.map(r => r.slug)).toEqual(['notes/rebuilt-alice-example', 'notes/waiting-alice-example']);
+ expect(rows.every(r => r.stamped_at_null)).toBe(true);
+ expect(Number(rows[0].waited_s)).toBeLessThan(HOUR);
+ expect(Number(rows[1].waited_s)).toBeGreaterThan(2 * DAY);
});
});
diff --git a/test/doctor-grant-new-ops.test.ts b/test/doctor-grant-new-ops.test.ts
new file mode 100644
index 0000000000..a1fa6a7ba5
--- /dev/null
+++ b/test/doctor-grant-new-ops.test.ts
@@ -0,0 +1,177 @@
+/**
+ * D4 `grant_new_ops_available` doctor check: grants that cannot call operations
+ * their scopes allow, with proven blockers kept apart from inferred grant age.
+ * The fix asks the user, carries rescope commands that differ by credential
+ * type, never defaults to `--operations all`, and changes nothing itself.
+ *
+ * PGLite in-memory ($0).
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { readClientGrant, rescopeClientGrant, resolveGrantProfile } from '../src/core/grants/service.ts';
+import { parseClientRescopeArgs, splitRescopeTarget } from '../src/core/grants/cli.ts';
+import { parseRescopeTokenArgs } from '../src/core/grants/legacy-token.ts';
+import { mintLegacyToken } from '../src/core/token-mint.ts';
+import { checkGrantNewOps, grantNewOpsEntry } from '../src/commands/doctor/checks/grant-new-ops.ts';
+import { legacyTokenGrantsEntry } from '../src/commands/doctor/checks/legacy-token-grants.ts';
+import { DOCTOR_CHECK_REGISTRY } from '../src/commands/doctor/registry.ts';
+import { categorizeCheck } from '../src/core/doctor-categories.ts';
+import { cliRenderContext, deriveNext, type Action } from '../src/core/agent-output.ts';
+
+let engine: PGLiteEngine;
+let provider: GBrainOAuthProvider;
+const cfg = { engine: 'pglite' } as any;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+}, 60_000);
+afterAll(async () => { await engine?.disconnect(); }, 15_000);
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM oauth_grant_audit');
+ await engine.executeRaw('DELETE FROM oauth_clients');
+ await engine.executeRaw('DELETE FROM access_tokens');
+});
+
+const writerProfile = () => resolveGrantProfile({ profile: 'memory-writer', sourceId: 'default' });
+
+/** The shape every pre-D4 memory-writer has: operator-pinned starter, a snapshot without put_pages, no catalog provenance. */
+async function legacyWriter(name: string): Promise<string> {
+ const profile = writerProfile();
+ const created = await provider.registerClientManual(name, ['client_credentials'], 'read write', [], 'default', undefined, undefined, undefined,
+ { ...profile, surface: 'starter', allowedOperations: profile.allowedOperations!.filter(op => op !== 'put_pages') });
+ await engine.executeRaw("UPDATE oauth_grant_audit SET after_grant = after_grant - 'catalogProvenance' WHERE client_id = $1", [created.clientId]);
+ return created.clientId;
+}
+
+type Finding = { kind: string; id: string; name: string; blockers: any[]; grant_age: any; preview_argv: string[]; argv: string[]; all_operations_argv: string[]; excluded_operations: any };
+const grants = (details: Record<string, unknown> | undefined) => (details?.grants ?? []) as Finding[];
+
+describe('grant_new_ops_available', () => {
+ test('a brain without grants, or with only fresh full-surface grants, is ok', async () => {
+ expect((await checkGrantNewOps(engine, { cfg })).status).toBe('ok');
+ await provider.registerClientManual('fresh-writer', ['client_credentials'], 'read write', [], 'default', undefined, undefined, undefined, writerProfile());
+ const check = await checkGrantNewOps(engine, { cfg });
+ expect(check.status).toBe('ok');
+ expect(check.fix).toBeUndefined();
+ expect(categorizeCheck('grant_new_ops_available')).toBe('ops');
+ });
+
+ test('an operator-pinned old client is reported with both blockers and intent unknown, and is not widened', async () => {
+ const clientId = await legacyWriter('old-writer');
+ const before = await readClientGrant(engine, clientId);
+ const check = await checkGrantNewOps(engine, { cfg });
+ expect(check.status).toBe('warn');
+ const [f] = grants(check.details);
+ expect(f).toMatchObject({ kind: 'oauth_client', id: clientId, name: 'old-writer' });
+ expect(f.blockers.map(b => b.blocker)).toEqual(['operation_snapshot', 'client_pin']);
+ expect(f.blockers[0]).toEqual({ blocker: 'operation_snapshot', excluded_count: 1 });
+ expect(f.blockers[1]).toMatchObject({ blocker: 'client_pin', surface: 'starter', set_by: 'operator' });
+ expect(f.excluded_operations.operation_snapshot).toEqual(['put_pages']);
+ expect(f.grant_age).toEqual({ state: 'intent_unknown', excluded_count: 1,
+ statement: "This grant's snapshot excludes 1 currently eligible operation; original intent unknown." });
+ expect(check.message).toContain('original intent unknown');
+ expect(check.message).not.toContain('predates');
+ expect(await readClientGrant(engine, clientId)).toEqual(before);
+ });
+
+ test('client argv: an explicit --operations list plus --surface full, previewed with --dry-run, that the client parser accepts', async () => {
+ const clientId = await legacyWriter('argv-writer');
+ const snapshot = (await readClientGrant(engine, clientId)).allowedOperations!;
+ const [f] = grants((await checkGrantNewOps(engine, { cfg })).details);
+ const list = [...snapshot, 'put_pages'].sort().join(',');
+ expect(f.preview_argv).toEqual(['gbrain', 'auth', 'rescope', '--client', clientId, '--operations', list, '--surface', 'full', '--dry-run']);
+ expect(f.argv).toEqual(f.preview_argv.slice(0, -1));
+ const target = splitRescopeTarget(f.preview_argv.slice(3));
+ expect(target).toMatchObject({ kind: 'client', clientId });
+ const parsed = parseClientRescopeArgs(clientId, (target as { args: string[] }).args);
+ expect(parsed.dryRun).toBe(true);
+ expect(parsed.patch.allowedOperations).toContain('put_pages');
+ expect(parsed.patch.surface).toBe('full');
+ });
+
+ test('token argv: --refresh-operations preview, then --add put_pages; it differs from the client argv', async () => {
+ const ops = writerProfile().allowedOperations!.filter(op => op !== 'put_pages');
+ await mintLegacyToken(engine, { name: 'old-token', scopes: ['read', 'write'], takesHolders: ['world'], allowedOperations: ops });
+ const clientId = await legacyWriter('pair-writer');
+ const found = grants((await checkGrantNewOps(engine, { cfg })).details);
+ const token = found.find(f => f.kind === 'legacy_token')!;
+ const client = found.find(f => f.id === clientId)!;
+ expect(token.preview_argv).toEqual(['gbrain', 'auth', 'rescope', '--token', 'old-token', '--refresh-operations']);
+ expect(token.argv).toEqual(['gbrain', 'auth', 'rescope', '--token', 'old-token', '--refresh-operations', '--add', 'put_pages']);
+ expect(token.argv).not.toContain('--client');
+ expect(client.argv).not.toContain('--refresh-operations');
+ expect(token.blockers).toEqual([{ blocker: 'operation_snapshot', excluded_count: 1 }]);
+ expect(token.grant_age.state).toBe('intent_unknown');
+ const parsed = parseRescopeTokenArgs(token.argv.slice(4));
+ expect(parsed.refreshOperations).toBe(true);
+ expect(parsed.add).toEqual(['put_pages']);
+ });
+
+ test('duplicate token names fall back to the row id', async () => {
+ const ops = writerProfile().allowedOperations!.filter(op => op !== 'put_pages');
+ const first = await mintLegacyToken(engine, { name: 'twin-token', scopes: ['read', 'write'], takesHolders: ['world'], allowedOperations: ops });
+ await mintLegacyToken(engine, { name: 'twin-token', scopes: ['read', 'write'], takesHolders: ['world'], allowedOperations: ops });
+ const found = grants((await checkGrantNewOps(engine, { cfg })).details);
+ expect(found.find(f => f.id === first.id)!.preview_argv).toEqual(['gbrain', 'auth', 'rescope', '--id', first.id, '--refresh-operations']);
+ });
+
+ test('the fix asks the user, previews first, and never defaults to --operations all', async () => {
+ await legacyWriter('fix-writer');
+ const check = await checkGrantNewOps(engine, { cfg });
+ const fix = check.fix as Action;
+ expect(deriveNext(fix, cliRenderContext())).toBe('ask_user');
+ expect(fix.preview_argv).toContain('--dry-run');
+ expect(fix.argv).not.toContain('all');
+ expect(fix.preview_argv).not.toContain('all');
+ const [f] = grants(check.details);
+ expect(f.all_operations_argv).toEqual(['gbrain', 'auth', 'rescope', '--client', f.id, '--operations', 'all', '--surface', 'full', '--dry-run']);
+ expect(fix.user_message).toContain('including ones later upgrades add');
+ expect(check.message).toContain('not the default repair');
+ });
+
+ test('two identically shaped grants get identical output and the same uncertainty', async () => {
+ const a = await legacyWriter('shape-a');
+ const b = await legacyWriter('shape-b');
+ const found = grants((await checkGrantNewOps(engine, { cfg })).details);
+ const strip = (f: Finding) => JSON.parse(JSON.stringify(f).replaceAll(f.id, '<ID>').replaceAll(f.name, '<NAME>'));
+ const fa = found.find(f => f.id === a)!;
+ const fb = found.find(f => f.id === b)!;
+ expect(strip(fa)).toEqual(strip(fb));
+ expect(fa.grant_age.state).toBe('intent_unknown');
+ });
+
+ test('post-D4 wording: a snapshot written with provenance says which operations it predates', async () => {
+ const created = await provider.registerClientManual('new-writer', ['client_credentials'], 'read write', [], 'default', undefined, undefined, undefined, writerProfile());
+ const minted = await readClientGrant(engine, created.clientId);
+ await rescopeClientGrant(engine, created.clientId, { allowedOperations: minted.allowedOperations!.filter(op => op !== 'put_pages') }, { actor: 'test' });
+ let [f] = grants((await checkGrantNewOps(engine, { cfg })).details);
+ expect(f.grant_age).toMatchObject({ state: 'provenance_recorded', predates_count: 0, excluded_at_snapshot_count: 1 });
+ expect(f.blockers).toEqual([{ blocker: 'operation_snapshot', excluded_count: 1 }]);
+ await engine.executeRaw(`UPDATE oauth_grant_audit SET after_grant = jsonb_set(after_grant, '{catalogProvenance,operations}', (after_grant->'catalogProvenance'->'operations') - 'put_pages')
+ WHERE client_id = $1 AND after_grant->'catalogProvenance' IS NOT NULL`, [created.clientId]);
+ const check = await checkGrantNewOps(engine, { cfg });
+ [f] = grants(check.details);
+ expect(f.grant_age).toMatchObject({ state: 'provenance_recorded', predates_count: 1, excluded_at_snapshot_count: 0 });
+ expect(check.message).toContain('This grant predates 1 currently eligible operation');
+ });
+
+ test('a restricted reader is not offered write operations', async () => {
+ const reader = resolveGrantProfile({ profile: 'memory-reader', sourceId: 'default' });
+ await provider.registerClientManual('restricted-reader', ['client_credentials'], 'read', [], 'default', undefined, undefined, undefined, { ...reader, surface: 'starter' });
+ const [f] = grants((await checkGrantNewOps(engine, { cfg })).details);
+ expect(f.blockers[0]).toEqual({ blocker: 'scope', missing_scopes: ['write'] });
+ expect([...f.excluded_operations.client_pin, ...f.excluded_operations.operation_snapshot]).not.toContain('put_pages');
+ });
+
+ test('registered after the legacy token checks', () => {
+ const index = DOCTOR_CHECK_REGISTRY.indexOf(grantNewOpsEntry);
+ expect(index).toBeGreaterThan(-1);
+ expect(DOCTOR_CHECK_REGISTRY[index - 1]).toBe(legacyTokenGrantsEntry);
+ expect(grantNewOpsEntry.emits).toEqual(['grant_new_ops_available']);
+ });
+});
diff --git a/test/e2e/client-grants.test.ts b/test/e2e/client-grants.test.ts
index cedde87d31..0334dece13 100644
--- a/test/e2e/client-grants.test.ts
+++ b/test/e2e/client-grants.test.ts
@@ -10,6 +10,7 @@ import { PostgresEngine } from '../../src/core/postgres-engine.ts';
import { GBrainOAuthProvider } from '../../src/core/oauth-provider.ts';
import { sqlQueryForEngine } from '../../src/core/sql-query.ts';
import { readClientGrant, rescopeClientGrant, resolveGrantProfile } from '../../src/core/grants/service.ts';
+import { checkGrantNewOps } from '../../src/commands/doctor/checks/grant-new-ops.ts';
import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
import { keylessBrainEnv } from '../helpers/provider-env.ts';
@@ -19,7 +20,7 @@ const port = 19937;
const base = `http://127.0.0.1:${port}`;
suite('client capability grants — Postgres and admin HTTP', () => {
let engine: PostgresEngine; let home: string; let server: ChildProcess | undefined; let cookie = '';
- const clients: string[] = []; const jobs: number[] = []; const sources: string[] = [];
+ const clients: string[] = []; const jobs: number[] = []; const sources: string[] = []; const pagesWritten: string[] = [];
const adminToken = 'grant-admin-test-' + randomUUID().replaceAll('-', '');
beforeAll(async () => {
assertSafeE2eDatabaseUrl(databaseUrl!);
@@ -46,6 +47,7 @@ suite('client capability grants — Postgres and admin HTTP', () => {
}
if (engine) {
for (const id of jobs) await engine.executeRaw('DELETE FROM minion_jobs WHERE id = $1', [id]);
+ for (const slug of pagesWritten) await engine.executeRaw('DELETE FROM pages WHERE slug = $1', [slug]);
for (const id of clients) { await engine.executeRaw('DELETE FROM oauth_grant_audit WHERE client_id = $1', [id]); await engine.executeRaw('DELETE FROM oauth_clients WHERE client_id = $1', [id]); }
for (const id of sources) await engine.executeRaw('DELETE FROM sources WHERE id = $1', [id]);
await engine.disconnect();
@@ -133,6 +135,80 @@ suite('client capability grants — Postgres and admin HTTP', () => {
expect(listed.fix.argv.slice(0, 6)).toEqual(['gbrain', 'auth', 'rescope', '--client', created.clientId, '--operations']);
});
+ // D4: new profile grants are callable on the full surface; old pinned grants are reported, never widened.
+ const clientToken = async (clientId: string, clientSecret: string): Promise<string> => {
+ const response = await fetch(base + '/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: new URLSearchParams({ grant_type: 'client_credentials', client_id: clientId, client_secret: clientSecret }) });
+ expect(response.status).toBe(200);
+ return (await response.json() as any).access_token;
+ };
+ const callTool = async (token: string, name: string, args: Record<string, unknown>): Promise<{ isError: boolean; text: string }> => {
+ const response = await fetch(base + '/mcp', { method: 'POST',
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }) });
+ const raw = await response.text();
+ const data = raw.split('\n').find(line => line.startsWith('data:'));
+ const rpc = JSON.parse(data ? data.slice(5) : raw);
+ if (rpc.error) return { isError: true, text: JSON.stringify(rpc.error) };
+ return { isError: rpc.result?.isError === true, text: (rpc.result?.content ?? []).map((b: any) => b?.text ?? '').join('\n') };
+ };
+ const onePage = (slug: string) => ({ pages: [{ slug, content: `---\ntitle: ${slug}\n---\nD4 bulk write fixture.\n` }], request_id: randomUUID() });
+ const whoamiDiagnosis = async (token: string) => JSON.parse((await callTool(token, 'whoami', {})).text).grant_diagnosis;
+
+ test('D4: a fresh memory-writer registered through the admin API calls put_pages', async () => {
+ const registration = await post('/admin/api/register-client', { name: 'd4-writer-' + randomUUID(), profile: 'memory-writer', sourceId: 'default' });
+ expect(registration.status).toBe(200);
+ const created = await registration.json() as any; clients.push(created.clientId);
+ expect((await readClientGrant(engine, created.clientId)).surface).toBe('full');
+ const token = await clientToken(created.clientId, created.clientSecret);
+ const slug = 'wiki/d4-bulk-' + randomUUID().slice(0, 8); pagesWritten.push(slug);
+ const result = await callTool(token, 'put_pages', onePage(slug));
+ expect(result.text).not.toContain('unknown_tool');
+ expect(result.text).not.toContain('permission_denied');
+ expect(result.isError).toBe(false);
+ expect((await whoamiDiagnosis(token)).blockers).toEqual([]);
+ });
+
+ test('D4: an operator-pinned old client is reported, not widened, and still refused', async () => {
+ const old = await new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine) }).registerClientManual('d4-old-' + randomUUID(), ['client_credentials'], 'read write', [], 'default', undefined, undefined, undefined,
+ { ...resolveGrantProfile({ profile: 'memory-writer', sourceId: 'default' }), surface: 'starter' });
+ clients.push(old.clientId);
+ const before = await readClientGrant(engine, old.clientId);
+ const token = await clientToken(old.clientId, old.clientSecret!);
+ const refused = await callTool(token, 'put_pages', onePage('wiki/d4-refused-' + randomUUID().slice(0, 8)));
+ expect(refused.isError).toBe(true);
+ const diagnosis = await whoamiDiagnosis(token);
+ expect(diagnosis.blockers).toEqual([expect.objectContaining({ blocker: 'client_pin', surface: 'starter', set_by: 'operator' })]);
+ expect(diagnosis.fix.argv).toEqual(['gbrain', 'auth', 'rescope', '--client', old.clientId, '--surface', 'full', '--dry-run']);
+ expect(JSON.stringify(diagnosis)).not.toContain('put_pages');
+ const check = await checkGrantNewOps(engine, { cfg: null });
+ const finding = ((check.details?.grants ?? []) as any[]).find(g => g.id === old.clientId);
+ expect(finding.blockers.map((b: any) => b.blocker)).toEqual(['client_pin']);
+ expect(finding.excluded_operations.client_pin).toContain('put_pages');
+ expect(await readClientGrant(engine, old.clientId)).toEqual(before);
+ expect((await callTool(token, 'put_pages', onePage('wiki/d4-still-refused-' + randomUUID().slice(0, 8)))).isError).toBe(true);
+ });
+
+ test('D4: a deliberately restricted writer and a memory-reader stay unable to call put_pages, and whoami says why', async () => {
+ const writer = await post('/admin/api/register-client', { name: 'd4-restricted-' + randomUUID(), profile: 'memory-writer', sourceId: 'default' });
+ const restricted = await writer.json() as any; clients.push(restricted.clientId);
+ const grant = await readClientGrant(engine, restricted.clientId);
+ await rescopeClientGrant(engine, restricted.clientId, { allowedOperations: grant.allowedOperations!.filter(op => op !== 'put_pages') }, { actor: 'test', expectedRevision: grant.revision });
+ const restrictedToken = await clientToken(restricted.clientId, restricted.clientSecret);
+ expect((await callTool(restrictedToken, 'put_pages', onePage('wiki/d4-restricted-' + randomUUID().slice(0, 8)))).isError).toBe(true);
+ const restrictedDiagnosis = await whoamiDiagnosis(restrictedToken);
+ expect(restrictedDiagnosis.blockers).toEqual([{ blocker: 'operation_snapshot', excluded_count: 1 }]);
+ expect(restrictedDiagnosis.grant_age).toMatchObject({ state: 'provenance_recorded', predates_count: 0, excluded_at_snapshot_count: 1 });
+
+ const reader = await post('/admin/api/register-client', { name: 'd4-reader-' + randomUUID(), profile: 'memory-reader', sourceId: 'default' });
+ const readerClient = await reader.json() as any; clients.push(readerClient.clientId);
+ const readerToken = await clientToken(readerClient.clientId, readerClient.clientSecret);
+ expect((await callTool(readerToken, 'put_pages', onePage('wiki/d4-reader-' + randomUUID().slice(0, 8)))).isError).toBe(true);
+ const readerDiagnosis = await whoamiDiagnosis(readerToken);
+ expect(readerDiagnosis.blockers).toEqual([{ blocker: 'scope', missing_scopes: ['write'] }]);
+ expect(readerDiagnosis.fix).toBeNull();
+ });
+
test('admin credential delivery can be recovered without another grant or secret rotation', async () => {
const name = 'delivery-admin-' + randomUUID();
const request = { name, profile: 'memory-reader', sourceId: 'default' };
diff --git a/test/e2e/serve-http-multi-agent.test.ts b/test/e2e/serve-http-multi-agent.test.ts
index 101e410d22..d29fa51ca4 100644
--- a/test/e2e/serve-http-multi-agent.test.ts
+++ b/test/e2e/serve-http-multi-agent.test.ts
@@ -309,6 +309,8 @@ describeE2E('serve-http multi-agent E2E (cathedral-6)', () => {
'--harness', 'claude-code',
'--preset', 'coding-agent',
'--federated-read', 'proj-widget',
+ // S0/D4: presets register `full`; case 7 needs A narrowed, so pin starter explicitly.
+ '--surface', 'starter',
'--url', `http://localhost:${PORT}`,
'--json', '--show-token',
]);
@@ -584,7 +586,7 @@ describeE2E('serve-http multi-agent E2E (cathedral-6)', () => {
ON CONFLICT (page_id, row_num) DO NOTHING
`);
- // A runs on the 'starter' surface (coding-agent preset): takes_list is
+ // A runs on the 'starter' surface (pinned at registration in case 1): takes_list is
// hidden there, and a hidden op is indistinguishable from a nonexistent
// one — denied. Either way, the foreign claim must never appear.
const deniedA = await callTool(tokenA!, 'takes_list', { page_slug: 'notes/nova-secret' });
diff --git a/test/embedding-dim-check.test.ts b/test/embedding-dim-check.test.ts
index c25ef937d9..26f1904007 100644
--- a/test/embedding-dim-check.test.ts
+++ b/test/embedding-dim-check.test.ts
@@ -128,6 +128,13 @@ describe('embeddingMismatchMessage', () => {
expect(nullIdx).toBeLessThan(alterIdx);
});
+ test('Postgres recipe stamps embedding_pending_since where it NULLs the vectors', () => {
+ // Doctor's embeddings check ages the re-embed backlog from the stamp; a
+ // recipe that NULLs without it leaves the backlog's age unknown.
+ const msg = embeddingMismatchMessage({ currentDims: 1536, requestedDims: 768, source: 'init', engineKind: 'postgres' });
+ expect(msg).toContain('UPDATE content_chunks SET embedding = NULL, embedded_at = NULL, embedding_pending_since = now();');
+ });
+
test('Postgres branch skips HNSW recreate when requested dims exceed pgvector cap', () => {
// Codex finding #8: 2048d (Voyage 4 Large) cannot be HNSW-indexed in pgvector.
// The recipe must NOT instruct a CREATE INDEX HNSW for that dim.
diff --git a/test/eval-longmemeval-cli-smoke.test.ts b/test/eval-longmemeval-cli-smoke.test.ts
index 9f894f9316..87175cc4e6 100644
--- a/test/eval-longmemeval-cli-smoke.test.ts
+++ b/test/eval-longmemeval-cli-smoke.test.ts
@@ -13,11 +13,14 @@
* in-memory PGLite; GBRAIN_HOME points at an empty tmp dir so no user brain or
* config is read.
*/
-import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { describe, test, expect, beforeAll, afterAll, afterEach } from 'bun:test';
import { spawnSync } from 'child_process';
import { mkdtempSync, rmSync, readFileSync, existsSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
+import { runEvalLongMemEval } from '../src/commands/eval-longmemeval.ts';
+import { createBenchmarkBrain } from '../src/eval/longmemeval/harness.ts';
+import { configureGateway, resetGateway, __setGenerateTextTransportForTests } from '../src/core/ai/gateway.ts';
const REPO = process.cwd();
const CLI = join(REPO, 'src', 'cli.ts');
@@ -74,3 +77,58 @@ describe('gbrain eval longmemeval — documented invocation end-to-end', () => {
expect(r.stderr).not.toContain('[longmemeval]');
}, 60_000);
});
+
+// A1 (wave 0): every answered row keeps the reader call's provider usage and
+// finish reason, normalized so the two cached-token conventions agree. The
+// same 100-token prompt with 60 tokens read from cache and 25 reasoning tokens
+// is reported the AI SDK v6 way by both providers (input total includes the
+// cache buckets); Anthropic's cache counts ride providerMetadata, OpenAI's the
+// SDK's cacheRead detail. Hermetic: the generateText seam replaces only the
+// final SDK call, so the gateway's own usage normalization runs.
+describe('gbrain eval longmemeval: reader usage on every row (A1)', () => {
+ afterEach(() => {
+ __setGenerateTextTransportForTests(null);
+ resetGateway();
+ });
+
+ const PROVIDERS = {
+ anthropic: {
+ model: 'anthropic:claude-opus-5-5',
+ result: { finishReason: 'stop', usage: { inputTokens: 100, inputTokenDetails: { noCacheTokens: 40, cacheReadTokens: 60, cacheWriteTokens: 0 }, outputTokens: 30, outputTokenDetails: { textTokens: 5, reasoningTokens: 25 } },
+ providerMetadata: { anthropic: { cacheReadInputTokens: 60, cacheCreationInputTokens: 0 } } },
+ },
+ openai: {
+ model: 'openai:gpt-6.1-sol',
+ result: { finishReason: 'stop', usage: { inputTokens: 100, inputTokenDetails: { noCacheTokens: 40, cacheReadTokens: 60, cacheWriteTokens: undefined }, outputTokens: 30, outputTokenDetails: { textTokens: 5, reasoningTokens: 25 }, cachedInputTokens: 60 } },
+ },
+ } as const;
+
+ for (const [provider, { model, result }] of Object.entries(PROVIDERS)) {
+ test(`${provider}: reader_usage and reader_finish_reason on each answered row`, async () => {
+ configureGateway({ env: { ANTHROPIC_API_KEY: 'sk-ant-fake', OPENAI_API_KEY: 'sk-fake' } });
+ let calls = 0;
+ __setGenerateTextTransportForTests((async () => {
+ calls++;
+ return { content: [{ type: 'text', text: 'stub reader answer' }], ...result };
+ }) as never);
+ const engine = await createBenchmarkBrain();
+ const out = join(tmp, `usage-${provider}.jsonl`);
+ try {
+ await runEvalLongMemEval([FIXTURE, '--keyword-only', '--no-trajectory', '--limit', '2', '--model', model, '--output', out], { engine });
+ } finally {
+ await engine.disconnect();
+ }
+ const rows = readFileSync(out, 'utf-8').split('\n').filter(l => l.trim()).map(l => JSON.parse(l)).filter(r => r.kind !== 'by_type_summary');
+ expect(rows.length).toBe(2);
+ expect(calls).toBe(2);
+ for (const row of rows) {
+ expect(row.hypothesis).toBe('stub reader answer');
+ expect(row.reader_finish_reason).toBe('end_turn');
+ expect(row.reader_usage).toEqual({
+ total_input_tokens: 100, uncached_input_tokens: 40, cache_read_input_tokens: 60, cache_write_input_tokens: 0,
+ output_tokens: 30, reasoning_tokens: 25,
+ });
+ }
+ }, 60_000);
+ }
+});
diff --git a/test/fixtures/agent-contract/v1/journey/init-first-run.json b/test/fixtures/agent-contract/v1/journey/init-first-run.json
index 649868cbc7..6473970075 100644
--- a/test/fixtures/agent-contract/v1/journey/init-first-run.json
+++ b/test/fixtures/agent-contract/v1/journey/init-first-run.json
@@ -119,7 +119,7 @@
"options": [
{
"id": "wire",
- "label": "Register `<absolute path to gbrain> serve --surface starter` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "label": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
{
"id": "skip",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index e8324ee525..041422b593 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -1398,7 +1398,8 @@
"22 doc_comment text/text NULL",
"23 symbol_name_qualified text/text NULL",
"24 search_vector tsvector/tsvector NULL",
- "25 edges_backfilled_at timestamp with time zone/timestamptz NULL"
+ "25 edges_backfilled_at timestamp with time zone/timestamptz NULL",
+ "26 embedding_pending_since timestamp with time zone/timestamptz NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index 3518c74a66..dfb064f505 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -1398,7 +1398,8 @@
"22 doc_comment text/text NULL",
"23 symbol_name_qualified text/text NULL",
"24 search_vector tsvector/tsvector NULL",
- "25 edges_backfilled_at timestamp with time zone/timestamptz NULL"
+ "25 edges_backfilled_at timestamp with time zone/timestamptz NULL",
+ "26 embedding_pending_since timestamp with time zone/timestamptz NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index a56fe0fb3a..e24ce49b25 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -1394,7 +1394,8 @@
"22 doc_comment text/text NULL",
"23 symbol_name_qualified text/text NULL",
"24 search_vector tsvector/tsvector NULL",
- "25 edges_backfilled_at timestamp with time zone/timestamptz NULL"
+ "25 edges_backfilled_at timestamp with time zone/timestamptz NULL",
+ "26 embedding_pending_since timestamp with time zone/timestamptz NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index f1d4197f62..3d2ccdfe1d 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -1399,7 +1399,8 @@
"22 modality text/text NOT NULL DEFAULT 'text'::text",
"23 embedding_image USER-DEFINED/vector NULL",
"24 embedding_multimodal USER-DEFINED/vector NULL",
- "25 edges_backfilled_at timestamp with time zone/timestamptz NULL"
+ "25 edges_backfilled_at timestamp with time zone/timestamptz NULL",
+ "26 embedding_pending_since timestamp with time zone/timestamptz NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index 2165f17f9d..21e5b03dc4 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -1399,7 +1399,8 @@
"22 modality text/text NOT NULL DEFAULT 'text'::text",
"23 embedding_image USER-DEFINED/vector NULL",
"24 embedding_multimodal USER-DEFINED/vector NULL",
- "25 edges_backfilled_at timestamp with time zone/timestamptz NULL"
+ "25 edges_backfilled_at timestamp with time zone/timestamptz NULL",
+ "26 embedding_pending_since timestamp with time zone/timestamptz NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index a336430724..e76fa6938f 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -1395,7 +1395,8 @@
"22 modality text/text NOT NULL DEFAULT 'text'::text",
"23 embedding_image USER-DEFINED/vector NULL",
"24 embedding_multimodal USER-DEFINED/vector NULL",
- "25 edges_backfilled_at timestamp with time zone/timestamptz NULL"
+ "25 edges_backfilled_at timestamp with time zone/timestamptz NULL",
+ "26 embedding_pending_since timestamp with time zone/timestamptz NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
diff --git a/test/fixtures/goldens/doctor/early-stop-connection-failure.json b/test/fixtures/goldens/doctor/early-stop-connection-failure.json
index a13aa76d52..8cca6cbb45 100644
--- a/test/fixtures/goldens/doctor/early-stop-connection-failure.json
+++ b/test/fixtures/goldens/doctor/early-stop-connection-failure.json
@@ -279,7 +279,7 @@
"docs": "docs/protocol/MEMORY_VERBS_v1.md#install-the-4-command-quickstart",
"requires_exclusive": false,
"user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
- "why": "Register `<absolute path to gbrain> serve --surface starter` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "why": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
"message": "No agent harness was detected. Wire one when the user picks an agent app.",
"name": "harness_wiring",
diff --git a/test/fixtures/goldens/doctor/early-stop-null-engine-connect-error.json b/test/fixtures/goldens/doctor/early-stop-null-engine-connect-error.json
index ba80efa10c..39dfee4ed1 100644
--- a/test/fixtures/goldens/doctor/early-stop-null-engine-connect-error.json
+++ b/test/fixtures/goldens/doctor/early-stop-null-engine-connect-error.json
@@ -201,7 +201,7 @@
"docs": "docs/protocol/MEMORY_VERBS_v1.md#install-the-4-command-quickstart",
"requires_exclusive": false,
"user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
- "why": "Register `<absolute path to gbrain> serve --surface starter` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "why": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
"message": "No agent harness was detected. Wire one when the user picks an agent app.",
"name": "harness_wiring",
diff --git a/test/fixtures/goldens/doctor/early-stop-null-engine-fast.json b/test/fixtures/goldens/doctor/early-stop-null-engine-fast.json
index a3ab8c4cab..2ef6e28097 100644
--- a/test/fixtures/goldens/doctor/early-stop-null-engine-fast.json
+++ b/test/fixtures/goldens/doctor/early-stop-null-engine-fast.json
@@ -201,7 +201,7 @@
"docs": "docs/protocol/MEMORY_VERBS_v1.md#install-the-4-command-quickstart",
"requires_exclusive": false,
"user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
- "why": "Register `<absolute path to gbrain> serve --surface starter` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "why": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
"message": "No agent harness was detected. Wire one when the user picks an agent app.",
"name": "harness_wiring",
diff --git a/test/fixtures/goldens/doctor/early-stop-null-engine-no-config.json b/test/fixtures/goldens/doctor/early-stop-null-engine-no-config.json
index c569da365f..6363d99eb6 100644
--- a/test/fixtures/goldens/doctor/early-stop-null-engine-no-config.json
+++ b/test/fixtures/goldens/doctor/early-stop-null-engine-no-config.json
@@ -196,7 +196,7 @@
"docs": "docs/protocol/MEMORY_VERBS_v1.md#install-the-4-command-quickstart",
"requires_exclusive": false,
"user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
- "why": "Register `<absolute path to gbrain> serve --surface starter` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "why": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
"message": "No agent harness was detected. Wire one when the user picks an agent app.",
"name": "harness_wiring",
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 67bc112862..d07019ef23 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -41,7 +41,7 @@
"next": "report",
"requires_exclusive": false,
"user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
- "why": "Register `<absolute path to gbrain> serve --surface starter` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "why": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
"message": "pglite — serve IPC socket not present; enabled but NO resolve path exists right now: the IPC socket is only bound by a running `gbrain serve` (stdio or --http) — until one is up, hooks/reflex degrade to no_serve on this brain (host capability may still supply pointers; policy skill carries otherwise) — policy skill not installed; run `gbrain integrations install retrieval-reflex --target <host-repo>`",
"name": "retrieval_reflex_health",
@@ -383,7 +383,7 @@
"next": "report",
"requires_exclusive": false,
"user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
- "why": "Register `<absolute path to gbrain> serve --surface starter` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "why": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
"message": "No agent harness was detected. Wire one when the user picks an agent app.",
"name": "harness_wiring",
@@ -530,6 +530,11 @@
},
{
"category": "brain",
+ "details": {
+ "age_threshold_s": 86400,
+ "backlog": 0,
+ "oldest_pending_age_s": null
+ },
"message": "100% coverage, 0 missing",
"name": "embeddings",
"status": "ok"
@@ -1227,6 +1232,17 @@
"name": "legacy_token_null_scope",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "docs": "docs/mcp/ADMIN.md#grants-that-cannot-reach-new-operations",
+ "grants": [],
+ "server_surface": "full"
+ },
+ "message": "Every active client and token can call the operations its scopes allow.",
+ "name": "grant_new_ops_available",
+ "status": "ok"
+ },
{
"category": "brain",
"message": "No image assets indexed yet",
diff --git a/test/fixtures/goldens/doctor/json-pglite-fast.json b/test/fixtures/goldens/doctor/json-pglite-fast.json
index 98d88c9d64..8b8da128cd 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fast.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fast.json
@@ -42,7 +42,7 @@
"next": "report",
"requires_exclusive": false,
"user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
- "why": "Register `<absolute path to gbrain> serve --surface starter` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "why": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
"message": "pglite — serve IPC socket not present; enabled but NO resolve path exists right now: the IPC socket is only bound by a running `gbrain serve` (stdio or --http) — until one is up, hooks/reflex degrade to no_serve on this brain (host capability may still supply pointers; policy skill carries otherwise) — policy skill not installed; run `gbrain integrations install retrieval-reflex --target <host-repo>`",
"name": "retrieval_reflex_health",
@@ -287,7 +287,7 @@
"next": "report",
"requires_exclusive": false,
"user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
- "why": "Register `<absolute path to gbrain> serve --surface starter` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "why": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
"message": "No agent harness was detected. Wire one when the user picks an agent app.",
"name": "harness_wiring",
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 9816694ecb..fe80aaf3cf 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -44,7 +44,7 @@
"next": "report",
"requires_exclusive": false,
"user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
- "why": "Register `<absolute path to gbrain> serve --surface starter` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "why": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
"message": "pglite — serve IPC socket not present; enabled but NO resolve path exists right now: the IPC socket is only bound by a running `gbrain serve` (stdio or --http) — until one is up, hooks/reflex degrade to no_serve on this brain (host capability may still supply pointers; policy skill carries otherwise) — policy skill not installed; run `gbrain integrations install retrieval-reflex --target <host-repo>`",
"name": "retrieval_reflex_health",
@@ -386,7 +386,7 @@
"next": "report",
"requires_exclusive": false,
"user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
- "why": "Register `<absolute path to gbrain> serve --surface starter` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "why": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
"message": "No agent harness was detected. Wire one when the user picks an agent app.",
"name": "harness_wiring",
@@ -1315,6 +1315,17 @@
"name": "legacy_token_null_scope",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "docs": "docs/mcp/ADMIN.md#grants-that-cannot-reach-new-operations",
+ "grants": [],
+ "server_surface": "full"
+ },
+ "message": "Every active client and token can call the operations its scopes allow.",
+ "name": "grant_new_ops_available",
+ "status": "ok"
+ },
{
"category": "brain",
"message": "No image assets indexed yet",
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index aca0db8d7e..55515c5dca 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -379,7 +379,7 @@
"next": "report",
"requires_exclusive": false,
"user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
- "why": "Register `<absolute path to gbrain> serve --surface starter` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "why": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
"message": "No agent harness was detected. Wire one when the user picks an agent app.",
"name": "harness_wiring",
@@ -1307,6 +1307,17 @@
"name": "legacy_token_null_scope",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "docs": "docs/mcp/ADMIN.md#grants-that-cannot-reach-new-operations",
+ "grants": [],
+ "server_surface": "full"
+ },
+ "message": "Every active client and token can call the operations its scopes allow.",
+ "name": "grant_new_ops_available",
+ "status": "ok"
+ },
{
"category": "brain",
"message": "No image assets indexed yet",
diff --git a/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json b/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json
index f1731b10a4..a0c6b3c2f9 100644
--- a/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json
+++ b/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json
@@ -239,7 +239,7 @@
"next": "report",
"requires_exclusive": false,
"user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
- "why": "Register `<absolute path to gbrain> serve --surface starter` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "why": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
"message": "No agent harness was detected. Wire one when the user picks an agent app.",
"name": "harness_wiring",
diff --git a/test/fixtures/goldens/doctor/json-postgres-unreachable.json b/test/fixtures/goldens/doctor/json-postgres-unreachable.json
index 1896fa5131..6a6a209b0c 100644
--- a/test/fixtures/goldens/doctor/json-postgres-unreachable.json
+++ b/test/fixtures/goldens/doctor/json-postgres-unreachable.json
@@ -238,7 +238,7 @@
"next": "report",
"requires_exclusive": false,
"user_message": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",
- "why": "Register `<absolute path to gbrain> serve --surface starter` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
+ "why": "Register `<absolute path to gbrain> serve --surface full` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."
},
"message": "No agent harness was detected. Wire one when the user picks an agent app.",
"name": "harness_wiring",
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index 12c25cb20b..ca04afa9a4 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -589,6 +589,10 @@
"category": "ops",
"name": "legacy_token_null_scope"
},
+ {
+ "category": "ops",
+ "name": "grant_new_ops_available"
+ },
{
"category": "ops",
"name": "index_audit"
diff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.json
index a5ded4d59e..803fc97ecb 100644
--- a/test/fixtures/goldens/exports/runtime.json
+++ b/test/fixtures/goldens/exports/runtime.json
@@ -581,6 +581,8 @@
"generateAnswer",
"rawSessionId",
"readerConfigHash",
+ "readerUsageFromGateway",
+ "readerUsageFromMessage",
"renderRetrievedAsHypothesis",
"resolveReaderConfig"
],
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index f3d9126df3..1c32891992 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -1633,7 +1633,7 @@
"responseModel?: string | undefined",
"stopReason: \"other\" | \"length\" | \"end\" | \"tool_calls\" | \"refusal\" | \"content_filter\"",
"text: string",
- "usage: { input_tokens: number; output_tokens: number; cache_read_tokens: number; cache_creation_tokens: number; }"
+ "usage: { input_tokens: number; output_tokens: number; cache_read_tokens: number; cache_creation_tokens: number; reasoning_tokens?: number; }"
],
"name": "ChatResult"
},
@@ -1837,7 +1837,7 @@
"messages: ChatMessage[]",
"stopReason: ToolLoopStopReason",
"totalTurns: number",
- "totalUsage: { input_tokens: number; output_tokens: number; cache_read_tokens: number; cache_creation_tokens: number; }"
+ "totalUsage: { input_tokens: number; output_tokens: number; cache_read_tokens: number; cache_creation_tokens: number; reasoning_tokens?: number; }"
],
"name": "ToolLoopResult"
},
@@ -4001,7 +4001,8 @@
"finish_reason: string | null",
"response_model: string | null",
"sessions_truncated: number",
- "text: string"
+ "text: string",
+ "usage: ReaderUsage | null"
],
"name": "ReaderAnswer"
},
@@ -4023,6 +4024,18 @@
"\"direct\" | \"notes\""
]
},
+ {
+ "kind": "interface",
+ "members": [
+ "cache_read_input_tokens: number",
+ "cache_write_input_tokens: number",
+ "output_tokens: number",
+ "reasoning_tokens: number | null",
+ "total_input_tokens: number",
+ "uncached_input_tokens: number"
+ ],
+ "name": "ReaderUsage"
+ },
{
"kind": "interface",
"members": [
@@ -4068,6 +4081,20 @@
"(config: ReaderConfig, model: string) => string"
]
},
+ {
+ "kind": "function",
+ "name": "readerUsageFromGateway",
+ "signature": [
+ "(u: ChatResult[\"usage\"]) => ReaderUsage"
+ ]
+ },
+ {
+ "kind": "function",
+ "name": "readerUsageFromMessage",
+ "signature": [
+ "(message: Anthropic.Message & { gbrain_usage?: ReaderUsage; }) => ReaderUsage | null"
+ ]
+ },
{
"kind": "function",
"name": "renderRetrievedAsHypothesis",
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index affc654c04..235d6e8a8e 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,6 +1,6 @@
{
"golden": {
- "count": 215,
+ "count": 216,
"gaps": [
17,
18,
@@ -36,7 +36,7 @@
"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5",
"verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"
},
- "latest": 220,
+ "latest": 221,
"records": [
{
"handler": {
@@ -3267,6 +3267,19 @@
"transaction": "absent",
"verify": "absent",
"version": 220
+ },
+ {
+ "handler": "absent",
+ "idempotent": true,
+ "name": "chunk_embedding_pending_since",
+ "sql": {
+ "length": 897,
+ "sha256": "ba56b68f73e85332abfab79b4d36b2bd174ca57886d9191e05a21d14c3a38144"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 221
}
],
"versions": [
@@ -3484,7 +3497,8 @@
217,
218,
219,
- 220
+ 220,
+ 221
]
},
"normalizer": "migrations-record-v1"
diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
index d3697952cb..13c729e48e 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -1398,7 +1398,8 @@
"22 doc_comment text/text NULL",
"23 symbol_name_qualified text/text NULL",
"24 search_vector tsvector/tsvector NULL",
- "25 edges_backfilled_at timestamp with time zone/timestamptz NULL"
+ "25 edges_backfilled_at timestamp with time zone/timestamptz NULL",
+ "26 embedding_pending_since timestamp with time zone/timestamptz NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
diff --git a/test/fixtures/goldens/sql-text/chunks.json b/test/fixtures/goldens/sql-text/chunks.json
index e0c86152bc..9166afd9b2 100644
--- a/test/fixtures/goldens/sql-text/chunks.json
+++ b/test/fixtures/goldens/sql-text/chunks.json
@@ -296,8 +296,8 @@
"params": [
"array<>"
],
- "sql": "UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL, embedded_text_hash = NULL FROM pages p WHERE cc.page_id = p.id AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND p.deleted_at IS NULL AND cc.\"embedding\" IS NOT NULL AND cc.embedded_text_hash IS NOT NULL AND cc.embedded_text_hash <> md5(cc.chunk_text) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') RETURNING cc.page_id",
- "textSha256": "7a816ccd870a8bcc2c64cfd2737318fecc8461ab5b81863f03fd5e72bc8eeb29"
+ "sql": "UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL, embedded_text_hash = NULL, embedding_pending_since = now() FROM pages p WHERE cc.page_id = p.id AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND p.deleted_at IS NULL AND cc.\"embedding\" IS NOT NULL AND cc.embedded_text_hash IS NOT NULL AND cc.embedded_text_hash <> md5(cc.chunk_text) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') RETURNING cc.page_id",
+ "textSha256": "1923e910207cfe4111f94acf3d93af891997f1f1ef503ede9593b0650ccb54e7"
},
{
"event": "commit",
@@ -330,8 +330,8 @@
"array<>",
"string"
],
- "sql": "UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL, embedded_text_hash = NULL FROM pages p WHERE cc.page_id = p.id AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND p.deleted_at IS NULL AND cc.\"embedding\" IS NOT NULL AND cc.embedded_text_hash IS NOT NULL AND cc.embedded_text_hash <> md5(cc.chunk_text) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND p.source_id = $2 RETURNING cc.page_id",
- "textSha256": "69aa7144c3192b4347ab9454a97bc714a964e33793d6a1937b6ce9302cb23c4d"
+ "sql": "UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL, embedded_text_hash = NULL, embedding_pending_since = now() FROM pages p WHERE cc.page_id = p.id AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND p.deleted_at IS NULL AND cc.\"embedding\" IS NOT NULL AND cc.embedded_text_hash IS NOT NULL AND cc.embedded_text_hash <> md5(cc.chunk_text) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND p.source_id = $2 RETURNING cc.page_id",
+ "textSha256": "8aa457cf6fd0f7a5891eb13db34d5d109faebe46ef2c798adf18622dac5a2687"
},
{
"event": "commit",
@@ -368,8 +368,8 @@
"number",
"string"
],
- "sql": "UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL FROM pages p WHERE cc.page_id = p.id AND p.deleted_at IS NULL AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND cc.\"embedding\" IS NOT NULL AND NOT COALESCE(cc.\"embedding\" IS NOT NULL AND cc.model = $2 AND cc.embedded_text_hash = md5(cc.chunk_text) AND vector_dims(cc.\"embedding\") = $3::int, false) AND p.embedding_signature IS NOT NULL AND p.embedding_signature <> $4 RETURNING cc.page_id",
- "textSha256": "21e7a3a312ece95c266d3a91240a030475b0bae3598aa9be1d066d307ace6b8b"
+ "sql": "UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL, embedding_pending_since = now() FROM pages p WHERE cc.page_id = p.id AND p.deleted_at IS NULL AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND cc.\"embedding\" IS NOT NULL AND NOT COALESCE(cc.\"embedding\" IS NOT NULL AND cc.model = $2 AND cc.embedded_text_hash = md5(cc.chunk_text) AND vector_dims(cc.\"embedding\") = $3::int, false) AND p.embedding_signature IS NOT NULL AND p.embedding_signature <> $4 RETURNING cc.page_id",
+ "textSha256": "3ce3ae1c80591bc67dd42aa8fd96381113d78112b8d9639f94c66c2fd990defb"
},
{
"event": "commit",
@@ -405,8 +405,8 @@
"string",
"string"
],
- "sql": "UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL FROM pages p WHERE cc.page_id = p.id AND p.deleted_at IS NULL AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND cc.\"embedding\" IS NOT NULL AND NOT COALESCE(cc.\"embedding\" IS NOT NULL AND cc.model = $2 AND cc.embedded_text_hash = md5(cc.chunk_text) AND vector_dims(cc.\"embedding\") = $3::int, false) AND (p.embedding_signature IS NULL OR p.embedding_signature <> $4) AND p.source_id = $5 RETURNING cc.page_id",
- "textSha256": "6349179f5610dc303ad7be6584575ad4df865ce166939cd9d44e896b68c4b8e2"
+ "sql": "UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL, embedding_pending_since = now() FROM pages p WHERE cc.page_id = p.id AND p.deleted_at IS NULL AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND cc.\"embedding\" IS NOT NULL AND NOT COALESCE(cc.\"embedding\" IS NOT NULL AND cc.model = $2 AND cc.embedded_text_hash = md5(cc.chunk_text) AND vector_dims(cc.\"embedding\") = $3::int, false) AND (p.embedding_signature IS NULL OR p.embedding_signature <> $4) AND p.source_id = $5 RETURNING cc.page_id",
+ "textSha256": "1e9cf1d1f6783e8c9bed7fe1cb42cdc67435878649e9e0527182294f3002aeaa"
},
{
"event": "commit",
@@ -682,8 +682,8 @@
"number",
"string"
],
- "sql": "INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image) SELECT $1::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding::vector, c.model, c.token_count, CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END, CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END, c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line, c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector FROM jsonb_to_recordset($2::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text, embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding\" WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.\"embedding\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding\" ELSE content_chunks.\"embedding\" END, model = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.model WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.model WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.model ELSE content_chunks.model END, token_count = EXCLUDED.token_count, embedded_at = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.\"embedding\" IS NULL THEN NULL WHEN content_chunks.\"embedding\" IS NULL AND EXCLUDED.\"embedding\" IS NOT NULL THEN EXCLUDED.embedded_at WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_at ELSE content_chunks.embedded_at END, embedded_text_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedded_text_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedded_text_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_text_hash ELSE content_chunks.embedded_text_hash END, embedding_input_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedding_input_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedding_input_hash ELSE content_chunks.embedding_input_hash END, language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END, symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END, symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END, start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END, end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END, parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END, doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END, symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END, modality = EXCLUDED.modality, embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image)",
- "textSha256": "f0dc7197c233b4ee91dd77108bc7f294d449811f43fbadd7927c25e4f7a0ec1f"
+ "sql": "INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image, embedding_pending_since) SELECT $1::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding::vector, c.model, c.token_count, CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END, CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END, c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line, c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector, CASE WHEN c.embedding IS NULL THEN now() ELSE NULL END FROM jsonb_to_recordset($2::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text, embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding\" WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.\"embedding\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding\" ELSE content_chunks.\"embedding\" END, model = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.model WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.model WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.model ELSE content_chunks.model END, token_count = EXCLUDED.token_count, embedded_at = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.\"embedding\" IS NULL THEN NULL WHEN content_chunks.\"embedding\" IS NULL AND EXCLUDED.\"embedding\" IS NOT NULL THEN EXCLUDED.embedded_at WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_at ELSE content_chunks.embedded_at END, embedded_text_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedded_text_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedded_text_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_text_hash ELSE content_chunks.embedded_text_hash END, embedding_input_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedding_input_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedding_input_hash ELSE content_chunks.embedding_input_hash END, language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END, symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END, symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END, start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END, end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END, parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END, doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END, symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END, modality = EXCLUDED.modality, embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image), embedding_pending_since = CASE WHEN EXCLUDED.\"embedding\" IS NOT NULL THEN NULL WHEN content_chunks.\"embedding\" IS NULL THEN COALESCE(content_chunks.embedding_pending_since, now()) WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN now() ELSE content_chunks.embedding_pending_since END",
+ "textSha256": "bf6f08105ad8432890deac7ff28ac5b5870235625f1b4f3163e6adda1ca53a86"
},
{
"event": "commit",
@@ -770,8 +770,8 @@
"number",
"string"
],
- "sql": "INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image) SELECT $1::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding::vector, c.model, c.token_count, CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END, CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END, c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line, c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector FROM jsonb_to_recordset($2::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text, embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding\" WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.\"embedding\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding\" ELSE content_chunks.\"embedding\" END, model = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.model WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.model WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.model ELSE content_chunks.model END, token_count = EXCLUDED.token_count, embedded_at = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.\"embedding\" IS NULL THEN NULL WHEN content_chunks.\"embedding\" IS NULL AND EXCLUDED.\"embedding\" IS NOT NULL THEN EXCLUDED.embedded_at WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_at ELSE content_chunks.embedded_at END, embedded_text_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedded_text_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedded_text_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_text_hash ELSE content_chunks.embedded_text_hash END, embedding_input_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedding_input_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedding_input_hash ELSE content_chunks.embedding_input_hash END, language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END, symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END, symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END, start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END, end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END, parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END, doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END, symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END, modality = EXCLUDED.modality, embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image)",
- "textSha256": "f0dc7197c233b4ee91dd77108bc7f294d449811f43fbadd7927c25e4f7a0ec1f"
+ "sql": "INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image, embedding_pending_since) SELECT $1::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding::vector, c.model, c.token_count, CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END, CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END, c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line, c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector, CASE WHEN c.embedding IS NULL THEN now() ELSE NULL END FROM jsonb_to_recordset($2::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text, embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding\" WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.\"embedding\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding\" ELSE content_chunks.\"embedding\" END, model = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.model WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.model WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.model ELSE content_chunks.model END, token_count = EXCLUDED.token_count, embedded_at = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.\"embedding\" IS NULL THEN NULL WHEN content_chunks.\"embedding\" IS NULL AND EXCLUDED.\"embedding\" IS NOT NULL THEN EXCLUDED.embedded_at WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_at ELSE content_chunks.embedded_at END, embedded_text_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedded_text_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedded_text_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_text_hash ELSE content_chunks.embedded_text_hash END, embedding_input_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedding_input_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedding_input_hash ELSE content_chunks.embedding_input_hash END, language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END, symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END, symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END, start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END, end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END, parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END, doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END, symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END, modality = EXCLUDED.modality, embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image), embedding_pending_since = CASE WHEN EXCLUDED.\"embedding\" IS NOT NULL THEN NULL WHEN content_chunks.\"embedding\" IS NULL THEN COALESCE(content_chunks.embedding_pending_since, now()) WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN now() ELSE content_chunks.embedding_pending_since END",
+ "textSha256": "bf6f08105ad8432890deac7ff28ac5b5870235625f1b4f3163e6adda1ca53a86"
},
{
"event": "commit",
@@ -852,8 +852,8 @@
"number",
"string"
],
- "sql": "INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding_voyage\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image) SELECT $1::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding::vector, c.model, c.token_count, CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END, CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END, c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line, c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector FROM jsonb_to_recordset($2::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text, embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding_voyage\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding_voyage\" WHEN content_chunks.\"embedding_voyage\" IS NULL THEN EXCLUDED.\"embedding_voyage\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding_voyage\" ELSE content_chunks.\"embedding_voyage\" END, model = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.model WHEN content_chunks.\"embedding_voyage\" IS NULL THEN EXCLUDED.model WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.model ELSE content_chunks.model END, token_count = EXCLUDED.token_count, embedded_at = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.\"embedding_voyage\" IS NULL THEN NULL WHEN content_chunks.\"embedding_voyage\" IS NULL AND EXCLUDED.\"embedding_voyage\" IS NOT NULL THEN EXCLUDED.embedded_at WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_at ELSE content_chunks.embedded_at END, embedded_text_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedded_text_hash WHEN content_chunks.\"embedding_voyage\" IS NULL THEN EXCLUDED.embedded_text_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_text_hash ELSE content_chunks.embedded_text_hash END, embedding_input_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hash WHEN content_chunks.\"embedding_voyage\" IS NULL THEN EXCLUDED.embedding_input_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedding_input_hash ELSE content_chunks.embedding_input_hash END, language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END, symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END, symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END, start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END, end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END, parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END, doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END, symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END, modality = EXCLUDED.modality, embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image)",
- "textSha256": "5bda6091d4af919745901fa63a0aa3cd2b37ab0f09c985e31daee1220efe102d"
+ "sql": "INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding_voyage\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image, embedding_pending_since) SELECT $1::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding::vector, c.model, c.token_count, CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END, CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END, c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line, c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector, CASE WHEN c.embedding IS NULL THEN now() ELSE NULL END FROM jsonb_to_recordset($2::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text, embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding_voyage\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding_voyage\" WHEN content_chunks.\"embedding_voyage\" IS NULL THEN EXCLUDED.\"embedding_voyage\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding_voyage\" ELSE content_chunks.\"embedding_voyage\" END, model = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.model WHEN content_chunks.\"embedding_voyage\" IS NULL THEN EXCLUDED.model WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.model ELSE content_chunks.model END, token_count = EXCLUDED.token_count, embedded_at = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.\"embedding_voyage\" IS NULL THEN NULL WHEN content_chunks.\"embedding_voyage\" IS NULL AND EXCLUDED.\"embedding_voyage\" IS NOT NULL THEN EXCLUDED.embedded_at WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_at ELSE content_chunks.embedded_at END, embedded_text_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedded_text_hash WHEN content_chunks.\"embedding_voyage\" IS NULL THEN EXCLUDED.embedded_text_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_text_hash ELSE content_chunks.embedded_text_hash END, embedding_input_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hash WHEN content_chunks.\"embedding_voyage\" IS NULL THEN EXCLUDED.embedding_input_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedding_input_hash ELSE content_chunks.embedding_input_hash END, language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END, symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END, symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END, start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END, end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END, parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END, doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END, symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END, modality = EXCLUDED.modality, embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image), embedding_pending_since = CASE WHEN EXCLUDED.\"embedding_voyage\" IS NOT NULL THEN NULL WHEN content_chunks.\"embedding_voyage\" IS NULL THEN COALESCE(content_chunks.embedding_pending_since, now()) WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN now() ELSE content_chunks.embedding_pending_since END",
+ "textSha256": "923b1cb0903628bf79f7510e6ddfb14efcac2fdc2d607b0a111a713969fc45ef"
},
{
"event": "commit",
@@ -1023,8 +1023,8 @@
"number",
"string"
],
- "sql": "INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image) SELECT $1::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding::vector, c.model, c.token_count, CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END, CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END, c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line, c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector FROM jsonb_to_recordset($2::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text, embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding\" WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.\"embedding\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding\" ELSE content_chunks.\"embedding\" END, model = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.model WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.model WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.model ELSE content_chunks.model END, token_count = EXCLUDED.token_count, embedded_at = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.\"embedding\" IS NULL THEN NULL WHEN content_chunks.\"embedding\" IS NULL AND EXCLUDED.\"embedding\" IS NOT NULL THEN EXCLUDED.embedded_at WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_at ELSE content_chunks.embedded_at END, embedded_text_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedded_text_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedded_text_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_text_hash ELSE content_chunks.embedded_text_hash END, embedding_input_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedding_input_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedding_input_hash ELSE content_chunks.embedding_input_hash END, language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END, symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END, symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END, start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END, end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END, parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END, doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END, symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END, modality = EXCLUDED.modality, embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image)",
- "textSha256": "f0dc7197c233b4ee91dd77108bc7f294d449811f43fbadd7927c25e4f7a0ec1f"
+ "sql": "INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, \"embedding\", model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image, embedding_pending_since) SELECT $1::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding::vector, c.model, c.token_count, CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END, CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END, c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line, c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector, CASE WHEN c.embedding IS NULL THEN now() ELSE NULL END FROM jsonb_to_recordset($2::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text, embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text, start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text) ON CONFLICT (page_id, chunk_index) DO UPDATE SET chunk_text = EXCLUDED.chunk_text, chunk_source = EXCLUDED.chunk_source, \"embedding\" = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.\"embedding\" WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.\"embedding\" WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.\"embedding\" ELSE content_chunks.\"embedding\" END, model = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.model WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.model WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.model ELSE content_chunks.model END, token_count = EXCLUDED.token_count, embedded_at = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.\"embedding\" IS NULL THEN NULL WHEN content_chunks.\"embedding\" IS NULL AND EXCLUDED.\"embedding\" IS NOT NULL THEN EXCLUDED.embedded_at WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_at ELSE content_chunks.embedded_at END, embedded_text_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedded_text_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedded_text_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedded_text_hash ELSE content_chunks.embedded_text_hash END, embedding_input_hash = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hash WHEN content_chunks.\"embedding\" IS NULL THEN EXCLUDED.embedding_input_hash WHEN EXCLUDED.embedded_at IS NOT NULL AND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at) THEN EXCLUDED.embedding_input_hash ELSE content_chunks.embedding_input_hash END, language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END, symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END, symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END, start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END, end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END, parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END, doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END, symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END, modality = EXCLUDED.modality, embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image), embedding_pending_since = CASE WHEN EXCLUDED.\"embedding\" IS NOT NULL THEN NULL WHEN content_chunks.\"embedding\" IS NULL THEN COALESCE(content_chunks.embedding_pending_since, now()) WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN now() ELSE content_chunks.embedding_pending_since END",
+ "textSha256": "bf6f08105ad8432890deac7ff28ac5b5870235625f1b4f3163e6adda1ca53a86"
},
{
"event": "commit",
diff --git a/test/grant-profiles-surface.test.ts b/test/grant-profiles-surface.test.ts
new file mode 100644
index 0000000000..138eda74c8
--- /dev/null
+++ b/test/grant-profiles-surface.test.ts
@@ -0,0 +1,162 @@
+/**
+ * D4: new memory-writer, memory-reader and coding-agent grants are callable and
+ * advertised on the full surface, so a fresh writer reaches put_pages while a
+ * reader still has no write scope. Existing grants never widen by migration or
+ * repair; an explicit profile application is the only widening path. Catalog
+ * provenance is recorded when a snapshot is written and never synthesized.
+ *
+ * PGLite in-memory ($0).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { withEnv } from './helpers/with-env.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { catalogProvenance, grantCatalog, readClientCatalogProvenance, readClientGrant, rescopeClientGrant, resolveGrantProfile } from '../src/core/grants/service.ts';
+import { repairLegacyClientGrants } from '../src/core/grants/migration.ts';
+import { provisionHarnessGrant } from '../src/commands/mcp-provision.ts';
+import { resolveAuthCapabilities } from '../src/core/harness/capabilities.ts';
+import { effectiveSurfaceForClient, isMcpSurface } from '../src/mcp/surface.ts';
+import type { AuthInfo } from '../src/core/ops/contract.ts';
+
+let engine: PGLiteEngine;
+let provider: GBrainOAuthProvider;
+let home: string;
+beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-profile-surface-'));
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+}, 60_000);
+afterAll(async () => { await engine?.disconnect(); rmSync(home, { recursive: true, force: true }); }, 15_000);
+
+/** Provisioning retains a private credential delivery under GBRAIN_HOME; keep it in a temp home. */
+const provision = (input: Parameters<typeof provisionHarnessGrant>[1]) => withEnv({ GBRAIN_HOME: home }, () => provisionHarnessGrant(engine, input, 'test'));
+
+/** A verified token's AuthInfo with the effective surface serve --http computes (ceiling full, no DCR default). */
+async function verifiedAuth(clientId: string, secret: string): Promise<AuthInfo> {
+ const token = await provider.exchangeClientCredentials(clientId, secret);
+ const auth = await provider.verifyAccessToken(token.access_token) as unknown as AuthInfo;
+ auth.effectiveSurface = effectiveSurfaceForClient({ ceiling: 'full', clientSurface: isMcpSurface(auth.surface) ? auth.surface : null, defaultSurface: null });
+ return auth;
+}
+
+async function capabilities(auth: AuthInfo) {
+ return await resolveAuthCapabilities(auth, engine, { engine: 'pglite' } as any, { surfaceCeiling: 'full' });
+}
+
+describe('profile surface defaults', () => {
+ test('memory-writer and coding-agent resolve to an operator-set full surface with put_pages in the snapshot', () => {
+ const writer = resolveGrantProfile({ profile: 'memory-writer', sourceId: 'default' });
+ const coding = resolveGrantProfile({ profile: 'coding-agent', sourceId: 'default', boundSlugPrefixes: ['agents/example/'] });
+ for (const grant of [writer, coding]) {
+ expect(grant.surface).toBe('full');
+ expect(grant.surfaceSetBy).toBe('operator');
+ expect(grant.allowedOperations).toContain('put_pages');
+ }
+ });
+
+ test('memory-reader resolves to full but holds no write scope and no put_pages', () => {
+ const reader = resolveGrantProfile({ profile: 'memory-reader', sourceId: 'default' });
+ expect(reader.surface).toBe('full');
+ expect(reader.scopes).toEqual(['read']);
+ expect(reader.allowedOperations).not.toContain('put_pages');
+ expect(reader.allowedOperations).not.toContain('put_page');
+ });
+
+ test('delegating-agent keeps its starter pin', () => {
+ expect(resolveGrantProfile({ profile: 'delegating-agent', sourceId: 'default', boundTools: ['search'] }).surface).toBe('starter');
+ });
+
+ test('a fresh provisioned memory-writer can call put_pages and its diagnosis shows no blocker', async () => {
+ const created = await provision({ name: 'fresh-writer-example', harness: 'generic', url: 'https://brain.example.com/mcp', profile: 'memory-writer' });
+ expect(created.grant.surface).toBe('full');
+ const caps = await capabilities(await verifiedAuth(created.grant.clientId, created.credentials!.client_secret!));
+ expect(caps.surface).toBe('full');
+ expect(caps.available_operations).toContain('put_pages');
+ expect(caps.grant_diagnosis.blockers).toEqual([]);
+ expect(caps.grant_diagnosis.unreachable_count).toBe(0);
+ expect(caps.grant_diagnosis.grant_age).toEqual({ state: 'snapshot_complete', excluded_count: 0 });
+ expect(caps.grant_diagnosis.fix).toBeNull();
+ });
+
+ test('a fresh memory-reader cannot call put_pages, and the diagnosis names the scope blocker without counting write operations', async () => {
+ const created = await provision({ name: 'fresh-reader-example', harness: 'generic', url: 'https://brain.example.com/mcp', profile: 'memory-reader' });
+ const caps = await capabilities(await verifiedAuth(created.grant.clientId, created.credentials!.client_secret!));
+ expect(caps.available_operations).not.toContain('put_pages');
+ expect(caps.grant_diagnosis.blockers).toEqual([{ blocker: 'scope', missing_scopes: ['write'] }]);
+ expect(caps.grant_diagnosis.unreachable_count).toBe(0);
+ expect(caps.grant_diagnosis.fix).toBeNull();
+ });
+});
+
+describe('existing grants widen only through an explicit profile application', () => {
+ async function preD4Writer(name: string) {
+ // The shape every pre-D4 memory-writer was minted with: operator-pinned starter.
+ const created = await provider.registerClientManual(name, ['client_credentials'], 'read write', [], 'default', undefined, undefined, undefined,
+ { ...resolveGrantProfile({ profile: 'memory-writer', sourceId: 'default' }), surface: 'starter' });
+ return { created, grant: await readClientGrant(engine, created.clientId) };
+ }
+
+ test('migration repair and an ordinary harness update keep the starter pin and the snapshot', async () => {
+ const { created, grant } = await preD4Writer('pre-d4-writer-example');
+ await repairLegacyClientGrants(engine);
+ expect(await readClientGrant(engine, created.clientId)).toEqual(grant);
+ await rescopeClientGrant(engine, created.clientId, { surface: 'full' }, { actor: 'test', repair: true });
+ expect((await readClientGrant(engine, created.clientId)).surface).toBe('starter');
+ const updated = await provision({ name: grant.clientName, harness: 'generic', url: 'https://brain.example.com/mcp',
+ clientId: created.clientId, expectedRevision: grant.revision, patch: { tokenTtlSeconds: 7200 } });
+ expect(updated.grant.surface).toBe('starter');
+ expect(updated.grant.allowedOperations).toEqual(grant.allowedOperations);
+ const caps = await capabilities(await verifiedAuth(created.clientId, created.clientSecret!));
+ expect(caps.available_operations).not.toContain('put_pages');
+ expect(caps.grant_diagnosis.blockers).toEqual([expect.objectContaining({ blocker: 'client_pin', surface: 'starter', set_by: 'operator' })]);
+ });
+
+ test('an explicit memory-writer profile application regrants the full surface', async () => {
+ const { created, grant } = await preD4Writer('reprofile-writer-example');
+ const regrant = await provision({ name: grant.clientName, harness: 'generic', url: 'https://brain.example.com/mcp',
+ clientId: created.clientId, expectedRevision: grant.revision, profile: 'memory-writer' });
+ expect(regrant.grant.surface).toBe('full');
+ expect(regrant.grant.allowedOperations).toContain('put_pages');
+ const caps = await capabilities(await verifiedAuth(created.clientId, created.clientSecret!));
+ expect(caps.available_operations).toContain('put_pages');
+ });
+});
+
+describe('catalog provenance', () => {
+ test('a new grant records the catalog its snapshot was written against', async () => {
+ const created = await provider.registerClientManual('provenance-example', ['client_credentials'], 'read write', [], 'default', undefined, undefined, undefined,
+ resolveGrantProfile({ profile: 'memory-writer', sourceId: 'default' }));
+ const grant = await readClientGrant(engine, created.clientId);
+ const provenance = await readClientCatalogProvenance(engine, created.clientId, grant.allowedOperations!);
+ expect(provenance).toEqual(catalogProvenance());
+ expect(provenance!.operations).toEqual([...grantCatalog().operationNames].sort());
+ });
+
+ test('a grant without provenance never gains it from a write that leaves its snapshot alone', async () => {
+ const created = await provider.registerClientManual('legacy-provenance-example', ['client_credentials'], 'read write', [], 'default', undefined, undefined, undefined,
+ resolveGrantProfile({ profile: 'memory-writer', sourceId: 'default' }));
+ await engine.executeRaw("UPDATE oauth_grant_audit SET after_grant = after_grant - 'catalogProvenance' WHERE client_id = $1", [created.clientId]);
+ await rescopeClientGrant(engine, created.clientId, { tokenTtlSeconds: 7200 }, { actor: 'test' });
+ await rescopeClientGrant(engine, created.clientId, { surface: 'full' }, { actor: 'test' });
+ const grant = await readClientGrant(engine, created.clientId);
+ expect(await readClientCatalogProvenance(engine, created.clientId, grant.allowedOperations!)).toBeNull();
+ });
+
+ test('provenance applies only while its snapshot is the current one, and a new snapshot write records its own', async () => {
+ const created = await provider.registerClientManual('snapshot-change-example', ['client_credentials'], 'read write', [], 'default', undefined, undefined, undefined,
+ resolveGrantProfile({ profile: 'memory-writer', sourceId: 'default' }));
+ const minted = await readClientGrant(engine, created.clientId);
+ const narrowed = minted.allowedOperations!.filter(name => name !== 'put_pages');
+ await engine.executeRaw("UPDATE oauth_clients SET allowed_operations = $2::text[] WHERE client_id = $1", [created.clientId, `{${narrowed.join(',')}}`]);
+ expect(await readClientCatalogProvenance(engine, created.clientId, narrowed)).toBeNull();
+ await engine.executeRaw("UPDATE oauth_clients SET allowed_operations = $2::text[] WHERE client_id = $1", [created.clientId, `{${minted.allowedOperations!.join(',')}}`]);
+ await rescopeClientGrant(engine, created.clientId, { allowedOperations: narrowed }, { actor: 'test' });
+ expect(await readClientCatalogProvenance(engine, created.clientId, narrowed)).toEqual(catalogProvenance());
+ });
+});
diff --git a/test/helpers/engine-sql-rollback-cases.ts b/test/helpers/engine-sql-rollback-cases.ts
index 2c08a16094..ee19924be6 100644
--- a/test/helpers/engine-sql-rollback-cases.ts
+++ b/test/helpers/engine-sql-rollback-cases.ts
@@ -15,6 +15,9 @@
*/
import { expect, test } from 'bun:test';
import type { BrainEngine } from '../../src/core/engine.ts';
+import { invalidateStaleSignatureEmbeddingsGuarded } from '../../src/core/embedding-invalidation.ts';
+import { reconcileContextualEmbeddingInputs } from '../../src/core/page-state/contextual-proof.ts';
+import { installPageProjection, readProjectionSnapshot } from '../../src/core/page-state/projections.ts';
import { installFixtureChunks } from './page-projection.ts';
export interface RollbackCase {
@@ -167,6 +170,94 @@ export const ROLLBACK_CASES: RollbackCase[] = [
return rows[0]?.s ?? null;
},
},
+ // Every site that leaves a chunk without its vector stamps
+ // embedding_pending_since (doctor ages the embedding backlog from it).
+ // Seeded embedded, so the stamp is NULL before the write.
+ {
+ domain: 'chunks (upsertChunks insert without a vector stamps embedding_pending_since)',
+ async seed(engine) {
+ await seedPage(engine);
+ await engine.deleteChunks(SLUG);
+ },
+ async write(tx) {
+ await tx.upsertChunks(SLUG, [{ chunk_index: 0, chunk_text: 'pending chunk', chunk_source: 'compiled_truth' }]);
+ expect(await vectorState(tx)).toEqual({ missing: true, pending: true });
+ },
+ observe: pendingStamp,
+ },
+ {
+ domain: 'chunks (upsertChunks text change NULLs the vector and stamps embedding_pending_since)',
+ seed: (engine) => seedEmbeddedChunk(engine),
+ async write(tx) {
+ await tx.upsertChunks(SLUG, [{ chunk_index: 0, chunk_text: 'edited chunk', chunk_source: 'compiled_truth' }]);
+ expect(await vectorState(tx)).toEqual({ missing: true, pending: true });
+ },
+ observe: pendingStamp,
+ },
+ {
+ domain: 'chunks (invalidateStaleSignatureEmbeddings stamps embedding_pending_since)',
+ seed: (engine) => seedEmbeddedChunk(engine),
+ async write(tx) {
+ expect(await tx.invalidateStaleSignatureEmbeddings({ signature: await swapSignature(tx), includeNullSignature: true })).toBe(1);
+ expect(await vectorState(tx)).toEqual({ missing: true, pending: true });
+ },
+ observe: pendingStamp,
+ },
+ {
+ domain: 'chunks (invalidateContentDriftEmbeddings stamps embedding_pending_since)',
+ async seed(engine) {
+ await seedEmbeddedChunk(engine);
+ await engine.executeRaw(`UPDATE content_chunks SET chunk_text = 'drifted chunk'
+ WHERE page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = 'default')`, [SLUG]);
+ },
+ async write(tx) {
+ expect(await tx.invalidateContentDriftEmbeddings()).toBe(1);
+ expect(await vectorState(tx)).toEqual({ missing: true, pending: true });
+ },
+ observe: pendingStamp,
+ },
+ {
+ domain: 'embedding-invalidation (guarded model-swap invalidation stamps embedding_pending_since)',
+ seed: (engine) => seedEmbeddedChunk(engine),
+ async write(tx) {
+ expect(await invalidateStaleSignatureEmbeddingsGuarded(tx, { signature: await swapSignature(tx), includeNullSignature: true })).toBe(1);
+ expect(await vectorState(tx)).toEqual({ missing: true, pending: true });
+ },
+ observe: pendingStamp,
+ },
+ {
+ domain: 'pages (contextual mode back to none stamps embedding_pending_since)',
+ async seed(engine) {
+ await seedEmbeddedChunk(engine);
+ await engine.executeRaw(`UPDATE pages SET contextual_retrieval_mode = 'title' WHERE slug = $1 AND source_id = 'default'`, [SLUG]);
+ },
+ async write(tx) {
+ await tx.updatePageContextualRetrievalState(SLUG, 'default', 'none', null);
+ expect(await vectorState(tx)).toEqual({ missing: true, pending: true });
+ },
+ observe: pendingStamp,
+ },
+ {
+ domain: 'contextual proof (a vector from a retired model input stamps embedding_pending_since)',
+ seed: (engine) => seedEmbeddedChunk(engine, RETIRED_MODEL),
+ async write(tx) {
+ const snapshot = await tx.readPageSnapshot(SLUG, { sourceId: 'default' });
+ expect(await reconcileContextualEmbeddingInputs(tx, snapshot!, 'none', null)).toBe(1);
+ expect(await vectorState(tx)).toEqual({ missing: true, pending: true });
+ },
+ observe: pendingStamp,
+ },
+ {
+ domain: 'projections (a re-seal that drops a retired vector stamps embedding_pending_since)',
+ seed: (engine) => seedEmbeddedChunk(engine, RETIRED_MODEL),
+ async write(tx) {
+ const snapshot = await readProjectionSnapshot(tx, SLUG, 'default', { allowUnsealed: true });
+ await installPageProjection(tx, snapshot!, [{ chunk_index: 0, chunk_text: EMBEDDED_TEXT, chunk_source: 'compiled_truth' }],
+ { seal: true, preserveEmbeddings: true });
+ expect(await vectorState(tx)).toEqual({ missing: true, pending: true });
+ },
+ observe: pendingStamp,
+ },
{
domain: 'pages',
async seed(engine) {
@@ -248,6 +339,45 @@ async function chunkTexts(engine: BrainEngine): Promise<string[]> {
return rows.map((r) => r.t);
}
+const EMBEDDED_TEXT = 'embedded chunk';
+const CURRENT_MODEL = 'openai:text-embedding-3-large';
+const RETIRED_MODEL = 'rollback:retired-model';
+
+/** SLUG with one sealed chunk embedded through the real upsert, no contextual mode, no signature. */
+async function seedEmbeddedChunk(engine: BrainEngine, model = CURRENT_MODEL): Promise<void> {
+ await seedPage(engine);
+ await engine.executeRaw(`UPDATE pages SET contextual_retrieval_mode = NULL, embedding_signature = NULL
+ WHERE slug = $1 AND source_id = 'default'`, [SLUG]);
+ await installFixtureChunks(engine, SLUG, [{ chunk_index: 0, chunk_text: EMBEDDED_TEXT, chunk_source: 'compiled_truth', model }]);
+ const vector = new Float32Array(await embeddingDims(engine));
+ vector[0] = 1;
+ await engine.upsertChunks(SLUG, [{ chunk_index: 0, chunk_text: EMBEDDED_TEXT, chunk_source: 'compiled_truth', embedding: vector, model }]);
+ expect(await vectorState(engine)).toEqual({ missing: false, pending: false });
+}
+
+async function embeddingDims(engine: BrainEngine): Promise<number> {
+ const rows = await engine.executeRaw<{ dim: number }>(
+ `SELECT atttypmod AS dim FROM pg_attribute WHERE attrelid = 'content_chunks'::regclass AND attname = 'embedding' AND attnum > 0`);
+ return Number(rows[0].dim);
+}
+
+/** A signature for a model the seeded chunk was not embedded with. */
+async function swapSignature(engine: BrainEngine): Promise<string> {
+ return `rollback:swapped-model:${await embeddingDims(engine)}`;
+}
+
+async function vectorState(engine: BrainEngine): Promise<{ missing: boolean; pending: boolean } | null> {
+ const rows = await engine.executeRaw<{ missing: boolean; pending: boolean }>(
+ `SELECT cc.embedding IS NULL AS missing, cc.embedding_pending_since IS NOT NULL AS pending
+ FROM content_chunks cc JOIN pages p ON p.id = cc.page_id
+ WHERE p.slug = $1 AND p.source_id = 'default' AND cc.chunk_index = 0`, [SLUG]);
+ return rows[0] ? { missing: rows[0].missing, pending: rows[0].pending } : null;
+}
+
+async function pendingStamp(engine: BrainEngine): Promise<boolean | null> {
+ return (await vectorState(engine))?.pending ?? null;
+}
+
async function rollbackChunk(engine: BrainEngine): Promise<number> {
const existing = await engine.getChunks(SLUG);
if (existing.length > 0) return existing[0]!.id;
diff --git a/test/longmemeval-reader.test.ts b/test/longmemeval-reader.test.ts
index 27a78f3b73..6fc9a7d444 100644
--- a/test/longmemeval-reader.test.ts
+++ b/test/longmemeval-reader.test.ts
@@ -6,7 +6,7 @@
*/
import { describe, test, expect } from 'bun:test';
import type Anthropic from '@anthropic-ai/sdk';
-import { buildReaderRequest, generateAnswer, READER_MAX_SESSION_CHARS, READER_PROMPT_VERSION, READER_SYSTEM_TEXT, READER_NOTES_SYSTEM_TEXT, readerConfigHash, resolveReaderConfig } from '../src/eval/longmemeval/reader.ts';
+import { buildReaderRequest, generateAnswer, READER_MAX_SESSION_CHARS, READER_PROMPT_VERSION, READER_SYSTEM_TEXT, READER_NOTES_SYSTEM_TEXT, readerConfigHash, resolveReaderConfig, readerUsageFromGateway, readerUsageFromMessage } from '../src/eval/longmemeval/reader.ts';
import { checkResumeReaderConfig } from '../src/eval/longmemeval/resume.ts';
import { sha256Hex } from '../src/eval/longmemeval/run-config.ts';
import type { SearchResult } from '../src/core/types.ts';
@@ -133,3 +133,35 @@ describe('generateAnswer context construction', () => {
expect(out.context_sessions).toBe(1);
});
});
+
+// A1: one normalized usage record whichever cached-token convention the
+// client reports. A 100-token prompt with 60 tokens read from cache: the
+// Anthropic Messages API puts 40 in input_tokens and 60 in its own bucket;
+// the gateway (AI SDK v6) reports input_tokens 100 with 60 as a subset.
+// Adding the cache bucket to the gateway total again would read 160.
+describe('A1 reader usage normalization', () => {
+ const expected = { total_input_tokens: 100, uncached_input_tokens: 40, cache_read_input_tokens: 60, cache_write_input_tokens: 0, output_tokens: 12, reasoning_tokens: null };
+
+ test('Anthropic Messages convention (separate cache buckets)', () => {
+ const message = { usage: { input_tokens: 40, output_tokens: 12, cache_read_input_tokens: 60, cache_creation_input_tokens: 0 } } as unknown as Anthropic.Message;
+ expect(readerUsageFromMessage(message)).toEqual(expected);
+ });
+
+ test('gateway convention (cache counts inside the input total)', () => {
+ expect(readerUsageFromGateway({ input_tokens: 100, output_tokens: 12, cache_read_tokens: 60, cache_creation_tokens: 0 })).toEqual(expected);
+ expect(readerUsageFromGateway({ input_tokens: 100, output_tokens: 12, cache_read_tokens: 60, cache_creation_tokens: 0, reasoning_tokens: 7 }).reasoning_tokens).toBe(7);
+ });
+
+ test('a client that reports no usage yields null, never zeros', () => {
+ expect(readerUsageFromMessage({ content: [] } as unknown as Anthropic.Message)).toBeNull();
+ });
+
+ test('generateAnswer keeps the usage and the finish reason', async () => {
+ const answer = await generateAnswer({ create: async () => ({ content: [{ type: 'text', text: 'Paris' }], stop_reason: 'max_tokens',
+ usage: { input_tokens: 40, output_tokens: 12, cache_read_input_tokens: 60 } }) as unknown as Anthropic.Message },
+ { question: 'Where?' }, [], [], new Map(), 'anthropic:claude-opus-5-5');
+ expect(answer.text).toBe('Paris');
+ expect(answer.finish_reason).toBe('max_tokens');
+ expect(answer.usage).toEqual(expected);
+ });
+});
diff --git a/test/mcp-initialize-instructions.test.ts b/test/mcp-initialize-instructions.test.ts
index 18527becc2..0ff162ecdf 100644
--- a/test/mcp-initialize-instructions.test.ts
+++ b/test/mcp-initialize-instructions.test.ts
@@ -197,3 +197,42 @@ describe('#6170: writeback line and error protocol inside the harness read limit
}
}
});
+
+// D1 (wave 0): when callable tools are left out of the listed set, the
+// hidden-tool sentence is the first thing a capped harness reads, on every
+// surface, writeback mode and with the status line; the other prompt-critical
+// lines still fit. On master the sentence was appended after the contract.
+describe('D1: hidden-tool sentence inside the harness read limit', () => {
+ const STATUS_LINE = 'This server is status-only: call gbrain_status for brain health; every other tool is off on this connection.';
+ for (const surface of SURFACES) {
+ for (const mode of ['off', 'salient', 'all'] as const) {
+ for (const statusLine of [undefined, STATUS_LINE]) {
+ test(`${surface} / ${mode} / status line=${statusLine !== undefined}`, () => {
+ const listed = new Set(filterOpsForSurface(operations, surface).map(o => o.name));
+ const callable = (n: string) => listed.has(n) || n === 'request_tools';
+ const writeback = mode !== 'off' && listed.has('remember') ? { mode, transientTtl: '3d', visibility: 'private' as const, extractFactsAvailable: true } : null;
+ const text = buildMcpInstructions({ tools: { callable, hiddenCallable: 100, statusLine }, writeback });
+ const critical = [
+ '100 more are callable. Call request_tools with no arguments',
+ listed.has('context_pack') && 'call `context_pack` at session start',
+ listed.has('put_page') && listed.has('get_page') && 'put_page REPLACES the entire page',
+ listed.has('put_page') && 'Writing:',
+ 'Follow `fix.next`',
+ writeback && 'Ambient writeback is ON',
+ ].filter((marker): marker is string => typeof marker === 'string');
+ for (const marker of critical) {
+ const start = text.indexOf(marker);
+ expect({ marker, found: start >= 0 }).toEqual({ marker, found: true });
+ const end = text.indexOf('\n', start);
+ expect({ marker, end: Math.min(end === -1 ? text.length : end, HARNESS_READ_LIMIT + 1) }).toEqual({ marker, end: Math.min(end === -1 ? text.length : end, HARNESS_READ_LIMIT) });
+ }
+ });
+ }
+ }
+ }
+
+ test('no hidden callable tools, or request_tools not callable: no sentence', () => {
+ expect(buildMcpInstructions({ tools: { callable: () => true, hiddenCallable: 0 } })).not.toContain('more are callable');
+ expect(buildMcpInstructions({ tools: { callable: n => n !== 'request_tools', hiddenCallable: 5 } })).not.toContain('more are callable');
+ });
+});
diff --git a/test/mcp-registration.test.ts b/test/mcp-registration.test.ts
index 60b5e0d79c..a17099b4b7 100644
--- a/test/mcp-registration.test.ts
+++ b/test/mcp-registration.test.ts
@@ -10,12 +10,13 @@
*/
import { describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { REGISTRATION_SURFACE, registeredSurface, stdioServeArgv } from '../src/core/mcp-registration.ts';
import { harnessWiringEntry } from '../src/core/readiness.ts';
import { registerClaudeMcp, registerCodexMcp } from '../src/core/bootstrap/hooks.ts';
+import { resolveSurfaceWithSource } from '../src/mcp/surface.ts';
const BIN = '/opt/example/bin/gbrain';
const ROOT = resolve(import.meta.dir, '..');
@@ -23,9 +24,10 @@ const wiring = (h: 'claude-code' | 'codex' | 'opencode', surface?: 'verbs' | 'st
harnessWiringEntry({ transport: 'cli', harnesses: [h], lockOwner: null, gbrainBin: BIN, ...(surface ? { surface } : {}) }).fix;
describe('REGISTRATION_SURFACE and stdioServeArgv', () => {
- test('new registrations pin starter; null renders a bare serve', () => {
- expect(REGISTRATION_SURFACE).toBe('starter');
- expect(stdioServeArgv(BIN)).toEqual([BIN, 'serve', '--surface', 'starter']);
+ test('S0: new registrations pin full (callable and advertised); null renders a bare serve', () => {
+ expect(REGISTRATION_SURFACE).toBe('full');
+ expect(stdioServeArgv(BIN)).toEqual([BIN, 'serve', '--surface', 'full']);
+ expect(stdioServeArgv(BIN, 'starter')).toEqual([BIN, 'serve', '--surface', 'starter']);
expect(stdioServeArgv(BIN, 'full')).toEqual([BIN, 'serve', '--surface', 'full']);
expect(stdioServeArgv(BIN, null)).toEqual([BIN, 'serve']);
});
@@ -43,14 +45,14 @@ describe('every stdio registration path builds from REGISTRATION_SURFACE', () =>
expect(wiring('claude-code')?.argv).toEqual(['claude', 'mcp', 'add', 'gbrain', '--', ...stdioServeArgv(BIN)]);
expect(wiring('codex')?.argv).toEqual(['codex', 'mcp', 'add', 'gbrain', '--', ...stdioServeArgv(BIN)]);
expect(wiring('opencode')?.argv).toEqual(['gbrain', 'bootstrap', 'hooks', '--harness', 'opencode', '--no-hooks']);
- expect(wiring('claude-code')?.why).toContain(`${BIN} serve --surface starter`);
+ expect(wiring('claude-code')?.why).toContain(`${BIN} serve --surface full`);
});
test('init --surface reaches the readiness fix (the quickstart line and the first-run harness decision read it)', () => {
- expect(wiring('claude-code', 'full')?.argv).toEqual(['claude', 'mcp', 'add', 'gbrain', '--', BIN, 'serve', '--surface', 'full']);
+ expect(wiring('claude-code', 'starter')?.argv).toEqual(['claude', 'mcp', 'add', 'gbrain', '--', BIN, 'serve', '--surface', 'starter']);
expect(wiring('opencode', 'verbs')?.argv).toEqual(['gbrain', 'bootstrap', 'hooks', '--harness', 'opencode', '--no-hooks', '--surface', 'verbs']);
const missing = harnessWiringEntry({ transport: 'cli', harnesses: [], lockOwner: null, gbrainBin: BIN }).fix;
- expect(missing?.why).toContain('serve --surface starter');
+ expect(missing?.why).toContain('serve --surface full');
});
test('bootstrap hooks: registerClaudeMcp and registerCodexMcp default to the surface and carry an existing form', () => {
@@ -58,7 +60,7 @@ describe('every stdio registration path builds from REGISTRATION_SURFACE', () =>
const codex = registerCodexMcp({ gbrainBin: BIN, sourceId: 'workspace' })[0];
expect(claude.slice(claude.indexOf('--') + 1)).toEqual(stdioServeArgv(BIN));
expect(codex.slice(codex.indexOf('--') + 1)).toEqual(stdioServeArgv(BIN));
- expect(registerClaudeMcp({ gbrainBin: BIN, scope: 'user', sourceId: 'w', surface: 'full' })[0].slice(-3)).toEqual(['serve', '--surface', 'full']);
+ expect(registerClaudeMcp({ gbrainBin: BIN, scope: 'user', sourceId: 'w', surface: 'starter' })[0].slice(-3)).toEqual(['serve', '--surface', 'starter']);
expect(registerCodexMcp({ gbrainBin: BIN, sourceId: 'w', surface: null })[0].slice(-2)).toEqual([BIN, 'serve']);
});
@@ -82,14 +84,49 @@ describe('every stdio registration path builds from REGISTRATION_SURFACE', () =>
writeFileSync(join(root, 'skills', 'alpha', 'SKILL.md'), '---\nname: alpha\ndescription: fixture skill\n---\n# alpha\n');
writeFileSync(join(root, 'skills', 'manifest.json'), JSON.stringify({ skills: [{ name: 'alpha' }] }));
writeFileSync(join(root, 'skills', 'plugin-lanes.json'), JSON.stringify({ starter_policy: 'x', additions: {}, base_exclusions: {}, not_added: {}, starter_gaps: {} }));
- writeFileSync(join(root, '.codex-plugin', 'mcp.json'), JSON.stringify({ mcpServers: { gbrain: { command: 'x', args: ['serve', '--surface', 'full'] } } }));
+ writeFileSync(join(root, '.codex-plugin', 'mcp.json'), JSON.stringify({ mcpServers: { gbrain: { command: 'x', args: ['serve', '--surface', 'starter'] } } }));
const bad = spawnSync('bun', ['run', join(ROOT, 'scripts/generate-plugin-tree.ts'), '--out', join(root, 'out')], {
encoding: 'utf8', timeout: 60_000, env: { ...process.env, GBRAIN_PLUGIN_TREE_ROOT: root },
});
expect(bad.status).toBe(1);
- expect(bad.stderr).toContain(`.codex-plugin/mcp.json pins --surface full; plugin lanes serve the registration surface '${REGISTRATION_SURFACE}'`);
+ expect(bad.stderr).toContain(`.codex-plugin/mcp.json pins --surface starter; plugin lanes serve the registration surface '${REGISTRATION_SURFACE}'`);
} finally {
rmSync(out, { recursive: true, force: true });
}
}, 120_000);
});
+
+// S0 (wave 0): one surface constant across every install path. Every
+// registration command these files show pins REGISTRATION_SURFACE; a bare
+// `serve` resolves to the same value. Narrower surfaces stay documented as
+// opt-ins in prose, never as a registration command. The dated *-CLI-PIN.md
+// files are verification records of what was observed, not install paths.
+describe('S0: README, docs/mcp, INSTALL, BOOTSTRAP, push-context and the manifests name one surface', () => {
+ const DOCS = [
+ 'README.md', 'INSTALL_FOR_AGENTS.md', 'BOOTSTRAP_FOR_AGENTS.md', 'docs/guides/push-context.md',
+ 'docs/INSTALL.md', 'docs/protocol/MEMORY_VERBS_v1.md', 'docs/tutorials/connect-coding-agent.md',
+ ...readdirSync(join(ROOT, 'docs/mcp')).filter(f => f.endsWith('.md') && !f.endsWith('-CLI-PIN.md')).map(f => `docs/mcp/${f}`),
+ ];
+
+ test('every `serve --surface <x>` in the install docs is the registration surface', () => {
+ const offenders: string[] = [];
+ for (const file of DOCS) {
+ readFileSync(join(ROOT, file), 'utf8').split('\n').forEach((line, i) => {
+ for (const m of line.matchAll(/\bserve\b[^`\n|]*?--surface[\s=]+["']?(verbs|starter|full)\b/g)) {
+ if (m[1] !== REGISTRATION_SURFACE) offenders.push(`${file}:${i + 1}: ${line.trim()}`);
+ }
+ });
+ }
+ expect(offenders).toEqual([]);
+ });
+
+ test('the plugin manifests pin the registration surface; the OpenClaw bundle runs a bare serve, whose default is the same value', () => {
+ for (const file of ['.codex-plugin/mcp.json', '.claude-plugin/plugin.json']) {
+ const args = (JSON.parse(readFileSync(join(ROOT, file), 'utf8')) as { mcpServers: { gbrain: { args: string[] } } }).mcpServers.gbrain.args;
+ expect({ file, surface: args[args.indexOf('--surface') + 1] }).toEqual({ file, surface: REGISTRATION_SURFACE });
+ }
+ const openclaw = JSON.parse(readFileSync(join(ROOT, 'openclaw.plugin.json'), 'utf8')) as { mcpServers: { gbrain: { args: string[] } } };
+ expect(openclaw.mcpServers.gbrain.args).toEqual(['serve']);
+ expect(resolveSurfaceWithSource(null, {})).toEqual({ surface: REGISTRATION_SURFACE, source: 'default' });
+ });
+});
diff --git a/test/persistence-history-fixture.test.ts b/test/persistence-history-fixture.test.ts
index af84c85065..e1b8710d86 100644
--- a/test/persistence-history-fixture.test.ts
+++ b/test/persistence-history-fixture.test.ts
@@ -22,13 +22,13 @@ import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
import { withEnv } from './helpers/with-env.ts';
-async function build(databaseUrl: string | undefined, seed: number): Promise<{ fixture: HistoryFixture; rows: Record<string, unknown> }> {
+async function build(databaseUrl: string | undefined, seed: number, writeWaitMs?: number): Promise<{ fixture: HistoryFixture; rows: Record<string, unknown> }> {
const home = mkdtempSync(join(tmpdir(), 'gbrain-history-fixture-test-'));
try {
return await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
try {
- const fixture = await buildHistoryFixture(engine, { pages: 30, seed, sources: 3, worktrees: 2, root: join(home, 'checkouts') });
+ const fixture = await buildHistoryFixture(engine, { pages: 30, seed, sources: 3, worktrees: 2, root: join(home, 'checkouts'), writeWaitMs });
const [queued] = await engine.executeRaw('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [fixture.queuedRequestId]);
const [delayed] = await engine.executeRaw<{ state: string; future: boolean }>(
'SELECT state,next_attempt_at>now() AS future FROM persistence_effects WHERE id=$1', [fixture.delayedEffectId]);
@@ -58,6 +58,15 @@ for (const backend of testBackends()) {
expect(rows.terminal).toBeGreaterThan(30);
expect(rows.principals).toEqual(expect.arrayContaining(['legacy_token', 'local_cli', 'oauth_client']));
}, 240_000);
+
+ // A loaded host can take longer than a write's reply wait (graduation-cli-history
+ // saw 2 of 1,000 put_page writes answer write_pending under the CI gate). A 0 ms
+ // reply wait forces that on every write: the fixture replays the same request_id
+ // until each write commits, and still requires every op to commit.
+ test('writes that outlive their reply wait (write_pending) still all commit', async () => {
+ const { fixture } = await build(databaseUrl, 11, 0);
+ expect(fixture.observations.filter(o => o.status !== 'committed').map(o => `${o.id} ${o.kind} ${o.code}`)).toEqual([]);
+ }, 240_000);
});
}
diff --git a/test/readiness.test.ts b/test/readiness.test.ts
index 1367929d9d..ce5b4d8987 100644
--- a/test/readiness.test.ts
+++ b/test/readiness.test.ts
@@ -168,13 +168,13 @@ describe('harness_wiring by state', () => {
const BIN = '/opt/gbrain/bin/gbrain';
const owner = (transport: 'stdio' | 'http', is_self = false): LockOwner => ({ pid: 4242, transport, is_self });
- test('one harness, no serve: harness-native stdio registration with the absolute binary and --surface starter', () => {
+ test('one harness, no serve: harness-native stdio registration with the absolute binary and --surface full', () => {
const claude = harnessWiringEntry({ transport: 'cli', harnesses: ['claude-code'], lockOwner: null, gbrainBin: BIN });
- expect(claude.fix?.argv).toEqual(['claude', 'mcp', 'add', 'gbrain', '--', BIN, 'serve', '--surface', 'starter']);
+ expect(claude.fix?.argv).toEqual(['claude', 'mcp', 'add', 'gbrain', '--', BIN, 'serve', '--surface', 'full']);
expect(claude.fix?.consent).toEqual(['persistent_install']);
expect(claude.fix?.why).toContain('~/.claude.json');
expect(harnessWiringEntry({ transport: 'cli', harnesses: ['codex'], lockOwner: null, gbrainBin: BIN }).fix?.argv)
- .toEqual(['codex', 'mcp', 'add', 'gbrain', '--', BIN, 'serve', '--surface', 'starter']);
+ .toEqual(['codex', 'mcp', 'add', 'gbrain', '--', BIN, 'serve', '--surface', 'full']);
expect(harnessWiringEntry({ transport: 'cli', harnesses: ['opencode'], lockOwner: null, gbrainBin: BIN }).fix?.argv)
.toEqual(['gbrain', 'bootstrap', 'hooks', '--harness', 'opencode', '--no-hooks']);
});
diff --git a/test/request-tools.test.ts b/test/request-tools.test.ts
index 43f7397d18..2c396ab43f 100644
--- a/test/request-tools.test.ts
+++ b/test/request-tools.test.ts
@@ -201,6 +201,64 @@ describe('request_tools {tools: [...]} descriptor fetch (D5)', () => {
});
});
+describe('D1: request_tools with an empty or unknown-only list returns the catalog', () => {
+ const RO = () => ({ ...HTTP, auth: authFor('ro-client', ['read']) });
+
+ test('{tools: []} returns the grouped catalog (master returned {tools: []})', async () => {
+ const res = await dispatchToolCall(engine, 'request_tools', { tools: [] }, RO());
+ expect(res.isError ?? false).toBe(false);
+ const body = parsed(res);
+ expect(body.tools).toEqual([]);
+ const catalog = parsed(await dispatchToolCall(engine, 'request_tools', {}, RO())).catalog;
+ expect(body.catalog).toEqual(catalog);
+ expect(body.total_tools).toBe(flatNames(catalog).length);
+ expect(body.did_you_mean).toBeUndefined();
+ expect(body.note).toContain('catalog lists every tool you can call');
+ });
+
+ test('unknown-only list: catalog plus a did-you-mean drawn from caller-visible ops only', async () => {
+ const res = await dispatchToolCall(engine, 'request_tools', { tools: ['get_pagez', 'serch'] }, RO());
+ const body = parsed(res);
+ expect(body.tools).toEqual([]);
+ expect(body.did_you_mean).toEqual(['get_page', 'search']);
+ const visible = new Set(flatNames(body.catalog));
+ for (const name of body.did_you_mean) expect(visible.has(name)).toBe(true);
+ expect(res.content[0].text).not.toContain('get_pagez');
+ expect(res.content[0].text).not.toContain('serch');
+ });
+
+ test('a near-miss of an invisible op never suggests it (put_page is write-scope)', async () => {
+ const body = parsed(await dispatchToolCall(engine, 'request_tools', { tools: ['put_pagex'] }, RO()));
+ expect(flatNames(body.catalog)).not.toContain('put_page');
+ expect(body.did_you_mean ?? []).not.toContain('put_page');
+ expect(body.did_you_mean ?? []).not.toContain('put_pages');
+ });
+
+ test('existing-but-invisible name and nonexistent name: byte-identical HTTP envelopes', async () => {
+ // put_page exists but needs write scope; gut_page exists nowhere. Both sit
+ // closest to the visible get_page, so the only thing that could differ is
+ // whether the op exists, and it must not show.
+ expect(operations.some(o => o.name === 'put_page')).toBe(true);
+ expect(operations.some(o => o.name === 'gut_page')).toBe(false);
+ const invisible = await dispatchToolCall(engine, 'request_tools', { tools: ['put_page'] }, RO());
+ const nonexistent = await dispatchToolCall(engine, 'request_tools', { tools: ['gut_page'] }, RO());
+ expect(parsed(invisible).did_you_mean).toEqual(['get_page']);
+ expect(JSON.stringify(invisible)).toBe(JSON.stringify(nonexistent));
+ // Far from every visible name (admin-only vs nonexistent): no suggestion either way.
+ expect(operations.some(o => o.name === 'sync_brain')).toBe(true);
+ const admin = await dispatchToolCall(engine, 'request_tools', { tools: ['sync_brain'] }, RO());
+ const none = await dispatchToolCall(engine, 'request_tools', { tools: ['zzqx_nothing_here'] }, RO());
+ expect(parsed(admin).did_you_mean).toBeUndefined();
+ expect(JSON.stringify(admin)).toBe(JSON.stringify(none));
+ });
+
+ test('a mixed list keeps the descriptor behavior (no catalog)', async () => {
+ const body = parsed(await dispatchToolCall(engine, 'request_tools', { tools: ['get_page', 'no_such_tool_xyz'] }, RO()));
+ expect(body.tools.map((t: { name: string }) => t.name)).toEqual(['get_page']);
+ expect(body.catalog).toBeUndefined();
+ });
+});
+
describe('request_tools {surface} persist branch', () => {
test('happy path: persists surface + surface_set_by=self and writes the audit row', async () => {
await seedClient('cl-persist');
diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.ts
index fa441e2f14..7e9b307ba2 100644
--- a/test/schema-bootstrap-coverage.test.ts
+++ b/test/schema-bootstrap-coverage.test.ts
@@ -891,6 +891,12 @@ const COLUMN_EXEMPTIONS = new Set<string>([
// claim, after the migration chain has run.
'minion_jobs.spend_authorization',
'minion_jobs.spend_claim_token',
+ // E-B (wave 0) content_chunks.embedding_pending_since (migration
+ // chunk_embedding_pending_since): deliberately migration-only so fresh and
+ // upgraded catalogs keep the same column order (test/pglite-upgrade-replay);
+ // the schema blob carries a comment, no CREATE TABLE column and no index
+ // reads it, so there is no forward reference for the bootstrap to trip on.
+ 'content_chunks.embedding_pending_since',
// T7 — search_telemetry rank-1 drift columns (migration v111). search_telemetry
// is created entirely by migration v57 (not in the schema blob), so the v57+v111
// chain handles fresh + upgrade; no CREATE INDEX references these columns, so
diff --git a/test/scripts/ubi-runner.test.ts b/test/scripts/ubi-runner.test.ts
index 47487864df..0462261c49 100644
--- a/test/scripts/ubi-runner.test.ts
+++ b/test/scripts/ubi-runner.test.ts
@@ -4,7 +4,8 @@
// out in-flight creates when `up` gets SIGTERM or SIGKILL mid-provision.
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
-import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { execFileSync } from "node:child_process";
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { startMockUbicloud, waitForEvent, type MockUbicloud, type MockUbicloudOptions } from "../helpers/mock-ubicloud-api.ts";
@@ -205,3 +206,38 @@ describe("stale sweep and ownership", () => {
expect(usage).toMatch(/^total\s+5\s+46$/m);
});
});
+
+// `pack` from a checkout on a branch named like `git init`'s default branch
+// (master on this repo). slim_git fetches HEAD into that branch inside a fresh
+// repository whose unborn HEAD names the same branch; without --update-head-ok
+// git refuses ("refusing to fetch into branch ... checked out"), pack falls
+// back to the full .git and prints that error on stderr, which the gate wrote
+// into the tarball it streamed to every VM.
+describe("pack", () => {
+ it("packs a checkout on init's default branch with a slim .git and nothing on stderr", async () => {
+ const repo = join(dir, "repo");
+ const git = (...args: string[]) => execFileSync("git", ["-C", repo, ...args], { encoding: "utf8" }).trim();
+ execFileSync("git", ["init", "-q", repo]);
+ git("config", "user.email", "[email protected]");
+ git("config", "user.name", "t");
+ writeFileSync(join(repo, "tracked.txt"), "tracked\n");
+ git("add", "tracked.txt");
+ git("commit", "-q", "-m", "one");
+ writeFileSync(join(repo, "untracked.txt"), "untracked\n");
+ // An unreachable object: the full .git carries it, the slim copy (a fetch of HEAD) does not.
+ writeFileSync(join(dir, "dangling.txt"), "dangling blob\n");
+ const dangling = git("hash-object", "-w", join(dir, "dangling.txt"));
+ const branch = git("symbolic-ref", "HEAD");
+ expect(branch).toMatch(/^refs\/heads\//);
+ const proc = Bun.spawn(["bash", RUNNER, "pack", repo], { env: env(), stdout: "pipe", stderr: "pipe" });
+ const [archive, stderr, code] = await Promise.all([new Response(proc.stdout).arrayBuffer(), new Response(proc.stderr).text(), proc.exited]);
+ expect({ code, stderr }).toEqual({ code: 0, stderr: "" });
+ const out = join(dir, "out");
+ execFileSync("mkdir", ["-p", out]);
+ execFileSync("tar", ["-xzf", "-", "-C", out], { input: Buffer.from(archive) });
+ expect(readFileSync(join(out, "untracked.txt"), "utf8")).toBe("untracked\n");
+ expect(execFileSync("git", ["-C", out, "symbolic-ref", "HEAD"], { encoding: "utf8" }).trim()).toBe(branch);
+ expect(execFileSync("git", ["-C", out, "log", "--format=%s"], { encoding: "utf8" }).trim()).toBe("one");
+ expect(() => execFileSync("git", ["-C", out, "cat-file", "-e", dangling], { stdio: "ignore" })).toThrow();
+ });
+});
diff --git a/test/scripts/ubicloud-run-script.test.ts b/test/scripts/ubicloud-run-script.test.ts
new file mode 100644
index 0000000000..96407524ab
--- /dev/null
+++ b/test/scripts/ubicloud-run-script.test.ts
@@ -0,0 +1,51 @@
+// ubicloud-run-script.test.ts — scripts/ubicloud/run-script.ts, the way
+// scripts/ci-ubicloud.ts runs every ubi-runner.sh subcommand.
+//
+// Protects: with `stdoutOnly`, a script's stderr never lands in the `out`
+// file (the gate's checkout tarball was corrupted by a git warning written
+// into it), and a child that exits before reading its `input` (a failed
+// `ssh` during `unpack`) resolves with its exit code instead of an uncaught
+// EPIPE that killed the orchestrator before it tore its VMs down.
+// Each case runs in its own Bun process, so an uncaught error shows up as a
+// crashed child rather than taking this test runner down.
+
+import { afterEach, beforeEach, describe, expect, it } from "bun:test";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+
+const HELPER = resolve(import.meta.dir, "..", "..", "scripts/ubicloud/run-script.ts");
+let dir = "";
+beforeEach(() => { dir = mkdtempSync(join(tmpdir(), "ubicloud-run-script-")); });
+afterEach(() => { rmSync(dir, { recursive: true, force: true }); });
+
+async function drive(script: string, opts: Record<string, unknown>) {
+ const scriptPath = join(dir, "script.sh");
+ writeFileSync(scriptPath, script);
+ const driver = join(dir, "driver.ts");
+ writeFileSync(driver, `import { runScript } from ${JSON.stringify(HELPER)};
+const r = await runScript(${JSON.stringify(scriptPath)}, [], ${JSON.stringify(opts)});
+console.log(JSON.stringify(r));
+`);
+ const proc = Bun.spawn(["bun", driver], { stdout: "pipe", stderr: "pipe" });
+ const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ return { code, stderr, result: code === 0 ? JSON.parse(stdout.trim().split("\n").at(-1)!) as { code: number; stdout: string } : null };
+}
+
+describe("runScript", () => {
+ it("stdoutOnly: the out file holds stdout alone; stderr comes back in the result", async () => {
+ const out = join(dir, "archive.bin");
+ const run = await drive("printf 'ARCHIVE'\necho 'fatal: a git warning' >&2\n", { out, stdoutOnly: true });
+ expect(run.code).toBe(0);
+ expect(readFileSync(out, "utf8")).toBe("ARCHIVE");
+ expect(run.result).toEqual({ code: 0, stdout: "fatal: a git warning\n" });
+ });
+
+ it("a child that exits before reading all its input resolves with its exit code (no uncaught EPIPE)", async () => {
+ const input = join(dir, "big.bin");
+ writeFileSync(input, Buffer.alloc(32 * 1024 * 1024, 1));
+ const run = await drive("head -c 1 >/dev/null; sleep 0.2; exit 3\n", { input, out: join(dir, "log.txt") });
+ expect({ code: run.code, crashed: /EPIPE/.test(run.stderr) }).toEqual({ code: 0, crashed: false });
+ expect(run.result?.code).toBe(3);
+ });
+});
diff --git a/test/whoami.test.ts b/test/whoami.test.ts
index 844b9c17f9..b2f30c44f7 100644
--- a/test/whoami.test.ts
+++ b/test/whoami.test.ts
@@ -7,9 +7,14 @@
* test/e2e/serve-http-oauth.test.ts and test/e2e/sources-remote-mcp.test.ts.
*/
-import { test, expect, describe } from 'bun:test';
+import { test, expect, describe, beforeAll, afterAll } from 'bun:test';
import { operations, OperationError } from '../src/core/operations.ts';
import type { OperationContext, AuthInfo } from '../src/core/operations.ts';
+import { STARTER_OPS } from '../src/mcp/surface.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { readClientGrant, rescopeClientGrant, resolveGrantProfile } from '../src/core/grants/service.ts';
const whoami = operations.find(o => o.name === 'whoami')!;
@@ -260,3 +265,184 @@ describe('whoami op metadata', () => {
expect(whoami.mutating).toBeFalsy();
});
});
+
+// ---------------------------------------------------------------------------
+// D4: grant_diagnosis — proven blockers with counts and no operation names,
+// inferred grant age kept apart, identity from the verifier's principal.
+// ---------------------------------------------------------------------------
+
+const EXCLUDED = ['put_pages', 'delete_page'];
+
+async function diagnose(auth: AuthInfo, extra: Partial<OperationContext> = {}): Promise<any> {
+ return (await whoami.handler(ctxWith({ remote: true, auth, ...extra }), {})) as any;
+}
+
+function oauthAuth(overrides: Partial<AuthInfo>): AuthInfo {
+ return {
+ token: 'gbrain_at_diag', clientId: 'display-only-id', clientName: 'diag-example',
+ principal: { kind: 'oauth_client', id: 'gbrain_cl_diag_principal' },
+ scopes: ['read', 'write'], expiresAt: 1, sourceId: 'default', allowedSources: ['default'],
+ ...overrides,
+ } as AuthInfo;
+}
+
+/** Every operation a read+write grant may call on this server: a no-snapshot full-surface grant lists exactly that set. */
+async function eligibleFor(scopes: string[]): Promise<string[]> {
+ return (await diagnose(oauthAuth({ scopes, allowedOperations: null }))).available_operations;
+}
+
+describe('whoami grant_diagnosis', () => {
+ test('snapshot-blocked: names the operation snapshot, counts the excluded operations and names none', async () => {
+ const eligible = await eligibleFor(['read', 'write']);
+ expect(eligible).toEqual(expect.arrayContaining(EXCLUDED));
+ const result = await diagnose(oauthAuth({ allowedOperations: eligible.filter(name => !EXCLUDED.includes(name)), surface: 'full', surfaceSetBy: 'operator' }));
+ const d = result.grant_diagnosis;
+ expect(d.blockers).toEqual([{ blocker: 'operation_snapshot', excluded_count: 2 }]);
+ expect(d.unreachable_count).toBe(2);
+ expect(d.grant_age).toEqual({ state: 'intent_unknown', excluded_count: 2,
+ statement: "This grant's snapshot excludes 2 currently eligible operations; original intent unknown." });
+ expect(d.fix.next).toBe('tell_user_to_run');
+ expect(d.fix.argv).toEqual(['gbrain', 'auth', 'rescope', '--client', 'gbrain_cl_diag_principal', '--operations', '<OPERATIONS>', '--dry-run']);
+ expect(d.fix.then_argv).toEqual(['gbrain', 'auth', 'rescope', '--client', 'gbrain_cl_diag_principal', '--operations', '<OPERATIONS>']);
+ expect(d.fix.all_operations.argv).toContain('all');
+ for (const name of EXCLUDED) expect(JSON.stringify(result)).not.toContain(name);
+ });
+
+ test('pin-blocked: names the client pin and its surface; the snapshot is complete', async () => {
+ const eligible = await eligibleFor(['read', 'write']);
+ const d = (await diagnose(oauthAuth({ allowedOperations: eligible, surface: 'starter', surfaceSetBy: 'operator' }))).grant_diagnosis;
+ const outsideStarter = eligible.filter(name => !STARTER_OPS.has(name)).length;
+ expect(outsideStarter).toBeGreaterThan(0);
+ expect(d.blockers).toEqual([{ blocker: 'client_pin', surface: 'starter', set_by: 'operator', excluded_count: outsideStarter }]);
+ expect(d.grant_age).toEqual({ state: 'snapshot_complete', excluded_count: 0 });
+ expect(d.fix.argv).toEqual(['gbrain', 'auth', 'rescope', '--client', 'gbrain_cl_diag_principal', '--surface', 'full', '--dry-run']);
+ expect(d.fix.inputs).toBeUndefined();
+ for (const name of EXCLUDED) expect(JSON.stringify(d)).not.toContain(name);
+ });
+
+ test('both: a client blocked by its snapshot and its pin gets both blockers and one command lifting both', async () => {
+ const eligible = await eligibleFor(['read', 'write']);
+ const d = (await diagnose(oauthAuth({ allowedOperations: eligible.filter(name => name !== 'put_pages'), surface: 'starter', surfaceSetBy: 'operator' }))).grant_diagnosis;
+ const outsideStarter = eligible.filter(name => !STARTER_OPS.has(name));
+ expect(d.blockers).toEqual([
+ { blocker: 'operation_snapshot', excluded_count: 1 },
+ { blocker: 'client_pin', surface: 'starter', set_by: 'operator', excluded_count: outsideStarter.length },
+ ]);
+ expect(d.unreachable_count).toBe(new Set([...outsideStarter, 'put_pages']).size);
+ expect(d.fix.argv).toEqual(['gbrain', 'auth', 'rescope', '--client', 'gbrain_cl_diag_principal', '--operations', '<OPERATIONS>', '--surface', 'full', '--dry-run']);
+ expect(JSON.stringify(d)).not.toContain('put_pages');
+ });
+
+ test('scope-blocked: a reader names the missing write scope and counts no write operations', async () => {
+ const eligible = await eligibleFor(['read']);
+ expect(eligible).not.toContain('put_pages');
+ const d = (await diagnose(oauthAuth({ scopes: ['read'], allowedOperations: eligible, surface: 'full' }))).grant_diagnosis;
+ expect(d.blockers).toEqual([{ blocker: 'scope', missing_scopes: ['write'] }]);
+ expect(d.unreachable_count).toBe(0);
+ expect(d.fix).toBeNull();
+ });
+
+ test('server-ceiling: a narrower transport ceiling is its own blocker and no grant change is offered', async () => {
+ const eligible = await eligibleFor(['read', 'write']);
+ const d = (await diagnose(oauthAuth({ allowedOperations: eligible, effectiveSurface: 'starter' }), { surfaceCeiling: 'starter' })).grant_diagnosis;
+ expect(d.blockers).toEqual([{ blocker: 'server_ceiling', surface: 'starter', excluded_count: eligible.filter(name => !STARTER_OPS.has(name)).length }]);
+ expect(d.fix).toBeNull();
+ });
+
+ test('scope-eligible counting: a writer snapshot holding every read/write operation reports 0 though the catalog has admin-only operations', async () => {
+ const eligible = await eligibleFor(['read', 'write']);
+ const adminOnly = operations.filter(op => !op.localOnly && op.scope === 'admin').map(op => op.name);
+ expect(adminOnly.length).toBeGreaterThan(0);
+ for (const name of adminOnly) expect(eligible).not.toContain(name);
+ const d = (await diagnose(oauthAuth({ allowedOperations: eligible, surface: 'full' }))).grant_diagnosis;
+ expect(d.blockers).toEqual([]);
+ expect(d.unreachable_count).toBe(0);
+ expect(d.grant_age).toEqual({ state: 'snapshot_complete', excluded_count: 0 });
+ });
+
+ test('legacy token: identity is the verifier principal id and the fix refreshes the snapshot', async () => {
+ const eligible = await eligibleFor(['read', 'write']);
+ const auth = { token: 'gbrain_x', clientId: 'shared-token-name', clientName: 'shared-token-name',
+ principal: { kind: 'legacy_token', id: '00000000-0000-4000-8000-0000000000d4' }, scopes: ['read', 'write'],
+ allowedOperations: eligible.filter(name => name !== 'put_pages'), expiresAt: 1 } as AuthInfo;
+ const result = await diagnose(auth);
+ expect(result.transport).toBe('legacy');
+ const d = result.grant_diagnosis;
+ expect(d.blockers).toEqual([{ blocker: 'operation_snapshot', excluded_count: 1 }]);
+ expect(d.grant_age.state).toBe('intent_unknown');
+ expect(d.fix.argv).toEqual(['gbrain', 'auth', 'rescope', '--id', '00000000-0000-4000-8000-0000000000d4', '--refresh-operations']);
+ expect(d.fix.then_argv).toEqual(['gbrain', 'auth', 'rescope', '--id', '00000000-0000-4000-8000-0000000000d4', '--refresh-operations', '--add', '<OPERATIONS>']);
+ expect(JSON.stringify(result)).not.toContain('put_pages');
+ });
+
+ test('no principal: counts still report, but no host command is built from a display name', async () => {
+ const eligible = await eligibleFor(['read', 'write']);
+ const d = (await diagnose(oauthAuth({ principal: undefined, allowedOperations: eligible.filter(name => name !== 'put_pages') }))).grant_diagnosis;
+ expect(d.blockers).toEqual([{ blocker: 'operation_snapshot', excluded_count: 1 }]);
+ expect(d.fix).toBeNull();
+ });
+});
+
+describe('whoami grant_diagnosis grant age on a real grant record (PGLite)', () => {
+ let engine: PGLiteEngine;
+ let provider: GBrainOAuthProvider;
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ }, 60_000);
+ afterAll(async () => { await engine?.disconnect(); }, 15_000);
+
+ async function writerWithout(name: string, excluded: string[]) {
+ const created = await provider.registerClientManual(name, ['client_credentials'], 'read write', [], 'default', undefined, undefined, undefined,
+ resolveGrantProfile({ profile: 'memory-writer', sourceId: 'default' }));
+ const grant = await readClientGrant(engine, created.clientId);
+ await rescopeClientGrant(engine, created.clientId, { allowedOperations: grant.allowedOperations!.filter(op => !excluded.includes(op)) }, { actor: 'test' });
+ return created;
+ }
+ async function liveDiagnosis(clientId: string, secret: string) {
+ const token = await provider.exchangeClientCredentials(clientId, secret);
+ const auth = await provider.verifyAccessToken(token.access_token) as unknown as AuthInfo;
+ auth.effectiveSurface = 'full';
+ return (await whoami.handler(ctxWith({ remote: true, auth, engine, config: { engine: 'pglite' } as any, surfaceCeiling: 'full' }), {}) as any).grant_diagnosis;
+ }
+ const dropFromCatalog = (clientId: string, name: string) => engine.executeRaw(
+ `UPDATE oauth_grant_audit SET after_grant = jsonb_set(after_grant, '{catalogProvenance,operations}', (after_grant->'catalogProvenance'->'operations') - $2::text)
+ WHERE client_id = $1 AND after_grant->'catalogProvenance' IS NOT NULL`, [clientId, name]);
+
+ test('post-D4: a snapshot written without an operation that existed reports it as left out, not predated', async () => {
+ const created = await writerWithout('age-left-out-example', ['put_pages']);
+ const d = await liveDiagnosis(created.clientId, created.clientSecret!);
+ expect(d.blockers).toEqual([{ blocker: 'operation_snapshot', excluded_count: 1 }]);
+ expect(d.grant_age).toMatchObject({ state: 'provenance_recorded', excluded_count: 1, predates_count: 0, excluded_at_snapshot_count: 1 });
+ expect(d.grant_age.statement).toContain('all existed when the snapshot was written');
+ expect(d.grant_age.statement).not.toContain('predates');
+ });
+
+ test('post-D4: an operation added after the snapshot was written is asserted as predated', async () => {
+ const created = await writerWithout('age-predates-example', ['put_pages']);
+ await dropFromCatalog(created.clientId, 'put_pages');
+ const d = await liveDiagnosis(created.clientId, created.clientSecret!);
+ expect(d.grant_age).toMatchObject({ state: 'provenance_recorded', excluded_count: 1, predates_count: 1, excluded_at_snapshot_count: 0 });
+ expect(d.grant_age.statement).toStartWith('This grant predates 1 currently eligible operation:');
+ expect(JSON.stringify(d)).not.toContain('put_pages');
+ });
+
+ test('a new admin-only operation outside a writer grant is not counted', async () => {
+ const created = await writerWithout('age-admin-example', ['put_pages']);
+ const adminOp = operations.find(op => !op.localOnly && op.scope === 'admin')!.name;
+ await dropFromCatalog(created.clientId, adminOp);
+ const d = await liveDiagnosis(created.clientId, created.clientSecret!);
+ expect(d.blockers).toEqual([{ blocker: 'operation_snapshot', excluded_count: 1 }]);
+ expect(d.grant_age).toMatchObject({ excluded_count: 1, predates_count: 0 });
+ });
+
+ test('legacy: without recorded provenance the same snapshot says original intent unknown', async () => {
+ const created = await writerWithout('age-legacy-example', ['put_pages']);
+ await engine.executeRaw("UPDATE oauth_grant_audit SET after_grant = after_grant - 'catalogProvenance' WHERE client_id = $1", [created.clientId]);
+ const d = await liveDiagnosis(created.clientId, created.clientSecret!);
+ expect(d.grant_age).toEqual({ state: 'intent_unknown', excluded_count: 1,
+ statement: "This grant's snapshot excludes 1 currently eligible operation; original intent unknown." });
+ });
+});
diff --git a/tests/docker/bootstrap-e2e-inner.sh b/tests/docker/bootstrap-e2e-inner.sh
index b0c0f7838a..b7c437a9ff 100644
--- a/tests/docker/bootstrap-e2e-inner.sh
+++ b/tests/docker/bootstrap-e2e-inner.sh
@@ -256,7 +256,7 @@ grep -Fq "GBRAIN_SOURCE=" "$GB_CODEX_STATE" || fail "codex registration did not
# Every stdio registration gbrain writes pins REGISTRATION_SURFACE
# (src/core/mcp-registration.ts); test/check-bootstrap-guards.test.ts keeps
# this literal equal to it so a surface change fails on the PR, not nightly.
-EXPECTED_SURFACE=starter
+EXPECTED_SURFACE=full
grep -Fq "serve --surface $EXPECTED_SURFACE" "$GB_CODEX_STATE" \
|| fail "codex registration did not pin the registration surface '$EXPECTED_SURFACE' (registered: $(cat "$GB_CODEX_STATE")). Why: bootstrap hooks builds the serve argv from stdioServeArgv/REGISTRATION_SURFACE in src/core/mcp-registration.ts. Next: if REGISTRATION_SURFACE changed on purpose, update EXPECTED_SURFACE here; otherwise fix registerCodexMcp in src/core/bootstrap/hooks.ts, then run bash tests/docker/bootstrap-e2e.sh"