Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
v0.45.13.0 feat(mcp): truthful surface wave — honest catalog, fail-loud retrieval, per-client starter surface (#4096)
Garry Tan6a905a1e5b73
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.mdindex 16120766fc..f2a634ee1d 100644--- a/BOOTSTRAP_FOR_AGENTS.md+++ b/BOOTSTRAP_FOR_AGENTS.md@@ -1,4 +1,4 @@-<!-- gbrain-runbook-stamp: 0.45.12.0 -->+<!-- gbrain-runbook-stamp: 0.45.13.0 --><!-- This stamp must equal the VERSION file at every release; CI enforces it(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it tothe installed binary and warns on skew. -->diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 83740ae983..ed0f2873c7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,107 @@All notable changes to GBrain will be documented in this file.+## [0.45.13.0] - 2026-08-13++**The Truthful Surface wave: your agent's MCP catalog now tells the truth. What's listed is callable, empty answers explain themselves, and new clients start with a focused ~26-tool surface they can widen on demand.**++This wave answers a production consumer's six-point review of the remote MCP+experience ("A- tools, B- packaging"). Every fix rewires signals gbrain already+computes into responses agents already receive — organized around one principle:+the tool catalog is an API promise.++### Added++- **Starter tool surface + pull-based unlock.** A new `starter` surface+ (~26 daily-driver tools: the seven verbs plus the reviewed brain-tool+ slice and the agent lane, re-derivable from your own production usage via+ `scripts/derive-starter-ops.ts`) sits between `verbs` and `full`. Each connected client can carry its own surface, bounded+ by the server ceiling — it can narrow itself or widen up to the ceiling with+ the new `request_tools` tool, and operators can pin a client's surface with+ `gbrain auth rescope-client` (pins beat self-service, always). Every surface+ change writes an audit row, so "why did this client see 20 tools yesterday+ and 100 today" is answerable from logs alone.+- **`request_tools` discovery meta-op.** No arguments → the catalog visible to+ YOUR credentials, grouped by area with one-line summaries. `{tools: [...]}`+ → full schemas for named tools. `{surface}` → persist a wider or narrower+ surface (rate-limited, ceiling-bounded, operator-pin-aware), then re-list.+- **Fail-loud retrieval.** Every `query`/`search` response now carries+ `_meta.retrieval` — retrieved count, a closed-vocabulary `degraded[]` trail+ (embed unavailable, expansion failed, budget truncated, ...), and a hint for+ concept-shaped queries. Empty results additionally carry a model-visible+ explanation block, and the CLI names the cause instead of a bare+ "No results."+- **Synthesis that says why.** `synthesize` (and `think`) report+ `synthesis_status`, pages/takes gathered, and typed warnings. When the LLM+ compose step fails but retrieval found material, you now get an extractive+ fallback answer built from the gathered pages instead of silence.+- **Minions queue visibility.** `get_status_snapshot` gains `queue` (per-queue+ depth + oldest-waiting age) and `workers` (supervisor liveness) sections.+ `submit_agent`/`submit_job` return `queue_state` with a warning when the+ queue is backed up, paused, or has no live worker — a job ID alone is no+ longer mistakable for progress. New `get_agent_job` op lets agent-scope+ clients poll their own jobs (and only their own).+- **Lint visibility on writes.** `put_page` now returns the top lint findings+ (errors first, with per-validator fix hints) instead of just counts.+- **Operator tooling.** `gbrain auth clients --usage` (per-client op usage),+ a starter-fit advisor collector with drift detection, a generated+ `docs/TOOL_CATALOG.md`, and a surface-operations runbook.++### Changed++- **The tool catalog is now honest on every transport.** `tools/list` reflects+ what the caller can actually invoke: publish-gated, scope-blocked,+ surface-hidden, and fence-blocked tools are unlisted rather than listed-then-+ denied; local-only tools are confined to the local transport. Hidden and+ nonexistent tools are indistinguishable on the wire.+- **Complete, guessable schemas.** Every network-visible tool parameter now+ carries a description with examples (37 backfilled), CI-guarded so new params+ can't ship undocumented. Unknown arguments get a did-you-mean response:+ warn-and-accept by default this release (`mcp.strict_params`), with a named+ flip to reject in a future minor.+- **Search degradation is survivable.** One failed embedding arm no longer+ zeroes the whole vector fan-out — survivors are salvaged and stamped. A+ first-result-exceeds-budget search now returns one truncated result instead+ of an empty list, and the token cap is now a true hard cap.+- Degraded result sets cache for ~60s (stamped) instead of full TTL, so a+ transient provider outage stops echoing for an hour. Cache keys fold the new+ degradation stamp (one-time miss spike on upgrade).++### Fixed++- Request-log statuses now distinguish denials-after-list and warn-mode+ successes on both HTTP transports, usage-derived features count only+ successful calls, and the admin error-rate metric no longer counts audit+ bookkeeping as traffic.+- Config read failures fail closed: a transient config outage can no longer+ widen a client's surface or re-open the unknown-argument grace period on a+ strict server.+- Raw exception text no longer rides MCP responses — degradation reasons and+ warnings use closed code vocabularies; details go to server logs.++## To take advantage of v0.45.13.0++`gbrain upgrade` runs the schema migration automatically.++1. **Upgrade and check:**+ ```bash+ gbrain upgrade+ gbrain doctor+ ```+2. **See what your clients actually use, then right-size them:**+ ```bash+ gbrain auth clients --usage+ gbrain auth rescope-client <client-id> --surface starter+ ```+ Existing clients keep their current (full) surface — nothing narrows on+ upgrade. New clients can be defaulted with `mcp.default_surface_dcr`.+3. **Watch retrieval health:** `gbrain search stats` now breaks down empty+ results by cause, and every `query`/`search` response carries+ `_meta.retrieval`.+4. **Agents discover the rest themselves:** any client can call+ `request_tools` to browse the full catalog and (within your ceiling)+ widen its own surface.+## [0.45.12.0] - 2026-08-13**Hermes joins the tested-install club: a real-binary harness now proves gbrain works inside Hermes, and `gbrain friction diff` tells you whether an install problem is the agent's or ours.**@@ -105,6 +206,7 @@ To take advantage of v0.45.11.0: nothing to do — `gbrain self-upgrade` (or you- **`gbrain bootstrap hooks` with a missing harness CLI** now still installs per-turn hooks and reports the phase as partial (so a resuming agent re-runs it once the CLI is on PATH) instead of leaving a false "wire complete".- **`gbrain bootstrap interview --set/--skip` after a confirmation** warns that it voided the read-back instead of failing silently later at render.- Review-pass self-fixes: the keyless upgrade hint now names the re-init command that actually works (not the schema-sizing field `config set` rejects); compiled-binary detection for the detached update refresh no longer breaks for a renamed/official-named binary; the DX harness scrubs copied credentials even on interrupt and reaps the child's whole process tree.+## [0.45.10.0] - 2026-08-13**21 more community and maintainer bug fixes. Search answers get more complete, sync gets safer, and doctor learns to warn you before a provider dies.**diff --git a/TODOS.md b/TODOS.mdindex 737ac707a6..a0bdd3e380 100644--- a/TODOS.md+++ b/TODOS.md@@ -1,5 +1,203 @@# TODOS+## Truthful-surface wave follow-ups (filed with T14, amendment 35 + D14.5)++Deferred from the MCP consumer-feedback wave (plan at+`~/.claude/plans/system-instruction-you-are-working-snuggly-parrot.md`; scoped+OUT deliberately — see the plan's "NOT in scope" list).++- [ ] **P1 — strict_params reject-flip.** **What:** flip the `mcp.strict_params`+ default from `warn` to `reject`. **Why:** the warn grace period exists so+ clients adapt before unknown args become hard errors; leaving it warn forever+ re-opens the silent-arg-typo class WP3 closed. **Context:** named flip+ criterion — ZERO `success_with_warnings` rows over 30 days of production+ traffic (`SELECT count(*) FROM mcp_request_log WHERE+ status='success_with_warnings' AND created_at > now() - interval '30 days'`;+ see docs/operations/mcp-surface-runbook.md Move 3). The flip is a config+ DEFAULT change in `resolveStrictParamsMode` + the `additionalProperties:+ false` emission becoming the default tools/list shape; the pinned+ default=warn test to update is `test/validate-params.test.ts` ("unresolved+ (absent) config defaults to warn") and `test/mcp-tool-defs.test.ts` pins+ both emission states. **Effort:** small (1-line default + test updates).+ **Priority:** P1.+- [ ] **P2 — mcp_request_log retention/pruning.** **What:** a retention policy+ (age- or row-capped prune, `gbrain maintain` hook or cron). **Why:** the+ table now carries MORE than request telemetry — `surface_change` audit rows+ (ENG-8) and `denied_after_list` metric rows ride it — and it grows unbounded+ on busy brains. **Context:** pruning must NOT silently discard the audit+ trail — either exempt `operation='surface_change'` or archive before delete;+ the usage reader (src/core/mcp-usage.ts) windows at ≤3650d. **Effort:**+ medium. **Priority:** P2.+- [ ] **P3 — describe_tools op.** **What:** a dedicated per-op schema+ introspection op (design OQ4). **Why:** deferred — `request_tools`' no-arg+ catalog + complete tools/list schemas + did-you-mean on unknown tools/params+ cover the need. **Context:** revisit if a consumer asks for schema detail+ beyond what tools/list carries. **Effort:** small. **Priority:** P3.+- [ ] **P3 — page_lint pull op.** **What:** an op returning the FULL lint+ report for a slug (design OQ5). **Why:** deferred — `put_page`'s inline+ `writer_lint.top_findings` (top 5, errors first) suffices until someone+ needs more than five findings or lint-without-write. **Context:** the+ validator registry + FIX_HINTS (src/core/validators/index.ts) already+ expose everything a pull op would need. **Effort:** small. **Priority:** P3.+- [ ] **P3 — named client tiers.** **What:** Phase 2 of the per-client surface:+ named tiers (e.g. 'analyst', 'writer') stored in the SAME+ `oauth_clients.surface` column. **Why:** teams want role-shaped catalogs,+ not just the 3-step ladder. **Context:** the column's value space is+ documented OPEN (amendment 18) — unknown values fall back to server/config+ resolution with a warn-once, so tier names can land without a migration;+ resolution/UI is the work. **Effort:** medium. **Priority:** P3.+- [ ] **P3 — per-client token budgets.** **What:** Phase 2: per-client+ response token budgets (same column pattern as surface). **Why:** a+ starter-surface client with a 4K-context harness still gets full-size+ payloads; budget belongs to the CLIENT, not the query. **Context:** builds+ on `oauth_clients` per-client columns + the search-mode `tokenBudget` knob;+ interacts with `packToBudget`/`enforceTokenBudget` (keep the frozen-verb+ strictness — ENG-2). **Effort:** medium. **Priority:** P3.+- [ ] **P3 — full list-size telemetry.** **What:** first-class telemetry for+ tools/list responses (per token class: count, approx bytes, trend).+ **Why:** catalog size is the consumer complaint the wave started from;+ today's stopgap only records the count. **Context:** the stopgap+ (amendment 23) rides the existing tools/list `mcp_request_log` row as+ `params.tool_count` — see the runbook's first-5-minutes SQL. A full+ version would bucket bytes and surface in `gbrain search stats`-style+ output. **Effort:** medium. **Priority:** P3.+- [ ] **P3 — get_job invalid_params→not_found alignment (ENG-13).** **What:**+ align admin `get_job`'s unknown-id envelope with `get_agent_job`'s uniform+ `not_found`. **Why:** the two job-read ops answer "no such job" with+ different error codes; `get_agent_job` chose `not_found` deliberately+ (anti-enumeration) and the divergence is recorded, not designed. **Context:**+ ENG-13 kept `get_agent_job` at `not_found` and filed this sibling; check+ callers that branch on `invalid_params` before changing. **Effort:** small.+ **Priority:** P3.++## Truthful-surface wave — pre-landing review deferrals++Filed from the /ship pre-landing review of the wave branch (all classified+review-deferred, not fix-now). Grouped by component.++### MCP transport / serve-http++- [ ] **P2 — memoize the `mcp.default_surface_dcr` read on the tools/call hot+ path.** **What:** a short-TTL (15–30s) memo of the dual-plane+ `resolveDefaultClientSurface` read for NULL-surface clients. **Why:** every+ request from a NULL-surface client pays one serial config RTT today (on+ network Postgres that is real latency); a 15–30s memo makes the hot path+ free while config flips still land within the TTL. **Context:** rescope+ freshness is unaffected — the client ROW surface rides the auth JOIN in+ `verifyAccessToken`, so only the config DEFAULT would be memoized+ (`src/commands/serve-http.ts` resolveEffectiveSurface →+ `src/mcp/surface.ts` resolveDefaultClientSurface). **Effort:** small.+ **Priority:** P2.+- [ ] **P2 — extend the Postgres-host e2e with request-log row assertions.**+ **What:** extend `test/e2e/serve-http-oauth.test.ts` with the honest-list+ cell plus row-level twins of the new pure-function pins: a+ `denied_after_list` row, a `success_with_warnings` row, and the tools/list+ `params->>'tool_count'` param. **Why:** `requestLogStatusForResult` is+ unit-pinned pure (test/denied-after-list.test.ts) but the INSERT wiring in+ serve-http (real HTTP, real OAuth tokens, real mcp_request_log rows) only+ runs on a Postgres-equipped host. **Context:** the e2e already stands up+ the real OAuth server; add cells, not scaffolding. **Effort:** small.+ **Priority:** P2.+- [ ] **P3 — surfaceProjectionDegraded marker for drift-shaped brains.**+ **What:** a visible marker (whoami/_meta/log line) when the surface+ projection is degraded because the schema is drift-shaped: v127 columns+ (`oauth_clients.surface`) present but v85-era prerequisites missing.+ **Why:** on the degrade ladder today an operator surface LOCK silently+ widens to the server ceiling — the operator believes a pin holds when it+ does not. **Context:** only reachable via restored dumps, since migrations+ are ordered; cheap to detect at the existing isUndefinedColumnError seams.+ **Effort:** small. **Priority:** P3.++### Minions / status++- [ ] **P3 — partial index for completed-job recency probes.** **What:**+ `CREATE INDEX ... ON minion_jobs (updated_at) WHERE status='completed'` (or+ fold into the wedge-index family) if `get_status_snapshot` polling becomes+ frequent. **Why:** `buildWorkersSnapshot`'s `max(updated_at)` over completed+ rows seq-scans today; fine at human frequency, wrong under dashboard+ polling. **Context:** same family as the buildQueueDepths perf note in+ `src/commands/status.ts` (partial (queue, created_at) WHERE+ status='waiting' is the sibling fix there). **Effort:** small.+ **Priority:** P3.++### Test infra (master-owned)++- [ ] **P1 — test/extract-atoms-chunk-embed.test.ts flakes under parallel+ shards.** **What:** deflake the extract-atoms chunk-embed suite when run in+ parallel shards. **Why:** it fails under shard parallelism but passes alone+ — a shard-ordering trap for every future branch. **Context:** failure+ signature: extraction returns status 'warn' with ALL transcripts skipped+ (0 processed) → count assertions fail; env-coupling suspected — the same+ withEnv class fixed in token-budget.test.ts this wave. Pre-existing on+ master; owned there, not by any feature branch. **Effort:** small.+ **Priority:** P1.++### Hygiene dedupe batch (single entry — take together)++- [ ] **P3 — hygiene dedupe batch from the pre-landing review.** **What:**+ eight small same-shape dedupes, cheapest done as one sweep: (1) shared+ `firstSentence` helper (`src/core/operations.ts` firstSentenceOf vs+ `src/mcp/tool-catalog.ts` firstSentence); (2) shared empty-retrieval renderer+ (`src/cli.ts` describeEmptyRetrieval vs `src/mcp/dispatch.ts`+ buildEmptyRetrievalBlock); (3) generic resolveDualPlaneConfig helper for+ the three hand-rolled DB>file>default reads (publish gates,+ strict_params, default_surface_dcr); (4) use `isMcpSurface` at the three+ literal `'verbs'|'starter'|'full'` validation sites; (5) shared `toIso`+ (mcp-usage.ts vs siblings); (6) export the MCP_USAGE window bounds+ ([1, 3650]) from mcp-usage.ts and consume in parseAuthClientsArgs ++ derive-starter-ops instead of re-typing; (7) reuse buildQueueDepths+ (status.ts) in doctor's waitingByQueue + the supervisor probe instead of+ three copies of the same GROUP BY; (8) compose rescopeClient's+ optional-column branch matrix instead of enumerating it. **Why:** each is+ a copy that can drift independently; none is worth its own entry.+ **Context:** all two-way doors, no behavior change intended — land with+ the existing pins green. **Effort:** medium (as a batch). **Priority:** P3.++### Adversarial-review deferrals (cross-model, ship-stage)++Filed from the /ship adversarial review (Codex + Claude synthesis). The twelve+fix-now findings landed on the branch; these four are the review-deferred tail.++- [ ] **P2 — request_tools persist: fold the old-surface read into the atomic+ UPDATE.** **What:** replace the SELECT → UPDATE → audit-write triple with+ one `UPDATE ... RETURNING (SELECT surface FROM oauth_clients WHERE ...)`+ (or capture old via `RETURNING` on a CTE) so the audit row's `old` value+ can never be a stale read from before a concurrent change. **Why:** today+ a rescope racing the persist can make the audit trail record a wrong+ `old→new` transition — the trail answers "why did the surface change" and+ must not lie under concurrency. **Context:**+ `src/core/operations.ts` request_tools persist branch ++ `src/core/surface-audit.ts`; both engines (CTE-in-UPDATE parity check).+ **Effort:** small. **Priority:** P2.+- [ ] **P3 — persist rate-limit durability across restarts/processes.**+ **What:** decide whether the request_tools persist limiter (in-memory+ token bucket, ~5/hr/client) needs DB-backed durability. A server restart+ refills every bucket; a multi-process fleet multiplies the budget by+ process count. **Why:** today the cap is advisory under restart churn —+ fine for the abuse class it targets (runaway clients), wrong if it ever+ guards something stronger. **Context:** `src/mcp/rate-limit.ts` ++ `requestToolsPersistLimiter`; the surface_change audit rows already give+ a DB-side count to enforce against if needed. **Effort:** medium.+ **Priority:** P3.+- [ ] **P3 — cancel (not just abandon) timed-out submit-time queue probes.**+ **What:** the WP5 wedge/pause probes time-bound via Promise.race, but the+ losing query keeps running on the pool after the race resolves. Wire+ AbortSignal / statement_timeout so a slow probe releases its slot. **Why:**+ under pool exhaustion (the exact regime the probes exist to detect) an+ abandoned probe query holds a pooler slot and makes the exhaustion worse.+ **Context:** `src/core/minion/supervisor.ts` queryWedgeSignals callers in+ `src/core/operations.ts` submit paths. **Effort:** small. **Priority:** P3.+- [ ] **P3 — document the status --json snapshot union under schema_version.**+ **What:** a short protocol note (docs/progress-events.md sibling) pinning+ the `get_status_snapshot` v2 shape as a discriminated union on+ `schema_version` (v1: no queue/workers keys; v2: sections present but+ per-section fail-soft `{error: 'unavailable'}`), plus a compat table for+ thin-client consumers. **Why:** external `--json` consumers can't rely on+ reading the TypeScript; the fail-soft section shapes are non-obvious.+ **Context:** `src/core/operations.ts` get_status_snapshot,+ `src/commands/status.ts` thin-client sections. **Effort:** small.+ **Priority:** P3.+## Onboarding DX follow-ups (filed v0.45.9.0)- [ ] **Retire the `config set embedding_model` dead-end across ALL surfaces.** v0.45.9.0 fixed the keyless-init notice to point at `gbrain init --force --pglite --embedding-model <id>`, but `src/core/embed-preflight.ts` (lines ~73/83/90/115) and `src/core/embedding-dim-check.ts:78` still advertise `gbrain config set embedding_model <...>`, which `src/commands/config.ts:142` hard-refuses as a schema-sizing no-op. Same dead-end class, different surfaces. Sweep them to the re-init recipe. Priority: P2.@@ -99,7 +297,11 @@ Deferred from the BrainBench wave (eng-reviewed; plan + GSTACK REVIEW REPORT at- [ ] **Hermetic-ize the 7 env-sensitive LLM-availability tests.** `test/think-gateway-adapter.test.ts`, `test/conversation-parser/llm-base.test.ts`/`llm-fallback.test.ts`, `test/doctor-ze-checks.test.ts` assert behavior "when ANTHROPIC_API_KEY is unset" by reading the live process env — they fail on any dev shell that exports provider keys (verified failing on clean master in such a shell; green in keyless CI). Stub/save-restore the env per test so local runs match CI. Priority: P2.## #2416 follow-ups (query-steering wave)-- [ ] **P2 — MCP-envelope `hint` field for concept-shaped `search` calls.**+- [x] **P2 — MCP-envelope `hint` field for concept-shaped `search` calls.**+ DONE (Truthful Surface Wave, E1): the hint rides `_meta.retrieval.hint` on the+ `search` op (the sibling-metadata-channel option this entry proposed) plus the+ model-visible second content block on empty results. See+ `docs/protocol/MCP_META_CHANNELS.md`.**What:** surface the concept→query nudge to remote/MCP agent callers, notjust the CLI. **Why:** MCP agents are the primary misrouting class the#2416 issue describes; the shipped CLI stderr nudge covers the caller classdiff --git a/VERSION b/VERSIONindex 2faa506ea1..500fb8965a 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.45.12.0\ No newline at end of file+0.45.13.0\ No newline at end of filediff --git a/docs/INSTALL.md b/docs/INSTALL.mdindex 6825b256a2..e1770e1980 100644--- a/docs/INSTALL.md+++ b/docs/INSTALL.md@@ -13,7 +13,7 @@ Mix later if needed.## 1. Run with an agent platform-Already running [OpenClaw](https://github.com/garrytan/openclaw) or [Hermes](https://github.com/NousResearch/hermes-agent)?+Already running [OpenClaw](https://github.com/garrytan/openclaw) or [Hermes](https://github.com/garrytan/hermes)?```bashbun install -g github:garrytan/gbrain#latest-stable@@ -71,7 +71,7 @@ claude mcp add gbrain -- gbrain serve --surface verbs # Claude Codecodex mcp add gbrain -- gbrain serve --surface verbs # 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; 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 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 (~26 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)**.## 3. MCP server (any MCP client)@@ -98,8 +98,6 @@ Per-client setup guides live in [`docs/mcp/`](mcp/):- [`docs/mcp/CODEX.md`](mcp/CODEX.md)- [`docs/mcp/CLAUDE_DESKTOP.md`](mcp/CLAUDE_DESKTOP.md)- [`docs/mcp/CHATGPT.md`](mcp/CHATGPT.md)-- [`docs/mcp/HERMES.md`](mcp/HERMES.md)-- [`docs/mcp/OPENCLAW.md`](mcp/OPENCLAW.md)- [`docs/mcp/PERPLEXITY.md`](mcp/PERPLEXITY.md)- [`docs/mcp/DEPLOY.md`](mcp/DEPLOY.md) — production deploy patternsdiff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.mdnew file mode 100644index 0000000000..3bc78fde6c--- /dev/null+++ b/docs/TOOL_CATALOG.md@@ -0,0 +1,222 @@+# MCP tool catalog++<!-- GENERATED FILE — do not edit by hand. -->+<!-- Regenerate: bun run scripts/generate-tool-catalog.ts -->+<!-- Freshness-guarded by scripts/check-tool-catalog-fresh.sh (bun run verify). -->++Every non-localOnly operation on the MCP surface: 104 tools across 22 areas. **Starter** marks membership in the ~26-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.++## admin++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `get_health` | Brain health dashboard (embed coverage, stale pages, orphans) | admin | | |+| `get_stats` | Brain statistics (page count, chunk count, etc.) | admin | | |+| `get_status_snapshot` | Snapshot for `gbrain status` thin-client mode: sync freshness + last cycle + queue depths + worker liveness. | admin | | |+| `run_doctor` | Run brain health checks and return a structured DoctorReport (thin-client doctor surface). | admin | | |+| `run_onboard` | Probe brain health + optionally submit onboard remediations. | admin | | |+| `run_skillopt` | Run SkillOpt against a single skill. | admin | | |++## advisor++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `advisor` | Ranked, read-only "what to do next" for this brain: version drift, pending migrations, schema-pack issues, stalled jobs, usage-shape gaps, and setup smells. | read | | `mcp.publish_advisor` |++## chronicle++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `chronicle_day` | Life Chronicle: events + timeline entries on a given day (or its ISO week when week=true), ordered chronologically; each row backlinks to its depth page. | read | | |+| `chronicle_last_seen` | Life Chronicle: when an entity was last seen — its own timeline rows OR an event's `who`. | read | | |+| `chronicle_on_this_day` | Life Chronicle: events from the same calendar day in PRIOR years ("on this day"). | read | | |+| `chronicle_since` | Life Chronicle: events + timeline entries on or after a date, optionally filtered by event kind. | read | | |+| `volunteer_chronicle` | Life Chronicle agent-orientation: the recent timeline (last N days) + the current validity-resolved ontology for the named entities, in one zero-LLM payload, so an agent orients before acting. | read | | |++## code++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `code_blast` | BEFORE editing any function, run code_blast with the symbol name to surface every transitive caller grouped by depth (direct → 2-hop → 3-hop). | read | | |+| `code_callees` | When tracing how a function flows to its dependencies (DB calls, HTTP calls, file I/O), run code_callees from the entry point. | read | | |+| `code_callers` | BEFORE editing any function, run code_callers with the symbol name to find every caller (the people who'd be affected by your change). | read | | |+| `code_def` | Where is this symbol defined? | read | | |+| `code_flow` | When tracing how a request flows through the codebase from entry point to side effect (DB write, HTTP call, file I/O), run code_flow from the entry point. | read | | |+| `code_refs` | Find every reference to a symbol across the codebase (every file, every line). | read | | |++## discovery++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `request_tools` | Discover this brain's tool catalog and optionally unlock a wider tool surface for your client. | read | yes | |++## entities++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `extract_entities` | Extract entity names (people, companies) from text and create/update their brain stub pages. | write | | |+| `extraction_pending` | List unverified auto-extracted entity stubs awaiting owner review (the quarantine lane from extract_entities). | read | | |++## identity++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `get_brain_identity` | Brain identity + counters for thin-client banner. | read | | |+| `whoami` | Introspect the calling identity. | read | yes | |++## ingest++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `get_ingest_log` | Get recent ingestion log entries | read | yes | |+| `log_ingest` | Log an ingestion event | write | | |++## insights++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `find_anomalies` | Returns statistical anomalies in recent page activity, grouped by cohort (tag or type). | read | yes | |+| `find_contradictions` | v0.32.6 — return suspected-contradiction findings from the most recent `gbrain eval suspected-contradictions` probe run, optionally filtered by slug and/or severity. | read | | |+| `find_experts` | Answers 'who in my brain knows about <topic>'. | read | | |+| `find_trajectory` | v0.35.4 — return the chronological claim trajectory for an entity (typed metric values over time, plus auto-detected regressions and narrative drift). | read | | |+| `get_calibration_profile` | Read the active calibration profile for a holder. | read | | |+| `get_recent_salience` | Returns pages recently touched and ranked by emotional + activity salience (deterministic 0..1 emotional_weight + take density + recency decay). | read | yes | |+| `volunteer_context` | Push-based context: volunteer brain pages relevant to a rolling conversation window WITHOUT being asked. | read | | |++## jobs++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `cancel_job` | Cancel a waiting, active, or delayed job | admin | | |+| `get_agent_job` | Poll an agent job submitted via submit_agent. | agent | yes | |+| `get_job` | Get job status and details by ID | admin | | |+| `get_job_progress` | Get structured progress for a running job | admin | | |+| `list_jobs` | List jobs with optional filters | admin | | |+| `pause_job` | Pause a waiting, active, or delayed job | admin | | |+| `replay_job` | Replay a completed/failed/dead job, optionally with modified data | admin | | |+| `resume_job` | Resume a paused job back to waiting | admin | | |+| `retry_job` | Re-queue a failed or dead job for retry | admin | | |+| `send_job_message` | Send a sidechannel message to a running job's inbox | admin | | |+| `submit_agent` | Submit an LLM agent job that the worker dispatches via the gateway-native tool loop. | agent | yes | |+| `submit_job` | Submit a background job to the Minions queue. | admin | | |++## links++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `add_link` | Create link between pages | write | | |+| `find_orphans` | Find pages with no inbound wikilinks. | read | | |+| `get_backlinks` | List incoming links to a page | read | yes | |+| `get_links` | List outgoing links from a page | read | | |+| `list_link_sources` | List distinct link_source provenances in the brain with edge counts (e.g. | read | yes | |+| `remove_link` | Remove link between pages | write | | |+| `traverse_graph` | Traverse link graph from a page. | read | yes | |++## memory++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `extract_facts` | v0.31: extract personal-knowledge facts (events, preferences, commitments, beliefs) from a conversation turn into the per-source hot memory. | write | | |+| `forget_fact` | v0.32.2: forget a fact. | write | | |++## memory-verbs++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `context_pack` | MEMORY VERB (v1): budget-packed session-boundary bundle for a set of standing entities — entity cards + open threads + hot facts, zero-LLM, sub-second. | read | yes | |+| `delta` | MEMORY VERB (v1): "what changed since T" for heartbeats — pages updated after `since` + hot facts newer than `since` + open-thread events after `since`, zero-LLM. | read | yes | |+| `entity` | MEMORY VERB (v1): inspect ONE known person/company/project card — zero LLM calls, sub-100ms. | read | yes | |+| `forget` | MEMORY VERB (v1): expire a remembered fact by id — the protocol delete verb. | write | yes | |+| `recall` | MEMORY VERB (v1): retrieve saved facts/snippets — the protocol read verb. | read | yes | |+| `remember` | MEMORY VERB (v1): save one fact to durable agent memory — the protocol write verb. | write | yes | |+| `synthesize` | [EXPENSIVE / SLOW — makes LLM calls, seconds-to-minutes latency, costs money] MEMORY VERB (v1): answer a broad question using cross-page LLM reasoning with citations and gap analysis. | read | yes | |++## ontology++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `ontology_conflicts` | Life Chronicle: dimensions with ≥2 distinct current values from ≥2 provenances (genuine disagreement, not temporal supersession). | read | | |+| `ontology_dimensions` | Life Chronicle meta-ontology: which dimensions the brain tracks across entities, with entity + observation counts. | read | | |+| `ontology_get` | Life Chronicle: the current resolved per-entity ontology (dimension → value) at `asof` (default now), with provenance + confidence + validity. | read | | |+| `ontology_propose` | Life Chronicle: record one ontology observation (entity has dimension=value), sourced + confidence-weighted + bi-temporal. | write | | |++## pages++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `delete_page` | Soft-delete a page. | write | | |+| `get_chunks` | Get content chunks for a page | read | | |+| `get_page` | Read a page by slug (supports optional fuzzy matching). | read | yes | |+| `get_raw_data` | Retrieve raw data for a page | read | | |+| `get_versions` | Page version history | read | | |+| `list_pages` | List pages with optional filters. | read | yes | |+| `put_page` | Write/update a page (markdown with frontmatter). | write | yes | |+| `put_raw_data` | Store raw API response data for a page | write | | |+| `resolve_slugs` | Fuzzy-resolve a partial slug to matching page slugs | read | yes | |+| `restore_page` | v0.26.5 — restore a soft-deleted page (clear deleted_at). | write | | |+| `revert_version` | Revert page to a previous version | write | | |++## schema++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `get_active_schema_pack` | v0.40.6.0: cheap identity packet for the active schema pack. | read | | |+| `list_schema_packs` | v0.40.6.0: list installed schema packs (bundled + user-installed). | read | | |+| `reload_schema_pack` | v0.40.6.0: flush the in-process schema pack cache so the next loadActivePack re-reads from disk. | admin | | |+| `schema_apply_mutations` | v0.40.7.0: batched schema pack mutation. | admin | | |+| `schema_explain_type` | v0.40.6.0: resolved settings for a single page_type in the active pack. | read | | |+| `schema_graph` | v0.40.6.0: schema pack graph as JSON edges. | read | | |+| `schema_lint` | v0.40.6.0: lint the active (or named) schema pack. | read | | |+| `schema_review_orphans` | v0.40.6.0: list pages with no active-pack type match. | read | | |+| `schema_stats` | v0.40.6.0: per-type page counts + typed-coverage from the DB. | read | | |++## search++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `query` | Hybrid search with vector + keyword + multi-query expansion. | read | yes | |+| `search` | Cheap hybrid search (vector + keyword + RRF) with no LLM expansion. | read | yes | |+| `search_by_image` | v0.36 cross-modal Phase 2: image-as-query retrieval. | read | | |++## skills++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `get_skill` | Fetch one skill's full instructions by name. | read | | `mcp.publish_skills` |+| `list_brain_skillpack` | List brain-resident skillpacks this brain ships (per-source). | read | | `mcp.publish_skills` |+| `list_skills` | List the skills this agent's brain publishes. | read | | `mcp.publish_skills` |++## sources++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `sources_add` | Register a new source. | sources_admin | | |+| `sources_list` | List registered sources with page counts and remote_url. | read | | |+| `sources_remove` | Hard-remove a source (cascades pages/chunks/embeddings). | sources_admin | | |+| `sources_status` | Per-source diagnostic. | read | | |++## tags++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `add_tag` | Add tag to page | write | | |+| `get_tags` | List tags for a page | read | | |+| `remove_tag` | Remove tag from page | write | | |++## takes++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `takes_calibration` | Calibration curve: resolved correct/incorrect bets binned by stated weight; observed vs predicted per bucket. | read | | |+| `takes_list` | List takes (typed/weighted/attributed claims) filtered by holder/kind/active/etc. | read | | |+| `takes_scorecard` | Calibration scorecard for resolved bets: counts, accuracy, Brier (correct ∨ incorrect only), partial_rate. | read | | |+| `takes_search` | Keyword search across takes (pg_trgm similarity over claim text) | read | | |+| `think` | Multi-hop synthesis across pages + takes + graph. | read | | |++## timeline++| Tool | Description | Scope | Starter | Gate |+|---|---|---|---|---|+| `add_timeline_entry` | Add timeline entry to a page | write | yes | |+| `get_timeline` | Get timeline entries for a page, optionally filtered by date window | read | | |+diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.mdindex cff2e290a7..0fefe226cc 100644--- a/docs/architecture/KEY_FILES.md+++ b/docs/architecture/KEY_FILES.md@@ -164,7 +164,7 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/archive-crawler-config.ts` — safety gate for the `archive-crawler` skill. Refuses to run unless `archive-crawler.scan_paths:` is explicitly set in the brain repo's `gbrain.yml`. Mirrors the storage-config.ts parsing pattern (sibling file, separate concern from storage tiering). `loadArchiveCrawlerConfig(repoPath)` throws `ArchiveCrawlerConfigError(missing_section | empty_scan_paths | invalid_path | parse_error)`. `normalizeAndValidateArchiveCrawlerConfig` rejects relative paths and `..` traversal; `~` is expanded; paths are stored resolved and terminated with the PLATFORM separator (`path.sep`) so error output reads natively on each OS. `isPathAllowed(candidate, config)` is the runtime per-file gate (scan_paths prefix-match with directory-boundary correctness; deny_paths overrides). Candidate, scan_paths and deny_paths all funnel through the private `toComparablePrefix()` before the prefix test — on Windows it folds `\`→`/` and lowercases (NTFS is case-insensitive, so a deny_path spelled `Private` must still match `private`, else the gate fails OPEN); on POSIX it is identity apart from the trailing separator, deliberately NOT folding, since `\` is a legal filename character and paths are case-sensitive. Storing a native separator while appending a hardcoded `/` is the mixed-separator bug that made `isPathAllowed` deny every real path on Windows; the two functions must stay symmetric or the prefix test is meaningless. Pinned by `test/archive-crawler-config.test.ts` (26 cases, platform-selected fixtures + `it.if`-gated win32/POSIX comparison semantics).- `test/helpers/cli-pty-runner.ts` — generic real-PTY harness (~470 lines) using pure `Bun.spawn({terminal:})` (Bun 1.3.10+; engines.bun pin in package.json). Generic primitives only, no plan-mode orchestrators. Exports `launchPty`, `resolveBinary`, `stripAnsi`, `parseNumberedOptions`, `optionsSignature`, `isNumberedOptionListVisible`, `isTrustDialogVisible`. Self-tests in `test/cli-pty-runner.test.ts` (24 cases).- `src/core/skillpack/{init-brain-pack,brain-pack-advisory,brain-pack-lint,brain-resident-locate,nag-state}.ts` (#2180) — brain-resident skillpacks. `manifest-v1.ts` gains optional `brain_resident` + `schema_pack` (additive). `runInitBrainPack` scaffolds a pack beside brain content (`brain_resident:true`, exact `gbrain_min_version`, 5-section machine-parseable README); `applyWritePlan` is factored out of `init-scaffold.ts` for the shared refuse-overwrite loop. `brain-pack-lint.lintBrainPackTools` validates each skill's `tools:` against the serving op set (E6 version-skew). Topology A: `src/commands/sources.ts` `runAdd` prints `brain-pack-advisory` to stderr after `opsAddSource`, fail-open; `nag-state.ts` (`~/.gbrain/skillpack-nag-state.json`) keys declines by `(source-repo brain_id, source_id, pack_name)` with pure `decideNagAction` (first/reminder/version-bump/ceiling) — declines count ONLY on CLI-interactive displays. Topology B: `brain-resident-locate.loadResidentPacksForServer` (source-scoped via `sourceScopeOpts`) backs the `list_brain_skillpack` op; `getResidentSkillDetail` backs `get_skill` `source_id`; `scaffold_spec` is the git source, never a server FS path. Tests: `test/skillpack-{init-brain-pack,nag-state,brain-resident-locate}.test.ts` + the brain-resident cases in `test/skillpack-manifest-v1.test.ts`.-- `src/core/advisor/{types,run,render,recommended-set,history,apply,collect-*}.ts` + `src/commands/advisor.ts` (#2180) — `gbrain advisor`: read-only ranked actions from brain state. `run.runAdvisor` executes 8 hardcoded collectors (version [cache-only], migration, schema-pack, stalled-jobs [absent-table tolerant], usage-shape, setup-smells, uninstalled-brain-pack, uninstalled-bundled), each in its own try/catch; `rankFindings` orders critical>warn>info then collector order, caps the info tail, and drops `workspace_dependent` findings when `remote` (A1). `render.ts` is the shared `=`-bar renderer used by the advisor AND `post-install-advisory.ts` (generalized to a single current-state `recommended-set.RECOMMENDED`, `install`→`scaffold`). `history.ts` appends bounded `~/.gbrain/advisor-history.jsonl` (no DB migration) for since-last-run deltas; local-only. `apply.resolveApplyTarget` is the allowlist+injection guard for `commands/advisor.ts --apply <id>` (structured argv, never a shell; local-only). The `advisor` op (`operations.ts`) is read-scoped, NOT localOnly, gated by `mcp.publish_advisor` (config.ts; default off) and strictly read-only on remote. CLI wired in `cli.ts` (`CLI_ONLY` + dispatch). Bundled skill `skills/gbrain-advisor/` + weekly cron recipe. Tests: `test/advisor-{core,apply,op-gate,ranking-eval}.test.ts`.+- `src/core/advisor/{types,run,render,recommended-set,history,apply,collect-*}.ts` + `src/commands/advisor.ts` (#2180) — `gbrain advisor`: read-only ranked actions from brain state. `run.runAdvisor` executes the hardcoded COLLECTORS array (version [cache-only], migration, schema-pack, stalled-jobs [absent-table tolerant], usage-shape, setup-smells, uninstalled-brain-pack, uninstalled-bundled, chronicle, mcp-client-fit), each in its own try/catch; `collect-mcp-client-fit.ts` (E3) flags full-surface MCP clients whose 30d usage fits STARTER_OPS (exact `rescope-client --surface starter` fix; ≥10-call threshold; automation-shaped clients excluded per D12) plus STARTER_OPS drift (top-used ops missing; starter members unused 90d) via the shared `src/core/mcp-usage.ts` reader — starter membership is judged against the exported `ALWAYS_INCLUDED_STARTER_OPS` (surface.ts) so the always-included lane never reads as unused, and the missing-from-starter arm excludes `localOnly` ops (never proposable for a network surface, mirroring derive-starter-ops) — REMOTE runs redact client identifiers to aggregate counts (amendment 29), and its dismiss/snooze rides the nag-state engine with its own `~/.gbrain/advisor-usage-nag-state.json` (local runs only); `rankFindings` orders critical>warn>info then collector order, caps the info tail, and drops `workspace_dependent` findings when `remote` (A1). `render.ts` is the shared `=`-bar renderer used by the advisor AND `post-install-advisory.ts` (generalized to a single current-state `recommended-set.RECOMMENDED`, `install`→`scaffold`). `history.ts` appends bounded `~/.gbrain/advisor-history.jsonl` (no DB migration) for since-last-run deltas; local-only. `apply.resolveApplyTarget` is the allowlist+injection guard for `commands/advisor.ts --apply <id>` (structured argv, never a shell; local-only). The `advisor` op (`operations.ts`) is read-scoped, NOT localOnly, gated by `mcp.publish_advisor` (config.ts; default off) and strictly read-only on remote. CLI wired in `cli.ts` (`CLI_ONLY` + dispatch). Bundled skill `skills/gbrain-advisor/` + weekly cron recipe. Tests: `test/advisor-{core,apply,op-gate,ranking-eval}.test.ts`.- `src/core/chronicle/{eligibility,config,backstop,extract-events,ontology,narrative}.ts` + `src/eval/chronicle/harness.ts` + `src/commands/eval-chronicle.ts` (#2390) — Life Chronicle: the temporal spine. `eligibility.isChronicleEligible` decides which pages auto-emit events (meeting/conversation/calendar-event + directory rescue; diary and event pages NEVER eligible — privacy + anti-loop). `backstop.runChronicleBackstop` is the put_page hook body (fires ONLY on `status==='imported'` + the auto-link trust gate + the default-OFF `auto_chronicle` flag; enqueues a `chronicle_extract` minion job — LLM never runs on the write path). `extract-events.runChronicleExtract` is the job body: deterministic when/who, injectable judge (default = chat gateway; output cap 4000 tokens by default, operator override `chronicle.judge_max_tokens`), an ALL-or-nothing parse barrier (`isValidProposal` requires a real parseable date — a malformed batch writes NOTHING), then content-addressed `life/events/` pages + a `timeline_entries` projection via `engine.upsertEventProjection` (dedup `(event_page_id, date)`; idempotent re-runs). An unusable judge response is never recorded as `no_events` (#2606): a `stopReason: 'length'` truncation or a no-JSON-array response (`parseJudgeJson` returns `null` on parse failure; `[]` only for a legitimate empty array) surfaces as `status: 'skipped'` with reason `judge_truncated` / `judge_parse_failed`. `ontology.ts` carries the deterministic pieces of the bi-temporal per-entity ontology that RIDES THE `facts` TABLE (migration v122 adds `dimension`/`value`/`value_hash`/`dim_status`): `valueHash` (normalized, timestamp-free → crash-retry idempotent), `normalizeDimension` (seed alias lexicon), `isNovelDimension` (novel → quarantined, excluded from resolution/context until confirmed). The engine methods (`mergeOntologyFact` — corroborate on same value, forward-supersede via `valid_until`+`superseded_by` on a new value, backdated conflicts kept + flagged; `getOntology` with `--asof` valid-time travel; `discoverOntologyDimensions`; `findOntologyConflicts` — currently-open rows only) live in BOTH engines; both engines are on the R8 `valid_until` write allow-list (engine-layer, `dimension IS NOT NULL` rows only). Chronicle reads (`getTimelineForDate`/`getSince`/`getLastSeen`/`getOnThisDay`) JOIN the depth page (`deleted_at IS NULL`), hide soft-deleted event projections at READ time, and order by event `effective_date` for intra-day sequence. Ops: `chronicle_day`/`chronicle_since`/`chronicle_last_seen`/`chronicle_on_this_day`/`ontology_*`/`volunteer_chronicle` (agent orientation via `src/core/context/chronicle-context.ts`)/`chronicle_backfill` (admin, localOnly). Diary privacy: diary-sourced ontology + conflict values redacted for `ctx.remote !== false` callers. Search: `applyChronicleTypeBoost` in `search/hybrid.ts` (bounded [1.0,1.25], fires only inside the `recency !== 'off'` post-fusion branch → non-temporal search bit-for-bit unchanged). Advisor collector `collect-chronicle.ts` (conflicts + coverage gap); doctor `chronicle_projection_health` (BRAIN category). Eval: `gbrain eval chronicle` — deterministic, own in-memory PGLite, 6 gold tasks (day order, last-seen, supersession, asof, conflict, isolation), exit 0 iff 6/6. Tests: `test/chronicle-*.test.ts`, `test/eval-chronicle.test.ts`.- `src/core/skill-manifest.ts` — parser for `skill-manifest.json` records. Used by skillpack installer to detect drift between the shipped bundle and the user's local edits, so updates merge instead of overwriting.- `src/commands/routing-eval.ts` + `src/core/routing-eval.ts` — `gbrain routing-eval` catches user phrasings that route to the wrong skill. Reads `skills/<name>/routing-eval.jsonl` fixtures (`{intent, expected_skill, ambiguous_with?}`). Structural layer runs in `check-resolvable` by default (zero API cost). `--llm` is a placeholder for a future LLM tie-break layer; today it emits a stderr notice and runs structural only. Uses `autoDetectSkillsDirReadOnly` and the same multi-file resolver merge as `check-resolvable`, so on OpenClaw layouts (`skills/RESOLVER.md` + `../AGENTS.md`) all three commands see the same trigger index. RESOLVER.md rows carry the full frontmatter `triggers:` arrays so the structural matcher sees realistic phrasings; ambiguous-fixture annotations cover deliberate skill chains like `enrich → article-enrichment`.@@ -253,13 +253,13 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/core/minions/transcript.ts` — renders `subagent_messages` + `subagent_tool_executions` to markdown. Tool rows splice under their owning assistant `tool_use` by `tool_use_id`. UTF-8-safe truncation; unknown block types fall through to fenced JSON.- `src/core/minions/plugin-loader.ts` — `GBRAIN_PLUGIN_PATH` discovery. Absolute paths only, left-wins collision, `gbrain.plugin.json` with `plugin_version: "gbrain-plugin-v1"`, plugins ship DEFS only (no new tools), `allowed_tools:` validated at load time against the derived registry.- `src/core/minions/tools/brain-allowlist.ts` — derives the subagent tool registry from `src/core/operations.ts` (15-name allow-list, size pinned by `test/brain-allowlist.serial.test.ts`). Includes `add_timeline_entry` (the canonical timeline write), fenced server-side by the same `enforceSubagentSlugFence` policy as `put_page`. By default `put_page` schema is namespace-wrapped per subagent (`^wiki/agents/<subagentId>/.+`). When `BuildBrainToolsOpts.allowedSlugPrefixes` is set, the put_page schema describes the prefix list to the model and the OperationContext is threaded with `allowedSlugPrefixes` — trust comes from `PROTECTED_JOB_NAMES` gating subagent submission (MCP cannot reach this field); only cycle.ts (synthesize/patterns) and direct CLI submitters set it. Allow-list includes `get_recent_salience` + `find_anomalies` but deliberately NOT `get_recent_transcripts` (all subagent calls run `ctx.remote === true` and the trust gate rejects remote callers, so it would always reject; the cycle synthesize phase calls `discoverTranscripts` directly instead). `paramsToInputSchema()` consumes `paramDefToSchema` from `src/mcp/tool-defs.ts`; required-aggregation at the tool-def level stays here (the shared helper is per-param).-- `src/mcp/tool-defs.ts` — `buildToolDefs(ops)` helper; MCP server + subagent tool registry both call it, byte-for-byte equivalence pinned by `test/mcp-tool-defs.test.ts`. Exports the recursive `paramDefToSchema(p: ParamDef)` — single source of truth for ParamDef→JSON Schema mapping shared by three consumers: `buildToolDefs` (stdio MCP), `src/commands/serve-http.ts:837` (HTTP MCP `tools/list`), and `src/core/minions/tools/brain-allowlist.ts:84` (subagent registry). Recursive on `items` so nested array-of-arrays preserves inner shape on the wire. Key ordering (type, description, enum, default, items) is intentional so `JSON.stringify` output stays byte-stable. `test/mcp-tool-defs.test.ts` has a `findArrayWithoutItems` walker that fails on any `type: 'array'` lacking `items.type`.+- `src/mcp/tool-defs.ts` — `buildToolDefs(ops, opts?)` helper; the stdio MCP server, the OAuth HTTP `tools/list` (WP3 amendment 14 unified the former inline mapper onto it), and the subagent tool registry all consume it, byte-for-byte equivalence pinned by `test/mcp-tool-defs.test.ts`. Default emission is byte-identical to the pre-WP3 output; `opts.strictParams: true` (when `mcp.strict_params` resolves `'reject'`) additionally declares the `_meta`/`dry_run` passthrough keys in `properties` and closes each schema with `additionalProperties: false` (D14.1 — schema-validating clients must not strip `_meta.session_id`); both emission states pinned. Exports the recursive `paramDefToSchema(p: ParamDef)` — single source of truth for ParamDef→JSON Schema mapping shared by `buildToolDefs` and `src/core/minions/tools/brain-allowlist.ts` (subagent registry). Recursive on `items` so nested array-of-arrays preserves inner shape on the wire. Key ordering (type, description, enum, default, items) is intentional so `JSON.stringify` output stays byte-stable. `test/mcp-tool-defs.test.ts` has a `findArrayWithoutItems` walker that fails on any `type: 'array'` lacking `items.type`.- `src/core/verbs.ts` — MEMORY_VERBS v1 (Cathedral 1): the four new frozen protocol verbs (`remember`, `entity`, `synthesize`, `forget`) as first-class Operations, plus `MEMORY_VERBS_VERSION` (single source of truth, =1), `VERB_NAMES`, the hand-authored `RESPONSE_SCHEMAS` registry (Operation carries input params only; response shapes live here and conformance validates LIVE responses against them), and `ERROR_SCHEMA`. The fifth verb is the extended `recall` op in operations.ts. RUNTIME LEAF invariant: operations.ts spreads `verbOperations` into its array at module-eval time, so this file must never statically import operations.ts VALUES (type-only imports fine; handlers use dynamic import) — violating it reintroduces a TDZ crash on whichever module evaluates second. Every verb error carries a populated `suggestion` + `protocol_version` (via `verbError` in operations.ts). The `forget` verb deliberately has NO cliHints (CLI_ONLY `forget` dispatches first and would shadow it). Frozen contract: docs/protocol/MEMORY_VERBS_v1.md; pinned by test/memory-verbs-conformance.test.ts.- `src/core/verbs/entity-card.ts` — `buildEntityCard(engine, sourceId, name, {remote})`: the zero-LLM sub-100ms card behind the `entity` verb. Resolution reuses the Retrieval Reflex arms (alias > exact title/slug > slug-suffix; exact-slug candidates include the RAW input because slugify flattens slashes in namespaced slugs); ties break on GREATEST(updated_at, last_retrieved_at). Per-arm degradation: a pre-page_aliases brain still resolves via arm 2 (aka returns empty, never throws). Card assembly is a parallel Promise.all of depth-1 indexed reads (page row, alias reverse lookup, getLinks+getBacklinks mentions-excluded cap 10, getBacklinkCounts, getTimeline(5), listFactsByEntity world-only-when-remote); deliberately NOT the recursive-CTE traversePaths — the card is a latency contract (CI gate: test/entity-card-perf.slow.test.ts, p99 < 100ms × GBRAIN_PERF_BUDGET_MULTIPLIER + 50× getPage-p50 ratio guard on a 20K corpus). `summary` runs through the exported `safeSynopsis` (the get_page fence boundary). Miss → keyword near-miss suggestions with create_safety hints.- `src/core/verbs/usage-log.ts` — E4 observability sidecar: one JSONL line per verb call at `~/.gbrain/integrations/memory-verbs/usage.jsonl` (gbrainPath — GBRAIN_HOME honored; `brainId()` = the resolved gbrain home). LOCAL ONLY, never uploaded, stats-only (lock-free 10MB rotation may drop lines; O_APPEND line-atomic, best-effort on Windows). `logVerbUsage` is fire-and-forget (never awaited, never throws); written from the DISPATCH layer so param-validation failures count. `readVerbUsage`/`earliestVerbUsageTs` feed `gbrain protocol stats` (incl. measured TTHW vs the init-stamped `protocol_installed_at`) and the doctor `memory_verbs_usage` check.- `src/core/verbs/conformance.ts` + `src/core/verbs/conformance-fixtures.ts` — the conformance runner core (transport-agnostic: minimal `ConformanceClient` = list_tools + call_tool) and the embedded fixture set. Deterministic by construction: shape/enum/behavior/round-trip checks only, never ranking quality. Validation is NON-STRICT on extra fields (additive-forever means unknown fields are always legal). Entity-card cases seed via put_page when the target exposes it and skip honestly on verbs-only targets; synthesize is cost-gated behind --synthesize. `validateAgainstSchema` is a minimal JSON-Schema-subset validator (type unions, required, properties, enum, const, items). Fixtures mirror to `test/fixtures/memory-verbs/cases.json` (BrainBench seeds; drift-guarded by the conformance test). The negative self-test (test/memory-verbs-conformance.test.ts) proves the runner FAILS a lying server.- `src/core/facts/write-single.ts` — `writeSingleFact(fact, ctx)`: the zero-LLM single-fact seam behind `remember` [E1]. `runFactsPipeline` is extraction-first (LLM-gated) and cannot back a pre-formed fact; this reuses the pipeline's post-extraction stages directly: resolve → embedding-cosine dedup (same 0.95 threshold) → fence-first write with the same legacy DB-only fallbacks (thin-client, unparented, stub-guard). Supersession [X1]: deterministic rule — same entity_slug + same kind + similarity ≥ threshold + DIFFERENT text ⇒ the new fact supersedes (fence path: append new + forgetFactInFence(old) + superseded_by link; DB path: engine insertFact supersedeId). Provenance lands on NewFact.source verbatim (no FactsBackstopCtx). No embedding provider ⇒ `degraded_dedup: true` (near-duplicates may insert — documented).-- `src/mcp/surface.ts` — MCP tool-surface modes: `'verbs'` (exactly the ops marked `verb: true`) | `'full'` (default — identity; existing installs unchanged). `parseSurfaceFlag` (strict, loud reject), `resolveSurface` (flag > config `mcp_surface` > full), `filterOpsForSurface`, `allowedOpNames`. 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). Pinned by test/mcp-surface.test.ts.+- `src/mcp/surface.ts` — MCP tool-surface modes: `'verbs'` (exactly the ops marked `verb: true`) | `'starter'` (the ~26-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 FOV-6b fallback daily slice (`BRAIN_TOOL_ALLOWLIST` + the agent lane `submit_agent`/`get_agent_job`) + `whoami` + `request_tools`; 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) is the exported always-set consumed by BOTH `derive-starter-ops.ts` and the advisor starter-fit collector, so neither re-types the composition (an out-of-sync copy in the collector once produced a perpetual bogus unused-starter finding). `parseSurfaceFlag` (strict, loud reject), `resolveSurface` (flag > config `mcp_surface` > full), `filterOpsForSurface`, `allowedOpNames`. 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). WP4 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).- `src/commands/protocol.ts` — `gbrain protocol [--json] | conformance [--target <http-url|stdio-cmd>] [--token] [--synthesize] | stats [--days N]`. `--json` emits input schemas from the LIVE Operation defs + RESPONSE_SCHEMAS (doc/code can't drift). Conformance default target self-spawns gbrain's own stdio server (dev `.ts` entry vs compiled binary both handled); CI certifies stdio with --synthesize (no key ⇒ asserts the clean `unavailable` error). Stats aggregates the usage sidecar + the measured TTHW; output states "local JSONL only — never uploaded". CLI_ONLY + SELF_HELP wired in cli.ts; no pre-bound engine.- `src/core/minions/attachments.ts` — Attachment validation (path traversal, null byte, oversize, base64, duplicate detection).- `src/commands/agent.ts` — `gbrain agent run <prompt> [flags]` CLI. 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.@@ -268,9 +268,15 @@ per-release `**vX.Y.Z:**` narration — CI enforces this- `src/commands/features.ts` — `gbrain features --json --auto-fix`: usage scan + feature adoption salesman.- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn (no inline `crashCount`/`startWorker`/`child.on('exit')`); `--max-rss 2048` and `maxCrashes: 5` preserved. `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` adds `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`); `src/core/config.ts` adds the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID, startup checks `kill -0 <pid>` before refusing to start (stale lock from a crashed process no longer blocks). (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector.- `src/mcp/server.ts` — MCP stdio server (generated from operations). Tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path. Stdin `'end'` / `'close'` shutdown hooks are skipped when `process.env.MCP_STDIO === '1'` — gateway-piped stdio MCP wrappers (OpenClaw's `bundle-mcp`) pipe the handshake then close their stdin half, which would otherwise kill the server before the first tool call; signal handlers (SIGTERM/SIGINT/SIGHUP) + the parent-process watchdog still cover legitimate disconnects. `src/commands/serve.ts` exposes `ServeOptions.mcpStdio?: boolean` as a test seam so the guard is exercisable without process.env mutation. Pinned by `test/serve-stdio-lifecycle.test.ts`.-- `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)`, `validateParams(op, params)`. Single source of truth for `(ctx, params)` handler arg order and the 5-field `OperationContext` shape (engine + config + logger + dryRun + remote). Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. 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). New logging paths route through this helper, not `JSON.stringify(params)`.-- `src/mcp/rate-limit.ts` — Bounded-LRU token-bucket limiter. `buildDefaultLimiters()` returns the two-bucket pipeline: pre-auth IP (30/60s, fires BEFORE the DB lookup so brute-force load against `access_tokens` is capped) + post-auth token-id (60/60s). Tracks `lastTouchedMs` separately from `lastRefillMs` so an exhausted key can't be reset by hammering past the TTL. LRU cap bounds memory under attacker-controlled key growth.-- `src/commands/serve-http.ts` — Express 5 HTTP MCP server with OAuth 2.1, admin dashboard, and SSE live activity feed. Started via `gbrain serve --http [--port N] [--token-ttl N] [--enable-dcr] [--public-url URL] [--bind HOST] [--log-full-params]`. Combines MCP SDK's `mcpAuthRouter` (authorize/token/register/revoke), a custom `client_credentials` handler running BEFORE the router (SDK's token endpoint throws `UnsupportedGrantTypeError` for CC; custom handler falls through for `auth_code` / `refresh_token`), `requireBearerAuth` middleware for `/mcp` with scope enforcement + `localOnly` rejection before op dispatch, and `express-rate-limit` at 50 req / 15 min on `/token`. Serves the built admin SPA from `admin/dist/` with SPA fallback. `/admin/events` SSE broadcasts every MCP request. `cookie-parser` wired (Express 5 has no built-in). Startup logging prints port, engine, issuer URL (honors `--public-url`), client count, DCR status, and the admin bootstrap token line — but the generated token's raw value only prints when stderr is an interactive TTY (`shouldSuppressBootstrapPrint`): a non-TTY (containerized/piped) start hides it so the secret never lands in centralized log storage, env-sourced tokens (`$GBRAIN_ADMIN_BOOTSTRAP_TOKEN`) are always hidden, `--print-admin-token` forces the raw value on a trusted terminal, and `--suppress-bootstrap-token` hides everything. The `/mcp` request handler's OperationContext literal sets `remote: true` explicitly (without it `submit_job`'s protected-name guard at `operations.ts:1391` saw a falsy undefined and a `read+write`-scoped OAuth token could submit `shell` jobs — RCE). `summarizeMcpParams` from `src/mcp/dispatch.ts` feeds both `mcp_request_log` writes and the SSE feed by default (raw via `--log-full-params`). Cookie `Secure` flag set behind HTTPS or a public-URL proxy; magic-link nonce store LRU-bounded; DCR disable routes through the `GBrainOAuthProvider` `dcrDisabled` constructor option (not a router monkey-patch); `transport.handleRequest` wrapped in try/catch to return a JSON-RPC 500 envelope; OperationError + unexpected exceptions unified through `buildError` / `serializeError` so `/mcp` always returns the same envelope. `/health` is liveness-only via `probeLiveness(sql, engineName, version, timeoutMs)` racing `sql\`SELECT 1\`` against the exported `HEALTH_TIMEOUT_MS = 3000` (returns the same `ProbeHealthResult` tagged-union as `probeHealth`, single timer-cleanup site, single 503 envelope); body shape `{status, version, engine}` only. Full stats moved to admin-only `/admin/api/full-stats` (gated by `requireAdmin`, calls `probeHealth(engine, ...)`) — keeps `getStats()`'s 6× count(*) off the public route so a saturated pool doesn't trigger orchestrator restart cascades. Every OAuth/admin/audit SQL call routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` so it works against PGLite; the four `mcp_request_log.params` INSERT sites (success / auth_failed / scope_denied / server-error) go through `executeRawJsonb(engine, ...)` so the column stores real objects (`params->>'op'` returns `search`, not the quoted string). `--bind HOST` defaults `127.0.0.1` (self-hosters pass `--bind 0.0.0.0`); a stderr WARN fires when `--public-url` is set without `--bind`; the banner prints a `Bind:` line. `AuthInfo.sourceId` + `AuthInfo.allowedSources` + `AuthInfo.takesHoldersAllowList` are the typed source of truth, populated by `oauth-provider.ts:verifyAccessToken` (source scope from the `oauth_clients` row; takes-holders from `access_tokens.permissions.takes_holders` for legacy bearer tokens). The `/mcp` dispatch site reads `authInfo.takesHoldersAllowList ?? ['world']` — absent grants (OAuth-client tokens, pre-v29 brains) fail closed to world-only takes visibility, while an explicit `[]` grant is preserved as deny-all; pinned end-to-end by `test/e2e/serve-http-takes-holders.test.ts`. The HTTP MCP `tools/list` handler at `:837-849` uses `paramDefToSchema(v)` from `src/mcp/tool-defs.ts` so array params keep `items` (strict-mode OAuth clients otherwise reject the whole tool list). `POST /ingest` enforces the slug-prefix write fence at the ROUTE, not the op layer: the route hands its payload to the `ingest_capture` minion handler, which deliberately bypasses `put_page`, so no `OperationContext` exists and `enforceClientSlugFence` never runs — a slug-bound client must therefore supply `X-Gbrain-Slug` and it must satisfy `slugUnderBoundPrefixes`, else 403 (without the check a bound client could overwrite any page, in the `default` source, since untrusted payloads carry no source grant). confidential revoke: a pre-router `/revoke` handler validates the RFC 7009 body, verifies hash-only secrets for both `client_secret_post` and `client_secret_basic`, rejects mixed authentication, preserves the SDK path for public clients, and separates opaque client-auth failures from retryable/backend failures. OAuth metadata advertises both confidential methods. Pinned by `test/e2e/serve-http-oauth.test.ts`. three admin routes: `/admin/api/calibration/profile`, `/admin/api/calibration/charts/:type` (image/svg+xml; type in {brier-trend, domain-bars, pattern-statements, abandoned-threads}), `/admin/api/calibration/pattern/:id` (drill-down). The manual mint route `/admin/api/register-client` accepts optional `source` + `federatedRead` bindings mirroring the CLI's `--source`/`--federated-read` (validated via `normalizeSourceInput`/`normalizeFederatedReadInput` from `src/core/source-id.ts`; omitting both preserves the default binding `source_id='default'` / `federated_read=[source_id]`, invalid values return a structured 400 `invalid_source`), so an admin SPA or provisioning proxy can mint a source-confined client over HTTP; pinned by `test/register-client-source-normalize.test.ts`.+- `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 extracted 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, D7), 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`), each producer isolated so one failure never drops another's key; empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock` (D8). Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier (amendment 33/D10): 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` / `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 amendment-33 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). New logging paths route through this helper, not `JSON.stringify(params)`.+- `src/mcp/validate-params.ts` — param normalization + validation extracted from dispatch (WP3, direct unit surface). `validateParams` (required/type/enum — enum membership is a TYPE error in BOTH strict modes; the caller's raw value is never echoed into the message), `normalizeOptionalParams` (null/`''` optional-param idioms become truly absent, copy-on-write), `findUnknownParams` (unknown top-level keys on the NORMALIZED object; `UNKNOWN_PARAM_ALLOWLIST` = `_meta` + `dry_run`; per-op did-you-mean from the op's OWN declared params only), `buildUnknownParamWarnBlock` (the model-visible warn notice), `resolveStrictParamsMode(engine, config)` (dual-plane `mcp.strict_params`, DB > file > `'warn'`; a failed DB read applies the LAST successfully read DB mode, held per process — fail-closed, so a transient config outage on a reject-mode server cannot re-open the warn grace period; test seam `resetStrictParamsModeCache()`). Privacy: raw unknown key names reach the CALLER only, never `mcp_request_log`. Pinned by test/validate-params.test.ts.+- `src/mcp/publish-gates.ts` — publish-gate resolution for the honest tools/list (WP1). `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.+- `src/mcp/tool-catalog.ts` — `renderToolCatalogMarkdown()`: the docs/TOOL_CATALOG.md renderer (E6). 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.+- `src/core/surface-audit.ts` — `writeSurfaceChangeAudit(engine, audit)`: the surface-mutation audit trail (amendment 32/ENG-8). Every surface mutation (rescope CLI, `POST /admin/api/rescope-client`, `request_tools` persist) writes one typed `mcp_request_log` row — `operation='surface_change'`, params a RAW object `{actor, client_id, old, new, via}` via `executeRawJsonb` (never `JSON.stringify` into `::jsonb`). Zero new DDL; rides `idx_mcp_log_time_agent` + the retention TODO. Best-effort: a failed audit write warns to stderr, never fails the committed mutation (callers needing fail-closed semantics inspect the returned boolean). CLI-actor rows are written even though stdio ops don't otherwise log (documented exception — audit outranks the transport-logging convention). The usage reader excludes these rows from op-call stats.+- `src/core/mcp-usage.ts` — `readClientOpUsage(engine, {days})`: the ONE shared reader over `mcp_request_log` (amendment 30), consumed by `gbrain auth clients --usage` (E4), the advisor `mcp-client-fit` collector (E3), and `scripts/derive-starter-ops.ts`. Encodes the row-hygiene rules once (`normalizeLoggedOperation`): JSON-RPC method rows (`tools/list`, `initialize`, …) and `surface_change` audit rows drop; the legacy `tools/call:<name>` prefix strips to the op name, and the hygiene check re-runs on the stripped name (`tools/call:tools/list` is still not an op call). Only `status IN ('success','success_with_warnings')` rows count as usage — denied or erroring traffic cannot "use" its way into starter derivation or advisor fit findings. Windows on `created_at` (rides `idx_mcp_log_time_agent`); plain SQL through `engine.executeRaw`, both engines. D12 behavioral automation classification: `likely_automation` = >90% of calls are `context_pack`/`delta` boundary verbs (the hook lane is stdio and never logs, so there is no name convention to key on). Sees HTTP clients ONLY — stdio never writes the log. Pinned by test/mcp-usage.test.ts.+- `docs/protocol/MCP_META_CHANNELS.md` — normative `_meta` conventions for MCP tool responses: one producer per top-level key, additive-forever within a key, producer isolation, and the registered-keys table (`brain_hot_memory`, `retrieval`, `warnings`). Anything the model must SEE rides a content block (mainstream harnesses don't feed `_meta` to the model); `_meta` serves structured consumers. Add a key by registering it in the table — one producer, additive-forever.+- `src/mcp/rate-limit.ts` — Bounded-LRU token-bucket limiter. `buildDefaultLimiters()` returns the two-bucket pipeline: pre-auth IP (30/60s, fires BEFORE the DB lookup so brute-force load against `access_tokens` is capped) + post-auth token-id (60/60s). Tracks `lastTouchedMs` separately from `lastRefillMs` so an exhausted key can't be reset by hammering past the TTL. LRU cap bounds memory under attacker-controlled key growth. `refund(key)` returns one consumed token (capped at the limit) — the `request_tools` persist path refunds when a race-lost 0-row UPDATE (concurrent operator pin) means no write actually happened; dry-run previews never draw a token at all (the limiter meters actual writes only).+- `src/commands/serve-http.ts` — Express 5 HTTP MCP server with OAuth 2.1, admin dashboard, and SSE live activity feed. Started via `gbrain serve --http [--port N] [--token-ttl N] [--enable-dcr] [--public-url URL] [--bind HOST] [--log-full-params]`. Combines MCP SDK's `mcpAuthRouter` (authorize/token/register/revoke), a custom `client_credentials` handler running BEFORE the router (SDK's token endpoint throws `UnsupportedGrantTypeError` for CC; custom handler falls through for `auth_code` / `refresh_token`), `requireBearerAuth` middleware for `/mcp` with scope enforcement + `localOnly` rejection before op dispatch, and `express-rate-limit` at 50 req / 15 min on `/token`. Serves the built admin SPA from `admin/dist/` with SPA fallback. `/admin/events` SSE broadcasts every MCP request. `cookie-parser` wired (Express 5 has no built-in). Startup logging prints port, engine, issuer URL (honors `--public-url`), client count, DCR status, and the admin bootstrap token line — but the generated token's raw value only prints when stderr is an interactive TTY (`shouldSuppressBootstrapPrint`): a non-TTY (containerized/piped) start hides it so the secret never lands in centralized log storage, env-sourced tokens (`$GBRAIN_ADMIN_BOOTSTRAP_TOKEN`) are always hidden, `--print-admin-token` forces the raw value on a trusted terminal, and `--suppress-bootstrap-token` hides everything. The `/mcp` request handler's OperationContext literal sets `remote: true` explicitly (without it `submit_job`'s protected-name guard at `operations.ts:1391` saw a falsy undefined and a `read+write`-scoped OAuth token could submit `shell` jobs — RCE). `summarizeMcpParams` from `src/mcp/dispatch.ts` feeds both `mcp_request_log` writes and the SSE feed by default (raw via `--log-full-params`). Cookie `Secure` flag set behind HTTPS or a public-URL proxy; magic-link nonce store LRU-bounded; DCR disable routes through the `GBrainOAuthProvider` `dcrDisabled` constructor option (not a router monkey-patch); `transport.handleRequest` wrapped in try/catch to return a JSON-RPC 500 envelope; OperationError + unexpected exceptions unified through `buildError` / `serializeError` so `/mcp` always returns the same envelope. `/health` is liveness-only via `probeLiveness(sql, engineName, version, timeoutMs)` racing `sql\`SELECT 1\`` against the exported `HEALTH_TIMEOUT_MS = 3000` (returns the same `ProbeHealthResult` tagged-union as `probeHealth`, single timer-cleanup site, single 503 envelope); body shape `{status, version, engine}` only. Full stats moved to admin-only `/admin/api/full-stats` (gated by `requireAdmin`, calls `probeHealth(engine, ...)`) — keeps `getStats()`'s 6× count(*) off the public route so a saturated pool doesn't trigger orchestrator restart cascades. Every OAuth/admin/audit SQL call routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` so it works against PGLite; the four `mcp_request_log.params` INSERT sites (success / auth_failed / scope_denied / server-error) go through `executeRawJsonb(engine, ...)` so the column stores real objects (`params->>'op'` returns `search`, not the quoted string). `--bind HOST` defaults `127.0.0.1` (self-hosters pass `--bind 0.0.0.0`); a stderr WARN fires when `--public-url` is set without `--bind`; the banner prints a `Bind:` line. `AuthInfo.sourceId` + `AuthInfo.allowedSources` + `AuthInfo.takesHoldersAllowList` are the typed source of truth, populated by `oauth-provider.ts:verifyAccessToken` (source scope from the `oauth_clients` row; takes-holders from `access_tokens.permissions.takes_holders` for legacy bearer tokens). The `/mcp` dispatch site reads `authInfo.takesHoldersAllowList ?? ['world']` — absent grants (OAuth-client tokens, pre-v29 brains) fail closed to world-only takes visibility, while an explicit `[]` grant is preserved as deny-all; pinned end-to-end by `test/e2e/serve-http-takes-holders.test.ts`. The HTTP MCP `tools/list` handler at `:837-849` uses `paramDefToSchema(v)` from `src/mcp/tool-defs.ts` so array params keep `items` (strict-mode OAuth clients otherwise reject the whole tool list). `POST /ingest` enforces the slug-prefix write fence at the ROUTE, not the op layer: the route hands its payload to the `ingest_capture` minion handler, which deliberately bypasses `put_page`, so no `OperationContext` exists and `enforceClientSlugFence` never runs — a slug-bound client must therefore supply `X-Gbrain-Slug` and it must satisfy `slugUnderBoundPrefixes`, else 403 (without the check a bound client could overwrite any page, in the `default` source, since untrusted payloads carry no source grant). confidential revoke: a pre-router `/revoke` handler validates the RFC 7009 body, verifies hash-only secrets for both `client_secret_post` and `client_secret_basic`, rejects mixed authentication, preserves the SDK path for public clients, and separates opaque client-auth failures from retryable/backend failures. OAuth metadata advertises both confidential methods. Pinned by `test/e2e/serve-http-oauth.test.ts`. three admin routes: `/admin/api/calibration/profile`, `/admin/api/calibration/charts/:type` (image/svg+xml; type in {brier-trend, domain-bars, pattern-statements, abandoned-threads}), `/admin/api/calibration/pattern/:id` (drill-down). The manual mint route `/admin/api/register-client` accepts optional `source` + `federatedRead` bindings mirroring the CLI's `--source`/`--federated-read` (validated via `normalizeSourceInput`/`normalizeFederatedReadInput` from `src/core/source-id.ts`; omitting both preserves the default binding `source_id='default'` / `federated_read=[source_id]`, invalid values return a structured 400 `invalid_source`), so an admin SPA or provisioning proxy can mint a source-confined client over HTTP; pinned by `test/register-client-source-normalize.test.ts`. The `/mcp` tools/list is the WP1 honest catalog: per-request filters (token scope incl. the FOV-4 `agentCallable` carve-out, bound-client fence via `opAllowedForBoundClient`, publish gates via `disabledOpsForPublishGates`) over the surface-filtered op set, schemas via `buildToolDefs` (strict emission when `mcp.strict_params` resolves reject); the tools/list `mcp_request_log` row records the listed size as `params.tool_count` (amendment 23 stopgap). Call-time op-level denials the list should have prevented — the inline scope deny, publish-gate backstop (`config_key=...`), fence op-level deny (`fence=op`, classified via `isListLevelDenialEnvelope`) — log `status='denied_after_list'` instead of `'error'` (amendment 33/D10; the trend-to-zero honest-catalog metric, see docs/operations/mcp-surface-runbook.md) — every tools/call row's status resolves through `requestLogStatusForResult` (dispatch.ts) on BOTH transports. The admin health-indicators error rate counts `status NOT IN ('success','success_with_warnings')` and excludes `operation='surface_change'` audit rows from numerator AND denominator (audit rows record operator/self actions, not traffic). Per-request surface resolution lives in `resolveEffectiveSurface`: a `verbs` ceiling skips the default-surface config read, and a failed read applies the last successfully read default per process (fail-closed — a transient config outage cannot widen a NULL-surface client).- `src/core/sql-query.ts` — engine-aware tagged-template SQL adapter for OAuth/admin/auth infrastructure. `sqlQueryForEngine(engine)` returns a `SqlQuery` (`(strings, ...values) => Promise<rows[]>`) that walks the template, builds `$N` positional SQL, asserts every value is a `SqlValue` (string | number | bigint | boolean | Date | null), and routes through `engine.executeRaw(sql, params)` (Postgres via postgres.js `unsafe(sql, params)`, PGLite via `db.query(sql, params)`). Deliberately narrower than postgres.js's `sql` tag: no nested fragments, `sql.json()`, `sql.unsafe()`, `sql.begin()`, or array binding — the narrow scalar-only surface is the feature (keeps it from drifting into a partial postgres.js clone). JSONB writes go through `executeRawJsonb(engine, sql, scalarParams, jsonbParams)` which composes positional `$N::jsonb` casts and passes JS **objects** through; an object reaches the wire with the correct type oid, so executeRawJsonb is safe (verified by `test/sql-query.test.ts` on PGLite, `test/e2e/auth-permissions.test.ts:67` on Postgres). Positional binding is NOT universally immune, though: binding a `JSON.stringify(x)` **string** to a bare `$N::jsonb` via `unsafe()` double-encodes it into a jsonb string scalar on real Postgres (the #2339 class; PGLite hides it). Fixes: pass a raw object (executeRawJsonb / `sql.json`), or cast through `$N::text::jsonb`. `scripts/check-jsonb-pattern.sh` (template grep) doesn't fire on `executeRawJsonb(...)` because it passes objects; the positional `$N::jsonb` + `JSON.stringify` form is caught by `scripts/check-jsonb-params.mjs`. Consumed by `src/commands/auth.ts`, `src/commands/serve-http.ts`, `src/core/oauth-provider.ts`, `src/commands/files.ts`, `src/mcp/http-transport.ts` so all five work uniformly against PGLite and Postgres.- `src/commands/serve.ts` — `gbrain serve` stdio MCP entrypoint with idempotent shutdown across every parent-disconnect signal. Stdio EOF, SIGTERM, SIGINT, SIGHUP, and parent-process death (every reparent case — PID 1, launchd subreaper, systemd, tmux, or a parent shell with `PR_SET_CHILD_SUBREAPER`) all funnel into one `cleanup(reason)` that releases the engine and the PGLite write-lock dir within 5 seconds (otherwise the lock is held indefinitely after Claude Desktop / Cursor / launchd-managed gateways disconnect, forcing a 5-minute stale-lock wait on next start). Watchdog reparent check is `getParentPid() !== initialParentPid` (the `=== 1` check missed the subreaper case under launchd/systemd). Bun's `process.ppid` cache is stale across reparenting ([oven-sh/bun#30305](https://github.com/oven-sh/bun/issues/30305)) so `getParentPid()` runs `spawnSync('ps', ['-o', 'ppid=', '-p', PID])` per tick. Startup probe verifies `ps` is on PATH; if not (stripped containers, busybox), the watchdog skips installing AND emits a loud `[gbrain serve] watchdog disabled: ps unavailable ...` stderr line so operators see the degraded mode. Pinned by `test/serve-stdio-lifecycle.test.ts` (22 cases). Credit @Aragorn2046 + @seungsu-kr.- `src/core/oauth-provider.ts` — `GBrainOAuthProvider` implementing the MCP SDK's `OAuthServerProvider` + `OAuthRegisteredClientsStore`. Backed by raw SQL (works on both PGLite and Postgres — OAuth is infrastructure, not a BrainEngine concern). Full OAuth 2.1: `authorize` + `exchangeAuthorizationCode` with PKCE, `client_credentials`, `refresh_token` with rotation, `revokeToken`, `registerClient` (DCR validates redirect_uri is `https://` or loopback per RFC 6749 §3.1.2.1). All tokens + client secrets SHA-256 hashed before storage. Auth codes single-use with 10-minute TTL via atomic `DELETE...RETURNING` (closes RFC 6749 §10.5 TOCTOU); refresh rotation also `DELETE...RETURNING` (§10.4 stolen-token detection). `pgArray()` escapes commas/quotes/braces so a comma-bearing redirect_uri can't smuggle a second array element. Legacy `access_tokens` fallback in `verifyAccessToken` grandfathers pre-v0.26 bearer tokens as `read+write+admin`, and threads BOTH stored grants off the token's `permissions` JSONB: `source_id` via `parseLegacyTokenScope` and `takes_holders` via `parseTakesHoldersAllowList` (both in `src/core/legacy-token-scope.ts`, shared with the legacy HTTP transport so the two transports cannot drift; `[]` takes-holders preserved as explicit deny-all, missing/non-array → undefined → the `/mcp` dispatch site's fail-closed `['world']`; OAuth-client tokens carry no takes-holders grant pending per-client storage — TODOS.md). `sweepExpiredTokens()` runs on startup in try/catch and returns the count via `RETURNING 1` + array length. RFC hardening: `client_id` folded atomically into the `DELETE WHERE` for both auth-code exchange and refresh rotation (wrong-client paths don't burn the row); refresh-scope-subset enforced against the original grant on the row (RFC 6749 §6, so revoking a scope shrinks existing refresh tokens); `client_id` bound on `revokeToken` (RFC 7009 §2.1); `/token` `redirect_uri` validated against the `/authorize` value (RFC 6749 §4.1.3, empty-string treated as missing not wildcard); bare `catch {}` in `verifyAccessToken`/`getClient` replaced by `isUndefinedColumnError` from `src/core/utils.ts` (only SQLSTATE 42703 falls through to legacy; lock timeouts/network blips throw); `dcrDisabled` constructor option lets `serve-http.ts` disable `/register` without monkey-patching the router. Module-private `coerceTimestamp()` normalizes postgres-driver-as-string BIGINT columns to JS numbers at 5 read sites (`getClient` for RFC 7591 §3.2.1 numeric timestamps, `exchangeRefreshToken` + `verifyAccessToken` for the SDK's `typeof === 'number'` check); throws on NaN/Infinity (fail loud at boundary), returns undefined for SQL NULL (callers treat NULL as expired). Not promoted to `utils.ts` — generic BIGINT precision-loss risk. `registerClient` honors `token_endpoint_auth_method: "none"` (RFC 7591 §3.2.1): public PKCE clients store `client_secret_hash = NULL` and the response omits `client_secret`; confidential clients (`client_secret_post` / `client_secret_basic`) keep their one-time-reveal shape; `getClient` normalizes NULL `client_secret_hash` to JS `undefined` so the SDK's clientAuth path accepts public clients. `verifyAccessToken` JOINs `oauth_clients.source_id` (write scope, scalar) + `oauth_clients.federated_read` (read scope, TEXT[]) + `oauth_clients.bound_slug_prefixes` (write fence, TEXT[] — consumed by `enforceClientSlugFence` in `operations.ts`) onto the returned `AuthInfo`; legacy brains degrade via `isUndefinedColumnError` fallback, dropping the newest projection first. `rescopeClient(clientId, {sourceId?, federatedRead?, boundSlugPrefixes?})` is the trusted-operator rescope (CLI `gbrain auth rescope-client`, admin `POST /admin/api/rescope-client`); `boundSlugPrefixes` is tri-state — undefined leaves the binding untouched, `null` clears it, a non-empty array replaces it (explicit empty array rejected as ambiguous deny-all) — so roster churn updates the write fence in place without rotating secrets. with `src/commands/serve-http.ts`: custom `/token` middleware that runs BEFORE the MCP SDK's `clientAuth`. The SDK does plaintext compare against the request's `client_secret`; gbrain stores SHA-256 hashes only, so every confidential-client `/token` request would fail. The middleware detects confidential auth via `Authorization: Basic` header OR `client_secret_post` form body (both shapes per RFC 6749 §2.3.1), verifies via `verifyClient(client_id, presented_secret)` (SHA-256 hash compare), and falls through to the SDK for public PKCE clients (which the SDK's clientAuth still accepts via NULL-`client_secret_hash` normalization). Pinned by `test/oauth-confidential-client.test.ts` (both `client_secret_basic` and `client_secret_post`).diff --git a/docs/architecture/thin-client.md b/docs/architecture/thin-client.mdindex 96b99ef640..017654c500 100644--- a/docs/architecture/thin-client.md+++ b/docs/architecture/thin-client.md@@ -10,6 +10,16 @@ empty local PGLite, so a populated remote brain can't silently return"No results." Local-only commands refuse with a pinpoint hint instead offalling through.+**Surface posture:** thin clients stay FULL-surface. The thin-client CLI routes+arbitrary `gbrain <op>` invocations over MCP, so a narrowed per-client surface+(`oauth_clients.surface`, WP4) would break commands the install legitimately+owns — bootstrap pins `--surface full` on its serve registrations and operators+should keep thin-client OAuth rows at `full` (or NULL). The stdio transport has+no client row at all: it serves the server-resolved surface directly, and the+per-client ceiling machinery (`effectiveSurfaceForClient`) applies only to the+OAuth HTTP transport. The starter/verbs narrowing is for agent-harness clients,+not for thin-client installs.+Key files (per-file detail lives in each file's `KEY_FILES.md` entry; this doccarries the routing-seam picture):diff --git a/docs/mcp/CLAUDE_CODE.md b/docs/mcp/CLAUDE_CODE.mdindex 0d566a94db..710437fdeb 100644--- a/docs/mcp/CLAUDE_CODE.md+++ b/docs/mcp/CLAUDE_CODE.md@@ -21,8 +21,10 @@ That's it. Claude Code spawns `gbrain serve` as a stdio subprocess. No server, ntunnel, no token needed. Works with both PGLite and Supabase engines.`--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. Drop the flag for the full+`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 (~26 ops total). Drop the flag for the fulloperation catalog (`get_page`, `put_page`, `search`, graph ops, …) — `full` isthe default and what existing installs already run.diff --git a/docs/mcp/DEPLOY.md b/docs/mcp/DEPLOY.mdindex 7e7df56a1f..7c6ebdcffe 100644--- a/docs/mcp/DEPLOY.md+++ b/docs/mcp/DEPLOY.md@@ -27,6 +27,7 @@ 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 (~26 ops: the verbs plus the daily-driver set);omit the flag (default `full`) for every operation.### Remote over OAuth 2.1 (recommended)diff --git a/docs/operations/mcp-surface-runbook.md b/docs/operations/mcp-surface-runbook.mdnew file mode 100644index 0000000000..249b62040d--- /dev/null+++ b/docs/operations/mcp-surface-runbook.md@@ -0,0 +1,211 @@+# MCP surface runbook++Operator moves for the remote MCP surface (the truthful-surface wave:+honest per-token tools/list, per-client surfaces, strict-params grace+period, STARTER_OPS). Current behavior only; release history lives in+`CHANGELOG.md` + git. Companion references: the generated+[`docs/TOOL_CATALOG.md`](../TOOL_CATALOG.md) (every non-localOnly op with+scope/starter/gate), `docs/protocol/MEMORY_VERBS_v1.md` (surface modes),+`docs/protocol/MCP_META_CHANNELS.md` (`_meta` conventions).++Everything below assumes `gbrain serve --http` (the OAuth transport).+tools/list is recomputed **per request** — none of these moves needs a+server restart unless it says so.++## Move 1 — flip a publish gate++Gated ops (`Operation.publishGateKey`): `list_skills` / `get_skill` /+`list_brain_skillpack` (`mcp.publish_skills`) and `advisor`+(`mcp.publish_advisor`). Both gates default OFF: the ops are hidden from+remote tools/list AND denied at call time.++```bash+gbrain config set mcp.publish_skills true # or mcp.publish_advisor+```++**Expected outcome:** the very next tools/list from any token includes the+gated ops (dual-plane read, DB > file, per request — no restart). Flipping+back to `false` hides them again on the next list; the call-time backstop+denies immediately with the machine-readable detail+`config_key=mcp.publish_skills`. A failed gate READ during tools/list+resolves to hidden (fail-closed consent posture), never a failed list.++## Move 2 — rescope a client's surface++```bash+gbrain auth clients --usage # who needs it? (op counts, surface, last seen)+gbrain auth rescope-client <client_id> --surface starter # verbs | starter | full | clear+```++Usage counts only successful calls (`success` / `success_with_warnings`) —+a client flooding denials or errors shows zero usage, so denied traffic can+never argue its way into a wider surface or the starter derivation.++**Expected outcomes:**+- The client's NEXT request resolves the new surface (per-request+ ceiling-bounded resolution: `min(server --surface ceiling, client row)`)+ — the client must re-issue tools/list to see the change; cached tool+ lists in a long-lived session go stale until it does.+- An audit row lands in `mcp_request_log` (`operation='surface_change'`,+ params carrying actor/old/new/via) — every surface mutation writes one+ (rescope CLI, admin endpoint, request_tools persist):++```sql+SELECT created_at, params FROM mcp_request_log+ WHERE operation = 'surface_change' ORDER BY created_at DESC LIMIT 10;+```++- A CLI rescope sets `surface_set_by='operator'` — the operator lock:+ `request_tools` persist cannot override it. (The persist itself is+ rate-limited per client and meters actual writes only — `dry_run`+ previews are free.)+- The advisor's `mcp-client-fit` collector proposes exactly this command+ for full-surface clients whose 30d usage fits STARTER_OPS.++**Default for NULL-surface clients** (including future DCR+self-registrations):++```bash+gbrain config set mcp.default_surface_dcr starter # verbs | starter | full+```++Dual-plane read (DB > file), applied on each client's next request,+ceiling-bounded like everything else; unset means NULL-surface clients+resolve to the server ceiling (pre-wave behavior). Pre-seed important+clients with an explicit `rescope-client --surface full` before flipping it.++## Move 3 — flip strict params from warn to reject++`mcp.strict_params` governs unknown-argument handling at dispatch:+`warn` (default) accepts the call, surfaces `_meta.warnings` + a+model-visible notice block, and logs the success as+`status='success_with_warnings'`; `reject` returns `invalid_params` with+did-you-mean suggestions.++**Flip criterion (evidence-based, amendment 13):** near-zero+`success_with_warnings` rows over 30 days of production traffic —++```sql+SELECT count(*) FROM mcp_request_log+ WHERE status = 'success_with_warnings'+ AND created_at > now() - interval '30 days';+```++When that count is ~0, clients have adapted; flip:++```bash+gbrain config set mcp.strict_params reject+```++**Expected outcome (schema emission change):** besides rejecting unknown+args, tools/list schemas change shape — each `inputSchema` closes with+`additionalProperties: false` and declares the `_meta`/`dry_run`+passthrough keys (D14.1), keeping schema-validating clients aligned with+the server's reject posture. Read per request; flipping back to `warn`+reopens the schemas on the next list. A transient config-read failure+cannot re-open the grace period: dispatch holds the last successfully+read mode per process, so a reject-mode server stays reject through a+config outage. `test/mcp-tool-defs.test.ts` pins+both emission states; the default stays `warn` until the project-level+flip (see TODOS.md, strict_params reject-flip).++## Move 4 — change STARTER_OPS++```bash+bun run scripts/derive-starter-ops.ts [--days 30]+```++reads production `mcp_request_log` through the shared usage reader+(automation-shaped clients excluded, per-client DISTINCT-op sets weighted+by client count), prints a proposed daily-driver block with a provenance+header. Paste it into `src/mcp/surface.ts` (replacing+`FALLBACK_DAILY_OPS`) — the script never edits files. Then:++```bash+bun test test/mcp-surface.test.ts # membership + monotonicity: verbs ⊆ starter ⊆ full+bun run scripts/generate-tool-catalog.ts # refresh the Starter column; freshness guard fails CI otherwise+```++`VERB_NAMES` + `whoami` + `request_tools` + the agent lane are composed in+`surface.ts` and always included — the derivation only proposes the daily+slice. The advisor's drift finding (`mcp_starter_ops_drift`) is the+standing prompt to re-run this move.++## Incident levers++- **`GBRAIN_MCP_FORCE_SURFACE=verbs|starter|full`** — narrow-only clamp+ (FOV-6a): it `min()`s into every resolved surface and can NEVER widen+ past the configured ceiling; widening requires an explicit `--surface`+ restart. Use it to clamp a misbehaving deployment down to verbs without+ touching client rows.+- **`GBRAIN_SEARCH_SALVAGE=off`** — restores pre-wave all-or-nothing+ retrieval (no allSettled salvage, strict budget, no minKeep failsafe)+ if the fail-loud retrieval behavior itself misbehaves.++**Total embed outage, what to expect (ENG-6):** the query cache is+uncacheable by construction during a full embedding outage — `query_cache`+keys on embedding similarity, and both store and lookup no-op on a null+embedding. Expect cache hit rate ~0 (`gbrain search stats`) and+keyword-only degraded results carrying `_meta.retrieval.degraded` stages+plus the model-visible block on empty results. This is the designed+degradation, not a second incident; only PARTIAL degradations (expansion+failed, vector arm failed) get short-TTL cache entries.++## The honest-catalog metric (trend to zero)++The wave's working metric (amendment 33): op-level call-time denials the+tools/list filter should have made impossible. serve-http logs them as+`status='denied_after_list'` — scope denials, publish-gate backstop+denials (`config_key=...`), and bound-client fence OP-level denials+(`fence=op`). Argument-level slug-fence denials are legitimate for a+listed op and excluded (D10).++```sql+SELECT count(*) FROM mcp_request_log+ WHERE status = 'denied_after_list'+ AND created_at > now() - interval '30 days';+```++A non-zero trend means list-time and call-time predicates drifted (a bug)+or a client is calling ops it was never shown (staleness/guessing) —+either way, worth a look at the offending rows' `token_name` + `operation`.++## First 5 minutes after a deploy++Migrate-then-serve is atomic per process (initSchema runs before listen).+Post-deploy checks, in order:++1. **tools/list count per token class** — for each token class you run+ (admin/full, read/starter, agent-only, slug-bound): list tools and eyeball+ the count (starter ≈ the STARTER_OPS size, full ≈ the TOOL_CATALOG count,+ agent-only = its minimal lane). Counts are also queryable:+ `SELECT token_name, params->>'tool_count' FROM mcp_request_log WHERE operation='tools/list' ORDER BY created_at DESC LIMIT 10;`+2. **Empty-query probe shows the degraded block** — call `search` with a+ nonsense query; the empty result must carry a second content block+ ("0 results. … clean miss." or degraded stages) + `_meta.retrieval`.+3. **Workerless submit warns** — `submit_agent` while no worker runs must+ still succeed and carry `queue_state.warning` (worker_alive false).+4. **put_page lint fields present** — put an uncited page; the response+ must carry `writer_lint.top_findings` (or the zero-findings shape).++### As a smoke-tests.d drop-in++The smoke-test skill runs user scripts from `~/.gbrain/smoke-tests.d/*.sh`.+Save the four checks as a drop-in (fill in URL + token):++```bash+#!/usr/bin/env bash+# ~/.gbrain/smoke-tests.d/check-remote-mcp.sh — truthful-surface deploy checks+set -euo pipefail+URL="${GBRAIN_MCP_URL:?set GBRAIN_MCP_URL}"; TOK="${GBRAIN_MCP_TOKEN:?set GBRAIN_MCP_TOKEN}"+call() { curl -sf "$URL" -H "Authorization: Bearer $TOK" -H 'Content-Type: application/json' \+ -H 'Accept: application/json, text/event-stream' -d "$1"; }+# 1. tools/list responds and reports a sane count+N=$(call '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' | grep -o '"name"' | wc -l)+[ "$N" -gt 0 ] && echo "OK tools/list: $N tools" || { echo "FAIL tools/list"; exit 1; }+# 2. empty search carries the model-visible degradation block+call '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"search","arguments":{"query":"zzqx-no-such-thing-xkcd"}}}' \+ | grep -q '0 results' && echo 'OK empty-result loudness' || { echo 'FAIL empty-result block'; exit 1; }+# 3+4 need write/agent scopes — run only when the token has them:+# submit_agent → response contains "queue_state"; put_page → "writer_lint".+```diff --git a/docs/protocol/MCP_META_CHANNELS.md b/docs/protocol/MCP_META_CHANNELS.mdnew file mode 100644index 0000000000..9fe0fa58b8--- /dev/null+++ b/docs/protocol/MCP_META_CHANNELS.md@@ -0,0 +1,42 @@+# MCP `_meta` channels++Normative conventions for `ToolResult._meta` on gbrain's MCP surfaces+(WP2 amendment 9 / decision D3). `_meta` is the structured, out-of-band+channel for tool-call responses; the response BODY contract never changes+shape for it.++## Rules++1. **One producer per top-level key.** A producer owns exactly one+ namespaced key and never writes another producer's key. The dispatch+ layer (`src/mcp/dispatch.ts`) merges per top-level key — never wholesale+ `_meta` assignment.+2. **Additive-forever within a key.** Fields inside a key may be added,+ never renamed or removed — the RESPONSE_SCHEMAS discipline applied to+ `_meta`. Consumers must tolerate unknown fields.+3. **Producer isolation.** Every producer attaches inside its own+ try/catch. A failing producer degrades to its key being absent; it never+ drops another producer's key and never errors the tool call.+4. **Merge precedence.** Handler-emitted keys (via+ `OperationContext.emitResponseMeta`) attach first; transport hooks+ (`metaHook`) attach after and may add keys but shadow nothing that+ matters — key ownership (rule 1) makes ordering a non-event.+5. **Model visibility caveat.** Mainstream harnesses do NOT feed `_meta` to+ the model. Anything the model must SEE rides a content block (see the D8+ second text block on empty retrievals); `_meta` serves structured+ programmatic consumers (thin clients, harness plumbing, tests).++## Registered keys++| Key | Producer | Contents |+|-----|----------|----------|+| `brain_hot_memory` | serve-http `metaHook` (`getBrainHotMemoryMeta`) | Hot-memory facts relevant to the call (v0.31 eD3) |+| `retrieval` | `search`/`query` op handlers | `returned_count`, `retrieved_count`, `vector_enabled`, `expansion_applied`, `cache`, `token_budget`, `degraded[]` (closed stage vocabulary, D6), `hint` (non-contractual prose, E1) |+| `warnings` | dispatch strict-params warn mode (WP3) | `[{code: 'unknown_param', param, suggestion?}]` |++Inbound `_meta` (e.g. `_meta.session_id` inside tool ARGUMENTS, CX2-11) is a+separate, client-to-server plane. The eval-report `_meta.metric_glossary`+lives in JSON BODIES of eval commands — a third, unrelated plane. Ambient+recall (#4028) rides content/hooks, not `_meta`.++Adding a key: register it in the table above, one producer, additive-forever.diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.mdindex a88fca3553..9ecd0f0675 100644--- a/docs/protocol/MEMORY_VERBS_v1.md+++ b/docs/protocol/MEMORY_VERBS_v1.md@@ -71,10 +71,28 @@ 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 full` (the default)-exposes every operation, verbs included. Why default full: verbs is for-agents and quickstarts; full preserves existing advanced tooling. Persist a-default with `gbrain config set mcp_surface verbs`.+`unknown_tool` even when called by name). `--surface starter` exposes the+~26-op daily-driver set (`STARTER_OPS` in `src/mcp/surface.ts`): the seven+verbs plus the daily brain-tool slice, the agent lane, `whoami`, and the+`request_tools` discovery meta-op (re-derivable from production usage via+`scripts/derive-starter-ops.ts`). Monotonic by construction: verbs ⊆ starter ⊆ full+(pinned by test) — starter extends the ladder ABOVE verbs and never changes+verb semantics. `--surface full` (the default) exposes every operation,+verbs included. Why default full: verbs/starter are for agents and+quickstarts; full preserves existing advanced tooling. Persist a default+with `gbrain config set mcp_surface verbs`.++**Ceiling semantics (OAuth HTTP transport):** the server-resolved surface+is a CEILING, not the final answer. Each request resolves+`min(ceiling, client row surface ?? mcp.default_surface_dcr ?? ceiling)` —+so a verbs-pinned server always serves verbs regardless of client rows,+while a full server can narrow individual clients+(`gbrain auth rescope-client <id> --surface starter`) or let them narrow+themselves via `request_tools` (never past the ceiling; an operator-set+row is locked against self-service). Recomputed per request — rescopes+take effect on the client's next request; clients should re-issue+tools/list after a surface change. stdio and the legacy bearer transport+have no per-client row: they serve the server-resolved surface directly.## The verbs@@ -183,6 +201,36 @@ output_tokens, usd_estimate}, protocol_version }`.- No LLM configured ⇒ the protocol error `unavailable` with a fix — never afake answer.+#### synthesize compose status (v0.45.x, additive)++Every response additionally carries four ADDITIVE-FOREVER fields (absent on+pre-v0.45.x servers; a server that omits them still certifies):++- `synthesis_status` — how `answer` was produced: `ok` (LLM synthesis) or+ `extractive_fallback` (the LLM compose step failed but retrieval succeeded —+ `answer` is an extractive digest quoting ONLY retrieved pages, `sources`+ cite the digested pages). The remaining enum values (`empty_answer`,+ `not_json`, `no_llm`, `model_unusable`, `llm_error`) name compose-failure+ states a non-verb `think` surface may report; the verb converts them to the+ fallback or a typed error and never emits them itself.+- `pages_gathered` / `takes_gathered` — retrieval counts behind the answer.+- `warnings` — machine-stable pipeline warning codes (e.g.+ `LLM_OUTPUT_NOT_JSON`, `SYNTHESIS_EMPTY_ANSWER`, `LLM_CALL_FAILED: <class>`+ where `<class>` is one of the closed set `timeout` | `rate_limited` |+ `network` | `provider_error` — raw provider detail never rides the wire,+ `MODEL_NOT_USABLE:<reason>`).++Precedence (frozen): compose failure + NON-EMPTY gather ⇒+`extractive_fallback` — the digest is composed exclusively from gathered+pages, never fabricated. Compose failure + EMPTY gather ⇒ the protocol error+`unavailable` with message `retrieved 0 pages; compose failed: <warning-code>`+(an empty gather NEVER produces an answer). Provider/transport failures at+call time (429 / timeout / 5xx / network) are caught into `llm_error` and+follow the same precedence. No LLM configured stays the `unavailable`+configure-and-retry error regardless of gather — an extractive digest would+mask the misconfiguration forever. Refusals parse as `not_json` (coarse on+purpose, no dedicated status).+### forget(id, reason?) — writeExpire a fact by its opaque string id (from `remember` ordiff --git a/docs/tutorials/connect-coding-agent.md b/docs/tutorials/connect-coding-agent.mdindex 9804302d94..f6e09440ad 100644--- a/docs/tutorials/connect-coding-agent.md+++ b/docs/tutorials/connect-coding-agent.md@@ -160,7 +160,8 @@ That's the whole wire-up. No token, no URL, no tunnel. The agent spawns(`recall`, `remember`, `entity`, `synthesize`, `forget`, `context_pack`, `delta` —[MEMORY_VERBS v1](../protocol/MEMORY_VERBS_v1.md), frozen + additive-forever)instead of the full operation catalog, so the agent sees a tight, stable surface-instead of a 110-tool wall. Drop the flag (or pass `--surface full`) for every+instead of a 110-tool wall. `--surface starter` sits between: the verbs plus the+daily-driver set (~26 ops total). Drop the flag (or pass `--surface full`) for everyoperation. The default when the flag is omitted is `full`, so existing wire-upsare unchanged.@@ -192,12 +193,12 @@ about people, companies, decisions, projects, or past context:tokens → `search` (cheap hybrid, no expansion). Concept, landscape, or"all the X that do Y" questions → `query` FIRST — it recovers synonymphrasings `search` misses, and a populated `search` result set is not proof- of coverage. On the seven-verb surface the same split is `recall` (retrieve)+ of coverage. On the verbs surface the same split is `recall` (retrieve)vs `synthesize` (reasoned answer). Check the brain BEFORE answering frommemory or asking me. Never ask "who is X?" or "what did we decide about Y?"before checking — the brain probably already knows.2. **Write back.** When I make a decision, mention a new person/company, or land- on an idea worth keeping, write it to the brain: `remember` on the seven-verb+ on an idea worth keeping, write it to the brain: `remember` on the verbssurface (one fact, with provenance), or `put_page` on the full surface(entity pages under people/, companies/; decisions under decisions/ ornotes/). One insight, one page, linked.@@ -222,7 +223,7 @@ hundreds of linked pages and patterns you didn't know were there.**3. Briefing from your brain (not from the internet).** *"What do I need to knowbefore my 2pm with the Acme team?"* pulls your meeting history, the people,what's still open, what the brain doesn't know yet. The agent does your prep-because it read your context. (`query` — `synthesize` on the seven-verb surface —+because it read your context. (`query` — `synthesize` on the verbs surface —gives you the synthesized answer with citations; this is the example on the[README](../../README.md).)diff --git a/llms-full.txt b/llms-full.txtindex 6a27c000b4..0319f7029e 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -4004,6 +4004,7 @@ 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 (~26 ops: the verbs plus the daily-driver set);omit the flag (default `full`) for every operation.### Remote over OAuth 2.1 (recommended)@@ -4414,10 +4415,28 @@ 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 full` (the default)-exposes every operation, verbs included. Why default full: verbs is for-agents and quickstarts; full preserves existing advanced tooling. Persist a-default with `gbrain config set mcp_surface verbs`.+`unknown_tool` even when called by name). `--surface starter` exposes the+~26-op daily-driver set (`STARTER_OPS` in `src/mcp/surface.ts`): the seven+verbs plus the daily brain-tool slice, the agent lane, `whoami`, and the+`request_tools` discovery meta-op (re-derivable from production usage via+`scripts/derive-starter-ops.ts`). Monotonic by construction: verbs ⊆ starter ⊆ full+(pinned by test) — starter extends the ladder ABOVE verbs and never changes+verb semantics. `--surface full` (the default) exposes every operation,+verbs included. Why default full: verbs/starter are for agents and+quickstarts; full preserves existing advanced tooling. Persist a default+with `gbrain config set mcp_surface verbs`.++**Ceiling semantics (OAuth HTTP transport):** the server-resolved surface+is a CEILING, not the final answer. Each request resolves+`min(ceiling, client row surface ?? mcp.default_surface_dcr ?? ceiling)` —+so a verbs-pinned server always serves verbs regardless of client rows,+while a full server can narrow individual clients+(`gbrain auth rescope-client <id> --surface starter`) or let them narrow+themselves via `request_tools` (never past the ceiling; an operator-set+row is locked against self-service). Recomputed per request — rescopes+take effect on the client's next request; clients should re-issue+tools/list after a surface change. stdio and the legacy bearer transport+have no per-client row: they serve the server-resolved surface directly.## The verbs@@ -4526,6 +4545,36 @@ output_tokens, usd_estimate}, protocol_version }`.- No LLM configured ⇒ the protocol error `unavailable` with a fix — never afake answer.+#### synthesize compose status (v0.45.x, additive)++Every response additionally carries four ADDITIVE-FOREVER fields (absent on+pre-v0.45.x servers; a server that omits them still certifies):++- `synthesis_status` — how `answer` was produced: `ok` (LLM synthesis) or+ `extractive_fallback` (the LLM compose step failed but retrieval succeeded —+ `answer` is an extractive digest quoting ONLY retrieved pages, `sources`+ cite the digested pages). The remaining enum values (`empty_answer`,+ `not_json`, `no_llm`, `model_unusable`, `llm_error`) name compose-failure+ states a non-verb `think` surface may report; the verb converts them to the+ fallback or a typed error and never emits them itself.+- `pages_gathered` / `takes_gathered` — retrieval counts behind the answer.+- `warnings` — machine-stable pipeline warning codes (e.g.+ `LLM_OUTPUT_NOT_JSON`, `SYNTHESIS_EMPTY_ANSWER`, `LLM_CALL_FAILED: <class>`+ where `<class>` is one of the closed set `timeout` | `rate_limited` |+ `network` | `provider_error` — raw provider detail never rides the wire,+ `MODEL_NOT_USABLE:<reason>`).++Precedence (frozen): compose failure + NON-EMPTY gather ⇒+`extractive_fallback` — the digest is composed exclusively from gathered+pages, never fabricated. Compose failure + EMPTY gather ⇒ the protocol error+`unavailable` with message `retrieved 0 pages; compose failed: <warning-code>`+(an empty gather NEVER produces an answer). Provider/transport failures at+call time (429 / timeout / 5xx / network) are caught into `llm_error` and+follow the same precedence. No LLM configured stays the `unavailable`+configure-and-retry error regardless of gather — an extractive digest would+mask the misconfiguration forever. Refusals parse as `not_json` (coarse on+purpose, no dedicated status).+### forget(id, reason?) — writeExpire a fact by its opaque string id (from `remember` ordiff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex d49fe37cfb..c6ff9fc52a 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -1,7 +1,7 @@{"id": "gbrain-context-engine","name": "gbrain",- "version": "0.45.12.0",+ "version": "0.45.13.0","description": "Personal knowledge brain with Postgres + pgvector hybrid search","family": "bundle-plugin","configSchema": {diff --git a/package.json b/package.jsonindex 66e8a23c81..c3743d2359 100644--- a/package.json+++ b/package.json@@ -79,6 +79,7 @@"check:privacy": "bash scripts/check-privacy.sh","check:proposal-pii": "bash scripts/check-proposal-pii.sh","check:eval-glossary": "bash scripts/check-eval-glossary-fresh.sh",+ "check:tool-catalog": "bash scripts/check-tool-catalog-fresh.sh","check:skills-manifest": "bash scripts/check-skills-manifest-fresh.sh","check:test-names": "bash scripts/check-test-real-names.sh","check:progress": "bash scripts/check-progress-to-stdout.sh",@@ -154,7 +155,7 @@"bun": ">=1.3.10"},"license": "MIT",- "version": "0.45.12.0",+ "version": "0.45.13.0","overrides": {"@hono/node-server": "^2.0.5","fast-uri": "^3.1.5",diff --git a/scripts/check-operations-filter-bypass.sh b/scripts/check-operations-filter-bypass.shindex 45b8d24ce9..84ceac1498 100755--- a/scripts/check-operations-filter-bypass.sh+++ b/scripts/check-operations-filter-bypass.sh@@ -49,6 +49,8 @@ ALLOWED=("src/commands/enrich.ts" # local CLI tool; calls put_page handler with remote=false, not network-exposed"src/commands/book-mirror.ts" # local CLI tool; not network-exposed"src/commands/tools-json.ts" # gbrain --tools-json introspection; full op list IS the purpose+ "src/mcp/publish-gates.ts" # reads op.publishGateKey/name only to compute gate-DISABLED sets; never lists/exposes ops+ "src/mcp/tool-catalog.ts" # docs/TOOL_CATALOG.md renderer; filters !op.localOnly at the boundary; never a transport surface"src/commands/serve-http.ts" # MUST APPLY .filter(op => !op.localOnly) — verified by grep below)diff --git a/scripts/check-tool-catalog-fresh.sh b/scripts/check-tool-catalog-fresh.shnew file mode 100755index 0000000000..5ddc7b3f3d--- /dev/null+++ b/scripts/check-tool-catalog-fresh.sh@@ -0,0 +1,40 @@+#!/usr/bin/env bash+# E6 — CI guard for docs/TOOL_CATALOG.md freshness.+#+# Mirrors scripts/check-eval-glossary-fresh.sh: regenerate the doc into a tmp+# file, diff against the committed version, fail the build if they drift.+# The renderer is config-independent + deterministic (no timestamps), so a+# diff means someone changed operations/surface metadata without running the+# generator.+#+# Run: bash scripts/check-tool-catalog-fresh.sh+# Wired into `bun run verify` via package.json `check:tool-catalog`.++set -euo pipefail++REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"+COMMITTED="$REPO_ROOT/docs/TOOL_CATALOG.md"+TMP="$(mktemp)"+trap 'rm -f "$TMP"' EXIT++if [ ! -f "$COMMITTED" ]; then+ echo "ERROR: $COMMITTED not found." >&2+ echo "Run: bun run scripts/generate-tool-catalog.ts" >&2+ exit 1+fi++cd "$REPO_ROOT"+bun -e "import { renderToolCatalogMarkdown } from './src/mcp/tool-catalog.ts'; process.stdout.write(renderToolCatalogMarkdown() + '\n');" > "$TMP"++if ! diff -q "$COMMITTED" "$TMP" >/dev/null 2>&1; then+ echo "ERROR: docs/TOOL_CATALOG.md is stale." >&2+ echo "" >&2+ echo "Diff between committed and freshly-generated:" >&2+ echo "" >&2+ diff -u "$COMMITTED" "$TMP" >&2 || true+ echo "" >&2+ echo "To regenerate: bun run scripts/generate-tool-catalog.ts" >&2+ exit 1+fi++echo "✓ docs/TOOL_CATALOG.md is fresh"diff --git a/scripts/derive-starter-ops.ts b/scripts/derive-starter-ops.tsnew file mode 100644index 0000000000..27c08899e3--- /dev/null+++ b/scripts/derive-starter-ops.ts@@ -0,0 +1,172 @@+#!/usr/bin/env bun+/**+ * derive-starter-ops.ts — propose the STARTER_OPS daily-driver slice from+ * production `mcp_request_log` usage (amendment 23 + D12).+ *+ * Run: bun run scripts/derive-starter-ops.ts [--days N] [--target N]+ *+ * Reads the active brain (loadConfig → engine) through the shared usage+ * reader (src/core/mcp-usage.ts — the same hygiene rules as the E4 CLI and+ * the E3 advisor drift check: JSON-RPC method rows and 'surface_change'+ * audit rows dropped, the legacy 'tools/call:<name>' prefix stripped),+ * excludes automation-shaped clients (D12: >90% context_pack/delta boundary+ * calls), and ranks ops by CLIENT COUNT — the union of per-client+ * DISTINCT-op sets, never raw call volume, so one chatty client cannot+ * define the starter set.+ *+ * PRINTS a proposed block for a human to paste into src/mcp/surface.ts+ * (replacing FALLBACK_DAILY_OPS). It NEVER edits files. The always-included+ * slices (VERB_NAMES spread + whoami + request_tools + the agent lane) are+ * composed in surface.ts itself and excluded from the proposal.+ *+ * Caveats printed with the proposal:+ * - HTTP clients only (stdio never writes mcp_request_log).+ * - BRAIN_TOOL_ALLOWLIST cross-check (D12): allowlist members missing from+ * the derived set are listed — dropping one strands subagent parity.+ * - test/mcp-surface.test.ts pins membership + monotonicity+ * (verbs ⊆ starter ⊆ full); run it after pasting.+ */++import { loadConfig, toEngineConfig } from '../src/core/config.ts';+import { createEngine } from '../src/core/engine-factory.ts';+import { readClientOpUsage, MCP_USAGE_DEFAULT_WINDOW_DAYS } from '../src/core/mcp-usage.ts';+import { operations } from '../src/core/operations.ts';+import { ALWAYS_INCLUDED_STARTER_OPS } from '../src/mcp/surface.ts';+import { BRAIN_TOOL_ALLOWLIST } from '../src/core/minions/tools/brain-allowlist.ts';++/** Ops surface.ts always includes regardless of derivation (shared constant). */+const ALWAYS_INCLUDED = ALWAYS_INCLUDED_STARTER_OPS;++/** Target total STARTER_OPS size (the "~20-op daily-driver set"). */+const DEFAULT_TARGET_SIZE = 20;++function parseArgs(argv: string[]): { days: number; target: number } {+ let days = MCP_USAGE_DEFAULT_WINDOW_DAYS;+ let target = DEFAULT_TARGET_SIZE;+ for (let i = 0; i < argv.length; i++) {+ if (argv[i] === '--days') {+ days = Number(argv[++i]);+ if (!Number.isInteger(days) || days < 1 || days > 3650) {+ console.error('--days must be an integer between 1 and 3650');+ process.exit(1);+ }+ } else if (argv[i] === '--target') {+ target = Number(argv[++i]);+ if (!Number.isInteger(target) || target < ALWAYS_INCLUDED.size) {+ console.error(`--target must be an integer >= ${ALWAYS_INCLUDED.size} (the always-included slice)`);+ process.exit(1);+ }+ } else {+ console.error(`Unknown flag: ${argv[i]}`);+ console.error('Usage: bun run scripts/derive-starter-ops.ts [--days N] [--target N]');+ process.exit(1);+ }+ }+ return { days, target };+}++const { days, target } = parseArgs(process.argv.slice(2));++const config = loadConfig();+if (!config) {+ console.error('No GBrain config found. Run `gbrain init` first, or set DATABASE_URL / GBRAIN_DATABASE_URL.');+ process.exit(1);+}+const engineConfig = toEngineConfig(config);+const engine = await createEngine(engineConfig);+await engine.connect(engineConfig);++async function run(): Promise<number> {+ let usage: Awaited<ReturnType<typeof readClientOpUsage>>;+ try {+ usage = await readClientOpUsage(engine, { days });+ } catch (e) {+ // A brain that never served remote MCP may lack the table entirely.+ console.error('Could not read mcp_request_log — has this brain ever served remote MCP?');+ console.error(` ${e instanceof Error ? e.message : String(e)}`);+ return 1;+ }+ const automation = usage.filter((u) => u.likely_automation);+ const real = usage.filter((u) => !u.likely_automation);++ const knownOps = new Map(operations.map((o) => [o.name, o]));++ // Client-count ranking over per-client DISTINCT-op sets (D12).+ const clientCount = new Map<string, number>();+ const callCount = new Map<string, number>();+ const skippedUnknown = new Set<string>();+ for (const u of real) {+ for (const op of u.distinct_ops) {+ const known = knownOps.get(op);+ if (!known) {+ skippedUnknown.add(op); // attempted-but-nonexistent names from error rows+ continue;+ }+ if (known.localOnly) continue; // never proposable for a network surface+ clientCount.set(op, (clientCount.get(op) ?? 0) + 1);+ callCount.set(op, (callCount.get(op) ?? 0) + (u.ops[op] ?? 0));+ }+ }++ const ranked = [...clientCount.entries()]+ .sort((a, b) => b[1] - a[1] || (callCount.get(b[0]) ?? 0) - (callCount.get(a[0]) ?? 0) || (a[0] < b[0] ? -1 : 1))+ .map(([op]) => op);+ const derivedSlots = Math.max(0, target - ALWAYS_INCLUDED.size);+ const proposal = ranked.filter((op) => !ALWAYS_INCLUDED.has(op)).slice(0, derivedSlots);++ const today = new Date().toISOString().slice(0, 10);+ const lines: string[] = [];+ lines.push('/**');+ lines.push(` * STARTER_OPS daily-driver slice — derived from production mcp_request_log.`);+ lines.push(` * Provenance: window=${days}d, generated=${today}, script=scripts/derive-starter-ops.ts,`);+ lines.push(` * clients=${real.length} (excluded ${automation.length} automation-shaped: >90% context_pack/delta).`);+ lines.push(` * HTTP clients only — stdio does not write mcp_request_log.`);+ lines.push(` * NOTE: VERB_NAMES + whoami + request_tools + the agent lane (submit_agent,`);+ lines.push(` * get_agent_job) are ALWAYS included by surface.ts and are not listed here.`);+ lines.push(' */');+ lines.push('const DERIVED_DAILY_OPS: readonly string[] = [');+ for (const op of proposal) {+ lines.push(` '${op}', // ${clientCount.get(op)} client${clientCount.get(op) === 1 ? '' : 's'}, ${callCount.get(op)} calls/${days}d`);+ }+ lines.push('];');++ console.log(`# derive-starter-ops — ${days}d window, ${usage.length} clients seen (${automation.length} automation-shaped excluded)\n`);+ if (real.length === 0) {+ console.log('No non-automation HTTP client usage in the window. The FOV-6b fallback');+ console.log('(BRAIN_TOOL_ALLOWLIST ∪ agent lane) in src/mcp/surface.ts remains the right set.');+ return 0;+ }++ console.log('Ranked ops (client count desc, then call count):');+ for (const op of ranked) {+ const marks: string[] = [];+ if (ALWAYS_INCLUDED.has(op)) marks.push('always-included');+ if (proposal.includes(op)) marks.push('PROPOSED');+ console.log(` ${op.padEnd(28)} clients=${clientCount.get(op)} calls=${callCount.get(op)}${marks.length ? ' [' + marks.join(', ') + ']' : ''}`);+ }+ if (skippedUnknown.size > 0) {+ console.log(`\nSkipped ${skippedUnknown.size} logged name(s) not in the operations catalog (failed-call attempts).`);+ }++ const allowlistMissing = [...BRAIN_TOOL_ALLOWLIST].filter(+ (op: string) => !proposal.includes(op) && !ALWAYS_INCLUDED.has(op),+ );+ if (allowlistMissing.length > 0) {+ console.log(`\nWARNING (D12 cross-check): BRAIN_TOOL_ALLOWLIST members absent from the proposal:`);+ console.log(` ${allowlistMissing.join(', ')}`);+ console.log(' Dropping these breaks subagent/starter parity — include them unless deliberate.');+ }++ console.log('\nProposed block — paste into src/mcp/surface.ts (replacing FALLBACK_DAILY_OPS),');+ console.log('then run: bun test --timeout=60000 test/mcp-surface.test.ts && bun run scripts/generate-tool-catalog.ts\n');+ console.log(lines.join('\n'));+ return 0;+}++let exitCode = 1;+try {+ exitCode = await run();+} finally {+ await engine.disconnect();+}+process.exit(exitCode);diff --git a/scripts/generate-tool-catalog.ts b/scripts/generate-tool-catalog.tsnew file mode 100644index 0000000000..d1a6ea4312--- /dev/null+++ b/scripts/generate-tool-catalog.ts@@ -0,0 +1,27 @@+#!/usr/bin/env bun+/**+ * E6 — auto-generate docs/TOOL_CATALOG.md from src/mcp/tool-catalog.ts.+ *+ * Run: bun run scripts/generate-tool-catalog.ts+ *+ * CI guard `scripts/check-tool-catalog-fresh.sh` (in `bun run verify`)+ * regenerates and diffs against the committed version — an out-of-date doc+ * fails the build. Mirrors the METRIC_GLOSSARY generator pattern+ * (scripts/generate-metric-glossary.ts).+ */++import { writeFileSync, mkdirSync } from 'fs';+import { dirname, join, resolve } from 'path';+import { fileURLToPath } from 'url';+import { renderToolCatalogMarkdown } from '../src/mcp/tool-catalog.ts';++const __dirname = dirname(fileURLToPath(import.meta.url));+const REPO_ROOT = resolve(__dirname, '..');+const OUT_PATH = join(REPO_ROOT, 'docs', 'TOOL_CATALOG.md');++const md = renderToolCatalogMarkdown() + '\n';++mkdirSync(dirname(OUT_PATH), { recursive: true });+writeFileSync(OUT_PATH, md, 'utf-8');++console.log(`Wrote ${OUT_PATH} (${md.length} bytes, ${md.split('\n').length} lines).`);diff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.shindex 20bdcc2eeb..9377c80114 100755--- a/scripts/run-verify-parallel.sh+++ b/scripts/run-verify-parallel.sh@@ -51,6 +51,7 @@ CHECKS=("check:cli-exec""check:system-of-record""check:eval-glossary"+ "check:tool-catalog""check:skills-manifest""check:no-pii-agent-voice""check:synthetic-corpus-privacy"diff --git a/src/cli.ts b/src/cli.tsindex 5fc33e82f4..02891ea4e4 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -33,7 +33,7 @@ import { serializeMarkdown } from './core/markdown.ts';import { parseGlobalFlags, setCliOptions, getCliOptions } from './core/cli-options.ts';import { conceptNudge } from './core/search/query-intent.ts';import type { CliOptions } from './core/cli-options.ts';-import { callRemoteTool, RemoteMcpError, unpackToolResult } from './core/mcp-client.ts';+import { callRemoteTool, RemoteMcpError, unpackToolResult, extractResponseMeta } from './core/mcp-client.ts';import { maybePromptForUpgrade } from './core/thin-client-upgrade-prompt.ts';import { CLI_FLAG_REGISTRY } from './core/cli-flag-registry.generated.ts';import { VERSION } from './version.ts';@@ -720,6 +720,10 @@ async function runThinClientRouted(timeoutMs,signal: sigintController.signal,});+ // T15/FOV-1: lift the server's retrieval meta off the envelope before+ // unpacking (old servers lack _meta — capture is simply skipped).+ const envelopeMeta = extractResponseMeta(raw);+ if (envelopeMeta?.retrieval) captureRetrievalMeta('retrieval', envelopeMeta.retrieval);const result = unpackToolResult(raw);const output = formatResult(op.name, result, params);if (output) process.stdout.write(output);@@ -1307,9 +1311,50 @@ export async function makeContext(engine: BrainEngine, params: Record<string, un// brain (that would be an untrusted-caller cross-brain hole over MCP).brainId: activeBrainId,...(localFederated ? { localFederatedSourceIds: localFederated } : {}),+ // T15/FOV-1: capture the retrieval meta for formatResult's empty-result+ // render (the local-engine twin of the MCP _meta.retrieval channel).+ emitResponseMeta: captureRetrievalMeta,};}+/**+ * T15/FOV-1: the retrieval meta for the CURRENT CLI invocation, captured+ * from either result path — the local engine path via ctx.emitResponseMeta,+ * the thin-client routed path via the envelope's `_meta.retrieval`. Read by+ * formatResult's empty-result branch so `gbrain search`/`query` stop+ * printing a bare "No results." when the pipeline actually degraded.+ * Module state is safe here: one op per CLI process.+ */+let lastRetrievalMeta: Record<string, unknown> | null = null;++export function captureRetrievalMeta(key: string, value: unknown): void {+ if (key === 'retrieval' && value !== null && typeof value === 'object') {+ lastRetrievalMeta = value as Record<string, unknown>;+ }+}++// Exported for tests.+export function resetRetrievalMetaForTests(): void {+ lastRetrievalMeta = null;+}++/** One-line parenthetical for the empty-result render. '' when no meta. */+function describeEmptyRetrieval(): string {+ const m = lastRetrievalMeta;+ if (!m) return '';+ const parts: string[] = [];+ if (typeof m.retrieved_count === 'number' && m.retrieved_count > 0) {+ parts.push(`retrieved ${m.retrieved_count} before trimming`);+ }+ const stages = Array.isArray(m.degraded)+ ? [...new Set((m.degraded as Array<{ stage?: string }>).map(d => d?.stage).filter(Boolean))]+ : [];+ parts.push(stages.length > 0+ ? `degraded: ${stages.join(', ')}`+ : 'clean miss — no retrieval degradation');+ return ` (${parts.join('; ')})`;+}+// Exported for tests (same import-safety contract as cliAliases/printOpHelp)./*** #2416: hint-only steering — a concept-shaped `search` gets a one-line@@ -1369,7 +1414,10 @@ export function formatResult(case 'query': {const results = result as any[];if (params.json === true) return JSON.stringify(results, null, 2) + '\n';- if (results.length === 0) return 'No results.\n';+ // T15/FOV-1: an empty result names its cause when the pipeline told us+ // (degradation stages from _meta.retrieval / the local meta capture) —+ // a bare "No results." was indistinguishable from a degraded pipeline.+ if (results.length === 0) return `No results.${describeEmptyRetrieval()}\n`;// v0.40.4 — --explain switches to per-stage attribution formatter.// Reads CliOptions.explain via the module-level singleton.const cliOpts = getCliOptions();@@ -3196,8 +3244,9 @@ ADMINstorage status [--repo <path>] Storage tier status and health[--json] (git-tracked vs supabase-only)serve MCP server (stdio)- --surface verbs|full Tool surface: the 5 memory verbs only, or- every op (default full; verbs = quickstart)+ --surface verbs|starter|full Tool surface: the 7 memory verbs, the ~20-op+ starter set, or every op (default full).+ On --http this is the per-client CEILING.serve --http [--port N] HTTP MCP server with OAuth 2.1--token-ttl N Access token TTL in seconds (default: 3600)--enable-dcr Enable Dynamic Client Registration (DCR clients default to authorization_code)diff --git a/src/commands/auth.ts b/src/commands/auth.tsindex d7eb78f089..3676c888ec 100644--- a/src/commands/auth.ts+++ b/src/commands/auth.ts@@ -552,8 +552,19 @@ async function registerClient(name: string, args: string[]) {* so widening happens here (trusted local CLI) or via the requireAdmin* /admin/api/rescope-client endpoint.*/+/**+ * WP4: parse the `--surface` rescope value. 'clear' → null (clears both+ * surface AND surface_set_by); one of the three known surfaces → itself;+ * anything else → undefined (caller errors out). Exported for unit tests.+ */+export function parseRescopeSurfaceValue(value: string): 'verbs' | 'starter' | 'full' | null | undefined {+ if (value === 'clear') return null;+ if (value === 'verbs' || value === 'starter' || value === 'full') return value;+ return undefined;+}+async function rescopeClient(clientId: string, args: string[]) {- const usage = 'Usage: auth rescope-client <client_id> [--source SOURCE] [--federated-read SRC1,SRC2,...] [--bound-slug-prefixes P1,P2|none]';+ const usage = 'Usage: auth rescope-client <client_id> [--source SOURCE] [--federated-read SRC1,SRC2,...] [--bound-slug-prefixes P1,P2|none] [--surface verbs|starter|full|clear]';if (!clientId) {console.error(usage);process.exit(1);@@ -564,6 +575,9 @@ async function rescopeClient(clientId: string, args: string[]) {// array = replace. Lets roster churn (channel joins/leaves) update the// write fence in place instead of register+rotate.let boundSlugPrefixes: string[] | null | undefined;+ // WP4: tri-state — undefined = untouched, null = clear ('clear'), value =+ // set + surface_set_by='operator' (the lock request_tools cannot override).+ let surface: 'verbs' | 'starter' | 'full' | null | undefined;for (let i = 0; i < args.length; i += 2) {const flag = args[i];const value = args[i + 1];@@ -579,28 +593,50 @@ async function rescopeClient(clientId: string, args: string[]) {boundSlugPrefixes = value === 'none'? null: value.split(',').map(s => s.trim()).filter(Boolean);+ } else if (flag === '--surface') {+ surface = parseRescopeSurfaceValue(value);+ if (surface === undefined) {+ console.error(`Error: --surface must be verbs | starter | full | clear (got "${value}")`);+ console.error(usage);+ process.exit(1);+ }} else {console.error(`Error: Unknown flag: ${flag}`);console.error(usage);process.exit(1);}}- if (sourceId === undefined && federatedRead === undefined && boundSlugPrefixes === undefined) {- console.error('Error: pass --source, --federated-read, and/or --bound-slug-prefixes');+ if (sourceId === undefined && federatedRead === undefined && boundSlugPrefixes === undefined && surface === undefined) {+ console.error('Error: pass --source, --federated-read, --bound-slug-prefixes, and/or --surface');console.error(usage);process.exit(1);}try {- await withConfiguredSql(async (sql) => {+ await withConfiguredSql(async (sql, engine) => {const { GBrainOAuthProvider } = await import('../core/oauth-provider.ts');const provider = new GBrainOAuthProvider({ sql });- const result = await provider.rescopeClient(clientId, { sourceId, federatedRead, boundSlugPrefixes });+ const result = await provider.rescopeClient(clientId, { sourceId, federatedRead, boundSlugPrefixes, surface });+ // WP4 (amendment 32 / ENG-8): every surface mutation writes an audit+ // row (this CLI, the admin endpoint, the request_tools persist).+ if (surface !== undefined) {+ const { writeSurfaceChangeAudit } = await import('../core/surface-audit.ts');+ await writeSurfaceChangeAudit(engine, {+ actor: 'operator',+ client_id: clientId,+ old: result.surfaceOld ?? null,+ new: result.surface ?? null,+ via: 'rescope_cli',+ });+ }console.log(`OAuth client rescoped: "${result.clientName}" (${result.clientId})\n`);console.log(` Write source: ${result.sourceId}`);console.log(` Federated reads: ${result.federatedRead.join(', ') || '<none>'}`);if (result.boundSlugPrefixes !== undefined) {console.log(` Bound slug prefixes: ${result.boundSlugPrefixes?.join(', ') ?? '<none — full-source write authority>'}`);}+ if (result.surface !== undefined) {+ console.log(` Tool surface: ${result.surface ?? '<cleared — server/config surface applies>'}${result.surface != null ? ' (operator-pinned; request_tools cannot override)' : ''}`);+ }console.log('\nTakes effect on the client\'s next request (existing tokens included).');});} catch (e: any) {@@ -609,6 +645,136 @@ async function rescopeClient(clientId: string, args: string[]) {}}+/**+ * E4 (WP4 expansion): `gbrain auth clients [--usage] [--days N] [--json]`.+ *+ * Lists OAuth clients with their scopes + per-client MCP tool surface+ * (`surface` / `surface_set_by`, WP4), and with `--usage` joins the+ * per-client op-call usage from `mcp_request_log` via the shared reader+ * (src/core/mcp-usage.ts — same hygiene rules as the E3 advisor collector+ * and scripts/derive-starter-ops.ts). Legacy bearer tokens that called in+ * the window appear too (they log under their token name) but carry no+ * per-client surface row. stdio clients never appear — that transport does+ * not write mcp_request_log.+ */+export function parseAuthClientsArgs(args: string[]): { usage: boolean; days: number; json: boolean } {+ const out = { usage: false, days: 30, json: false };+ for (let i = 0; i < args.length; i++) {+ const flag = args[i];+ if (flag === '--usage') out.usage = true;+ else if (flag === '--json') out.json = true;+ else if (flag === '--days') {+ const v = Number(args[i + 1]);+ if (!Number.isInteger(v) || v < 1 || v > 3650) {+ throw new Error('--days must be an integer between 1 and 3650');+ }+ out.days = v;+ i++;+ } else {+ throw new Error(`Unknown flag: ${flag}`);+ }+ }+ return out;+}++interface ClientRow {+ client_id: string;+ client_name: string | null;+ scope: string | null;+ surface: string | null;+ surface_set_by: string | null;+}++async function clientsCmd(args: string[]) {+ const usageLine = 'Usage: auth clients [--usage] [--days N] [--json]';+ let parsed: { usage: boolean; days: number; json: boolean };+ try {+ parsed = parseAuthClientsArgs(args);+ } catch (e: any) {+ console.error(`Error: ${e.message}`);+ console.error(usageLine);+ process.exit(1);+ }+ try {+ await withConfiguredSql(async (_sql, engine) => {+ // Surface columns land in migration v127; a pre-migration brain still+ // gets the listing (surface renders as unknown) instead of an error.+ let clients: ClientRow[];+ try {+ clients = await engine.executeRaw<ClientRow>(+ `SELECT client_id, client_name, scope, surface, surface_set_by+ FROM oauth_clients ORDER BY client_name, client_id`,+ );+ } catch {+ const bare = await engine.executeRaw<Omit<ClientRow, 'surface' | 'surface_set_by'>>(+ `SELECT client_id, client_name, scope FROM oauth_clients ORDER BY client_name, client_id`,+ );+ clients = bare.map(r => ({ ...r, surface: null, surface_set_by: null }));+ }++ const { readClientOpUsage } = await import('../core/mcp-usage.ts');+ const usage = parsed.usage ? await readClientOpUsage(engine, { days: parsed.days }) : [];+ const usageByToken = new Map(usage.map(u => [u.token_name, u]));+ const clientIds = new Set(clients.map(c => c.client_id));+ const legacyUsage = usage.filter(u => !clientIds.has(u.token_name));++ if (parsed.json) {+ console.log(JSON.stringify({+ window_days: parsed.days,+ usage_included: parsed.usage,+ clients: clients.map(c => ({+ client_id: c.client_id,+ client_name: c.client_name,+ scopes: c.scope,+ surface: c.surface,+ surface_set_by: c.surface_set_by,+ usage: usageByToken.get(c.client_id) ?? null,+ })),+ // Legacy bearer tokens seen in the window (no oauth_clients row).+ legacy_tokens: legacyUsage,+ }, null, 2));+ return;+ }++ if (clients.length === 0 && legacyUsage.length === 0) {+ console.log('No OAuth clients registered. Register one: gbrain auth register-client "my-client"');+ return;+ }+ const fmtTop = (u: (typeof usage)[number]) =>+ Object.entries(u.ops).slice(0, 5).map(([op, n]) => `${op}(${n})`).join(', ');+ for (const c of clients) {+ const u = usageByToken.get(c.client_id);+ console.log(`${c.client_name ?? '<unnamed>'} (${c.client_id})`);+ const surfaceStr = c.surface+ ? `${c.surface}${c.surface_set_by ? ` (set by ${c.surface_set_by})` : ''}`+ : '<server/config resolution>';+ console.log(` scopes: ${c.scope ?? '<none>'} surface: ${surfaceStr}`);+ if (parsed.usage) {+ if (u) {+ const auto = u.likely_automation ? ' [automation-shaped: >90% context_pack/delta]' : '';+ console.log(` calls (${parsed.days}d): ${u.total_calls} across ${u.distinct_ops.length} ops last seen: ${u.last_seen}${auto}`);+ console.log(` top ops: ${fmtTop(u)}`);+ } else {+ console.log(` calls (${parsed.days}d): 0 (no HTTP MCP calls in window; stdio use is not logged)`);+ }+ }+ console.log('');+ }+ if (parsed.usage && legacyUsage.length > 0) {+ console.log(`Legacy bearer tokens seen in the last ${parsed.days}d (no per-client surface row):`);+ for (const u of legacyUsage) {+ const auto = u.likely_automation ? ' [automation-shaped]' : '';+ console.log(` ${u.token_name}: ${u.total_calls} calls across ${u.distinct_ops.length} ops last seen: ${u.last_seen}${auto}`);+ console.log(` top ops: ${fmtTop(u)}`);+ }+ }+ });+ } catch (e: any) {+ console.error('Error:', e.message);+ process.exit(1);+ }+}+/*** Entry point for the `gbrain auth` CLI subcommand. Also reused by the* direct-script path (see bottom of file) so `bun run src/commands/auth.ts`@@ -652,6 +818,7 @@ export async function runAuth(args: string[]): Promise<void> {case 'register-client': await registerClient(rest[0], rest.slice(1)); return;case 'rescope-client': await rescopeClient(rest[0], rest.slice(1)); return;case 'revoke-client': await revokeClient(rest[0]); return;+ case 'clients': await clientsCmd(rest); return;case 'test': {const tokenIdx = rest.indexOf('--token');const url = rest.find(a => !a.startsWith('--') && a !== rest[tokenIdx + 1]);@@ -701,6 +868,15 @@ Usage:--source <id> New write source--federated-read <id1,id2,...> New read-scope source list--bound-slug-prefixes <p1,p2|none> Replace the slug-prefix write fence ('none' clears it)+ --surface <verbs|starter|full|clear> Pin the client's MCP tool surface (operator lock —+ request_tools cannot override; 'clear' removes the pin+ so server/config resolution applies again). Always+ bounded by the server's --surface ceiling.+ gbrain auth clients [--usage] [--days N] [--json] List OAuth clients with scopes + tool surface. --usage+ joins per-client op-call counts, top ops, and last-seen+ from mcp_request_log (default 30d window; HTTP clients+ only — stdio use is not logged). Automation-shaped+ clients (>90% context_pack/delta) are flagged.gbrain auth revoke-client <client_id> Hard-delete an OAuth 2.1 client (cascades to tokens + codes)gbrain auth test <url> --token <token> Smoke-test a remote MCP server`);diff --git a/src/commands/doctor.ts b/src/commands/doctor.tsindex b0e6e5f7fd..3191e152fb 100644--- a/src/commands/doctor.ts+++ b/src/commands/doctor.ts@@ -2087,13 +2087,48 @@ export async function computeQueueHealthCheck([`${oldWaitingHours} hours`],);- let liveWorkerQueues = new Set<string>();- if (oldWaitingRows.length > 0) {- const workers = opts.readWorkers- ? opts.readWorkers()- : (await import('../core/minions/worker-registry.ts')).readWorkers();- liveWorkerQueues = new Set(workers.map((w) => w.queue));- }+ // Read the live-worker registry unconditionally (was: only when old+ // embed-backfill rows existed) — the structured `details.worker_alive`+ // below needs it on every run. Cheap: one directory enumeration.+ const workers = opts.readWorkers+ ? opts.readWorkers()+ : (await import('../core/minions/worker-registry.ts')).readWorkers();+ const liveWorkerQueues = new Set(workers.map((w) => w.queue));++ // Minions-visibility wave: structured details so machine callers stop+ // parsing prose. depth = total waiting jobs; oldest_age_seconds = age of+ // the oldest waiting job (null when the queue is empty); worker_alive =+ // every queue holding waiting work has a live registered worker+ // (vacuously true with zero waiting jobs). Messages stay unchanged.+ // Perf note (twin of buildQueueDepths in status.ts): WHERE constrains+ // only `status` — the second column of the (queue, status, updated_at)+ // wedge index — so this GROUP BY full-scans minion_jobs today. Acceptable+ // at doctor frequency over pruned waiting sets; a partial+ // (queue, created_at) WHERE status='waiting' index is the fix if hot.+ const waitingByQueue: Array<{+ queue: string;+ depth: number | string;+ oldest_age_seconds: number | string | null;+ }> = await engine.executeRaw(+ `SELECT queue,+ count(*)::int AS depth,+ EXTRACT(EPOCH FROM (now() - min(created_at)))::int AS oldest_age_seconds+ FROM minion_jobs+ WHERE status = 'waiting'+ GROUP BY queue`,+ );+ const details: Record<string, unknown> = {+ depth: waitingByQueue.reduce((n, r) => n + Number(r.depth), 0),+ oldest_age_seconds: waitingByQueue.reduce<number | null>(+ (max, r) => {+ const age = r.oldest_age_seconds === null ? null : Number(r.oldest_age_seconds);+ if (age === null) return max;+ return max === null ? age : Math.max(max, age);+ },+ null,+ ),+ worker_alive: waitingByQueue.every((r) => liveWorkerQueues.has(r.queue)),+ };const problems: string[] = [];if (stalledRows.length > 0) {@@ -2146,12 +2181,14 @@ export async function computeQueueHealthCheck(name: 'queue_health',status: 'ok',message: `No stalled-forever jobs; no queue over depth ${threshold}; no old embed-backfill jobs without a worker.`,+ details,};}return {name: 'queue_health',status: 'warn',message: problems.join(' '),+ details,};} catch (e) {return {diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.tsindex 3521d74a24..546ddacedc 100644--- a/src/commands/serve-http.ts+++ b/src/commands/serve-http.ts@@ -25,8 +25,9 @@ import { mcpAuthRouter } from '@modelcontextprotocol/sdk/server/auth/router.js';import { requireBearerAuth } from '@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js';import { OAuthTokenRevocationRequestSchema } from '@modelcontextprotocol/sdk/shared/auth.js';import type { BrainEngine } from '../core/engine.ts';-import { operations, OperationError } from '../core/operations.ts';+import { operations, OperationError, opAllowedForBoundClient } from '../core/operations.ts';import type { OperationContext, AuthInfo } from '../core/operations.ts';+import { disabledOpsForPublishGates } from '../mcp/publish-gates.ts';import {GBrainOAuthProvider,validateTokenEndpointAuthMethod,@@ -36,9 +37,18 @@ import {import type { SqlQuery } from '../core/oauth-provider.ts';import { hasScope, ALLOWED_SCOPES_LIST, normalizeScopesInput } from '../core/scope.ts';import { normalizeSourceInput, normalizeFederatedReadInput } from '../core/source-id.ts';-import { summarizeMcpParams, dispatchToolCall } from '../mcp/dispatch.ts';-import { paramDefToSchema } from '../mcp/tool-defs.ts';-import { filterOpsForSurface } from '../mcp/surface.ts';+import { summarizeMcpParams, dispatchToolCall, requestLogStatusForResult } from '../mcp/dispatch.ts';+import { resolveStrictParamsMode } from '../mcp/validate-params.ts';+import { buildToolDefs } from '../mcp/tool-defs.ts';+import {+ filterOpsForSurface,+ clampSurface,+ minSurface,+ resolveClientRowSurface,+ resolveDefaultClientSurface,+ type McpSurface,+} from '../mcp/surface.ts';+import { writeSurfaceChangeAudit } from '../core/surface-audit.ts';import { getBrainHotMemoryMeta } from '../core/facts/meta-hook.ts';import { loadConfig } from '../core/config.ts';import { buildError, serializeError } from '../core/errors.ts';@@ -482,11 +492,14 @@ interface ServeHttpOptions {*/suppressBootstrapToken?: boolean;/**- * MEMORY_VERBS v1: tool-surface mode. 'verbs' = exactly the five protocol- * verbs; 'full' (default) = every non-localOnly operation. Enforced on the- * tool list AND in dispatch (fail-closed).+ * MEMORY_VERBS v1 + WP4: tool-surface mode. 'verbs' = exactly the seven+ * protocol verbs; 'starter' = the STARTER_OPS daily-driver set; 'full'+ * (default) = every non-localOnly operation. Enforced on the tool list AND+ * in dispatch (fail-closed). WP4/D2: this is the server CEILING — each+ * request resolves min(ceiling, client row surface ?? config default),+ * so per-client rows can narrow below it but never widen past it.*/- surface?: 'verbs' | 'full';+ surface?: McpSurface;/*** #2624: force-print the generated admin bootstrap token even on a* non-TTY (containerized) start. By default the raw token is only printed@@ -1415,8 +1428,13 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOptiontry {const now = Math.floor(Date.now() / 1000);const [expiring] = await sql`SELECT count(*)::int as count FROM oauth_tokens WHERE token_type = 'access' AND expires_at BETWEEN ${now} AND ${now + 86400}`;- const [errors] = await sql`SELECT count(*)::int as count FROM mcp_request_log WHERE status != 'success' AND created_at > now() - interval '24 hours'`;- const [total] = await sql`SELECT count(*)::int as count FROM mcp_request_log WHERE created_at > now() - interval '24 hours'`;+ // Excluded from the error numerator: success and success_with_warnings+ // (a warn-mode success); denied_after_list stays counted — a denied+ // call IS a failure signal. surface_change is an OPERATION value (audit+ // rows carry status='success'), so audit rows are excluded from BOTH+ // counts — they are records of operator/self actions, not traffic.+ const [errors] = await sql`SELECT count(*)::int as count FROM mcp_request_log WHERE status NOT IN ('success', 'success_with_warnings') AND operation != 'surface_change' AND created_at > now() - interval '24 hours'`;+ const [total] = await sql`SELECT count(*)::int as count FROM mcp_request_log WHERE operation != 'surface_change' AND created_at > now() - interval '24 hours'`;const errorRate = (total as any).count > 0 ? ((errors as any).count / (total as any).count * 100).toFixed(1) : '0';res.json({expiring_soon: (expiring as any).count,@@ -1793,7 +1811,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption// validator inside rescopeClient.app.post('/admin/api/rescope-client', requireAdmin, express.json(), async (req: Request, res: Response) => {try {- const { clientId, sourceId, federatedRead, boundSlugPrefixes } = req.body ?? {};+ const { clientId, sourceId, federatedRead, boundSlugPrefixes, surface } = req.body ?? {};if (!clientId || typeof clientId !== 'string') {res.status(400).json({ error: 'clientId required' });return;@@ -1815,12 +1833,31 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOptionres.status(400).json({ error: 'boundSlugPrefixes must be null or an array of slug-prefix strings' });return;}- const result = await oauthProvider.rescopeClient(clientId, { sourceId, federatedRead, boundSlugPrefixes });+ // WP4: tri-state surface rescope — omitted = untouched, null = clear+ // (surface + surface_set_by both NULL), value = set + operator lock+ // (mirrors the CLI's --surface verbs|starter|full|clear).+ if (surface !== undefined && surface !== null &&+ surface !== 'verbs' && surface !== 'starter' && surface !== 'full') {+ res.status(400).json({ error: 'surface must be null or one of: verbs, starter, full' });+ return;+ }+ const result = await oauthProvider.rescopeClient(clientId, { sourceId, federatedRead, boundSlugPrefixes, surface });+ // WP4 (amendment 32 / ENG-8): every surface mutation writes an audit+ // row — this endpoint, the rescope CLI, and the request_tools persist.+ if (surface !== undefined) {+ await writeSurfaceChangeAudit(engine, {+ actor: 'admin-api',+ client_id: clientId,+ old: result.surfaceOld ?? null,+ new: result.surface ?? null,+ via: 'admin_api',+ });+ }res.json(result);} catch (e) {const message = e instanceof Error ? e.message : 'Rescope failed';const status = /No OAuth client found/.test(message) ? 404- : /Invalid source_id|requires --source|cannot be empty|does not exist|cannot be an empty list|bound_slug_prefixes entr/.test(message) ? 400+ : /Invalid source_id|requires --source|cannot be empty|does not exist|cannot be an empty list|bound_slug_prefixes entr|--surface must be/.test(message) ? 400: 500;res.status(status).json({ error: message });}@@ -1915,13 +1952,46 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption// ---------------------------------------------------------------------------// MCP tool calls (bearer auth + scope enforcement)// ---------------------------------------------------------------------------- // MEMORY_VERBS v1: surface filter applies AFTER the localOnly filter; the- // same set feeds dispatch as allowedOps so hidden ops are uncallable, not- // just unlisted [c2].- const surface = options.surface ?? 'full';- const mcpOperations = filterOpsForSurface(operations.filter(op => !op.localOnly), surface);- const surfaceAllowedOps: ReadonlySet<string> | undefined =- surface === 'full' ? undefined : new Set(mcpOperations.map(o => o.name));+ // MEMORY_VERBS v1 + WP4 (D2): the server-resolved surface is the CEILING.+ // The per-REQUEST effective surface — min(ceiling, client row surface ??+ // config default), clamped by the GBRAIN_MCP_FORCE_SURFACE kill switch+ // (narrow-only, FOV-6a) — is resolved inside the /mcp handler so a rescope+ // or config flip takes effect on the client's next request without a+ // restart, and the dispatch allow-set is recomputed per request+ // (amendment 20). The surface filter applies AFTER the localOnly filter;+ // the same set feeds dispatch as allowedOps so hidden ops are uncallable,+ // not just unlisted [c2].+ const serverSurfaceCeiling: McpSurface = options.surface ?? 'full';+ const mcpOperationsBase = operations.filter(op => !op.localOnly);++ /**+ * WP4 (D2): resolve this request's effective surface from the caller's+ * verified auth. The config default (`mcp.default_surface_dcr`) is read+ * dual-plane ONLY when the client row carries no usable surface — the+ * common full-surface path pays no extra config read. Unknown row values+ * are ignored with a warn-once per client (amendment 18). Never throws:+ * surface resolution must not take a request down. On a default-surface+ * read failure the LAST successfully read default (per process) still+ * applies, so a transient config outage cannot silently widen a client+ * that normally resolves narrower than the ceiling; with no prior read,+ * the ceiling is the only floor available (pre-WP4 behavior).+ */+ let lastKnownDefaultSurface: McpSurface | null = null;+ async function resolveEffectiveSurface(authInfo: AuthInfo): Promise<{ ceiling: McpSurface; effective: McpSurface }> {+ const ceiling = clampSurface(serverSurfaceCeiling);+ // min() can never go below the narrowest surface: a 'verbs' ceiling makes+ // the row/default resolution a no-op, so skip the awaited config read.+ if (ceiling === 'verbs') return { ceiling, effective: ceiling };+ const rowSurface = resolveClientRowSurface(authInfo.surface, authInfo.clientId);+ if (rowSurface !== null) return { ceiling, effective: minSurface(ceiling, rowSurface) };+ try {+ const dflt = await resolveDefaultClientSurface(engine, config);+ lastKnownDefaultSurface = dflt ?? null;+ return { ceiling, effective: minSurface(ceiling, dflt ?? ceiling) };+ } catch {+ return { ceiling, effective: minSurface(ceiling, lastKnownDefaultSurface ?? ceiling) };+ }+ }// v0.36.x #1076: MCP Streamable HTTP spec — GET /mcp opens an optional SSE// backchannel for server-initiated messages. gbrain's transport is stateless@@ -1944,6 +2014,14 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption// for legacy tokens or when the JOIN row's client_name is NULL.const agentName = authInfo.clientName ?? authInfo.clientId;+ // WP4 (D2): per-request effective surface + fail-closed allow-set,+ // recomputed per request (amendment 20) so rescopes/request_tools+ // persists take effect on the next request with zero restart.+ const { ceiling: surfaceCeiling, effective: surface } = await resolveEffectiveSurface(authInfo);+ const mcpOperations = filterOpsForSurface(mcpOperationsBase, surface);+ const surfaceAllowedOps: ReadonlySet<string> | undefined =+ surface === 'full' ? undefined : new Set(mcpOperations.map(o => o.name));+// Create a fresh MCP server per request (stateless)const server = new Server({ name: 'gbrain', version: VERSION },@@ -1951,10 +2029,48 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption);server.setRequestHandler(ListToolsRequestSchema, async () => {+ // WP1 honest catalog: the advertised list is exactly what THIS token+ // can call. Three per-request filters, cheapest first:+ // 1. token scope — a read-only token never sees admin/write tools;+ // 2. bound-client fence — a slug-bound client never sees ops the+ // dispatch fence would deny (same predicate, cannot drift);+ // 3. publish gates — gated ops (skills/advisor) are hidden while+ // their gate is off; the resolver never throws (read failure =+ // hidden, matching the default-off consent posture) so a config+ // hiccup costs at most the 4 gated tools, never the whole list.+ // Call-time enforcement (hasScope / fence / assertPublishEnabled)+ // stays as the fail-closed backstop for all three layers.+ // Both per-request config reads are independent — issue them+ // concurrently (one RTT of latency on network Postgres, not two).+ const [gateDisabled, strictParamsMode] = await Promise.all([+ disabledOpsForPublishGates(engine, config),+ resolveStrictParamsMode(engine, config),+ ]);+ // FOV-4: `agent` deliberately implies only itself, which would strand+ // agent-only tokens with ZERO discovery — ops flagged `agentCallable`+ // (request_tools) are visible to (and callable by, below) agent scope+ // in addition to their declared scope.+ const visibleOps = mcpOperations.filter(op =>+ (hasScope(authInfo.scopes, op.scope ?? 'read')+ || (op.agentCallable === true && hasScope(authInfo.scopes, 'agent')))+ && opAllowedForBoundClient(authInfo, op)+ && !gateDisabled.has(op.name),+ );+ // WP3 (amendment 14): ONE schema mapper — the inline map this handler+ // carried is unified onto buildToolDefs so the byte-pin test covers the+ // transport consumers actually use. strict_params is read dual-plane+ // PER REQUEST (same restart-free property as the publish gates above):+ // 'reject' closes each schema with additionalProperties:false and+ // declares the _meta/dry_run passthrough keys (D14.1).+ const strictParams = strictParamsMode === 'reject';+ const tools = buildToolDefs(visibleOps, { strictParams });// v0.28.10: log every JSON-RPC method, not just successful tools/call.// Pre-fix, /admin/api/requests showed nothing for clients that only// ever called tools/list, and the v0.26.3 persistence regression test// asserting >= 2 rows after tools/list + tools/call was unreachable.+ // Amendment 23 stopgap (full list-size telemetry deferred): the row's+ // params carry the listed-tool count so per-token-class list sizes are+ // queryable (`params->>'tool_count'`) without new telemetry plumbing.const latency = Date.now() - startTime;try {await executeRawJsonb(@@ -1962,7 +2078,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption`INSERT INTO mcp_request_log (token_name, agent_name, operation, latency_ms, status, params)VALUES ($1, $2, $3, $4, $5, $6::jsonb)`,[authInfo.clientId, agentName, 'tools/list', latency, 'success'],- [null],+ [{ tool_count: tools.length }],);} catch { /* best effort */ }broadcastEvent({@@ -1973,22 +2089,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOptionstatus: 'success',timestamp: new Date().toISOString(),});- return {- tools: mcpOperations.map(op => ({- name: op.name,- description: op.description,- inputSchema: {- type: 'object' as const,- properties: Object.fromEntries(- Object.entries(op.params).map(([k, v]) => [k, paramDefToSchema(v)]),- ),- required: Object.entries(op.params).filter(([, v]) => v.required).map(([k]) => k),- },- // MEMORY_VERBS v1: ToolAnnotations emitted only when the op defines- // them — existing tools stay byte-identical (mirrors buildToolDefs).- ...(op.annotations ? { annotations: op.annotations } : {}),- })),- };+ return { tools };});server.setRequestHandler(CallToolRequestSchema, async (request) => {@@ -2026,17 +2127,26 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption// hierarchy. Plain string includes() at this site would have made// sources_admin tokens look like they couldn't even read.)const requiredScope = op.scope || 'read';- if (!hasScope(authInfo.scopes, requiredScope)) {+ // FOV-4: agentCallable carve-out mirrors the tools/list filter above —+ // an op listed for an agent-only token must not scope-deny at call time.+ const scopeSatisfied = hasScope(authInfo.scopes, requiredScope)+ || (op.agentCallable === true && hasScope(authInfo.scopes, 'agent'));+ if (!scopeSatisfied) {// v0.28.10: persist scope-rejected attempts. Same operator-visibility// motivation as the unknown-op path — and it makes the v0.26.3// persistence regression test reliable across both rejection paths.+ // Amendment 33: a call-time scope deny is a LIST-LEVEL denial (the+ // tools/list filter uses this same hasScope predicate, so the op was+ // never advertised to this token — the client ignored or staled its+ // list, or list/call drifted). status='denied_after_list' makes the+ // honest-catalog metric a one-line count that trends to zero.const latency = Date.now() - startTime;try {await executeRawJsonb(engine,`INSERT INTO mcp_request_log (token_name, agent_name, operation, latency_ms, status, error_message, params)VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb)`,- [authInfo.clientId, agentName, name, latency, 'error', `insufficient_scope: requires '${requiredScope}'`],+ [authInfo.clientId, agentName, name, latency, 'denied_after_list', `insufficient_scope: requires '${requiredScope}'`],[null],);} catch { /* best effort */ }@@ -2045,7 +2155,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOptionoperation: name,scopes: authInfo.scopes.join(','),latency_ms: latency,- status: 'error',+ status: 'denied_after_list',error: { code: 'insufficient_scope', message: `requires '${requiredScope}'` },timestamp: new Date().toISOString(),});@@ -2109,12 +2219,17 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOptiontry {toolResult = await dispatchToolCall(engine, name, params as Record<string, unknown> | undefined, {remote: true,+ // WP1/D7: network transport — the dispatch-layer localOnly+ // backstop keys off this marker.+ transport: 'http',takesHoldersAllowList: tokenAllowList,sourceId: tokenSourceId,metaHook: getBrainHotMemoryMeta,// MEMORY_VERBS v1: fail-closed surface enforcement + usage attribution....(surfaceAllowedOps ? { allowedOps: surfaceAllowedOps } : {}),surface,+ // WP4 (D2): request_tools bounds its catalog + persist by this.+ surfaceCeiling,// v0.31 follow-up fix: thread auth so the whoami op (and any// future scope-aware handlers) can introspect the caller. The// original D12/eE1 refactor moved dispatch into dispatchToolCall@@ -2162,17 +2277,24 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption// dispatchToolCall serializes the error into the content text;// for the audit log we re-extract a message string for the// mcp_request_log error_message column. Best-effort parse.+ // Amendment 33 / D10: op-level denials the list should have+ // prevented (publish-gate backstop `config_key=...`, bound-client+ // fence op-level deny `fence=op`) log status='denied_after_list'+ // instead of plain 'error' — the honest-catalog trend-to-zero+ // metric. Argument-level fence denials carry no marker and stay+ // 'error' (legitimate for a listed op).let errMsg = 'unknown_error';try {const parsed = JSON.parse(toolResult.content[0]?.text ?? '{}');errMsg = parsed.error?.message ?? parsed.message ?? errMsg;} catch { /* ignore */ }+ const errStatus = requestLogStatusForResult(toolResult);try {await executeRawJsonb(engine,`INSERT INTO mcp_request_log (token_name, agent_name, operation, latency_ms, status, error_message, params)VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb)`,- [authInfo.clientId, agentName, name, latency, 'error', errMsg],+ [authInfo.clientId, agentName, name, latency, errStatus, errMsg],[logParamsObj],);} catch { /* best effort */ }@@ -2182,19 +2304,24 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOptionparams: broadcastParams,scopes: authInfo.scopes.join(','),latency_ms: latency,- status: 'error',+ status: errStatus,error: { code: 'op_error', message: errMsg },timestamp: new Date().toISOString(),});return toolResult;}+ // WP3 (amendment 13): warn-mode observability. A success whose _meta+ // carries a non-empty warnings array logs as 'success_with_warnings' so+ // the reject-flip decision is evidence-based (count per client via the+ // status column). Warn CONTENTS (the raw unknown keys) are never logged.+ const successStatus = requestLogStatusForResult(toolResult);try {await executeRawJsonb(engine,`INSERT INTO mcp_request_log (token_name, agent_name, operation, latency_ms, status, params)VALUES ($1, $2, $3, $4, $5, $6::jsonb)`,- [authInfo.clientId, agentName, name, latency, 'success'],+ [authInfo.clientId, agentName, name, latency, successStatus],[logParamsObj],);} catch { /* best effort */ }@@ -2204,7 +2331,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOptionparams: broadcastParams,scopes: authInfo.scopes.join(','),latency_ms: latency,- status: 'success',+ status: successStatus,timestamp: new Date().toISOString(),});return toolResult;diff --git a/src/commands/serve.ts b/src/commands/serve.tsindex 56f979deef..eccee07776 100644--- a/src/commands/serve.ts+++ b/src/commands/serve.ts@@ -58,7 +58,7 @@ export interface ServeOptions {// (which unconditionally attaches a 'data' listener to real// process.stdin and would pollute the test runner's stdin handle).// Defaults to the real implementation when omitted.- startMcpServer?: (engine: BrainEngine, opts?: { surface?: 'verbs' | 'full' }) => Promise<void>;+ startMcpServer?: (engine: BrainEngine, opts?: { surface?: 'verbs' | 'starter' | 'full' }) => Promise<void>;// Test seam for the parent-process watchdog. The default// (`readLiveParentPid`) reads the live kernel PPID via `ps` on POSIX// because `process.ppid` is captured at process creation and does not@@ -173,8 +173,9 @@ export async function runServe(const isHttp = args.includes('--http');// MEMORY_VERBS v1: tool-surface mode. Flag > config `mcp_surface` > 'full'.- // 'verbs' exposes exactly the five protocol verbs (the quickstart surface);- // 'full' (default) keeps every operation — existing installs see no change.+ // 'verbs' exposes exactly the seven protocol verbs (the quickstart surface);+ // 'starter' the ~20-op daily-driver set; 'full' (default) keeps every+ // operation — existing installs see no change.const { parseSurfaceFlag, resolveSurface } = await import('../mcp/surface.ts');const { loadConfig } = await import('../core/config.ts');const surface = resolveSurface(parseSurfaceFlag(args), loadConfig());diff --git a/src/commands/status.ts b/src/commands/status.tsindex cb17ef4f43..377f9c9f13 100644--- a/src/commands/status.ts+++ b/src/commands/status.ts@@ -23,11 +23,12 @@* 2 usage error (bad --section value)** Thin-client mode (isThinClient(cfg)):- * - Sync + Cycle route through `get_status_snapshot` MCP op (admin scope)- * - Locks/Workers/Queue/Autopilot render "local-only — N/A on remote brain"- * because they're host-local concerns; pretending the local install's- * local-host operational state is the remote brain's would lie to the- * operator.+ * - Sync + Cycle + Workers + Queue route through `get_status_snapshot`+ * MCP op (admin scope; workers/queue are snapshot-v2 sections — an old+ * server that omits them renders a graceful "upgrade the remote" line)+ * - Locks/Autopilot render "local-only — N/A on remote brain" because+ * they're host-local concerns; pretending the local install's local-host+ * operational state is the remote brain's would lie to the operator.** --json emits a stable envelope:* { schema_version: 1, sync, cycle, locks?, workers?, queue?, autopilot? }@@ -93,6 +94,47 @@ export interface QueueCounts {dead: number;}+/** Per-queue waiting depth + oldest-waiting age (snapshot v2 `queue.by_queue`). */+export interface QueueDepthRow {+ queue: string;+ depth: number;+ oldest_waiting_age_seconds: number | null;+}++/** Snapshot v2 `queue` section: status counts + per-queue waiting depths. */+export interface RemoteQueueSnapshot {+ counts: QueueCounts;+ by_queue: QueueDepthRow[];+}++/**+ * Snapshot v2 `workers` section — composed like `gbrain jobs supervisor+ * status` (pidfile first, queue-scoped DB singleton lock as the+ * HOME-independent fallback authority, #2227).+ */+export interface RemoteWorkersSnapshot {+ supervisor_alive: boolean;+ detected_via: 'pidfile' | 'db_lock' | null;+ live_lock_active: boolean;+ last_completed_at: string | null;+}++/**+ * Amendment 26: a snapshot v2 section that failed to compute degrades to this+ * marker instead of failing the whole snapshot.+ */+export interface SectionUnavailable {+ error: 'unavailable';+}++/**+ * Thin-client skew marker: the remote server predates snapshot v2 (missing+ * key / schema_version 1), so this section cannot be reported yet.+ */+export interface RemoteUnsupported {+ remote_unsupported: true;+}+export interface WorkerSummary {crashes_24h: number;clean_exits_24h: number;@@ -118,8 +160,8 @@ export interface StatusReport {sync?: SyncStatusReport;cycle?: CycleSnapshot;locks?: LockRow[] | { local_only_remote: true };- workers?: WorkerSummary | { local_only_remote: true };- queue?: QueueCounts | { local_only_remote: true };+ workers?: WorkerSummary | RemoteWorkersSnapshot | SectionUnavailable | RemoteUnsupported | { local_only_remote: true };+ queue?: QueueCounts | RemoteQueueSnapshot | SectionUnavailable | RemoteUnsupported | { local_only_remote: true };autopilot?: AutopilotStatus | { local_only_remote: true };warnings?: string[];/** #1984: true when a --deadline-ms budget elided one or more sections. */@@ -260,7 +302,8 @@ async function buildLocks(engine: BrainEngine): Promise<LockRow[]> {}}-async function buildQueueCounts(engine: BrainEngine): Promise<QueueCounts> {+// Exported for `src/core/operations.ts:get_status_snapshot` (snapshot v2 queue section).+export async function buildQueueCounts(engine: BrainEngine): Promise<QueueCounts> {type Row = { status: string; count: string | number };const counts: QueueCounts = { active: 0, waiting: 0, completed: 0, failed: 0, dead: 0 };try {@@ -279,6 +322,87 @@ async function buildQueueCounts(engine: BrainEngine): Promise<QueueCounts> {return counts;}+/**+ * Per-queue waiting depth + oldest-waiting age. Generalizes the doctor's+ * queue_health oldest-age SQL past its embed-backfill-only filter: EVERY+ * queue with waiting work reports here, name-agnostic. Perf note: WHERE+ * constrains only `status` — the SECOND column of the (queue, status,+ * updated_at) wedge index — so no prefix access exists and this GROUP BY+ * full-scans minion_jobs today. Acceptable at snapshot frequency over pruned+ * waiting sets; a partial (queue, created_at) WHERE status='waiting' index+ * is the fix if it becomes hot.+ */+export async function buildQueueDepths(engine: BrainEngine): Promise<QueueDepthRow[]> {+ const rows = await engine.executeRaw<{+ queue: string;+ depth: number | string;+ oldest_waiting_age_seconds: number | string | null;+ }>(+ `SELECT queue,+ count(*)::int AS depth,+ EXTRACT(EPOCH FROM (now() - min(created_at)))::int AS oldest_waiting_age_seconds+ FROM minion_jobs+ WHERE status = 'waiting'+ GROUP BY queue+ ORDER BY depth DESC`,+ );+ return rows.map((r) => ({+ queue: r.queue,+ depth: Number(r.depth),+ oldest_waiting_age_seconds:+ r.oldest_waiting_age_seconds === null ? null : Number(r.oldest_waiting_age_seconds),+ }));+}++/**+ * Snapshot v2 workers section. Same detection ladder as `gbrain jobs+ * supervisor status` (src/commands/jobs.ts): the pidfile is HOME-derived and+ * lies across split-$HOME deployments, so the queue-scoped DB singleton lock+ * (#1849/#2227) is probed as the fallback authority. `last_completed_at` is+ * the freshest completed-job timestamp — evidence a worker recently finished+ * something, regardless of how it was launched.+ *+ * `opts` exists as a test seam (scratch pidFile) — production callers take+ * the defaults.+ */+export async function buildWorkersSnapshot(+ engine: BrainEngine,+ opts: { pidFile?: string; queue?: string } = {},+): Promise<RemoteWorkersSnapshot> {+ const { readSupervisorPid } = await import('../core/minions/supervisor-pid.ts');+ const { DEFAULT_PID_FILE, supervisorLockId, SUPERVISOR_LOCK_TTL_MIN } = await import(+ '../core/minions/supervisor.ts'+ );+ const pidStatus = readSupervisorPid(opts.pidFile ?? DEFAULT_PID_FILE);++ let lockLive = false;+ try {+ const { inspectLock, isLockHolderLive } = await import('../core/db-lock.ts');+ const snap = await inspectLock(engine, supervisorLockId(opts.queue ?? 'default'));+ lockLive = snap !== null && isLockHolderLive(snap, SUPERVISOR_LOCK_TTL_MIN);+ } catch {+ /* pre-migration brains lack the locks table — pidfile signal stands */+ }++ let lastCompleted: string | null = null;+ try {+ const rows = await engine.executeRaw<{ last_completed: string | Date | null }>(+ `SELECT max(updated_at) AS last_completed FROM minion_jobs WHERE status = 'completed'`,+ );+ const v = rows[0]?.last_completed ?? null;+ lastCompleted = v ? (v instanceof Date ? v.toISOString() : new Date(v).toISOString()) : null;+ } catch {+ /* no minion_jobs table — leave null */+ }++ return {+ supervisor_alive: pidStatus.running || lockLive,+ detected_via: pidStatus.running ? 'pidfile' : lockLive ? 'db_lock' : null,+ live_lock_active: lockLive,+ last_completed_at: lastCompleted,+ };+}+function buildWorkerSummary(): WorkerSummary {let crashes_24h = 0;let clean_exits_24h = 0;@@ -425,7 +549,9 @@ async function buildThinClientReport(mode: 'thin-client',};- if (want('sync') || want('cycle')) {+ // Snapshot v2 also backs workers + queue (locks/autopilot stay host-local).+ const remoteBacked: Section[] = ['sync', 'cycle', 'workers', 'queue'];+ if (remoteBacked.some((s) => want(s))) {try {const payload = await withSectionDeadline((async () => {@@ -438,50 +564,69 @@ async function buildThinClientReport({},opts.deadlineMs && opts.deadlineMs > 0 ? { timeoutMs: opts.deadlineMs } : {},);- return unpackToolResult<{- schema_version: number;- version?: string;- sync: SyncStatusReport;- cycle: CycleSnapshot;- }>(raw);+ return unpackToolResult<RemoteSnapshotPayload>(raw);})(),opts.deadlineMs && opts.deadlineMs > 0 ? opts.deadlineMs : undefined,() => {report.partial = true;// Only name the sections the caller actually requested; the remote- // fetch backs both sync+cycle, but `--section sync` must not report- // `cycle` (a section it excluded) as stale. Matches the local path.- const elided: Section[] = [- ...(want('sync') ? (['sync'] as Section[]) : []),- ...(want('cycle') ? (['cycle'] as Section[]) : []),- ];+ // fetch backs sync+cycle+workers+queue, but `--section sync` must not+ // report a section it excluded as stale. Matches the local path.+ const elided = remoteBacked.filter((s) => want(s));report.stale_sections = [...(report.stale_sections ?? []), ...elided];warnings.push('remote snapshot exceeded the --deadline-ms budget (returned stale)');},);- if (payload) {- // #1984: surface the brain server's version for thin-client parity.- if (payload.version) report.remote_version = payload.version;- if (want('sync')) report.sync = payload.sync;- if (want('cycle')) report.cycle = payload.cycle;- }+ if (payload) applyRemoteSnapshot(report, payload, want);} catch (err) {warnings.push(`remote snapshot failed: ${(err as Error).message}`);}}if (want('locks')) report.locks = { local_only_remote: true };- if (want('workers')) report.workers = { local_only_remote: true };- if (want('queue')) report.queue = { local_only_remote: true };if (want('autopilot')) report.autopilot = { local_only_remote: true };if (warnings.length > 0) report.warnings = warnings;return report;}+/** Wire shape of the `get_status_snapshot` payload across server versions. */+export interface RemoteSnapshotPayload {+ schema_version: number;+ version?: string;+ sync: SyncStatusReport;+ cycle: CycleSnapshot;+ /** v2+ — absent on schema_version-1 servers. */+ workers?: RemoteWorkersSnapshot | SectionUnavailable;+ /** v2+ — absent on schema_version-1 servers. */+ queue?: RemoteQueueSnapshot | SectionUnavailable;+}++/**+ * Map a remote snapshot payload onto the thin-client report. Exported for the+ * skew fixture test: a NEW thin-client against an OLD (schema_version 1)+ * server must degrade the v2-only sections to a graceful marker, never crash+ * or pretend local data is remote data.+ */+export function applyRemoteSnapshot(+ report: StatusReport,+ payload: RemoteSnapshotPayload,+ want: (s: Section) => boolean,+): void {+ // #1984: surface the brain server's version for thin-client parity.+ if (payload.version) report.remote_version = payload.version;+ if (want('sync')) report.sync = payload.sync;+ if (want('cycle')) report.cycle = payload.cycle;+ // v2 sections: an old server omits the keys entirely (schema_version 1) —+ // degrade to the skew marker rather than the misleading "N/A on remote".+ if (want('workers')) report.workers = payload.workers ?? { remote_unsupported: true };+ if (want('queue')) report.queue = payload.queue ?? { remote_unsupported: true };+}+// ---------------------------------------------------------------------------// Human render// ----------------------------------------------------------------------------function renderHuman(report: StatusReport): string {+// Exported for the thin-client skew fixture test (old-server payload render).+export function renderHuman(report: StatusReport): string {const lines: string[] = [];lines.push('');lines.push('GBrain Status');@@ -554,6 +699,15 @@ function renderHuman(report: StatusReport): string {lines.push('Workers (last 24h):');if ('local_only_remote' in report.workers) {lines.push(' local-only — N/A on remote brain');+ } else if ('remote_unsupported' in report.workers) {+ lines.push(' not reported by this brain server (predates snapshot v2) — upgrade the remote gbrain to see workers');+ } else if ('error' in report.workers) {+ lines.push(' unavailable (remote section failed to compute)');+ } else if ('supervisor_alive' in report.workers) {+ const w = report.workers;+ const via = w.detected_via ? ` (via ${w.detected_via})` : '';+ lines.push(` supervisor: ${w.supervisor_alive ? 'alive' : 'not detected'}${via} db_lock=${w.live_lock_active ? 'live' : 'none'}`);+ lines.push(` last completed job: ${w.last_completed_at ?? 'never'}`);} else {const w = report.workers;lines.push(` crashes=${w.crashes_24h} clean_exits=${w.clean_exits_24h}`);@@ -571,6 +725,21 @@ function renderHuman(report: StatusReport): string {lines.push('Queue (live):');if ('local_only_remote' in report.queue) {lines.push(' local-only — N/A on remote brain');+ } else if ('remote_unsupported' in report.queue) {+ lines.push(' not reported by this brain server (predates snapshot v2) — upgrade the remote gbrain to see queue depth');+ } else if ('error' in report.queue) {+ lines.push(' unavailable (remote section failed to compute)');+ } else if ('counts' in report.queue) {+ const q = report.queue.counts;+ lines.push(+ ` active=${q.active} waiting=${q.waiting} failed=${q.failed} dead=${q.dead} completed=${q.completed}`,+ );+ for (const row of report.queue.by_queue) {+ const age = row.oldest_waiting_age_seconds != null+ ? ` oldest_waiting=${Math.round(row.oldest_waiting_age_seconds / 60)}m`+ : '';+ lines.push(` [${row.queue}] depth=${row.depth}${age}`);+ }} else {const q = report.queue;lines.push(diff --git a/src/commands/tools-json.ts b/src/commands/tools-json.tsindex ab74831ba4..d95e2fe405 100644--- a/src/commands/tools-json.ts+++ b/src/commands/tools-json.ts@@ -1,6 +1,17 @@import { operations } from '../core/operations.ts';+import { buildToolDefs } from '../mcp/tool-defs.ts';+/**+ * `gbrain --tools-json` — the public CLI tool-catalog contract.+ *+ * The legacy keys (`name`, `description`, `parameters` with the compact+ * `"type"` / `"type?"` strings) are preserved VERBATIM — downstream scripts+ * parse them. WP3 adds the full JSON Schema (param descriptions, enums,+ * defaults, required array) additively under a new `schema` key per tool,+ * generated by the same buildToolDefs mapper the MCP transports serve.+ */export function printToolsJson() {+ const defsByName = new Map(buildToolDefs(operations).map(def => [def.name, def]));const tools = operations.map(op => ({name: op.name,description: op.description,@@ -10,6 +21,7 @@ export function printToolsJson() {`${v.type}${v.required ? '' : '?'}`,]),),+ schema: defsByName.get(op.name)!.inputSchema,}));console.log(JSON.stringify(tools, null, 2));diff --git a/src/core/advisor/collect-mcp-client-fit.ts b/src/core/advisor/collect-mcp-client-fit.tsnew file mode 100644index 0000000000..a2ce6fca2c--- /dev/null+++ b/src/core/advisor/collect-mcp-client-fit.ts@@ -0,0 +1,272 @@+/**+ * advisor/collect-mcp-client-fit.ts — E3: MCP surface right-sizing over+ * `mcp_request_log` (amendment 29 + D12).+ *+ * Two checks, both read-only, both riding the shared usage reader+ * (src/core/mcp-usage.ts — the same hygiene rules as the E4 CLI and the+ * derive-starter-ops script):+ *+ * (a) Per-client fit: a client resolving to the FULL surface whose 30d+ * distinct-op set fits inside STARTER_OPS is paying the ~100-tool+ * catalog for a starter-sized workload. Finding carries the exact fix:+ * `gbrain auth rescope-client <id> --surface starter`.+ * (b) Set-level drift (the standing STARTER_OPS curator): top-10 most-used+ * ops (ranked by CLIENT COUNT, not raw calls — D12) missing from+ * STARTER_OPS, and starter members (excluding+ * ALWAYS_INCLUDED_STARTER_OPS — verbs + whoami + request_tools + the+ * agent lane) unused for 90d.+ *+ * Privacy (amendment 29): when the advisor runs REMOTE (ctx.remote), client+ * identifiers are REDACTED to aggregate counts ("2 clients fit the starter+ * surface — run gbrain advisor on the host for details"). Full per-client+ * detail is local-CLI-only. Op NAMES are not client identifiers and stay+ * visible in the drift finding on both surfaces.+ *+ * D12 exclusions: automation-shaped clients (>90% of calls are the+ * context_pack/delta boundary verbs — the hook-lane/turn-context signature;+ * there is no registered-name convention to key on, the hook lane is stdio+ * and never logs) are excluded from BOTH checks via+ * `ClientOpUsage.likely_automation`.+ *+ * Dismiss/snooze: the skillpack nag-state engine (escalate-then-suppress,+ * ceiling 3) with its OWN state file (`~/.gbrain/advisor-usage-nag-state.json`)+ * so declines never pollute the skillpack ledger. The nag "version" is a+ * fingerprint of the finding's inputs — a changed usage profile re-surfaces a+ * suppressed finding, an unchanged one goes quiet after the ceiling. Local+ * runs only: the remote advisor op is strictly read-only (no nag writes).+ *+ * Alert threshold (amendment 29): a client needs >= MIN_CALLS_FOR_FIT calls+ * in the window before a fit finding fires — one whoami probe is not a+ * workload.+ */++import { gbrainPath } from '../config.ts';+import { operations } from '../operations.ts';+import { readClientOpUsage, type ClientOpUsage } from '../mcp-usage.ts';+import {+ STARTER_OPS,+ ALWAYS_INCLUDED_STARTER_OPS,+ isMcpSurface,+ resolveDefaultClientSurface,+} from '../../mcp/surface.ts';+import {+ loadNagState,+ saveNagState,+ findNag,+ upsertNag,+ decideNagAction,+ recordNagDisplay,+ type NagState,+} from '../skillpack/nag-state.ts';+import type { AdvisorCollector, AdvisorContext, AdvisorFinding } from './types.ts';++/** Minimum 30d call volume before a per-client fit finding fires. */+export const MIN_CALLS_FOR_FIT = 10;++/** How many top-used ops the drift check inspects for starter membership. */+export const DRIFT_TOP_N = 10;++/** Window for the "starter member unused" drift arm. */+export const DRIFT_UNUSED_WINDOW_DAYS = 90;++/** Nag-state file for this collector (separate from the skillpack ledger). */+export function usageNagStatePath(): string {+ return _nagPathOverride ?? gbrainPath('advisor-usage-nag-state.json');+}++let _nagPathOverride: string | null = null;++/** Test seam: point the nag state at a tmp file (null restores the default). */+export function __setUsageNagStatePathForTests(path: string | null): void {+ _nagPathOverride = path;+}++/**+ * Gate a finding through the nag engine (local runs only). Returns true when+ * the finding should surface; records the display so the ceiling counts.+ */+function nagAllows(state: NagState, packName: string, fingerprint: string): { show: boolean; next: NagState } {+ const key = { brain_id: 'host', source_id: 'mcp-usage', pack_name: packName };+ const prior = findNag(state, key);+ const decision = decideNagAction(prior, { pack_version: fingerprint });+ if (!decision.show) return { show: false, next: state };+ const entry = recordNagDisplay(prior, key, { pack_version: fingerprint, nowIso: new Date().toISOString() });+ return { show: true, next: upsertNag(state, entry) };+}++/** Resolve the surface a client row would get WITHOUT the server ceiling. */+function clientResolvedSurface(+ rowSurface: unknown,+ defaultSurface: string | null,+): string {+ if (isMcpSurface(rowSurface)) return rowSurface;+ return defaultSurface ?? 'full';+}++async function readClientSurfaces(ctx: AdvisorContext): Promise<Map<string, unknown> | null> {+ try {+ const rows = await ctx.engine.executeRaw<{ client_id: string; surface: unknown }>(+ `SELECT client_id, surface FROM oauth_clients`,+ );+ return new Map(rows.map((r) => [r.client_id, r.surface]));+ } catch {+ // Pre-v127 brain (no surface column) or no oauth_clients table: the fit+ // finding's fix command could not work anyway — skip check (a).+ return null;+ }+}++export const collectMcpClientFit: AdvisorCollector = {+ id: 'mcp-client-fit',+ collect: async (ctx) => {+ const findings: AdvisorFinding[] = [];++ let usage30: ClientOpUsage[];+ try {+ usage30 = await readClientOpUsage(ctx.engine, { days: 30 });+ } catch {+ return []; // mcp_request_log absent / engine quirk → no findings+ }+ const real30 = usage30.filter((u) => !u.likely_automation);++ // Nag state: loaded once, saved once, LOCAL runs only (remote is read-only).+ const local = !ctx.remote;+ let nag = local ? loadNagState({ statePath: usageNagStatePath() }) : null;++ // ---- (a) per-client starter fit -------------------------------------+ const surfaces = await readClientSurfaces(ctx);+ if (surfaces !== null) {+ let defaultSurface: string | null = null;+ try {+ defaultSurface = await resolveDefaultClientSurface(ctx.engine, ctx.config);+ } catch {+ defaultSurface = null;+ }+ const fits: ClientOpUsage[] = [];+ for (const u of real30) {+ if (u.total_calls < MIN_CALLS_FOR_FIT) continue;+ if (!surfaces.has(u.token_name)) continue; // legacy bearer token — no per-client surface row to rescope+ const resolved = clientResolvedSurface(surfaces.get(u.token_name), defaultSurface);+ if (resolved !== 'full') continue; // already narrowed (row or DCR default)+ if (!u.distinct_ops.every((op) => STARTER_OPS.has(op))) continue;+ fits.push(u);+ }+ if (fits.length > 0) {+ if (!local) {+ // Amendment 29: remote output carries aggregate counts ONLY.+ findings.push({+ id: 'mcp_starter_fit_aggregate',+ severity: 'info',+ title: `${fits.length} MCP client${fits.length === 1 ? '' : 's'} fit the starter surface — run \`gbrain advisor\` on the host for details.`,+ detail:+ 'Each has 30 days of usage entirely inside STARTER_OPS while resolving to the full ' ++ 'catalog. Client identifiers are shown on the host CLI only.',+ fix: { command_argv: null },+ collector: 'mcp-client-fit',+ ask_user: true,+ });+ } else {+ for (const u of fits) {+ const fingerprint = `fit:${u.distinct_ops.join(',')}`;+ const gate = nagAllows(nag!, `fit:${u.token_name}`, fingerprint);+ nag = gate.next;+ if (!gate.show) continue;+ findings.push({+ id: `mcp_starter_fit:${u.token_name}`,+ severity: 'info',+ title: `MCP client "${u.token_name}" used only starter-surface ops for 30d (${u.distinct_ops.length} ops, ${u.total_calls} calls) but sees the full catalog.`,+ detail:+ 'A right-sized catalog means fewer wrong-tool calls and a smaller tools/list ' ++ 'prompt for that agent. The rescope takes effect on its next request; the client ' ++ 'should re-issue tools/list. (HTTP clients only — stdio usage is not logged. ' ++ 'Automation-shaped clients, >90% context_pack/delta, are excluded.)',+ fix: { command_argv: ['gbrain', 'auth', 'rescope-client', u.token_name, '--surface', 'starter'] },+ collector: 'mcp-client-fit',+ ask_user: true,+ });+ }+ }+ }+ }++ // ---- (b) set-level drift (the standing curator) ----------------------+ try {+ // Rank by CLIENT COUNT (D12: distinct-op sets, not raw call volume).+ const clientCountByOp = new Map<string, number>();+ for (const u of real30) {+ for (const op of u.distinct_ops) {+ clientCountByOp.set(op, (clientCountByOp.get(op) ?? 0) + 1);+ }+ }+ const topOps = [...clientCountByOp.entries()]+ .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))+ .slice(0, DRIFT_TOP_N)+ .map(([op]) => op);+ // localOnly ops are never proposable for a network surface (mirrors+ // derive-starter-ops); a logged localOnly name (old rows, CLI-actor+ // audit exception) must not produce an unactionable recommendation.+ const localOnlyOps = new Set(operations.filter((o) => o.localOnly).map((o) => o.name));+ const missingFromStarter = topOps.filter((op) => !STARTER_OPS.has(op) && !localOnlyOps.has(op));++ const usage90 = await readClientOpUsage(ctx.engine, { days: DRIFT_UNUSED_WINDOW_DAYS });+ const seen90 = new Set<string>();+ for (const u of usage90) {+ if (u.likely_automation) continue;+ for (const op of u.distinct_ops) seen90.add(op);+ }+ // Always-included-by-construction members (shared with surface.ts ++ // derive-starter-ops) never count as drift — including the agent lane,+ // whose usage would otherwise flag it "unused" forever.+ const unusedStarter = [...STARTER_OPS]+ .filter((op) => !ALWAYS_INCLUDED_STARTER_OPS.has(op) && !seen90.has(op))+ .sort();++ // Only meaningful once there is real traffic to curate against.+ if (real30.length > 0 && (missingFromStarter.length > 0 || unusedStarter.length > 0)) {+ const parts: string[] = [];+ if (missingFromStarter.length > 0) {+ parts.push(`top-used ops missing from STARTER_OPS: ${missingFromStarter.join(', ')}`);+ }+ if (unusedStarter.length > 0) {+ parts.push(`starter members unused for ${DRIFT_UNUSED_WINDOW_DAYS}d: ${unusedStarter.join(', ')}`);+ }+ const fingerprint = `drift:${missingFromStarter.join(',')}|${unusedStarter.join(',')}`;+ let show = true;+ if (local) {+ const gate = nagAllows(nag!, 'starter-drift', fingerprint);+ nag = gate.next;+ show = gate.show;+ }+ if (show) {+ findings.push({+ id: 'mcp_starter_ops_drift',+ severity: 'info',+ title: `STARTER_OPS has drifted from production usage (${parts.length === 2 ? 'both directions' : parts[0]!.split(':')[0]}).`,+ detail:+ parts.join('; ') ++ '. Re-derive with `bun run scripts/derive-starter-ops.ts` and paste the proposed ' ++ 'block into src/mcp/surface.ts (the monotonicity test pins verbs ⊆ starter ⊆ full). ' ++ 'Automation-shaped clients are excluded from these stats.',+ fix: { command_argv: null },+ collector: 'mcp-client-fit',+ ask_user: true,+ });+ }+ }+ } catch {+ /* drift check is best-effort — never blocks the fit findings */+ }++ // Persist nag displays (local only, best-effort — a failed write costs one+ // extra display, never a report failure).+ if (local && nag) {+ try {+ saveNagState(nag, { statePath: usageNagStatePath() });+ } catch {+ /* best effort */+ }+ }++ return findings;+ },+};diff --git a/src/core/advisor/run.ts b/src/core/advisor/run.tsindex f663fdd70e..5d76696a2b 100644--- a/src/core/advisor/run.ts+++ b/src/core/advisor/run.ts@@ -17,6 +17,7 @@ import { collectSetupSmells } from './collect-setup-smells.ts';import { collectUninstalledBrainPack } from './collect-uninstalled-brain-pack.ts';import { collectUninstalledBundled } from './collect-uninstalled-bundled.ts';import { collectChronicle } from './collect-chronicle.ts';+import { collectMcpClientFit } from './collect-mcp-client-fit.ts';/** Deterministic v1 collector order (also the secondary sort key for ranking). */export const COLLECTORS: AdvisorCollector[] = [@@ -29,6 +30,7 @@ export const COLLECTORS: AdvisorCollector[] = [collectUninstalledBrainPack,collectUninstalledBundled,collectChronicle,+ collectMcpClientFit,];const SEV_RANK: Record<AdvisorSeverity, number> = { critical: 0, warn: 1, info: 2 };diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 3fa513df33..33832b4426 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -12,7 +12,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'agent': ['--aliases', '--all', '--brain', '--detach', '--fanout-manifest', '--federated', '--flag', '--flags', '--follow', '--help', '--include-null-signature', '--json', '--max-turns', '--model', '--no-extract', '--no-federated', '--no-follow', '--note', '--path', '--pattern', '--pending', '--repo', '--reset', '--resolve', '--restore-only', '--since', '--source', '--stale', '--subagent-def', '--supersessions', '--thin', '--timeout-ms', '--tools', '--word'],'anomalies': ['--aliases', '--all', '--brain', '--fast', '--force', '--from-pages', '--help', '--http', '--include-null-signature', '--json', '--lookback-days', '--mcp-only', '--no-embedding', '--no-extract', '--pattern', '--pending', '--reset', '--resolve', '--sigma', '--since', '--source', '--stale', '--supersessions', '--surface', '--thin', '--timeout', '--token-ttl'],'apply-migrations': ['--ab', '--all', '--auto-update', '--brain', '--break-lock', '--build-index', '--by-mention', '--compile', '--days', '--dry-run', '--exclusive', '--fast', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--from-meetings', '--from-pages', '--help', '--history', '--host-dir', '--http', '--json', '--lang', '--list', '--locks', '--markdown', '--max-age', '--migrate-only', '--migration', '--mode', '--multimodal', '--no-autopilot-install', '--no-embedding', '--no-extract', '--non-interactive', '--phase', '--priority', '--refresh-unqualified', '--remediate', '--rollback', '--skip-verify', '--source', '--stale', '--surface', '--token-ttl', '--undo-wave', '--use-captured-snapshot', '--with-calibration', '--yes'],- 'auth': ['--aliases', '--all', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--enable-dcr', '--enable-dcr-insecure', '--fast', '--federated-read', '--force', '--from-pages', '--grant-types', '--help', '--http', '--include-null-signature', '--json', '--no-embedding', '--no-extract', '--pattern', '--pending', '--redirect-uri', '--reset', '--resolve', '--scopes', '--source', '--stale', '--supersessions', '--surface', '--takes-holders', '--thin', '--token', '--token-endpoint-auth-method', '--token-ttl', '--yes'],+ 'auth': ['--aliases', '--all', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--days', '--enable-dcr', '--enable-dcr-insecure', '--fast', '--federated-read', '--force', '--from-pages', '--grant-types', '--help', '--http', '--include-null-signature', '--json', '--no-embedding', '--no-extract', '--pattern', '--pending', '--redirect-uri', '--reset', '--resolve', '--scopes', '--source', '--stale', '--supersessions', '--surface', '--takes-holders', '--thin', '--token', '--token-endpoint-auth-method', '--token-ttl', '--usage', '--yes'],'autopilot': ['--aliases', '--all', '--auto-fix', '--batch', '--brain', '--break-lock', '--by-type', '--check', '--dim', '--dimensions', '--dir', '--drain', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--ff-only', '--fix', '--force', '--force-break-lock', '--force-retry', '--from-pages', '--help', '--http', '--include-null-signature', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--json', '--markdown', '--max-age', '--max-rss', '--max-usd', '--migrate-only', '--model', '--multimodal', '--no', '--no-embed', '--no-embedding', '--no-extract', '--no-federated', '--no-inject', '--no-mutate', '--no-worker', '--non-interactive', '--now', '--once', '--output', '--path', '--pattern', '--pending', '--phase', '--refresh-cache', '--remediate', '--remediation-plan', '--repo', '--reset', '--resolve', '--source', '--stale', '--status', '--supersessions', '--surface', '--swap-only', '--target', '--target-score', '--thin', '--timeout', '--to', '--token-ttl', '--uninstall', '--unsafe-bypass-dream-guard', '--user', '--version', '--yes'],'backfill': ['--aliases', '--all', '--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--include-null-signature', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--no-extract', '--pattern', '--pending', '--reset', '--resolve', '--resume', '--source', '--stale', '--supersessions', '--thin'],'bench': ['--baseline', '--brain', '--explain', '--force', '--from', '--help', '--json', '--label', '--lang', '--limit', '--markdown', '--multimodal', '--near-symbol', '--restore-only', '--source', '--stale', '--symbol-kind', '--thin', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],@@ -26,7 +26,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'check-backlinks': ['--background', '--brain', '--brain-wide-max-cost-usd', '--dir', '--dry-run', '--explain', '--follow', '--help', '--include-frontmatter', '--json', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--source', '--stale', '--timeout', '--type'],'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'],'check-update': ['--all', '--brain', '--check', '--dim', '--ff-only', '--help', '--json', '--markdown', '--migrate-only', '--non-interactive', '--refresh-cache', '--source', '--swap-only', '--to', '--version', '--yes'],- 'claw-test': ['--ab', '--agent', '--all', '--auto-update', '--brain', '--break-lock', '--build-index', '--by-mention', '--compile', '--days', '--dir', '--exclusive', '--force-retry', '--force-schema', '--from-meetings', '--help', '--history', '--http', '--json', '--keep-tempdir', '--lang', '--list-agents', '--live', '--local', '--locks', '--markdown', '--max-age', '--message', '--multimodal', '--no-embed', '--no-embedding', '--no-extract', '--path', '--pglite', '--phase', '--priority', '--progress-json', '--prompt-file', '--refresh-unqualified', '--remediate', '--rollback', '--run-id', '--scenario', '--skip-verify', '--source', '--stale', '--transcripts', '--undo-wave', '--use-captured-snapshot', '--with-calibration', '--yes'],+ 'claw-test': ['--ab', '--agent', '--all', '--auto-update', '--brain', '--break-lock', '--build-index', '--by-mention', '--compile', '--days', '--dir', '--exclusive', '--force-retry', '--force-schema', '--from-meetings', '--help', '--history', '--http', '--json', '--keep-tempdir', '--lang', '--list-agents', '--live', '--local', '--locks', '--markdown', '--max-age', '--message', '--multimodal', '--no-embed', '--no-embedding', '--no-extract', '--path', '--pglite', '--phase', '--priority', '--progress-json', '--prompt-file', '--refresh-unqualified', '--remediate', '--rollback', '--run-id', '--scenario', '--skip-verify', '--source', '--stale', '--surface', '--transcripts', '--undo-wave', '--use-captured-snapshot', '--with-calibration', '--yes'],'code-callees': ['--aliases', '--all', '--all-sources', '--brain', '--chunker-debug', '--clone-dir', '--confirm-destructive', '--federated', '--force', '--help', '--include-null-signature', '--json', '--limit', '--no-extract', '--no-federated', '--no-json', '--path', '--pattern', '--pending', '--repo', '--reset', '--resolve', '--restore-only', '--source', '--stale', '--supersessions', '--thin', '--url', '--url-managed', '--yes'],'code-callers': ['--aliases', '--all', '--all-sources', '--brain', '--chunker-debug', '--clone-dir', '--confirm-destructive', '--federated', '--force', '--help', '--include-null-signature', '--json', '--limit', '--no-extract', '--no-federated', '--no-json', '--path', '--pattern', '--pending', '--repo', '--reset', '--resolve', '--restore-only', '--source', '--stale', '--supersessions', '--thin', '--url', '--url-managed', '--yes'],'code-def': ['--aliases', '--all', '--brain', '--chunker-debug', '--help', '--include-null-signature', '--json', '--lang', '--limit', '--no-extract', '--no-json', '--pattern', '--pending', '--pretty', '--reset', '--resolve', '--source', '--stale', '--supersessions', '--thin', '--yes'],diff --git a/src/core/config.ts b/src/core/config.tsindex d2e8f083c0..97158f1f6d 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -120,10 +120,14 @@ export interface GBrainConfig {provider_chat_options?: Record<string, Record<string, unknown>>;/*** MEMORY_VERBS v1 (Cathedral 1): default MCP tool surface for `gbrain serve`.- * 'verbs' = exactly the 5 protocol verbs (the quickstart surface);- * 'full' (default) = every operation. The `--surface` flag overrides per-run.+ * 'verbs' = exactly the 7 protocol verbs (the quickstart surface);+ * 'starter' (WP4) = the ~20-op daily-driver set (STARTER_OPS in+ * src/mcp/surface.ts); 'full' (default) = every operation. The `--surface`+ * flag overrides per-run. On the OAuth HTTP transport this resolves the+ * server CEILING (D2): per-client row surfaces can narrow below it but+ * never widen past it.*/- mcp_surface?: 'verbs' | 'full';+ mcp_surface?: 'verbs' | 'starter' | 'full';/*** MEMORY_VERBS v1 [D6C]: ISO timestamp stamped by `gbrain init` so* `gbrain protocol stats` can derive real TTHW (install → first verb call).@@ -427,6 +431,30 @@ export interface GBrainConfig {* tier so a hosted gbrain never serves its own bundled dev skills).*/skills_dir?: string;+ /**+ * WP3 — unknown tool-call argument posture for MCP dispatch.+ * 'warn' (default / absent): unknown params are accepted; each call+ * collects `_meta.warnings` + a model-visible notice block, and the+ * request logs as 'success_with_warnings'.+ * 'reject': unknown params return `invalid_params` (with a+ * did-you-mean suggestion), and tool schemas are emitted with+ * `additionalProperties: false`.+ * Dual-plane: DB plane (`gbrain config set mcp.strict_params ...`) wins+ * over this file slot. See src/mcp/validate-params.ts.+ */+ strict_params?: 'warn' | 'reject';+ /**+ * WP4 (D2 / plan OQ1) — default surface for OAuth clients whose+ * `oauth_clients.surface` row value is NULL. oauth_clients carries no+ * DCR-origin marker, so this applies to ALL null-surface clients (not+ * just dynamically-registered ones); operators pre-seed important+ * clients with `gbrain auth rescope-client <id> --surface full`.+ * Unset (default) = null-surface clients get the server ceiling —+ * pre-WP4 behavior, existing clients untouched. Dual-plane: the DB+ * plane (`gbrain config set mcp.default_surface_dcr starter`) wins+ * over this file slot. Always bounded by the server ceiling (D2).+ */+ default_surface_dcr?: 'verbs' | 'starter' | 'full';};}@@ -1079,6 +1107,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [// the advisor exposes operational diagnostics (version/jobs/key presence),// not prose skills. Default OFF; read-only over MCP.'mcp.publish_advisor',+ // WP3 — unknown tool-call argument posture ('warn' default | 'reject').+ // Read dual-plane by src/mcp/validate-params.ts (DB > file > 'warn').+ 'mcp.strict_params',// Skill-nag suppression (#2180): brain-resident pack install nag off-switch.'skillpack.nag_disabled',// Self-upgrade (v0.42; file plane, read on the hot path)diff --git a/src/core/mcp-client.ts b/src/core/mcp-client.tsindex 3853cc5105..6fc91ed444 100644--- a/src/core/mcp-client.ts+++ b/src/core/mcp-client.ts@@ -384,6 +384,10 @@ export function unpackToolResult<T = unknown>(res: unknown): T {if (!Array.isArray(content) || content.length === 0) {throw new RemoteMcpError('parse', 'Remote tool returned no content');}+ // Deliberately content[0]-only (D8 skew guard): new servers append a+ // model-facing diagnosis block as content[1] on empty retrievals; the+ // structured body contract stays in block 0 and this parser must never+ // trip on the extra block. Pinned by test.const first = content[0] as { type?: string; text?: string };if (first.type !== 'text' || typeof first.text !== 'string') {throw new RemoteMcpError('parse', 'Remote tool returned unexpected content shape');@@ -394,3 +398,16 @@ export function unpackToolResult<T = unknown>(res: unknown): T {throw new RemoteMcpError('parse', `Remote tool result was not valid JSON: ${(e as Error).message}`);}}++/**+ * T15/FOV-1: read the response-level `_meta` from a tool-call envelope+ * (see docs/protocol/MCP_META_CHANNELS.md). Old servers simply lack the+ * field — callers must treat undefined as "no meta", never as an error.+ */+export function extractResponseMeta(res: unknown): Record<string, unknown> | undefined {+ const meta = (res as { _meta?: unknown } | undefined)?._meta;+ if (meta && typeof meta === 'object' && !Array.isArray(meta)) {+ return meta as Record<string, unknown>;+ }+ return undefined;+}diff --git a/src/core/mcp-usage.ts b/src/core/mcp-usage.tsnew file mode 100644index 0000000000..e1193eaa02--- /dev/null+++ b/src/core/mcp-usage.ts@@ -0,0 +1,173 @@+/**+ * mcp-usage.ts — the ONE shared reader over `mcp_request_log` (amendment 30).+ *+ * Consumed by three surfaces that must never disagree on what counts as an+ * "operation call":+ * - `gbrain auth clients --usage` (E4, src/commands/auth.ts)+ * - the advisor starter-fit collector (E3, src/core/advisor/collect-mcp-client-fit.ts)+ * - `scripts/derive-starter-ops.ts` (amendment 23 / D12)+ *+ * Row hygiene (amendments 23 + 30) — encoded HERE, nowhere else:+ * - JSON-RPC method rows are NOT op calls: 'tools/list', 'initialize',+ * 'notifications/initialized', 'ping' are dropped.+ * - The legacy bearer transport (src/mcp/http-transport.ts) logs calls as+ * 'tools/call:<name>' — the prefix is stripped and the row counts as <name>.+ * - 'surface_change' audit rows (ENG-8, src/core/surface-audit.ts) are+ * bookkeeping, not usage — dropped.+ * - Only successful calls count ('success' / 'success_with_warnings').+ * Denied and errored rows are not usage: a client repeatedly bouncing off+ * a gated op must not "use" its way into starter-set derivation or an+ * advisor fit finding (that would let denial traffic curate the catalog).+ *+ * Windowed on `created_at` so the query rides `idx_mcp_log_time_agent`+ * (created_at, token_name). Plain SQL through `engine.executeRaw` — works on+ * BOTH engines; never writes, so no jsonb pathway is involved.+ *+ * Scope caveat (amendment 30): usage-derived features see HTTP clients ONLY.+ * The stdio transport (local pipe, including every bootstrap/hook-lane serve)+ * does not write `mcp_request_log`, so stdio usage is structurally invisible+ * here — treat absence of a client as "not an HTTP client", never "unused".+ *+ * D12 automation classification: bootstrap/hook-lane identities register no+ * distinguishing client name (the hook lane is stdio and never logs; thin+ * clients carry operator-chosen names), so automation is detected+ * BEHAVIORALLY — a client whose calls are >90% ambient-recall boundary ops+ * (`context_pack` / `delta`) is flagged `likely_automation` and excluded from+ * starter-set derivation + advisor fit findings. The threshold and op set are+ * exported so consumers cite one definition.+ */++import type { BrainEngine } from './engine.ts';++/** Default trailing window for every usage-derived surface. */+export const MCP_USAGE_DEFAULT_WINDOW_DAYS = 30;++/** JSON-RPC method / server-plane rows that are not operation calls. */+export const NON_OP_LOG_ROWS: ReadonlySet<string> = new Set([+ 'tools/list',+ 'initialize',+ 'notifications/initialized',+ 'ping',+ // ENG-8 surface-change audit rows (src/core/surface-audit.ts).+ 'surface_change',+]);++/** Legacy bearer transport row prefix — 'tools/call:query' means op 'query'. */+export const LEGACY_CALL_PREFIX = 'tools/call:';++/**+ * D12: ambient-recall boundary verbs — the ops a hook-lane / turn-context+ * automation client calls almost exclusively.+ */+export const AUTOMATION_BOUNDARY_OPS: ReadonlySet<string> = new Set(['context_pack', 'delta']);++/** Fraction of a client's calls that must be boundary ops to classify as automation. */+export const AUTOMATION_FRACTION_THRESHOLD = 0.9;++/**+ * Normalize one logged `operation` value to an op name, or null when the row+ * is not an operation call. The single source for the hygiene rules above.+ */+export function normalizeLoggedOperation(operation: string): string | null {+ if (operation.startsWith(LEGACY_CALL_PREFIX)) {+ const name = operation.slice(LEGACY_CALL_PREFIX.length);+ if (name.length === 0) return null;+ // The stripped name re-runs the hygiene check: 'tools/call:tools/list'+ // or a prefixed 'surface_change' audit row is still not an op call.+ return NON_OP_LOG_ROWS.has(name) ? null : name;+ }+ if (NON_OP_LOG_ROWS.has(operation)) return null;+ return operation;+}++export interface ClientOpUsage {+ /** `mcp_request_log.token_name`: OAuth client_id, or a legacy bearer token name. */+ token_name: string;+ /** Op name → call count inside the window (post-hygiene). */+ ops: Record<string, number>;+ total_calls: number;+ /** Sorted distinct op names inside the window. */+ distinct_ops: string[];+ /** ISO timestamp of the client's most recent op call in the window. */+ last_seen: string;+ /** Fraction of calls that are AUTOMATION_BOUNDARY_OPS (0 when no calls). */+ automation_fraction: number;+ /** D12 behavioral classification: automation_fraction > threshold. */+ likely_automation: boolean;+}++function toIso(v: unknown): string {+ if (v instanceof Date) return v.toISOString();+ const d = new Date(String(v));+ return Number.isNaN(d.getTime()) ? String(v) : d.toISOString();+}++/**+ * Per-client op usage over the trailing window (default 30d). Returns one+ * entry per token_name, sorted by total_calls descending. Never throws for+ * an empty log; a missing table (very old brain) DOES throw — callers that+ * must be resilient wrap in try/catch (the advisor collector does).+ */+export async function readClientOpUsage(+ engine: BrainEngine,+ opts: { days?: number } = {},+): Promise<ClientOpUsage[]> {+ const days = opts.days ?? MCP_USAGE_DEFAULT_WINDOW_DAYS;+ if (!Number.isInteger(days) || days < 1 || days > 3650) {+ throw new Error(`readClientOpUsage: days must be an integer in [1, 3650]; got ${String(opts.days)}`);+ }+ // Windowed on created_at (rides idx_mcp_log_time_agent). The day count is+ // bound as a parameter and multiplied into a unit interval — portable+ // across Postgres and PGLite, no string-splicing into the SQL.+ const rows = await engine.executeRaw<{+ token_name: string | null;+ operation: string;+ n: number | string;+ last_seen: unknown;+ }>(+ `SELECT token_name, operation, count(*)::int AS n, max(created_at) AS last_seen+ FROM mcp_request_log+ WHERE created_at > now() - ($1::int * interval '1 day')+ AND token_name IS NOT NULL+ AND status IN ('success', 'success_with_warnings')+ GROUP BY token_name, operation`,+ [days],+ );++ const byClient = new Map<string, { ops: Map<string, number>; total: number; lastSeen: string }>();+ for (const row of rows) {+ if (!row.token_name) continue;+ const op = normalizeLoggedOperation(row.operation);+ if (op === null) continue;+ const n = typeof row.n === 'number' ? row.n : parseInt(String(row.n), 10) || 0;+ const lastSeen = toIso(row.last_seen);+ let entry = byClient.get(row.token_name);+ if (!entry) {+ entry = { ops: new Map(), total: 0, lastSeen };+ byClient.set(row.token_name, entry);+ }+ entry.ops.set(op, (entry.ops.get(op) ?? 0) + n);+ entry.total += n;+ if (lastSeen > entry.lastSeen) entry.lastSeen = lastSeen;+ }++ const out: ClientOpUsage[] = [];+ for (const [token, entry] of byClient) {+ let automationCalls = 0;+ for (const [op, n] of entry.ops) {+ if (AUTOMATION_BOUNDARY_OPS.has(op)) automationCalls += n;+ }+ const fraction = entry.total > 0 ? automationCalls / entry.total : 0;+ out.push({+ token_name: token,+ ops: Object.fromEntries([...entry.ops.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))),+ total_calls: entry.total,+ distinct_ops: [...entry.ops.keys()].sort(),+ last_seen: entry.lastSeen,+ automation_fraction: fraction,+ likely_automation: fraction > AUTOMATION_FRACTION_THRESHOLD,+ });+ }+ out.sort((a, b) => b.total_calls - a.total_calls || (a.token_name < b.token_name ? -1 : 1));+ return out;+}diff --git a/src/core/migrate.ts b/src/core/migrate.tsindex c504c25c76..cf11e8ce6c 100644--- a/src/core/migrate.ts+++ b/src/core/migrate.ts@@ -5672,6 +5672,44 @@ export const MIGRATIONS: Migration[] = [ON session_context_state (updated_at);`,},+ {+ version: 127,+ name: 'oauth_client_surface_and_minion_queue_index',+ // WP4 (MCP consumer-feedback wave) — two additive pieces:+ //+ // 1. oauth_clients.surface + surface_set_by (amendments 17-19): the+ // per-client MCP tool surface consumed by the D2 ceiling resolution in+ // serve-http (`min(server --surface ceiling, row surface ?? config+ // default)`) and written by `gbrain auth rescope-client --surface`+ // (surface_set_by='operator', the lock the request_tools persist+ // branch cannot override) and the `request_tools` meta-op+ // (surface_set_by='self'). TEXT with an OPEN value space (amendment+ // 18): unrecognized values are ignored at resolution (warn-once per+ // client), and future client tiers will write tier names into this+ // same column — never a second column. NULL = no per-client surface+ // (server/config resolution applies). verifyAccessToken's degrade+ // ladder gained a rung above v85's so pre-v127 brains keep+ // authenticating (ENG-9: both columns probed by missingOAuthColumn).+ //+ // 2. idx_minion_jobs_queue_status_updated (ENG-10, WP5 wedge index):+ // btree (queue, status, updated_at) covering all four count FILTERs+ // and both max(updated_at) FILTERs in queryWedgeSignals+ // (supervisor.ts) — no non-partial queue index existed before this.+ // Plain CREATE INDEX (small table; no CONCURRENTLY needed, which also+ // keeps this runnable inside the migration transaction on both+ // engines).+ //+ // Keep in sync with src/schema.sql, src/core/pglite-schema.ts,+ // src/core/schema-embedded.ts + the bootstrap probe sets in both engines+ // (test/schema-bootstrap-coverage.test.ts pins coverage).+ idempotent: true,+ sql: `+ ALTER TABLE oauth_clients ADD COLUMN IF NOT EXISTS surface TEXT;+ ALTER TABLE oauth_clients ADD COLUMN IF NOT EXISTS surface_set_by TEXT;+ CREATE INDEX IF NOT EXISTS idx_minion_jobs_queue_status_updated+ ON minion_jobs (queue, status, updated_at);+ `,+ },];export const LATEST_VERSION = MIGRATIONS.length > 0diff --git a/src/core/minions/supervisor.ts b/src/core/minions/supervisor.tsindex c7288b00ee..c84043526b 100644--- a/src/core/minions/supervisor.ts+++ b/src/core/minions/supervisor.ts@@ -44,8 +44,10 @@ import {} from 'fs';import { dirname, resolve } from 'path';import type { BrainEngine } from '../engine.ts';-import { tryAcquireDbLock, type DbLockHandle } from '../db-lock.ts';-import { currentBrainId } from './worker-registry.ts';+import { tryAcquireDbLock, inspectLock, isLockHolderLive, type DbLockHandle } from '../db-lock.ts';+import { currentBrainId, readWorkers } from './worker-registry.ts';+import { autopilotPausedMarkerPath } from '../autopilot-paths.ts';+import { resolveEnvNumber } from '../env-number.ts';export type SupervisorEvent =| 'started'@@ -287,6 +289,131 @@ export async function queryWedgeSignals(};}+/**+ * Submit-time queue truthfulness snapshot, attached to submit_job/submit_agent+ * responses so a job id handed back over a dead lane stops meaning nothing.+ * Every field is best-effort: a probe failure or timeout collapses to+ * `{probe_failed: true}` and NEVER errors the (already enqueued, possibly+ * paid) submission — the enqueue result stands on its own.+ */+export interface QueueSubmitState {+ /** Waiting-job count on the target queue (includes the job just enqueued). */+ depth?: number;+ /** Age of the oldest waiting job on the queue, or null when depth is 0. */+ oldest_waiting_age_seconds?: number | null;+ /** A supervisor DB lock is live, a registered worker serves the queue, or a live-lock active job proves one exists. */+ worker_alive?: boolean;+ /** The autopilot pause marker is present — nothing will start until it clears. */+ paused?: boolean;+ /** Human-readable submit-time caution; absent when the lane looks healthy. */+ warning?: string;+ /** The probe itself failed or timed out; the other fields are absent. */+ probe_failed?: boolean;+}++/** Total wall-clock budget for the whole submit-time probe. */+export const QUEUE_PROBE_TIMEOUT_MS = 1500;++/**+ * Probe the health of a queue right after a job was enqueued on it.+ *+ * Composes three signals the codebase already computes elsewhere:+ * - `queryWedgeSignals` (depth + live-lock active evidence) plus the+ * doctor-style oldest-waiting age, generalized past embed-backfill;+ * - supervisor DB-lock liveness (`inspectLock`/`isLockHolderLive` on+ * `supervisorLockId(queue)` — the HOME-independent authority, #2227)+ * plus the host-local worker registry (standalone `gbrain jobs work`+ * holds no supervisor lock; the MCP server runs on the brain host);+ * - the autopilot pause marker (a paused system makes `worker_alive`+ * truthful-but-misleading on its own).+ *+ * Fail-open by contract: any throw or a `timeoutMs` overrun returns+ * `{probe_failed: true}`. Warn-only — callers must never gate the enqueue+ * on this result.+ */+export async function probeQueueState(+ engine: BrainEngine,+ queue: string,+ handlerNames: string[],+ opts: { timeoutMs?: number } = {},+): Promise<QueueSubmitState> {+ const timeoutMs = opts.timeoutMs ?? QUEUE_PROBE_TIMEOUT_MS;+ let timer: ReturnType<typeof setTimeout> | undefined;+ const timeout = new Promise<QueueSubmitState>((resolveTimeout) => {+ timer = setTimeout(() => resolveTimeout({ probe_failed: true }), timeoutMs);+ });+ try {+ return await Promise.race([probeQueueStateInner(engine, queue, handlerNames), timeout]);+ } catch {+ return { probe_failed: true };+ } finally {+ if (timer) clearTimeout(timer);+ }+}++async function probeQueueStateInner(+ engine: BrainEngine,+ queue: string,+ handlerNames: string[],+): Promise<QueueSubmitState> {+ const sig = await queryWedgeSignals(engine, queue, handlerNames);++ // Oldest-waiting age, same filter shape as the wedge signals. Perf: the+ // wave's migration (landing in another lane) adds the btree+ // (queue, status, updated_at) wedge index whose (queue, status) prefix+ // covers this WHERE; until it lands, minion_jobs is small enough that a+ // scan fits comfortably inside the probe's wall-clock budget.+ const ageRows = await engine.executeRaw<{ age: number | string | null }>(+ `SELECT EXTRACT(EPOCH FROM (now() - min(created_at)))::int AS age+ FROM minion_jobs+ WHERE queue = $1 AND status = 'waiting'`,+ [queue],+ );+ const rawAge = ageRows[0]?.age ?? null;+ const oldestAge = rawAge === null ? null : Number(rawAge);++ let supervisorLive = false;+ try {+ const snap = await inspectLock(engine, supervisorLockId(queue));+ supervisorLive = snap !== null && isLockHolderLive(snap, SUPERVISOR_LOCK_TTL_MIN);+ } catch {+ // Pre-migration brains lack the locks table — registry/active signals stand.+ }+ let registeredWorker = false;+ try {+ registeredWorker = readWorkers().some((w) => w.queue === queue);+ } catch {+ // Registry dir unreadable — remaining signals stand.+ }++ const workerAlive = supervisorLive || registeredWorker || sig.activeHealthy > 0;+ const paused = existsSync(autopilotPausedMarkerPath());++ // Same operator knob the doctor's queue_health depth check reads.+ const threshold = resolveEnvNumber('GBRAIN_QUEUE_WAITING_THRESHOLD', 10);+ const warnings: string[] = [];+ if (paused) {+ warnings.push('system paused for migration — job will not start until the pause clears');+ }+ if (!workerAlive) {+ warnings.push(+ `no live worker detected for queue '${queue}' — job will wait until one starts (gbrain jobs work --queue ${queue})`,+ );+ }+ if (sig.waiting > threshold) {+ warnings.push(`waiting depth ${sig.waiting} exceeds GBRAIN_QUEUE_WAITING_THRESHOLD (${threshold})`);+ }++ const state: QueueSubmitState = {+ depth: sig.waiting,+ oldest_waiting_age_seconds: oldestAge,+ worker_alive: workerAlive,+ };+ if (paused) state.paused = true;+ if (warnings.length > 0) state.warning = warnings.join('; ');+ return state;+}+/** Exit codes for documented agent branching. */export const ExitCodes = {CLEAN: 0,diff --git a/src/core/oauth-provider.ts b/src/core/oauth-provider.tsindex b2c7716976..a57f18346a 100644--- a/src/core/oauth-provider.ts+++ b/src/core/oauth-provider.ts@@ -735,15 +735,17 @@ export class GBrainOAuthProvider implements OAuthServerProvider {try {oauthRows = await this.sql`SELECT t.client_id, t.scopes, t.expires_at, t.resource, c.client_name,- c.source_id, c.federated_read, c.bound_slug_prefixes+ c.source_id, c.federated_read, c.bound_slug_prefixes,+ c.surface, c.surface_set_byFROM oauth_tokens tLEFT JOIN oauth_clients c ON c.client_id = t.client_idWHERE t.token_hash = ${tokenHash} AND t.token_type = 'access'`;} catch (err) {// Degrade ladder for brains that haven't run apply-migrations yet:- // bound_slug_prefixes (v85) → federated_read (v61) → source_id (v60) →- // pre-v0.34 base projection. Auth must keep working the whole way down.+ // surface/surface_set_by (v127) → bound_slug_prefixes (v85) →+ // federated_read (v61) → source_id (v60) → pre-v0.34 base projection.+ // Auth must keep working the whole way down.//// `isUndefinedColumnError(err, name)` canNOT actually tell us WHICH// column was missing — with SQLSTATE 42703 present it returns true for@@ -753,42 +755,62 @@ export class GBrainOAuthProvider implements OAuthServerProvider {// rethrows once the narrowest one still fails. (Branching on the name// is what made the first cut of this hard-fail every token// verification on a pre-v61 brain.)- // Any of the three optional columns may be the missing one, and on the+ // Any of the optional columns may be the missing one, and on the// message-fallback path (drivers that don't surface SQLSTATE) the name- // is what identifies it — so probe all three at every rung.+ // is what identifies it — so probe all five at every rung (ENG-9:+ // surface + surface_set_by ship in one migration and go missing+ // together, so BOTH names are probed).const missingOAuthColumn = (e: unknown): boolean =>+ isUndefinedColumnError(e, 'surface') ||+ isUndefinedColumnError(e, 'surface_set_by') ||isUndefinedColumnError(e, 'bound_slug_prefixes') ||isUndefinedColumnError(e, 'federated_read') ||isUndefinedColumnError(e, 'source_id');if (!missingOAuthColumn(err)) throw err;try {- // v85 missing: keep source_id + federated_read, drop the fence column.+ // v127 missing: drop the surface columns first, keep the fence+ // column (WP4 amendment 17 — the NEW top rung). Surface degrade is+ // fail-OPEN by design: the serve-http ceiling still bounds every+ // request, so a missing per-client surface only means "server+ // surface applies", never a widened catalog.oauthRows = await this.sql`SELECT t.client_id, t.scopes, t.expires_at, t.resource, c.client_name,- c.source_id, c.federated_read+ c.source_id, c.federated_read, c.bound_slug_prefixesFROM oauth_tokens tLEFT JOIN oauth_clients c ON c.client_id = t.client_idWHERE t.token_hash = ${tokenHash} AND t.token_type = 'access'`;- } catch (err2) {- if (!missingOAuthColumn(err2)) throw err2;+ } catch (errS) {+ if (!missingOAuthColumn(errS)) throw errS;try {- // v61 missing: source_id only.+ // v85 missing: keep source_id + federated_read, drop the fence column.oauthRows = await this.sql`- SELECT t.client_id, t.scopes, t.expires_at, t.resource, c.client_name, c.source_id- FROM oauth_tokens t- LEFT JOIN oauth_clients c ON c.client_id = t.client_id- WHERE t.token_hash = ${tokenHash} AND t.token_type = 'access'- `;- } catch (err3) {- if (!missingOAuthColumn(err3)) throw err3;- // Truly pre-v60: pre-v0.34 projection.- oauthRows = await this.sql`- SELECT t.client_id, t.scopes, t.expires_at, t.resource, c.client_name+ SELECT t.client_id, t.scopes, t.expires_at, t.resource, c.client_name,+ c.source_id, c.federated_readFROM oauth_tokens tLEFT JOIN oauth_clients c ON c.client_id = t.client_idWHERE t.token_hash = ${tokenHash} AND t.token_type = 'access'`;+ } catch (err2) {+ if (!missingOAuthColumn(err2)) throw err2;+ try {+ // v61 missing: source_id only.+ oauthRows = await this.sql`+ SELECT t.client_id, t.scopes, t.expires_at, t.resource, c.client_name, c.source_id+ FROM oauth_tokens t+ LEFT JOIN oauth_clients c ON c.client_id = t.client_id+ WHERE t.token_hash = ${tokenHash} AND t.token_type = 'access'+ `;+ } catch (err3) {+ if (!missingOAuthColumn(err3)) throw err3;+ // Truly pre-v60: pre-v0.34 projection.+ oauthRows = await this.sql`+ SELECT t.client_id, t.scopes, t.expires_at, t.resource, c.client_name+ FROM oauth_tokens t+ LEFT JOIN oauth_clients c ON c.client_id = t.client_id+ WHERE t.token_hash = ${tokenHash} AND t.token_type = 'access'+ `;+ }}}}@@ -841,6 +863,14 @@ export class GBrainOAuthProvider implements OAuthServerProvider {// restored dump missing one column) where bindings DO exist and every// bound client would otherwise be silently unfenced.const fenceProjectionDegraded = !('bound_slug_prefixes' in row);+ // WP4 (D2): per-client tool surface. Raw TEXT threaded as-is — the+ // value space is OPEN (amendment 18; future tiers write tier names into+ // this column), so parsing/warning happens at the serve-http resolution+ // site, not here. Undefined when the column is NULL, the projection+ // degraded (v127 rung), or the brain predates v127. Surface degrade is+ // fail-open by design: the server ceiling still bounds every request.+ const rowSurface = typeof row.surface === 'string' ? row.surface : undefined;+ const rowSurfaceSetBy = typeof row.surface_set_by === 'string' ? row.surface_set_by : undefined;return {token,clientId: row.client_id as string,@@ -860,6 +890,9 @@ export class GBrainOAuthProvider implements OAuthServerProvider {// operations.ts on every direct slug-mutating write op.boundSlugPrefixes,...(fenceProjectionDegraded ? { fenceProjectionDegraded: true } : {}),+ // WP4: per-client surface + operator-lock marker (amendment 19).+ ...(rowSurface !== undefined ? { surface: rowSurface } : {}),+ ...(rowSurfaceSetBy !== undefined ? { surfaceSetBy: rowSurfaceSetBy } : {}),} as CoreAuthInfo as SdkAuthInfo;}@@ -1206,11 +1239,22 @@ export class GBrainOAuthProvider implements OAuthServerProvider {*/async rescopeClient(clientId: string,- opts: { sourceId?: string; federatedRead?: string[]; boundSlugPrefixes?: string[] | null },- ): Promise<{ clientId: string; clientName: string; sourceId: string; federatedRead: string[]; boundSlugPrefixes?: string[] | null }> {- const { sourceId, federatedRead, boundSlugPrefixes } = opts;- if (sourceId === undefined && federatedRead === undefined && boundSlugPrefixes === undefined) {- throw new Error('rescope-client requires --source, --federated-read, and/or --bound-slug-prefixes');+ opts: {+ sourceId?: string;+ federatedRead?: string[];+ boundSlugPrefixes?: string[] | null;+ /**+ * WP4 (D2/amendment 19): per-client tool surface. Tri-state —+ * undefined = untouched, null = clear (both surface AND+ * surface_set_by go NULL), value = set + surface_set_by='operator'+ * (the operator lock: request_tools persist cannot override it).+ */+ surface?: 'verbs' | 'starter' | 'full' | null;+ },+ ): Promise<{ clientId: string; clientName: string; sourceId: string; federatedRead: string[]; boundSlugPrefixes?: string[] | null; surface?: string | null; surfaceOld?: string | null }> {+ const { sourceId, federatedRead, boundSlugPrefixes, surface } = opts;+ if (sourceId === undefined && federatedRead === undefined && boundSlugPrefixes === undefined && surface === undefined) {+ throw new Error('rescope-client requires --source, --federated-read, --bound-slug-prefixes, and/or --surface');}if (sourceId !== undefined) assertValidSourceId(sourceId);if (federatedRead !== undefined) {@@ -1219,6 +1263,13 @@ export class GBrainOAuthProvider implements OAuthServerProvider {}for (const s of federatedRead) assertValidSourceId(s);}+ // WP4: only the three known surfaces are OPERATOR-writable here; the+ // column value space stays open (amendment 18) for future tier writers,+ // but this surface validates so a typo'd rescope fails loud, not silent.+ if (surface !== undefined && surface !== null+ && surface !== 'verbs' && surface !== 'starter' && surface !== 'full') {+ throw new Error(`--surface must be verbs | starter | full | clear (got "${String(surface)}")`);+ }// v0.42.72.0: bound_slug_prefixes rescope, so channel-membership churn// (the qm-harness roster case) updates the write fence in place instead// of forcing a register+rotate cycle. Tri-state: undefined = untouched,@@ -1233,21 +1284,42 @@ export class GBrainOAuthProvider implements OAuthServerProvider {assertValidSlugPrefixes(boundSlugPrefixes);}let rows: Record<string, unknown>[];+ // WP4: when the surface axis is being touched, capture the OLD value+ // first so callers can write the amendment-32 audit row ({old, new}).+ let surfaceOld: string | null | undefined;try {- // Only touch bound_slug_prefixes when the caller actually passed it.- // Naming the column unconditionally would make a plain+ if (surface !== undefined) {+ const prior = await this.sql`+ SELECT surface FROM oauth_clients WHERE client_id = ${clientId}+ `;+ surfaceOld = prior.length > 0 ? ((prior[0].surface as string | null) ?? null) : null;+ }+ // Only touch bound_slug_prefixes / surface when the caller actually+ // passed them. Naming a column unconditionally would make a plain// `rescope-client --source wiki` fail on a brain that has the v60/v61- // OAuth columns but not v85's bound_* set — a regression on an axis- // the caller never asked about.- rows = boundSlugPrefixes === undefined- ? await this.sql`+ // OAuth columns but not v85's bound_* set (or v127's surface set) — a+ // regression on an axis the caller never asked about.+ const surfaceSetBy = surface === null ? null : 'operator';+ if (boundSlugPrefixes === undefined && surface === undefined) {+ rows = await this.sql`UPDATE oauth_clientsSET source_id = COALESCE(${sourceId ?? null}::text, source_id),federated_read = COALESCE(${federatedRead ? pgArray(federatedRead) : null}::text[], federated_read)WHERE client_id = ${clientId}RETURNING client_id, client_name, source_id, federated_read- `- : await this.sql`+ `;+ } else if (boundSlugPrefixes === undefined) {+ rows = await this.sql`+ UPDATE oauth_clients+ SET source_id = COALESCE(${sourceId ?? null}::text, source_id),+ federated_read = COALESCE(${federatedRead ? pgArray(federatedRead) : null}::text[], federated_read),+ surface = ${surface ?? null}::text,+ surface_set_by = ${surfaceSetBy}::text+ WHERE client_id = ${clientId}+ RETURNING client_id, client_name, source_id, federated_read, surface, surface_set_by+ `;+ } else if (surface === undefined) {+ rows = await this.sql`UPDATE oauth_clientsSET source_id = COALESCE(${sourceId ?? null}::text, source_id),federated_read = COALESCE(${federatedRead ? pgArray(federatedRead) : null}::text[], federated_read),@@ -1255,11 +1327,25 @@ export class GBrainOAuthProvider implements OAuthServerProvider {WHERE client_id = ${clientId}RETURNING client_id, client_name, source_id, federated_read, bound_slug_prefixes`;+ } else {+ rows = await this.sql`+ UPDATE oauth_clients+ SET source_id = COALESCE(${sourceId ?? null}::text, source_id),+ federated_read = COALESCE(${federatedRead ? pgArray(federatedRead) : null}::text[], federated_read),+ bound_slug_prefixes = ${boundSlugPrefixes ? pgArray(boundSlugPrefixes) : null}::text[],+ surface = ${surface ?? null}::text,+ surface_set_by = ${surfaceSetBy}::text+ WHERE client_id = ${clientId}+ RETURNING client_id, client_name, source_id, federated_read, bound_slug_prefixes, surface, surface_set_by+ `;+ }} catch (err) {if (isUndefinedColumnError(err, 'source_id') ||isUndefinedColumnError(err, 'federated_read') ||- isUndefinedColumnError(err, 'bound_slug_prefixes')+ isUndefinedColumnError(err, 'bound_slug_prefixes') ||+ isUndefinedColumnError(err, 'surface') ||+ isUndefinedColumnError(err, 'surface_set_by')) {throw new Error('rescope-client requires an up-to-date OAuth schema; run `gbrain apply-migrations --yes` and retry.');}@@ -1284,6 +1370,10 @@ export class GBrainOAuthProvider implements OAuthServerProvider {boundSlugPrefixes: 'bound_slug_prefixes' in row? (Array.isArray(row.bound_slug_prefixes) ? (row.bound_slug_prefixes as string[]) : null): undefined,+ // WP4: undefined = surface untouched this call; null = cleared.+ ...(surface !== undefined+ ? { surface: (row.surface as string | null) ?? null, surfaceOld: surfaceOld ?? null }+ : {}),};}diff --git a/src/core/operations.ts b/src/core/operations.tsindex 33ce99cc15..8711dc4e8c 100644--- a/src/core/operations.ts+++ b/src/core/operations.ts@@ -12,6 +12,7 @@ import type { PageType } from './types.ts';import { importFromContent } from './import-file.ts';import { writePageThrough, type WriteThroughResult } from './write-through.ts';import { hybridSearch, hybridSearchCached, stampContentFlags, stampUnverifiedExtractions } from './search/hybrid.ts';+import { looksConceptShaped } from './search/query-intent.ts';import { expandQuery } from './search/expansion.ts';import { dedupResults } from './search/dedup.ts';import { captureEvalCandidate, isEvalCaptureEnabled, isEvalScrubEnabled } from './eval-capture.ts';@@ -19,6 +20,7 @@ import type { HybridSearchMeta } from './types.ts';import { extractPageLinks, isAutoLinkEnabled, isAutoTimelineEnabled, isGlobalBasenameEnabled, parseTimelineEntries, makeResolver, type UnresolvedFrontmatterRef } from './link-extraction.ts';import { isFactsBackstopEligible } from './facts/eligibility.ts';import { stripTakesFence } from './takes-fence.ts';+import type { WriterLintPayload } from './output/post-write.ts';import { stripFactsFence } from './facts-fence.ts';import { getContentFlag } from './quarantine.ts';import { unverifiedExtractionFragment, isUnverifiedExtraction, EXTRACTION_STATUS_KEY, STATUS_VERIFIED } from './extraction-review.ts';@@ -52,6 +54,15 @@ import {LIST_SKILLS_DESCRIPTION,GET_SKILL_DESCRIPTION,} from './operations-descriptions.ts';+// WP4 (request_tools): all three are runtime leaves relative to this module+// (no import cycles back into operations.ts). The cyclic dependencies —+// src/mcp/surface.ts (→ brain-allowlist → operations) and+// src/mcp/publish-gates.ts (→ operations) — are loaded via dynamic import+// inside the handler instead (the verbs.ts house pattern).+import { isUndefinedColumnError } from './utils.ts';+import { hasScope } from './scope.ts';+import { RateLimiter } from '../mcp/rate-limit.ts';+import { writeSurfaceChangeAudit } from './surface-audit.ts';// --- Types ---@@ -79,7 +90,9 @@ export type ErrorCode =// MEMORY_VERBS v1 protocol codes (frozen — docs/protocol/MEMORY_VERBS_v1.md).// Coarse on purpose: codes are for branching (configure/retry vs caller bug// vs server bug); the freeform `detail` field carries specifics.- | 'not_found' // verb-level: unknown fact id (forget)+ | 'not_found' // unknown resource. Verb-level (forget: unknown fact id) AND+ // get_agent_job's uniform foreign-or-missing envelope (anti-enumeration:+ // a caller cannot distinguish another client's job from a nonexistent id)| 'scope_denied' // verb-level: OAuth scope / trust-boundary refusal| 'provenance_required' // remember: provenance missing or empty| 'unavailable' // a required dependency cannot serve (no API key, gateway down, model refusal)@@ -404,41 +417,87 @@ export const CLIENT_FENCED_WRITE_OPS: ReadonlySet<string> = new Set(['submit_agent',]);+/**+ * WP4 (D9) — discovery meta-ops exempt from the bound-client fence's+ * LISTING/dispatch denial. `request_tools` is `mutating: true` (its persist+ * branch writes oauth_clients.surface), which would otherwise hide discovery+ * from every slug-bound client. The exemption is safe because the persist+ * branch SELF-ENFORCES its own guards — server ceiling (D2), operator lock+ * (amendment 19), OAuth scopes, and a per-client rate limit (D14.5) — and it+ * never touches a slug. Lives here (not inline in the predicate) so the+ * tools/list filter and the dispatch fence consume the identical carve-out+ * (ENG-3 drift-proofing).+ */+const BOUND_CLIENT_META_OPS: ReadonlySet<string> = new Set(['request_tools']);++/**+ * Single source of truth for "may a slug-bound client use this op" (ENG-3).+ * Consumed by BOTH the dispatch-time fence below AND the tools/list filter+ * in serve-http, so the advertised catalog and the deny behavior cannot+ * drift — a bound client is never shown an op that will fence-deny at call+ * time. Gate on "mutates, or carries any non-read scope" rather than on the+ * two literal scope strings 'write'/'admin': `sources_add`/`sources_remove`+ * carry the bespoke `sources_admin` scope and are `mutating: true`, so a+ * scope-string check let a bound client DROP AN ENTIRE SOURCE — every page+ * in it, far outside any prefix. Anything that isn't a plain read must be+ * explicitly allow-listed. A degraded projection (binding unreadable) denies+ * every non-read op — the unfenceable ops must not stay reachable precisely+ * when the fence is unreadable. Exception: BOUND_CLIENT_META_OPS (D9) stay+ * allowed even degraded — they are slug-free discovery ops whose only write+ * self-enforces ceiling+lock+scopes+rate-limit (and a degraded projection+ * also dropped the surface columns, so that write fails 'migration pending'+ * rather than running unguarded).+ */+export function opAllowedForBoundClient(+ auth: Pick<AuthInfo, 'boundSlugPrefixes' | 'fenceProjectionDegraded'> | undefined,+ op: Pick<Operation, 'name' | 'scope' | 'mutating'>,+): boolean {+ const degraded = auth?.fenceProjectionDegraded === true;+ if (!degraded && !auth?.boundSlugPrefixes) return true;+ const isRead = op.scope === 'read' && op.mutating !== true;+ if (isRead) return true;+ if (BOUND_CLIENT_META_OPS.has(op.name)) return true;+ if (degraded) return false;+ return CLIENT_FENCED_WRITE_OPS.has(op.name);+}+/*** Fail-closed gate for slug-bound clients, applied at dispatch (the single* choke point both MCP transports share) so it cannot be forgotten per op.* Read ops are untouched — read scope is enforced by source federation.+ * Allow/deny derives from `opAllowedForBoundClient`; this wrapper only owns+ * the error envelopes.*/export function enforceBoundClientOpAllowList(auth: AuthInfo | undefined,op: Pick<Operation, 'name' | 'scope' | 'mutating'>,): void {- // A degraded projection means we could not read the binding, not that- // there isn't one. Deny every non-read op outright — otherwise the- // unfenceable ops stay reachable precisely when the fence is unreadable.+ if (opAllowedForBoundClient(auth, op)) return;const degraded = auth?.fenceProjectionDegraded === true;- if (!degraded && !auth?.boundSlugPrefixes) return;- // Gate on "mutates, or carries any non-read scope" rather than on the two- // literal scope strings 'write'/'admin': `sources_add` / `sources_remove`- // carry the bespoke `sources_admin` scope and are `mutating: true`, so a- // scope-string check let a bound client DROP AN ENTIRE SOURCE — every page- // in it, far outside any prefix. Anything that isn't a plain read must be- // explicitly allow-listed.- const isRead = op.scope === 'read' && op.mutating !== true;- if (isRead) return;if (degraded) {- throw new OperationError(+ const err = new OperationError('permission_denied',`${op.name}: this brain's oauth_clients projection is missing bound_slug_prefixes, so client write bindings cannot be evaluated. Refusing every non-read operation rather than running unfenced.`,'Run `gbrain apply-migrations --yes` on the brain host.',);+ // Amendment 33 / D10: OP-level fence denial — the tools/list filter+ // (opAllowedForBoundClient, the same predicate) should have hidden this+ // op, so serve-http counts it toward the honest-catalog metric+ // (status='denied_after_list'). key=value detail grammar (WP1).+ err.detail = 'fence=op';+ throw err;}- if (CLIENT_FENCED_WRITE_OPS.has(op.name)) return;- throw new OperationError(+ const err = new OperationError('permission_denied',`${op.name} is not available to slug-bound clients: it can write outside client ${auth?.clientId ?? '(unknown)'}'s bound_slug_prefixes (${(auth?.boundSlugPrefixes ?? []).join(', ')}).`,'Use put_page / add_timeline_entry / add_link under your own prefixes, or ask an operator to clear the binding with `gbrain auth rescope-client <id> --bound-slug-prefixes none`.',);+ // Amendment 33 / D10: op-level, not argument-level — see above. The+ // slug-prefix ARGUMENT denials (enforceClientSlugFence) deliberately do+ // NOT carry this marker: a listed write op denying an out-of-fence slug+ // is legitimate and excluded from the metric.+ err.detail = 'fence=op';+ throw err;}/**@@ -561,6 +620,24 @@ export interface AuthInfo {* unaffected — this axis alone fails closed.*/fenceProjectionDegraded?: boolean;+ /**+ * WP4 (D2): per-client tool surface from `oauth_clients.surface`, threaded+ * at token-verification time (same JOIN as sourceId/allowedSources). The+ * serve-http transport resolves the request's effective surface as+ * `min(server ceiling, this ?? config default)` — the row can narrow, never+ * widen. Value space is OPEN (amendment 18: future client tiers write tier+ * names into the same column); unrecognized values are ignored at+ * resolution with a warn-log once per client. Undefined = column NULL,+ * projection degraded, or the brain predates migration v127.+ */+ surface?: string;+ /**+ * WP4 (amendment 19) — who set `surface`: 'operator' (rescope CLI/admin+ * endpoint; request_tools persist may NOT override it), 'self'+ * (request_tools persist), or 'dcr_default'. Undefined when surface is+ * unset or the projection degraded.+ */+ surfaceSetBy?: string;}export interface OperationContext {@@ -594,9 +671,30 @@ export interface OperationContext {* untrusted) but has no per-token auth (local pipe), so identity ops like* whoami need a way to distinguish "known auth-less transport" from "a* transport bug forgot to thread ctx.auth". Trust decisions MUST NOT key- * off this field — only `ctx.remote === false` grants trust.+ * off this field — only `ctx.remote === false` grants trust. It IS the+ * transport-LOCALITY axis: localOnly ops dispatch on 'stdio' (a local+ * pipe with the operator's own filesystem) and are denied on 'http'+ * (network transports), independent of the remote trust flag.*/- transport?: 'stdio';+ transport?: 'stdio' | 'http';+ /**+ * WP2/D3: response-meta side channel. Handlers that compute out-of-band+ * result metadata (retrieval degradation, strict-mode warnings) publish it+ * here under a namespaced top-level key; the MCP dispatch layer merges the+ * collected keys into `ToolResult._meta` (one producer per key — see+ * docs/protocol/MCP_META_CHANNELS.md). Unset on CLI/local dispatch paths,+ * which render the same meta directly; emissions are always optional-chained.+ */+ emitResponseMeta?: (key: string, value: unknown) => void;+ /**+ * WP4 (D2): the SERVER surface ceiling for this transport (force-clamped),+ * threaded by the MCP dispatch layer. Consumed by `request_tools`: the+ * catalog never names ops above the ceiling, and the persist branch+ * rejects widening past it with a machine-readable denial+ * (`detail: "ceiling=<surface>"`). Unset (local CLI / direct dispatch) is+ * treated as 'full'.+ */+ surfaceCeiling?: 'verbs' | 'starter' | 'full';/*** Subagent runtime context (v0.16+). Set by the subagent tool dispatcher when* dispatching an op as a tool call from an LLM loop. Used to enforce per-op@@ -985,19 +1083,52 @@ export interface Operation {* transport. v0.28 added `sources_admin` (manage federated sources) and* `users_admin` (reserved). The hierarchy lives in src/core/scope.ts —* `admin` implies all, `write` implies `read`, the two `*_admin` scopes- * are siblings (different axes; neither implies the other).+ * are siblings (different axes; neither implies the other). `agent` is+ * also a sibling NOT implied by admin (v0.38 D13): admin tokens must be+ * explicitly re-registered with bindings to touch the agent lane.** Local CLI callers (ctx.remote === false) bypass scope enforcement* because the trust boundary there is the OS, not OAuth scopes.*/- scope?: 'read' | 'write' | 'admin' | 'sources_admin' | 'users_admin';+ scope?: 'read' | 'write' | 'admin' | 'sources_admin' | 'users_admin' | 'agent';localOnly?: boolean;/**- * MEMORY_VERBS v1: marks the five frozen protocol verbs (recall, remember,- * entity, synthesize, forget). `gbrain serve --surface verbs` exposes- * EXACTLY the ops with `verb: true`; `full` (default) exposes everything.+ * WP1 honest catalog: the op is callable by remote callers only when this+ * config gate resolves true (dual-plane, DB > file > absent=false). Network+ * transports hide the op from tools/list while the gate is off — a listed+ * tool that always denies reads as broken, not private. The in-handler+ * gate (assertPublishEnabled / the advisor inline check) stays as the+ * fail-closed call-time backstop; stdio (local pipe) bypasses publish+ * gates entirely. Resolution lives in src/mcp/publish-gates.ts.+ */+ publishGateKey?: 'mcp.publish_skills' | 'mcp.publish_advisor';+ /**+ * MEMORY_VERBS v1: marks the seven frozen protocol verbs (recall, remember,+ * entity, synthesize, forget, context_pack, delta). `gbrain serve --surface+ * verbs` exposes EXACTLY the ops with `verb: true`; 'starter' (the ~20-op+ * daily-driver tier) sits between verbs and `full` (default), which exposes+ * everything.*/verb?: boolean;+ /**+ * WP4 (amendment 22) — coarse grouping label consumed by the+ * `request_tools` catalog and the generated tool-catalog doc. Area NAMES+ * ARE NON-CONTRACTUAL: they exist so an agent can scan ~20 groups instead+ * of ~100 flat names; renaming/regrouping is never a breaking change.+ * Required (by the CI walker in test/mcp-tool-defs.test.ts) on every+ * non-localOnly op; populated centrally via OP_AREAS at the bottom of+ * this file.+ */+ area?: string;+ /**+ * WP4 (FOV-4) — marks a discovery meta-op callable by the `agent` scope+ * IN ADDITION to its declared scope. `agent` deliberately implies only+ * itself (v0.38 D13), which would strand agent-only tokens with zero+ * discovery; the MCP scope checks (serve-http tools/list + tools/call)+ * add a one-line carve-out for ops with this flag. Currently only+ * `request_tools`.+ */+ agentCallable?: true;/*** MCP ToolAnnotations passthrough (SDK 1.29+). Emitted by buildToolDefs* ONLY when set — existing tools keep byte-identical definitions.@@ -1513,22 +1644,19 @@ const put_page: Operation = {// validators on the freshly-written page and logs findings to// ingest_log + ~/.gbrain/validator-lint.jsonl. Does NOT reject the// write — that's the deferred strict-mode flip after the 7-day soak.- let writerLint: { error_count: number; warning_count: number } | { skipped: string } | undefined;+ // Response contract (T11): lint ran → full summary (counts, errors-first+ // top_findings with hints, by_validator histogram) even at zero findings;+ // lint crashed → {status: 'lint_error'}; lint off (flag / validate:false)+ // → key absent.+ let writerLint: WriterLintPayload | undefined;try {- const { runPostWriteLint } = await import('./output/post-write.ts');- const lint = await runPostWriteLint(ctx.engine, result.slug, {+ const { writerLintForPutPage } = await import('./output/post-write.ts');+ writerLint = await writerLintForPutPage(ctx.engine, result.slug, {sourceId: ctx.sourceId ?? 'default',});- if (lint.ran) {- writerLint = {- error_count: lint.findings.filter(f => f.severity === 'error').length,- warning_count: lint.findings.filter(f => f.severity === 'warning').length,- };- } else if (lint.skippedReason) {- writerLint = { skipped: lint.skippedReason };- }} catch {- // Non-fatal; never blocks put_page.+ // Module-load failure gets the same crash marker; never blocks put_page.+ writerLint = { status: 'lint_error' };}return {@@ -1735,7 +1863,7 @@ const delete_page: Operation = {name: 'delete_page',description: 'Soft-delete a page. The row is hidden from search and from get_page/list_pages, but is recoverable via restore_page within 72h. The autopilot purge phase hard-deletes after the recovery window. Pass include_deleted: true to get_page to verify the soft-delete landed.',params: {- slug: { type: 'string', required: true },+ slug: { type: 'string', required: true, description: "Slug of the page to soft-delete, e.g. 'people/alice-example'." },},mutating: true,scope: 'write',@@ -1769,7 +1897,7 @@ const restore_page: Operation = {name: 'restore_page',description: 'v0.26.5 — restore a soft-deleted page (clear deleted_at). Returns success only if the page was actually soft-deleted. After this op, the page reappears in search and in get_page/list_pages without the include_deleted flag.',params: {- slug: { type: 'string', required: true },+ slug: { type: 'string', required: true, description: "Slug of the soft-deleted page to restore, e.g. 'people/alice-example'." },},mutating: true,scope: 'write',@@ -1926,11 +2054,44 @@ const list_pages: Operation = {// --- Search ---+/**+ * WP2/D3 + E1: the `retrieval` response-meta payload for the search/query+ * ops. Carries the already-computed HybridSearchMeta signal (vector arm,+ * cache, budget, degradation stages — populated by the search pipeline) plus+ * the concept-shaped hint, so an MCP caller can distinguish "clean miss"+ * from "the pipeline degraded" without a second call. The `hint` is+ * non-contractual prose (agents read it; nothing should parse it).+ */+function buildRetrievalResponseMeta(+ queryText: string,+ results: unknown[],+ meta: HybridSearchMeta | null,+ opts: { conceptHint?: boolean } = {},+): Record<string, unknown> {+ const m = meta as (HybridSearchMeta & { degraded?: unknown; retrieved_count?: number }) | null;+ const hint = opts.conceptHint && looksConceptShaped(queryText)+ ? "concept-shaped question — the 'query' tool adds multi-query expansion and recovers " ++ 'synonym-phrased matches this keyword-leaning search can miss.'+ : undefined;+ return {+ returned_count: results.length,+ retrieved_count: m?.retrieved_count ?? results.length,+ ...(m ? {+ vector_enabled: m.vector_enabled,+ expansion_applied: m.expansion_applied,+ ...(m.cache ? { cache: m.cache.status } : {}),+ ...(m.token_budget ? { token_budget: m.token_budget } : {}),+ ...(m.degraded !== undefined ? { degraded: m.degraded } : {}),+ } : {}),+ ...(hint ? { hint } : {}),+ };+}+const search: Operation = {name: 'search',description: SEARCH_DESCRIPTION,params: {- query: { type: 'string', required: true },+ query: { type: 'string', required: true, description: "Search text. Exact tokens, names, and structured-field values work best here (e.g. 'acme-example series A'), since this op does no LLM expansion. This is the search text param — there is no `text` or `q` param." },limit: { type: 'number', description: 'Max results (default 20)' },offset: { type: 'number', description: 'Skip first N results (for pagination)' },mode: { type: 'string', description: 'Search mode (conservative|balanced|tokenmax). Local callers only.' },@@ -1967,6 +2128,7 @@ const search: Operation = {await stampUnverifiedExtractions(ctx.engine, results);bumpLastRetrievedAt(ctx.engine, results.map((r) => r.page_id));maybeCaptureSearch(ctx, queryText, results, Date.now() - startedAt, false);+ ctx.emitResponseMeta?.('retrieval', buildRetrievalResponseMeta(queryText, results, null, { conceptHint: true }));return results;}@@ -1984,6 +2146,7 @@ const search: Operation = {const latency_ms = Date.now() - startedAt;bumpLastRetrievedAt(ctx.engine, results.map((r) => r.page_id));maybeCaptureSearch(ctx, queryText, results, latency_ms, true, capturedMeta);+ ctx.emitResponseMeta?.('retrieval', buildRetrievalResponseMeta(queryText, results, capturedMeta, { conceptHint: true }));return results;},scope: 'read',@@ -1999,7 +2162,7 @@ const query: Operation = {// validator at src/cli.ts honors `cliHints.altRequired` and admits the// image-only invocation. MCP / programmatic callers must still pass// `query` OR `image` (handler refuses if both are absent).- query: { type: 'string', required: false },+ query: { type: 'string', required: false, description: "Question or topic text for hybrid retrieval with expansion (e.g. 'agents that do web research'). This is the search text param — there is no `text` or `q` param. Optional ONLY because `image` is the alternative entry point; a call with neither fails with invalid_params." },/** v0.27.1: image-similarity search. Path resolved on the CLI side* before the op fires (the op receives raw bytes neither side; the* CLI loads the file, base64-encodes, and passes through `image`). */@@ -2133,7 +2296,13 @@ const query: Operation = {}if (!queryText) {- throw new Error('query requires either `query` (text) or `image` (base64 bytes).');+ // WP3: typed envelope — a caller mistake must classify as invalid_params+ // over MCP, not the internal_error a plain throw produced.+ throw new OperationError(+ 'invalid_params',+ 'query requires either `query` (text) or `image` (base64 bytes).',+ 'Pass `query` with your search text (e.g. {"query": "acme-example roadmap"}), or `image` with base64 image bytes.',+ );}// v0.25.0 — capture meta side-channel. hybridSearch's return contract@@ -2221,6 +2390,8 @@ const query: Operation = {);}+ // WP2/D3: query never nudges toward itself — no concept hint here.+ ctx.emitResponseMeta?.('retrieval', buildRetrievalResponseMeta(queryText, results, capturedMeta));return results;},scope: 'read',@@ -2268,7 +2439,7 @@ const takes_search: Operation = {description: 'Keyword search across takes (pg_trgm similarity over claim text)',scope: 'read',params: {- query: { type: 'string', required: true },+ query: { type: 'string', required: true, description: "Search text matched against take claim text via trigram similarity, e.g. 'valuation cap'. This is the search text param — there is no `text` param." },limit: { type: 'number', description: 'Max results (default 30, cap 100)' },},handler: async (ctx, p) => {@@ -2415,8 +2586,8 @@ const add_tag: Operation = {name: 'add_tag',description: 'Add tag to page',params: {- slug: { type: 'string', required: true },- tag: { type: 'string', required: true },+ slug: { type: 'string', required: true, description: "Slug of the page to tag, e.g. 'people/alice-example'." },+ tag: { type: 'string', required: true, description: "Tag to add — a plain string like 'founder' or 'follow-up', not a slug." },},mutating: true,scope: 'write',@@ -2435,8 +2606,8 @@ const remove_tag: Operation = {name: 'remove_tag',description: 'Remove tag from page',params: {- slug: { type: 'string', required: true },- tag: { type: 'string', required: true },+ slug: { type: 'string', required: true, description: 'Slug of the page to untag.' },+ tag: { type: 'string', required: true, description: 'Tag to remove (exact match against the tags get_tags returns).' },},mutating: true,scope: 'write',@@ -2454,7 +2625,7 @@ const get_tags: Operation = {name: 'get_tags',description: 'List tags for a page',params: {- slug: { type: 'string', required: true },+ slug: { type: 'string', required: true, description: 'Slug of the page whose tags to list.' },},handler: async (ctx, p) => {// #2200: route through sourceScopeOpts so a federated read grant@@ -2486,8 +2657,8 @@ const add_link: Operation = {name: 'add_link',description: 'Create link between pages',params: {- from: { type: 'string', required: true },- to: { type: 'string', required: true },+ from: { type: 'string', required: true, description: "Slug of the page the link originates from (the edge renders on this page), e.g. 'people/alice-example'. These are page slugs — there is no `source`/`target` pair." },+ to: { type: 'string', required: true, description: "Slug of the page the link points to, e.g. 'companies/acme-example'." },link_type: { type: 'string', description: 'Link type (e.g., invested_in, works_at)' },context: { type: 'string', description: 'Context for the link' },link_source: { type: 'string', description: "Provenance tag (kebab-case, e.g. 'citation-graph'). Defaults to 'manual'. Reconciliation-managed built-ins (markdown/frontmatter/mentions/wikilink-resolved) are rejected." },@@ -2531,8 +2702,8 @@ const remove_link: Operation = {name: 'remove_link',description: 'Remove link between pages',params: {- from: { type: 'string', required: true },- to: { type: 'string', required: true },+ from: { type: 'string', required: true, description: 'Slug of the page the link originates from (same endpoint order as add_link).' },+ to: { type: 'string', required: true, description: 'Slug of the page the link points to.' },link_type: { type: 'string', description: 'Only remove edges of this link type (omit = all types)' },link_source: { type: 'string', description: 'Only remove edges of this provenance (e.g. citation-graph); omit = any provenance' },},@@ -2559,7 +2730,7 @@ const get_links: Operation = {name: 'get_links',description: 'List outgoing links from a page',params: {- slug: { type: 'string', required: true },+ slug: { type: 'string', required: true, description: 'Slug of the page whose outgoing links to list.' },},handler: async (ctx, p) => {// #2200: linkReadScopeOpts so a federated grant — and an untrusted remote@@ -2575,7 +2746,7 @@ const get_backlinks: Operation = {name: 'get_backlinks',description: 'List incoming links to a page',params: {- slug: { type: 'string', required: true },+ slug: { type: 'string', required: true, description: 'Slug of the page whose incoming links to list.' },},handler: async (ctx, p) => {// #2200: linkReadScopeOpts — federated grant + untrusted remote scalar@@ -2617,7 +2788,7 @@ const traverse_graph: Operation = {name: 'traverse_graph',description: 'Traverse link graph from a page. With link_type/direction, returns edges (GraphPath[]) instead of nodes.',params: {- slug: { type: 'string', required: true },+ slug: { type: 'string', required: true, description: "Slug of the page to start the traversal from, e.g. 'people/alice-example'. This is the start-node param — there is no `start` or `root` param." },depth: { type: 'number', description: `Max traversal depth (default 5, capped at ${TRAVERSE_DEPTH_CAP})` },link_type: { type: 'string', description: 'Filter to one link type (per-edge filter, traversal only follows matching edges)' },direction: { type: 'string', enum: ['in', 'out', 'both'], description: 'Traversal direction (default out)' },@@ -2653,11 +2824,11 @@ const add_timeline_entry: Operation = {name: 'add_timeline_entry',description: 'Add timeline entry to a page',params: {- slug: { type: 'string', required: true },- date: { type: 'string', required: true },- summary: { type: 'string', required: true },- detail: { type: 'string' },- source: { type: 'string' },+ slug: { type: 'string', required: true, description: 'Slug of the page whose timeline to append to.' },+ date: { type: 'string', required: true, description: "Entry date, strict YYYY-MM-DD (e.g. '2026-04-03'). Timestamps and non-calendar dates are rejected." },+ summary: { type: 'string', required: true, description: 'One-line summary of what happened on that date.' },+ detail: { type: 'string', description: 'Longer free-text detail behind the summary.' },+ source: { type: 'string', description: "Provenance ref for the entry, e.g. a meeting slug like 'meetings/2026-04-03' or a URL." },},mutating: true,scope: 'write',@@ -2702,7 +2873,7 @@ const get_timeline: Operation = {name: 'get_timeline',description: 'Get timeline entries for a page, optionally filtered by date window',params: {- slug: { type: 'string', required: true },+ slug: { type: 'string', required: true, description: 'Slug of the page whose timeline entries to return.' },after: { type: 'string', description: 'Return entries on or after this date (YYYY-MM-DD)' },before: { type: 'string', description: 'Return entries on or before this date (YYYY-MM-DD)' },since: { type: 'string', description: 'Alias for after; accepted for agent callers' },@@ -2810,6 +2981,7 @@ const get_brain_identity: Operation = {const list_skills: Operation = {name: 'list_skills',description: LIST_SKILLS_DESCRIPTION,+ publishGateKey: 'mcp.publish_skills',params: {section: {type: 'string',@@ -2832,6 +3004,7 @@ const list_skills: Operation = {const get_skill: Operation = {name: 'get_skill',description: GET_SKILL_DESCRIPTION,+ publishGateKey: 'mcp.publish_skills',params: {name: {type: 'string',@@ -2872,6 +3045,7 @@ const list_brain_skillpack: Operation = {'one-line descriptions, the schema pack it targets + whether that matches this brain, and a ' +'git scaffold spec. Read-only; gated by mcp.publish_skills. After orienting, call this and ' +'ask the user whether to install any pack the brain offers (gbrain skillpack scaffold <spec>).',+ publishGateKey: 'mcp.publish_skills',params: {},handler: async (ctx) => {const sc = await import('./skill-catalog.ts');@@ -2892,6 +3066,7 @@ const advisor: Operation = {'severity, why-it-matters, and the exact fix command. Never mutates. Tell the user; ask ' +'before running any fix. Gated by mcp.publish_advisor (separate from mcp.publish_skills ' +'because diagnostics are not prose skills).',+ publishGateKey: 'mcp.publish_advisor',params: {},handler: async (ctx) => {// Publish gate: a remote caller needs mcp.publish_advisor=true. Local@@ -2905,11 +3080,16 @@ const advisor: Operation = {enabled = ctx.config?.mcp?.publish_advisor === true;}if (!enabled) {- throw new OperationError(+ // Same k=v detail grammar as assertPublishEnabled (WP1): honest+ // catalogs hide this op at list time; the throw is the backstop.+ const err = new OperationError('permission_denied',- 'The advisor is not published over MCP by the brain owner.',+ 'The advisor is not published over MCP by the brain owner, so it is hidden from your ' ++ 'tool catalog. Ask the owner to enable it if you need it.','The owner can enable it with `gbrain config set mcp.publish_advisor true`.',);+ err.detail = 'config_key=mcp.publish_advisor';+ throw err;}}const { runAdvisor } = await import('./advisor/run.ts');@@ -2944,21 +3124,26 @@ const advisor: Operation = {* - Scope: admin (NOT localOnly). The op exposes operational state* including sync timestamps and cycle metadata. Locking it to admin* matches the `run_doctor` posture and prevents future feature creep- * (adding locks/workers/queue counters) from quietly leaking ops state- * to read-scoped clients.+ * from quietly leaking ops state to read-scoped clients.+ *+ * - Payload (schema_version 2, Minions-visibility wave): `{schema_version,+ * version, sync, cycle, queue, workers}`. `queue` (status counts ++ * per-queue waiting depth + oldest-waiting age) and `workers`+ * (supervisor liveness via pidfile/DB-lock + last completed job) were+ * added so a remote submitter can see whether the lane its job ids point+ * at is actually alive. Locks and Autopilot stay deliberately omitted —+ * host-local concerns the thin client renders as "N/A on remote brain".*- * - Payload: `{schema_version: 1, sync, cycle}` ONLY. Locks, Workers,- * Queue, and Autopilot sections are deliberately omitted from the- * remote payload — they are local-host concerns that thin-client- * callers shouldn't see at all (and the local `gbrain status` renders- * them as "N/A on remote brain" instead of pretending they exist).+ * - Fail-soft (amendment 26): each v2 section computes in its own+ * try/catch and degrades to `{error: 'unavailable'}` without failing+ * the whole snapshot.** - The local CLI composes the same data plus the local-only sections* directly (no MCP round-trip when running against ~/.gbrain).*/const get_status_snapshot: Operation = {name: 'get_status_snapshot',- description: 'Snapshot for `gbrain status` thin-client mode: sync freshness + last cycle. Admin-scope.',+ description: 'Snapshot for `gbrain status` thin-client mode: sync freshness + last cycle + queue depths + worker liveness. Admin-scope.',params: {},handler: async (ctx) => {const { buildSyncStatusReport } = await import('../commands/sync.ts');@@ -2997,10 +3182,27 @@ const get_status_snapshot: Operation = {}const sync = await buildSyncStatusReport(ctx.engine, sources);const cycle = await buildCycleSnapshot(ctx.engine);+ // v2 sections, each fail-soft (amendment 26): a broken/pre-migration+ // queue table must not take down the sync/cycle payload that v1 clients+ // already depend on.+ let queue: unknown;+ try {+ const { buildQueueCounts, buildQueueDepths } = await import('../commands/status.ts');+ queue = { counts: await buildQueueCounts(ctx.engine), by_queue: await buildQueueDepths(ctx.engine) };+ } catch {+ queue = { error: 'unavailable' as const };+ }+ let workers: unknown;+ try {+ const { buildWorkersSnapshot } = await import('../commands/status.ts');+ workers = await buildWorkersSnapshot(ctx.engine);+ } catch {+ workers = { error: 'unavailable' as const };+ }// #1984: report the brain server's version so a thin-client `gbrain status`// can surface remote_version alongside its own local CLI version.const { VERSION } = await import('../version.ts');- return { schema_version: 1 as const, version: VERSION, sync, cycle };+ return { schema_version: 2 as const, version: VERSION, sync, cycle, queue, workers };},scope: 'admin',localOnly: false,@@ -3044,7 +3246,7 @@ const get_versions: Operation = {name: 'get_versions',description: 'Page version history',params: {- slug: { type: 'string', required: true },+ slug: { type: 'string', required: true, description: 'Slug of the page whose version history to list.' },},handler: async (ctx, p) => {const versions = await ctx.engine.getVersions(p.slug as string, sourceScopeOpts(ctx));@@ -3063,8 +3265,8 @@ const revert_version: Operation = {name: 'revert_version',description: 'Revert page to a previous version',params: {- slug: { type: 'string', required: true },- version_id: { type: 'number', required: true },+ slug: { type: 'string', required: true, description: 'Slug of the page to revert.' },+ version_id: { type: 'number', required: true, description: 'Numeric version id to revert to, as returned by get_versions. Not a version NUMBER offset — pass the id field.' },},mutating: true,scope: 'write',@@ -3122,7 +3324,7 @@ const put_raw_data: Operation = {name: 'put_raw_data',description: 'Store raw API response data for a page',params: {- slug: { type: 'string', required: true },+ slug: { type: 'string', required: true, description: 'Slug of the page to attach the raw data to.' },source: { type: 'string', required: true, description: 'Data source (e.g., crustdata, happenstance)' },data: { type: 'object', required: true, description: 'Raw data object' },},@@ -3142,7 +3344,7 @@ const get_raw_data: Operation = {name: 'get_raw_data',description: 'Retrieve raw data for a page',params: {- slug: { type: 'string', required: true },+ slug: { type: 'string', required: true, description: 'Slug of the page whose raw data to fetch.' },source: { type: 'string', description: 'Filter by source' },},handler: async (ctx, p) => {@@ -3157,7 +3359,7 @@ const resolve_slugs: Operation = {name: 'resolve_slugs',description: 'Fuzzy-resolve a partial slug to matching page slugs',params: {- partial: { type: 'string', required: true },+ partial: { type: 'string', required: true, description: "Partial slug or title text to match, e.g. 'alice-ex' or 'meeting notes'. This is the search text param — there is no `text` param." },},handler: async (ctx, p) => {// #3242: was fully UNSCOPED — the one read that leaked every source's@@ -3173,7 +3375,7 @@ const get_chunks: Operation = {name: 'get_chunks',description: 'Get content chunks for a page',params: {- slug: { type: 'string', required: true },+ slug: { type: 'string', required: true, description: 'Slug of the page whose content chunks to return.' },},handler: async (ctx, p) => {// #2555: route through the canonical scope ladder (federated array >@@ -3190,10 +3392,10 @@ const log_ingest: Operation = {name: 'log_ingest',description: 'Log an ingestion event',params: {- source_type: { type: 'string', required: true },- source_ref: { type: 'string', required: true },- pages_updated: { type: 'array', required: true, items: { type: 'string' } },- summary: { type: 'string', required: true },+ source_type: { type: 'string', required: true, description: "Kind of ingest source, e.g. 'email', 'meeting', 'rss', 'api'." },+ source_ref: { type: 'string', required: true, description: 'Identifier of the ingested item — a URL, message id, or file path.' },+ pages_updated: { type: 'array', required: true, items: { type: 'string' }, description: 'Slugs of the pages this ingest created or updated.' },+ summary: { type: 'string', required: true, description: 'One-line human-readable summary of what was ingested.' },},mutating: true,scope: 'write',@@ -3462,10 +3664,32 @@ const submit_job: Operation = {} catch { /* audit failures never block submission */ }}- return job;+ // Amendments 24/25: post-enqueue queue-state probe (time-bounded,+ // fail-open). The job is already persisted; a probe failure degrades to+ // {probe_failed: true}, never an error on a successful submission.+ return { ...job, queue_state: await probeQueueStateSafe(ctx, job.queue, [name]) };},};+/**+ * Wrapper around `probeQueueState` that also swallows module-load failures,+ * so BOTH submit surfaces (submit_job, submit_agent) satisfy amendment 24's+ * "probe failure NEVER errors a successful submission" — even when the+ * supervisor module itself cannot load.+ */+async function probeQueueStateSafe(+ ctx: OperationContext,+ queue: string,+ handlerNames: string[],+): Promise<Record<string, unknown>> {+ try {+ const { probeQueueState } = await import('./minions/supervisor.ts');+ return (await probeQueueState(ctx.engine, queue, handlerNames)) as unknown as Record<string, unknown>;+ } catch {+ return { probe_failed: true };+ }+}+// v0.38 Slice 3 — D13 — remote-callable submit_agent with registration-time// binding enforcement. Distinct from `submit_job` because:// 1. It's the FIRST op that lets remote MCP callers spawn paid LLM work@@ -3486,7 +3710,7 @@ const submit_agent: Operation = {queue: { type: 'string', description: 'Queue name (default "default")' },},mutating: true,- scope: 'agent' as any,+ scope: 'agent',handler: async (ctx, p) => {// Remote-callable but only when the OAuth client has scope=agent AND// a binding row. Local CLI callers (ctx.remote === false) skip the@@ -3689,7 +3913,117 @@ const submit_agent: Operation = {});} catch { /* never block submission */ }- return { id: job.id, name: 'subagent', client_id: clientId };+ // Amendments 24/25: the returned job id means nothing if the lane is+ // dead — attach a time-bounded, fail-open queue-state probe.+ return {+ id: job.id,+ name: 'subagent',+ client_id: clientId,+ queue_state: await probeQueueStateSafe(ctx, job.queue, ['subagent']),+ };+ },+};++/**+ * Minions-visibility wave — ownership-fenced agent-job status (amendment 27).+ *+ * The companion read for `submit_agent`: an agent-scoped client can poll ONLY+ * its own delegated jobs. Deliberate posture:+ * - `ctx.auth.clientId` is REQUIRED on EVERY transport — stdio and legacy+ * bearer callers carry no client identity and are refused+ * (permission_denied) rather than silently unfenced. This is stricter+ * than scope enforcement alone (which local/stdio callers bypass).+ * - The ownership filter is a fail-closed SQL WHERE on+ * `data->>'__owner_client_id'` (the JSONB predicate submit_agent already+ * uses for its concurrency cap — identical semantics on both engines),+ * never a post-fetch JS check.+ * - Foreign and missing ids return one uniform `not_found` envelope so the+ * op is not a job-id enumeration oracle (ENG-13; the ErrorCode comment+ * was widened accordingly). Shell/admin jobs stay on admin-scope+ * `get_job` — this op reads the agent lane (`name = 'subagent'`) only.+ * - `queue_position` = count of waiting jobs ahead in claim order+ * (priority ASC, created_at ASC — the exact ORDER BY of+ * `MinionQueue.claim`), computed only while status = 'waiting'.+ */+const get_agent_job: Operation = {+ name: 'get_agent_job',+ description: 'Poll an agent job submitted via submit_agent. Returns a trimmed status view (id, status, timestamps, error_text, result) plus queue_position (waiting jobs ahead in claim order; 0 = next) while the job is still waiting. Requires the `agent` OAuth scope; only jobs owned by the calling client are visible.',+ params: {+ id: { type: 'number', required: true, description: 'Job id returned by submit_agent' },+ },+ scope: 'agent',+ handler: async (ctx, p) => {+ const clientId = ctx.auth?.clientId;+ if (!clientId || typeof clientId !== 'string') {+ throw new OperationError(+ 'permission_denied',+ 'get_agent_job requires an authenticated OAuth client identity.',+ 'Call over HTTP MCP with an `agent`-scoped token. Transports without a per-client identity (stdio, legacy bearer) cannot read agent jobs; use admin-scope get_job from a trusted context instead.',+ );+ }+ const id = p.id;+ if (typeof id !== 'number' || !Number.isInteger(id)) {+ throw new OperationError('invalid_params', 'id must be an integer job id');+ }++ // One round-trip: the ownership fence rides the WHERE, and the+ // queue_position subselect mirrors MinionQueue.claim's candidate set+ // (same queue, status='waiting') and ORDER BY (priority, created_at),+ // with the row id as the deterministic tie-break. Perf: the outer lookup+ // is a primary-key read; the subselect's (queue, status) filter is+ // covered by the wave's wedge-index prefix once that migration (another+ // lane) lands, and stays a small scan until then.+ const rows = await ctx.engine.executeRaw<{+ id: number;+ status: string;+ created_at: string | Date | null;+ started_at: string | Date | null;+ finished_at: string | Date | null;+ error_text: string | null;+ result: unknown;+ queue_position: number | string | null;+ }>(+ `SELECT j.id, j.status, j.created_at, j.started_at, j.finished_at, j.error_text, j.result,+ CASE WHEN j.status = 'waiting' THEN (+ SELECT count(*)::int FROM minion_jobs q+ WHERE q.queue = j.queue AND q.status = 'waiting'+ AND (q.priority < j.priority+ OR (q.priority = j.priority AND q.created_at < j.created_at)+ OR (q.priority = j.priority AND q.created_at = j.created_at AND q.id < j.id))+ ) ELSE NULL END AS queue_position+ FROM minion_jobs j+ WHERE j.id = $1+ AND j.name = 'subagent'+ AND j.data->>'__owner_client_id' = $2`,+ [id, clientId],+ );+ if (rows.length === 0) {+ // Uniform envelope: foreign-owned and nonexistent ids are+ // indistinguishable by design (anti-enumeration).+ throw new OperationError('not_found', `Job not found: ${id}`);+ }+ const row = rows[0];+ const iso = (v: string | Date | null): string | null =>+ v ? (v instanceof Date ? v.toISOString() : new Date(v).toISOString()) : null;+ // PGLite may hand jsonb back as text; postgres.js parses it.+ let result: unknown = row.result ?? null;+ if (typeof result === 'string') {+ try { result = JSON.parse(result); } catch { /* keep raw text */ }+ }+ return {+ id: row.id,+ status: row.status,+ created_at: iso(row.created_at),+ started_at: iso(row.started_at),+ finished_at: iso(row.finished_at),+ // Cap: error_text is an unbounded worker-written field (stack traces,+ // provider dumps); a remote polling view shouldn't ship megabytes.+ error_text: row.error_text ? row.error_text.slice(0, 2000) : null,+ result,+ ...(row.status === 'waiting' && row.queue_position !== null+ ? { queue_position: Number(row.queue_position) }+ : {}),+ };},};@@ -4482,7 +4816,7 @@ const sources_remove: Operation = {'under $GBRAIN_HOME/clones/ (realpath+lstat — symlink-safe). For most ' +'workflows prefer sources_archive for the soft-delete path.',params: {- id: { type: 'string', required: true },+ id: { type: 'string', required: true, description: "Source id to remove, as listed by sources_list (e.g. 'wiki'). A source id, not a page slug." },confirm_destructive: {type: 'boolean',description:@@ -4516,7 +4850,7 @@ const sources_status: Operation = {'so a remote MCP caller can diagnose whether the on-disk clone is ' +'syncable without SSH access to the brain host.',params: {- id: { type: 'string', required: true },+ id: { type: 'string', required: true, description: "Source id to diagnose, as listed by sources_list (e.g. 'wiki'). A source id, not a page slug." },},scope: 'read',handler: async (ctx, p) => {@@ -6679,10 +7013,259 @@ const extraction_review: Operation = {cliHints: { name: 'extraction-review', positional: ['action'] },};+// --- WP4 (T9): request_tools — discovery + pull-based per-client unlock ---++/**+ * D14.5: per-client rate limit on the persist branch (~5 surface persists /+ * hour / client). Module-level token bucket (bounded LRU — attacker-chosen+ * client ids can't grow memory); `let` + reset seam so tests don't leak+ * bucket state across files.+ */+let requestToolsPersistLimiter = new RateLimiter({ limit: 5, windowMs: 3_600_000, lruCap: 5_000 });++/** Test seam: fresh persist-rate-limit buckets. */+export function __resetRequestToolsPersistLimiterForTests(): void {+ requestToolsPersistLimiter = new RateLimiter({ limit: 5, windowMs: 3_600_000, lruCap: 5_000 });+}++/**+ * One-line catalog summary: the first sentence of an op description,+ * capped. Non-contractual rendering — full schemas come from the+ * `{tools: [...]}` branch.+ */+function firstSentenceOf(description: string): string {+ const t = description.trim();+ const m = t.match(/^.*?[.!?](?=\s|$)/);+ const s = (m ? m[0] : t).trim();+ return s.length > 160 ? `${s.slice(0, 157)}...` : s;+}++/**+ * The set of ops VISIBLE to this caller (never leak hidden names — C8/+ * amendment 11 class): bounded by the server ceiling (ops above it can+ * never be served, so naming them would recreate listed-but-denied at the+ * persist level), minus localOnly on network transports (stdio and the+ * trusted local CLI keep them — D7), minus ops outside the caller's scopes+ * (agent-callable carve-out per FOV-4), minus bound-client-fenced ops (same+ * predicate as tools/list, ENG-3), minus publish-gated ops whose gate is off+ * (stdio and the trusted local CLI bypass gates — the D7 local-surface+ * posture, matching assertPublishEnabled's remote===false exemption; a+ * failed gate read hides the gated ops, fail-closed).+ */+async function visibleOpsForCaller(+ ctx: OperationContext,+ ceiling: 'verbs' | 'starter' | 'full',+): Promise<Operation[]> {+ const { filterOpsForSurface } = await import('../mcp/surface.ts');+ // Trusted local callers: the stdio pipe, or the local CLI (remote is+ // strictly false — the fail-closed trust marker). Both CAN call localOnly+ // and gated ops, so hiding them would make the catalog dishonest.+ const isLocal = ctx.transport === 'stdio' || ctx.remote === false;++ let gateDisabled: ReadonlySet<string> = new Set();+ if (!isLocal) {+ try {+ const { disabledOpsForPublishGates } = await import('../mcp/publish-gates.ts');+ gateDisabled = await disabledOpsForPublishGates(ctx.engine, ctx.config);+ } catch {+ // Fail-closed: if the resolver can't even load, hide every gated op.+ gateDisabled = new Set(operations.filter(o => o.publishGateKey).map(o => o.name));+ }+ }++ // Auth-less transports (stdio) and grandfathered legacy bearer tokens+ // (empty scopes array — that transport does no call-time scope checks+ // either) skip scope filtering: for them the whole surface IS callable,+ // so hiding by scope would make the catalog LESS honest, not more.+ const scopes = ctx.auth?.scopes && ctx.auth.scopes.length > 0 ? ctx.auth.scopes : null;++ return filterOpsForSurface(operations, ceiling).filter(op =>+ (isLocal || !op.localOnly)+ && (scopes === null+ || hasScope(scopes, op.scope ?? 'read')+ || (op.agentCallable === true && hasScope(scopes, 'agent')))+ && opAllowedForBoundClient(ctx.auth, op)+ && !gateDisabled.has(op.name),+ );+}++const request_tools: Operation = {+ name: 'request_tools',+ description:+ '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.',+ area: 'discovery',+ // FOV-4: callable by read OR agent scope — discovery for every token class.+ agentCallable: true,+ params: {+ tools: {+ type: 'array',+ items: { type: 'string', description: 'A tool name from the catalog.' },+ description: 'Fetch full read-only tool schemas for these names. Names outside your visible surface are silently omitted (D5).',+ },+ surface: {+ type: 'string',+ enum: ['verbs', 'starter', 'full'],+ description: 'Persist this tool surface for your client. Must not exceed the server ceiling; ignored surfaces stay available via no-arg discovery. Takes effect on your next tools/list.',+ },+ },+ scope: 'read',+ // D9: mutating because the persist branch writes oauth_clients.surface.+ // The bound-client fence exempts it via BOUND_CLIENT_META_OPS (see the+ // carve-out comment at opAllowedForBoundClient); the persist branch+ // self-enforces ceiling + operator lock + scopes + rate limit.+ mutating: true,+ handler: async (ctx, p) => {+ const { surfaceWiderThan, isMcpSurface } = await import('../mcp/surface.ts');+ // Unset ceiling (local CLI / direct dispatch) = 'full' — trusted-local+ // callers were never surface-bounded.+ const ceiling = ctx.surfaceCeiling ?? 'full';++ // D5: the three branches are mutually exclusive. {surface, tools}+ // together is ambiguous (persist vs descriptor fetch) — reject loudly+ // rather than silently persisting and ignoring the tools list.+ if (p.surface !== undefined && p.tools !== undefined) {+ throw new OperationError(+ 'invalid_params',+ 'pass either {surface} (persist) or {tools} (descriptor fetch), not both.',+ );+ }++ // ── persist branch (D5: accepts ONLY {surface}) ─────────────────────+ if (p.surface !== undefined) {+ const requested = p.surface as string;+ if (!isMcpSurface(requested)) {+ // Backstop for direct handler calls — MCP dispatch already rejects+ // via the enum in validateParams (invalid_params naming the valid set).+ throw new OperationError('invalid_params', `surface must be one of: verbs, starter, full (got an unrecognized value)`);+ }+ const clientId = ctx.auth?.clientId;+ if (!clientId) {+ // stdio has no per-token identity; a surface persist has nowhere to land.+ return { persisted: false, reason: 'no per-client surface on this transport; use --surface' };+ }+ if (surfaceWiderThan(requested, ceiling)) {+ const e = new OperationError(+ 'permission_denied',+ `surface '${requested}' is above this server's ceiling '${ceiling}' (D2: per-client surfaces narrow, never widen).`,+ `The operator caps this transport at --surface ${ceiling}; widening requires a server restart with a wider --surface.`,+ );+ e.detail = `ceiling=${ceiling}`; // amendment 4 key=value denial grammar; ENG-11 assign-after+ throw e;+ }+ let rows: Record<string, unknown>[];+ try {+ rows = await ctx.engine.executeRaw(+ `SELECT surface, surface_set_by FROM oauth_clients WHERE client_id = $1`,+ [clientId],+ );+ } catch (err) {+ if (isUndefinedColumnError(err, 'surface') || isUndefinedColumnError(err, 'surface_set_by')) {+ // D5: a capability-negotiation op never returns internal_error for+ // a pre-migration brain — report the gap and keep serving.+ return { persisted: false, reason: 'migration pending' };+ }+ throw err;+ }+ if (rows.length === 0) {+ // Legacy bearer tokens carry a clientId that is not an oauth_clients row.+ return { persisted: false, reason: 'no per-client surface on this transport; use --surface' };+ }+ const current = rows[0] as { surface?: string | null; surface_set_by?: string | null };+ const operatorLocked = () => {+ const e = new OperationError(+ 'permission_denied',+ "this client's surface is operator-pinned and cannot be self-changed (amendment 19).",+ `Ask the brain operator to change it: gbrain auth rescope-client ${clientId} --surface ${requested}`,+ );+ e.detail = 'locked_by=operator';+ return e;+ };+ if (current.surface_set_by === 'operator') throw operatorLocked();+ // A dry-run preview exercises every denial above but must not consume+ // the persist budget — the limiter meters actual writes only.+ if (ctx.dryRun) {+ return { persisted: false, dry_run: true, surface: requested, reason: 'dry_run' };+ }+ const rl = requestToolsPersistLimiter.check(clientId);+ if (!rl.allowed) {+ throw new OperationError(+ 'rate_limited',+ 'surface persistence is rate-limited to ~5 changes per hour per client (D14.5).',+ `Retry after ~${rl.retryAfter ?? 60}s.`,+ );+ }+ // Atomic re-check: a concurrent operator pin between the SELECT and+ // this UPDATE must still win.+ const updated = await ctx.engine.executeRaw(+ `UPDATE oauth_clients SET surface = $1, surface_set_by = 'self'+ WHERE client_id = $2 AND (surface_set_by IS DISTINCT FROM 'operator')+ RETURNING client_id`,+ [requested, clientId],+ );+ if (updated.length === 0) {+ // Concurrent operator pin won the race: the denial must not consume+ // the client's persist budget (the limiter meters actual writes).+ requestToolsPersistLimiter.refund(clientId);+ throw operatorLocked();+ }+ await writeSurfaceChangeAudit(ctx.engine, {+ actor: clientId,+ client_id: clientId,+ old: (current.surface as string | null) ?? null,+ new: requested,+ via: 'request_tools',+ });+ return { persisted: true, surface: requested, note: 're-issue tools/list to see the new catalog' };+ }++ const visible = await visibleOpsForCaller(ctx, ceiling);++ // ── descriptor branch (D5: read-only) ───────────────────────────────+ if (p.tools !== undefined) {+ const requested = (p.tools as unknown[]).filter((t): t is string => typeof t === 'string');+ const byName = new Map(visible.map(o => [o.name, o]));+ const picked: Operation[] = [];+ const seen = new Set<string>();+ for (const name of requested) {+ if (seen.has(name)) continue;+ seen.add(name);+ const op = byName.get(name);+ if (op) picked.push(op); // invisible names silently omitted (D5)+ }+ 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';+ return { tools: buildToolDefs(picked, { strictParams }) };+ }++ // ── 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: 'Call request_tools {tools: ["name", ...]} for full schemas, or {surface: "starter"|"full"} to persist a wider tool surface (within the server ceiling), then re-issue tools/list.',+ };+ },+};+export const operations: Operation[] = [// MEMORY_VERBS v1 (Cathedral 1) — remember/entity/synthesize/forget live in- // verbs.ts; the fifth verb is the extended `recall` op below. Spread first- // so `--surface verbs` agents see them at the top of the tool list.+ // verbs.ts; the remaining three of the seven verbs (the extended `recall`,+ // plus the v0.45.x boundary verbs `context_pack`/`delta`) are defined below.+ // Spread first so `--surface verbs` agents see them at the top of the list....verbOperations,// Page CRUDget_page, put_page, delete_page, list_pages,@@ -6720,7 +7303,8 @@ export const operations: Operation[] = [submit_job, get_job, list_jobs, cancel_job, retry_job, get_job_progress,pause_job, resume_job, replay_job, send_job_message,// v0.38 Slice 3: remote-callable agent dispatch with OAuth-bound trust boundary- submit_agent,+ // + Minions-visibility wave: ownership-fenced agent-job polling+ submit_agent, get_agent_job,// Orphansfind_orphans,// v0.36.1.0 (T7) — Hindsight calibration wave: read profile via MCP@@ -6731,6 +7315,8 @@ export const operations: Operation[] = [takes_scorecard, takes_calibration,// v0.28: whoami + scoped sources managementwhoami, sources_add, sources_list, sources_remove, sources_status,+ // WP4 (T9): discovery + pull-based per-client surface unlock (D4/D5/D9)+ request_tools,// v0.29: Salience + anomalies + recent transcriptsget_recent_salience, find_anomalies, get_recent_transcripts,// v0.42.x (#2390): Life Chronicle timeline reads@@ -6774,6 +7360,100 @@ export const operations: Operation[] = [run_skillopt,];+// ---------------------------------------------------------------------------+// WP4 (amendment 22) — area taxonomy.+//+// One central map (single reviewable block) rather than 100+ scattered inline+// fields. Area NAMES ARE NON-CONTRACTUAL: they group the request_tools+// catalog and the generated tool-catalog doc; renaming or regrouping is never+// a breaking change. Every non-localOnly op MUST have an area — enforced by+// the CI walker in test/mcp-tool-defs.test.ts, so a future op missing from+// this map fails at PR time. localOnly ops are covered too (harmless; the+// walker only requires non-localOnly). Ops that declare `area` inline+// (request_tools) win over this map.+// ---------------------------------------------------------------------------+const OP_AREAS: Record<string, string> = {+ // memory verbs (the frozen protocol facade)+ recall: 'memory-verbs', remember: 'memory-verbs', entity: 'memory-verbs',+ synthesize: 'memory-verbs', forget: 'memory-verbs',+ context_pack: 'memory-verbs', delta: 'memory-verbs',+ // pages (CRUD, versions, raw payloads, resolution)+ get_page: 'pages', put_page: 'pages', delete_page: 'pages', list_pages: 'pages',+ restore_page: 'pages', purge_deleted_pages: 'pages',+ get_versions: 'pages', revert_version: 'pages',+ resolve_slugs: 'pages', get_chunks: 'pages',+ put_raw_data: 'pages', get_raw_data: 'pages',+ // search+ search: 'search', query: 'search', search_by_image: 'search',+ // tags+ add_tag: 'tags', remove_tag: 'tags', get_tags: 'tags',+ // links + graph+ add_link: 'links', remove_link: 'links', get_links: 'links',+ get_backlinks: 'links', list_link_sources: 'links', traverse_graph: 'links',+ find_orphans: 'links',+ // timeline+ add_timeline_entry: 'timeline', get_timeline: 'timeline',+ // life chronicle+ chronicle_day: 'chronicle', chronicle_on_this_day: 'chronicle',+ chronicle_since: 'chronicle', chronicle_last_seen: 'chronicle',+ volunteer_chronicle: 'chronicle', chronicle_backfill: 'chronicle',+ // ontology+ ontology_get: 'ontology', ontology_propose: 'ontology',+ ontology_dimensions: 'ontology', ontology_conflicts: 'ontology',+ // admin + operations+ get_stats: 'admin', get_health: 'admin', run_doctor: 'admin',+ get_status_snapshot: 'admin', run_onboard: 'admin', run_skillopt: 'admin',+ migrate_embeddings: 'admin', code_traversal_cache_clear: 'admin',+ // identity+ whoami: 'identity', get_brain_identity: 'identity',+ // skills+ list_skills: 'skills', get_skill: 'skills', list_brain_skillpack: 'skills',+ // advisor+ advisor: 'advisor',+ // sources+ sources_add: 'sources', sources_list: 'sources', sources_remove: 'sources',+ sources_status: 'sources',+ // sync (localOnly)+ sync_brain: 'sync',+ // ingest log+ log_ingest: 'ingest', get_ingest_log: 'ingest',+ // files (localOnly)+ file_list: 'files', file_upload: 'files', file_url: 'files',+ // jobs (Minions + agent lane)+ submit_job: 'jobs', get_job: 'jobs', list_jobs: 'jobs', cancel_job: 'jobs',+ retry_job: 'jobs', get_job_progress: 'jobs', pause_job: 'jobs',+ resume_job: 'jobs', replay_job: 'jobs', send_job_message: 'jobs',+ submit_agent: 'jobs', get_agent_job: 'jobs',+ // takes + think+ takes_list: 'takes', takes_search: 'takes', think: 'takes',+ takes_scorecard: 'takes', takes_calibration: 'takes',+ // hot memory (facts)+ extract_facts: 'memory', forget_fact: 'memory',+ // entity extraction lane+ extract_entities: 'entities', extraction_pending: 'entities',+ extraction_review: 'entities',+ // insight / signal reads+ get_recent_salience: 'insights', find_anomalies: 'insights',+ find_contradictions: 'insights', find_experts: 'insights',+ find_trajectory: 'insights', get_calibration_profile: 'insights',+ volunteer_context: 'insights', get_recent_transcripts: 'insights',+ // code intelligence+ code_callers: 'code', code_callees: 'code', code_def: 'code',+ code_refs: 'code', code_blast: 'code', code_flow: 'code',+ // schema packs+ get_active_schema_pack: 'schema', list_schema_packs: 'schema',+ schema_stats: 'schema', schema_lint: 'schema', schema_graph: 'schema',+ schema_explain_type: 'schema', schema_review_orphans: 'schema',+ schema_apply_mutations: 'schema', reload_schema_pack: 'schema',+ // discovery+ request_tools: 'discovery',+};+for (const op of operations) {+ if (op.area === undefined && OP_AREAS[op.name] !== undefined) {+ op.area = OP_AREAS[op.name];+ }+}+export const operationsByName = Object.fromEntries(operations.map(op => [op.name, op]),) as Record<string, Operation>;diff --git a/src/core/output/post-write.ts b/src/core/output/post-write.tsindex cf6074820b..0493add902 100644--- a/src/core/output/post-write.ts+++ b/src/core/output/post-write.ts@@ -22,13 +22,8 @@ import { dirname } from 'path';import { gbrainPath } from '../config.ts';import type { BrainEngine } from '../engine.ts';-import {- citationValidator,- linkValidator,- backLinkValidator,- tripleHrValidator,-} from './validators/index.ts';-import type { ValidationFinding, PageValidator } from './writer.ts';+import { BUILTIN_VALIDATORS, FIX_HINTS } from './validators/index.ts';+import type { ValidationFinding } from './writer.ts';const getLintLogFile = () => gbrainPath('validator-lint.jsonl');const LINT_CONFIG_KEY = 'writer.lint_on_put_page';@@ -98,7 +93,6 @@ export async function runPostWriteLint(return { ran: false, slug, findings: [], skippedReason: 'validate_false_frontmatter' };}- const validators: PageValidator[] = [citationValidator, linkValidator, backLinkValidator, tripleHrValidator];const ctx = {slug,type: page.type,@@ -111,7 +105,7 @@ export async function runPostWriteLint(};const findings: ValidationFinding[] = [];- for (const v of validators) {+ for (const v of BUILTIN_VALIDATORS) {try {const out = await v.validate(ctx);for (const f of out) findings.push(f);@@ -129,6 +123,92 @@ export async function runPostWriteLint(return { ran: true, slug, findings };}+// ---------------------------------------------------------------------------+// put_page payload plumbing (T11 writer-lint visibility)+// ---------------------------------------------------------------------------++/** top_findings cap: enough to act on, small enough for the wire. */+const TOP_FINDINGS_CAP = 5;+/** Per-finding message cap; validators already truncate embedded content. */+const FINDING_MESSAGE_MAX = 200;++export interface WriterLintFindingSummary {+ validator: string;+ severity: 'error' | 'warning';+ line?: number;+ message: string;+ hint: string;+}++export interface WriterLintSummary {+ error_count: number;+ warning_count: number;+ /** Errors-first, capped at TOP_FINDINGS_CAP, one actionable hint each. */+ top_findings: WriterLintFindingSummary[];+ /** True when findings beyond the cap were dropped from top_findings. */+ details_truncated: boolean;+ /** Finding count per validator id, e.g. { citation: 17, link: 2 }. */+ by_validator: Record<string, number>;+}++/**+ * The put_page `writer_lint` value: a full summary when lint ran, or the+ * crash marker — distinguishable from lint-off, where the key is absent.+ */+export type WriterLintPayload = WriterLintSummary | { status: 'lint_error' };++/**+ * Shape the `writer_lint` response block from the full findings array.+ * Sort is stable, so within a severity findings keep validator order.+ */+export function summarizeWriterLint(findings: ValidationFinding[]): WriterLintSummary {+ const errorsFirst = [...findings].sort((a, b) =>+ a.severity === b.severity ? 0 : a.severity === 'error' ? -1 : 1,+ );+ const byValidator: Record<string, number> = {};+ for (const f of findings) byValidator[f.validator] = (byValidator[f.validator] ?? 0) + 1;+ return {+ error_count: findings.filter(f => f.severity === 'error').length,+ warning_count: findings.filter(f => f.severity === 'warning').length,+ top_findings: errorsFirst.slice(0, TOP_FINDINGS_CAP).map(f => ({+ validator: f.validator,+ severity: f.severity,+ ...(f.line !== undefined ? { line: f.line } : {}),+ message: truncate(f.message, FINDING_MESSAGE_MAX),+ // Registry completeness is test-pinned; the fallback covers a+ // non-builtin validator ever reaching this path.+ hint: FIX_HINTS[f.validator] ?? 'see the validator rule for the fix',+ })),+ details_truncated: findings.length > TOP_FINDINGS_CAP,+ by_validator: byValidator,+ };+}++/**+ * put_page-facing wrapper mapping every lint outcome to the response+ * contract: ran (zero findings included) → full summary; did not run+ * (flag off / validate:false / page missing) → undefined so the+ * writer_lint key stays absent; threw → {status: 'lint_error'} so a lint+ * crash is distinguishable from lint-off. Never throws.+ */+export async function writerLintForPutPage(+ engine: BrainEngine,+ slug: string,+ opts: PostWriteLintOpts = {},+): Promise<WriterLintPayload | undefined> {+ try {+ const lint = await runPostWriteLint(engine, slug, opts);+ if (!lint.ran) return undefined;+ return summarizeWriterLint(lint.findings);+ } catch {+ return { status: 'lint_error' };+ }+}++function truncate(s: string, n: number): string {+ return s.length <= n ? s : s.slice(0, n - 3) + '...';+}+// ---------------------------------------------------------------------------// Loggers// ---------------------------------------------------------------------------diff --git a/src/core/output/validators/index.ts b/src/core/output/validators/index.tsindex f3c7436c13..a36deb2fc3 100644--- a/src/core/output/validators/index.ts+++ b/src/core/output/validators/index.ts@@ -2,7 +2,7 @@* Barrel export + convenience installer for the four built-in validators.*/-import type { BrainWriter } from '../writer.ts';+import type { BrainWriter, PageValidator } from '../writer.ts';import { citationValidator } from './citation.ts';import { linkValidator } from './link.ts';import { backLinkValidator } from './back-link.ts';@@ -10,10 +10,38 @@ import { tripleHrValidator } from './triple-hr.ts';export { citationValidator, linkValidator, backLinkValidator, tripleHrValidator };-/** Register all four built-in validators on a BrainWriter instance. */+/**+ * The single registry of built-in validators. registerBuiltinValidators,+ * runPostWriteLint, and FIX_HINTS all derive from this list — never a+ * parallel hardcoded copy. A validator added here without a matching+ * FIX_HINTS entry fails the completeness pin in+ * test/put-page-writer-lint.test.ts.+ */+export const BUILTIN_VALIDATORS: readonly PageValidator[] = [+ citationValidator,+ linkValidator,+ backLinkValidator,+ tripleHrValidator,+];++/** Register all built-in validators on a BrainWriter instance. */export function registerBuiltinValidators(writer: BrainWriter): void {- writer.register(citationValidator);- writer.register(linkValidator);- writer.register(backLinkValidator);- writer.register(tripleHrValidator);+ for (const v of BUILTIN_VALIDATORS) writer.register(v);}++/**+ * One actionable fix hint per built-in validator, keyed by validator id.+ * Shipped verbatim in put_page's `writer_lint.top_findings` so a consumer+ * can act on a finding without reading validator source. Keys must cover+ * every BUILTIN_VALIDATORS id (pinned by the completeness test).+ */+export const FIX_HINTS: Readonly<Record<string, string>> = {+ [citationValidator.id]:+ 'add a [Source: ...] citation marker (or an inline https:// link) to each factual paragraph, or set frontmatter validate: false to opt this page out',+ [linkValidator.id]:+ 'fix or remove the dangling wikilink — the target page does not exist in this source (check the slug, or create the page first)',+ [backLinkValidator.id]:+ 'informational — the linked page does not link back; runAutoLink reconciles reverse edges on its next put_page, or add the back-link there yourself',+ [tripleHrValidator.id]:+ 'remove the bare "---" line from compiled_truth (it re-splits the page on round-trip); only the triple-HR bar between compiled truth and timeline may use it',+};diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 52b3ac9b67..8d19bc7610 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -825,6 +825,10 @@ export class PGLiteEngine implements BrainEngine {WHERE table_schema='public' AND table_name='oauth_clients' AND column_name='source_id') AS oauth_clients_source_id_exists,EXISTS (SELECT 1 FROM information_schema.columnsWHERE table_schema='public' AND table_name='oauth_clients' AND column_name='federated_read') AS oauth_clients_federated_read_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema='public' AND table_name='oauth_clients' AND column_name='surface') AS oauth_clients_surface_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema='public' AND table_name='oauth_clients' AND column_name='surface_set_by') AS oauth_clients_surface_set_by_exists,EXISTS (SELECT 1 FROM information_schema.tablesWHERE table_schema='public' AND table_name='sources') AS sources_exists,EXISTS (SELECT 1 FROM information_schema.columns@@ -893,6 +897,8 @@ export class PGLiteEngine implements BrainEngine {oauth_clients_exists: boolean;oauth_clients_source_id_exists: boolean;oauth_clients_federated_read_exists: boolean;+ oauth_clients_surface_exists: boolean;+ oauth_clients_surface_set_by_exists: boolean;sources_exists: boolean;sources_archived_exists: boolean;sources_archived_at_exists: boolean;@@ -946,6 +952,13 @@ export class PGLiteEngine implements BrainEngine {// PGLITE_SCHEMA_SQL crash without them.const needsOauthClientsBootstrap = probe.oauth_clients_exists&& (!probe.oauth_clients_source_id_exists || !probe.oauth_clients_federated_read_exists);+ // WP4 (v127): oauth_clients.surface + surface_set_by. No PGLITE_SCHEMA_SQL+ // index references them, but the columns are migration-added AND in the+ // blob's CREATE TABLE — the exact v121 mask class — so the bootstrap adds+ // them defense-in-depth (and satisfies the MIGRATIONS ADD COLUMN+ // coverage gate). They ship in one migration and go missing together.+ const needsOauthClientsSurface = probe.oauth_clients_exists+ && (!probe.oauth_clients_surface_exists || !probe.oauth_clients_surface_set_by_exists);// v0.26.5 (v34): sources.archived + archived_at + archive_expires_at added// for soft-delete lifecycle. Not directly referenced by indexes BUT// PGLITE_SCHEMA_SQL's `CREATE TABLE IF NOT EXISTS sources` is a no-op on@@ -1005,6 +1018,7 @@ export class PGLiteEngine implements BrainEngine {&& !needsMcpLogBootstrap && !needsSubagentProviderId&& !needsPagesRecency && !needsIngestLogSourceId&& !needsFilesBootstrap && !needsOauthClientsBootstrap+ && !needsOauthClientsSurface&& !needsSourcesArchive && !needsPagesLastRetrievedAt&& !needsPagesProvenance&& !needsContextualRetrievalColumns && !needsPagesGeneration@@ -1175,6 +1189,18 @@ export class PGLiteEngine implements BrainEngine {`);}+ if (needsOauthClientsSurface) {+ // WP4 (v127): per-client MCP tool surface + operator-lock marker.+ // Nullable TEXT, no index — bootstrap mirrors the v127 column shape so+ // the blob's CREATE TABLE presence can't mask the forward reference on+ // pre-v127 brains (the v121 wedge class). v127 runs later via+ // runMigrations and is idempotent.+ await this.db.exec(`+ ALTER TABLE oauth_clients ADD COLUMN IF NOT EXISTS surface TEXT;+ ALTER TABLE oauth_clients ADD COLUMN IF NOT EXISTS surface_set_by TEXT;+ `);+ }+if (needsSourcesArchive) {// v34 (destructive_guard_columns) promotes archive lifecycle from JSONB// config to real columns on sources. PGLITE_SCHEMA_SQL'sdiff --git a/src/core/pglite-schema.ts b/src/core/pglite-schema.tsindex 3e782359a5..cbc18c17f5 100644--- a/src/core/pglite-schema.ts+++ b/src/core/pglite-schema.ts@@ -496,6 +496,9 @@ CREATE INDEX IF NOT EXISTS idx_minion_jobs_parent_status ON minion_jobs (parent_WHERE parent_job_id IS NOT NULL;CREATE UNIQUE INDEX IF NOT EXISTS uniq_minion_jobs_idempotency ON minion_jobs (idempotency_key)WHERE idempotency_key IS NOT NULL;+-- WP4/WP5 (v127, ENG-10): wedge-signal index — covers the queue-health count+-- FILTERs and max(updated_at) reads in queryWedgeSignals (supervisor.ts).+CREATE INDEX IF NOT EXISTS idx_minion_jobs_queue_status_updated ON minion_jobs (queue, status, updated_at);-- Inbox table for sidechannel messagingCREATE TABLE IF NOT EXISTS minion_inbox (@@ -899,6 +902,11 @@ CREATE TABLE IF NOT EXISTS oauth_clients (bound_brain_id TEXT NULL,bound_slug_prefixes TEXT[] NULL,bound_max_concurrent INTEGER NOT NULL DEFAULT 1,+ -- WP4 (v127): per-client MCP tool surface + who set it ('operator' |+ -- 'self' | 'dcr_default'). Value space is OPEN (future client tiers write+ -- tier names into surface); NULL = server/config surface resolution.+ surface TEXT NULL,+ surface_set_by TEXT NULL,created_at TIMESTAMPTZ NOT NULL DEFAULT now());-- v0.34.1 (#861, D13 + #876): source_id is the OAuth client's write-sourcediff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 8da46531af..a192b6402b 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -537,6 +537,8 @@ export class PostgresEngine implements BrainEngine {oauth_clients_exists: boolean;oauth_clients_source_id_exists: boolean;oauth_clients_federated_read_exists: boolean;+ oauth_clients_surface_exists: boolean;+ oauth_clients_surface_set_by_exists: boolean;sources_exists: boolean;sources_archived_exists: boolean;sources_archived_at_exists: boolean;@@ -591,6 +593,10 @@ export class PostgresEngine implements BrainEngine {WHERE table_schema = current_schema() AND table_name = 'oauth_clients' AND column_name = 'source_id') AS oauth_clients_source_id_exists,EXISTS (SELECT 1 FROM information_schema.columnsWHERE table_schema = current_schema() AND table_name = 'oauth_clients' AND column_name = 'federated_read') AS oauth_clients_federated_read_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'oauth_clients' AND column_name = 'surface') AS oauth_clients_surface_exists,+ EXISTS (SELECT 1 FROM information_schema.columns+ WHERE table_schema = current_schema() AND table_name = 'oauth_clients' AND column_name = 'surface_set_by') AS oauth_clients_surface_set_by_exists,EXISTS (SELECT 1 FROM information_schema.tablesWHERE table_schema = current_schema() AND table_name = 'sources') AS sources_exists,EXISTS (SELECT 1 FROM information_schema.columns@@ -671,6 +677,17 @@ export class PostgresEngine implements BrainEngine {// SCHEMA_SQL crash without them.const needsOauthClientsBootstrap = probe.oauth_clients_exists&& (!probe.oauth_clients_source_id_exists || !probe.oauth_clients_federated_read_exists);+ // WP4 (v127): oauth_clients.surface + surface_set_by. No SCHEMA_SQL index+ // references them, but the columns are migration-added AND in the blob's+ // CREATE TABLE — the exact v121 mask class — so the bootstrap adds them+ // defense-in-depth (and satisfies the MIGRATIONS ADD COLUMN coverage+ // gate). They ship in one migration and go missing together.+ const probeSurface = probe as {+ oauth_clients_surface_exists?: boolean;+ oauth_clients_surface_set_by_exists?: boolean;+ };+ const needsOauthClientsSurface = probe.oauth_clients_exists+ && (!probeSurface.oauth_clients_surface_exists || !probeSurface.oauth_clients_surface_set_by_exists);// v0.26.5 (v34): sources.archived + archived_at + archive_expires_at added// for soft-delete lifecycle. SCHEMA_SQL's `CREATE TABLE IF NOT EXISTS sources`// is a no-op on pre-existing sources tables (won't add columns), so the@@ -749,7 +766,8 @@ export class PostgresEngine implements BrainEngine {&& !needsPagesDeletedAt && !needsMcpLogBootstrap && !needsSubagentProviderId&& !needsChunksEmbeddingImage && !needsPagesRecency&& !needsIngestLogSourceId && !needsFilesBootstrap- && !needsOauthClientsBootstrap && !needsSourcesArchive+ && !needsOauthClientsBootstrap && !needsOauthClientsSurface+ && !needsSourcesArchive&& !needsPagesLastRetrievedAt&& !needsPagesProvenance&& !needsContextualRetrievalColumns && !needsPagesGeneration@@ -920,6 +938,18 @@ export class PostgresEngine implements BrainEngine {`);}+ if (needsOauthClientsSurface) {+ // WP4 (v127): per-client MCP tool surface + operator-lock marker.+ // Nullable TEXT, no index — bootstrap mirrors the v127 column shape so+ // the blob's CREATE TABLE presence can't mask the forward reference on+ // pre-v127 brains (the v121 wedge class). v127 runs later via+ // runMigrations and is idempotent. Mirror of the PGLite bootstrap.+ await conn.unsafe(`+ ALTER TABLE oauth_clients ADD COLUMN IF NOT EXISTS surface TEXT;+ ALTER TABLE oauth_clients ADD COLUMN IF NOT EXISTS surface_set_by TEXT;+ `);+ }+if (needsSourcesArchive) {// v34 (destructive_guard_columns) promotes archive lifecycle from JSONB// config to real columns on sources. SCHEMA_SQL's `CREATE TABLE IF NOT EXISTSdiff --git a/src/core/schema-embedded.ts b/src/core/schema-embedded.tsindex 57a0c49b71..220f2216b7 100644--- a/src/core/schema-embedded.ts+++ b/src/core/schema-embedded.ts@@ -664,6 +664,11 @@ CREATE TABLE IF NOT EXISTS oauth_clients (bound_brain_id TEXT NULL,bound_slug_prefixes TEXT[] NULL,bound_max_concurrent INTEGER NOT NULL DEFAULT 1,+ -- WP4 (v127): per-client MCP tool surface + who set it ('operator' |+ -- 'self' | 'dcr_default'). Value space is OPEN (future client tiers write+ -- tier names into surface); NULL = server/config surface resolution.+ surface TEXT NULL,+ surface_set_by TEXT NULL,created_at TIMESTAMPTZ NOT NULL DEFAULT now());-- v0.34.1 (#861, D13 + #876): source_id is the write-source scope;@@ -766,7 +771,7 @@ CREATE INDEX IF NOT EXISTS context_volunteer_events_src_slug_idxON context_volunteer_events (source_id, slug);-- session_context_state (v0.45.7 / migration v126 — ambient recall issue #1):--- per-session cursor + surfaced-slug dedup for the \`delta\` verb + heartbeat+-- per-session cursor + boundary-tie dedup for the \`delta\` verb + heartbeat-- runtime. Key (source_id, client_id, session_id); client_id 'local' sentinel-- for CLI/hook, remote auth client id otherwise. jsonb DDL-literal defaults.CREATE TABLE IF NOT EXISTS session_context_state (@@ -948,6 +953,9 @@ CREATE INDEX IF NOT EXISTS idx_minion_jobs_parent ON minion_jobs(parent_job_id);CREATE INDEX IF NOT EXISTS idx_minion_jobs_timeout ON minion_jobs (timeout_at) WHERE status = 'active' AND timeout_at IS NOT NULL;CREATE INDEX IF NOT EXISTS idx_minion_jobs_parent_status ON minion_jobs (parent_job_id, status) WHERE parent_job_id IS NOT NULL;CREATE UNIQUE INDEX IF NOT EXISTS uniq_minion_jobs_idempotency ON minion_jobs (idempotency_key) WHERE idempotency_key IS NOT NULL;+-- WP4/WP5 (v127, ENG-10): wedge-signal index — covers the queue-health count+-- FILTERs and max(updated_at) reads in queryWedgeSignals (supervisor.ts).+CREATE INDEX IF NOT EXISTS idx_minion_jobs_queue_status_updated ON minion_jobs (queue, status, updated_at);-- Inbox table for sidechannel messagingCREATE TABLE IF NOT EXISTS minion_inbox (diff --git a/src/core/search/hybrid.ts b/src/core/search/hybrid.tsindex b386c332e6..a77d8f6e21 100644--- a/src/core/search/hybrid.ts+++ b/src/core/search/hybrid.ts@@ -11,7 +11,14 @@import type { BrainEngine } from '../engine.ts';import { MAX_SEARCH_LIMIT, clampSearchLimit } from '../engine.ts';-import type { SearchResult, SearchOpts, HybridSearchMeta } from '../types.ts';+import type {+ SearchResult,+ SearchOpts,+ HybridSearchMeta,+ DegradedStage,+ DegradedStageEntry,+ DegradedReason,+} from '../types.ts';import { embed, embedQuery } from '../embedding.ts';import { registerBackgroundWorkDrainer } from '../background-work.ts';import { resolveEmbeddingColumn, isCacheSafe } from './embedding-column.ts';@@ -33,7 +40,7 @@ import { isTitlePhraseMatch } from './title-match.ts';import { normalizeAlias } from './alias-normalize.ts';import { stampEvidence } from './evidence.ts';import { expandAnchors, hydrateChunks } from './two-pass.ts';-import { enforceTokenBudget } from './token-budget.ts';+import { enforceTokenBudget, searchSalvageEnabled, type TokenBudgetMeta } from './token-budget.ts';import { warnOncePerProcess } from '../utils.ts';import { recordSearchTelemetry } from './telemetry.ts';import {@@ -922,6 +929,41 @@ export function resolveDateBoundary();}+/**+ * WP2/T3 — classify an embed/vector failure as a timeout vs a provider+ * error for the enumerated degraded[] reason codes (D6). Matches both the+ * embedQueryBounded deadline rejection and AbortSignal.timeout's+ * TimeoutError/AbortError. The raw error text never rides the wire — it+ * goes to stderr via warnOncePerProcess only.+ */+function isTimeoutError(err: unknown): boolean {+ if (!(err instanceof Error)) return false;+ if (/deadline \d+ms exceeded/.test(err.message)) return true;+ return err.name === 'TimeoutError' || err.name === 'AbortError';+}++/** WP2/T3 — append a degraded stage once (stages are set-like per response). */+function pushDegraded(+ list: DegradedStageEntry[],+ stage: DegradedStage,+ reason?: DegradedReason,+): void {+ if (list.some((d) => d.stage === stage)) return;+ list.push(reason ? { stage, reason } : { stage });+}++/**+ * WP2/T3 — budget-stage stamp shared by the enforceTokenBudget call sites.+ * Two distinct stages so consumers can tell "empty" from "clipped":+ * budget_truncated when the minKeep failsafe kept one truncated copy+ * (results non-empty); budget_dropped_all when the strict packer returned+ * [] (kept 0 with drops, under GBRAIN_SEARCH_SALVAGE=off).+ */+function stampBudgetStage(list: DegradedStageEntry[], meta: TokenBudgetMeta): void {+ if (meta.truncated) pushDegraded(list, 'budget_truncated', 'first_result_truncated');+ else if (meta.kept === 0 && meta.dropped > 0) pushDegraded(list, 'budget_dropped_all');+}+export async function hybridSearch(engine: BrainEngine,query: string,@@ -1045,6 +1087,10 @@ export async function hybridSearch(// surfaced. Capture wrapper passes a closure to receive the meta and// threads it into the eval_candidates row.let expansionApplied = false;+ // WP2/T3 — degradation stamp accumulated across stages. Emitted on EVERY+ // return path (empty array = clean run) so cache rows always carry the+ // stamp and a served row can prove its cleanliness (ENG-5/cache_prestamp).+ const degraded: DegradedStageEntry[] = [];// A throwing user callback must never break the search hot path — onMeta// is a public surface (gbrain/search/hybrid) so a third-party closure bug@@ -1252,6 +1298,14 @@ export async function hybridSearch(await stampContentFlags(engine, noEmbedBudgeted);lastResultsCount = noEmbedBudgeted.length;lastRank1Score = noEmbedBudgeted[0] ? (noEmbedBudgeted[0].base_score ?? noEmbedBudgeted[0].score) : undefined;+ // WP2/T3 — no silent bypass: the keyword-only-config branch names why+ // vector didn't run, and whether the keyword arm itself came up empty+ // (skipped-by-modality is not a keyword miss, hence the image gate).+ pushDegraded(degraded, 'embed_unavailable', 'no_provider');+ if (keywordResults.length === 0 && earlyModality !== 'image') {+ pushDegraded(degraded, 'keyword_zero');+ }+ stampBudgetStage(degraded, noEmbedBudgetMeta);emitMeta({vector_enabled: false,detail_resolved: detailResolved,@@ -1259,6 +1313,8 @@ export async function hybridSearch(intent: suggestions.intent,mode: resolvedMode.resolved_mode,embedding_column: resolvedCol.name,+ degraded: [...degraded],+ retrieved_count: noEmbedSliced.length,...(resolvedMode.tokenBudget && resolvedMode.tokenBudget > 0? { token_budget: noEmbedBudgetMeta }: {}),@@ -1327,8 +1383,10 @@ export async function hybridSearch(if (queries.length === 0) queries = [query];// "Applied" = produced variants beyond the original, not just called.expansionApplied = queries.length > 1;- } catch {- // Expansion failure is non-fatal+ } catch (err) {+ // Expansion failure is non-fatal — original query proceeds alone,+ // stamped so the consumer knows the multi-query recall arm was lost.+ pushDegraded(degraded, 'expansion_failed', isTimeoutError(err) ? 'timeout' : 'provider_error');}}@@ -1383,6 +1441,8 @@ export async function hybridSearch(`[cross-modal] unified_multimodal embed failed; falling back to dual-column path. reason=${reason}`,);crossModalFellOpen = true;+ // WP2/T3 — the configured unified arm fell over; dual-column carried it.+ pushDegraded(degraded, 'vector_arm_failed', isTimeoutError(err) ? 'timeout' : 'provider_error');}}@@ -1414,6 +1474,9 @@ export async function hybridSearch(`[cross-modal] image-side embed failed for modality=${effectiveModality}; falling back to text-only. reason=${reason}`,);crossModalFellOpen = true;+ // WP2/T3 — the image-search branch is no silent bypass: the fell-open+ // arm is named in the meta the surviving text path emits.+ pushDegraded(degraded, 'vector_arm_failed', isTimeoutError(err) ? 'timeout' : 'provider_error');}}@@ -1431,32 +1494,114 @@ export async function hybridSearch(// the global default. Empty embeddingModel falls back to gateway// default — preserves pre-v0.36 behavior for the builtin 'embedding'// column.- try {- const embedOpts = resolvedCol.embeddingModel- ? { embeddingModel: resolvedCol.embeddingModel, dimensions: resolvedCol.dimensions }- : undefined;- // v0.42.20.0 (Fix 3) — bound the query embed. Reuse the shared deadline- // threaded from hybridSearchCached (so the cache-lookup embed + this one- // share one ~6s budget); direct callers get a fresh deadline. On timeout- // the embed throws → the catch below falls back to keyword-only.- const embedDl = opts?._queryEmbedDeadline ?? makeQueryEmbedDeadline();- const embeddings = await Promise.all(queries.map(q => embedQueryBounded(q, embedOpts, embedDl)));- queryEmbedding = embeddings[0];- const textLists = await Promise.all(- embeddings.map(emb => engine.searchVector(emb, searchOpts)),- );- for (const list of textLists) {- for (const r of list) {- r.modality = r.modality ?? 'text';+ const embedOpts = resolvedCol.embeddingModel+ ? { embeddingModel: resolvedCol.embeddingModel, dimensions: resolvedCol.dimensions }+ : undefined;+ // v0.42.20.0 (Fix 3) — bound the query embed. Reuse the shared deadline+ // threaded from hybridSearchCached (so the cache-lookup embed + this one+ // share one ~6s budget); direct callers get a fresh deadline. On timeout+ // the embed rejects → salvage below (or keyword-only when all reject).+ const embedDl = opts?._queryEmbedDeadline ?? makeQueryEmbedDeadline();+ if (!searchSalvageEnabled()) {+ // ENG-7 kill switch (GBRAIN_SEARCH_SALVAGE=off): pre-wave+ // all-or-nothing fan-outs — one variant's failure abandons every+ // embedding and falls back to keyword-only.+ try {+ const embeddings = await Promise.all(queries.map(q => embedQueryBounded(q, embedOpts, embedDl)));+ queryEmbedding = embeddings[0];+ const textLists = await Promise.all(+ embeddings.map(emb => engine.searchVector(emb, searchOpts)),+ );+ for (const list of textLists) {+ for (const r of list) {+ r.modality = r.modality ?? 'text';+ }}+ vectorLists = textLists;+ // 'both' mode: also include the image-side list as another input to RRF.+ if (effectiveModality === 'both' && imageVectorList !== null) {+ vectorLists = [...vectorLists, imageVectorList];+ }+ } catch (err) {+ // Embedding failure is non-fatal, fall back to keyword-only —+ // stamped with an enumerated code; raw text to stderr only (D6).+ const timedOut = isTimeoutError(err);+ pushDegraded(degraded, timedOut ? 'embed_timeout' : 'embed_unavailable', timedOut ? 'timeout' : 'provider_error');+ warnOncePerProcess(+ 'search-embed-fanout-failed',+ `[gbrain] query embed/vector fan-out failed (keyword fallback): ` ++ `${err instanceof Error ? err.message : String(err)}`,+ );}- vectorLists = textLists;- // 'both' mode: also include the image-side list as another input to RRF.- if (effectiveModality === 'both' && imageVectorList !== null) {- vectorLists = [...vectorLists, imageVectorList];+ } else {+ // WP2/T3 (ENG-15) salvage fan-outs: allSettled on BOTH the embed+ // fan-out and the searchVector fan-out so one variant's failure no+ // longer abandons the survivors (the query-vs-search asymmetry fix).+ const settled = await Promise.allSettled(queries.map(q => embedQueryBounded(q, embedOpts, embedDl)));+ const okEmbeds: Float32Array[] = [];+ const embedFailures: unknown[] = [];+ for (const s of settled) {+ if (s.status === 'fulfilled') okEmbeds.push(s.value);+ else embedFailures.push(s.reason);+ }+ if (embedFailures.length > 0) {+ warnOncePerProcess(+ 'search-embed-fanout-failed',+ `[gbrain] ${embedFailures.length}/${settled.length} query embeds failed (salvaging survivors): ` ++ `${embedFailures[0] instanceof Error ? (embedFailures[0] as Error).message : String(embedFailures[0])}`,+ );+ }+ if (okEmbeds.length === 0) {+ // Every embed failed → keyword-only fallback below, honestly staged.+ const allTimeouts = embedFailures.every(isTimeoutError);+ pushDegraded(degraded, allTimeouts ? 'embed_timeout' : 'embed_unavailable', allTimeouts ? 'timeout' : 'provider_error');+ } else {+ const originalOk = settled[0].status === 'fulfilled';+ if (embedFailures.length > 0) {+ // Mixed outcome — only reachable when expansion produced variants.+ pushDegraded(degraded, 'expansion_partial', originalOk ? 'variant_embed_failed' : 'original_embed_failed');+ }+ if (originalOk) {+ queryEmbedding = (settled[0] as PromiseFulfilledResult<Float32Array>).value;+ } else {+ // Registry refinement: variant lists are salvaged, but the cosine+ // re-score needs the ORIGINAL query's vector — skip it rather than+ // re-score in a variant's embedding space.+ queryEmbedding = null;+ pushDegraded(degraded, 'rescore_skipped', 'original_embed_failed');+ }+ const vSettled = await Promise.allSettled(okEmbeds.map(emb => engine.searchVector(emb, searchOpts)));+ const okLists: SearchResult[][] = [];+ let vFirstErr: unknown;+ let vFailed = 0;+ for (const s of vSettled) {+ if (s.status === 'fulfilled') okLists.push(s.value);+ else {+ if (vFailed === 0) vFirstErr = s.reason;+ vFailed += 1;+ }+ }+ if (vFailed > 0) {+ pushDegraded(degraded, 'vector_arm_failed', isTimeoutError(vFirstErr) ? 'timeout' : 'provider_error');+ warnOncePerProcess(+ 'search-vector-arm-failed',+ `[gbrain] ${vFailed}/${vSettled.length} searchVector arms failed (salvaging survivors): ` ++ `${vFirstErr instanceof Error ? vFirstErr.message : String(vFirstErr)}`,+ );+ }+ for (const list of okLists) {+ for (const r of list) {+ r.modality = r.modality ?? 'text';+ }+ }+ vectorLists = okLists;+ // 'both' mode: also include the image-side list as another input to+ // RRF — only when a text arm survived, matching the pre-wave shape+ // (a total text failure falls back to keyword-only either way).+ if (vectorLists.length > 0 && effectiveModality === 'both' && imageVectorList !== null) {+ vectorLists = [...vectorLists, imageVectorList];+ }}- } catch {- // Embedding failure is non-fatal, fall back to keyword-only}}@@ -1494,6 +1639,13 @@ export async function hybridSearch(await stampContentFlags(engine, kwBudgeted);lastResultsCount = kwBudgeted.length;lastRank1Score = kwBudgeted[0] ? (kwBudgeted[0].base_score ?? kwBudgeted[0].score) : undefined;+ // WP2/T3 — the embed/vector failure that emptied vectorLists already+ // pushed its stage above; add the keyword-arm outcome (skipped-by-+ // modality is not a keyword miss, hence the image gate).+ if (keywordResults.length === 0 && earlyModality !== 'image') {+ pushDegraded(degraded, 'keyword_zero');+ }+ stampBudgetStage(degraded, kwBudgetMeta);emitMeta({vector_enabled: false,detail_resolved: detailResolved,@@ -1501,6 +1653,8 @@ export async function hybridSearch(intent: suggestions.intent,mode: resolvedMode.resolved_mode,embedding_column: resolvedCol.name,+ degraded: [...degraded],+ retrieved_count: kwSliced.length,...(resolvedMode.tokenBudget && resolvedMode.tokenBudget > 0? { token_budget: kwBudgetMeta }: {}),@@ -1733,6 +1887,7 @@ export async function hybridSearch(await stampContentFlags(engine, budgeted);lastResultsCount = budgeted.length;lastRank1Score = budgeted[0] ? (budgeted[0].base_score ?? budgeted[0].score) : undefined;+ stampBudgetStage(degraded, budgetMeta);emitMeta({vector_enabled: true,detail_resolved: detailResolved,@@ -1740,6 +1895,8 @@ export async function hybridSearch(intent: suggestions.intent,mode: resolvedMode.resolved_mode,embedding_column: resolvedCol.name,+ degraded: [...degraded],+ retrieved_count: sliced.length,...(resolvedMode.tokenBudget && resolvedMode.tokenBudget > 0? { token_budget: budgetMeta }: {}),@@ -1943,24 +2100,31 @@ export async function hybridSearchCached(// Budget enforcement — same pipeline tail as fresh path.const { results: budgeted, meta: budgetMeta } = enforceTokenBudget(sliced, opts?.tokenBudget);- // Emit meta describing the cache path.+ // Emit meta describing the cache path. WP2/T3 (ENG-5): spread-carry+ // the STORED meta so every key the bare hybridSearch emitted at write+ // time (intent, mode, embedding_column, adaptive_return, autocut,+ // degraded, token_budget, future additions) survives the hit without+ // a hand-copied rebuild — the class of drop Codex P2 caught for+ // adaptive_return can't recur. Explicit fields BELOW the spread are+ // the hit-time overrides.const cachedMeta: HybridSearchMeta = {+ ...(hit.meta ?? {}),vector_enabled: hit.meta?.vector_enabled ?? true,detail_resolved: hit.meta?.detail_resolved ?? null,expansion_applied: hit.meta?.expansion_applied ?? false,- intent: hit.meta?.intent,+ // A row stored before the degradation stamp existed (no `degraded`+ // key, not even []) can't prove it was a clean run — surface that+ // honestly instead of claiming clean (cache_prestamp). Post-bump+ // rows always carry the stamp (knobsHash v-bump makes pre-stamp+ // rows unreachable in production; this is the belt-and-braces).+ degraded: hit.meta?.degraded ?? [{ stage: 'cache_prestamp' }],+ // Pre-budget count for THIS response's page (offset/limit applied).+ retrieved_count: sliced.length,cache: {status: 'hit',similarity: cacheSimilarity,age_seconds: cacheAge,},- // Carry the trimmed-set decision fields from the cached row so cache- // HITS report the same autocut/adaptive/mode/column meta as a fresh- // run (Codex P2 — the cached result set was already trimmed).- ...(hit.meta?.mode ? { mode: hit.meta.mode } : {}),- ...(hit.meta?.embedding_column ? { embedding_column: hit.meta.embedding_column } : {}),- ...(hit.meta?.adaptive_return ? { adaptive_return: hit.meta.adaptive_return } : {}),- ...(hit.meta?.autocut ? { autocut: hit.meta.autocut } : {}),// Per-call budget: prefer the STORED budget record, which carries// the true dropped count from the write-time cut — the// re-application above ran on an already-cut set and reads@@ -2024,21 +2188,22 @@ export async function hybridSearchCached(// Token budget pass (no-op when not set).const { results: budgeted, meta: budgetMeta } = enforceTokenBudget(results, opts?.tokenBudget);- // Compose the final meta and emit. v0.42.3.0 (Codex #5): carry over the- // inner meta's decision fields — pre-fix this manual rebuild silently dropped- // adaptive_return (and would drop autocut), so cached writeback/hit paths and- // eval-capture under-reported the feature. Propagate mode + embedding_column- // too (same drop class).+ // Compose the final meta and emit. v0.42.3.0 (Codex #5) + WP2/T3 (ENG-5):+ // spread-carry the inner meta so every field the bare hybridSearch emitted+ // (intent, mode, embedding_column, adaptive_return, autocut, degraded,+ // retrieved_count, token_budget, future additions) survives the wrapper —+ // the manual-rebuild drop class (adaptive_return, Codex #5) can't recur.+ // Explicit fields below the spread are the wrapper's own overrides.const finalMeta: HybridSearchMeta = {+ ...(innerMeta ?? {}),vector_enabled: innerMeta?.vector_enabled ?? false,detail_resolved: innerMeta?.detail_resolved ?? null,expansion_applied: innerMeta?.expansion_applied ?? false,- intent: innerMeta?.intent,+ // Always stamp: a stored row must be able to prove it was clean+ // (cache_prestamp posture on the hit path above).+ degraded: innerMeta?.degraded ?? [],+ retrieved_count: innerMeta?.retrieved_count ?? results.length,cache: { status: cacheStatus },- ...(innerMeta?.mode ? { mode: innerMeta.mode } : {}),- ...(innerMeta?.embedding_column ? { embedding_column: innerMeta.embedding_column } : {}),- ...(innerMeta?.adaptive_return ? { adaptive_return: innerMeta.adaptive_return } : {}),- ...(innerMeta?.autocut ? { autocut: innerMeta.autocut } : {}),// Per-call budget: prefer the INNER meta's budget record. The inner// hybridSearch already enforced the same resolved budget (per-call wins// in resolveSearchMode), so the re-application above sees an@@ -2058,15 +2223,28 @@ export async function hybridSearchCached(// Best-effort writeback (skip when search returned empty so we don't// cache zero-result queries forever — they often indicate a typo).+ //+ // WP2/T3 (D14.2 revised per ENG-6): a DEGRADED result set is still cached+ // — full exclusion would amplify load exactly when a provider is limping —+ // but only for a short TTL (~60s) and stamped with its degradation, so a+ // salvaged set is never served as clean for the full TTL. Only embeddable+ // degradations reach this write: a total embed outage has no+ // queryEmbedding (store() no-ops on null) and vector_enabled=false, so it+ // is uncacheable by construction.if (cacheStatus === 'miss' &&queryEmbedding &&results.length > 0 &&(innerMeta?.vector_enabled ?? false)) {+ const isDegraded = (finalMeta.degraded?.length ?? 0) > 0;trackCacheWrite(cache- .store(query, queryEmbedding, results, finalMeta, { sourceId: cacheScopeKey(opts), knobsHash: cacheKnobsHash })+ .store(query, queryEmbedding, results, finalMeta, {+ sourceId: cacheScopeKey(opts),+ knobsHash: cacheKnobsHash,+ ...(isDegraded ? { ttlSeconds: DEGRADED_CACHE_TTL_SECONDS } : {}),+ }).catch(() => { /* swallow */ }),);}@@ -2074,6 +2252,14 @@ export async function hybridSearchCached(return budgeted;}+/**+ * WP2/T3 (D14.2) — TTL for cache rows written from a degraded run. Long+ * enough to absorb a burst against a limping provider, short enough that a+ * salvaged (partial) result set can't shadow the recovered pipeline for the+ * normal cache TTL.+ */+export const DEGRADED_CACHE_TTL_SECONDS = 60;+/*** RRF/dedup identity for a result row, at chunk granularity.*diff --git a/src/core/search/mode.ts b/src/core/search/mode.tsindex 37ea29e00e..c74307479c 100644--- a/src/core/search/mode.ts+++ b/src/core/search/mode.ts@@ -790,7 +790,17 @@ export function attributeKnob<K extends keyof ModeBundle>(// `fts=` fold (#3677), so this lands as v=16 per the D8 sequencing// convention (see the v=4/v=5 note above). Same one-time global cold-miss// pattern as the bumps above.-export const KNOBS_HASH_VERSION = 16;+//+// bump 16→17 (WP2/T3): degradation-stamp epoch. HybridSearchMeta gains+// `degraded[]` + `retrieved_count` and every cache write now stamps them+// (degraded rows additionally get a short TTL). A pre-stamp row served as a+// hit would claim a clean run it can't prove; bumping makes pre-upgrade rows+// unreachable (one-time cold-miss, refills within cache.ttl_seconds), and+// any row that still lacks the stamp surfaces as+// degraded:[{stage:'cache_prestamp'}] at hit time (belt-and-braces).+// (Merge note: both this wave and master's #3515 wave claimed v=16 in+// flight; the merge sequences them as 16 then 17.)+export const KNOBS_HASH_VERSION = 17;/*** v0.36 (D8 / CDX-2) — second-arg context for the cache key. Thediff --git a/src/core/search/query-cache.ts b/src/core/search/query-cache.tsindex 6d05582644..bef0095619 100644--- a/src/core/search/query-cache.ts+++ b/src/core/search/query-cache.ts@@ -199,6 +199,13 @@ export class SemanticQueryCache {* Persist a fresh search result set into the cache. Idempotent on* (query_text + source_id) \u2014 re-writes the row with a fresh* created_at. Best-effort: errors are swallowed.+ *+ * WP2/T3: the null-embedding no-op below is load-bearing for ENG-6 \u2014+ * a total embed outage produces no cache-lookup embedding, so degraded+ * keyword-only result sets are uncacheable by construction. Degraded+ * sets that DO have an embedding are written by hybridSearchCached with+ * `ttlSeconds: DEGRADED_CACHE_TTL_SECONDS` and a `meta.degraded` stamp+ * (D14.2), so a salvaged set never serves as clean for the full TTL.*/async store(queryText: string,diff --git a/src/core/search/telemetry.ts b/src/core/search/telemetry.tsindex 180fe16710..531c1fe04d 100644--- a/src/core/search/telemetry.ts+++ b/src/core/search/telemetry.ts@@ -60,6 +60,36 @@ interface Bucket {const RANK1_SOLID_FLOOR = 0.6;const RANK1_HIGH_FLOOR = 0.85;+/**+ * WP2/T3 — reserved `mode` value for the empty-result cause rollup. Rides+ * the existing (date, mode, intent) PK with ZERO new DDL: rows keyed+ * (date, 'empty_result', <cause>) count empty responses by cause, and+ * readSearchStats diverts them out of the call/intent/mode aggregates.+ * Never collides with real modes ('conservative'|'balanced'|'tokenmax'|+ * 'unset'). Bounded growth: 3 causes × 365 days ≈ 1.1k rows/year.+ */+export const EMPTY_RESULT_MODE = 'empty_result';++export type EmptyResultCause = 'vector_disabled' | 'budget_dropped_all' | 'keyword_zero';++/**+ * WP2/T3 — why did this search return zero results? Precedence: a budget+ * that dropped everything (only reachable with GBRAIN_SEARCH_SALVAGE=off;+ * the minKeep failsafe otherwise returns 1) beats vector-unavailability+ * beats "healthy pipeline, keyword found nothing".+ */+export function classifyEmptyResultCause(meta: HybridSearchMeta): EmptyResultCause {+ const tb = meta.token_budget;+ if (+ (tb && tb.kept === 0 && tb.dropped > 0) ||+ meta.degraded?.some((d) => d.stage === 'budget_dropped_all')+ ) {+ return 'budget_dropped_all';+ }+ if (!meta.vector_enabled) return 'vector_disabled';+ return 'keyword_zero';+}+const FLUSH_INTERVAL_MS = 60_000;const FLUSH_THRESHOLD_CALLS = 100;@@ -136,12 +166,48 @@ class TelemetryWriter {else b.rank1_high += 1;}+ // WP2/T3 — empty-result cause rollup. Cache HITS are excluded: an empty+ // hit slice is an offset-past-end artifact, not a retrieval failure.+ if (opts.results_count === 0 && meta.cache?.status !== 'hit') {+ this.recordEmptyResult(date, classifyEmptyResultCause(meta));+ }+this.pendingCount += 1;if (this.pendingCount >= FLUSH_THRESHOLD_CALLS) {void this.flush().catch(() => { /* swallow */ });}}+ /**+ * Bump the reserved (date, EMPTY_RESULT_MODE, cause) bucket. Only `count`+ * carries signal on these rows — every other column stays 0 and the flush+ * SQL is unchanged (zero new DDL).+ */+ private recordEmptyResult(date: string, cause: EmptyResultCause): void {+ const key = `${date}::${EMPTY_RESULT_MODE}::${cause}`;+ let b = this.buckets.get(key);+ if (!b) {+ b = {+ date,+ mode: EMPTY_RESULT_MODE,+ intent: cause,+ count: 0,+ sum_results: 0,+ sum_tokens: 0,+ sum_budget_dropped: 0,+ cache_hit: 0,+ cache_miss: 0,+ sum_rank1_score: 0,+ count_rank1: 0,+ rank1_lt_solid: 0,+ rank1_solid: 0,+ rank1_high: 0,+ };+ this.buckets.set(key, b);+ }+ b.count += 1;+ }+/*** Drain the bucket map to the database. Idempotent; concurrent flushes* are coalesced via flushInFlight — a caller arriving mid-flush awaits the@@ -315,6 +381,11 @@ export interface StatsWindow {avg_rank1_score: number | null; // null when no rank-1 samplesrank1_count: number;rank1_distribution: { lt_solid: number; solid: number; high: number };+ // WP2/T3 — empty-result responses by cause (vector_disabled /+ // budget_dropped_all / keyword_zero). Diverted from the reserved+ // EMPTY_RESULT_MODE rows; never counted in total_calls or the+ // intent/mode distributions.+ empty_results: { total: number; by_cause: Record<string, number> };}export async function readSearchStats(@@ -377,8 +448,17 @@ export async function readSearchStats(let r1_lt = 0;let r1_solid = 0;let r1_high = 0;+ let empty_total = 0;+ const empty_by_cause: Record<string, number> = {};for (const r of rows) {+ // WP2/T3 — reserved empty-result rows carry cause in the intent slot;+ // divert them so they never skew calls/averages/distributions.+ if (r.mode === EMPTY_RESULT_MODE) {+ empty_total += r.count;+ empty_by_cause[r.intent] = (empty_by_cause[r.intent] ?? 0) + r.count;+ continue;+ }total_calls += r.count;cache_hits += r.cache_hit;cache_misses += r.cache_miss;@@ -413,6 +493,7 @@ export async function readSearchStats(avg_rank1_score: count_rank1 > 0 ? sum_rank1 / count_rank1 : null,rank1_count: count_rank1,rank1_distribution: { lt_solid: r1_lt, solid: r1_solid, high: r1_high },+ empty_results: { total: empty_total, by_cause: empty_by_cause },};} catch {// Table missing or query failed — return empty stats rather than throw.@@ -430,6 +511,7 @@ export async function readSearchStats(avg_rank1_score: null,rank1_count: 0,rank1_distribution: { lt_solid: 0, solid: 0, high: 0 },+ empty_results: { total: 0, by_cause: {} },};}}diff --git a/src/core/search/token-budget.ts b/src/core/search/token-budget.tsindex 85af26f3b0..430582aa68 100644--- a/src/core/search/token-budget.ts+++ b/src/core/search/token-budget.ts@@ -21,7 +21,8 @@* enforcer is a no-op. The pre-v0.32 contract for search results is* unchanged.*- * Pure module. No DB, no LLM, no async. Tested in test/token-budget.test.ts.+ * Pure module. No DB, no LLM, no async; the only ambient input is the+ * GBRAIN_SEARCH_SALVAGE env kill switch. Tested in test/token-budget.test.ts.*/import type { SearchResult } from '../types.ts';@@ -60,6 +61,24 @@ export interface TokenBudgetMeta {dropped: number;/** Count of results actually returned. */kept: number;+ /**+ * WP2/T3 (ENG-2/FOV-2) — set when the minKeep failsafe kept ONE result+ * whose chunk_text was truncated (on a copy) to fit the budget. Only the+ * search wrapper (`enforceTokenBudget`) produces this; `packToBudget`+ * stays strict for the frozen verb consumers.+ */+ truncated?: boolean;+}++/**+ * WP2/T3 (ENG-7) — env-only kill switch for the fail-loud salvage behavior+ * (allSettled embed/vector fan-outs in hybrid.ts + the minKeep:1 budget+ * failsafe below). `GBRAIN_SEARCH_SALVAGE=off` restores the pre-wave+ * all-or-nothing embeds and the strict budget wrapper. Env-above-config on+ * purpose (incident escape hatch, pace-mode precedent); no config surface.+ */+export function searchSalvageEnabled(): boolean {+ return process.env.GBRAIN_SEARCH_SALVAGE !== 'off';}/**@@ -71,7 +90,10 @@ export interface TokenBudgetMeta {* Edge cases (all preserve the pre-v0.32 contract):* - budget undefined / <= 0: returns input unchanged; dropped=0, kept=N.* - First item alone exceeds budget: returns []; dropped=N, kept=0.- * (Intentionally strict: the caller asked for a hard cap.)+ * (Intentionally strict: the caller asked for a hard cap. FROZEN for+ * the memory-verb consumers — recall/entity/context_pack budget-pack+ * through this; the search wrapper enforceTokenBudget layers its+ * minKeep failsafe on top, never here.)* - Input empty: returns []; budget unused.*/export function packToBudget<T>(@@ -115,14 +137,44 @@ export function packToBudget<T>(/*** Search-pipeline budget enforcement — a thin wrapper over packToBudget- * with the SearchResult cost model (title + chunk_text). Behavior is- * byte-identical to the pre-refactor implementation; pinned by+ * with the SearchResult cost model (title + chunk_text). Pinned by* test/token-budget.test.ts.+ *+ * WP2/T3 (ENG-2/FOV-2) minKeep:1 failsafe: when the FIRST result alone+ * exceeds the budget (packToBudget's strict [] edge), keep one result with+ * chunk_text truncated to fit — on a COPY, never mutating the shared+ * SearchResult (it flows on to cache write + eval capture). A budget below+ * even the title-only cost truncates the TITLE too (chunk_text: ''), so+ * `used <= budget` holds unconditionally — a hard cap that can be exceeded+ * is not a cap. The failsafe lives HERE, not in packToBudget, because it also+ * feeds the frozen memory-verb paths (recall/entity/context_pack) whose+ * strict-cap contract must not drift. `GBRAIN_SEARCH_SALVAGE=off`+ * restores the strict [] behavior (ENG-7).*/export function enforceTokenBudget(results: SearchResult[],budget: number | undefined,): { results: SearchResult[]; meta: TokenBudgetMeta } {const { items, meta } = packToBudget(results, resultTokens, budget);+ if (items.length === 0 && results.length > 0 && meta.budget > 0 && searchSalvageEnabled()) {+ const first = results[0];+ // Chars that keep resultTokens(copy) <= budget under the char/4 model:+ // ceil(4*(budget - titleCost)/4) = budget - titleCost. A sub-title-cost+ // budget slices the title itself (budget*4 chars costs exactly budget+ // tokens under ceil(len/4)), so used <= budget holds unconditionally.+ const title = (first.title ?? '').slice(0, meta.budget * 4);+ const chunkChars = Math.max(0, (meta.budget - estimateTokens(title)) * 4);+ const copy: SearchResult = { ...first, title, chunk_text: first.chunk_text.slice(0, chunkChars) };+ return {+ results: [copy],+ meta: {+ budget: meta.budget,+ used: resultTokens(copy),+ dropped: results.length - 1,+ kept: 1,+ truncated: true,+ },+ };+ }return { results: items, meta };}diff --git a/src/core/skill-catalog.ts b/src/core/skill-catalog.tsindex fa3c2432c0..1a811a54c5 100644--- a/src/core/skill-catalog.ts+++ b/src/core/skill-catalog.ts@@ -568,9 +568,17 @@ export function getSkillDetail(export function assertPublishEnabled(ctx: OperationContext, publishSkills: boolean): void {if (ctx.remote === false) return;if (publishSkills) return;- throw new OperationError(+ // Caller-facing wording + machine-readable detail (WP1). The k=v `detail`+ // grammar (`config_key=<key>`) is THE machine-parseable denial format —+ // future denial classes reuse it rather than inventing new string shapes.+ // Honest catalogs hide this op at list time; reaching this throw means a+ // caller guessed the name or the gate flipped between list and call.+ const err = new OperationError('permission_denied',- 'Skill publishing is disabled by the brain owner.',+ 'This tool is not published by the brain owner, so it is hidden from your tool catalog. ' ++ 'Ask the owner to enable skill publishing if you need it.','The owner can enable it with `gbrain config set mcp.publish_skills true`.',);+ err.detail = 'config_key=mcp.publish_skills';+ throw err;}diff --git a/src/core/surface-audit.ts b/src/core/surface-audit.tsnew file mode 100644index 0000000000..7c7f14f311--- /dev/null+++ b/src/core/surface-audit.ts@@ -0,0 +1,58 @@+/**+ * WP4 (amendment 32 / ENG-8) — surface-change audit trail.+ *+ * EVERY surface mutation (rescope CLI, POST /admin/api/rescope-client,+ * request_tools persist) writes one typed `mcp_request_log` row —+ * `operation='surface_change'`, `token_name`/`agent_name` = the acting+ * identity, `params` = a RAW OBJECT carrying `{actor, client_id, old, new,+ * via}` via executeRawJsonb (NEVER `JSON.stringify` into a `::jsonb` cast —+ * the #2339 double-encode class). Zero new DDL: it rides the existing+ * request log + `idx_mcp_log_time_agent` and the retention TODO, and is+ * remote-queryable via the E4 usage machinery. "Why did client X see 20+ * tools yesterday and 100 today" must be answerable from logs alone.+ *+ * Doc exception (ENG-8): CLI-actor audit rows are written even though stdio+ * ops don't otherwise log to mcp_request_log — the audit trail outranks the+ * transport-logging convention.+ *+ * Best-effort by design: the mutation has already committed when this runs;+ * a failed audit write warns to stderr rather than turning a successful+ * mutation into a caller-visible error. Callers that need fail-closed audit+ * semantics should await + inspect the returned boolean.+ */++import type { BrainEngine } from './engine.ts';+import { executeRawJsonb } from './sql-query.ts';++export interface SurfaceChangeAudit {+ /** Acting identity: OAuth client id (self-persist), 'operator' (CLI), 'admin-api'. */+ actor: string;+ /** The client whose surface changed. */+ client_id: string;+ /** Previous row value (null = column was NULL / no per-client surface). */+ old: string | null;+ /** New row value (null = cleared). */+ new: string | null;+ via: 'rescope_cli' | 'admin_api' | 'request_tools';+}++/** Returns true when the audit row landed; false (after a stderr warn) otherwise. */+export async function writeSurfaceChangeAudit(+ engine: BrainEngine,+ audit: SurfaceChangeAudit,+): Promise<boolean> {+ try {+ await executeRawJsonb(+ engine,+ `INSERT INTO mcp_request_log (token_name, agent_name, operation, latency_ms, status, params)+ VALUES ($1, $2, $3, $4, $5, $6::jsonb)`,+ [audit.actor, audit.actor, 'surface_change', 0, 'success'],+ [{ actor: audit.actor, client_id: audit.client_id, old: audit.old, new: audit.new, via: audit.via }],+ );+ return true;+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ process.stderr.write(`[surface-audit] failed to write surface_change audit row for ${audit.client_id} (via ${audit.via}): ${msg}\n`);+ return false;+ }+}diff --git a/src/core/think/gather.ts b/src/core/think/gather.tsindex a13c806e03..f809c60031 100644--- a/src/core/think/gather.ts+++ b/src/core/think/gather.ts@@ -308,7 +308,7 @@ function excerptWindow(content: string, requestedStart: number, excerptLen: numb}/** Select the fixed-budget window containing the strongest unique query-term coverage. */-function selectRelevantExcerpt(+export function selectRelevantExcerpt(content: string,query: string,excerptLen: number,diff --git a/src/core/think/index.ts b/src/core/think/index.tsindex 1c020daf1e..b71ab4a486 100644--- a/src/core/think/index.ts+++ b/src/core/think/index.ts@@ -19,7 +19,8 @@import type Anthropic from '@anthropic-ai/sdk';import type { BrainEngine, SynthesisEvidenceInput } from '../engine.ts';-import { runGather, renderPagesBlock, takesHitToTakeForPrompt } from './gather.ts';+import type { SearchResult } from '../types.ts';+import { runGather, renderPagesBlock, takesHitToTakeForPrompt, selectRelevantExcerpt } from './gather.ts';import { renderTakesBlock } from './sanitize.ts';import { buildThinkSystemPrompt, buildThinkUserMessage } from './prompt.ts';import { resolveCitations, type ParsedCitation } from './cite-render.ts';@@ -35,6 +36,23 @@ export interface ThinkLLMClient {create(params: Anthropic.MessageCreateParamsNonStreaming, opts?: { signal?: AbortSignal }): Promise<Anthropic.Message>;}+/** Closed set of LLM-call failure classes carried on the wire (D6 discipline). */+export type LlmCallFailureClass = 'timeout' | 'rate_limited' | 'network' | 'provider_error';++/**+ * Coarse, closed-vocabulary failure class for a thrown LLM call. The wire+ * (verb `warnings`) carries ONLY this class — raw provider/transport messages+ * (which can name hosts, keys, request ids) stay off remote responses and go+ * to stderr instead. Exported so tests pin the vocabulary.+ */+export function classifyLlmCallFailure(e: unknown): LlmCallFailureClass {+ const msg = (e instanceof Error ? e.message : String(e)).toLowerCase();+ if (/\b429\b|rate.?limit|overloaded/.test(msg)) return 'rate_limited';+ if (/timeout|timed.?out|etimedout/.test(msg)) return 'timeout';+ if (/econnrefused|econnreset|enotfound|eai_again|network|socket|fetch failed|dns/.test(msg)) return 'network';+ return 'provider_error';+}+export interface RunThinkOpts {question: string;/** Anchor entity slug. Activates the graph stream + entity-focused prompt. */@@ -121,6 +139,20 @@ export interface ThinkResponse {gaps: string[];}+/**+ * WP2/T5 — how the synthesis step concluded. Additive: the synthesize verb+ * maps this onto the protocol's `synthesis_status` field (stamping+ * `extractive_fallback` at the verb layer when a compose failure met a+ * non-empty gather). `ok` is the only value that marks a real answer.+ */+export type ThinkSynthesisStatus =+ | 'ok' // parsed JSON with a non-empty answer+ | 'empty_answer' // parsed JSON, answer empty+ | 'not_json' // unparseable output: malformed JSON, refusals, the graceful sentinel+ | 'no_llm' // no key configured — gather-only stub+ | 'model_unusable' // configured model failed the probe (unknown provider/model)+ | 'llm_error'; // client.create() threw (429 / timeout / 5xx / network)+export interface ThinkResult {question: string;answer: string;@@ -140,6 +172,20 @@ export interface ThinkResult {* pre-existing/test `ThinkResult` literals → treated as persistable (back-compat).*/synthesisOk?: boolean;+ /**+ * WP2/T5 — why synthesis produced (or didn't produce) a real answer.+ * Additive-forever; `synthesisOk` remains the persistence gate. The MCP+ * `think` op spreads this through verbatim.+ */+ synthesis_status?: ThinkSynthesisStatus;+ /**+ * WP2/E2 — extractive-fallback material, present ONLY when synthesis failed+ * (`synthesis_status !== 'ok'`) AND gather returned pages. Composed+ * exclusively from gathered pages — an empty gather never yields one+ * (ENG-19: no pages, no answer). `answer`/`citations` are left untouched+ * so existing consumers keep the raw failure shape; callers opt in.+ */+ extractive?: ExtractiveFallback;/*** MEMORY_VERBS v1 [E2] — gateway token usage for the synthesis call(s),* summed across rounds. Best-effort: null when no LLM ran (graceful stub),@@ -209,6 +255,54 @@ function tryParseJSON(text: string): unknown {}}+// ─── Extractive fallback [WP2/E2] ────────────────────────────────────────────+// When synthesis fails but gather succeeded, a digest of the top gathered+// pages (title + best excerpt, page-level citations) beats an empty failure.++const EXTRACTIVE_TOP_PAGES = 5;+const EXTRACTIVE_EXCERPT_LEN = 400;++export interface ExtractiveFallback {+ answer: string;+ /** Page-level citations (row_num null) for the digested pages, gather order. */+ citations: ParsedCitation[];+}++/**+ * Compose an extractive digest from gathered pages: one line per page,+ * title + the excerpt window with the strongest query-term coverage, cited+ * `[slug]`. NEVER fabricates: every line quotes ONE gathered page and an+ * empty gather returns null (ENG-19 — no pages, no answer, ever).+ */+export function composeExtractiveFallback(+ pages: SearchResult[],+ question: string,+): ExtractiveFallback | null {+ if (pages.length === 0) return null;+ const top = pages.slice(0, EXTRACTIVE_TOP_PAGES);+ const citations: ParsedCitation[] = [];+ const lines = top.map((p, idx) => {+ const page = p as unknown as {+ slug?: string; title?: string; chunk_text?: string; compiled_truth?: string; snippet?: string;+ };+ const slug = String(page.slug ?? '');+ const title = String(page.title ?? '') || slug;+ const slugIdentity = slug.split('/').pop()?.replace(/[-_]/g, ' ') ?? '';+ const content = String(page.chunk_text ?? page.compiled_truth ?? page.snippet ?? '');+ const excerpt = selectRelevantExcerpt(+ content, question, EXTRACTIVE_EXCERPT_LEN, `${title} ${slugIdentity}`,+ ).trim();+ citations.push({ page_slug: slug, row_num: null, citation_index: idx + 1 });+ return excerpt ? `- ${title} [${slug}]: ${excerpt}` : `- ${title} [${slug}]`;+ });+ return {+ answer:+ `No synthesized answer — extractive excerpts from the ${top.length} most relevant retrieved page(s):\n` ++ lines.join('\n'),+ citations,+ };+}+/*** Persist citations into synthesis_evidence. Resolves slugs to page_ids* via the engine. Pages that don't exist in the brain are skipped + warn'd.@@ -294,7 +388,9 @@ export async function runThink(const e = await opts.embedQuestion(opts.question);if (e) questionEmbedding = e;} catch (e) {- warnings.push(`QUESTION_EMBED_FAILED: ${(e as Error).message}`);+ // D6: code-only on the wire; raw exception text goes to server logs.+ warnings.push('QUESTION_EMBED_FAILED');+ process.stderr.write(`[think] question embed failed: ${e instanceof Error ? e.message : String(e)}\n`);}}@@ -345,9 +441,9 @@ export async function runThink(warnings.push('NO_CALIBRATION_PROFILE');}} catch (err) {- warnings.push(- `CALIBRATION_FETCH_FAILED: ${err instanceof Error ? err.message : 'unknown'}`,- );+ // D6: code-only on the wire; raw exception text goes to server logs.+ warnings.push('CALIBRATION_FETCH_FAILED');+ process.stderr.write(`[think] calibration fetch failed: ${err instanceof Error ? err.message : String(err)}\n`);}}@@ -427,9 +523,9 @@ export async function runThink(// Defensive: trajectory injection is best-effort. Any unexpected// error degrades to "no trajectory block" + a warning. The think// call itself never fails because of trajectory wiring.- warnings.push(- `TRAJECTORY_INJECTION_FAILED: ${err instanceof Error ? err.message : 'unknown'}`,- );+ // D6: code-only on the wire; raw exception text goes to server logs.+ warnings.push('TRAJECTORY_INJECTION_FAILED');+ process.stderr.write(`[think] trajectory injection failed: ${err instanceof Error ? err.message : String(err)}\n`);}}if (trajectoryPointsCount > 0) {@@ -460,10 +556,15 @@ export async function runThink(// sentinel, which is non-JSON) and on the no-client early return below; the final// return ANDs it with a non-empty-answer check (catches valid-but-empty JSON).let synthesisOk = true;+ // [WP2/T5] typed compose status. Starts 'ok'; failure branches overwrite it+ // with their specific value; the parsed-but-empty check at the bottom is the+ // only downgrade applied to a still-'ok' status.+ let synthesisStatus: ThinkSynthesisStatus = 'ok';// [E2] best-effort usage aggregation across synthesis calls (single-pass in// v0.28+, but summed so the round loop inherits it when gap-fill lands).let usage: { input_tokens: number; output_tokens: number } | null = null;- let response: ThinkResponse;+ // Initialized to the llm_error shape; every non-throwing branch overwrites it.+ let response: ThinkResponse = { answer: '', citations: [], gaps: [] };if (opts.stubResponse) {response = opts.stubResponse;} else {@@ -494,6 +595,10 @@ export async function runThink();const detail = !probe.ok ? probe.detail : '';const fix = !probe.ok && probe.fix ? ` Fix: ${probe.fix}` : '';+ // [WP2/E2] non-empty gather still has value — attach the extractive+ // digest so callers (the synthesize verb) can surface it instead of+ // the stub answer. Null on empty gather (never fabricate).+ const stubExtractive = composeExtractiveFallback(gather.pages, opts.question);// Degrade gracefully: return the gather without synthesis. Better than throwing.return {question: opts.question,@@ -513,6 +618,8 @@ export async function runThink(rounds: 0,warnings,synthesisOk: false, // #1698: no LLM ran — never persist this+ synthesis_status: modelProblem ? 'model_unusable' : 'no_llm',+ ...(stubExtractive ? { extractive: stubExtractive } : {}),usage: null, // [E2] no LLM ran — no accountingdiagnostics: {pagesFromHybrid: gather.diagnostics.pagesFromHybrid,@@ -522,37 +629,64 @@ export async function runThink(},};}- const result = await client.create({- model: modelUsed,- max_tokens: maxOutputTokensFor(normalizeModelId(modelUsed)),- system: systemPrompt,- messages: [{ role: 'user', content: userMessage }],- });- // [E2] capture usage when the message carries it (test-injected clients- // and providers without accounting leave it null).- const u = (result as { usage?: { input_tokens?: number; output_tokens?: number } }).usage;- if (u && typeof u.input_tokens === 'number' && typeof u.output_tokens === 'number') {- // Single synthesis call in v0.28+; when gap-driven rounds land, sum here.- const prev = usage as { input_tokens: number; output_tokens: number } | null;- usage = {- input_tokens: (prev?.input_tokens ?? 0) + u.input_tokens,- output_tokens: (prev?.output_tokens ?? 0) + u.output_tokens,- };+ let created: Anthropic.Message | null = null;+ try {+ created = await client.create({+ model: modelUsed,+ max_tokens: maxOutputTokensFor(normalizeModelId(modelUsed)),+ system: systemPrompt,+ messages: [{ role: 'user', content: userMessage }],+ });+ } catch (e) {+ // [ENG-10] provider/transport failures (429, timeout, 5xx, network)+ // become a typed llm_error status instead of killing the whole call —+ // gather already succeeded and the caller can still act on it. Three+ // throw classes stay hard: the explicit-model config error (#1698 — the+ // gateway adapter only lets AIConfigError escape on the explicit path),+ // budget exhaustion (spend control must stop the enclosing loop), and+ // aborts (cancellation is control flow, not an LLM failure).+ const name = e instanceof Error ? e.name : '';+ if ((opts.modelExplicit && e instanceof AIConfigError) || name === 'BudgetExhausted' || name === 'AbortError') {+ throw e;+ }+ // D6 closed vocabulary: the wire carries the coarse class only; the raw+ // provider/transport message goes to stderr for the operator.+ warnings.push(`LLM_CALL_FAILED: ${classifyLlmCallFailure(e)}`);+ process.stderr.write(`[think] LLM call failed (${classifyLlmCallFailure(e)}): ${e instanceof Error ? e.message : String(e)}\n`);+ synthesisStatus = 'llm_error';+ synthesisOk = false;+ // response keeps its empty llm_error initialization.}- const block = result.content.find(b => b.type === 'text');- const text = block && 'text' in block ? block.text : '';- const parsed = tryParseJSON(text);- if (!parsed || typeof parsed !== 'object') {- warnings.push('LLM_OUTPUT_NOT_JSON');- synthesisOk = false; // #1698: malformed output (and the non-JSON graceful sentinel)- response = { answer: text, citations: [], gaps: [] };- } else {- const r = parsed as Partial<ThinkResponse>;- response = {- answer: typeof r.answer === 'string' ? r.answer : '',- citations: Array.isArray(r.citations) ? (r.citations as ThinkResponse['citations']) : [],- gaps: Array.isArray(r.gaps) ? (r.gaps as string[]).filter(g => typeof g === 'string') : [],- };+ if (created) {+ // [E2] capture usage when the message carries it (test-injected clients+ // and providers without accounting leave it null).+ const u = (created as { usage?: { input_tokens?: number; output_tokens?: number } }).usage;+ if (u && typeof u.input_tokens === 'number' && typeof u.output_tokens === 'number') {+ // Single synthesis call in v0.28+; when gap-driven rounds land, sum here.+ const prev = usage as { input_tokens: number; output_tokens: number } | null;+ usage = {+ input_tokens: (prev?.input_tokens ?? 0) + u.input_tokens,+ output_tokens: (prev?.output_tokens ?? 0) + u.output_tokens,+ };+ }+ const block = created.content.find(b => b.type === 'text');+ const text = block && 'text' in block ? block.text : '';+ const parsed = tryParseJSON(text);+ if (!parsed || typeof parsed !== 'object') {+ warnings.push('LLM_OUTPUT_NOT_JSON');+ synthesisOk = false; // #1698: malformed output (and the non-JSON graceful sentinel)+ // Refusals + the graceful sentinel land here too — coarse on purpose+ // (no dedicated status; the raw text stays in `answer` for consumers).+ synthesisStatus = 'not_json';+ response = { answer: text, citations: [], gaps: [] };+ } else {+ const r = parsed as Partial<ThinkResponse>;+ response = {+ answer: typeof r.answer === 'string' ? r.answer : '',+ citations: Array.isArray(r.citations) ? (r.citations as ThinkResponse['citations']) : [],+ gaps: Array.isArray(r.gaps) ? (r.gaps as string[]).filter(g => typeof g === 'string') : [],+ };+ }}}@@ -569,6 +703,18 @@ export async function runThink(break; // v0.28: single-pass only}+ // [WP2/T5] parsed-but-empty answer gets its own status; branches that+ // already flagged a more specific failure keep theirs.+ if (synthesisStatus === 'ok' && response.answer.trim().length === 0) {+ synthesisStatus = 'empty_answer';+ warnings.push('SYNTHESIS_EMPTY_ANSWER');+ }+ // [WP2/E2] compose failed + non-empty gather → attach extractive material+ // (callers decide whether to surface it; null on empty gather — ENG-19).+ const extractive = synthesisStatus !== 'ok'+ ? composeExtractiveFallback(gather.pages, opts.question)+ : null;+return {question: opts.question,answer: response.answer,@@ -583,6 +729,8 @@ export async function runThink(// #1698: persistable only when a real synthesis produced a non-empty answer.// ANDs the not-JSON/sentinel flag with a content check (catches valid-but-empty JSON).synthesisOk: synthesisOk && response.answer.trim().length > 0,+ synthesis_status: synthesisStatus,+ ...(extractive ? { extractive } : {}),usage,diagnostics: {pagesFromHybrid: gather.diagnostics.pagesFromHybrid,diff --git a/src/core/types.ts b/src/core/types.tsindex 646a2f404e..40ec978a53 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -1646,6 +1646,67 @@ export interface EvalCaptureFailure {reason: EvalCaptureFailureReason;}+/**+ * WP2/T3 — CLOSED degradation vocabulary for `HybridSearchMeta.degraded`+ * (D6). Every stage a search can degrade through has an enumerated name;+ * consumers (MCP `_meta.retrieval`, telemetry, `--explain`) match on these+ * codes. Additive-forever: new stages append, existing names never change.+ *+ * embed_unavailable — no embedding ran (no provider, or provider errored)+ * embed_timeout — every query embed hit the wall-clock deadline+ * expansion_failed — the LLM multi-query expander threw; original only+ * expansion_partial — some (not all) variant embeds survived; results+ * salvaged from the surviving lists (ENG-15)+ * rescore_skipped — original-query embed failed, so the cosine+ * re-score stage was skipped (variant-list salvage)+ * vector_arm_failed — an engine.searchVector arm threw; surviving arms+ * (or keyword) carried the result+ * budget_dropped_all — the first result alone exceeded the token budget+ * and NOTHING was returned (GBRAIN_SEARCH_SALVAGE=off+ * strict path — the result set is empty)+ * budget_truncated — the minKeep failsafe kept ONE result truncated to+ * fit the budget (results non-empty but cut; distinct+ * stage so consumers can tell "empty" from "clipped")+ * keyword_zero — the keyword arm returned zero rows on a path where+ * it was the primary recall arm (vector unavailable)+ * cache_prestamp — served from a cache row written before the+ * degradation stamp existed; cleanliness unprovable+ */+export const DEGRADED_STAGES = [+ 'embed_unavailable',+ 'embed_timeout',+ 'expansion_failed',+ 'expansion_partial',+ 'rescore_skipped',+ 'vector_arm_failed',+ 'budget_dropped_all',+ 'budget_truncated',+ 'keyword_zero',+ 'cache_prestamp',+] as const;+export type DegradedStage = (typeof DEGRADED_STAGES)[number];++/**+ * WP2/T3 — enumerated reason codes for degraded stages (D6). NEVER raw+ * exception text: raw errors go to stderr/telemetry only, so a provider's+ * error string (which can embed URLs, keys, internal hostnames) never+ * rides the wire to a remote MCP consumer.+ */+export const DEGRADED_REASONS = [+ 'no_provider',+ 'provider_error',+ 'timeout',+ 'variant_embed_failed',+ 'original_embed_failed',+ 'first_result_truncated',+] as const;+export type DegradedReason = (typeof DEGRADED_REASONS)[number];++export interface DegradedStageEntry {+ stage: DegradedStage;+ reason?: DegradedReason;+}+/*** Side-channel metadata that hybridSearch reports about what actually ran.* Surfaced via the optional `onMeta` callback in HybridSearchOpts so@@ -1688,7 +1749,27 @@ export interface HybridSearchMeta {used: number;kept: number;dropped: number;+ /**+ * WP2/T3 (ENG-2/FOV-2) — set when the minKeep failsafe kept ONE result+ * whose chunk_text was truncated (on a copy) to fit the budget, where+ * the strict packer would have returned [].+ */+ truncated?: boolean;};+ /**+ * WP2/T3 (D6) — degradation stamp. Empty array = clean run (every stage+ * ran as configured); entries name what fell over, with enumerated reason+ * codes only. Always present on hybridSearch-emitted meta so cache rows+ * carry the stamp; absent only on meta shapes written before this field+ * existed (surfaced as `cache_prestamp` at hit time).+ */+ degraded?: DegradedStageEntry[];+ /**+ * WP2/T3 — pre-budget hit count: how many results retrieval produced for+ * this page BEFORE token-budget enforcement. Lets a consumer distinguish+ * "0 retrieved" (clean miss) from "N retrieved, budget dropped them".+ */+ retrieved_count?: number;/*** v0.32.x (search-lite): cache hit/miss tracking. Omitted when the* semantic query cache wasn't consulted (cache disabled, vector searchdiff --git a/src/core/verbs.ts b/src/core/verbs.tsindex bf704ca9d9..018573427e 100644--- a/src/core/verbs.ts+++ b/src/core/verbs.ts@@ -211,13 +211,27 @@ const entity: Operation = {// ─── synthesize ──────────────────────────────────────────────────────────────+// [WP2/T5] compose-failure status → the machine-stable warning code named in+// the empty-gather `unavailable` error message. Freeform tails (provider+// messages) ride `detail` only; the message carries the code.+const SYNTHESIS_FAILURE_CODES: Record<string, string> = {+ not_json: 'LLM_OUTPUT_NOT_JSON',+ empty_answer: 'SYNTHESIS_EMPTY_ANSWER',+ llm_error: 'LLM_CALL_FAILED',+ model_unusable: 'MODEL_NOT_USABLE',+ no_llm: 'NO_ANTHROPIC_API_KEY',+};+const synthesize: Operation = {name: 'synthesize',description:'[EXPENSIVE / SLOW — makes LLM calls, seconds-to-minutes latency, costs money] ' +'MEMORY VERB (v1): answer a broad question using cross-page LLM reasoning with citations and gap analysis. ' +'Prefer recall (facts/snippets) or entity (one known card, zero LLM) for lookups — use synthesize only when the answer ' +- 'requires combining evidence across pages. Response carries a best-effort cost block (model, tokens, usd_estimate).',+ 'requires combining evidence across pages. Response carries a best-effort cost block (model, tokens, usd_estimate) ' ++ 'plus compose-status fields (synthesis_status, pages_gathered, takes_gathered, warnings); when the LLM compose step ' ++ 'fails but retrieval succeeded, `answer` degrades to an extractive digest of retrieved pages ' ++ '(synthesis_status: "extractive_fallback") instead of an error.',params: {question: { type: 'string', required: true, description: 'The question to answer.' },since: { type: 'string', description: 'Optional temporal window start (ISO 8601 date or datetime).' },@@ -253,6 +267,9 @@ const synthesize: Operation = {// [c10] runThink degrades gracefully to a no-LLM stub RESULT; the protocol// contract converts that state into an explicit `unavailable` error so// agents branch on configure/retry instead of relaying a fake answer.+ // Deliberately unconditional (fires even with a non-empty gather): an+ // unconfigured key routed to the extractive fallback would be masked on+ // every call and never get fixed.if (result.warnings.includes('NO_ANTHROPIC_API_KEY')) {throw verbError('unavailable',@@ -271,17 +288,50 @@ const synthesize: Operation = {usage && pricing? (usage.input_tokens * pricing.input + usage.output_tokens * pricing.output) / 1_000_000: null;+ const cost = {+ model: result.modelUsed,+ input_tokens: usage?.input_tokens ?? null,+ output_tokens: usage?.output_tokens ?? null,+ usd_estimate: usdEstimate,+ };++ // [WP2/T5+E2] compose-status precedence: 'ok' → the synthesized answer;+ // any compose failure with a NON-EMPTY gather → the extractive fallback+ // (quotes/cites ONLY gathered pages); compose failure with an EMPTY+ // gather → typed error. An answer is NEVER fabricated from nothing+ // (ENG-19). Defensive ?? 'ok' mirrors synthesisOk's back-compat posture.+ const status = result.synthesis_status ?? 'ok';+ if (status !== 'ok') {+ if (result.extractive) {+ return {+ answer: result.extractive.answer,+ sources: result.extractive.citations.map(c => c.page_slug),+ gaps: result.gaps,+ cost,+ synthesis_status: 'extractive_fallback',+ pages_gathered: result.pagesGathered,+ takes_gathered: result.takesGathered,+ warnings: result.warnings,+ protocol_version: MEMORY_VERBS_VERSION,+ };+ }+ throw verbError(+ 'unavailable',+ `retrieved ${result.pagesGathered} pages; compose failed: ${SYNTHESIS_FAILURE_CODES[status] ?? status}`,+ 'The LLM compose step failed and retrieval found nothing to fall back on. Rephrase or broaden the question (or the since/until window); if the code names the model or provider, fix the model config and retry.',+ result.warnings.length > 0 ? result.warnings.join('; ') : undefined,+ );+ }return {answer: result.answer,sources: result.citations.map(c => c.page_slug),gaps: result.gaps,- cost: {- model: result.modelUsed,- input_tokens: usage?.input_tokens ?? null,- output_tokens: usage?.output_tokens ?? null,- usd_estimate: usdEstimate,- },+ cost,+ synthesis_status: 'ok',+ pages_gathered: result.pagesGathered,+ takes_gathered: result.takesGathered,+ warnings: result.warnings,protocol_version: MEMORY_VERBS_VERSION,};},@@ -375,6 +425,14 @@ export const verbOperations: Operation[] = [remember, entity, synthesize, forgetconst EVIDENCE_ENUM = ['alias_hit', 'exact_title_match', 'high_vector_match', 'keyword_exact', 'weak_semantic'];const CREATE_SAFETY_ENUM = ['exists', 'probable', 'unknown'];const STATUS_ENUM = ['inserted', 'duplicate', 'superseded'];+// v0.45.x (WP2/T5+E2) — additive-forever. The verb emits 'ok' or+// 'extractive_fallback'; the remaining compose-failure values ride the+// non-verb `think` surface (the verb converts them to the extractive+// fallback or a typed `unavailable` error) and stay enum-listed so any+// v1 server emitting them validates.+const SYNTHESIS_STATUS_ENUM = [+ 'ok', 'empty_answer', 'not_json', 'no_llm', 'model_unusable', 'llm_error', 'extractive_fallback',+];export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {recall: {@@ -524,6 +582,17 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {usd_estimate: { type: ['number', 'null'] },},},+ // v0.45.x (WP2/T5+E2) additive compose-status fields — never required+ // (a pre-v0.45.x v1 server that omits them must still certify).+ synthesis_status: {+ type: 'string',+ enum: SYNTHESIS_STATUS_ENUM,+ description:+ 'How the answer was produced. ok = LLM synthesis; extractive_fallback = compose failed with a non-empty gather — answer is an extractive digest quoting ONLY retrieved pages, sources cite the digested pages (never fabricated).',+ },+ pages_gathered: { type: 'integer', description: 'Pages retrieved by the gather phase behind this answer.' },+ takes_gathered: { type: 'integer', description: 'Takes retrieved by the gather phase behind this answer.' },+ warnings: { type: 'array', items: { type: 'string' }, description: 'Machine-stable pipeline warning codes (e.g. LLM_OUTPUT_NOT_JSON, LLM_CALL_FAILED: <class> where <class> is timeout | rate_limited | network | provider_error).' },},},forget: {diff --git a/src/core/verbs/conformance-fixtures.ts b/src/core/verbs/conformance-fixtures.tsindex 522fe7de82..7a3a343b60 100644--- a/src/core/verbs/conformance-fixtures.ts+++ b/src/core/verbs/conformance-fixtures.ts@@ -222,6 +222,10 @@ export const CONFORMANCE_CASES: ConformanceCase[] = [requiresSynthesizeFlag: true,// Either a schema-valid answer (key configured) or a clean unavailable// error (no key). The runner accepts both; anything else fails.+ // v0.45.x: the answer path also validates the additive compose-status+ // fields (synthesis_status enum incl. extractive_fallback, pages_gathered,+ // takes_gathered, warnings) via RESPONSE_SCHEMAS.synthesize — present on+ // post-v0.45.x servers, never required (additive-forever).},// ── v0.45.7 additive verbs: context_pack + delta ──────────────────────────diff --git a/src/core/verbs/usage-log.ts b/src/core/verbs/usage-log.tsindex 5b2d1792a4..6136ef28b4 100644--- a/src/core/verbs/usage-log.ts+++ b/src/core/verbs/usage-log.ts@@ -26,7 +26,7 @@ const ROTATE_BYTES = 10 * 1024 * 1024;export interface VerbUsageEvent {ts: string;verb: string;- surface: 'verbs' | 'full';+ surface: 'verbs' | 'starter' | 'full';remote: boolean;ok: boolean;latency_ms: number;diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 00b0771fb8..a28d63dd47 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -8,10 +8,22 @@import type { BrainEngine } from '../core/engine.ts';import { operations, OperationError, enforceBoundClientOpAllowList } from '../core/operations.ts';-import type { Operation, OperationContext, AuthInfo } from '../core/operations.ts';+import type { OperationContext, AuthInfo } from '../core/operations.ts';import { loadConfig } from '../core/config.ts';import { VERB_NAMES, MEMORY_VERBS_VERSION } from '../core/verbs.ts';import { logVerbUsage } from '../core/verbs/usage-log.ts';+import { suggestNearest } from '../core/levenshtein.ts';+import {+ normalizeOptionalParams,+ validateParams,+ findUnknownParams,+ buildUnknownParamWarnBlock,+ resolveStrictParamsMode,+} from './validate-params.ts';++// WP3: normalization + validation moved to validate-params.ts (direct unit+// surface). Re-exported here so existing imports/tests keep working.+export { normalizeOptionalParams, validateParams } from './validate-params.ts';const VERB_NAME_SET: ReadonlySet<string> = new Set(VERB_NAMES);@@ -39,7 +51,10 @@ export interface DispatchOpts {/*** #1061: transport marker for auth-less remote surfaces. The stdio MCP* server passes 'stdio' so identity ops (whoami) can report the transport- * instead of throwing unknown_transport. Never used for trust decisions.+ * instead of throwing unknown_transport. Never used for TRUST decisions+ * (that is `remote`), but it IS the transport-LOCALITY axis: localOnly+ * ops dispatch only when this is 'stdio' (WP1/D7) — HTTP transports pass+ * 'http', and an unset marker is treated as non-local, fail-closed.*/transport?: OperationContext['transport'];/**@@ -106,9 +121,19 @@ export interface DispatchOpts {/*** Which surface this transport is serving — recorded on the verb usage* sidecar so adoption stats can split quickstart installs from full- * surfaces. Defaults to 'full'.+ * surfaces. Defaults to 'full'. On the OAuth HTTP transport this is the+ * per-request EFFECTIVE surface (D2 ceiling resolution, recomputed per+ * request — amendment 20).+ */+ surface?: 'verbs' | 'starter' | 'full';+ /**+ * WP4 (D2): the SERVER surface ceiling for this transport (force-clamped),+ * threaded into `OperationContext.surfaceCeiling` for the request_tools+ * meta-op — its catalog never names ops above the ceiling and its persist+ * branch rejects widening past it. Unset (local CLI / direct dispatch) is+ * treated as 'full'.*/- surface?: 'verbs' | 'full';+ surfaceCeiling?: 'verbs' | 'starter' | 'full';}/**@@ -206,60 +231,111 @@ export function summarizeMcpParams(opName: string, params: unknown): ParamSummar};}-/** Validate required params exist and have the expected type. Returns null on success, error message on failure. */-export function validateParams(op: Operation, params: Record<string, unknown>): string | null {- for (const [key, def] of Object.entries(op.params)) {- if (def.required && (params[key] === undefined || params[key] === null)) {- return `Missing required parameter: ${key}`;- }- if (params[key] !== undefined && params[key] !== null) {- const val = params[key];- const expected = def.type;- if (expected === 'string' && typeof val !== 'string') return `Parameter "${key}" must be a string`;- if (expected === 'number' && typeof val !== 'number') return `Parameter "${key}" must be a number`;- if (expected === 'boolean' && typeof val !== 'boolean') return `Parameter "${key}" must be a boolean`;- if (expected === 'object' && (typeof val !== 'object' || Array.isArray(val))) return `Parameter "${key}" must be an object`;- if (expected === 'array' && !Array.isArray(val)) return `Parameter "${key}" must be an array`;- }- }- return null;+/**+ * D8: render the second (model-visible) content block for an empty retrieval+ * result from the handler-emitted `retrieval` meta. Returns null when the+ * meta doesn't carry the expected shape — the block is best-effort loudness,+ * never a failure source. Reason codes come from the closed degradation+ * vocabulary (D6); raw exception text never reaches this string.+ */+export function buildEmptyRetrievalBlock(retrieval: unknown): string | null {+ if (retrieval === null || typeof retrieval !== 'object') return null;+ const r = retrieval as {+ retrieved_count?: number;+ degraded?: Array<{ stage?: string; reason?: string }>;+ hint?: string;+ };+ const parts: string[] = ['0 results.'];+ if (typeof r.retrieved_count === 'number') parts.push(`retrieved ${r.retrieved_count} before trimming.`);+ const stages = (r.degraded ?? [])+ .map(d => d?.stage)+ .filter((s): s is string => typeof s === 'string' && s.length > 0);+ parts.push(stages.length > 0+ ? `degraded: ${[...new Set(stages)].join(', ')}.`+ : 'no retrieval degradation — this is a clean miss.');+ if (typeof r.hint === 'string' && r.hint.length > 0) parts.push(`hint: ${r.hint}`);+ return parts.join(' ');}/**- * Normalize the absent-idioms real MCP clients send for OPTIONAL params- * before validation and dispatch: `null` (any type) and `''` (string-typed- * params) become "not provided".+ * Amendment 33 / D10 — honest-catalog metric classifier. True when a parsed+ * error envelope is an OP-LEVEL denial the tools/list filter SHOULD have+ * prevented (the same predicates gate list and call time, so in a correct+ * world these trend to zero):+ * - publish-gate call-time backstop (`detail: 'config_key=...'` — WP1's+ * machine-readable denial grammar)+ * - bound-client fence OP-level deny (`detail: 'fence=op'` —+ * enforceBoundClientOpAllowList; the tools/list filter consumes the+ * identical predicate, ENG-3)*- * Why: non-Claude models routinely fill optional params with `""` or `null`- * instead of omitting them. `validateParams` already reads null as absent- * for the required-param check (see above); handlers do not — some guard- * with `typeof p.x === 'string' && p.x.length > 0` (entity / session_id in- * `recall`), others with `p.x !== undefined` (since in `recall`), so- * `recall {since: ""}` silently returned zero facts where the same call- * with `since` omitted returns rows. Normalizing once at the shared- * dispatch layer gives every handler one canonical absence instead of- * per-handler guards.- *- * Deliberately narrow:- * - Required params are untouched — null on a required param still fails- * validation loudly, and `''` on a required string still reaches the- * handler exactly as before.- * - Type-mismatched junk is untouched — `limit: ""` keeps its loud- * "must be a number" error rather than silently succeeding.- * - Undeclared keys are untouched (they were already ignored).- * Copy-on-write: callers' param objects are never mutated.+ * Argument-level fence denials (slug-prefix rejections inside handlers) are+ * legitimate for a LISTED op and deliberately excluded (D10) — they carry no+ * marker. serve-http logs matching rows with status='denied_after_list' so+ * `SELECT count(*) FROM mcp_request_log WHERE status='denied_after_list'`+ * is the wave's trend-to-zero working metric (the scope-deny path in+ * serve-http is the third list-level class; it logs the status directly).*/-export function normalizeOptionalParams(op: Operation, params: Record<string, unknown>): Record<string, unknown> {- let out: Record<string, unknown> | null = null;- for (const [key, def] of Object.entries(op.params)) {- if (def.required) continue;- const val = params[key];- const isAbsentIdiom = val === null || (val === '' && def.type === 'string');- if (!isAbsentIdiom) continue;- if (out === null) out = { ...params };- delete out[key];+export function isListLevelDenialEnvelope(parsed: unknown): boolean {+ if (parsed === null || typeof parsed !== 'object') return false;+ const p = parsed as { error?: unknown; detail?: unknown };+ if (p.error !== 'permission_denied') return false;+ if (typeof p.detail !== 'string') return false;+ return p.detail.startsWith('config_key=') || p.detail === 'fence=op';+}++/** The mcp_request_log status classes a dispatched tool result maps onto. */+export type RequestLogStatus = 'success' | 'success_with_warnings' | 'denied_after_list' | 'error';++/**+ * The ONE `mcp_request_log.status` decision for a dispatched tool result+ * (serve-http's tools/call persistence + SSE broadcast both consume this):+ * - errors whose envelope is a list-level denial (isListLevelDenialEnvelope+ * above) → 'denied_after_list' (amendment 33 / D10 trend-to-zero metric);+ * other errors (including unparseable content) → 'error';+ * - successes whose `_meta.warnings` is a non-empty array →+ * 'success_with_warnings' (WP3 amendment 13 warn-mode observability;+ * warn CONTENTS are never logged); otherwise → 'success'.+ * The scope-deny and unknown-op paths in serve-http log their statuses+ * directly — they never produce a ToolResult through the dispatcher.+ */+export function requestLogStatusForResult(result: ToolResult): RequestLogStatus {+ if (result.isError) {+ try {+ const parsed: unknown = JSON.parse(result.content[0]?.text ?? '{}');+ if (isListLevelDenialEnvelope(parsed)) return 'denied_after_list';+ } catch { /* unparseable error content stays plain 'error' */ }+ return 'error';}- return out ?? params;+ const warnings = result._meta?.warnings;+ return Array.isArray(warnings) && warnings.length > 0 ? 'success_with_warnings' : 'success';+}++/**+ * WP3: the ONE unknown_tool envelope builder, shared by all three deny paths+ * (surface-hidden via allowedOps, nonexistent op, localOnly over a network+ * transport) so they stay byte-identical for the same input name — a hidden+ * op must remain indistinguishable from a nonexistent one.+ *+ * The did-you-mean candidates are the caller's VISIBLE surface only+ * (amendment 11): (allowedOps if set, else the full catalog) MINUS localOnly+ * ops MINUS publish-gated ops. Gated names are excluded unconditionally —+ * gate state is unknown here, and a suggestion naming a hidden/gated op+ * would be the exact existence oracle this envelope exists to prevent.+ */+function unknownToolEnvelope(name: string, allowedOps?: ReadonlySet<string>): ToolResult {+ const candidates = operations+ .filter(op => !op.localOnly && !op.publishGateKey && (allowedOps ? allowedOps.has(op.name) : true))+ .map(op => op.name);+ const nearest = suggestNearest(name, candidates);+ const envelope = {+ error: 'unknown_tool',+ message: `Unknown tool: ${name}`,+ ...(nearest ? { suggestion: `Did you mean "${nearest}"?` } : {}),+ };+ return {+ content: [{ type: 'text', text: JSON.stringify(envelope, null, 2) }],+ isError: true,+ };}const stderrLogger: OperationContext['logger'] = {@@ -312,6 +388,7 @@ export function buildOperationContext(sourceId: opts.sourceId ?? 'default',...(sessionId ? { sessionId } : {}),...(opts.localFederatedSourceIds ? { localFederatedSourceIds: opts.localFederatedSourceIds } : {}),+ ...(opts.surfaceCeiling ? { surfaceCeiling: opts.surfaceCeiling } : {}),auth: opts.auth,};}@@ -349,10 +426,7 @@ export async function dispatchToolCall(// on every transport, not just unlisted. Same envelope as unknown ops so// the surface doesn't leak which names exist.if (opts.allowedOps && !opts.allowedOps.has(name)) {- return {- content: [{ type: 'text', text: JSON.stringify({ error: 'unknown_tool', message: `Unknown tool: ${name}` }, null, 2) }],- isError: true,- };+ return unknownToolEnvelope(name, opts.allowedOps);}const op = operations.find(o => o.name === name);@@ -362,10 +436,18 @@ export async function dispatchToolCall(// plain `Error: ...` string here breaks the contract on every// unknown-op path and the resulting test failure looked like a// transport bug.- return {- content: [{ type: 'text', text: JSON.stringify({ error: 'unknown_tool', message: `Unknown tool: ${name}` }, null, 2) }],- isError: true,- };+ return unknownToolEnvelope(name, opts.allowedOps);+ }++ // localOnly backstop at the SHARED layer (WP1/D7): localOnly ops reach the+ // operator's filesystem, so they dispatch only on the local stdio pipe.+ // Any non-stdio transport — both HTTP servers, and any future caller that+ // forgets to mark its transport — is denied fail-closed. Same envelope as+ // a nonexistent op so the catalog doesn't leak which names exist. The+ // serve-http path also filters these at list time; the legacy bearer+ // transport at surface 'full' had no gate at all before this line.+ if (op.localOnly && opts.transport !== 'stdio') {+ return unknownToolEnvelope(name, opts.allowedOps);}const safeParams = normalizeOptionalParams(op, params || {});@@ -388,6 +470,40 @@ export async function dispatchToolCall(};}+ // WP3 strict/warn unknown-argument validation. Runs on the NORMALIZED+ // object (a null/'' optional idiom is never an unknown key). `_meta` and+ // `dry_run` are allowlisted inside findUnknownParams. The mode resolves+ // dual-plane (DB > file > 'warn') once per dispatch, and only when an+ // unknown key actually exists — the all-declared common case pays no+ // config read.+ const unknownParamWarnings = findUnknownParams(op, safeParams);+ if (unknownParamWarnings.length > 0) {+ const strictMode = await resolveStrictParamsMode(engine, loadConfig());+ if (strictMode === 'reject') {+ logVerb(false);+ // Privacy (amendment 11): the raw unknown key rides `suggestion` ONLY.+ // serve-http persists the envelope's `message` into+ // mcp_request_log.error_message — the message therefore counts, never+ // names (same posture as the redacted params summarizer).+ const n = unknownParamWarnings.length;+ const suggestion = unknownParamWarnings+ .map(w => w.suggestion+ ? `Unknown parameter "${w.param}" — did you mean "${w.suggestion}"?`+ : `Unknown parameter "${w.param}".`)+ .join(' ');+ const envelope = {+ error: 'invalid_params',+ message: `${n} unknown parameter${n === 1 ? '' : 's'} not declared in the ${name} tool schema (mcp.strict_params=reject). See suggestion for the submitted name${n === 1 ? '' : 's'}.`,+ suggestion,+ ...(isVerb ? { protocol_version: MEMORY_VERBS_VERSION } : {}),+ };+ return {+ content: [{ type: 'text', text: JSON.stringify(envelope, null, 2) }],+ isError: true,+ };+ }+ }+// Remote callers must arrive with a resolved source scope. Every shipped// transport passes sourceId explicitly (serve-http from the OAuth client// row, http-transport from the legacy token grant, stdio from@@ -405,6 +521,22 @@ export async function dispatchToolCall(const ctx = buildOperationContext(engine, safeParams, opts);+ // WP2/D3: response-meta side channel. Handlers publish namespaced+ // out-of-band metadata (retrieval degradation, strict-mode warnings) here;+ // the success path below merges the collected keys into ToolResult._meta.+ // Last write per key wins within one call; the collector never throws.+ const responseMeta: Record<string, unknown> = {};+ ctx.emitResponseMeta = (key, value) => {+ if (value !== undefined) responseMeta[key] = value;+ };++ // WP3 warn mode: unknown keys were accepted above — surface them on the+ // structured channel (`_meta.warnings`, amendment 13 shape) so operators+ // and capable clients see the grace-period signal per call.+ if (unknownParamWarnings.length > 0) {+ ctx.emitResponseMeta('warnings', unknownParamWarnings);+ }+try {// Fail-closed gate for slug-bound OAuth clients, applied here because// this is the one path both MCP transports share. Per-op fences still@@ -421,17 +553,39 @@ export async function dispatchToolCall(});}const out: ToolResult = { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };+ // D8: model-visible loudness for empty retrievals. The body stays a bare+ // array (D3 — deployed thin-clients parse content[0] only), and a SECOND+ // text block carries the diagnosis the model actually sees. Structured+ // consumers read the same facts from _meta.retrieval below.+ if (Array.isArray(result) && result.length === 0 && responseMeta.retrieval) {+ const block = buildEmptyRetrievalBlock(responseMeta.retrieval);+ if (block) out.content.push({ type: 'text', text: block });+ }+ // WP3/D8: warn-mode unknown-param notices ride the same model-visible+ // extra-block mechanism, so the grace period actually corrects clients+ // (old thin-clients read content[0] only — skew-safe).+ if (unknownParamWarnings.length > 0) {+ out.content.push({ type: 'text', text: buildUnknownParamWarnBlock(unknownParamWarnings) });+ }+ // _meta assembly (WP2 amendment 9): one producer per top-level key,+ // each isolated — handler-emitted keys (retrieval, warnings) attach+ // BEFORE and independently of the metaHook, so a hot-memory hook+ // failure can never drop the retrieval channel. Per-key merge, never+ // wholesale assignment. See docs/protocol/MCP_META_CHANNELS.md.+ if (Object.keys(responseMeta).length > 0) {+ out._meta = { ...responseMeta };+ }// v0.31 (eD3 + eE4): best-effort _meta.brain_hot_memory injection.// The hook is wrapped in its own try/catch — any DB blip / cache miss /- // helper crash degrades to no `_meta` rather than flipping the whole+ // helper crash degrades to no hook keys rather than flipping the whole// tool call to error.if (opts.metaHook) {try {const meta = await opts.metaHook(name, ctx);- if (meta && Object.keys(meta).length > 0) out._meta = meta;+ if (meta && Object.keys(meta).length > 0) out._meta = { ...(out._meta ?? {}), ...meta };} catch (metaErr) {const msg = metaErr instanceof Error ? metaErr.message : String(metaErr);- ctx.logger.warn(`[mcp] _meta hook failed for ${name}: ${msg}; degrading to no-_meta`);+ ctx.logger.warn(`[mcp] _meta hook failed for ${name}: ${msg}; degrading to no hook keys`);}}return out;diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.tsindex d1e8c203ae..eebcd52b6b 100644--- a/src/mcp/http-transport.ts+++ b/src/mcp/http-transport.ts@@ -31,8 +31,11 @@ import { buildToolDefs } from './tool-defs.ts';import { operations } from '../core/operations.ts';import type { AuthInfo } from '../core/operations.ts';import { VERSION } from '../version.ts';-import { dispatchToolCall } from './dispatch.ts';-import { filterOpsForSurface } from './surface.ts';+import { dispatchToolCall, requestLogStatusForResult } from './dispatch.ts';+import { parseStrictParamsMode } from './validate-params.ts';+import { filterOpsForSurface, clampSurface, type McpSurface } from './surface.ts';+import { disabledOpsForPublishGates } from './publish-gates.ts';+import { loadConfig } from '../core/config.ts';import { buildDefaultLimiters, type RateLimiter } from './rate-limit.ts';import { sqlQueryForEngine } from '../core/sql-query.ts';import { parseLegacyTokenScope, parseTakesHoldersAllowList, coerceLegacyPermissions } from '../core/legacy-token-scope.ts';@@ -65,9 +68,13 @@ interface HttpTransportOptions {/*** MEMORY_VERBS v1 [c1]: tool-surface mode for this transport (the SECOND* HTTP path — the OAuth path in serve-http.ts carries its own). 'verbs' =- * exactly the five protocol verbs; 'full' (default) = everything.+ * exactly the seven protocol verbs; 'starter' (WP4) = the STARTER_OPS+ * daily-driver set; 'full' (default) = everything. Legacy bearer tokens+ * have no oauth_clients row, so there is no per-client surface here — the+ * transport surface (clamped by GBRAIN_MCP_FORCE_SURFACE, narrow-only)+ * applies to every caller.*/- surface?: 'verbs' | 'full';+ surface?: McpSurface;}interface AuthResult {@@ -164,12 +171,24 @@ export async function startHttpTransport(opts: HttpTransportOptions) {const bodyCap = envInt('GBRAIN_HTTP_MAX_BODY_BYTES', DEFAULT_BODY_CAP);const corsAllowlist = parseCorsAllowlist();// MEMORY_VERBS v1 [c1]: surface filter applies to THIS transport too —- // the advertised list AND dispatch (allowedOps), fail-closed.- const surface = opts.surface ?? 'full';- const surfacedOps = filterOpsForSurface(operations, surface);+ // the advertised list AND dispatch (allowedOps), fail-closed. WP4: the+ // GBRAIN_MCP_FORCE_SURFACE kill switch min()s in (narrow-only, FOV-6a);+ // resolved once at startup — this transport builds its tool list once.+ const surface = clampSurface(opts.surface ?? 'full');+ // WP1/D7: this is a network transport — localOnly ops (operator-filesystem+ // reach) never appear in its catalog, matching serve-http's filter. The+ // dispatch-layer backstop denies them even if a caller guesses the name.+ const surfacedOps = filterOpsForSurface(operations.filter(op => !op.localOnly), surface);const surfaceAllowedOps: ReadonlySet<string> | undefined =surface === 'full' ? undefined : new Set(surfacedOps.map(o => o.name));- const tools = buildToolDefs(surfacedOps);+ // WP3: strict-params schema emission resolved ONCE at startup from the FILE+ // config plane — this transport builds its tool list once, so a+ // `mcp.strict_params` flip needs a restart here (deliberate; the OAuth+ // serve-http path re-reads dual-plane per request). Dispatch-side+ // enforcement still resolves per call.+ const fileConfig = loadConfig();+ const strictParams = parseStrictParamsMode(fileConfig?.mcp?.strict_params) === 'reject';+ const tools = buildToolDefs(surfacedOps, { strictParams });/*** v0.41.3 (T6): single consolidated CORS header builder. Pre-fix there were@@ -391,9 +410,23 @@ export async function startHttpTransport(opts: HttpTransportOptions) {// tools/listif (method === 'tools/list') {+ // WP1/E5 truthful catalog on THIS transport too: publish-gated ops+ // (`Operation.publishGateKey`) are hidden while their gate resolves+ // off. Read per request (dual-plane, DB > file > false) so a+ // `gbrain config set mcp.publish_skills true` takes effect on the+ // next list with no restart — matching the OAuth transport. The+ // resolver never throws (read failure = hidden, the fail-closed+ // consent posture); the in-handler gates stay as the call-time+ // backstop. Pre-fix this transport listed the gated ops+ // unconditionally, so gates-off served the exact listed-but-denied+ // catalog lie E5 (test/truthful-catalog.e2e-lite.test.ts) pins out.+ const gateDisabled = await disabledOpsForPublishGates(engine, fileConfig);+ const visibleTools = gateDisabled.size === 0+ ? tools+ : tools.filter(t => !gateDisabled.has(t.name));logRequest(auth.tokenName!, 'tools/list', 'success', Date.now() - startedMs);return Response.json(- { result: { tools }, jsonrpc: '2.0', id },+ { result: { tools: visibleTools }, jsonrpc: '2.0', id },{ headers: corsHeaders(origin) },);}@@ -418,6 +451,9 @@ export async function startHttpTransport(opts: HttpTransportOptions) {}const result = await dispatchToolCall(engine, toolName, args, {remote: true,+ // WP1/D7: network transport — the dispatch-layer localOnly+ // backstop keys off this marker.+ transport: 'http',takesHoldersAllowList: auth.takesHoldersAllowList,sourceId: auth.sourceId,...(localFederated ? { localFederatedSourceIds: localFederated } : {}),@@ -427,8 +463,13 @@ export async function startHttpTransport(opts: HttpTransportOptions) {// MEMORY_VERBS v1 [c1/c2]: fail-closed surface enforcement here too....(surfaceAllowedOps ? { allowedOps: surfaceAllowedOps } : {}),surface,+ // WP4 (D2): this transport has no per-client rows, so its surface+ // IS the ceiling request_tools bounds catalog + persist by.+ surfaceCeiling: surface,});- const status = result.isError ? 'error' : 'success';+ // Same status taxonomy as the OAuth transport (denied_after_list /+ // success_with_warnings feed the amendment-33 metric + E4 usage).+ const status = requestLogStatusForResult(result);logRequest(auth.tokenName!, `tools/call:${toolName}`, status, Date.now() - startedMs);return Response.json({ result, jsonrpc: '2.0', id },diff --git a/src/mcp/publish-gates.ts b/src/mcp/publish-gates.tsnew file mode 100644index 0000000000..9c7868ed5b--- /dev/null+++ b/src/mcp/publish-gates.ts@@ -0,0 +1,68 @@+/**+ * Publish-gate resolution for the honest tools/list (WP1).+ *+ * Ops carrying `Operation.publishGateKey` are callable by remote callers only+ * when the named config gate resolves true. Before this module, the gates+ * fired only inside handlers, so gated tools were LISTED unconditionally and+ * denied at call time — the "worse than omitting them, looks broken" consumer+ * complaint. Network transports now consult this resolver per tools/list+ * request (config flips take effect on the next list, no restart — the+ * per-POST stateless server makes that free).+ *+ * Resolution per key is dual-plane, matching `readMcpPublishSkills`+ * (src/core/skill-catalog.ts): DB plane (`engine.getConfig`) wins, file plane+ * (`config.mcp.*`) is the fallback, absent on both = false. A FAILED gate+ * read also resolves false — hide-on-doubt matches the default-off consent+ * posture, and listing-on-doubt would recreate the listed-but-denied+ * complaint. This helper never throws and never fails a tools/list.+ */++import type { BrainEngine } from '../core/engine.ts';+import type { GBrainConfig } from '../core/config.ts';+import { operations, type Operation } from '../core/operations.ts';++export type PublishGateKey = NonNullable<Operation['publishGateKey']>;++/** Dual-plane gate read: DB > file > false; read failure = false (hidden). */+export async function readPublishGate(+ engine: BrainEngine,+ config: GBrainConfig | null | undefined,+ key: PublishGateKey,+): Promise<boolean> {+ let dbVal: string | null = null;+ try {+ dbVal = await engine.getConfig(key);+ } catch {+ // Engine without a config table / transient error → file plane decides.+ }+ if (dbVal != null) return dbVal === 'true';+ const mcp = config?.mcp as Record<string, unknown> | undefined;+ const fileKey = key.slice('mcp.'.length);+ return mcp?.[fileKey] === true;+}++/**+ * The set of op NAMES whose publish gate currently resolves off. tools/list+ * subtracts this set. One getConfig read per DISTINCT gate key per call+ * (two today, issued concurrently — one RTT of latency, not one per key),+ * deliberately not memoized — the per-request read is what makes+ * `gbrain config set mcp.publish_skills true` take effect without a+ * server restart.+ */+export async function disabledOpsForPublishGates(+ engine: BrainEngine,+ config: GBrainConfig | null | undefined,+): Promise<ReadonlySet<string>> {+ const gated = operations.filter(op => op.publishGateKey);+ if (gated.length === 0) return new Set();+ const keys = [...new Set(gated.map(op => op.publishGateKey as PublishGateKey))];+ const resolved = new Map<PublishGateKey, boolean>();+ await Promise.all(keys.map(async (key) => {+ resolved.set(key, await readPublishGate(engine, config, key));+ }));+ const disabled = new Set<string>();+ for (const op of gated) {+ if (!resolved.get(op.publishGateKey as PublishGateKey)) disabled.add(op.name);+ }+ return disabled;+}diff --git a/src/mcp/rate-limit.ts b/src/mcp/rate-limit.tsindex 6ec9579322..a8e5644122 100644--- a/src/mcp/rate-limit.ts+++ b/src/mcp/rate-limit.ts@@ -117,6 +117,19 @@ export class RateLimiter {}}+ /**+ * Return one token to a key's bucket (capped at the limit). For callers+ * that meter an action's SUCCESS, not its attempt: check() before the+ * action, refund() when the action turns out to be a no-op (e.g. a+ * concurrent-lock loser whose UPDATE affected 0 rows) so denials don't+ * consume the caller's budget. No-op for unknown keys.+ */+ refund(key: string): void {+ const bucket = this.buckets.get(key);+ if (!bucket) return;+ bucket.tokens = Math.min(this.opts.limit, bucket.tokens + 1);+ }+/** Test helper: current key count. */get size(): number {return this.buckets.size;diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex 927fd52b7f..5c6fb8fe0e 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -5,8 +5,9 @@ import type { BrainEngine } from '../core/engine.ts';import { operations } from '../core/operations.ts';import { VERSION } from '../version.ts';import { buildToolDefs } from './tool-defs.ts';-import { dispatchToolCall, validateParams, buildOperationContext } from './dispatch.ts';-import { filterOpsForSurface, allowedOpNames, type McpSurface } from './surface.ts';+import { dispatchToolCall, buildOperationContext } from './dispatch.ts';+import { validateParams, parseStrictParamsMode } from './validate-params.ts';+import { filterOpsForSurface, allowedOpNames, clampSurface, type McpSurface } from './surface.ts';import { getBrainHotMemoryMeta } from '../core/facts/meta-hook.ts';import { loadConfig } from '../core/config.ts';import {@@ -45,17 +46,26 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS);// MEMORY_VERBS v1 surface mode: 'full' (default — every op, byte-identical- // to pre-surface behavior) or 'verbs' (exactly the 5 protocol verbs).- // Enforced BOTH on the advertised list and in dispatch (fail-closed [c2]).- const surface: McpSurface = opts.surface ?? 'full';+ // to pre-surface behavior), 'starter' (WP4 daily-driver set), or 'verbs'+ // (exactly the 7 protocol verbs). Enforced BOTH on the advertised list and+ // in dispatch (fail-closed [c2]). WP4: the GBRAIN_MCP_FORCE_SURFACE kill+ // switch min()s in (narrow-only, FOV-6a). Note stdio keeps localOnly ops+ // on every surface tier that includes them — it IS the local surface (D7).+ const surface: McpSurface = clampSurface(opts.surface ?? 'full');const surfacedOps = filterOpsForSurface(operations, surface);const allowedOps = surface === 'full' ? undefined : allowedOpNames(operations, surface);+ // WP3: strict-params schema emission, resolved ONCE at startup from the+ // FILE config plane only — stdio has no per-request list cycle, so a+ // `mcp.strict_params` flip needs a serve restart here (deliberate; the+ // OAuth HTTP path re-reads dual-plane per request).+ const strictParams = parseStrictParamsMode(loadConfig()?.mcp?.strict_params) === 'reject';+// Generate tool definitions from operations. Extracted to buildToolDefs so// the subagent tool registry (v0.15+) can call the same mapper against a// filtered OPERATIONS subset instead of duplicating this shape.server.setRequestHandler(ListToolsRequestSchema, async () => ({- tools: buildToolDefs(surfacedOps),+ tools: buildToolDefs(surfacedOps, { strictParams }),}));// Dispatch tool calls via shared dispatch.ts (parity with HTTP transport).@@ -102,6 +112,9 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS// MEMORY_VERBS v1: fail-closed surface enforcement + usage attribution....(allowedOps ? { allowedOps } : {}),surface,+ // WP4 (D2): stdio has no per-client rows; its surface is the ceiling+ // request_tools bounds its catalog by (persist no-ops without auth).+ surfaceCeiling: surface,});});diff --git a/src/mcp/surface.ts b/src/mcp/surface.tsindex aac4210a09..235542c2e7 100644--- a/src/mcp/surface.ts+++ b/src/mcp/surface.ts@@ -1,12 +1,16 @@/**- * MEMORY_VERBS v1 — MCP tool-surface modes (Cathedral 1).+ * MEMORY_VERBS v1 + WP4 — MCP tool-surface modes.*- * 'full' (default) — every operation, verbs included. Existing installs- * see no change; e2e tool-count assertions hold.- * 'verbs' — EXACTLY the five frozen protocol verbs (ops marked- * `verb: true`). The quickstart surface: agents see- * recall/remember/entity/synthesize/forget and nothing- * else.+ * 'full' (default) — every operation, verbs included. Existing installs+ * see no change; e2e tool-count assertions hold.+ * 'starter' — the ~20-op daily-driver set (STARTER_OPS below):+ * the seven frozen verbs + the fallback daily ops ++ * whoami + the request_tools discovery meta-op. The+ * answer to the "85-tool wall" consumer complaint.+ * 'verbs' — EXACTLY the seven frozen protocol verbs (ops marked+ * `verb: true`). The quickstart surface. Its semantics+ * are frozen — 'starter' extends the ladder ABOVE it,+ * never changes it.** Enforcement is two-layer and fail-closed: ListTools advertises the filtered* set, AND dispatchToolCall receives the same set as `allowedOps` so a hidden@@ -14,29 +18,105 @@* alone leaves dispatch resolving the global catalog — codex c2).** Resolution: --surface flag > config `mcp_surface` > 'full'. Why default- * full: verbs is for agents and quickstarts; full preserves existing advanced- * tooling.+ * full: verbs/starter are for agents and quickstarts; full preserves existing+ * advanced tooling.+ *+ * WP4 (D2 CEILING): on the OAuth HTTP transport the server-resolved surface is+ * a CEILING, not the final answer — each request resolves+ * `min(ceiling, client row surface ?? DCR/config default)` via+ * `effectiveSurfaceForClient`, recomputed per request (amendment 20).+ * `GBRAIN_MCP_FORCE_SURFACE` is the incident kill switch: it min()s in on top+ * and can NEVER widen past the configured ceiling (FOV-6a) — widening requires+ * an explicit `--surface` restart.*/import type { Operation } from '../core/operations.ts';import type { GBrainConfig } from '../core/config.ts';+import type { BrainEngine } from '../core/engine.ts';+import { VERB_NAMES } from '../core/verbs.ts';+import { BRAIN_TOOL_ALLOWLIST } from '../core/minions/tools/brain-allowlist.ts';++export type McpSurface = 'verbs' | 'starter' | 'full';-export type McpSurface = 'verbs' | 'full';+/** Widening order for the D2 ceiling math: verbs < starter < full. */+const SURFACE_RANK: Record<McpSurface, number> = { verbs: 0, starter: 1, full: 2 };export function isMcpSurface(v: unknown): v is McpSurface {- return v === 'verbs' || v === 'full';+ return v === 'verbs' || v === 'starter' || v === 'full';+}++/** The narrower of two surfaces (verbs < starter < full). */+export function minSurface(a: McpSurface, b: McpSurface): McpSurface {+ return SURFACE_RANK[a] <= SURFACE_RANK[b] ? a : b;+}++/** True when `a` is strictly wider than `b` (used for the ceiling deny). */+export function surfaceWiderThan(a: McpSurface, b: McpSurface): boolean {+ return SURFACE_RANK[a] > SURFACE_RANK[b];}+/**+ * WP4 FOV-6b fallback for the daily-driver slice of STARTER_OPS.+ *+ * Provenance: the plan's STARTER_OPS derivation from the production+ * `mcp_request_log` histogram (30d window, keyed by token_name) had NOT+ * landed at implementation time (2026-08-13), so per FOV-6b this v1 set is+ * the fallback: the reviewed subagent brain-tool allow-list+ * (BRAIN_TOOL_ALLOWLIST — imported, never name-copied) plus the agent lane+ * (`submit_agent` / `get_agent_job`, FOV-4 — agent-scope clients must not be+ * stranded). Corrected later by `scripts/derive-starter-ops.ts` + the E3+ * advisor drift check once the histogram pull lands.+ */+const FALLBACK_DAILY_OPS: readonly string[] = [+ ...BRAIN_TOOL_ALLOWLIST,+ 'submit_agent',+ 'get_agent_job',+];++/**+ * The 'starter' surface membership set (WP4). Composed PROGRAMMATICALLY —+ * the verb slice is a spread of VERB_NAMES (ENG-1: post-#4028 that is SEVEN+ * verbs including context_pack/delta; never a hand-count), the daily slice+ * is the FOV-6b fallback above, plus `whoami` (identity) and `request_tools`+ * (the D4 discovery meta-op: listed on starter + full, never verbs).+ *+ * Membership is pinned by test/mcp-surface.test.ts: every name here must+ * exist in `operations`, and allowedOpNames(verbs) ⊆ starter ⊆ full holds+ * (monotonicity, ENG-1).+ */+export const STARTER_OPS: ReadonlySet<string> = new Set([+ ...VERB_NAMES,+ ...FALLBACK_DAILY_OPS,+ 'whoami',+ 'request_tools',+]);++/**+ * The never-remove STARTER_OPS core: the seven frozen verbs, identity+ * (`whoami`), discovery (`request_tools`), and the agent lane+ * (`submit_agent`/`get_agent_job` — FOV-4: agent-scope clients must not be+ * stranded). Usage-driven re-derivation (`scripts/derive-starter-ops.ts`)+ * and the advisor drift check (collect-mcp-client-fit) both consume THIS+ * set so "always included" has exactly one definition.+ */+export const ALWAYS_INCLUDED_STARTER_OPS: ReadonlySet<string> = new Set([+ ...VERB_NAMES,+ 'whoami',+ 'request_tools',+ 'submit_agent',+ 'get_agent_job',+]);+/** Strict flag parser — unknown values reject loudly (parseStdioIdleTimeout pattern). */export function parseSurfaceFlag(args: string[]): McpSurface | null {const idx = args.indexOf('--surface');if (idx < 0) return null;const raw = args[idx + 1];if (raw === undefined || raw.startsWith('--')) {- throw new Error(`--surface requires a value: verbs | full`);+ throw new Error(`--surface requires a value: verbs | starter | full`);}if (!isMcpSurface(raw)) {- throw new Error(`Unknown --surface "${raw}". Use: verbs (the 5 memory verbs) | full (all operations, default)`);+ throw new Error(`Unknown --surface "${raw}". Use: verbs (the 7 memory verbs) | starter (the ~20 daily-driver ops) | full (all operations, default)`);}return raw;}@@ -53,10 +133,130 @@ export function resolveSurface(export function filterOpsForSurface(ops: Operation[], surface: McpSurface): Operation[] {if (surface === 'full') return ops;- return ops.filter(op => op.verb === true);+ // FROZEN: 'verbs' is EXACTLY `op.verb === true` (MEMORY_VERBS v1) — starter+ // extends the ladder above it and must never alter these semantics.+ if (surface === 'verbs') return ops.filter(op => op.verb === true);+ return ops.filter(op => STARTER_OPS.has(op.name));}/** The fail-closed allow-set handed to dispatchToolCall. */export function allowedOpNames(ops: Operation[], surface: McpSurface): ReadonlySet<string> {return new Set(filterOpsForSurface(ops, surface).map(o => o.name));}++// ---------------------------------------------------------------------------+// WP4 — kill switch + per-client (D2 ceiling) resolution+// ---------------------------------------------------------------------------++let warnedBadForceValue = false;++/**+ * `GBRAIN_MCP_FORCE_SURFACE` — incident kill switch (amendment 21,+ * env-above-config per the pace-mode precedent). NARROW-ONLY (FOV-6a):+ * consumers min() it into the resolved surface, so it can clamp a+ * misbehaving deployment down but can never widen past the configured+ * ceiling. Unknown values are ignored with a one-time warn (ignoring can+ * only leave the surface as configured — it never widens anything).+ */+export function readForceSurfaceEnv(+ warn: (msg: string) => void = (msg) => process.stderr.write(`${msg}\n`),+): McpSurface | null {+ const raw = process.env.GBRAIN_MCP_FORCE_SURFACE;+ if (raw === undefined || raw === '') return null;+ if (isMcpSurface(raw)) return raw;+ if (!warnedBadForceValue) {+ warnedBadForceValue = true;+ warn(`[mcp] ignoring unknown GBRAIN_MCP_FORCE_SURFACE="${raw}" (use verbs | starter | full); surface stays as configured`);+ }+ return null;+}++/** min() the kill switch into a resolved surface. Narrow-only by construction. */+export function clampSurface(+ surface: McpSurface,+ warn?: (msg: string) => void,+): McpSurface {+ const force = readForceSurfaceEnv(warn);+ return force ? minSurface(surface, force) : surface;+}++// Warn-once-per-client bookkeeping for unknown oauth_clients.surface values+// (amendment 18). Bounded so attacker-controlled client ids can't grow it.+const warnedUnknownRowSurface = new Set<string>();+const WARNED_CLIENTS_CAP = 10_000;++/** Test seam: reset the warn-once caches. */+export function __resetSurfaceWarnCachesForTests(): void {+ warnedUnknownRowSurface.clear();+ warnedBadForceValue = false;+}++/**+ * Parse an `oauth_clients.surface` row value (amendment 18). The column's+ * value space is documented OPEN — deferred client tiers will write tier+ * names into this same column — so an unrecognized value is IGNORED (falls+ * back to server/config resolution) with a warn-log once per client, never+ * an auth failure.+ */+export function resolveClientRowSurface(+ raw: unknown,+ clientId: string,+ warn: (msg: string) => void = (msg) => process.stderr.write(`${msg}\n`),+): McpSurface | null {+ if (raw === null || raw === undefined) return null;+ if (isMcpSurface(raw)) return raw;+ if (!warnedUnknownRowSurface.has(clientId)) {+ if (warnedUnknownRowSurface.size >= WARNED_CLIENTS_CAP) warnedUnknownRowSurface.clear();+ warnedUnknownRowSurface.add(clientId);+ warn(`[mcp] client ${clientId} carries unrecognized oauth_clients.surface value; ignoring it and falling back to the server/config surface (rescope with: gbrain auth rescope-client ${clientId} --surface verbs|starter|full|clear)`);+ }+ return null;+}++/**+ * Dual-plane resolution for `mcp.default_surface_dcr` — the surface applied+ * to clients whose row surface is NULL (oauth_clients carries no DCR-origin+ * marker, so the default applies to ALL null-surface clients; operators+ * pre-seed important clients with `gbrain auth rescope-client <id> --surface+ * full`). DB plane wins, file plane falls back, absent/unparseable on both =+ * null (caller falls back to the server ceiling — pre-WP4 behavior). A+ * failed DB read falls to the file plane; surface resolution must never take+ * a request down.+ */+export async function resolveDefaultClientSurface(+ engine: BrainEngine,+ config: GBrainConfig | null | undefined,+): Promise<McpSurface | null> {+ try {+ const dbVal = await engine.getConfig('mcp.default_surface_dcr');+ if (isMcpSurface(dbVal)) return dbVal;+ if (dbVal != null) return null; // set but unrecognized → ignore (open value space)+ } catch {+ // Engine without a config table / transient error → file plane decides.+ }+ const fileVal = (config?.mcp as Record<string, unknown> | undefined)?.default_surface_dcr;+ return isMcpSurface(fileVal) ? fileVal : null;+}++/**+ * D2 CEILING resolution — the per-request effective surface on the OAuth+ * HTTP transport:+ *+ * effective = clamp(min(server ceiling, client row surface ?? default ?? ceiling))+ *+ * where `clamp` folds in the GBRAIN_MCP_FORCE_SURFACE kill switch+ * (narrow-only, FOV-6a). A verbs-pinned server with a `full` client row+ * still serves verbs (pinned by test); a client can request a narrower+ * surface than the ceiling and get it.+ */+export function effectiveSurfaceForClient(opts: {+ ceiling: McpSurface;+ /** Parsed row value (resolveClientRowSurface); null = no per-client surface. */+ clientSurface: McpSurface | null;+ /** mcp.default_surface_dcr resolution; null = unset (fall back to ceiling). */+ defaultSurface: McpSurface | null;+ warn?: (msg: string) => void;+}): McpSurface {+ const requested = opts.clientSurface ?? opts.defaultSurface ?? opts.ceiling;+ return clampSurface(minSurface(opts.ceiling, requested), opts.warn);+}diff --git a/src/mcp/tool-catalog.ts b/src/mcp/tool-catalog.tsnew file mode 100644index 0000000000..92f74cca05--- /dev/null+++ b/src/mcp/tool-catalog.ts@@ -0,0 +1,84 @@+/**+ * tool-catalog.ts — renderer for the generated docs/TOOL_CATALOG.md (E6).+ *+ * Config-INDEPENDENT by design: no engine, no config reads, no gate+ * resolution — the catalog is the operations array plus static surface+ * metadata (STARTER_OPS membership, publish-gate keys), rendered through+ * `buildToolDefs`'s non-strict shape so the doc names/describes exactly what+ * a default tools/list emits. Deterministic: no timestamps, stable sort+ * everywhere — the committed doc must byte-match a fresh render+ * (scripts/check-tool-catalog-fresh.sh, wired into `bun run verify`).+ *+ * Non-localOnly ops ONLY: localOnly ops never appear on a network catalog,+ * so documenting them here would recreate the listed-but-uncallable class+ * the honest-catalog wave exists to kill.+ *+ * Area names are NON-CONTRACTUAL (Operation.area, amendment 22) — renaming+ * or regrouping is never a breaking change; the per-op rows are the stable+ * content.+ */++import { operations, type Operation } from '../core/operations.ts';+import { STARTER_OPS } from './surface.ts';+import { buildToolDefs } from './tool-defs.ts';++/** First sentence of a description (up to the first '.', '!' or '?' + space). */+export function firstSentence(text: string): string {+ const oneLine = text.replace(/\s+/g, ' ').trim();+ const m = oneLine.match(/^(.*?[.!?])\s/);+ return (m ? m[1] : oneLine).trim();+}++function escapeCell(text: string): string {+ return text.replace(/\|/g, '\\|');+}++export function renderToolCatalogMarkdown(): string {+ const ops = operations.filter((op) => !op.localOnly);+ const defs = new Map(buildToolDefs(ops).map((d) => [d.name, d]));++ const byArea = new Map<string, Operation[]>();+ for (const op of ops) {+ const area = op.area ?? 'other';+ const list = byArea.get(area) ?? [];+ list.push(op);+ byArea.set(area, list);+ }+ const areas = [...byArea.keys()].sort();++ const lines: string[] = [];+ lines.push('# MCP tool catalog');+ lines.push('');+ lines.push('<!-- GENERATED FILE — do not edit by hand. -->');+ lines.push('<!-- Regenerate: bun run scripts/generate-tool-catalog.ts -->');+ lines.push('<!-- Freshness-guarded by scripts/check-tool-catalog-fresh.sh (bun run verify). -->');+ lines.push('');+ lines.push(+ `Every non-localOnly operation on the MCP surface: ${ops.length} tools across ` ++ `${areas.length} areas. **Starter** marks membership in the ~${STARTER_OPS.size}-op ` ++ '`starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be ' ++ 'true before remote callers see/call the op (`gbrain config set <key> true`). ' ++ 'What a given token actually sees is further filtered per request by scope, ' ++ 'bound-client fence, publish gates, and the per-client surface — see ' ++ '`docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.',+ );+ lines.push('');++ for (const area of areas) {+ const areaOps = byArea.get(area)!.slice().sort((a, b) => (a.name < b.name ? -1 : 1));+ lines.push(`## ${area}`);+ lines.push('');+ lines.push('| Tool | Description | Scope | Starter | Gate |');+ lines.push('|---|---|---|---|---|');+ for (const op of areaOps) {+ const def = defs.get(op.name);+ const desc = escapeCell(firstSentence(def?.description ?? op.description));+ const starter = STARTER_OPS.has(op.name) ? 'yes' : '';+ const gate = op.publishGateKey ? `\`${op.publishGateKey}\`` : '';+ lines.push(`| \`${op.name}\` | ${desc} | ${op.scope ?? 'read'} | ${starter} | ${gate} |`);+ }+ lines.push('');+ }++ return lines.join('\n');+}diff --git a/src/mcp/tool-defs.ts b/src/mcp/tool-defs.tsindex 289923715b..a34ca77c0b 100644--- a/src/mcp/tool-defs.ts+++ b/src/mcp/tool-defs.ts@@ -7,6 +7,8 @@ export interface McpToolDef {type: 'object';properties: Record<string, unknown>;required: string[];+ /** WP3 (D14.1): emitted ONLY when buildToolDefs runs with strictParams. */+ additionalProperties?: false;};/*** MCP ToolAnnotations (SDK 1.29+), emitted ONLY when the op defines them —@@ -48,18 +50,54 @@ export function paramDefToSchema(p: ParamDef): Record<string, unknown> {};}-export function buildToolDefs(ops: Operation[]): McpToolDef[] {+/**+ * WP3 (D14.1): when a strict schema closes the property set with+ * `additionalProperties: false`, the two dispatch-allowlisted passthrough+ * keys MUST be declared in `properties` — schema-validating clients+ * (Gemini strict, OpenAI structured outputs) would otherwise strip+ * `_meta.session_id` and `dry_run` from arguments before they ever reach+ * the server. Declared only when the op doesn't already declare them+ * (several ops carry a real `dry_run` param).+ */+function strictPassthroughProperties(op: Operation): Record<string, unknown> {+ return {+ ...('_meta' in op.params ? {} : {+ _meta: {+ type: 'object',+ description: 'MCP client metadata passthrough (e.g. session id); not an operation parameter.',+ },+ }),+ ...('dry_run' in op.params ? {} : { dry_run: { type: 'boolean' } }),+ };+}++/**+ * Build MCP tool definitions from operations.+ *+ * Default emission (no opts / strictParams false) is BYTE-IDENTICAL to the+ * pre-WP3 output — pinned by test/mcp-tool-defs.test.ts. With+ * `strictParams: true` (mcp.strict_params = 'reject'), each inputSchema+ * additionally declares the `_meta`/`dry_run` passthrough keys and closes+ * the schema with `additionalProperties: false`, keeping client-side+ * validation aligned with the server's reject posture.+ */+export function buildToolDefs(ops: Operation[], opts?: { strictParams?: boolean }): McpToolDef[] {+ const strict = opts?.strictParams === true;return ops.map(op => ({name: op.name,description: op.description,inputSchema: {type: 'object' as const,- properties: Object.fromEntries(- Object.entries(op.params).map(([k, v]) => [k, paramDefToSchema(v)]),- ),+ properties: {+ ...Object.fromEntries(+ Object.entries(op.params).map(([k, v]) => [k, paramDefToSchema(v)]),+ ),+ ...(strict ? strictPassthroughProperties(op) : {}),+ },required: Object.entries(op.params).filter(([, v]) => v.required).map(([k]) => k),+ ...(strict ? { additionalProperties: false as const } : {}),},...(op.annotations ? { annotations: op.annotations } : {}),}));diff --git a/src/mcp/validate-params.ts b/src/mcp/validate-params.tsnew file mode 100644index 0000000000..c4e237efd6--- /dev/null+++ b/src/mcp/validate-params.ts@@ -0,0 +1,187 @@+/**+ * Param normalization + validation for MCP tool dispatch (WP3).+ *+ * Extracted from src/mcp/dispatch.ts so the branch-heavy validation logic has+ * a direct unit-test surface (amendment 12). Call order is load-bearing and+ * preserved from the dispatch layer: `normalizeOptionalParams` FIRST (absent+ * idioms become truly absent), THEN `validateParams` (types + enums), THEN+ * `findUnknownParams` (strict/warn unknown-key detection on the normalized+ * object — so a null/'' optional idiom is never mistaken for an unknown key).+ *+ * dispatch.ts re-exports `normalizeOptionalParams` and `validateParams` so+ * existing imports keep working.+ */++import type { Operation } from '../core/operations.ts';+import type { BrainEngine } from '../core/engine.ts';+import type { GBrainConfig } from '../core/config.ts';+import { suggestNearest } from '../core/levenshtein.ts';++/** Validate required params exist and have the expected type. Returns null on success, error message on failure. */+export function validateParams(op: Operation, params: Record<string, unknown>): string | null {+ for (const [key, def] of Object.entries(op.params)) {+ if (def.required && (params[key] === undefined || params[key] === null)) {+ return `Missing required parameter: ${key}`;+ }+ if (params[key] !== undefined && params[key] !== null) {+ const val = params[key];+ const expected = def.type;+ if (expected === 'string' && typeof val !== 'string') return `Parameter "${key}" must be a string`;+ if (expected === 'number' && typeof val !== 'number') return `Parameter "${key}" must be a number`;+ if (expected === 'boolean' && typeof val !== 'boolean') return `Parameter "${key}" must be a boolean`;+ if (expected === 'object' && (typeof val !== 'object' || Array.isArray(val))) return `Parameter "${key}" must be an object`;+ if (expected === 'array' && !Array.isArray(val)) return `Parameter "${key}" must be an array`;+ // WP3: enum membership is a TYPE error, enforced in BOTH strict modes+ // (warn and reject). The message names the declared values only — the+ // caller's raw value is never echoed (it can land in persistent logs+ // via the error_message column; declared values are safe by definition).+ if (def.enum && typeof val === 'string' && !def.enum.includes(val)) {+ return `Parameter "${key}" must be one of: ${def.enum.join(', ')}`;+ }+ }+ }+ return null;+}++/**+ * Normalize the absent-idioms real MCP clients send for OPTIONAL params+ * before validation and dispatch: `null` (any type) and `''` (string-typed+ * params) become "not provided".+ *+ * Why: non-Claude models routinely fill optional params with `""` or `null`+ * instead of omitting them. `validateParams` already reads null as absent+ * for the required-param check (see above); handlers do not — some guard+ * with `typeof p.x === 'string' && p.x.length > 0` (entity / session_id in+ * `recall`), others with `p.x !== undefined` (since in `recall`), so+ * `recall {since: ""}` silently returned zero facts where the same call+ * with `since` omitted returns rows. Normalizing once at the shared+ * dispatch layer gives every handler one canonical absence instead of+ * per-handler guards.+ *+ * Deliberately narrow:+ * - Required params are untouched — null on a required param still fails+ * validation loudly, and `''` on a required string still reaches the+ * handler exactly as before.+ * - Type-mismatched junk is untouched — `limit: ""` keeps its loud+ * "must be a number" error rather than silently succeeding.+ * - Undeclared keys are untouched (they were already ignored).+ * Copy-on-write: callers' param objects are never mutated.+ */+export function normalizeOptionalParams(op: Operation, params: Record<string, unknown>): Record<string, unknown> {+ let out: Record<string, unknown> | null = null;+ for (const [key, def] of Object.entries(op.params)) {+ if (def.required) continue;+ const val = params[key];+ const isAbsentIdiom = val === null || (val === '' && def.type === 'string');+ if (!isAbsentIdiom) continue;+ if (out === null) out = { ...params };+ delete out[key];+ }+ return out ?? params;+}++// ---------------------------------------------------------------------------+// WP3 — strict/warn unknown-argument validation+// ---------------------------------------------------------------------------++/**+ * Top-level keys that are legitimate on ANY tool call without being declared+ * in the op's params: `_meta` is the MCP client metadata slot (several+ * clients fold it into `arguments`; dispatch reads `_meta.session_id` from+ * it), and `dry_run` is the contract-wide preview flag consumed by+ * buildOperationContext.+ */+export const UNKNOWN_PARAM_ALLOWLIST: ReadonlySet<string> = new Set(['_meta', 'dry_run']);++/**+ * `_meta.warnings` entry shape (amendment 13) — documented in+ * docs/protocol/MCP_META_CHANNELS.md. `suggestion` is the nearest DECLARED+ * param name when one is within edit distance; the candidates are ONLY the+ * op's declared params, so a suggestion can never leak another op's surface.+ */+export interface UnknownParamWarning {+ code: 'unknown_param';+ param: string;+ suggestion?: string;+}++/**+ * Detect submitted top-level keys the op does not declare. Runs on the+ * NORMALIZED params object (normalizeOptionalParams only deletes DECLARED+ * optional keys, so null/'' absent-idioms are never reported here).+ *+ * Privacy note (amendment 11 / C8 class): the raw unknown key names returned+ * here reach the CALLER (warn block, `_meta.warnings`, reject `suggestion`)+ * but must NEVER be written to `mcp_request_log` — the redacted summarizer+ * counts unknown keys without naming them, and the reject-mode envelope keeps+ * the raw key out of `message` (the one field serve-http persists to+ * error_message).+ */+export function findUnknownParams(op: Operation, params: Record<string, unknown>): UnknownParamWarning[] {+ const declared = Object.keys(op.params);+ const declaredSet = new Set(declared);+ const warnings: UnknownParamWarning[] = [];+ for (const key of Object.keys(params)) {+ if (declaredSet.has(key) || UNKNOWN_PARAM_ALLOWLIST.has(key)) continue;+ const nearest = suggestNearest(key, declared);+ warnings.push({ code: 'unknown_param', param: key, ...(nearest ? { suggestion: nearest } : {}) });+ }+ return warnings;+}++/**+ * Render the model-visible warn-mode notice lines (one per unknown key) that+ * dispatch appends as an extra text content block on the RESULT — the same+ * D8 second-block mechanism that carries empty-retrieval loudness, so the+ * grace period actually corrects clients instead of warning into a void.+ */+export function buildUnknownParamWarnBlock(warnings: UnknownParamWarning[]): string {+ return warnings+ .map(w => w.suggestion+ ? `warning: unknown parameter "${w.param}" ignored — did you mean "${w.suggestion}"? A future release rejects unknown parameters.`+ : `warning: unknown parameter "${w.param}" ignored. A future release rejects unknown parameters.`)+ .join('\n');+}++export type StrictParamsMode = 'warn' | 'reject';++/** Strict value parse: anything but the two known modes resolves null. */+export function parseStrictParamsMode(v: unknown): StrictParamsMode | null {+ return v === 'warn' || v === 'reject' ? v : null;+}++/**+ * Dual-plane resolution for `mcp.strict_params`: DB plane (`engine.getConfig`)+ * wins, file plane (`config.mcp.strict_params`) is the fallback, absent or+ * unparseable on both = 'warn' (the grace-period default). A failed DB read+ * holds the LAST successfully resolved DB mode (per process) before falling+ * to the file plane — a transient config outage on a reject-mode server must+ * not silently re-open the warn-mode grace period. Validation posture never+ * takes a tool call down. Resolved once per dispatch (amendment 12);+ * serve-http's tools/list also reads it per request so `gbrain config set+ * mcp.strict_params reject` flips the advertised schema without a restart+ * (stdio + the legacy bearer transport resolve once at startup — restart to+ * flip there, deliberate).+ */+let lastKnownDbStrictMode: StrictParamsMode | null = null;++/** Test seam: clear the last-known-good DB mode between cases. */+export function resetStrictParamsModeCache(): void {+ lastKnownDbStrictMode = null;+}++export async function resolveStrictParamsMode(+ engine: BrainEngine,+ config: GBrainConfig | null | undefined,+): Promise<StrictParamsMode> {+ try {+ const dbMode = parseStrictParamsMode(await engine.getConfig('mcp.strict_params'));+ lastKnownDbStrictMode = dbMode;+ if (dbMode) return dbMode;+ } catch {+ // Engine without a config table / transient error: last-known-good DB+ // mode wins; with no prior successful read, the file plane decides.+ if (lastKnownDbStrictMode) return lastKnownDbStrictMode;+ }+ return parseStrictParamsMode(config?.mcp?.strict_params) ?? 'warn';+}diff --git a/src/schema.sql b/src/schema.sqlindex 28b8e29eb7..b4fe1cf166 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -660,6 +660,11 @@ CREATE TABLE IF NOT EXISTS oauth_clients (bound_brain_id TEXT NULL,bound_slug_prefixes TEXT[] NULL,bound_max_concurrent INTEGER NOT NULL DEFAULT 1,+ -- WP4 (v127): per-client MCP tool surface + who set it ('operator' |+ -- 'self' | 'dcr_default'). Value space is OPEN (future client tiers write+ -- tier names into surface); NULL = server/config surface resolution.+ surface TEXT NULL,+ surface_set_by TEXT NULL,created_at TIMESTAMPTZ NOT NULL DEFAULT now());-- v0.34.1 (#861, D13 + #876): source_id is the write-source scope;@@ -944,6 +949,9 @@ CREATE INDEX IF NOT EXISTS idx_minion_jobs_parent ON minion_jobs(parent_job_id);CREATE INDEX IF NOT EXISTS idx_minion_jobs_timeout ON minion_jobs (timeout_at) WHERE status = 'active' AND timeout_at IS NOT NULL;CREATE INDEX IF NOT EXISTS idx_minion_jobs_parent_status ON minion_jobs (parent_job_id, status) WHERE parent_job_id IS NOT NULL;CREATE UNIQUE INDEX IF NOT EXISTS uniq_minion_jobs_idempotency ON minion_jobs (idempotency_key) WHERE idempotency_key IS NOT NULL;+-- WP4/WP5 (v127, ENG-10): wedge-signal index — covers the queue-health count+-- FILTERs and max(updated_at) reads in queryWedgeSignals (supervisor.ts).+CREATE INDEX IF NOT EXISTS idx_minion_jobs_queue_status_updated ON minion_jobs (queue, status, updated_at);-- Inbox table for sidechannel messagingCREATE TABLE IF NOT EXISTS minion_inbox (diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.mdindex 8115f6bf2d..8b9363e476 100644--- a/templates/bootstrap/template-repo/README.md+++ b/templates/bootstrap/template-repo/README.md@@ -1,6 +1,6 @@# gbrain agent workspace — template-<!-- gbrain-template-stamp: 0.45.12.0 -->+<!-- gbrain-template-stamp: 0.45.13.0 -->This repository is the **"Use this template"** distribution artifact for a[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the samediff --git a/test/advisor-mcp-client-fit.test.ts b/test/advisor-mcp-client-fit.test.tsnew file mode 100644index 0000000000..7e21ced413--- /dev/null+++ b/test/advisor-mcp-client-fit.test.ts@@ -0,0 +1,235 @@+/**+ * E3 (amendment 29 + D12) — the mcp-client-fit advisor collector.+ *+ * Pins:+ * - per-client starter fit: full-surface client whose 30d distinct-op set+ * ⊆ STARTER_OPS gets the exact rescope command+ * - local vs REMOTE redaction: remote output aggregates counts, never+ * names a client id (amendment 29)+ * - exclusions: automation-shaped clients (D12), below-threshold volume,+ * already-narrowed clients, legacy tokens without an oauth_clients row+ * - set-level drift: top-used op missing from STARTER_OPS + starter+ * members unused for 90d+ * - nag snooze: unchanged findings go quiet after the ceiling; a changed+ * usage fingerprint re-surfaces them+ *+ * Hermetic in-memory PGLite + a tmpdir nag-state path (test seam — never+ * touches ~/.gbrain).+ */++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { mkdtempSync, rmSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import {+ collectMcpClientFit,+ __setUsageNagStatePathForTests,+ MIN_CALLS_FOR_FIT,+} from '../src/core/advisor/collect-mcp-client-fit.ts';+import { COLLECTORS } from '../src/core/advisor/run.ts';+import { STARTER_OPS, ALWAYS_INCLUDED_STARTER_OPS } from '../src/mcp/surface.ts';+import { operations } from '../src/core/operations.ts';+import type { AdvisorContext } from '../src/core/advisor/types.ts';++let engine: PGLiteEngine;+let nagDir: string;+let nagSeq = 0;++// Programmatic op picks so the test survives STARTER_OPS re-derivation.+const starterOp = 'recall'; // VERB_NAMES ⊆ STARTER_OPS by construction+const starterOp2 = 'whoami';+const nonStarterOp = operations.find((o) => !o.localOnly && !STARTER_OPS.has(o.name))!.name;++function ctx(over: Partial<AdvisorContext> = {}): AdvisorContext {+ return {+ engine,+ config: {} as AdvisorContext['config'],+ version: '0.0.0.0',+ workspace: null,+ skillsDir: null,+ now: new Date(),+ remote: false,+ ...over,+ };+}++async function seedCalls(token: string, operation: string, count: number): Promise<void> {+ for (let i = 0; i < count; i++) {+ await engine.executeRaw(+ `INSERT INTO mcp_request_log (token_name, agent_name, operation, latency_ms, status)+ VALUES ($1, $1, $2, 5, 'success')`,+ [token, operation],+ );+ }+}++async function seedClient(clientId: string, surface: string | null): Promise<void> {+ await engine.executeRaw(+ `INSERT INTO oauth_clients (client_id, client_name, surface)+ VALUES ($1, $1, $2)+ ON CONFLICT (client_id) DO UPDATE SET surface = $2`,+ [clientId, surface],+ );+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ nagDir = mkdtempSync(join(tmpdir(), 'gbrain-fit-nag-'));++ // fit-client: full surface (NULL row), 12 calls all inside STARTER_OPS.+ await seedClient('fit-client', null);+ await seedCalls('fit-client', starterOp, 8);+ await seedCalls('fit-client', starterOp2, 4);++ // narrowed-client: already on starter — never flagged.+ await seedClient('narrowed-client', 'starter');+ await seedCalls('narrowed-client', starterOp, MIN_CALLS_FOR_FIT + 5);++ // busy-client: full surface but uses a non-starter op — not a fit; drives+ // the drift check's "top-used op missing from STARTER_OPS" arm.+ await seedClient('busy-client', null);+ await seedCalls('busy-client', nonStarterOp, MIN_CALLS_FOR_FIT + 2);++ // automation-client: >90% boundary calls — excluded everywhere (D12).+ await seedClient('automation-client', null);+ await seedCalls('automation-client', 'context_pack', 30);++ // low-volume-client: fits but below the alert threshold.+ await seedClient('low-volume-client', null);+ await seedCalls('low-volume-client', starterOp, MIN_CALLS_FOR_FIT - 1);++ // legacy-token: usage without an oauth_clients row — no rescope target.+ await seedCalls('legacy-token', starterOp, MIN_CALLS_FOR_FIT + 5);+}, 120_000);++afterAll(async () => {+ __setUsageNagStatePathForTests(null);+ await engine.disconnect();+ rmSync(nagDir, { recursive: true, force: true });+});++beforeEach(() => {+ // Fresh nag file per test so snooze state never leaks between tests.+ nagSeq++;+ __setUsageNagStatePathForTests(join(nagDir, `nag-${nagSeq}.json`));+});++describe('registration', () => {+ test('collector is registered in the advisor COLLECTORS array', () => {+ expect(COLLECTORS.some((c) => c.id === 'mcp-client-fit')).toBe(true);+ });+});++describe('per-client starter fit (local)', () => {+ test('full-surface client with starter-only usage gets the exact rescope command', async () => {+ const findings = await collectMcpClientFit.collect(ctx());+ const fit = findings.find((f) => f.id === 'mcp_starter_fit:fit-client');+ expect(fit).toBeDefined();+ expect(fit!.severity).toBe('info');+ expect(fit!.fix.command_argv).toEqual([+ 'gbrain', 'auth', 'rescope-client', 'fit-client', '--surface', 'starter',+ ]);+ });++ test('excluded: narrowed, below-threshold, automation-shaped, legacy, non-fitting', async () => {+ const findings = await collectMcpClientFit.collect(ctx());+ const ids = findings.map((f) => f.id);+ expect(ids).not.toContain('mcp_starter_fit:narrowed-client');+ expect(ids).not.toContain('mcp_starter_fit:low-volume-client');+ expect(ids).not.toContain('mcp_starter_fit:automation-client');+ expect(ids).not.toContain('mcp_starter_fit:legacy-token');+ expect(ids).not.toContain('mcp_starter_fit:busy-client');+ });+});++describe('remote redaction (amendment 29)', () => {+ test('remote output aggregates counts and never names a client id', async () => {+ const findings = await collectMcpClientFit.collect(ctx({ remote: true }));+ const agg = findings.find((f) => f.id === 'mcp_starter_fit_aggregate');+ expect(agg).toBeDefined();+ expect(agg!.title).toContain('1 MCP client');+ expect(agg!.title).toContain('run `gbrain advisor` on the host');+ expect(agg!.fix.command_argv).toBeNull();+ // No per-client finding, and no client identifier anywhere in the output.+ const serialized = JSON.stringify(findings);+ expect(serialized).not.toContain('fit-client');+ expect(findings.some((f) => f.id.startsWith('mcp_starter_fit:'))).toBe(false);+ });++ test('remote runs never write nag state (read-only op)', async () => {+ const path = join(nagDir, `nag-${nagSeq}.json`);+ await collectMcpClientFit.collect(ctx({ remote: true }));+ expect(existsSync(path)).toBe(false);+ });+});++describe('set-level drift', () => {+ test('names top-used ops missing from STARTER_OPS and long-unused starter members', async () => {+ const findings = await collectMcpClientFit.collect(ctx());+ const drift = findings.find((f) => f.id === 'mcp_starter_ops_drift');+ expect(drift).toBeDefined();+ // busy-client made nonStarterOp a top-used op that starter lacks.+ expect(drift!.detail).toContain(nonStarterOp);+ // The fixture uses only two starter ops, so some starter member+ // (excluding ALWAYS_INCLUDED_STARTER_OPS) is unused.+ expect(drift!.detail).toContain('unused for 90d');+ expect(drift!.detail).toContain('derive-starter-ops');+ });++ test('agent-lane ops are always-included — never flagged as unused starter members', async () => {+ const findings = await collectMcpClientFit.collect(ctx());+ const drift = findings.find((f) => f.id === 'mcp_starter_ops_drift');+ expect(drift).toBeDefined();+ // No fixture client ever calls the agent lane, yet it must not read as+ // drift: it is in ALWAYS_INCLUDED_STARTER_OPS by construction (pre-fix,+ // the collector's local always-set omitted it → a perpetual finding).+ expect(drift!.detail).not.toContain('submit_agent');+ expect(drift!.detail).not.toContain('get_agent_job');+ });++ test('ALWAYS_INCLUDED_STARTER_OPS ⊆ STARTER_OPS (an always-member outside starter would be unfixable drift)', () => {+ for (const op of ALWAYS_INCLUDED_STARTER_OPS) {+ expect(STARTER_OPS.has(op)).toBe(true);+ }+ });+});++describe('nag snooze (escalate-then-suppress)', () => {+ test('unchanged finding goes quiet after the ceiling; the drift finding too', async () => {+ let last: string[] = [];+ // Ceiling is 3 displays (DEFAULT_NAG_CEILING): first + 2 reminders.+ for (let run = 1; run <= 4; run++) {+ const findings = await collectMcpClientFit.collect(ctx());+ last = findings.map((f) => f.id);+ if (run <= 3) {+ expect(last).toContain('mcp_starter_fit:fit-client');+ expect(last).toContain('mcp_starter_ops_drift');+ }+ }+ expect(last).not.toContain('mcp_starter_fit:fit-client');+ expect(last).not.toContain('mcp_starter_ops_drift');+ });++ test('a changed usage fingerprint re-surfaces a suppressed finding', async () => {+ // Suppress at the current fingerprint.+ for (let run = 1; run <= 3; run++) await collectMcpClientFit.collect(ctx());+ let findings = await collectMcpClientFit.collect(ctx());+ expect(findings.map((f) => f.id)).not.toContain('mcp_starter_fit:fit-client');+ try {+ // New starter-surface op joins fit-client's usage → new fingerprint.+ await seedCalls('fit-client', 'request_tools', 1);+ findings = await collectMcpClientFit.collect(ctx());+ expect(findings.map((f) => f.id)).toContain('mcp_starter_fit:fit-client');+ } finally {+ // The shared engine outlives this test — remove the extra usage row so+ // fit-client's fingerprint is unchanged for any later assertion.+ await engine.executeRaw(+ `DELETE FROM mcp_request_log WHERE token_name = 'fit-client' AND operation = 'request_tools'`,+ );+ }+ });+});diff --git a/test/auth-create-args.test.ts b/test/auth-create-args.test.tsindex 3ce9e7758a..5d8f71c71a 100644--- a/test/auth-create-args.test.ts+++ b/test/auth-create-args.test.ts@@ -1,5 +1,5 @@import { test, expect, describe } from 'bun:test';-import { parseAuthCreateArgs } from '../src/commands/auth.ts';+import { parseAuthCreateArgs, parseAuthClientsArgs, parseRescopeSurfaceValue } from '../src/commands/auth.ts';describe('parseAuthCreateArgs', () => {test('bare name (no flag) resolves the name — regression for the dropped-name bug', () => {@@ -36,3 +36,54 @@ describe('parseAuthCreateArgs', () => {expect(parseAuthCreateArgs(['n', '--takes-holders', ' world , , garry ']).takesHolders).toEqual(['world', 'garry']);});});++// WP4: `auth rescope-client --surface` value parsing. 'clear' → null (clears+// the pin), the three known surfaces pass through, anything else → undefined+// (caller errors with usage).+describe('parseRescopeSurfaceValue (WP4)', () => {+ test('known surfaces pass through', () => {+ expect(parseRescopeSurfaceValue('verbs')).toBe('verbs');+ expect(parseRescopeSurfaceValue('starter')).toBe('starter');+ expect(parseRescopeSurfaceValue('full')).toBe('full');+ });++ test("'clear' → null (removes the operator pin)", () => {+ expect(parseRescopeSurfaceValue('clear')).toBe(null);+ });++ test('anything else → undefined (loud CLI error)', () => {+ expect(parseRescopeSurfaceValue('everything')).toBeUndefined();+ expect(parseRescopeSurfaceValue('')).toBeUndefined();+ expect(parseRescopeSurfaceValue('none')).toBeUndefined();+ });+});++// E4 (WP4): `auth clients [--usage] [--days N] [--json]` flag parsing.+describe('parseAuthClientsArgs (E4)', () => {+ test('defaults: no usage join, 30d window, human output', () => {+ expect(parseAuthClientsArgs([])).toEqual({ usage: false, days: 30, json: false });+ });++ test('--usage and --json flags, in any order', () => {+ expect(parseAuthClientsArgs(['--usage', '--json'])).toEqual({ usage: true, days: 30, json: true });+ expect(parseAuthClientsArgs(['--json', '--usage'])).toEqual({ usage: true, days: 30, json: true });+ });++ test('--days accepts integers in [1, 3650]', () => {+ expect(parseAuthClientsArgs(['--days', '1']).days).toBe(1);+ expect(parseAuthClientsArgs(['--days', '90']).days).toBe(90);+ expect(parseAuthClientsArgs(['--days', '3650']).days).toBe(3650);+ });++ test('--days rejects out-of-bounds and non-integer values loudly', () => {+ expect(() => parseAuthClientsArgs(['--days', '0'])).toThrow(/--days/);+ expect(() => parseAuthClientsArgs(['--days', '3651'])).toThrow(/--days/);+ expect(() => parseAuthClientsArgs(['--days', '1.5'])).toThrow(/--days/);+ expect(() => parseAuthClientsArgs(['--days', 'soon'])).toThrow(/--days/);+ expect(() => parseAuthClientsArgs(['--days'])).toThrow(/--days/);+ });++ test('unknown flags reject loudly', () => {+ expect(() => parseAuthClientsArgs(['--nope'])).toThrow(/Unknown flag/);+ });+});diff --git a/test/cli-empty-retrieval-render.test.ts b/test/cli-empty-retrieval-render.test.tsnew file mode 100644index 0000000000..a410bf3d04--- /dev/null+++ b/test/cli-empty-retrieval-render.test.ts@@ -0,0 +1,70 @@+/**+ * T15/FOV-1 — the CLI surfaces retrieval degradation on empty results, and+ * the thin-client parser tolerates the D8 second content block.+ *+ * Before this, `cli.ts` returned a bare "No results." BEFORE the --explain+ * branch, and `unpackToolResult` discarded `_meta` — so both CLI surfaces+ * printed nothing diagnosable while the server knew exactly why the result+ * was empty.+ */++import { afterEach, describe, expect, test } from 'bun:test';+import { formatResult, captureRetrievalMeta, resetRetrievalMetaForTests } from '../src/cli.ts';+import { unpackToolResult, extractResponseMeta } from '../src/core/mcp-client.ts';++afterEach(() => resetRetrievalMetaForTests());++describe('formatResult empty-result rendering (T15)', () => {+ test('no meta captured → bare No results (old servers / non-retrieval paths)', () => {+ expect(formatResult('search', [], {})).toBe('No results.\n');+ });++ test('degraded meta → cause named inline', () => {+ captureRetrievalMeta('retrieval', {+ returned_count: 0,+ retrieved_count: 3,+ degraded: [{ stage: 'embed_unavailable' }, { stage: 'embed_unavailable' }],+ });+ const out = formatResult('query', [], {});+ expect(out).toContain('No results.');+ expect(out).toContain('retrieved 3 before trimming');+ expect(out).toContain('degraded: embed_unavailable');+ expect((out.match(/embed_unavailable/g) ?? []).length).toBe(1);+ });++ test('clean-miss meta → clean miss named', () => {+ captureRetrievalMeta('retrieval', { returned_count: 0, retrieved_count: 0, degraded: [] });+ expect(formatResult('search', [], {})).toContain('clean miss — no retrieval degradation');+ });++ test('non-retrieval keys are ignored by the capture', () => {+ captureRetrievalMeta('warnings', [{ code: 'unknown_param', param: 'lmit' }]);+ expect(formatResult('search', [], {})).toBe('No results.\n');+ });++ test('--json path is untouched (machine output stays a bare array)', () => {+ captureRetrievalMeta('retrieval', { degraded: [{ stage: 'embed_timeout' }] });+ expect(formatResult('search', [], { json: true })).toBe('[]\n');+ });+});++describe('thin-client envelope handling (ENG-17 skew guard)', () => {+ const twoBlockEnvelope: unknown = {+ content: [+ { type: 'text', text: '[]' },+ { type: 'text', text: '0 results. degraded: embed_unavailable.' },+ ],+ _meta: { retrieval: { returned_count: 0, degraded: [{ stage: 'embed_unavailable' }] } },+ };++ test('unpackToolResult parses content[0] only — the D8 second block never trips it', () => {+ expect(unpackToolResult<unknown[]>(twoBlockEnvelope)).toEqual([]);+ });++ test('extractResponseMeta lifts _meta; absent on old servers → undefined', () => {+ const meta = extractResponseMeta(twoBlockEnvelope);+ expect((meta as any).retrieval.degraded[0].stage).toBe('embed_unavailable');+ expect(extractResponseMeta({ content: [{ type: 'text', text: '[]' }] })).toBeUndefined();+ expect(extractResponseMeta({ content: [{ type: 'text', text: '[]' }], _meta: ['not-an-object'] })).toBeUndefined();+ });+});diff --git a/test/cross-modal-phase1.test.ts b/test/cross-modal-phase1.test.tsindex 8dd6d39359..68745455d6 100644--- a/test/cross-modal-phase1.test.ts+++ b/test/cross-modal-phase1.test.ts@@ -136,7 +136,7 @@ describe('D2 — knobsHash differs across cross-modal knob values', () => {return resolveSearchMode({ mode: 'balanced' });}- test('KNOBS_HASH_VERSION is 16 (cross-modal still appended; 15→16 detail fold #3515)', () => {+ test('KNOBS_HASH_VERSION is 17 (cross-modal still appended; 15→16 detail fold #3515; 16→17 degradation-stamp epoch)', () => {// v0.35 ladder: 1→2 reranker, 2→3 floor_ratio. v0.36 piggybacks on v=3// with 7 cross-modal knobs + column/provider context. v0.40.4 (salem) +// v0.39 T21 (master) bump to v=4 for graph_signals + schema-pack fields.@@ -150,7 +150,9 @@ describe('D2 — knobsHash differs across cross-modal knob values', () => {// 14→15: the resolved FTS configuration name (fts=) — a language switch// plus `reindex-search-vector` must not keep serving pre-switch rows.// #3515: 15→16 detail fold (det=).- expect(KNOBS_HASH_VERSION).toBe(16);+ // WP2/T3: 16→17 degradation-stamp epoch — pre-stamp cache rows must not+ // claim a clean (undegraded) run they can't prove.+ expect(KNOBS_HASH_VERSION).toBe(17);});test('flipping unified_multimodal changes the hash', () => {diff --git a/test/denied-after-list.test.ts b/test/denied-after-list.test.tsnew file mode 100644index 0000000000..33795d71d3--- /dev/null+++ b/test/denied-after-list.test.ts@@ -0,0 +1,157 @@+/**+ * T14 (amendment 33 + D10) — the honest-catalog metric's denial classifier.+ *+ * `isListLevelDenialEnvelope` decides which error envelopes serve-http logs+ * as status='denied_after_list' (the wave's trend-to-zero metric). Pins:+ * - publish-gate call-time backstop (detail 'config_key=...') → counted+ * - bound-client fence OP-level deny (detail 'fence=op') → counted+ * - argument-level slug-fence denials (no marker) → EXCLUDED (D10)+ * - non-permission errors → excluded+ *+ * The fence + gate cases run through the real dispatchToolCall so the+ * envelopes are the ones serve-http actually parses.+ *+ * `requestLogStatusForResult` is the ONE status decision serve-http persists+ * per tools/call row (success / success_with_warnings / denied_after_list /+ * error) — pinned pure here. ROW-LEVEL assertions (actual mcp_request_log+ * inserts, plus the tools/list `params.tool_count` contract) live in the+ * Postgres-host e2e (test/e2e/serve-http-oauth.test.ts — extension filed in+ * TODOS.md).+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import {+ dispatchToolCall,+ isListLevelDenialEnvelope,+ requestLogStatusForResult,+ type ToolResult,+} from '../src/mcp/dispatch.ts';+import type { AuthInfo } from '../src/core/operations.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ // Publish gates OFF on the DB plane (wins over any dev-machine file config)+ // so the advisor gate backstop fires deterministically.+ await engine.setConfig('mcp.publish_advisor', 'false');+}, 120_000);++afterAll(async () => {+ await engine.disconnect();+});++function boundAuth(): AuthInfo {+ return { token: 't', clientId: 'bound-client', scopes: ['read', 'write'], boundSlugPrefixes: ['notes/'] } as AuthInfo;+}++const HTTP = { remote: true, transport: 'http' as const, sourceId: 'default' };++function parsed(result: { content: Array<{ text: string }> }): Record<string, unknown> {+ return JSON.parse(result.content[0]!.text);+}++describe('isListLevelDenialEnvelope (pure)', () => {+ test('counts config_key= gate denials and fence=op fence denials', () => {+ expect(isListLevelDenialEnvelope({ error: 'permission_denied', detail: 'config_key=mcp.publish_skills' })).toBe(true);+ expect(isListLevelDenialEnvelope({ error: 'permission_denied', detail: 'fence=op' })).toBe(true);+ });+ test('excludes everything else', () => {+ expect(isListLevelDenialEnvelope({ error: 'permission_denied' })).toBe(false); // no marker = argument-level+ expect(isListLevelDenialEnvelope({ error: 'permission_denied', detail: 'something_else' })).toBe(false);+ expect(isListLevelDenialEnvelope({ error: 'invalid_params', detail: 'config_key=x' })).toBe(false);+ expect(isListLevelDenialEnvelope({ error: 'unknown_tool' })).toBe(false);+ expect(isListLevelDenialEnvelope(null)).toBe(false);+ expect(isListLevelDenialEnvelope('permission_denied')).toBe(false);+ });+});++describe('requestLogStatusForResult (pure — the persisted status decision)', () => {+ const ok = (extra: Partial<ToolResult> = {}): ToolResult => ({+ content: [{ type: 'text', text: '{}' }],+ ...extra,+ });++ test('plain success → success', () => {+ expect(requestLogStatusForResult(ok())).toBe('success');+ // Empty warnings array is NOT a warn state.+ expect(requestLogStatusForResult(ok({ _meta: { warnings: [] } }))).toBe('success');+ // Unrelated _meta payloads do not flip the status.+ expect(requestLogStatusForResult(ok({ _meta: { brain_hot_memory: { x: 1 } } }))).toBe('success');+ });++ test('success with non-empty _meta.warnings → success_with_warnings', () => {+ const res = ok({ _meta: { warnings: [{ code: 'unknown_param', param: 'zz' }] } });+ expect(requestLogStatusForResult(res)).toBe('success_with_warnings');+ });++ test('list-level denial envelopes → denied_after_list', () => {+ const gate: ToolResult = {+ isError: true,+ content: [{ type: 'text', text: JSON.stringify({ error: 'permission_denied', detail: 'config_key=mcp.publish_skills' }) }],+ };+ const fence: ToolResult = {+ isError: true,+ content: [{ type: 'text', text: JSON.stringify({ error: 'permission_denied', detail: 'fence=op' }) }],+ };+ expect(requestLogStatusForResult(gate)).toBe('denied_after_list');+ expect(requestLogStatusForResult(fence)).toBe('denied_after_list');+ });++ test('other errors (argument-level denials, op errors, unparseable content) → error', () => {+ const argLevel: ToolResult = {+ isError: true,+ content: [{ type: 'text', text: JSON.stringify({ error: 'permission_denied' }) }],+ };+ const opError: ToolResult = {+ isError: true,+ content: [{ type: 'text', text: JSON.stringify({ error: 'invalid_params', message: 'x' }) }],+ };+ const garbage: ToolResult = { isError: true, content: [{ type: 'text', text: 'not json' }] };+ const empty: ToolResult = { isError: true, content: [] };+ expect(requestLogStatusForResult(argLevel)).toBe('error');+ expect(requestLogStatusForResult(opError)).toBe('error');+ expect(requestLogStatusForResult(garbage)).toBe('error');+ expect(requestLogStatusForResult(empty)).toBe('error');+ });+});++describe('real envelopes through dispatchToolCall', () => {+ test('publish-gate backstop (advisor, gate off, remote) → counted', async () => {+ const res = await dispatchToolCall(engine, 'advisor', {}, { ...HTTP });+ expect(res.isError).toBe(true);+ const p = parsed(res);+ expect(p.error).toBe('permission_denied');+ expect(p.detail).toBe('config_key=mcp.publish_advisor');+ expect(isListLevelDenialEnvelope(p)).toBe(true);+ });++ test('bound-client fence OP-level deny (unfenceable write op) → counted', async () => {+ // forget_fact writes by numeric fact id (not a slug) — never available+ // to slug-bound clients; the dispatch fence denies at the op level.+ const res = await dispatchToolCall(engine, 'forget_fact', { id: 1 }, { ...HTTP, auth: boundAuth() });+ expect(res.isError).toBe(true);+ const p = parsed(res);+ expect(p.error).toBe('permission_denied');+ expect(p.detail).toBe('fence=op');+ expect(isListLevelDenialEnvelope(p)).toBe(true);+ });++ test('argument-level slug-fence deny (listed op, out-of-fence slug) → excluded (D10)', async () => {+ // put_page IS fence-allowed (listed for bound clients); an out-of-prefix+ // slug denies at the ARGUMENT level — legitimate, not a catalog lie.+ const res = await dispatchToolCall(+ engine,+ 'put_page',+ { slug: 'other/page', title: 'x', content: 'x' },+ { ...HTTP, auth: boundAuth() },+ );+ expect(res.isError).toBe(true);+ const p = parsed(res);+ expect(p.error).toBe('permission_denied');+ expect(isListLevelDenialEnvelope(p)).toBe(false);+ });+});diff --git a/test/dispatch-localonly.test.ts b/test/dispatch-localonly.test.tsnew file mode 100644index 0000000000..c72553063c--- /dev/null+++ b/test/dispatch-localonly.test.ts@@ -0,0 +1,70 @@+/**+ * Dispatch-layer localOnly backstop (WP1/D7).+ *+ * localOnly ops reach the operator's filesystem. Transport locality decides+ * dispatch: 'stdio' (local pipe) passes the backstop; 'http' and an UNSET+ * marker are denied fail-closed with the same envelope as a nonexistent op.+ * The trust axis (`remote`) is deliberately not consulted — stdio dispatches+ * with remote:true and still keeps its localOnly surface.+ */++import { describe, test, expect } from 'bun:test';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { operations } from '../src/core/operations.ts';+import type { BrainEngine } from '../src/core/engine.ts';++// Minimal engine stub: the backstop fires before any handler/engine call on+// the deny paths; on the stdio pass path the handler may touch the engine,+// and an empty result set is fine — the assertion is only that dispatch got+// PAST the backstop (i.e. the error, if any, is not unknown_tool).+const engineStub = {+ kind: 'postgres',+ executeRaw: async () => [],+ sql: async () => [],+} as unknown as BrainEngine;++const A_LOCAL_ONLY = 'file_list';++function parsed(result: { content: Array<{ text: string }> }) {+ return JSON.parse(result.content[0].text);+}++describe('dispatch localOnly backstop (WP1/D7)', () => {+ test('the fixture op is still declared localOnly', () => {+ const op = operations.find(o => o.name === A_LOCAL_ONLY);+ expect(op?.localOnly).toBe(true);+ });++ test("transport 'http' → unknown_tool, byte-identical to a nonexistent op", async () => {+ const denied = await dispatchToolCall(engineStub, A_LOCAL_ONLY, {}, {+ remote: true, transport: 'http', sourceId: 'default',+ });+ expect(denied.isError).toBe(true);+ const noSuchOp = await dispatchToolCall(engineStub, 'no_such_op_xyz', {}, {+ remote: true, transport: 'http', sourceId: 'default',+ });+ expect(parsed(denied).error).toBe('unknown_tool');+ // Same envelope shape as a nonexistent op: no existence oracle.+ expect(parsed(denied).error).toBe(parsed(noSuchOp).error);+ });++ test('unset transport marker → denied fail-closed', async () => {+ const denied = await dispatchToolCall(engineStub, A_LOCAL_ONLY, {}, {+ remote: true, sourceId: 'default',+ });+ expect(denied.isError).toBe(true);+ expect(parsed(denied).error).toBe('unknown_tool');+ });++ test("transport 'stdio' → passes the backstop (D7: stdio is the local surface)", async () => {+ const result = await dispatchToolCall(engineStub, A_LOCAL_ONLY, {}, {+ remote: true, transport: 'stdio', sourceId: 'default',+ });+ // The stub engine can't run the real handler; the contract under test is+ // only that stdio got PAST the backstop — any failure is a handler-level+ // error, never the unknown_tool denial.+ if (result.isError) {+ expect(parsed(result).error).not.toBe('unknown_tool');+ }+ });+});diff --git a/test/dispatch-response-meta.serial.test.ts b/test/dispatch-response-meta.serial.test.tsnew file mode 100644index 0000000000..4dd80d81fc--- /dev/null+++ b/test/dispatch-response-meta.serial.test.ts@@ -0,0 +1,131 @@+/**+ * WP2/D3/D8 — the `_meta.retrieval` response channel and the model-visible+ * second content block on empty retrievals, driven through the REAL dispatch+ * path (dispatchToolCall → search op handler) with hybridSearchCached mocked.+ *+ * Pins the four load-bearing behaviors:+ * 1. empty results → bare-array body + SECOND text block (D8);+ * 2. `_meta.retrieval` present on empty AND non-empty responses (D3);+ * 3. a metaHook failure never drops the retrieval key (per-key isolation);+ * 4. metaHook keys merge ALONGSIDE retrieval, not over it.+ *+ * Serial: mock.module (isolation guard R2).+ */++import { describe, expect, mock, test } from 'bun:test';+import * as realHybrid from '../src/core/search/hybrid.ts';+import type { BrainEngine } from '../src/core/engine.ts';++let nextResults: unknown[] = [];+let nextMeta: Record<string, unknown> | null = null;++// Mock BEFORE importing dispatch (operations.ts binds hybridSearchCached at+// import time; the spread keeps every other export live).+mock.module('../src/core/search/hybrid.ts', () => ({+ ...realHybrid,+ hybridSearchCached: async (+ _engine: unknown,+ _query: string,+ opts: { onMeta?: (m: unknown) => void },+ ) => {+ if (nextMeta) opts.onMeta?.(nextMeta);+ return nextResults;+ },+}));++const { dispatchToolCall } = await import('../src/mcp/dispatch.ts');++const engineStub = {+ getConfig: async () => null,+ executeRaw: async () => [],+} as unknown as BrainEngine;++const DEGRADED_META = {+ vector_enabled: false,+ expansion_applied: false,+ detail_resolved: null,+ retrieved_count: 3,+ degraded: [{ stage: 'embed_unavailable' }],+};++function callSearch(metaHook?: () => Promise<Record<string, unknown> | undefined>) {+ return dispatchToolCall(engineStub, 'search', { query: 'anything at all' }, {+ remote: true,+ transport: 'http',+ sourceId: 'default',+ ...(metaHook ? { metaHook } : {}),+ });+}++describe('dispatch response meta (WP2/D3/D8)', () => {+ test('empty results → second content block + _meta.retrieval', async () => {+ nextResults = [];+ nextMeta = DEGRADED_META;+ const out = await callSearch();+ expect(out.isError).toBeUndefined();+ // Body block 0 stays the bare array (deployed thin-clients parse only this).+ expect(JSON.parse(out.content[0].text)).toEqual([]);+ // D8: the model-visible diagnosis block.+ expect(out.content.length).toBe(2);+ expect(out.content[1].text).toContain('0 results');+ expect(out.content[1].text).toContain('retrieved 3');+ expect(out.content[1].text).toContain('degraded: embed_unavailable');+ const retrieval = (out._meta as Record<string, any>).retrieval;+ expect(retrieval.returned_count).toBe(0);+ expect(retrieval.retrieved_count).toBe(3);+ expect(retrieval.degraded).toEqual([{ stage: 'embed_unavailable' }]);+ });++ test('clean miss → second block says clean miss, degraded absent', async () => {+ nextResults = [];+ nextMeta = { vector_enabled: true, expansion_applied: false, detail_resolved: null };+ const out = await callSearch();+ expect(out.content.length).toBe(2);+ expect(out.content[1].text).toContain('clean miss');+ const retrieval = (out._meta as Record<string, any>).retrieval;+ expect(retrieval.degraded).toBeUndefined();+ expect(retrieval.vector_enabled).toBe(true);+ });++ test('non-empty results → single block, _meta.retrieval still present (D3: on ALL responses)', async () => {+ nextResults = [{ page_id: 1, slug: 'a', chunk_text: 'x' }];+ nextMeta = DEGRADED_META;+ const out = await callSearch();+ expect(out.content.length).toBe(1);+ const retrieval = (out._meta as Record<string, any>).retrieval;+ expect(retrieval.returned_count).toBe(1);+ });++ test('metaHook failure never drops the retrieval key (per-key isolation)', async () => {+ nextResults = [];+ nextMeta = DEGRADED_META;+ const out = await callSearch(async () => { throw new Error('hot memory down'); });+ expect((out._meta as Record<string, any>).retrieval).toBeDefined();+ });++ test('metaHook keys merge alongside retrieval, not over it', async () => {+ nextResults = [];+ nextMeta = DEGRADED_META;+ const out = await callSearch(async () => ({ brain_hot_memory: { facts: [] } }));+ const meta = out._meta as Record<string, any>;+ expect(meta.retrieval).toBeDefined();+ expect(meta.brain_hot_memory).toEqual({ facts: [] });+ });+});++describe('buildEmptyRetrievalBlock (unit)', () => {+ test('hint passthrough + stage dedupe + garbage tolerance', async () => {+ const { buildEmptyRetrievalBlock } = await import('../src/mcp/dispatch.ts');+ const text = buildEmptyRetrievalBlock({+ retrieved_count: 5,+ degraded: [{ stage: 'embed_timeout' }, { stage: 'embed_timeout' }, { stage: 'budget_dropped_all' }],+ hint: 'try the query tool.',+ });+ expect(text).toContain('retrieved 5');+ expect(text).toContain('degraded: embed_timeout, budget_dropped_all');+ expect(text).toContain('hint: try the query tool.');+ expect((text!.match(/embed_timeout/g) ?? []).length).toBe(1);+ expect(buildEmptyRetrievalBlock(null)).toBeNull();+ expect(buildEmptyRetrievalBlock('nope')).toBeNull();+ });+});diff --git a/test/doctor-wedged-queue.test.ts b/test/doctor-wedged-queue.test.tsindex c22601a43c..0248251b75 100644--- a/test/doctor-wedged-queue.test.ts+++ b/test/doctor-wedged-queue.test.ts@@ -132,6 +132,44 @@ describe('issue #1801 fix #3 — computeWedgedQueueCheck', () => {});});+describe('Minions-visibility wave — computeQueueHealthCheck structured details', () => {+ it('ok path carries {depth, oldest_age_seconds, worker_alive} (messages unchanged)', async () => {+ const check = await computeQueueHealthCheck(pgLike, { readWorkers: () => [] });+ expect(check.status).toBe('ok');+ // Message text is pinned elsewhere by prose consumers — unchanged.+ expect(check.message).toContain('No stalled-forever jobs');+ // Empty queue: zero depth, null oldest age, vacuously worker_alive.+ expect(check.details).toEqual({ depth: 0, oldest_age_seconds: null, worker_alive: true });+ });++ it('warn path reports total waiting depth + oldest age + worker_alive=false when a waiting queue has no worker', async () => {+ await seed('default', 'embed-backfill', 'waiting', {+ createdAtSql: "now() - interval '3 hours'",+ });+ await seed('default', 'embed', 'waiting', {+ createdAtSql: "now() - interval '10 minutes'",+ });+ const check = await computeQueueHealthCheck(pgLike, {+ readWorkers: () => [],+ oldWaitingHours: 1,+ });+ expect(check.status).toBe('warn');+ const d = check.details as { depth: number; oldest_age_seconds: number; worker_alive: boolean };+ expect(d.depth).toBe(2);+ expect(d.oldest_age_seconds).toBeGreaterThanOrEqual(3 * 3600 - 60);+ expect(d.worker_alive).toBe(false);+ });++ it('worker_alive=true when every waiting queue has a live registered worker', async () => {+ await seed('default', 'embed', 'waiting');+ const check = await computeQueueHealthCheck(pgLike, {+ readWorkers: () => [{ queue: 'default' }],+ });+ const d = check.details as { worker_alive: boolean };+ expect(d.worker_alive).toBe(true);+ });+});+describe('issue #1801 fix #3 — remote queue_health state→status regression', () => {it('doctor.ts no longer queries the non-existent `state` column', () => {const src = readFileSync(diff --git a/test/file-upload-engine-context.test.ts b/test/file-upload-engine-context.test.tsindex b743ce34d7..1f475c60e2 100644--- a/test/file-upload-engine-context.test.ts+++ b/test/file-upload-engine-context.test.ts@@ -34,10 +34,14 @@ describe('file_upload engine ownership', () => {const fixture = join(fixtureDir, 'capture.json');writeFileSync(fixture, '{"source":"camofox"}\n');+ // WP1/D7: file_upload is localOnly — the dispatch backstop only admits+ // the stdio local pipe. This test is about ENGINE ownership, so dispatch+ // as the local surface (transport policy is pinned in+ // test/dispatch-localonly.test.ts).const result = await dispatchToolCall(engine, 'file_upload', {path: fixture,page_slug: 'concepts/example-board',- }, { remote: true, sourceId: 'default' });+ }, { remote: true, transport: 'stdio', sourceId: 'default' });expect(result.isError).toBeFalsy();expect(JSON.parse(result.content[0].text)).toEqual({@@ -48,7 +52,7 @@ describe('file_upload engine ownership', () => {const listed = await dispatchToolCall(engine, 'file_list', {slug: 'concepts/example-board',- }, { remote: true, sourceId: 'default' });+ }, { remote: true, transport: 'stdio', sourceId: 'default' });expect(listed.isError).toBeFalsy();expect(JSON.parse(listed.content[0].text)).toEqual([expect.objectContaining({@@ -59,7 +63,7 @@ describe('file_upload engine ownership', () => {const url = await dispatchToolCall(engine, 'file_url', {storage_path: 'concepts/example-board/capture.json',- }, { remote: true, sourceId: 'default' });+ }, { remote: true, transport: 'stdio', sourceId: 'default' });expect(url.isError).toBeFalsy();expect(JSON.parse(url.content[0].text)).toEqual({storage_path: 'concepts/example-board/capture.json',diff --git a/test/get-agent-job.test.ts b/test/get-agent-job.test.tsnew file mode 100644index 0000000000..30d0441897--- /dev/null+++ b/test/get-agent-job.test.ts@@ -0,0 +1,215 @@+/**+ * Minions-visibility wave — `get_agent_job` MCP op tests (amendment 27,+ * ENG-16/18).+ *+ * Mirrors the `test/submit-agent.test.ts` harness (the file that pins the+ * `__owner_client_id` semantics) and covers the trust boundary:+ * - ctx.auth.clientId REQUIRED on EVERY transport (absent → permission_denied,+ * including local ctx.remote === false — closes the stdio/legacy bypass)+ * - cross-client isolation: client A cannot read client B's job+ * - foreign vs missing id: uniform not_found envelope (no enumeration oracle)+ * - agent-lane only: a non-subagent job with a matching id is invisible+ * - trimmed view: no data/prompt leak in the response+ * - queue_position: claim-order (priority ASC, created_at ASC) count of+ * waiting jobs ahead, present ONLY while status = 'waiting'+ *+ * Engine parity note: these run on PGLite. The ownership fence is the plain+ * `data->>'__owner_client_id' = $2` JSONB predicate — byte-identical SQL on+ * both engines and the same expression submit_agent's concurrency cap already+ * exercises; the DATABASE_URL-gated e2e parity suite covers the executeRaw+ * seam on real Postgres.+ */++import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { operationsByName, OperationError } from '../src/core/operations.ts';++const get_agent_job = operationsByName['get_agent_job'];+if (!get_agent_job) {+ throw new Error('get_agent_job op missing from operations registry — test fixture invalid');+}++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.setConfig('version', '85');+});++function makeCtx(opts: { clientId?: string; remote?: boolean } = {}): any {+ return {+ engine,+ config: {},+ logger: console,+ dryRun: false,+ remote: opts.remote ?? true,+ auth: opts.clientId ? { clientId: opts.clientId } : undefined,+ };+}++/** Insert a minion job row directly; returns the job id. */+async function seedJob(opts: {+ owner?: string;+ name?: string;+ status?: string;+ queue?: string;+ priority?: number;+ createdAtSql?: string;+ errorText?: string | null;+ result?: Record<string, unknown> | null;+}): Promise<number> {+ const data: Record<string, unknown> = { prompt: 'seeded' };+ if (opts.owner) data.__owner_client_id = opts.owner;+ const rows = await engine.executeRaw<{ id: number }>(+ `INSERT INTO minion_jobs (name, status, data, queue, priority, created_at, error_text, result)+ VALUES ($1, $2, $3::text::jsonb, $4, $5, ${opts.createdAtSql ?? 'now()'}, $6, $7::text::jsonb)+ RETURNING id`,+ [+ opts.name ?? 'subagent',+ opts.status ?? 'waiting',+ JSON.stringify(data),+ opts.queue ?? 'default',+ opts.priority ?? 0,+ opts.errorText ?? null,+ opts.result ? JSON.stringify(opts.result) : null,+ ],+ );+ return Number(rows[0].id);+}++describe('get_agent_job op surface', () => {+ it('declares scope=agent and a required numeric id param', () => {+ expect(get_agent_job.scope).toBe('agent');+ expect(get_agent_job.mutating).toBeUndefined();+ expect((get_agent_job.params.id as any).required).toBe(true);+ expect((get_agent_job.params.id as any).type).toBe('number');+ expect(typeof (get_agent_job.params.id as any).description).toBe('string');+ });+});++describe('client identity requirement (amendment 27 — every transport)', () => {+ it('refuses without ctx.auth.clientId on a remote transport', async () => {+ const id = await seedJob({ owner: 'alice' });+ await expect(get_agent_job.handler(makeCtx({ remote: true }), { id })).rejects.toMatchObject({+ code: 'permission_denied',+ });+ });++ it('refuses without ctx.auth.clientId even when remote === false (closes the stdio/legacy bypass)', async () => {+ const id = await seedJob({ owner: 'alice' });+ await expect(get_agent_job.handler(makeCtx({ remote: false }), { id })).rejects.toMatchObject({+ code: 'permission_denied',+ });+ });+});++describe('cross-client isolation + anti-enumeration', () => {+ it('client A reads its own job', async () => {+ const id = await seedJob({ owner: 'alice' });+ const r = (await get_agent_job.handler(makeCtx({ clientId: 'alice' }), { id })) as any;+ expect(r.id).toBe(id);+ expect(r.status).toBe('waiting');+ });++ it('client A cannot read client B\'s job', async () => {+ const id = await seedJob({ owner: 'bob' });+ await expect(get_agent_job.handler(makeCtx({ clientId: 'alice' }), { id })).rejects.toMatchObject({+ code: 'not_found',+ });+ });++ it('foreign and missing ids produce the SAME envelope (code + message shape)', async () => {+ const foreignId = await seedJob({ owner: 'bob' });+ const missingId = foreignId + 100_000;+ const grab = async (id: number): Promise<OperationError> => {+ try {+ await get_agent_job.handler(makeCtx({ clientId: 'alice' }), { id });+ } catch (e) {+ return e as OperationError;+ }+ throw new Error('expected a throw');+ };+ const foreign = await grab(foreignId);+ const missing = await grab(missingId);+ expect(foreign.code).toBe('not_found');+ expect(missing.code).toBe('not_found');+ // Identical wording modulo the id — no "exists but not yours" tell.+ expect(foreign.message.replace(String(foreignId), 'N')).toBe(+ missing.message.replace(String(missingId), 'N'),+ );+ expect(foreign.suggestion).toBe(missing.suggestion);+ });++ it('agent-lane only: a non-subagent job is invisible even with a matching owner field', async () => {+ const id = await seedJob({ owner: 'alice', name: 'sync' });+ await expect(get_agent_job.handler(makeCtx({ clientId: 'alice' }), { id })).rejects.toMatchObject({+ code: 'not_found',+ });+ });++ it('rejects a non-integer id as invalid_params (caller bug, distinct from not_found)', async () => {+ await expect(+ get_agent_job.handler(makeCtx({ clientId: 'alice' }), { id: 'abc' as any }),+ ).rejects.toMatchObject({ code: 'invalid_params' });+ });+});++describe('trimmed response shape', () => {+ it('returns only the trimmed keys — never data/prompt', async () => {+ const id = await seedJob({+ owner: 'alice',+ status: 'completed',+ errorText: null,+ result: { answer: 42 },+ });+ const r = (await get_agent_job.handler(makeCtx({ clientId: 'alice' }), { id })) as Record<string, unknown>;+ expect(Object.keys(r).sort()).toEqual(+ ['created_at', 'error_text', 'finished_at', 'id', 'result', 'started_at', 'status'].sort(),+ );+ expect(r.result).toEqual({ answer: 42 });+ expect(JSON.stringify(r)).not.toContain('__owner_client_id');+ expect(JSON.stringify(r)).not.toContain('prompt');+ });+});++describe('queue_position (claim-order: priority ASC, created_at ASC)', () => {+ it('counts waiting jobs ahead on the same queue, 0 = next to be claimed', async () => {+ // Claim order: p0-older, p0-newer, p5. Owners differ — position counts+ // ALL waiting competitors, not just the caller's own jobs.+ const first = await seedJob({ owner: 'alice', priority: 0, createdAtSql: "now() - interval '3 minutes'" });+ const second = await seedJob({ owner: 'bob', priority: 0, createdAtSql: "now() - interval '2 minutes'" });+ const third = await seedJob({ owner: 'alice', priority: 5, createdAtSql: "now() - interval '4 minutes'" });++ const r1 = (await get_agent_job.handler(makeCtx({ clientId: 'alice' }), { id: first })) as any;+ expect(r1.queue_position).toBe(0);+ const r2 = (await get_agent_job.handler(makeCtx({ clientId: 'bob' }), { id: second })) as any;+ expect(r2.queue_position).toBe(1);+ // Higher priority NUMBER = claimed later (priority ASC) despite being older.+ const r3 = (await get_agent_job.handler(makeCtx({ clientId: 'alice' }), { id: third })) as any;+ expect(r3.queue_position).toBe(2);+ });++ it('scopes the count to the job\'s own queue', async () => {+ await seedJob({ owner: 'bob', queue: 'other', createdAtSql: "now() - interval '10 minutes'" });+ const id = await seedJob({ owner: 'alice', queue: 'default' });+ const r = (await get_agent_job.handler(makeCtx({ clientId: 'alice' }), { id })) as any;+ expect(r.queue_position).toBe(0);+ });++ it('is absent for non-waiting jobs', async () => {+ const id = await seedJob({ owner: 'alice', status: 'active' });+ const r = (await get_agent_job.handler(makeCtx({ clientId: 'alice' }), { id })) as Record<string, unknown>;+ expect('queue_position' in r).toBe(false);+ });+});diff --git a/test/get-status-snapshot-op.test.ts b/test/get-status-snapshot-op.test.tsindex b07d8c5a00..85c88c4dd5 100644--- a/test/get-status-snapshot-op.test.ts+++ b/test/get-status-snapshot-op.test.ts@@ -1,24 +1,40 @@/*** `get_status_snapshot` MCP op contract.*- * Pins the v0.41.19.0 wave's per-op decisions:+ * Pins the per-op decisions:* - scope: 'admin' (codex MAJOR-9 / D10 — prevents read-scoped clients* from seeing brain-host operational state).* - localOnly: false (remote thin-client `gbrain status` callers need* it via HTTP MCP — that's the whole point).- * - payload returns ONLY {schema_version: 1, sync, cycle}. Locks /- * Workers / Queue / Autopilot are deliberately omitted from the- * remote shape; the local CLI's `gbrain status` renders them as- * "N/A on remote brain" instead.+ * - payload (schema_version 2, Minions-visibility wave): {schema_version,+ * version, sync, cycle, queue, workers}. `queue` and `workers` were+ * DELIBERATELY added so a remote submitter can see whether the lane its+ * job ids point at is alive; Locks / Autopilot remain omitted (host-local+ * concerns the thin client renders as "N/A on remote brain").+ * - fail-soft (amendment 26): a v2 section that cannot compute degrades to+ * {error: 'unavailable'} without failing the snapshot.** Hermetic — stubs the engine. The cycle / sync helpers degrade* gracefully when their queries throw, so a stubbed `executeRaw` that- * returns `[]` is enough to exercise the shape.+ * returns `[]` is enough to exercise the shape. The workers section also+ * reads host-local files (supervisor pidfile) — those assertions are+ * type-shaped, not value-pinned, so a dev machine with a live supervisor+ * doesn't flake the suite.*/import { describe, test, expect } from 'bun:test';import { operations, operationsByName } from '../src/core/operations.ts';+function makeCtx(engine: any): any {+ return {+ engine,+ config: {},+ logger: { info: () => {}, warn: () => {}, error: () => {} },+ dryRun: false,+ remote: true,+ };+}+describe('get_status_snapshot op definition', () => {test('exists and is registered in the operations array', () => {expect(operationsByName.get_status_snapshot).toBeDefined();@@ -41,34 +57,67 @@ describe('get_status_snapshot op definition', () => {});});-describe('get_status_snapshot handler shape', () => {- test('returns only {schema_version, sync, cycle} keys (no Locks/Workers/Queue/Autopilot)', async () => {+describe('get_status_snapshot handler shape (schema_version 2)', () => {+ test('returns {schema_version: 2, version, sync, cycle, queue, workers} (no Locks/Autopilot)', async () => {const op = operationsByName.get_status_snapshot;// Stub engine that returns empty rows for any executeRaw and a minimal// BrainEngine shape. The sync helper degrades to an empty sources list// and a synthetic SyncStatusReport; the cycle helper degrades to- // {last_full: null, last_targeted: null}.+ // {last_full: null, last_targeted: null}; the queue helpers degrade to+ // zero counts + an empty by_queue list.const stubEngine: any = {kind: 'pglite',executeRaw: async () => [],getConfig: async () => null,};- const ctx: any = {- engine: stubEngine,- config: {},- logger: { info: () => {}, warn: () => {}, error: () => {} },- dryRun: false,- remote: true,- };- const result = (await op.handler(ctx, {})) as Record<string, unknown>;- expect(result.schema_version).toBe(1);+ const result = (await op.handler(makeCtx(stubEngine), {})) as Record<string, unknown>;+ expect(result.schema_version).toBe(2);expect(result).toHaveProperty('sync');expect(result).toHaveProperty('cycle');- // #1984: the op now also reports the brain server's version (thin-client parity).+ // #1984: the op also reports the brain server's version (thin-client parity).expect(typeof result.version).toBe('string');+ // Minions-visibility wave: queue + workers are IN the remote payload now.+ expect(result).toHaveProperty('queue');+ expect(result).toHaveProperty('workers');+ // Locks / Autopilot stay host-local.expect(result).not.toHaveProperty('locks');- expect(result).not.toHaveProperty('workers');- expect(result).not.toHaveProperty('queue');expect(result).not.toHaveProperty('autopilot');++ const queue = result.queue as Record<string, unknown>;+ expect(queue.counts).toEqual({ active: 0, waiting: 0, completed: 0, failed: 0, dead: 0 });+ expect(queue.by_queue).toEqual([]);++ // Workers keys present; values are host-dependent (pidfile probe), so+ // pin types, not values.+ const workers = result.workers as Record<string, unknown>;+ expect(typeof workers.supervisor_alive).toBe('boolean');+ expect([null, 'pidfile', 'db_lock']).toContain(workers.detected_via as any);+ expect(typeof workers.live_lock_active).toBe('boolean');+ // Stubbed engine returns no completed rows.+ expect(workers.last_completed_at).toBeNull();+ });++ test('amendment 26: a failing queue section degrades to {error: unavailable} without failing the snapshot', async () => {+ const op = operationsByName.get_status_snapshot;+ // buildQueueCounts swallows its own errors (returns zeros); buildQueueDepths+ // does not — throwing from its GROUP BY queue SQL exercises the op-level+ // per-section catch.+ const stubEngine: any = {+ kind: 'pglite',+ executeRaw: async (sql: string) => {+ if (typeof sql === 'string' && sql.includes('GROUP BY queue')) {+ throw new Error('minion_jobs table melted');+ }+ return [];+ },+ getConfig: async () => null,+ };+ const result = (await op.handler(makeCtx(stubEngine), {})) as Record<string, unknown>;+ expect(result.schema_version).toBe(2);+ expect(result.queue).toEqual({ error: 'unavailable' });+ // The rest of the snapshot survives.+ expect(result).toHaveProperty('sync');+ expect(result).toHaveProperty('cycle');+ expect(result).toHaveProperty('workers');});});diff --git a/test/http-transport.test.ts b/test/http-transport.test.tsindex 12536342da..1e4a30d4fb 100644--- a/test/http-transport.test.ts+++ b/test/http-transport.test.ts@@ -342,6 +342,54 @@ describe('http-transport: tools/call dispatch', () => {});});+// --------------------------------------------------------------------------+// localOnly confinement (WP1/D7): localOnly ops reach the operator's+// filesystem, so the network transport neither lists nor dispatches them.+// stdio (the local pipe) keeps them — the dispatch backstop keys on the+// transport marker, and the denial envelope is byte-identical to a+// nonexistent op so the catalog doesn't leak which names exist.+// --------------------------------------------------------------------------++describe('http-transport: localOnly confinement (WP1/D7)', () => {+ let srv: TestServer;+ const TOK = 'tok-localonly';++ beforeAll(async () => {+ srv = await startTest({ validTokens: new Map([[hash(TOK), { id: 'tok-lo-id', name: 'localonly' }]]) });+ });+ afterAll(() => srv.stop());++ test('tools/list never includes localOnly ops', async () => {+ const r = await fetch(`${srv.url}/mcp`, {+ method: 'POST',+ headers: { 'Authorization': `Bearer ${TOK}`, 'Content-Type': 'application/json' },+ body: rpc('tools/list'),+ });+ const body = await r.json();+ const names = new Set(body.result.tools.map((t: { name: string }) => t.name));+ for (const localOnlyName of ['file_list', 'file_upload', 'file_url', 'sync_brain']) {+ expect(names.has(localOnlyName)).toBe(false);+ }+ // Non-localOnly ops are still present (the filter is targeted).+ expect(names.has('get_page')).toBe(true);+ });++ test('tools/call on a localOnly op is denied with the no-leak unknown_tool envelope', async () => {+ const r = await fetch(`${srv.url}/mcp`, {+ method: 'POST',+ headers: { 'Authorization': `Bearer ${TOK}`, 'Content-Type': 'application/json' },+ body: rpc('tools/call', { name: 'file_list', arguments: {} }),+ });+ expect(r.status).toBe(200);+ const body = await r.json();+ expect(body.result.isError).toBe(true);+ const parsed = JSON.parse(body.result.content[0].text);+ expect(parsed.error).toBe('unknown_tool');+ // Byte-identical message to a nonexistent op: no existence oracle.+ expect(parsed.message).toBe('Unknown tool: file_list');+ });+});+// --------------------------------------------------------------------------// CORS// --------------------------------------------------------------------------@@ -610,6 +658,26 @@ describe('http-transport: mcp_request_log audit', () => {} finally { srv.stop(); }});+ test('21b. gated-op call → denied_after_list status (amendment 33 metric parity with OAuth transport)', async () => {+ const TOK = 'audit-tok-denied';+ const srv = await startTest({ validTokens: new Map([[hash(TOK), { id: 'a-2', name: 'audit-denied' }]]) });+ try {+ // Pin the gate OFF on the DB plane (which wins over the file plane) so+ // the developer's real ~/.gbrain/config.json can't flip this test —+ // the call-time backstop then denies with detail config_key=…+ (srv.engine as { getConfig?: (k: string) => Promise<string | null> }).getConfig =+ async (key: string) => (key === 'mcp.publish_skills' ? 'false' : null);+ const r = await fetch(`${srv.url}/mcp`, { method: 'POST', headers: { 'Authorization': `Bearer ${TOK}`, 'Content-Type': 'application/json' }, body: rpc('tools/call', { name: 'list_skills', arguments: {} }) });+ const body = await r.json();+ expect(body.result.isError).toBe(true);+ expect(body.result.content[0].text).toContain('permission_denied');+ await new Promise(res => setTimeout(res, 10));+ const row = srv.engine.audit[srv.engine.audit.length - 1];+ expect(row.operation).toBe('tools/call:list_skills');+ expect(row.status).toBe('denied_after_list');+ } finally { srv.stop(); }+ });+test('22. failed auth → audit row with null token_name + auth_failed status', async () => {const srv = await startTest({});try {diff --git a/test/hybrid-degraded-cache-meta.serial.test.ts b/test/hybrid-degraded-cache-meta.serial.test.tsnew file mode 100644index 0000000000..83037f99d9--- /dev/null+++ b/test/hybrid-degraded-cache-meta.serial.test.ts@@ -0,0 +1,244 @@+/**+ * WP2/T3 — cached-wrapper meta correctness (ENG-5 + D14.2 + cache_prestamp).+ *+ * Drives real store→hit roundtrips (mocked `embedQuery` for a deterministic+ * vector, real PGLite SemanticQueryCache) and pins:+ *+ * - meta-key-parity: bare hybridSearch's meta keys ⊆ cached wrapper's,+ * on BOTH the miss and the hit path (the spread-carry rebuild can+ * never silently drop a key again — the adaptive_return drop class)+ * - cache-hit stamping: `cache.status === 'hit'`, degraded carried from+ * the stored row; hit-with-offset stays labeled 'hit'+ * - cache_prestamp: a row whose stored meta lacks the degradation stamp+ * surfaces degraded:[{stage:'cache_prestamp'}], never a clean claim+ * - D14.2 short TTL: a degraded (but embeddable) result set is written+ * with ttl_seconds=60; a clean set keeps the resolved TTL (3600)+ * - null-embedding store is a silent no-op (ENG-6 — total embed outage+ * is uncacheable by construction)+ *+ * Serial: mock.module + gateway/global-env mutation (isolation guard R2).+ */++import { afterAll, beforeAll, beforeEach, describe, expect, mock, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import * as realEmbedding from '../src/core/embedding.ts';+import type { HybridSearchMeta, SearchResult } from '../src/core/types.ts';++/** Deterministic 1536d unit vector — identical for every call, so the+ * second consult matches the first write at cosine 1.0. */+function fixedEmbedding(): Float32Array {+ const arr = new Float32Array(1536);+ for (let i = 0; i < 1536; i++) arr[i] = Math.sin(1 + i * 0.001);+ let norm = 0;+ for (let i = 0; i < 1536; i++) norm += arr[i] * arr[i];+ norm = Math.sqrt(norm);+ if (norm > 0) for (let i = 0; i < 1536; i++) arr[i] /= norm;+ return arr;+}++// Mock BEFORE importing hybrid.ts (spread keeps every other export live).+// EMBEDFAIL markers only fail the INNER variant embeds — the cache-consult+// embed uses the original query text.+mock.module('../src/core/embedding.ts', () => ({+ ...realEmbedding,+ embed: async () => fixedEmbedding(),+ embedQuery: async (text: string) => {+ if (String(text).includes('EMBEDFAIL')) throw new Error('mock embed provider failure');+ return fixedEmbedding();+ },+}));++// Import AFTER mocking.+const {+ hybridSearch,+ hybridSearchCached,+ awaitPendingSearchCacheWrites,+ DEGRADED_CACHE_TTL_SECONDS,+} = await import('../src/core/search/hybrid.ts');+const { SemanticQueryCache } = await import('../src/core/search/query-cache.ts');+const { configureGateway, resetGateway } = await import('../src/core/ai/gateway.ts');+const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');++let engine: InstanceType<typeof PGLiteEngine>;+let tmpHome: string;+const savedGbrainHome = process.env.GBRAIN_HOME;++beforeAll(async () => {+ tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-degraded-cache-meta-'));+ process.env.GBRAIN_HOME = tmpHome;++ resetGateway();+ configureGateway({+ embedding_model: 'openai:text-embedding-3-large',+ embedding_dimensions: 1536,+ env: { OPENAI_API_KEY: 'sk-fake' },+ });++ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();++ const fixtures: Array<[string, string, string]> = [+ ['alice-foo', 'Alice Foo', 'person'],+ ['bob-bar', 'Bob Bar', 'company'],+ ['carol-baz', 'Carol Baz', 'note'],+ ];+ for (const [slug, title, type] of fixtures) {+ const truth = `${title} is a builder shipping cache meta.`;+ await engine.putPage(slug, { type, title, compiled_truth: truth });+ await engine.upsertChunks(slug, [+ { chunk_index: 0, chunk_text: truth, chunk_source: 'compiled_truth' },+ ]);+ }+});++afterAll(async () => {+ if (savedGbrainHome === undefined) delete process.env.GBRAIN_HOME;+ else process.env.GBRAIN_HOME = savedGbrainHome;+ try { await engine.disconnect(); } catch { /* ignore */ }+ resetGateway();+ try { rmSync(tmpHome, { recursive: true, force: true }); } catch { /* ignore */ }+});++beforeEach(async () => {+ // Every query shares the same mocked vector, so rows from one test would+ // HIT for another test's different query text. Isolate per test.+ await engine.executeRaw('DELETE FROM query_cache');+});++async function cachedRun(+ query: string,+ opts: Parameters<typeof hybridSearchCached>[2] = {},+): Promise<{ results: SearchResult[]; meta: HybridSearchMeta }> {+ let meta: HybridSearchMeta | undefined;+ const results = await hybridSearchCached(engine, query, {+ ...opts,+ onMeta: (m) => { meta = m; },+ });+ if (!meta) throw new Error('onMeta never fired');+ return { results, meta };+}++describe('meta-key-parity (ENG-5) — bare keys ⊆ cached keys, hit and miss', () => {+ test('miss and hit both carry every key bare hybridSearch emits', async () => {+ let bareMeta: HybridSearchMeta | undefined;+ await hybridSearch(engine, 'builder', { limit: 5, onMeta: (m) => { bareMeta = m; } });+ const bareKeys = Object.keys(bareMeta!);+ expect(bareKeys).toContain('degraded');+ expect(bareKeys).toContain('retrieved_count');++ const { meta: missMeta } = await cachedRun('builder', { limit: 5 });+ expect(missMeta.cache?.status).toBe('miss');+ for (const k of bareKeys) {+ expect(Object.keys(missMeta)).toContain(k);+ }++ await awaitPendingSearchCacheWrites();++ const { meta: hitMeta } = await cachedRun('builder', { limit: 5 });+ expect(hitMeta.cache?.status).toBe('hit');+ for (const k of bareKeys) {+ expect(Object.keys(hitMeta)).toContain(k);+ }+ });+});++describe('cache-hit stamping', () => {+ test('hit carries cache.status=hit + the stored (clean) degradation stamp', async () => {+ const { meta: missMeta } = await cachedRun('builder', { limit: 5 });+ expect(missMeta.degraded).toEqual([]);+ await awaitPendingSearchCacheWrites();++ const { meta: hitMeta } = await cachedRun('builder', { limit: 5 });+ expect(hitMeta.cache?.status).toBe('hit');+ expect(hitMeta.degraded).toEqual([]); // stored stamp, not cache_prestamp+ expect(typeof hitMeta.retrieved_count).toBe('number');+ });++ test('hit-with-offset stays labeled hit (never a clean-miss mislabel)', async () => {+ const { results: missResults } = await cachedRun('builder', { limit: 5 });+ expect(missResults.length).toBeGreaterThan(0);+ await awaitPendingSearchCacheWrites();++ const { results, meta } = await cachedRun('builder', { limit: 5, offset: 50 });+ expect(results).toHaveLength(0); // offset past the stored set+ expect(meta.cache?.status).toBe('hit');+ expect(meta.retrieved_count).toBe(0); // pre-budget count for THIS page+ });+});++describe('cache_prestamp — pre-upgrade rows cannot claim clean', () => {+ test('stored meta lacking the degraded key surfaces cache_prestamp on hit', async () => {+ await cachedRun('builder', { limit: 5 });+ await awaitPendingSearchCacheWrites();+ // Simulate a pre-stamp row: strip the degraded key from the stored meta.+ await engine.executeRaw(`UPDATE query_cache SET meta = meta - 'degraded'`);++ const { meta } = await cachedRun('builder', { limit: 5 });+ expect(meta.cache?.status).toBe('hit');+ expect(meta.degraded).toEqual([{ stage: 'cache_prestamp' }]);+ });+});++describe('D14.2 — degraded result sets get a short-TTL cache entry', () => {+ test('embeddable degradation (expansion_partial) writes ttl_seconds=60, stamped', async () => {+ const { meta } = await cachedRun('builder', {+ limit: 5,+ expansion: true,+ expandFn: async () => ['builder', 'EMBEDFAIL variant'],+ });+ expect(meta.cache?.status).toBe('miss');+ expect((meta.degraded ?? []).map((d) => d.stage)).toContain('expansion_partial');+ await awaitPendingSearchCacheWrites();++ const rows = await engine.executeRaw<{ ttl_seconds: number; meta: unknown }>(+ 'SELECT ttl_seconds, meta FROM query_cache',+ );+ expect(rows).toHaveLength(1);+ expect(rows[0].ttl_seconds).toBe(DEGRADED_CACHE_TTL_SECONDS);+ const storedMeta = rows[0].meta as HybridSearchMeta;+ expect((storedMeta.degraded ?? []).map((d) => d.stage)).toContain('expansion_partial');+ });++ test('clean run keeps the resolved TTL (3600 default)', async () => {+ await cachedRun('builder', { limit: 5 });+ await awaitPendingSearchCacheWrites();+ const rows = await engine.executeRaw<{ ttl_seconds: number }>(+ 'SELECT ttl_seconds FROM query_cache',+ );+ expect(rows).toHaveLength(1);+ expect(rows[0].ttl_seconds).toBe(3600);+ });+});++describe('ENG-6 — null-embedding store stays a silent no-op', () => {+ test('store(null embedding) writes nothing and never throws', async () => {+ const cache = new SemanticQueryCache(engine);+ const result: SearchResult = {+ slug: 'alice-foo',+ page_id: 1,+ title: 'Alice Foo',+ type: 'person',+ chunk_text: 'Alice Foo is a builder.',+ chunk_source: 'compiled_truth',+ chunk_id: 1,+ chunk_index: 0,+ score: 1.0,+ stale: false,+ };+ const meta: HybridSearchMeta = {+ vector_enabled: false,+ detail_resolved: null,+ expansion_applied: false,+ degraded: [{ stage: 'embed_unavailable', reason: 'provider_error' }],+ retrieved_count: 1,+ };+ await cache.store('outage query', null, [result], meta);+ const rows = await engine.executeRaw<{ n: number }>(+ 'SELECT COUNT(*)::int AS n FROM query_cache',+ );+ expect(rows[0].n).toBe(0);+ });+});diff --git a/test/hybrid-salvage.serial.test.ts b/test/hybrid-salvage.serial.test.tsnew file mode 100644index 0000000000..bb255d5983--- /dev/null+++ b/test/hybrid-salvage.serial.test.ts@@ -0,0 +1,224 @@+/**+ * WP2/T3 (ENG-15) — allSettled salvage regression suite.+ *+ * Pins the three salvage branches of the embed fan-out plus the vector-arm+ * fan-out and the ENG-7 kill switch, via the mock.module embedding pattern+ * (seeded from test/hybrid-meta.serial.test.ts ++ * test/hybrid-cached-hit-budget-meta.serial.test.ts):+ *+ * A. one variant embed fails → original survives; `expansion_partial`+ * B. ORIGINAL embed fails, variants ok → variant lists salvaged, cosine+ * re-score SKIPPED; `expansion_partial` + `rescore_skipped`+ * C. all embeds fail → keyword-only; `embed_unavailable`/`embed_timeout`+ * D. every searchVector arm throws → keyword-only; `vector_arm_failed`+ * E. GBRAIN_SEARCH_SALVAGE=off restores all-or-nothing (one variant+ * failure abandons every embedding)+ *+ * Also pins the clean-run contract: degraded === [] (D3 "empty degraded =+ * clean miss") and retrieved_count present on every path.+ *+ * Serial: mock.module + gateway/global-env mutation (isolation guard R2).+ */++import { afterAll, afterEach, beforeAll, describe, expect, mock, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import * as realEmbedding from '../src/core/embedding.ts';+import type { HybridSearchMeta } from '../src/core/types.ts';++/** Deterministic 1536d unit vector. */+function fixedEmbedding(): Float32Array {+ const arr = new Float32Array(1536);+ for (let i = 0; i < 1536; i++) arr[i] = Math.sin(1 + i * 0.001);+ let norm = 0;+ for (let i = 0; i < 1536; i++) norm += arr[i] * arr[i];+ norm = Math.sqrt(norm);+ if (norm > 0) for (let i = 0; i < 1536; i++) arr[i] /= norm;+ return arr;+}++// Marker-driven per-query failure so one allSettled fan-out can mix+// fulfilled and rejected slots. Mock BEFORE importing hybrid.ts.+mock.module('../src/core/embedding.ts', () => ({+ ...realEmbedding,+ embed: async () => fixedEmbedding(),+ embedQuery: async (text: string) => {+ if (String(text).includes('EMBEDTIMEOUT')) {+ throw Object.assign(new Error('mock embed deadline'), { name: 'TimeoutError' });+ }+ if (String(text).includes('EMBEDFAIL')) throw new Error('mock embed provider failure');+ return fixedEmbedding();+ },+}));++// Import AFTER mocking.+const { hybridSearch } = await import('../src/core/search/hybrid.ts');+const { configureGateway, resetGateway } = await import('../src/core/ai/gateway.ts');+const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');++let engine: InstanceType<typeof PGLiteEngine>;+let tmpHome: string;+const savedGbrainHome = process.env.GBRAIN_HOME;+const savedSalvage = process.env.GBRAIN_SEARCH_SALVAGE;++beforeAll(async () => {+ // Hermetic config home so the developer's real ~/.gbrain/config.json+ // can't leak an embedding_model that changes column resolution.+ tmpHome = mkdtempSync(join(tmpdir(), 'gbrain-salvage-'));+ process.env.GBRAIN_HOME = tmpHome;++ resetGateway();+ configureGateway({+ embedding_model: 'openai:text-embedding-3-large',+ embedding_dimensions: 1536,+ env: { OPENAI_API_KEY: 'sk-fake' },+ });++ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();++ const fixtures: Array<[string, string, string]> = [+ ['alice-foo', 'Alice Foo', 'person'],+ ['bob-bar', 'Bob Bar', 'company'],+ ];+ for (const [slug, title, type] of fixtures) {+ const truth = `${title} is a builder working on search salvage.`;+ await engine.putPage(slug, { type, title, compiled_truth: truth });+ await engine.upsertChunks(slug, [+ { chunk_index: 0, chunk_text: truth, chunk_source: 'compiled_truth' },+ ]);+ }+});++afterAll(async () => {+ if (savedGbrainHome === undefined) delete process.env.GBRAIN_HOME;+ else process.env.GBRAIN_HOME = savedGbrainHome;+ if (savedSalvage === undefined) delete process.env.GBRAIN_SEARCH_SALVAGE;+ else process.env.GBRAIN_SEARCH_SALVAGE = savedSalvage;+ try { await engine.disconnect(); } catch { /* ignore */ }+ resetGateway();+ try { rmSync(tmpHome, { recursive: true, force: true }); } catch { /* ignore */ }+});++afterEach(() => {+ delete process.env.GBRAIN_SEARCH_SALVAGE;+});++async function run(+ query: string,+ opts: Parameters<typeof hybridSearch>[2] = {},+): Promise<{ results: Awaited<ReturnType<typeof hybridSearch>>; meta: HybridSearchMeta }> {+ let meta: HybridSearchMeta | undefined;+ const results = await hybridSearch(engine, query, {+ ...opts,+ onMeta: (m) => { meta = m; },+ });+ if (!meta) throw new Error('onMeta never fired');+ return { results, meta };+}++const stages = (meta: HybridSearchMeta): string[] => (meta.degraded ?? []).map((d) => d.stage);++describe('clean run — empty degraded = clean (D3)', () => {+ test('no failures → degraded [] and retrieved_count present', async () => {+ const { meta } = await run('builder', { limit: 5 });+ expect(meta.vector_enabled).toBe(true);+ expect(meta.degraded).toEqual([]);+ expect(typeof meta.retrieved_count).toBe('number');+ });+});++describe('branch A — one variant embed fails, original survives', () => {+ test('expansion_partial (variant_embed_failed); vector still ran', async () => {+ const { results, meta } = await run('builder', {+ limit: 5,+ expansion: true,+ expandFn: async () => ['builder', 'EMBEDFAIL variant query'],+ });+ expect(meta.vector_enabled).toBe(true);+ expect(meta.expansion_applied).toBe(true);+ expect(stages(meta)).toContain('expansion_partial');+ expect(meta.degraded!.find((d) => d.stage === 'expansion_partial')?.reason)+ .toBe('variant_embed_failed');+ expect(stages(meta)).not.toContain('rescore_skipped');+ expect(stages(meta)).not.toContain('embed_unavailable');+ expect(results.length).toBeGreaterThan(0);+ });+});++describe('branch B — ORIGINAL embed fails, variants ok', () => {+ test('variant lists salvaged; cosine re-score skipped; both stages emitted', async () => {+ const { results, meta } = await run('EMBEDFAIL builder original', {+ limit: 5,+ expansion: true,+ expandFn: async (q) => [q, 'builder salvage variant'],+ });+ // Vector RAN (via the surviving variant embeds) — the pre-wave behavior+ // was a silent keyword-only fallback.+ expect(meta.vector_enabled).toBe(true);+ expect(stages(meta)).toContain('expansion_partial');+ expect(meta.degraded!.find((d) => d.stage === 'expansion_partial')?.reason)+ .toBe('original_embed_failed');+ expect(stages(meta)).toContain('rescore_skipped');+ expect(results.length).toBeGreaterThan(0);+ });+});++describe('branch C — all embeds fail', () => {+ test('keyword-only + embed_unavailable (provider error class)', async () => {+ const { results, meta } = await run('EMBEDFAIL builder', { limit: 5, expansion: false });+ expect(meta.vector_enabled).toBe(false);+ expect(stages(meta)).toContain('embed_unavailable');+ expect(meta.degraded!.find((d) => d.stage === 'embed_unavailable')?.reason)+ .toBe('provider_error');+ // Keyword arm still carried the response (orFallback recall).+ expect(results.length).toBeGreaterThan(0);+ });++ test('all-timeout failures classify as embed_timeout', async () => {+ const { meta } = await run('EMBEDTIMEOUT builder', { limit: 5, expansion: false });+ expect(meta.vector_enabled).toBe(false);+ expect(stages(meta)).toContain('embed_timeout');+ expect(meta.degraded!.find((d) => d.stage === 'embed_timeout')?.reason).toBe('timeout');+ });++ test('reasons are enumerated codes — raw exception text never rides the meta (D6)', async () => {+ const { meta } = await run('EMBEDFAIL builder', { limit: 5, expansion: false });+ const serialized = JSON.stringify(meta.degraded);+ expect(serialized).not.toContain('mock embed provider failure');+ });+});++describe('branch D — searchVector arm failure', () => {+ test('every vector arm throws → keyword fallback + vector_arm_failed', async () => {+ const origSearchVector = engine.searchVector.bind(engine);+ (engine as unknown as { searchVector: unknown }).searchVector =+ async () => { throw new Error('mock searchVector failure'); };+ try {+ const { results, meta } = await run('builder', { limit: 5 });+ expect(meta.vector_enabled).toBe(false);+ expect(stages(meta)).toContain('vector_arm_failed');+ expect(results.length).toBeGreaterThan(0);+ } finally {+ (engine as unknown as { searchVector: unknown }).searchVector = origSearchVector;+ }+ });+});++describe('ENG-7 kill switch — GBRAIN_SEARCH_SALVAGE=off', () => {+ test('one variant failure abandons ALL embeddings (all-or-nothing restored)', async () => {+ process.env.GBRAIN_SEARCH_SALVAGE = 'off';+ const { results, meta } = await run('builder', {+ limit: 5,+ expansion: true,+ expandFn: async () => ['builder', 'EMBEDFAIL variant query'],+ });+ // Pre-wave semantics: Promise.all rejects, keyword-only fallback.+ expect(meta.vector_enabled).toBe(false);+ expect(stages(meta)).toContain('embed_unavailable');+ expect(stages(meta)).not.toContain('expansion_partial');+ expect(results.length).toBeGreaterThan(0);+ });+});diff --git a/test/hybrid-search-lite.serial.test.ts b/test/hybrid-search-lite.serial.test.tsindex f3705a7c15..e02c652e07 100644--- a/test/hybrid-search-lite.serial.test.ts+++ b/test/hybrid-search-lite.serial.test.ts@@ -108,17 +108,23 @@ describe('hybridSearchCached \u2014 meta surfaces intent', () => {});describe('hybridSearchCached \u2014 token budget', () => {- test('budget undefined returns no token_budget meta (no cut)', async () => {+ test('budget undefined carries the inner run\'s mode-resolved budget record (no cut)', async () => {let meta: HybridSearchMeta | undefined;const results = await hybridSearchCached(engine, 'alice', {limit: 10,onMeta: (m) => { meta = m; },});// Non-empty matters: pre-fix the fixture had no chunks, so this ran- // against an empty result set and the absent-budget assertion was+ // against an empty result set and the budget assertion was// trivially true.expect(results.length).toBeGreaterThan(0);- expect(meta?.token_budget).toBeUndefined();+ // WP2/T3 (ENG-5): the wrapper's spread-carry rebuild no longer HIDES+ // the inner run's budget record — the mode bundle's default budget+ // (balanced = 12000) applied inside bare hybridSearch, so the honest+ // report is "budget ran, nothing cut", not key-absence.+ expect(meta?.token_budget?.dropped).toBe(0);+ expect(meta?.token_budget?.truncated).toBeUndefined();+ expect(results.length).toBe(meta?.token_budget?.kept ?? -1);});test('budget meta is always emitted when budget is set', async () => {diff --git a/test/mcp-surface.test.ts b/test/mcp-surface.test.tsindex 296d6a5534..0fd37d9b79 100644--- a/test/mcp-surface.test.ts+++ b/test/mcp-surface.test.ts@@ -1,29 +1,42 @@/**- * MEMORY_VERBS v1 — surface-mode tests (Cathedral 1).+ * MEMORY_VERBS v1 + WP4 — surface-mode tests.** - 'verbs' filters to EXACTLY the seven protocol verbs+ * - 'starter' filters to STARTER_OPS (membership pinned; every member+ * exists in operations)+ * - monotonicity: allowedOpNames(verbs) ⊆ starter ⊆ full (ENG-1)* - 'full' is the identity (existing installs unchanged)* - dispatch-layer allowedOps is FAIL-CLOSED: a hidden op is uncallable* (unknown_tool), not merely unlisted [c2]* - flag parsing is strict (unknown value rejects loudly)* - resolution: flag > config mcp_surface > 'full'+ * - D2 ceiling: effective = min(ceiling, client row ?? default); the+ * GBRAIN_MCP_FORCE_SURFACE kill switch is NARROW-ONLY (FOV-6a)*/-import { afterAll, beforeAll, describe, expect, it } from 'bun:test';+import { afterAll, afterEach, beforeAll, describe, expect, it } from 'bun:test';import { mkdtempSync, rmSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { PGLiteEngine } from '../src/core/pglite-engine.ts';import { operations } from '../src/core/operations.ts';import { VERB_NAMES } from '../src/core/verbs.ts';+import { BRAIN_TOOL_ALLOWLIST } from '../src/core/minions/tools/brain-allowlist.ts';import {filterOpsForSurface,allowedOpNames,parseSurfaceFlag,resolveSurface,+ STARTER_OPS,+ minSurface,+ clampSurface,+ effectiveSurfaceForClient,+ resolveClientRowSurface,+ __resetSurfaceWarnCachesForTests,} from '../src/mcp/surface.ts';import { dispatchToolCall } from '../src/mcp/dispatch.ts';import { __setUsageLogPathForTests } from '../src/core/verbs/usage-log.ts';+import { withEnv } from './helpers/with-env.ts';let engine: PGLiteEngine;let home: string;@@ -52,6 +65,50 @@ describe('filterOpsForSurface', () => {it("'full' is the identity — existing installs see every op", () => {expect(filterOpsForSurface(operations, 'full')).toEqual(operations);});++ it("'starter' returns exactly the ops whose name is in STARTER_OPS", () => {+ const names = filterOpsForSurface(operations, 'starter').map(o => o.name).sort();+ expect(names).toEqual(operations.filter(o => STARTER_OPS.has(o.name)).map(o => o.name).sort());+ });+});++describe('STARTER_OPS (WP4)', () => {+ it('every member exists in operations (membership pin)', () => {+ const known = new Set(operations.map(o => o.name));+ const missing = [...STARTER_OPS].filter(name => !known.has(name));+ expect(missing).toEqual([]);+ });++ it('is composed programmatically: verbs + FOV-6b fallback daily ops + whoami + request_tools', () => {+ // ENG-1: the verb slice is a spread of VERB_NAMES — all SEVEN post-#4028+ // verbs (context_pack/delta included), never a hand-count.+ for (const v of VERB_NAMES) expect(STARTER_OPS.has(v)).toBe(true);+ // FOV-6b fallback: the reviewed brain-tool allow-list, imported not copied.+ for (const name of BRAIN_TOOL_ALLOWLIST) expect(STARTER_OPS.has(name)).toBe(true);+ // FOV-4: the agent lane must not strand agent-scope clients.+ expect(STARTER_OPS.has('submit_agent')).toBe(true);+ expect(STARTER_OPS.has('get_agent_job')).toBe(true);+ expect(STARTER_OPS.has('whoami')).toBe(true);+ // D4: request_tools is listed on starter (+full) …+ expect(STARTER_OPS.has('request_tools')).toBe(true);+ });++ it('D4: request_tools is NOT on the verbs surface', () => {+ expect(allowedOpNames(operations, 'verbs').has('request_tools')).toBe(false);+ expect(allowedOpNames(operations, 'starter').has('request_tools')).toBe(true);+ expect(allowedOpNames(operations, 'full').has('request_tools')).toBe(true);+ });++ it('monotonicity (ENG-1): allowedOpNames(verbs) ⊆ starter ⊆ full', () => {+ const verbs = allowedOpNames(operations, 'verbs');+ const starter = allowedOpNames(operations, 'starter');+ const full = allowedOpNames(operations, 'full');+ for (const name of verbs) expect(starter.has(name)).toBe(true);+ for (const name of starter) expect(full.has(name)).toBe(true);+ // And the ladder is strictly widening at each step.+ expect(verbs.size).toBeLessThan(starter.size);+ expect(starter.size).toBeLessThan(full.size);+ });});describe('dispatch allowedOps — fail-closed [c2]', () => {@@ -91,8 +148,9 @@ describe('dispatch allowedOps — fail-closed [c2]', () => {});describe('parseSurfaceFlag + resolveSurface', () => {- it('parses verbs/full, rejects unknown values loudly, requires a value', () => {+ it('parses verbs/starter/full, rejects unknown values loudly, requires a value', () => {expect(parseSurfaceFlag(['--surface', 'verbs'])).toBe('verbs');+ expect(parseSurfaceFlag(['--surface', 'starter'])).toBe('starter');expect(parseSurfaceFlag(['--surface', 'full'])).toBe('full');expect(parseSurfaceFlag(['serve'])).toBe(null);expect(() => parseSurfaceFlag(['--surface', 'all'])).toThrow(/Unknown --surface/);@@ -103,8 +161,96 @@ describe('parseSurfaceFlag + resolveSurface', () => {it('resolution: flag > config mcp_surface > full', () => {expect(resolveSurface('verbs', { mcp_surface: 'full' })).toBe('verbs');expect(resolveSurface(null, { mcp_surface: 'verbs' })).toBe('verbs');+ expect(resolveSurface(null, { mcp_surface: 'starter' })).toBe('starter');expect(resolveSurface(null, {})).toBe('full');expect(resolveSurface(null, null)).toBe('full');expect(resolveSurface(null, { mcp_surface: 'bogus' as never })).toBe('full');});});++// ---------------------------------------------------------------------------+// WP4 — D2 ceiling resolution + GBRAIN_MCP_FORCE_SURFACE kill switch (FOV-6a)+// ---------------------------------------------------------------------------++describe('D2 ceiling resolution (effectiveSurfaceForClient)', () => {+ afterEach(() => {+ __resetSurfaceWarnCachesForTests();+ });++ it('minSurface orders verbs < starter < full', () => {+ expect(minSurface('verbs', 'full')).toBe('verbs');+ expect(minSurface('full', 'verbs')).toBe('verbs');+ expect(minSurface('starter', 'full')).toBe('starter');+ expect(minSurface('full', 'starter')).toBe('starter');+ expect(minSurface('verbs', 'starter')).toBe('verbs');+ expect(minSurface('full', 'full')).toBe('full');+ });++ it('D2 pin: a verbs-pinned server + full client row still serves verbs', () => {+ expect(effectiveSurfaceForClient({ ceiling: 'verbs', clientSurface: 'full', defaultSurface: null })).toBe('verbs');+ });++ it('client row narrows below the ceiling', () => {+ expect(effectiveSurfaceForClient({ ceiling: 'full', clientSurface: 'starter', defaultSurface: null })).toBe('starter');+ expect(effectiveSurfaceForClient({ ceiling: 'full', clientSurface: 'verbs', defaultSurface: null })).toBe('verbs');+ });++ it('NULL row surface falls to the config default, bounded by the ceiling', () => {+ expect(effectiveSurfaceForClient({ ceiling: 'full', clientSurface: null, defaultSurface: 'starter' })).toBe('starter');+ expect(effectiveSurfaceForClient({ ceiling: 'verbs', clientSurface: null, defaultSurface: 'full' })).toBe('verbs');+ });++ it('NULL row + unset default = the ceiling (pre-WP4 behavior, existing clients untouched)', () => {+ expect(effectiveSurfaceForClient({ ceiling: 'full', clientSurface: null, defaultSurface: null })).toBe('full');+ expect(effectiveSurfaceForClient({ ceiling: 'starter', clientSurface: null, defaultSurface: null })).toBe('starter');+ });++ // FOV-6a pins, deliberately NEXT to the D2 ceiling test above.+ it('kill switch narrows: force=verbs clamps a full resolution to verbs', async () => {+ await withEnv({ GBRAIN_MCP_FORCE_SURFACE: 'verbs' }, () => {+ expect(effectiveSurfaceForClient({ ceiling: 'full', clientSurface: 'full', defaultSurface: null })).toBe('verbs');+ expect(clampSurface('full')).toBe('verbs');+ });+ });++ it('kill switch can NEVER widen: force=full over a verbs ceiling still serves verbs', async () => {+ await withEnv({ GBRAIN_MCP_FORCE_SURFACE: 'full' }, () => {+ expect(effectiveSurfaceForClient({ ceiling: 'verbs', clientSurface: 'full', defaultSurface: null })).toBe('verbs');+ expect(clampSurface('verbs')).toBe('verbs');+ expect(clampSurface('starter')).toBe('starter');+ });+ });++ it('unknown kill-switch value is ignored (warn once), surface stays as configured', async () => {+ await withEnv({ GBRAIN_MCP_FORCE_SURFACE: 'everything' }, () => {+ const warnings: string[] = [];+ expect(clampSurface('starter', msg => warnings.push(msg))).toBe('starter');+ expect(clampSurface('starter', msg => warnings.push(msg))).toBe('starter');+ expect(warnings.length).toBe(1);+ expect(warnings[0]).toContain('GBRAIN_MCP_FORCE_SURFACE');+ });+ });+});++describe('resolveClientRowSurface (amendment 18)', () => {+ afterEach(() => __resetSurfaceWarnCachesForTests());++ it('threads known values, null/undefined = no per-client surface', () => {+ expect(resolveClientRowSurface('starter', 'c1')).toBe('starter');+ expect(resolveClientRowSurface('verbs', 'c1')).toBe('verbs');+ expect(resolveClientRowSurface('full', 'c1')).toBe('full');+ expect(resolveClientRowSurface(null, 'c1')).toBe(null);+ expect(resolveClientRowSurface(undefined, 'c1')).toBe(null);+ });++ it('unknown value → ignored + warn-logged once per client', () => {+ const warnings: string[] = [];+ const warn = (msg: string) => warnings.push(msg);+ expect(resolveClientRowSurface('tier-gold', 'client-a', warn)).toBe(null);+ expect(resolveClientRowSurface('tier-gold', 'client-a', warn)).toBe(null);+ expect(resolveClientRowSurface('tier-gold', 'client-b', warn)).toBe(null);+ expect(warnings.length).toBe(2); // once per client, not per request+ expect(warnings[0]).toContain('client-a');+ expect(warnings[1]).toContain('client-b');+ });+});diff --git a/test/mcp-tool-defs.test.ts b/test/mcp-tool-defs.test.tsindex 8cfecaf76c..2168c07440 100644--- a/test/mcp-tool-defs.test.ts+++ b/test/mcp-tool-defs.test.ts@@ -70,6 +70,12 @@ describe('buildToolDefs', () => {expect(JSON.stringify(extracted)).toBe(JSON.stringify(inline));});+ test('explicit strictParams:false / empty opts stay byte-identical to the default emission (WP3)', () => {+ const base = JSON.stringify(buildToolDefs(operations));+ expect(JSON.stringify(buildToolDefs(operations, {}))).toBe(base);+ expect(JSON.stringify(buildToolDefs(operations, { strictParams: false }))).toBe(base);+ });+test('ops without annotations keep the pre-annotations shape exactly (no annotations key)', () => {const extracted = buildToolDefs(operations);for (const def of extracted) {@@ -105,6 +111,104 @@ describe('buildToolDefs', () => {});});+// ---------------------------------------------------------------------------+// WP3 (D14.1) — strictParams emission state.+//+// With mcp.strict_params = 'reject' the transports build schemas that CLOSE+// the property set (`additionalProperties: false`); the two dispatch-level+// passthrough keys (`_meta`, `dry_run`) must then be DECLARED so+// schema-validating clients (Gemini strict, OpenAI structured outputs) don't+// strip them from arguments. Both emission states are pinned here; the+// default state's byte-identity is pinned above.+// ---------------------------------------------------------------------------++describe('buildToolDefs strictParams emission (WP3/D14.1)', () => {+ const strictDefs = buildToolDefs(operations, { strictParams: true });++ test('every strict def closes the schema and declares _meta + dry_run', () => {+ for (const def of strictDefs) {+ expect(def.inputSchema.additionalProperties).toBe(false);+ const props = def.inputSchema.properties as Record<string, { type?: string }>;+ expect(props._meta).toBeDefined();+ expect(props._meta.type).toBe('object');+ expect(props.dry_run).toBeDefined();+ expect(props.dry_run.type).toBe('boolean');+ }+ });++ test('an op with a REAL declared dry_run param keeps its own schema (no clobber)', () => {+ const op = operations.find(o => 'dry_run' in o.params)!;+ expect(op).toBeDefined();+ const def = strictDefs.find(d => d.name === op.name)!;+ const props = def.inputSchema.properties as Record<string, { description?: string }>;+ // The declared param's own description survives; the injected fallback+ // (bare {type:'boolean'}) is only used when the op doesn't declare one.+ expect(props.dry_run.description).toBe(op.params.dry_run.description);+ });++ test('strict mode changes ONLY additionalProperties + the two passthrough keys', () => {+ const base = buildToolDefs(operations);+ for (let i = 0; i < base.length; i++) {+ const strict = strictDefs[i];+ const loose = base[i];+ expect(strict.name).toBe(loose.name);+ // Same declared params, byte-identical per-param schemas.+ for (const [k, v] of Object.entries(loose.inputSchema.properties)) {+ expect(JSON.stringify((strict.inputSchema.properties as Record<string, unknown>)[k])).toBe(JSON.stringify(v));+ }+ const extraKeys = Object.keys(strict.inputSchema.properties)+ .filter(k => !(k in loose.inputSchema.properties));+ expect(extraKeys.sort()).toEqual(['_meta', 'dry_run'].filter(k => !(k in loose.inputSchema.properties)).sort());+ expect(strict.inputSchema.required).toEqual(loose.inputSchema.required);+ }+ });++ test('default emission never carries additionalProperties', () => {+ for (const def of buildToolDefs(operations)) {+ expect('additionalProperties' in def.inputSchema).toBe(false);+ }+ });+});++// ---------------------------------------------------------------------------+// WP3 (T6) — param-description completeness walker.+//+// Every param of every non-localOnly op is an agent-facing contract: a param+// without a description is exactly the "unguessable arg names" consumer+// complaint. localOnly ops are exempt (operator-facing CLI surface). Mirrors+// the findArrayWithoutItems drift-guard pattern below.+// ---------------------------------------------------------------------------++describe('param description completeness (WP3)', () => {+ test('every non-localOnly op param carries a non-empty description', () => {+ const violations: string[] = [];+ for (const op of operations) {+ if (op.localOnly) continue;+ for (const [key, def] of Object.entries(op.params)) {+ if (typeof def.description !== 'string' || def.description.trim() === '') {+ violations.push(`${op.name}.${key}`);+ }+ }+ }+ expect(violations).toEqual([]);+ });++ // WP4 (amendment 22): every non-localOnly op must carry an `area` — the+ // request_tools catalog groups by it, and an op missing from the central+ // OP_AREAS map in operations.ts would silently land in the 'other' bucket.+ // Area NAMES are non-contractual; presence is not.+ test('every non-localOnly op carries a non-empty area (WP4)', () => {+ const violations: string[] = [];+ for (const op of operations) {+ if (op.localOnly) continue;+ if (typeof op.area !== 'string' || op.area.trim() === '') {+ violations.push(op.name);+ }+ }+ expect(violations).toEqual([]);+ });+});+// ---------------------------------------------------------------------------// Structural array-items guard (v0.34 fix wave).//diff --git a/test/mcp-usage.test.ts b/test/mcp-usage.test.tsnew file mode 100644index 0000000000..d3b69c50d5--- /dev/null+++ b/test/mcp-usage.test.ts@@ -0,0 +1,168 @@+/**+ * T12 (amendment 30) — src/core/mcp-usage.ts, the shared mcp_request_log+ * usage reader. Pins the row-hygiene rules that three consumers (auth+ * clients --usage, the advisor starter-fit collector, derive-starter-ops)+ * must agree on:+ * - JSON-RPC method rows ('tools/list', 'initialize', ...) are not op calls+ * - 'surface_change' audit rows (ENG-8) are excluded+ * - the legacy 'tools/call:<name>' prefix strips to <name>+ * - windowing on created_at (default 30d)+ * - D12 behavioral automation classification (>90% context_pack/delta)+ *+ * Hermetic in-memory PGLite (real SQL, both-engine-portable shape).+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import {+ readClientOpUsage,+ normalizeLoggedOperation,+ AUTOMATION_FRACTION_THRESHOLD,+ MCP_USAGE_DEFAULT_WINDOW_DAYS,+} from '../src/core/mcp-usage.ts';++let engine: PGLiteEngine;++async function seed(token: string | null, operation: string, count: number, daysAgo = 0, status = 'success'): Promise<void> {+ for (let i = 0; i < count; i++) {+ await engine.executeRaw(+ `INSERT INTO mcp_request_log (token_name, agent_name, operation, latency_ms, status, created_at)+ VALUES ($1, $2, $3, 5, $5, now() - ($4::int * interval '1 day'))`,+ [token, token ?? 'anon', operation, daysAgo, status],+ );+ }+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();++ // client-a: real ops + method rows + an audit row (methods/audit must drop).+ await seed('client-a', 'query', 3);+ await seed('client-a', 'search', 2);+ await seed('client-a', 'tools/list', 5);+ await seed('client-a', 'initialize', 1);+ await seed('client-a', 'surface_change', 1);++ // client-b: legacy bearer transport rows.+ await seed('client-b', 'tools/call:query', 2);+ await seed('client-b', 'tools/call:', 1); // empty op name → dropped+ // Prefixed method/audit rows must drop too (the stripped name re-runs hygiene).+ await seed('client-b', 'tools/call:tools/list', 2);+ await seed('client-b', 'tools/call:surface_change', 1);++ // client-c: automation-shaped (19 boundary calls of 20 total = 0.95).+ await seed('client-c', 'context_pack', 15);+ await seed('client-c', 'delta', 4);+ await seed('client-c', 'query', 1);++ // client-old: outside the default 30d window, inside 90d.+ await seed('client-old', 'query', 1, 40);++ // NULL token_name rows never attribute to a client.+ await seed(null, 'query', 1);++ // client-denied: denial/error traffic must not count as usage — a client+ // bouncing off a gated op can't "use" its way into starter derivation.+ await seed('client-denied', 'advisor', 20, 0, 'denied_after_list');+ await seed('client-denied', 'query', 3, 0, 'error');+ // warn-mode successes DO count.+ await seed('client-a', 'query', 1, 0, 'success_with_warnings');+}, 120_000);++afterAll(async () => {+ await engine.disconnect();+});++describe('normalizeLoggedOperation (hygiene rules, single source)', () => {+ test('plain op names pass through', () => {+ expect(normalizeLoggedOperation('query')).toBe('query');+ expect(normalizeLoggedOperation('put_page')).toBe('put_page');+ });+ test('JSON-RPC method rows drop', () => {+ expect(normalizeLoggedOperation('tools/list')).toBeNull();+ expect(normalizeLoggedOperation('initialize')).toBeNull();+ expect(normalizeLoggedOperation('notifications/initialized')).toBeNull();+ expect(normalizeLoggedOperation('ping')).toBeNull();+ });+ test('surface_change audit rows drop (ENG-8)', () => {+ expect(normalizeLoggedOperation('surface_change')).toBeNull();+ });+ test('legacy tools/call: prefix strips to the op name', () => {+ expect(normalizeLoggedOperation('tools/call:query')).toBe('query');+ expect(normalizeLoggedOperation('tools/call:')).toBeNull();+ });+ test('stripped names re-run the hygiene check — prefixed method/audit rows drop', () => {+ expect(normalizeLoggedOperation('tools/call:tools/list')).toBeNull();+ expect(normalizeLoggedOperation('tools/call:surface_change')).toBeNull();+ expect(normalizeLoggedOperation('tools/call:initialize')).toBeNull();+ expect(normalizeLoggedOperation('tools/call:notifications/initialized')).toBeNull();+ expect(normalizeLoggedOperation('tools/call:ping')).toBeNull();+ });+});++describe('readClientOpUsage', () => {+ test('default 30d window: hygiene applied, per-client counts + distinct ops', async () => {+ const usage = await readClientOpUsage(engine);+ const a = usage.find((u) => u.token_name === 'client-a');+ expect(a).toBeDefined();+ // 3 plain successes + 1 success_with_warnings (warn-mode successes count).+ expect(a!.ops).toEqual({ query: 4, search: 2 });+ expect(a!.total_calls).toBe(6);+ expect(a!.distinct_ops).toEqual(['query', 'search']);+ expect(a!.likely_automation).toBe(false);+ expect(new Date(a!.last_seen).getTime()).toBeGreaterThan(0);+ });++ test('legacy prefix rows merge into the plain op name', async () => {+ const usage = await readClientOpUsage(engine);+ const b = usage.find((u) => u.token_name === 'client-b');+ expect(b).toBeDefined();+ // 'tools/call:' (empty name) and the prefixed method/audit rows+ // ('tools/call:tools/list', 'tools/call:surface_change') all dropped.+ expect(b!.ops).toEqual({ query: 2 });+ expect(b!.total_calls).toBe(2);+ });++ test('automation classification (D12): >90% boundary calls flags the client', async () => {+ const usage = await readClientOpUsage(engine);+ const c = usage.find((u) => u.token_name === 'client-c')!;+ expect(c.automation_fraction).toBeCloseTo(0.95, 5);+ expect(c.automation_fraction).toBeGreaterThan(AUTOMATION_FRACTION_THRESHOLD);+ expect(c.likely_automation).toBe(true);+ });++ test('denied and errored rows are not usage — only success statuses count', async () => {+ const usage = await readClientOpUsage(engine);+ // client-denied has ONLY denied_after_list + error rows → no usage entry.+ expect(usage.find((u) => u.token_name === 'client-denied')).toBeUndefined();+ });++ test('window excludes old rows by default; wider window includes them', async () => {+ const usage30 = await readClientOpUsage(engine, { days: MCP_USAGE_DEFAULT_WINDOW_DAYS });+ expect(usage30.find((u) => u.token_name === 'client-old')).toBeUndefined();+ const usage90 = await readClientOpUsage(engine, { days: 90 });+ const old = usage90.find((u) => u.token_name === 'client-old');+ expect(old).toBeDefined();+ expect(old!.ops).toEqual({ query: 1 });+ });++ test('NULL token_name rows are never attributed', async () => {+ const usage = await readClientOpUsage(engine);+ // Every returned entry has a real token_name; the anonymous row is gone.+ for (const u of usage) expect(u.token_name.length).toBeGreaterThan(0);+ });++ test('sorted by total_calls descending', async () => {+ const usage = await readClientOpUsage(engine);+ const totals = usage.map((u) => u.total_calls);+ expect(totals).toEqual([...totals].sort((x, y) => y - x));+ });++ test('rejects invalid day windows loudly', async () => {+ await expect(readClientOpUsage(engine, { days: 0 })).rejects.toThrow(/days must be an integer/);+ await expect(readClientOpUsage(engine, { days: 1.5 })).rejects.toThrow(/days must be an integer/);+ await expect(readClientOpUsage(engine, { days: 10_000 })).rejects.toThrow(/days must be an integer/);+ });+});diff --git a/test/memory-verbs-conformance.test.ts b/test/memory-verbs-conformance.test.tsindex 12db67f966..4ecba91cbc 100644--- a/test/memory-verbs-conformance.test.ts+++ b/test/memory-verbs-conformance.test.ts@@ -329,6 +329,12 @@ describe('synthesize — marked expensive + unavailable conversion [c10]', () =>expect(body.cost.input_tokens).toBe(1200);expect(body.cost.output_tokens).toBe(80);expect(Array.isArray(body.sources)).toBe(true);+ // v0.45.x additive compose-status fields ride EVERY success response+ // (schema-optional for pre-v0.45.x servers, always emitted by this one).+ expect(body.synthesis_status).toBe('ok');+ expect(typeof body.pages_gathered).toBe('number');+ expect(typeof body.takes_gathered).toBe('number');+ expect(Array.isArray(body.warnings)).toBe(true);const violations = validateAgainstSchema(body, RESPONSE_SCHEMAS.synthesize);expect(violations).toEqual([]);});diff --git a/test/oauth-surface-ladder.test.ts b/test/oauth-surface-ladder.test.tsnew file mode 100644index 0000000000..48171b5ef5--- /dev/null+++ b/test/oauth-surface-ladder.test.ts@@ -0,0 +1,161 @@+/**+ * WP4 (amendments 17-19, ENG-9) — oauth_clients.surface threading + the+ * verifyAccessToken degrade ladder's NEW top rung + rescopeClient's surface+ * axis + the amendment-32 audit expectations at the provider layer.+ *+ * OWN PGlite instance (never the shared oauth.test.ts db): these tests DROP+ * OAuth columns to simulate pre-migration brains, which would poison every+ * later test on a shared database.+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGlite } from '@electric-sql/pglite';+import { vector } from '@electric-sql/pglite/vector';+import { pg_trgm } from '@electric-sql/pglite/contrib/pg_trgm';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { PGLITE_SCHEMA_SQL } from '../src/core/pglite-schema.ts';+import type { AuthInfo as CoreAuthInfo } from '../src/core/operations.ts';++let db: PGlite;+let sql: (strings: TemplateStringsArray, ...values: unknown[]) => Promise<any>;+let provider: GBrainOAuthProvider;++beforeAll(async () => {+ db = new PGlite({ extensions: { vector, pg_trgm } });+ await db.exec(PGLITE_SCHEMA_SQL);+ sql = async (strings: TemplateStringsArray, ...values: unknown[]) => {+ const query = strings.reduce((acc, str, i) => acc + str + (i < values.length ? `$${i + 1}` : ''), '');+ const result = await db.query(query, values as any[]);+ return result.rows;+ };+ provider = new GBrainOAuthProvider({ sql, tokenTtl: 60, refreshTtl: 300 });+}, 30_000);++afterAll(async () => {+ if (db) await db.close();+}, 15_000);++async function mintVerifiedClient(name: string): Promise<{ clientId: string; token: string }> {+ const { clientId, clientSecret } = await provider.registerClientManual(+ name, ['client_credentials'], 'read write',+ );+ const tokens = await provider.exchangeClientCredentials(clientId, clientSecret!, 'read');+ return { clientId, token: tokens.access_token };+}++describe('verifyAccessToken surface threading (WP4)', () => {+ test('fresh client → surface + surfaceSetBy undefined (column NULL)', async () => {+ const { token } = await mintVerifiedClient('surface-null-client');+ const info = await provider.verifyAccessToken(token) as unknown as CoreAuthInfo;+ expect(info.surface).toBeUndefined();+ expect(info.surfaceSetBy).toBeUndefined();+ });++ test('operator rescope --surface threads surface + surfaceSetBy=operator into AuthInfo', async () => {+ const { clientId, token } = await mintVerifiedClient('surface-rescope-client');+ const result = await provider.rescopeClient(clientId, { surface: 'starter' });+ expect(result.surface).toBe('starter');+ expect(result.surfaceOld).toBe(null);+ const info = await provider.verifyAccessToken(token) as unknown as CoreAuthInfo;+ expect(info.surface).toBe('starter');+ expect(info.surfaceSetBy).toBe('operator');+ });++ test("rescope --surface clear nulls BOTH columns; surfaceOld carries the prior value", async () => {+ const { clientId, token } = await mintVerifiedClient('surface-clear-client');+ await provider.rescopeClient(clientId, { surface: 'verbs' });+ const cleared = await provider.rescopeClient(clientId, { surface: null });+ expect(cleared.surface).toBe(null);+ expect(cleared.surfaceOld).toBe('verbs');+ const info = await provider.verifyAccessToken(token) as unknown as CoreAuthInfo;+ expect(info.surface).toBeUndefined();+ expect(info.surfaceSetBy).toBeUndefined();+ });++ test('rescope rejects an unrecognized surface value loudly', async () => {+ const { clientId } = await mintVerifiedClient('surface-badvalue-client');+ await expect(+ provider.rescopeClient(clientId, { surface: 'everything' as never }),+ ).rejects.toThrow(/--surface must be verbs \| starter \| full \| clear/);+ });++ test('rescope with surface leaves the other axes untouched', async () => {+ const { clientId } = await mintVerifiedClient('surface-axes-client');+ const before = await sql`SELECT source_id, federated_read FROM oauth_clients WHERE client_id = ${clientId}`;+ await provider.rescopeClient(clientId, { surface: 'full' });+ const after = await sql`SELECT source_id, federated_read, surface, surface_set_by FROM oauth_clients WHERE client_id = ${clientId}`;+ expect(after[0].source_id).toEqual(before[0].source_id);+ expect(after[0].federated_read).toEqual(before[0].federated_read);+ expect(after[0].surface).toBe('full');+ expect(after[0].surface_set_by).toBe('operator');+ });+});++describe('degrade ladder: v127 rung (amendment 17 / ENG-9)', () => {+ // Column drops are ordered narrowest-last and NOT restored — each block+ // walks the brain further back in schema history, mirroring how the+ // ladder degrades in production.++ test('pre-v127 brain (surface columns dropped): auth works, surface undefined, fence still threaded', async () => {+ // A bound client proves the v85 fence column survives the v127 rung drop.+ const bound = await provider.registerClientManual(+ 'ladder-bound-client', ['client_credentials'], 'read write', [], 'default', undefined, undefined,+ { boundSlugPrefixes: ['chan-eng/'] },+ );+ const boundTokens = await provider.exchangeClientCredentials(bound.clientId, bound.clientSecret!, 'read write');++ await db.exec(`+ ALTER TABLE oauth_clients DROP COLUMN IF EXISTS surface;+ ALTER TABLE oauth_clients DROP COLUMN IF EXISTS surface_set_by;+ `);++ const info = await provider.verifyAccessToken(boundTokens.access_token) as unknown as CoreAuthInfo;+ expect(info.clientId).toBe(bound.clientId);+ expect(info.surface).toBeUndefined();+ expect(info.surfaceSetBy).toBeUndefined();+ // The v85 rung's payload is intact — the new top rung dropped ONLY the+ // surface columns.+ expect(info.boundSlugPrefixes).toEqual(['chan-eng/']);+ expect(info.fenceProjectionDegraded).toBeUndefined();+ });++ test('pre-v127 brain: rescope --surface reports the migration gap, other axes still work', async () => {+ const { clientId } = await mintVerifiedClient('ladder-rescope-client');+ await expect(+ provider.rescopeClient(clientId, { surface: 'starter' }),+ ).rejects.toThrow(/up-to-date OAuth schema/);+ // Axes that predate v127 keep working on the same brain.+ const ok = await provider.rescopeClient(clientId, { sourceId: 'default' });+ expect(ok.clientId).toBe(clientId);+ expect(ok.surface).toBeUndefined();+ });++ test('pre-v85 brain (fence column also dropped): auth still works, fence fails closed', async () => {+ const { clientId, token } = await mintVerifiedClient('ladder-prev85-client');+ await db.exec(`ALTER TABLE oauth_clients DROP COLUMN IF EXISTS bound_slug_prefixes;`);+ const info = await provider.verifyAccessToken(token) as unknown as CoreAuthInfo;+ expect(info.clientId).toBe(clientId);+ expect(info.surface).toBeUndefined();+ expect(info.boundSlugPrefixes).toBeUndefined();+ // The fence axis (v85) keeps its own fail-closed degrade marker.+ expect(info.fenceProjectionDegraded).toBe(true);+ });++ test('pre-v61 brain (federated_read also dropped): auth still works, scalar grant synthesized', async () => {+ const { clientId, token } = await mintVerifiedClient('ladder-prev61-client');+ await db.exec(`ALTER TABLE oauth_clients DROP COLUMN IF EXISTS federated_read;`);+ const info = await provider.verifyAccessToken(token) as unknown as CoreAuthInfo;+ expect(info.clientId).toBe(clientId);+ expect(info.sourceId).toBe('default');+ expect(info.allowedSources).toEqual(['default']);+ });++ test('pre-v60 brain (source_id also dropped): the narrowest projection still authenticates', async () => {+ const { clientId, token } = await mintVerifiedClient('ladder-prev60-client');+ await db.exec(`ALTER TABLE oauth_clients DROP COLUMN IF EXISTS source_id;`);+ const info = await provider.verifyAccessToken(token) as unknown as CoreAuthInfo;+ expect(info.clientId).toBe(clientId);+ expect(info.sourceId).toBeUndefined();+ expect(info.surface).toBeUndefined();+ });+});diff --git a/test/oauth.test.ts b/test/oauth.test.tsindex 2389bfcf92..7e10862888 100644--- a/test/oauth.test.ts+++ b/test/oauth.test.ts@@ -231,7 +231,7 @@ describe('rescopeClient', () => {await expect(provider.rescopeClient(clientId, { sourceId: '../etc' })).rejects.toThrow('Invalid source_id');await expect(provider.rescopeClient(clientId, { federatedRead: ['ok', 'Not Valid!'] })).rejects.toThrow('Invalid source_id');await expect(provider.rescopeClient(clientId, { federatedRead: [] })).rejects.toThrow('cannot be empty');- await expect(provider.rescopeClient(clientId, {})).rejects.toThrow('requires --source, --federated-read, and/or --bound-slug-prefixes');+ await expect(provider.rescopeClient(clientId, {})).rejects.toThrow('requires --source, --federated-read, --bound-slug-prefixes, and/or --surface');// v0.42.70.0: an explicit empty prefix list is ambiguous (deny-all) — rejected.await expect(provider.rescopeClient(clientId, { boundSlugPrefixes: [] })).rejects.toThrow('cannot be an empty list');// An empty/whitespace ENTRY matches every slug under startsWith — it would@@ -900,7 +900,11 @@ describe('operation scope annotations', () => {// is read-scoped for OAuth/MCP because its handler forces save/take off// for remote callers before persistence (pinned by// test/takes-mcp-allowlist.serial.test.ts); local CLI can still persist.- const remoteReadOnlyMutatingOps = new Set(['think']);+ // WP4/D9: request_tools is read-scoped + mutating — its only write (the+ // {surface} persist branch) self-enforces the D2 ceiling, the operator+ // lock, and a per-client rate limit; the read scope keeps discovery+ // available to every token class (agent scope via the FOV-4 carve-out).+ const remoteReadOnlyMutatingOps = new Set(['think', 'request_tools']);for (const op of operations) {if (op.mutating) {if (remoteReadOnlyMutatingOps.has(op.name)) {diff --git a/test/operations-trust-boundary.test.ts b/test/operations-trust-boundary.test.tsindex 828a5085a4..54a48c15d2 100644--- a/test/operations-trust-boundary.test.ts+++ b/test/operations-trust-boundary.test.ts@@ -90,7 +90,11 @@ describe('operations contract — every op has scope + correct mutability shape'// `think` is read-scoped for OAuth/MCP because its handler forces// save/take OFF for remote callers before persistence — pinned by// test/takes-mcp-allowlist.serial.test.ts. Local CLI can still persist.- const REMOTE_READ_ONLY_MUTATING_OPS = new Set(['think']);+ // WP4/D9: request_tools is read-scoped + mutating — its only write (the+ // {surface} persist branch) self-enforces the D2 ceiling, the operator+ // lock, and a per-client rate limit (test/request-tools.test.ts pins all+ // three); read scope keeps discovery available to every token class.+ const REMOTE_READ_ONLY_MUTATING_OPS = new Set(['think', 'request_tools']);for (const op of operations) {if (op.mutating === true) {if (REMOTE_READ_ONLY_MUTATING_OPS.has(op.name)) {diff --git a/test/publish-gates.test.ts b/test/publish-gates.test.tsnew file mode 100644index 0000000000..8b1473aa82--- /dev/null+++ b/test/publish-gates.test.ts@@ -0,0 +1,105 @@+/**+ * WP1 honest catalog: publish-gate resolution for tools/list+ * (src/mcp/publish-gates.ts) and the shared bound-client predicate+ * (opAllowedForBoundClient) that keeps the advertised list and the dispatch+ * fence from drifting.+ */++import { describe, test, expect } from 'bun:test';+import { disabledOpsForPublishGates, readPublishGate } from '../src/mcp/publish-gates.ts';+import { operations, opAllowedForBoundClient, CLIENT_FENCED_WRITE_OPS } from '../src/core/operations.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import type { GBrainConfig } from '../src/core/config.ts';++const GATED_OPS = ['list_skills', 'get_skill', 'list_brain_skillpack', 'advisor'];++function engineWithConfig(values: Record<string, string | null> | 'throws'): BrainEngine {+ return {+ getConfig: async (key: string) => {+ if (values === 'throws') throw new Error('config table unavailable');+ return values[key] ?? null;+ },+ } as unknown as BrainEngine;+}++describe('publish-gates: gate declaration', () => {+ test('exactly the four gated ops carry publishGateKey', () => {+ const declared = operations.filter(o => o.publishGateKey).map(o => o.name).sort();+ expect(declared).toEqual([...GATED_OPS].sort());+ });+});++describe('publish-gates: disabledOpsForPublishGates', () => {+ test('gates absent on both planes → all four hidden (default-off posture)', async () => {+ const disabled = await disabledOpsForPublishGates(engineWithConfig({}), null);+ for (const name of GATED_OPS) expect(disabled.has(name)).toBe(true);+ });++ test('DB plane true → visible; per-key independence', async () => {+ const disabled = await disabledOpsForPublishGates(+ engineWithConfig({ 'mcp.publish_skills': 'true' }), null,+ );+ expect(disabled.has('list_skills')).toBe(false);+ expect(disabled.has('get_skill')).toBe(false);+ expect(disabled.has('list_brain_skillpack')).toBe(false);+ // advisor rides a SEPARATE gate and stays hidden.+ expect(disabled.has('advisor')).toBe(true);+ });++ test('DB plane false wins over file plane true (DB > file)', async () => {+ const cfg = { engine: 'pglite', mcp: { publish_skills: true } } as unknown as GBrainConfig;+ const disabled = await disabledOpsForPublishGates(+ engineWithConfig({ 'mcp.publish_skills': 'false' }), cfg,+ );+ expect(disabled.has('list_skills')).toBe(true);+ });++ test('file plane fallback when DB plane is unset', async () => {+ const cfg = { engine: 'pglite', mcp: { publish_advisor: true } } as unknown as GBrainConfig;+ const disabled = await disabledOpsForPublishGates(engineWithConfig({}), cfg);+ expect(disabled.has('advisor')).toBe(false);+ expect(disabled.has('list_skills')).toBe(true);+ });++ test('gate READ FAILURE hides the gated ops and never throws (ENG-20)', async () => {+ const disabled = await disabledOpsForPublishGates(engineWithConfig('throws'), null);+ for (const name of GATED_OPS) expect(disabled.has(name)).toBe(true);+ // Only the gated ops are affected — a config hiccup never hides the catalog.+ expect(disabled.size).toBe(GATED_OPS.length);+ });++ test('read failure with file-plane true → visible (file plane still decides)', async () => {+ const cfg = { engine: 'pglite', mcp: { publish_skills: true } } as unknown as GBrainConfig;+ expect(await readPublishGate(engineWithConfig('throws'), cfg, 'mcp.publish_skills')).toBe(true);+ });+});++describe('opAllowedForBoundClient (ENG-3: list filter and fence share one predicate)', () => {+ const readOp = { name: 'get_page', scope: 'read' as const, mutating: undefined };+ const fencedWrite = { name: 'put_page', scope: 'write' as const, mutating: undefined };+ const unfencedWrite = { name: 'import', scope: 'write' as const, mutating: undefined };+ const mutatingRead = { name: 'sources_add', scope: 'sources_admin' as const, mutating: true };++ test('unbound client: everything allowed', () => {+ for (const op of [readOp, fencedWrite, unfencedWrite, mutatingRead]) {+ expect(opAllowedForBoundClient(undefined, op)).toBe(true);+ expect(opAllowedForBoundClient({}, op)).toBe(true);+ }+ });++ test('bound client: reads + fenced writes allowed, everything else denied', () => {+ const auth = { boundSlugPrefixes: ['wiki/agents/x'] };+ expect(opAllowedForBoundClient(auth, readOp)).toBe(true);+ expect(opAllowedForBoundClient(auth, fencedWrite)).toBe(true);+ expect(opAllowedForBoundClient(auth, unfencedWrite)).toBe(false);+ expect(opAllowedForBoundClient(auth, mutatingRead)).toBe(false);+ expect(CLIENT_FENCED_WRITE_OPS.has(fencedWrite.name)).toBe(true);+ });++ test('degraded projection: reads only (fenced writes also denied)', () => {+ const auth = { fenceProjectionDegraded: true };+ expect(opAllowedForBoundClient(auth, readOp)).toBe(true);+ expect(opAllowedForBoundClient(auth, fencedWrite)).toBe(false);+ expect(opAllowedForBoundClient(auth, unfencedWrite)).toBe(false);+ });+});diff --git a/test/put-page-writer-lint.test.ts b/test/put-page-writer-lint.test.tsnew file mode 100644index 0000000000..d6c9123308--- /dev/null+++ b/test/put-page-writer-lint.test.ts@@ -0,0 +1,271 @@+/**+ * put_page writer_lint payload tests (T11 writer-lint visibility).+ *+ * Pins the extended writer_lint response contract, previously unpinned:+ * - lint ran, zero findings → full summary present with zeroed fields+ * - lint ran, findings past the cap → errors-first top_findings (cap 5),+ * details_truncated, by_validator histogram, one actionable hint each+ * - lint crashed → {status: 'lint_error'} (distinguishable from lint-off)+ * - flag off / validate:false frontmatter → writer_lint key absent+ * - FIX_HINTS completeness against the BUILTIN_VALIDATORS registry+ *+ * The crash path is pinned at the writerLintForPutPage seam (a stub engine+ * whose getPage rejects): put_page spreads whatever the seam returns, and+ * crashing the real handler mid-flow would need a module-level mock+ * (serial-file quarantine) for no extra coverage.+ *+ * PGLite hermetic; resetGateway() keeps embedding auto-detect keyless.+ */++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { mkdtempSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { resetGateway } from '../src/core/ai/gateway.ts';+import { operations } from '../src/core/operations.ts';+import type { OperationContext, Operation } from '../src/core/operations.ts';+import {+ summarizeWriterLint,+ writerLintForPutPage,+ type WriterLintSummary,+} from '../src/core/output/post-write.ts';+import { BUILTIN_VALIDATORS, FIX_HINTS } from '../src/core/output/validators/index.ts';+import type { ValidationFinding } from '../src/core/output/writer.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;++const put_page = operations.find(o => o.name === 'put_page') as Operation;+if (!put_page) throw new Error('put_page op missing');++function makeCtx(overrides: Partial<OperationContext> = {}): OperationContext {+ return {+ engine,+ config: { engine: 'pglite' } as any,+ logger: { info: () => {}, warn: () => {}, error: () => {} },+ dryRun: false,+ remote: true,+ sourceId: 'default',+ ...overrides,+ };+}++function page(body: string, frontmatterLines: string[] = []): string {+ return ['---', 'type: concept', 'title: Notes', ...frontmatterLines, '---', '', body].join('\n');+}++/** No citation markers, all factual per looksFactual — one citation error each. */+const SIX_UNCITED_PARAGRAPHS = [+ 'Acme raised a $5M seed round from fund-a in early 2024.',+ 'The founder previously built a payments product at widget-co.',+ 'Acme shipped its first public beta to customers in March 2025.',+ 'The team has twelve engineers and two designers on staff today.',+ 'Acme was founded in a garage in Mountain View by two brothers.',+ 'The company will launch its enterprise tier early next quarter.',+].join('\n\n');++function finding(over: Partial<ValidationFinding> = {}): ValidationFinding {+ return {+ slug: 'people/x',+ validator: 'citation',+ severity: 'error',+ line: 3,+ message: 'Paragraph has no citation marker',+ ...over,+ };+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => {+ if (engine) await engine.disconnect();+ resetGateway();+}, 60_000);++beforeEach(async () => {+ await resetPgliteState(engine);+ // Keyless embedding auto-detect: another file in this shard process may+ // have configured the module-global gateway; put_page reads it for noEmbed.+ resetGateway();+});++describe('FIX_HINTS registry completeness (ENG-12)', () => {+ test('every BUILTIN_VALIDATORS id has a non-empty hint', () => {+ expect(BUILTIN_VALIDATORS.length).toBeGreaterThanOrEqual(4);+ for (const v of BUILTIN_VALIDATORS) {+ const hint = FIX_HINTS[v.id];+ expect(typeof hint).toBe('string');+ expect((hint ?? '').length).toBeGreaterThan(0);+ }+ });++ test('registry covers the four known validators', () => {+ const ids = BUILTIN_VALIDATORS.map(v => v.id).sort();+ expect(ids).toEqual(['back-link', 'citation', 'link', 'triple-hr']);+ });++ test('FIX_HINTS carries no orphan keys (hints derive from the registry)', () => {+ const ids = new Set(BUILTIN_VALIDATORS.map(v => v.id));+ for (const key of Object.keys(FIX_HINTS)) {+ expect(ids.has(key)).toBe(true);+ }+ });+});++describe('summarizeWriterLint', () => {+ test('zero findings → zeroed summary with empty structures', () => {+ expect(summarizeWriterLint([])).toEqual({+ error_count: 0,+ warning_count: 0,+ top_findings: [],+ details_truncated: false,+ by_validator: {},+ });+ });++ test('errors sort before warnings; order within a severity is stable', () => {+ const s = summarizeWriterLint([+ finding({ validator: 'back-link', severity: 'warning', message: 'w1' }),+ finding({ validator: 'citation', severity: 'error', message: 'e1' }),+ finding({ validator: 'triple-hr', severity: 'warning', message: 'w2' }),+ finding({ validator: 'link', severity: 'error', message: 'e2' }),+ ]);+ expect(s.top_findings.map(f => f.message)).toEqual(['e1', 'e2', 'w1', 'w2']);+ });++ test('caps top_findings at 5 and flags details_truncated', () => {+ const findings = Array.from({ length: 7 }, (_, i) => finding({ message: `e${i}` }));+ const s = summarizeWriterLint(findings);+ expect(s.top_findings).toHaveLength(5);+ expect(s.details_truncated).toBe(true);+ expect(s.error_count).toBe(7);+ });++ test('exactly 5 findings is not truncated', () => {+ const findings = Array.from({ length: 5 }, (_, i) => finding({ message: `e${i}` }));+ const s = summarizeWriterLint(findings);+ expect(s.top_findings).toHaveLength(5);+ expect(s.details_truncated).toBe(false);+ });++ test('by_validator counts EVERY finding, not just the top 5', () => {+ const findings = [+ ...Array.from({ length: 6 }, () => finding({ validator: 'citation' })),+ finding({ validator: 'link', severity: 'warning' }),+ ];+ expect(summarizeWriterLint(findings).by_validator).toEqual({ citation: 6, link: 1 });+ });++ test('long messages are truncated to the cap with an ellipsis tail', () => {+ const s = summarizeWriterLint([finding({ message: 'x'.repeat(300) })]);+ expect(s.top_findings[0].message).toHaveLength(200);+ expect(s.top_findings[0].message.endsWith('...')).toBe(true);+ });++ test('line rides through when present and is omitted when absent', () => {+ const s = summarizeWriterLint([+ finding({ line: 12 }),+ finding({ line: undefined }),+ ]);+ expect(s.top_findings[0].line).toBe(12);+ expect('line' in s.top_findings[1]).toBe(false);+ });++ test('hints come from FIX_HINTS; unknown validators get the fallback', () => {+ const s = summarizeWriterLint([+ finding({ validator: 'citation' }),+ finding({ validator: 'not-a-builtin' }),+ ]);+ expect(s.top_findings[0].hint).toBe(FIX_HINTS['citation']);+ expect(s.top_findings[1].hint.length).toBeGreaterThan(0);+ });+});++describe('writerLintForPutPage outcome mapping', () => {+ test('lint machinery throwing → {status: lint_error}, never a throw', async () => {+ const broken = {+ getPage: async () => { throw new Error('db exploded mid-lint'); },+ } as unknown as BrainEngine;+ // force:true skips the config read, so getPage is the first engine touch.+ const payload = await writerLintForPutPage(broken, 'people/x', { force: true });+ expect(payload).toEqual({ status: 'lint_error' });+ });++ test('lint off (flag unset) → undefined, so the key stays absent', async () => {+ const off = {+ getConfig: async () => null,+ } as unknown as BrainEngine;+ expect(await writerLintForPutPage(off, 'people/x')).toBeUndefined();+ });+});++describe('put_page writer_lint payload (PGLite e2e)', () => {+ test('lint ran with zero findings → summary present, all zeroed', async () => {+ await engine.setConfig('writer.lint_on_put_page', 'true');+ const r = await put_page.handler(makeCtx(), {+ slug: 'notes/clean',+ content: page('## See Also\n- [Source: X/clean, 2026-04-18](https://x.com/clean/status/1)'),+ }) as { writer_lint?: WriterLintSummary };+ expect(r.writer_lint).toEqual({+ error_count: 0,+ warning_count: 0,+ top_findings: [],+ details_truncated: false,+ by_validator: {},+ });+ });++ test('findings past the cap → errors-first top 5, truncation flag, histogram, hints', async () => {+ await engine.setConfig('writer.lint_on_put_page', 'true');+ // 6 uncited factual paragraphs (citation errors) + 1 mailto bullet (link+ // warning). The local lint log writes under GBRAIN_HOME — point it at tmp.+ const home = mkdtempSync(join(tmpdir(), 'gbrain-lint-home-'));+ const r = await withEnv({ GBRAIN_HOME: home }, async () =>+ await put_page.handler(makeCtx(), {+ slug: 'notes/dirty',+ content: page(`${SIX_UNCITED_PARAGRAPHS}\n\n- [contact](mailto:[email protected])`),+ }) as { writer_lint?: WriterLintSummary },+ );++ const lint = r.writer_lint!;+ expect(lint.error_count).toBe(6);+ expect(lint.warning_count).toBe(1);+ expect(lint.details_truncated).toBe(true);+ expect(lint.by_validator).toEqual({ citation: 6, link: 1 });++ expect(lint.top_findings).toHaveLength(5);+ for (const f of lint.top_findings) {+ // Errors-first at cap 5 with 6 errors present → all five are errors.+ expect(f.severity).toBe('error');+ expect(f.validator).toBe('citation');+ expect(typeof f.line).toBe('number');+ expect(f.message).toContain('no citation marker');+ expect(f.hint).toBe(FIX_HINTS['citation']);+ }+ });++ test('flag off → writer_lint key absent (lint-off, not a crash)', async () => {+ const r = await put_page.handler(makeCtx(), {+ slug: 'notes/flag-off',+ content: page(SIX_UNCITED_PARAGRAPHS),+ }) as Record<string, unknown>;+ expect('writer_lint' in r).toBe(false);+ });++ test('validate:false frontmatter → key absent even with the flag on', async () => {+ await engine.setConfig('writer.lint_on_put_page', 'true');+ const r = await put_page.handler(makeCtx(), {+ slug: 'notes/grandfathered',+ content: page(SIX_UNCITED_PARAGRAPHS, ['validate: false']),+ }) as Record<string, unknown>;+ expect('writer_lint' in r).toBe(false);+ });+});diff --git a/test/request-tools.test.ts b/test/request-tools.test.tsnew file mode 100644index 0000000000..bb56f354a2--- /dev/null+++ b/test/request-tools.test.ts@@ -0,0 +1,377 @@+/**+ * WP4 (T9) — request_tools meta-op: catalog visibility (never leak hidden+ * names), read-only descriptor fetch (D5), and the {surface} persist branch+ * (D2 ceiling deny, operator lock, rate limit, no-clientId path, audit row,+ * migration-pending fallback).+ *+ * Exercised via dispatchToolCall against a real PGLite engine so the tests+ * cover the same envelope + validation path MCP clients hit.+ */++import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import {+ operations,+ __resetRequestToolsPersistLimiterForTests,+ type AuthInfo,+} from '../src/core/operations.ts';+import { VERB_NAMES } from '../src/core/verbs.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ // Pin the publish gates OFF on the DB plane (which wins over the file+ // plane) so the developer's real ~/.gbrain/config.json can't flip the+ // gated-op visibility assertions below.+ await engine.setConfig('mcp.publish_skills', 'false');+ await engine.setConfig('mcp.publish_advisor', 'false');+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(() => {+ __resetRequestToolsPersistLimiterForTests();+});++function parsed(result: { content: Array<{ text: string }> }) {+ return JSON.parse(result.content[0].text);+}++interface CatalogEntry { area: string; tools: Array<{ name: string; one_line: string }> }++function flatNames(catalog: CatalogEntry[]): string[] {+ return catalog.flatMap(g => g.tools.map(t => t.name));+}++async function seedClient(clientId: string, extra: { surface?: string; setBy?: string } = {}): Promise<void> {+ await engine.executeRaw(+ `INSERT INTO oauth_clients (client_id, client_name, surface, surface_set_by)+ VALUES ($1, $2, $3, $4)+ ON CONFLICT (client_id) DO UPDATE SET surface = $3, surface_set_by = $4`,+ [clientId, `test ${clientId}`, extra.surface ?? null, extra.setBy ?? null],+ );+}++function authFor(clientId: string, scopes: string[], extra: Partial<AuthInfo> = {}): AuthInfo {+ return { token: 't', clientId, scopes, ...extra };+}++const HTTP = { remote: true, transport: 'http' as const, sourceId: 'default' };++describe('request_tools catalog (no args)', () => {+ test('http transport, no auth: grouped by area; localOnly + gated ops never named', async () => {+ const res = await dispatchToolCall(engine, 'request_tools', {}, { ...HTTP });+ expect(res.isError ?? false).toBe(false);+ const body = parsed(res);+ expect(Array.isArray(body.catalog)).toBe(true);+ expect(body.total_tools).toBeGreaterThan(20);+ const names = flatNames(body.catalog);+ // Areas group the names; every group has a non-empty area label + one_lines.+ for (const group of body.catalog as CatalogEntry[]) {+ expect(typeof group.area).toBe('string');+ expect(group.area.length).toBeGreaterThan(0);+ for (const t of group.tools) expect(t.one_line.length).toBeGreaterThan(0);+ }+ expect(names).toContain('get_page');+ expect(names).toContain('put_page');+ expect(names).toContain('request_tools');+ // localOnly ops are hidden on network transports (D7)…+ expect(names).not.toContain('file_list');+ expect(names).not.toContain('sync_brain');+ // …and publish-gated ops are hidden while their gate is off (default).+ expect(names).not.toContain('list_skills');+ expect(names).not.toContain('get_skill');+ expect(names).not.toContain('list_brain_skillpack');+ expect(names).not.toContain('advisor');+ // Raw payload never leaks a gated name anywhere (C8 class).+ const raw = res.content[0].text;+ expect(raw).not.toContain('list_skills');+ expect(raw).not.toContain('advisor');+ });++ test('stdio transport: localOnly listed (D7) and publish gates bypassed (local surface)', async () => {+ const res = await dispatchToolCall(engine, 'request_tools', {}, {+ remote: true, transport: 'stdio', sourceId: 'default',+ });+ const names = flatNames(parsed(res).catalog);+ expect(names).toContain('file_list');+ expect(names).toContain('list_skills');+ });++ test('trusted local CLI (remote === false, no transport): localOnly + gated ops visible', async () => {+ const res = await dispatchToolCall(engine, 'request_tools', {}, {+ remote: false, sourceId: 'default',+ });+ const names = flatNames(parsed(res).catalog);+ // The local operator CAN call all of these (assertPublishEnabled exempts+ // remote === false), so hiding them would make the catalog dishonest.+ expect(names).toContain('file_list'); // localOnly+ expect(names).toContain('sync_brain'); // localOnly+ expect(names).toContain('list_skills'); // publish-gated (gates pinned off above)+ expect(names).toContain('advisor'); // publish-gated+ });++ test('read-scope token: write/admin ops hidden, reads visible', async () => {+ const res = await dispatchToolCall(engine, 'request_tools', {}, {+ ...HTTP, auth: authFor('ro-client', ['read']),+ });+ const names = flatNames(parsed(res).catalog);+ expect(names).toContain('get_page');+ expect(names).toContain('request_tools');+ expect(names).not.toContain('put_page'); // write scope+ expect(names).not.toContain('run_doctor'); // admin scope+ expect(names).not.toContain('submit_agent'); // agent scope+ });++ test('FOV-4: agent-only token gets the honest minimal catalog (agent lane + request_tools)', async () => {+ const res = await dispatchToolCall(engine, 'request_tools', {}, {+ ...HTTP, auth: authFor('agent-client', ['agent']),+ });+ const names = flatNames(parsed(res).catalog).sort();+ expect(names).toEqual(['get_agent_job', 'request_tools', 'submit_agent']);+ });++ test('D9: a slug-bound client keeps discovery; unfenceable writes stay hidden', async () => {+ const res = await dispatchToolCall(engine, 'request_tools', {}, {+ ...HTTP, auth: authFor('bound-client', ['read', 'write'], { boundSlugPrefixes: ['chan-a/'] }),+ });+ // Without the BOUND_CLIENT_META_OPS carve-out, the dispatch fence would+ // have denied this call outright (request_tools is mutating).+ expect(parsed(res).catalog).toBeDefined();+ const names = flatNames(parsed(res).catalog);+ expect(names).toContain('put_page'); // fenced-write allow-list+ expect(names).not.toContain('extract_facts'); // unfenceable write+ });++ test('D2: the catalog never names ops above the server ceiling', async () => {+ const res = await dispatchToolCall(engine, 'request_tools', {}, {+ ...HTTP, surfaceCeiling: 'verbs',+ });+ const names = flatNames(parsed(res).catalog).sort();+ expect(names).toEqual([...VERB_NAMES].sort());+ });+});++describe('request_tools {tools: [...]} descriptor fetch (D5)', () => {+ test('returns full schemas for the visible subset; hidden/unknown names silently omitted', async () => {+ const res = await dispatchToolCall(engine, 'request_tools', {+ tools: ['get_page', 'put_page', 'file_list', 'no_such_tool_xyz', 'get_page'],+ }, { ...HTTP, auth: authFor('ro-client', ['read']) });+ const body = parsed(res);+ expect(Array.isArray(body.tools)).toBe(true);+ const names = body.tools.map((t: { name: string }) => t.name);+ // Visible + deduped: put_page (write scope), file_list (localOnly), and+ // the unknown name are all silently omitted.+ expect(names).toEqual(['get_page']);+ expect(body.tools[0].inputSchema.type).toBe('object');+ expect(body.tools[0].inputSchema.properties.slug).toBeDefined();+ const raw = res.content[0].text;+ expect(raw).not.toContain('no_such_tool_xyz');+ });+});++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');+ const res = await dispatchToolCall(engine, 'request_tools', { surface: 'starter' }, {+ ...HTTP, surfaceCeiling: 'full', auth: authFor('cl-persist', ['read']),+ });+ const body = parsed(res);+ expect(body.persisted).toBe(true);+ expect(body.surface).toBe('starter');+ expect(body.note).toContain('tools/list');++ const rows = await engine.executeRaw(+ `SELECT surface, surface_set_by FROM oauth_clients WHERE client_id = $1`, ['cl-persist'],+ );+ expect(rows[0].surface).toBe('starter');+ expect(rows[0].surface_set_by).toBe('self');++ // Amendment 32 / ENG-8: the mutation is answerable from logs alone.+ const audit = await engine.executeRaw(+ `SELECT token_name, params FROM mcp_request_log+ WHERE operation = 'surface_change' AND token_name = $1`, ['cl-persist'],+ );+ expect(audit.length).toBe(1);+ const params = audit[0].params as { actor: string; client_id: string; old: string | null; new: string | null; via: string };+ expect(params.via).toBe('request_tools');+ expect(params.actor).toBe('cl-persist');+ expect(params.old).toBe(null);+ expect(params.new).toBe('starter');+ });++ test('D2 ceiling deny: widening past the ceiling is a machine-readable permission_denied', async () => {+ await seedClient('cl-ceiling');+ const res = await dispatchToolCall(engine, 'request_tools', { surface: 'full' }, {+ ...HTTP, surfaceCeiling: 'starter', auth: authFor('cl-ceiling', ['read']),+ });+ expect(res.isError).toBe(true);+ const body = parsed(res);+ expect(body.error).toBe('permission_denied');+ expect(body.detail).toBe('ceiling=starter');+ // Narrowing below the ceiling is always allowed.+ const ok = await dispatchToolCall(engine, 'request_tools', { surface: 'verbs' }, {+ ...HTTP, surfaceCeiling: 'starter', auth: authFor('cl-ceiling', ['read']),+ });+ expect(parsed(ok).persisted).toBe(true);+ });++ test('operator lock deny (amendment 19): surface_set_by=operator cannot be self-overridden', async () => {+ await seedClient('cl-locked', { surface: 'verbs', setBy: 'operator' });+ const res = await dispatchToolCall(engine, 'request_tools', { surface: 'full' }, {+ ...HTTP, surfaceCeiling: 'full', auth: authFor('cl-locked', ['read']),+ });+ expect(res.isError).toBe(true);+ const body = parsed(res);+ expect(body.error).toBe('permission_denied');+ expect(body.detail).toBe('locked_by=operator');+ const rows = await engine.executeRaw(+ `SELECT surface FROM oauth_clients WHERE client_id = $1`, ['cl-locked'],+ );+ expect(rows[0].surface).toBe('verbs'); // untouched+ });++ test('no clientId (stdio): persist no-ops with a reason, never an error', async () => {+ const res = await dispatchToolCall(engine, 'request_tools', { surface: 'starter' }, {+ remote: true, transport: 'stdio', sourceId: 'default', surfaceCeiling: 'full',+ });+ expect(res.isError ?? false).toBe(false);+ const body = parsed(res);+ expect(body.persisted).toBe(false);+ expect(body.reason).toContain('no per-client surface');+ });++ test('legacy token (clientId not an oauth_clients row): persist no-ops with the same reason', async () => {+ const res = await dispatchToolCall(engine, 'request_tools', { surface: 'starter' }, {+ ...HTTP, surfaceCeiling: 'full', auth: authFor('legacy-token-row-id', ['read']),+ });+ const body = parsed(res);+ expect(body.persisted).toBe(false);+ expect(body.reason).toContain('no per-client surface');+ });++ test('rate limit (D14.5): ~5 persists/hour/client, 6th is rate_limited', async () => {+ await seedClient('cl-rl');+ const opts = { ...HTTP, surfaceCeiling: 'full' as const, auth: authFor('cl-rl', ['read']) };+ for (let i = 0; i < 5; i++) {+ const res = await dispatchToolCall(engine, 'request_tools', {+ surface: i % 2 === 0 ? 'starter' : 'full',+ }, opts);+ expect(parsed(res).persisted).toBe(true);+ }+ const sixth = await dispatchToolCall(engine, 'request_tools', { surface: 'verbs' }, opts);+ expect(sixth.isError).toBe(true);+ expect(parsed(sixth).error).toBe('rate_limited');+ // A different client is unaffected (per-client buckets).+ await seedClient('cl-rl-2');+ const other = await dispatchToolCall(engine, 'request_tools', { surface: 'starter' }, {+ ...HTTP, surfaceCeiling: 'full', auth: authFor('cl-rl-2', ['read']),+ });+ expect(parsed(other).persisted).toBe(true);+ });++ test('{surface, tools} together → invalid_params, never a persist (D5 branch exclusivity)', async () => {+ await seedClient('cl-both');+ const res = await dispatchToolCall(engine, 'request_tools', { surface: 'starter', tools: ['query'] }, {+ ...HTTP, surfaceCeiling: 'full', auth: authFor('cl-both', ['read']),+ });+ expect(res.isError).toBe(true);+ const body = parsed(res);+ expect(body.error).toBe('invalid_params');+ expect(body.message).toContain('not both');+ const rows = await engine.executeRaw(+ `SELECT surface FROM oauth_clients WHERE client_id = $1`, ['cl-both'],+ );+ expect(rows[0].surface).toBe(null);+ });++ test('RateLimiter.refund returns a token so a race-lost persist never burns budget (adversarial fix)', async () => {+ // The handler refunds when the atomic UPDATE affects 0 rows (a concurrent+ // operator pin between SELECT and UPDATE); pin the primitive it leans on.+ const { RateLimiter } = await import('../src/mcp/rate-limit.ts');+ const now = 0;+ const lim = new RateLimiter({ limit: 2, windowMs: 60_000, lruCap: 10 }, () => now);+ expect(lim.check('k').allowed).toBe(true);+ expect(lim.check('k').allowed).toBe(true);+ expect(lim.check('k').allowed).toBe(false); // exhausted+ lim.refund('k');+ expect(lim.check('k').allowed).toBe(true); // refund restored exactly one token+ expect(lim.check('k').allowed).toBe(false);+ lim.refund('unknown-key'); // no-op, never throws+ // Refund never overfills past the limit.+ const lim2 = new RateLimiter({ limit: 1, windowMs: 60_000, lruCap: 10 }, () => now);+ expect(lim2.check('k').allowed).toBe(true);+ lim2.refund('k');+ lim2.refund('k');+ expect(lim2.check('k').allowed).toBe(true);+ expect(lim2.check('k').allowed).toBe(false);+ });++ test('invalid surface value → invalid_params naming the valid set (D10: never a persist)', async () => {+ await seedClient('cl-garbage');+ const res = await dispatchToolCall(engine, 'request_tools', { surface: 'garbage' }, {+ ...HTTP, surfaceCeiling: 'full', auth: authFor('cl-garbage', ['read']),+ });+ expect(res.isError).toBe(true);+ const body = parsed(res);+ expect(body.error).toBe('invalid_params');+ expect(body.message).toContain('verbs, starter, full');+ const rows = await engine.executeRaw(+ `SELECT surface FROM oauth_clients WHERE client_id = $1`, ['cl-garbage'],+ );+ expect(rows[0].surface).toBe(null);+ });++ test('dry_run: reports without writing', async () => {+ await seedClient('cl-dry');+ const res = await dispatchToolCall(engine, 'request_tools', { surface: 'starter', dry_run: true }, {+ ...HTTP, surfaceCeiling: 'full', auth: authFor('cl-dry', ['read']),+ });+ const body = parsed(res);+ expect(body.persisted).toBe(false);+ expect(body.dry_run).toBe(true);+ const rows = await engine.executeRaw(+ `SELECT surface FROM oauth_clients WHERE client_id = $1`, ['cl-dry'],+ );+ expect(rows[0].surface).toBe(null);+ });++ test('dry-run previews never consume the persist budget (D14.5)', async () => {+ await seedClient('cl-dry-budget');+ const opts = { ...HTTP, surfaceCeiling: 'full' as const, auth: authFor('cl-dry-budget', ['read']) };+ for (let i = 0; i < 5; i++) {+ const res = await dispatchToolCall(engine, 'request_tools', { surface: 'starter', dry_run: true }, opts);+ expect(parsed(res).dry_run).toBe(true);+ }+ // The limiter meters actual writes only: a real persist still succeeds+ // after 5 previews (pre-fix, the previews exhausted the budget).+ const real = await dispatchToolCall(engine, 'request_tools', { surface: 'starter' }, opts);+ expect(real.isError ?? false).toBe(false);+ expect(parsed(real).persisted).toBe(true);+ });++ // LAST: mutates the schema (drops the v127 columns); the finally block+ // restores them so the shared engine stays whole for any later suite.+ test('pre-migration brain: persist reports {persisted:false, reason:"migration pending"} (D5)', async () => {+ try {+ await engine.executeRaw(`ALTER TABLE oauth_clients DROP COLUMN IF EXISTS surface`, []);+ await engine.executeRaw(`ALTER TABLE oauth_clients DROP COLUMN IF EXISTS surface_set_by`, []);+ const res = await dispatchToolCall(engine, 'request_tools', { surface: 'starter' }, {+ ...HTTP, surfaceCeiling: 'full', auth: authFor('cl-persist', ['read']),+ });+ expect(res.isError ?? false).toBe(false);+ const body = parsed(res);+ expect(body.persisted).toBe(false);+ expect(body.reason).toBe('migration pending');+ } finally {+ await engine.executeRaw(`ALTER TABLE oauth_clients ADD COLUMN IF NOT EXISTS surface TEXT`, []);+ await engine.executeRaw(`ALTER TABLE oauth_clients ADD COLUMN IF NOT EXISTS surface_set_by TEXT`, []);+ }+ });+});diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.tsindex c5c5bf8ce6..9ed1c29e56 100644--- a/test/schema-bootstrap-coverage.test.ts+++ b/test/schema-bootstrap-coverage.test.ts@@ -121,6 +121,11 @@ const REQUIRED_BOOTSTRAP_COVERAGE: ForwardReference[] = [// them before SCHEMA_SQL replay creates the FK + index.{ kind: 'column', table: 'oauth_clients', column: 'source_id' },{ kind: 'column', table: 'oauth_clients', column: 'federated_read' },+ // WP4 (v127) — per-client MCP tool surface + operator-lock marker. Not+ // indexed, but migration-added AND present in the blob's CREATE TABLE (the+ // v121 mask class), so the bootstrap adds them on pre-v127 brains.+ { kind: 'column', table: 'oauth_clients', column: 'surface' },+ { kind: 'column', table: 'oauth_clients', column: 'surface_set_by' },// v0.26.5 (v34) — promotes archive lifecycle from JSONB config to real// columns on sources. CREATE TABLE IF NOT EXISTS is a no-op on existing// sources tables, so the visibility filters in search/list_pages that@@ -250,6 +255,10 @@ test('applyForwardReferenceBootstrap covers every forward reference declared inDROP INDEX IF EXISTS idx_oauth_clients_federated_read;ALTER TABLE oauth_clients DROP COLUMN IF EXISTS source_id;ALTER TABLE oauth_clients DROP COLUMN IF EXISTS federated_read;+ -- WP4 (v127) strip: surface columns are migration-added; bootstrap+ -- must re-add them.+ ALTER TABLE oauth_clients DROP COLUMN IF EXISTS surface;+ ALTER TABLE oauth_clients DROP COLUMN IF EXISTS surface_set_by;-- v0.40.3.0 v90 + v91 column strips so applyForwardReferenceBootstrap-- has work to do. Only strip pages columns + the trigger; sources@@ -368,6 +377,12 @@ test('after bootstrap, PGLITE_SCHEMA_SQL replays without crashing on missing forDROP INDEX IF EXISTS uniq_minion_jobs_idempotency;ALTER TABLE minion_jobs DROP COLUMN IF EXISTS timeout_at;ALTER TABLE minion_jobs DROP COLUMN IF EXISTS idempotency_key;++ -- WP4 (v127) strip: surface columns + the wedge-signal index; replay+ -- must succeed from the pre-v127 shape.+ DROP INDEX IF EXISTS idx_minion_jobs_queue_status_updated;+ ALTER TABLE oauth_clients DROP COLUMN IF EXISTS surface;+ ALTER TABLE oauth_clients DROP COLUMN IF EXISTS surface_set_by;`);// Bootstrap, then schema replay. Either step crashing fails the test.diff --git a/test/search-alias-resolved-boost.test.ts b/test/search-alias-resolved-boost.test.tsindex 9a4888c4b0..3d72a9696a 100644--- a/test/search-alias-resolved-boost.test.ts+++ b/test/search-alias-resolved-boost.test.ts@@ -89,7 +89,7 @@ describe('alias_resolved boost stage', () => {});describe('KNOBS_HASH_VERSION', () => {- it('is 16 (15→16 detail fold makes detail-contaminated rows unreachable, #3515)', () => {- expect(KNOBS_HASH_VERSION).toBe(16);+ it('is 17 (15→16 detail fold #3515; 16→17 degradation-stamp epoch: pre-stamp cache rows become unreachable)', () => {+ expect(KNOBS_HASH_VERSION).toBe(17);});});diff --git a/test/search-mode.test.ts b/test/search-mode.test.tsindex 2014be682c..5058970a16 100644--- a/test/search-mode.test.ts+++ b/test/search-mode.test.ts@@ -422,7 +422,7 @@ describe('knobsHash determinism + cross-mode separation (CDX-4)', () => {// not survive a `reindex-search-vector` switch.// #3515: bumped 15→16 to fold the effective detail level (det=) — a// detail=low write must not be served to a detail=medium lookup.- expect(KNOBS_HASH_VERSION).toBe(16);+ expect(KNOBS_HASH_VERSION).toBe(17);});test('#3515: detail set vs unset produces DIFFERENT hashes (cache contamination prevention)', () => {@@ -437,6 +437,9 @@ describe('knobsHash determinism + cross-mode separation (CDX-4)', () => {// Undefined falls back to 'medium' — the documented default — so legacy// callers that don't thread detail share the default-detail rows.expect(unset).toBe(medium);+ // WP2/T3: bumped 16→17 for the degradation-stamp epoch — cache rows now+ // carry degraded[]/retrieved_count; pre-stamp rows must not claim clean.+ expect(KNOBS_HASH_VERSION).toBe(17);});test('T1 (codex): floor_ratio set vs unset produces DIFFERENT hashes (cache contamination prevention)', () => {@@ -601,8 +604,8 @@ describe('v0.40.4 — graph_signals knob', () => {});describe('v0.42.3.0 — autocut knobs', () => {- test('KNOBS_HASH_VERSION is 16 (15→16 detail fold #3515)', () => {- expect(KNOBS_HASH_VERSION).toBe(16);+ test('KNOBS_HASH_VERSION is 17 (15→16 detail fold #3515; 16→17 degradation-stamp epoch)', () => {+ expect(KNOBS_HASH_VERSION).toBe(17);});test('bundle defaults: conservative off, balanced/tokenmax on @0.20', () => {diff --git a/test/search-telemetry.test.ts b/test/search-telemetry.test.tsindex c6f31f08a3..ac76da6e04 100644--- a/test/search-telemetry.test.ts+++ b/test/search-telemetry.test.ts@@ -232,12 +232,96 @@ describe('readSearchStats — read-time derived averages', () => {});test('missing search_telemetry table → empty stats (graceful)', async () => {- // Drop the table to simulate a pre-v0.32.3 brain.- await engine.executeRaw('DROP TABLE IF EXISTS search_telemetry');+ // Simulate a pre-v0.32.3 brain by HIDING the table — a rename preserves+ // the full column shape for the tests that follow. (The prior+ // DROP + initSchema() restore was a silent no-op: the migration ledger+ // already records v57, so initSchema never recreated the table.)+ await engine.executeRaw('ALTER TABLE search_telemetry RENAME TO search_telemetry_hidden');+ try {+ const s = await readSearchStats(engine, { days: 7 });+ expect(s.total_calls).toBe(0);+ expect(s.cache_hit_rate).toBe(0);+ expect(s.empty_results).toEqual({ total: 0, by_cause: {} });+ } finally {+ await engine.executeRaw('ALTER TABLE search_telemetry_hidden RENAME TO search_telemetry');+ }+ });+});++// WP2/T3 — empty-result cause rollup. Rides the reserved+// (date, EMPTY_RESULT_MODE, cause) rows with zero new DDL; readSearchStats+// diverts them out of the call/intent/mode aggregates.+describe('empty_result bucket keyed by cause (WP2/T3)', () => {+ test('vector down + empty response → vector_disabled cause', async () => {+ const w = getTelemetryWriter();+ w.setEngine(engine);+ recordSearchTelemetry(engine, makeMeta({ vector_enabled: false }), { results_count: 0 });+ await w.flush();const s = await readSearchStats(engine, { days: 7 });- expect(s.total_calls).toBe(0);- expect(s.cache_hit_rate).toBe(0);- // Restore for subsequent tests in this describe block.- await engine.initSchema();+ expect(s.empty_results.total).toBe(1);+ expect(s.empty_results.by_cause).toEqual({ vector_disabled: 1 });+ });++ test('budget dropped everything → budget_dropped_all cause (beats vector_disabled)', async () => {+ const w = getTelemetryWriter();+ w.setEngine(engine);+ recordSearchTelemetry(+ engine,+ makeMeta({+ vector_enabled: false,+ token_budget: { budget: 100, used: 0, kept: 0, dropped: 5 },+ }),+ { results_count: 0 },+ );+ await w.flush();+ const s = await readSearchStats(engine, { days: 7 });+ expect(s.empty_results.by_cause).toEqual({ budget_dropped_all: 1 });+ });++ test('degraded budget_dropped_all stage classifies the same way', async () => {+ const w = getTelemetryWriter();+ w.setEngine(engine);+ recordSearchTelemetry(+ engine,+ makeMeta({ degraded: [{ stage: 'budget_dropped_all' }] }),+ { results_count: 0 },+ );+ await w.flush();+ const s = await readSearchStats(engine, { days: 7 });+ expect(s.empty_results.by_cause).toEqual({ budget_dropped_all: 1 });+ });++ test('healthy pipeline + zero hits → keyword_zero cause', async () => {+ const w = getTelemetryWriter();+ w.setEngine(engine);+ recordSearchTelemetry(engine, makeMeta(), { results_count: 0 });+ await w.flush();+ const s = await readSearchStats(engine, { days: 7 });+ expect(s.empty_results.by_cause).toEqual({ keyword_zero: 1 });+ });++ test('empty cache HIT (offset artifact) is NOT counted as an empty-result cause', async () => {+ const w = getTelemetryWriter();+ w.setEngine(engine);+ recordSearchTelemetry(engine, makeMeta({ cache: { status: 'hit' } }), { results_count: 0 });+ await w.flush();+ const s = await readSearchStats(engine, { days: 7 });+ expect(s.empty_results.total).toBe(0);+ });++ test('reserved rows never skew total_calls or the distributions', async () => {+ const w = getTelemetryWriter();+ w.setEngine(engine);+ recordSearchTelemetry(engine, makeMeta(), { results_count: 5 });+ recordSearchTelemetry(engine, makeMeta({ vector_enabled: false }), { results_count: 0 });+ await w.flush();+ const s = await readSearchStats(engine, { days: 7 });+ // Both calls count as calls (the empty one still ran); the reserved+ // cause row does NOT add a third.+ expect(s.total_calls).toBe(2);+ expect(Object.keys(s.mode_distribution)).toEqual(['balanced']);+ expect(Object.keys(s.intent_distribution)).toEqual(['general']);+ expect(s.empty_results.total).toBe(1);+ expect(s.avg_results).toBeCloseTo(2.5, 5); // 5 / 2 calls — reserved row excluded});});diff --git a/test/search/knobs-hash-reranker.test.ts b/test/search/knobs-hash-reranker.test.tsindex 3a02801681..b32956c75c 100644--- a/test/search/knobs-hash-reranker.test.ts+++ b/test/search/knobs-hash-reranker.test.ts@@ -44,7 +44,7 @@ function baseKnobs(): ResolvedSearchKnobs {}describe('KNOBS_HASH_VERSION + version invariants', () => {- test('version is 16 (…; 12→13 embedding-provider migration #3390; 14→15 FTS language; 15→16 detail fold #3515)', () => {+ test('version is 17 (…; 12→13 embedding-provider migration #3390; 14→15 FTS language; 15→16 detail fold #3515; 16→17 degradation stamp)', () => {// v0.35.0.0: 1→2 to fold reranker fields. v0.35.6.0: 2→3 to fold// floor_ratio. v0.36 wave: piggybacks on v=3 with 7 cross-modal knobs// (D2) PLUS column + provider context (D8/CDX-2 cross-column isolation).@@ -73,7 +73,9 @@ describe('KNOBS_HASH_VERSION + version invariants', () => {// must not survive a `reindex-search-vector` language switch.// #3515: 15→16 to fold the effective detail level (det=) — a detail=low// write must not be served to a detail=medium lookup.- expect(KNOBS_HASH_VERSION).toBe(16);+ // WP2/T3: 16→17 degradation-stamp epoch — cache rows now carry+ // degraded[]/retrieved_count; pre-stamp rows must not claim clean.+ expect(KNOBS_HASH_VERSION).toBe(17);});test('hash is 16 hex chars regardless of reranker config', () => {diff --git a/test/status-thin-client-skew.test.ts b/test/status-thin-client-skew.test.tsnew file mode 100644index 0000000000..5059db2b05--- /dev/null+++ b/test/status-thin-client-skew.test.ts@@ -0,0 +1,126 @@+/**+ * Thin-client version-skew fixture (amendment 26 / ENG-20).+ *+ * A NEW thin-client `gbrain status` against an OLD brain server: the+ * schema_version-1 `get_status_snapshot` payload carries no workers/queue+ * keys. The client must degrade those sections to a graceful+ * "upgrade the remote" marker — never crash, never render the misleading+ * "local-only — N/A on remote brain" copy, never invent data.+ *+ * Hermetic: drives the exported payload→report mapper (`applyRemoteSnapshot`)+ * and the human renderer directly, with fixture payloads for both server+ * generations.+ */++import { describe, test, expect } from 'bun:test';+import {+ applyRemoteSnapshot,+ renderHuman,+ type RemoteSnapshotPayload,+ type StatusReport,+} from '../src/commands/status.ts';+import type { SyncStatusReport } from '../src/commands/sync.ts';++const syncFixture: SyncStatusReport = {+ schema_version: 1,+ generated_at: '2026-08-13T00:00:00.000Z',+ sources: [],+ unacknowledged_failures: 0,+ embedding_column: 'embedding',+};++const cycleFixture = { last_full: null, last_targeted: null };++function baseReport(): StatusReport {+ return {+ schema_version: 1,+ version: '0.99.0.0',+ generated_at: '2026-08-13T00:00:00.000Z',+ mode: 'thin-client',+ };+}++const wantAll = () => true;++describe('OLD server (schema_version 1 — no workers/queue keys)', () => {+ const v1Payload: RemoteSnapshotPayload = {+ schema_version: 1,+ version: '0.41.19.0',+ sync: syncFixture,+ cycle: cycleFixture,+ };++ test('v2-only sections degrade to the remote_unsupported marker', () => {+ const report = baseReport();+ applyRemoteSnapshot(report, v1Payload, wantAll);+ expect(report.sync).toBe(syncFixture);+ expect(report.cycle).toEqual(cycleFixture);+ expect(report.workers).toEqual({ remote_unsupported: true });+ expect(report.queue).toEqual({ remote_unsupported: true });+ expect(report.remote_version).toBe('0.41.19.0');+ });++ test('human render carries the graceful upgrade copy, not a crash or N/A lie', () => {+ const report = baseReport();+ applyRemoteSnapshot(report, v1Payload, wantAll);+ const out = renderHuman(report);+ expect(out).toContain('predates snapshot v2');+ expect(out).toContain('upgrade the remote gbrain');+ expect(out).not.toContain('N/A on remote brain');+ });+});++describe('NEW server (schema_version 2)', () => {+ const v2Payload: RemoteSnapshotPayload = {+ schema_version: 2,+ version: '0.99.0.0',+ sync: syncFixture,+ cycle: cycleFixture,+ workers: {+ supervisor_alive: true,+ detected_via: 'db_lock',+ live_lock_active: true,+ last_completed_at: '2026-08-13T00:30:00.000Z',+ },+ queue: {+ counts: { active: 1, waiting: 3, completed: 10, failed: 0, dead: 0 },+ by_queue: [{ queue: 'default', depth: 3, oldest_waiting_age_seconds: 120 }],+ },+ };++ test('sections map through verbatim', () => {+ const report = baseReport();+ applyRemoteSnapshot(report, v2Payload, wantAll);+ expect(report.workers).toEqual(v2Payload.workers as any);+ expect(report.queue).toEqual(v2Payload.queue as any);+ });++ test('human render shows the remote queue depth + worker liveness', () => {+ const report = baseReport();+ applyRemoteSnapshot(report, v2Payload, wantAll);+ const out = renderHuman(report);+ expect(out).toContain('supervisor: alive (via db_lock)');+ expect(out).toContain('[default] depth=3');+ expect(out).toContain('waiting=3');+ });++ test('a fail-soft section ({error: unavailable}) renders as unavailable, not a crash', () => {+ const report = baseReport();+ applyRemoteSnapshot(+ report,+ { ...v2Payload, queue: { error: 'unavailable' }, workers: { error: 'unavailable' } },+ wantAll,+ );+ const out = renderHuman(report);+ expect(out).toContain('unavailable (remote section failed to compute)');+ });++ test('--section filter is respected: unwanted sections stay unset', () => {+ const report = baseReport();+ applyRemoteSnapshot(report, v2Payload, (s) => s === 'sync');+ expect(report.sync).toBe(syncFixture);+ expect(report.cycle).toBeUndefined();+ expect(report.workers).toBeUndefined();+ expect(report.queue).toBeUndefined();+ });+});diff --git a/test/submit-agent.test.ts b/test/submit-agent.test.tsindex ba817ec33e..1ceab10412 100644--- a/test/submit-agent.test.ts+++ b/test/submit-agent.test.ts@@ -112,7 +112,9 @@ async function callSubmitAgent(ctx: any, params: Record<string, unknown>): Promidescribe('submit_agent op (v0.38 Slice 3 — remote-callable agent dispatch with binding enforcement)', () => {describe('op surface', () => {it('declares scope=agent + mutating=true', () => {- expect(submit_agent.scope).toBe('agent' as any);+ // Minions-visibility wave: 'agent' is a first-class member of the+ // Operation scope union now (amendment 16) — no `as any` escape hatch.+ expect(submit_agent.scope).toBe('agent');expect(submit_agent.mutating).toBe(true);});it('declares required prompt param', () => {@@ -365,6 +367,15 @@ describe('submit_agent op (v0.38 Slice 3 — remote-callable agent dispatch withexpect(result.id).toBeGreaterThan(0);expect(result.name).toBe('subagent');expect(result.client_id).toBe('cursor');+ // Minions-visibility wave (amendments 24/25): every successful submit+ // carries a queue-state probe. Either a real snapshot (depth counts the+ // job just enqueued) or the fail-open {probe_failed: true} marker —+ // never absent, never an error.+ expect(result.queue_state).toBeDefined();+ if (!result.queue_state.probe_failed) {+ expect(result.queue_state.depth).toBeGreaterThanOrEqual(1);+ expect(typeof result.queue_state.worker_alive).toBe('boolean');+ }// Job persisted with correct shape.const rows = await engine.executeRaw<Record<string, unknown>>(diff --git a/test/submit-queue-state.test.ts b/test/submit-queue-state.test.tsnew file mode 100644index 0000000000..fee415800b--- /dev/null+++ b/test/submit-queue-state.test.ts@@ -0,0 +1,208 @@+/**+ * Minions-visibility wave — submit-time queue-state probe (amendments 24/25,+ * ENG-18 dead-lane suite).+ *+ * Covers `probeQueueState` (src/core/minions/supervisor.ts) directly plus the+ * `submit_job` wiring:+ * - workerless queue → worker_alive: false + warning+ * - autopilot pause marker → paused: true + "paused for migration" warning+ * - depth over GBRAIN_QUEUE_WAITING_THRESHOLD → warning+ * - probe throws / hangs → {probe_failed: true}, and a throwing probe NEVER+ * errors a successful submission (fail-open contract)+ *+ * All filesystem probes (pause marker, worker registry) run under a scratch+ * GBRAIN_HOME so a dev machine's real ~/.gbrain state can't flake assertions.+ * PGLite only; the probe's SQL is engine-neutral executeRaw (the wedge-signal+ * query is already parity-pinned by test/supervisor-wedge.test.ts).+ */++import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { writeFileSync, mkdirSync } from 'node:fs';+import { dirname } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv, emptyHome } from './helpers/with-env.ts';+import { probeQueueState } from '../src/core/minions/supervisor.ts';+import { autopilotPausedMarkerPath } from '../src/core/autopilot-paths.ts';+import { operationsByName } from '../src/core/operations.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.setConfig('version', '85');+});++async function seedJob(opts: {+ status?: string;+ queue?: string;+ name?: string;+ createdAtSql?: string;+ lockUntilSql?: string;+} = {}): Promise<void> {+ await engine.executeRaw(+ `INSERT INTO minion_jobs (name, status, data, queue, priority, created_at, lock_until)+ VALUES ($1, $2, '{}'::jsonb, $3, 0, ${opts.createdAtSql ?? 'now()'}, ${opts.lockUntilSql ?? 'NULL'})`,+ [opts.name ?? 'embed', opts.status ?? 'waiting', opts.queue ?? 'default'],+ );+}++describe('probeQueueState — dead/degraded lane signals', () => {+ it('workerless queue: worker_alive false + a start-a-worker warning', async () => {+ await seedJob({ createdAtSql: "now() - interval '2 hours'" });+ await withEnv({ GBRAIN_HOME: emptyHome() }, async () => {+ const state = await probeQueueState(engine, 'default', ['embed']);+ expect(state.probe_failed).toBeUndefined();+ expect(state.depth).toBe(1);+ expect(state.worker_alive).toBe(false);+ expect(state.oldest_waiting_age_seconds).toBeGreaterThanOrEqual(7000);+ expect(state.warning).toContain("no live worker detected for queue 'default'");+ expect(state.warning).toContain('gbrain jobs work --queue default');+ });+ });++ it('a live-lock active job counts as worker evidence (worker_alive true, no worker warning)', async () => {+ await seedJob({ status: 'active', lockUntilSql: "now() + interval '5 minutes'" });+ await withEnv({ GBRAIN_HOME: emptyHome() }, async () => {+ const state = await probeQueueState(engine, 'default', ['embed']);+ expect(state.worker_alive).toBe(true);+ expect(state.warning).toBeUndefined();+ });+ });++ it('pause marker: paused true + the migration warning (amendment 25)', async () => {+ await withEnv({ GBRAIN_HOME: emptyHome() }, async () => {+ // Seed the marker the way `gbrain migrate` does (see+ // test/autopilot-pause-marker.test.ts) — path resolves under the+ // scratch GBRAIN_HOME at call time.+ const marker = autopilotPausedMarkerPath();+ mkdirSync(dirname(marker), { recursive: true });+ writeFileSync(marker, `paused by gbrain migrate (pid ${process.pid})\n`);++ const state = await probeQueueState(engine, 'default', ['embed']);+ expect(state.paused).toBe(true);+ expect(state.warning).toContain('system paused for migration — job will not start until the pause clears');+ });+ });++ it('depth over GBRAIN_QUEUE_WAITING_THRESHOLD → depth warning (doctor knob reused)', async () => {+ for (let i = 0; i < 4; i++) await seedJob({});+ await withEnv({ GBRAIN_HOME: emptyHome(), GBRAIN_QUEUE_WAITING_THRESHOLD: '2' }, async () => {+ const state = await probeQueueState(engine, 'default', ['embed']);+ expect(state.depth).toBe(4);+ expect(state.warning).toContain('waiting depth 4 exceeds GBRAIN_QUEUE_WAITING_THRESHOLD (2)');+ });+ });++ it('empty queue: depth 0, oldest age null', async () => {+ await withEnv({ GBRAIN_HOME: emptyHome() }, async () => {+ const state = await probeQueueState(engine, 'default', ['embed']);+ expect(state.depth).toBe(0);+ expect(state.oldest_waiting_age_seconds).toBeNull();+ });+ });++ it('probe throw → {probe_failed: true} (fail-open, amendment 24)', async () => {+ const throwing: any = {+ kind: 'pglite',+ executeRaw: async () => {+ throw new Error('db exploded');+ },+ };+ const state = await probeQueueState(throwing, 'default', ['embed']);+ expect(state).toEqual({ probe_failed: true });+ });++ it('probe hang → {probe_failed: true} within the time bound', async () => {+ const hanging: any = {+ kind: 'pglite',+ executeRaw: () => new Promise(() => {}), // never resolves+ };+ const started = Date.now();+ const state = await probeQueueState(hanging, 'default', ['embed'], { timeoutMs: 60 });+ expect(state).toEqual({ probe_failed: true });+ expect(Date.now() - started).toBeLessThan(1500);+ });+});++describe('submit_job wiring — probe never blocks a successful enqueue', () => {+ const submit_job = operationsByName['submit_job'];++ function makeCtx(eng: any): any {+ return {+ engine: eng,+ config: {},+ logger: console,+ dryRun: false,+ remote: true,+ };+ }++ it('attaches queue_state to a successful submission (workerless PGLite → warning)', async () => {+ await withEnv({ GBRAIN_HOME: emptyHome() }, async () => {+ const result = (await submit_job.handler(makeCtx(engine), { name: 'embed' })) as any;+ expect(result.id).toBeGreaterThan(0);+ expect(result.queue_state).toBeDefined();+ expect(result.queue_state.probe_failed).toBeUndefined();+ // The probe runs post-enqueue: depth counts the job just submitted.+ expect(result.queue_state.depth).toBeGreaterThanOrEqual(1);+ expect(result.queue_state.worker_alive).toBe(false);+ expect(result.queue_state.warning).toContain('no live worker');+ });+ });++ it('a throwing probe degrades to queue_state {probe_failed: true} — the enqueue still succeeds', async () => {+ // Delegate everything to the real engine EXCEPT the wedge-signal query+ // (identified by its waiting_claimable alias), which the probe — and only+ // the probe — runs.+ const throwOnWedge: any = new Proxy(engine, {+ get(target, prop) {+ if (prop === 'executeRaw') {+ return async (sql: string, ...rest: unknown[]) => {+ if (typeof sql === 'string' && sql.includes('waiting_claimable')) {+ throw new Error('probe-only failure');+ }+ return (target as any).executeRaw(sql, ...rest);+ };+ }+ const v = Reflect.get(target as object, prop, target);+ return typeof v === 'function' ? (v as (...a: unknown[]) => unknown).bind(target) : v;+ },+ });+ await withEnv({ GBRAIN_HOME: emptyHome() }, async () => {+ const result = (await submit_job.handler(makeCtx(throwOnWedge), { name: 'embed' })) as any;+ expect(result.id).toBeGreaterThan(0);+ expect(result.status).toBe('waiting');+ expect(result.queue_state).toEqual({ probe_failed: true });+ // The row really persisted — the probe failure cost nothing.+ const rows = await engine.executeRaw<{ n: number | string }>(+ `SELECT count(*)::int AS n FROM minion_jobs WHERE id = $1`,+ [result.id],+ );+ expect(Number(rows[0].n)).toBe(1);+ });+ });++ it('pause marker surfaces through submit_job (paused + warning, enqueue unblocked)', async () => {+ await withEnv({ GBRAIN_HOME: emptyHome() }, async () => {+ const marker = autopilotPausedMarkerPath();+ mkdirSync(dirname(marker), { recursive: true });+ writeFileSync(marker, `paused by gbrain migrate (pid ${process.pid})\n`);++ const result = (await submit_job.handler(makeCtx(engine), { name: 'embed' })) as any;+ expect(result.id).toBeGreaterThan(0);+ expect(result.queue_state.paused).toBe(true);+ expect(result.queue_state.warning).toContain('system paused for migration');+ });+ });+});diff --git a/test/surface-audit.test.ts b/test/surface-audit.test.tsnew file mode 100644index 0000000000..46fb4f7364--- /dev/null+++ b/test/surface-audit.test.ts@@ -0,0 +1,47 @@+/**+ * WP4 (amendment 32 / ENG-8) — writeSurfaceChangeAudit is best-effort by+ * design: the surface mutation has already committed when the audit write+ * runs, so an engine failure must resolve `false` (after a stderr warn),+ * NEVER throw — a failed audit row must not turn a successful mutation into+ * a caller-visible error. Happy-path row shape is pinned over real PGLite in+ * test/request-tools.test.ts; this file pins the fail-open contract with an+ * engine stub.+ */++import { describe, test, expect } from 'bun:test';+import { writeSurfaceChangeAudit, type SurfaceChangeAudit } from '../src/core/surface-audit.ts';+import type { BrainEngine } from '../src/core/engine.ts';++const AUDIT: SurfaceChangeAudit = {+ actor: 'cl-test',+ client_id: 'cl-test',+ old: null,+ new: 'starter',+ via: 'request_tools',+};++describe('writeSurfaceChangeAudit fail-open contract', () => {+ test('a throwing engine resolves false and does not throw', async () => {+ const throwing = {+ executeRaw: async () => { throw new Error('pool exhausted'); },+ } as unknown as BrainEngine;+ await expect(writeSurfaceChangeAudit(throwing, AUDIT)).resolves.toBe(false);+ });++ test('a working engine resolves true and binds the params object raw (jsonb discipline)', async () => {+ let captured: { sql: string; params: unknown[] } | null = null;+ const capturing = {+ executeRaw: async (sql: string, params: unknown[]) => {+ captured = { sql, params };+ return [];+ },+ } as unknown as BrainEngine;+ await expect(writeSurfaceChangeAudit(capturing, AUDIT)).resolves.toBe(true);+ expect(captured).not.toBeNull();+ expect(captured!.sql).toContain('mcp_request_log');+ // The jsonb param is a RAW OBJECT (never JSON.stringify — #2339 class).+ const jsonbParam = captured!.params[captured!.params.length - 1];+ expect(typeof jsonbParam).toBe('object');+ expect(jsonbParam).toMatchObject({ actor: 'cl-test', client_id: 'cl-test', old: null, new: 'starter', via: 'request_tools' });+ });+});diff --git a/test/think-extractive.serial.test.ts b/test/think-extractive.serial.test.tsnew file mode 100644index 0000000000..325bf47d20--- /dev/null+++ b/test/think-extractive.serial.test.ts@@ -0,0 +1,352 @@+/**+ * WP2/T5 + E2 — synthesize compose status + extractive fallback.+ *+ * Pins the compose-failure precedence (registry refinement):+ * - compose failed + NON-EMPTY gather → extractive fallback wins+ * (synthesis_status: 'extractive_fallback'; answer digests + cites ONLY+ * gathered pages)+ * - compose failed + EMPTY gather → typed verbError('unavailable',+ * 'retrieved 0 pages; compose failed: <warning-code>')+ * - no LLM configured → the [c10] `unavailable` error REGARDLESS of gather+ * (an extractive digest would mask the misconfiguration forever)+ * - client.create() throws (429/timeout/5xx/network) → 'llm_error' status+ * (ENG-10 reachability), routed like any other compose failure+ * - NEVER fabricate (ENG-19): extractive answers quote/cite only gathered+ * pages; an empty gather never produces an answer.+ *+ * Serial (env-mutating): withEnv / withoutAnthropicKey touch process.env.+ */++import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { operationsByName } from '../src/core/operations.ts';+import type { OperationContext } from '../src/core/operations.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { RESPONSE_SCHEMAS } from '../src/core/verbs.ts';+import { validateAgainstSchema } from '../src/core/verbs/conformance.ts';+import {+ runThink,+ persistSynthesis,+ composeExtractiveFallback,+ classifyLlmCallFailure,+ type ThinkLLMClient,+} from '../src/core/think/index.ts';+import type { SearchResult } from '../src/core/types.ts';+import { AIConfigError } from '../src/core/ai/errors.ts';+import { __setChatTransportForTests, __setEmbedTransportForTests, type ChatResult } from '../src/core/ai/gateway.ts';+import { __setUsageLogPathForTests } from '../src/core/verbs/usage-log.ts';+import { withEnv } from './helpers/with-env.ts';+import { withoutAnthropicKey } from './helpers/no-anthropic-key.ts';++let engine: PGLiteEngine;+let home: string;++beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-think-extractive-'));+ __setUsageLogPathForTests(join(home, 'usage.jsonl'));+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+ __setUsageLogPathForTests(null);+ try { rmSync(home, { recursive: true, force: true }); } catch { /* best-effort */ }+});++beforeEach(async () => {+ await resetPgliteState(engine);+ __setChatTransportForTests(null);+ __setEmbedTransportForTests(null);+});++function localCtx(sourceId = 'default'): OperationContext {+ return {+ engine,+ config: {},+ logger: { info: () => {}, warn: () => {}, error: () => {} },+ dryRun: false,+ remote: false,+ sourceId,+ } as unknown as OperationContext;+}++const SEED_SLUG = 'notes/zephyrine-payments';+const SEED_TITLE = 'Zephyrine Payments';+const SEED_FACT = 'The Zephyrine payments migration finished in March with zero downtime.';++async function seedZephyrinePage() {+ const put = operationsByName['put_page'];+ await put.handler(localCtx(), {+ slug: SEED_SLUG,+ content: `---\ntitle: ${SEED_TITLE}\ntype: note\n---\n\n# ${SEED_TITLE}\n\n${SEED_FACT}\n`,+ });+}++/** Remote-shaped synthesize call through the shared dispatcher. */+async function callSynthesize(question: string) {+ const res = await dispatchToolCall(engine, 'synthesize', { question }, {+ remote: true,+ takesHoldersAllowList: ['world'],+ sourceId: 'default',+ });+ return { isError: res.isError === true, body: JSON.parse(res.content[0].text) };+}++function chatResultOf(text: string): ChatResult {+ return {+ text,+ blocks: [],+ stopReason: 'end' as const,+ usage: { input_tokens: 100, output_tokens: 20, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-haiku-4-5-20251001',+ providerId: 'anthropic',+ } as ChatResult;+}++/** Every `[slug]` marker in an extractive answer. */+function citedSlugs(answer: string): string[] {+ return [...answer.matchAll(/\[([a-z0-9][a-z0-9\-]*(?:\/[a-z0-9][a-z0-9\-]*)*)\]/g)].map(m => m[1]);+}++describe('composeExtractiveFallback — ENG-19 never-fabricate pins', () => {+ const pages = [+ { slug: 'notes/alpha', title: 'Alpha Note', chunk_text: 'Alpha content about zebras migrating north in spring.' },+ { slug: 'notes/beta', title: 'Beta Note', chunk_text: 'Beta content: quokkas photographed on the island.' },+ ] as unknown as SearchResult[];++ it('empty gather NEVER produces an answer — returns null', () => {+ expect(composeExtractiveFallback([], 'anything at all')).toBeNull();+ });++ it('quotes + cites ONLY the gathered pages (page-level citations, gather order)', () => {+ const r = composeExtractiveFallback(pages, 'zebras migrating');+ expect(r).not.toBeNull();+ expect(r!.citations.map(c => c.page_slug)).toEqual(['notes/alpha', 'notes/beta']);+ expect(r!.citations.every(c => c.row_num === null)).toBe(true);+ expect(r!.citations.map(c => c.citation_index)).toEqual([1, 2]);+ // Every [slug] marker in the answer is one of the inputs — nothing invented.+ expect([...new Set(citedSlugs(r!.answer))].sort()).toEqual(['notes/alpha', 'notes/beta']);+ // The digest quotes input content verbatim (title + excerpt window).+ expect(r!.answer).toContain('Alpha content about zebras');+ expect(r!.answer).toContain('quokkas');+ expect(r!.answer).toContain('Alpha Note');+ });++ it('caps the digest at the top 5 pages', () => {+ const many = Array.from({ length: 8 }, (_, i) => ({+ slug: `notes/p-${i}`, title: `Page ${i}`, chunk_text: `Content number ${i}.`,+ })) as unknown as SearchResult[];+ const r = composeExtractiveFallback(many, 'content');+ expect(r!.citations).toHaveLength(5);+ expect(citedSlugs(r!.answer)).toHaveLength(5);+ });+});++describe('classifyLlmCallFailure — D6 closed vocabulary', () => {+ it('maps error shapes onto the closed set (raw detail never rides the wire)', () => {+ expect(classifyLlmCallFailure(new Error('Request timed out after 60000ms'))).toBe('timeout');+ expect(classifyLlmCallFailure(new Error('429 rate limited'))).toBe('rate_limited');+ expect(classifyLlmCallFailure(new Error('rate_limit_error: overloaded'))).toBe('rate_limited');+ expect(classifyLlmCallFailure(new Error('fetch failed: ECONNREFUSED 10.0.0.1'))).toBe('network');+ expect(classifyLlmCallFailure(new Error('internal server error'))).toBe('provider_error');+ expect(classifyLlmCallFailure('not even an Error')).toBe('provider_error');+ });+});++describe('runThink — llm_error reachability (ENG-10: create() throws)', () => {+ it('a thrown 429/network error becomes synthesis_status llm_error + LLM_CALL_FAILED warning', async () => {+ await seedZephyrinePage();+ const throwing: ThinkLLMClient = {+ create: async () => { throw new Error('simulated 429 rate limited'); },+ };+ const result = await runThink(engine, {+ question: 'Zephyrine payments migration status',+ client: throwing,+ withTrajectory: false,+ });+ expect(result.synthesis_status).toBe('llm_error');+ expect(result.synthesisOk).toBe(false);+ // D6 closed vocabulary: the wire carries the coarse class, never the raw+ // provider message.+ expect(result.warnings).toContain('LLM_CALL_FAILED: rate_limited');+ expect(result.warnings.some(w => w.includes('simulated'))).toBe(false);+ expect(result.usage).toBeNull();+ // Gather found the seeded page → extractive material rides the result.+ expect(result.pagesGathered).toBeGreaterThanOrEqual(1);+ expect(result.extractive).toBeDefined();+ expect(result.extractive!.citations.map(c => c.page_slug)).toContain(SEED_SLUG);+ // #1698 persist gate holds: an llm_error result is never persisted.+ const saved = await persistSynthesis(engine, result);+ expect(saved.slug).toBe('');+ expect(saved.warnings).toContain('SYNTHESIS_EMPTY_NOT_PERSISTED');+ });++ it('explicit-model AIConfigError stays a HARD error (#1698 contract preserved)', async () => {+ const throwing: ThinkLLMClient = {+ create: async () => { throw new AIConfigError('key revoked mid-run'); },+ };+ await expect(+ runThink(engine, { question: 'x', client: throwing, modelExplicit: true, withTrajectory: false }),+ ).rejects.toThrow('key revoked mid-run');+ });++ it('BudgetExhausted propagates — spend control must stop the enclosing loop', async () => {+ class FakeBudgetExhausted extends Error {+ constructor() { super('budget gone'); this.name = 'BudgetExhausted'; }+ }+ const throwing: ThinkLLMClient = {+ create: async () => { throw new FakeBudgetExhausted(); },+ };+ await expect(+ runThink(engine, { question: 'x', client: throwing, withTrajectory: false }),+ ).rejects.toThrow('budget gone');+ });+});++describe('synthesize verb — compose-failure precedence (via dispatch)', () => {+ it('not_json (refusal prose) + non-empty gather → extractive_fallback citing only gathered pages', async () => {+ await seedZephyrinePage();+ __setChatTransportForTests(async () => chatResultOf('I cannot help with that request.'));+ const { isError, body } = await withEnv({ ANTHROPIC_API_KEY: 'sk-test-hermetic' }, () =>+ callSynthesize('Zephyrine payments migration status?'),+ );+ expect(isError).toBe(false);+ expect(body.synthesis_status).toBe('extractive_fallback');+ expect(body.warnings).toContain('LLM_OUTPUT_NOT_JSON');+ expect(body.pages_gathered).toBeGreaterThanOrEqual(1);+ expect(typeof body.takes_gathered).toBe('number');+ expect(body.sources).toContain(SEED_SLUG);+ // ENG-19: every citation in the answer is a gathered page; the digest+ // quotes gathered content, not the refusal prose.+ expect(citedSlugs(body.answer)).toContain(SEED_SLUG);+ expect(citedSlugs(body.answer).every(s => s === SEED_SLUG)).toBe(true);+ expect(body.answer).toContain('Zephyrine');+ expect(body.answer).not.toContain('I cannot help');+ expect(body.protocol_version).toBe(1);+ expect(validateAgainstSchema(body, RESPONSE_SCHEMAS.synthesize)).toEqual([]);+ });++ it('empty_answer (valid JSON, empty answer) + non-empty gather → extractive_fallback', async () => {+ await seedZephyrinePage();+ __setChatTransportForTests(async () =>+ chatResultOf(JSON.stringify({ answer: '', citations: [], gaps: [] })),+ );+ const { isError, body } = await withEnv({ ANTHROPIC_API_KEY: 'sk-test-hermetic' }, () =>+ callSynthesize('Zephyrine payments migration status?'),+ );+ expect(isError).toBe(false);+ expect(body.synthesis_status).toBe('extractive_fallback');+ expect(body.warnings).toContain('SYNTHESIS_EMPTY_ANSWER');+ expect(body.sources).toContain(SEED_SLUG);+ expect(validateAgainstSchema(body, RESPONSE_SCHEMAS.synthesize)).toEqual([]);+ });++ it('llm_error (chat transport throws) + non-empty gather → extractive_fallback', async () => {+ await seedZephyrinePage();+ __setChatTransportForTests(async () => { throw new Error('simulated 503 upstream'); });+ const { isError, body } = await withEnv({ ANTHROPIC_API_KEY: 'sk-test-hermetic' }, () =>+ callSynthesize('Zephyrine payments migration status?'),+ );+ expect(isError).toBe(false);+ expect(body.synthesis_status).toBe('extractive_fallback');+ // '503 upstream' carries no timeout/rate-limit/network shape → provider_error.+ expect(body.warnings).toContain('LLM_CALL_FAILED: provider_error');+ expect(body.warnings.some((w: string) => w.includes('simulated'))).toBe(false);+ expect(body.sources).toContain(SEED_SLUG);+ expect(validateAgainstSchema(body, RESPONSE_SCHEMAS.synthesize)).toEqual([]);+ });++ it('llm_error + EMPTY gather → typed unavailable ("retrieved 0 pages; compose failed: LLM_CALL_FAILED")', async () => {+ // No pages seeded — gather retrieves nothing; an answer must NOT appear.+ __setChatTransportForTests(async () => { throw new Error('simulated 503 upstream'); });+ const { isError, body } = await withEnv({ ANTHROPIC_API_KEY: 'sk-test-hermetic' }, () =>+ callSynthesize('question with no matching content anywhere'),+ );+ expect(isError).toBe(true);+ expect(body.error).toBe('unavailable');+ expect(body.message).toMatch(/retrieved 0 pages; compose failed: LLM_CALL_FAILED/);+ expect(body.suggestion.length).toBeGreaterThan(0);+ expect(body.detail).toContain('LLM_CALL_FAILED');+ expect(body.protocol_version).toBe(1);+ });++ it('not_json + EMPTY gather → typed unavailable naming LLM_OUTPUT_NOT_JSON', async () => {+ __setChatTransportForTests(async () => chatResultOf('plain prose, not JSON'));+ const { isError, body } = await withEnv({ ANTHROPIC_API_KEY: 'sk-test-hermetic' }, () =>+ callSynthesize('question with no matching content anywhere'),+ );+ expect(isError).toBe(true);+ expect(body.error).toBe('unavailable');+ expect(body.message).toMatch(/retrieved 0 pages; compose failed: LLM_OUTPUT_NOT_JSON/);+ });++ it('no-key stub stays the [c10] unavailable error even with a NON-EMPTY gather', async () => {+ await seedZephyrinePage();+ const { isError, body } = await withoutAnthropicKey(() =>+ callSynthesize('Zephyrine payments migration status?'),+ );+ expect(isError).toBe(true);+ expect(body.error).toBe('unavailable');+ expect(body.message).toBe('synthesize needs an LLM and none is configured.');+ expect(body.suggestion).toContain('API key');+ });++ it('model_unusable + non-empty gather → extractive_fallback with the MODEL_NOT_USABLE warning', async () => {+ // voyage has no chat touchpoint — the deterministic unknown_model trigger+ // (same fixture think-pipeline.serial uses).+ await engine.setConfig('models.think', 'voyage:voyage-3');+ try {+ await seedZephyrinePage();+ const { isError, body } = await withoutAnthropicKey(() =>+ callSynthesize('Zephyrine payments migration status?'),+ );+ expect(isError).toBe(false);+ expect(body.synthesis_status).toBe('extractive_fallback');+ expect(body.warnings).toContain('MODEL_NOT_USABLE:unknown_model');+ expect(body.sources).toContain(SEED_SLUG);+ expect(validateAgainstSchema(body, RESPONSE_SCHEMAS.synthesize)).toEqual([]);+ } finally {+ await engine.unsetConfig('models.think');+ }+ });++ it('model_unusable + EMPTY gather → typed unavailable naming MODEL_NOT_USABLE', async () => {+ await engine.setConfig('models.think', 'voyage:voyage-3');+ try {+ const { isError, body } = await withoutAnthropicKey(() =>+ callSynthesize('question with no matching content anywhere'),+ );+ expect(isError).toBe(true);+ expect(body.error).toBe('unavailable');+ expect(body.message).toMatch(/retrieved 0 pages; compose failed: MODEL_NOT_USABLE/);+ } finally {+ await engine.unsetConfig('models.think');+ }+ });++ it('ok path carries the additive fields and synthesis_status ok', async () => {+ await seedZephyrinePage();+ __setChatTransportForTests(async () =>+ chatResultOf(JSON.stringify({+ answer: `Migration done [${SEED_SLUG}].`,+ citations: [{ page_slug: SEED_SLUG, row_num: null, citation_index: 1 }],+ gaps: [],+ })),+ );+ const { isError, body } = await withEnv({ ANTHROPIC_API_KEY: 'sk-test-hermetic' }, () =>+ callSynthesize('Zephyrine payments migration status?'),+ );+ expect(isError).toBe(false);+ expect(body.synthesis_status).toBe('ok');+ expect(body.answer).toContain('Migration done');+ expect(body.pages_gathered).toBeGreaterThanOrEqual(1);+ expect(Array.isArray(body.warnings)).toBe(true);+ expect(validateAgainstSchema(body, RESPONSE_SCHEMAS.synthesize)).toEqual([]);+ });+});diff --git a/test/token-budget.test.ts b/test/token-budget.test.tsindex 32fa1dd505..dc2b07ed9b 100644--- a/test/token-budget.test.ts+++ b/test/token-budget.test.ts@@ -6,14 +6,24 @@* - greedy walk preserves caller ordering* - meta accounting (used / kept / dropped) matches the actual cut* - undefined / <=0 budget is a no-op- * - first-result-too-big returns empty list+ * - first-result-too-big keeps ONE truncated copy (WP2/T3 minKeep:1);+ * GBRAIN_SEARCH_SALVAGE=off restores the strict [] (ENG-7)+ * - packToBudget's strict [] edge is FROZEN for the memory-verb+ * consumers (recall/entity/context_pack) \u2014 pinned directly (FOV-2)** Lives in test/token-budget.test.ts to mirror existing search/* test naming.*/import { describe, test, expect } from 'bun:test';-import { enforceTokenBudget, estimateTokens, resultTokens } from '../src/core/search/token-budget.ts';+import {+ enforceTokenBudget,+ estimateTokens,+ packToBudget,+ resultTokens,+ searchSalvageEnabled,+} from '../src/core/search/token-budget.ts';import type { SearchResult } from '../src/core/types.ts';+import { withEnv } from './helpers/with-env.ts';function makeResult(overrides: Partial<SearchResult> = {}): SearchResult {return {@@ -113,11 +123,127 @@ describe('enforceTokenBudget', () => {expect(kept[0].slug).toBe('low-score');});- test('first result exceeds budget alone \u2192 returns empty', () => {+ // WP2/T3 (ENG-2/FOV-2): the strict [] expectation flipped to the minKeep+ // shape \u2014 the search wrapper never returns empty just because the top hit+ // is big; it keeps one truncated COPY and reports the cut honestly.+ test('first result exceeds budget alone \u2192 keeps ONE truncated copy (minKeep:1)', () => {const big = makeResult({ slug: 'big', title: 'a', chunk_text: 'x'.repeat(1000) });const small = makeResult({ slug: 'small', title: 'a', chunk_text: 'xxxx' });const { results: kept, meta } = enforceTokenBudget([big, small], 5);- expect(kept).toHaveLength(0);- expect(meta.dropped).toBe(2);+ expect(kept).toHaveLength(1);+ expect(kept[0].slug).toBe('big');+ // title 'a' costs 1 token \u2192 4 tokens left \u2192 16 chars of chunk_text.+ expect(kept[0].chunk_text).toBe('x'.repeat(16));+ expect(resultTokens(kept[0])).toBeLessThanOrEqual(5);+ expect(meta.kept).toBe(1);+ expect(meta.dropped).toBe(1); // N-1+ expect(meta.truncated).toBe(true);+ expect(meta.used).toBeLessThanOrEqual(5);+ });++ test('minKeep truncates a COPY \u2014 the shared SearchResult is never mutated', () => {+ const big = makeResult({ slug: 'big', title: 'a', chunk_text: 'x'.repeat(1000) });+ const { results: kept } = enforceTokenBudget([big], 5);+ expect(kept[0]).not.toBe(big);+ expect(big.chunk_text).toBe('x'.repeat(1000)); // flows on to cache write + eval capture+ expect(kept[0].chunk_text.length).toBeLessThan(big.chunk_text.length);+ });++ test('budget below title-only cost \u2192 slices the title so used <= budget', () => {+ // Title alone costs 25 tokens (100 chars); budget 5 can't even fit it.+ // A hard cap that can be exceeded is not a cap: the title is sliced to+ // budget*4 chars (costs exactly `budget` under ceil(len/4)).+ const big = makeResult({ slug: 'big', title: 'T'.repeat(100), chunk_text: 'x'.repeat(1000) });+ const { results: kept, meta } = enforceTokenBudget([big], 5);+ expect(kept).toHaveLength(1);+ expect(kept[0].chunk_text).toBe('');+ expect(kept[0].title).toBe('T'.repeat(20));+ expect(meta.truncated).toBe(true);+ expect(meta.used).toBe(5);+ expect(meta.used).toBeLessThanOrEqual(meta.budget);+ });++ test('truncated flag absent on ordinary cuts and no-op passes', () => {+ const results = [+ makeResult({ slug: 'a', title: 'a', chunk_text: 'xxxx' }),+ makeResult({ slug: 'b', title: 'a', chunk_text: 'xxxx' }),+ ];+ expect(enforceTokenBudget(results, 2).meta.truncated).toBeUndefined();+ expect(enforceTokenBudget(results, undefined).meta.truncated).toBeUndefined();+ });+});++describe('GBRAIN_SEARCH_SALVAGE=off \u2014 strict budget wrapper restored (ENG-7)', () => {+ test('searchSalvageEnabled reads the env kill switch', async () => {+ await withEnv({ GBRAIN_SEARCH_SALVAGE: undefined }, () => {+ expect(searchSalvageEnabled()).toBe(true);+ });+ await withEnv({ GBRAIN_SEARCH_SALVAGE: 'off' }, () => {+ expect(searchSalvageEnabled()).toBe(false);+ });+ });++ test('first-result-exceeds returns [] again under the kill switch', async () => {+ await withEnv({ GBRAIN_SEARCH_SALVAGE: 'off' }, () => {+ const big = makeResult({ slug: 'big', title: 'a', chunk_text: 'x'.repeat(1000) });+ const small = makeResult({ slug: 'small', title: 'a', chunk_text: 'xxxx' });+ const { results: kept, meta } = enforceTokenBudget([big, small], 5);+ expect(kept).toHaveLength(0);+ expect(meta.dropped).toBe(2);+ expect(meta.kept).toBe(0);+ expect(meta.truncated).toBeUndefined();+ });+ });+});++// FOV-2 \u2014 direct packToBudget edge pins. The generic packer feeds the FROZEN+// memory-verb paths (recall operations.ts, entity, and context_pack); its+// strict first-item-exceeds [] edge must NOT inherit the search wrapper's+// minKeep salvage. No direct test existed at HEAD.+describe('packToBudget \u2014 frozen strict edge (memory-verb consumers)', () => {+ test('first item alone exceeds budget \u2192 [] (strict, regardless of salvage env)', async () => {+ // salvage ON \u2014 must not leak into the frozen packer edge.+ await withEnv({ GBRAIN_SEARCH_SALVAGE: undefined }, () => {+ const big = makeResult({ slug: 'big', title: 'a', chunk_text: 'x'.repeat(1000) });+ const { items, meta } = packToBudget([big], resultTokens, 5);+ expect(items).toHaveLength(0);+ expect(meta.kept).toBe(0);+ expect(meta.dropped).toBe(1);+ expect(meta.truncated).toBeUndefined();+ });+ });++ test('budget undefined / <= 0 passes items through unchanged', () => {+ const items = [makeResult({ slug: 'a' }), makeResult({ slug: 'b' })];+ expect(packToBudget(items, resultTokens, undefined).items).toHaveLength(2);+ expect(packToBudget(items, resultTokens, 0).items).toHaveLength(2);+ expect(packToBudget(items, resultTokens, -1).items).toHaveLength(2);+ });++ test('context_pack-shaped fixture: page-list packing keeps a contiguous prefix, strict on oversize head', () => {+ // Mirrors the context_pack cost model (operations.ts): pages costed by+ // `${title} ${slug}` via the generic <T> API.+ type PackPage = { title: string; slug: string };+ const cost = (pg: PackPage) => estimateTokens(`${pg.title} ${pg.slug}`);+ const pages: PackPage[] = [+ { title: 'Quarterly planning notes', slug: 'notes/quarterly-planning' }, // ~13 tokens+ { title: 'Acme seed memo', slug: 'deals/acme-seed' }, // ~8 tokens+ { title: 'Widget series A', slug: 'deals/widget-series-a' }, // ~10 tokens+ ];+ // Budget fits the first two, not the third \u2192 contiguous prefix of 2.+ const budget = cost(pages[0]) + cost(pages[1]);+ const packed = packToBudget(pages, cost, budget);+ expect(packed.items.map((p) => p.slug)).toEqual([+ 'notes/quarterly-planning',+ 'deals/acme-seed',+ ]);+ expect(packed.meta.dropped).toBe(1);++ // Oversize head: the first page alone exceeds the budget \u2192 STRICT [];+ // context_pack's budget contract never fabricates a truncated page row.+ const tiny = packToBudget(pages, cost, 2);+ expect(tiny.items).toHaveLength(0);+ expect(tiny.meta.kept).toBe(0);+ expect(tiny.meta.dropped).toBe(3);});});diff --git a/test/tool-catalog.test.ts b/test/tool-catalog.test.tsnew file mode 100644index 0000000000..7bf75ad34a--- /dev/null+++ b/test/tool-catalog.test.ts@@ -0,0 +1,87 @@+/**+ * E6 — the generated docs/TOOL_CATALOG.md: renderer determinism, coverage+ * (every non-localOnly op exactly once; localOnly never), starter/gate+ * annotations, the committed doc's freshness, and the CI wiring of the+ * freshness guard (package.json check + verify-chain membership).+ */++import { describe, test, expect } from 'bun:test';+import { readFileSync, existsSync } from 'fs';+import { join } from 'path';++import { renderToolCatalogMarkdown, firstSentence } from '../src/mcp/tool-catalog.ts';+import { operations } from '../src/core/operations.ts';+import { STARTER_OPS } from '../src/mcp/surface.ts';++const REPO_ROOT = join(import.meta.dir, '..');++describe('firstSentence', () => {+ test('cuts at the first sentence boundary', () => {+ expect(firstSentence('Read a page by slug. Soft-deleted pages are hidden.')).toBe('Read a page by slug.');+ expect(firstSentence('No trailing period here')).toBe('No trailing period here');+ expect(firstSentence('Multi\nline text. Rest.')).toBe('Multi line text.');+ });+});++describe('renderToolCatalogMarkdown', () => {+ const md = renderToolCatalogMarkdown();++ test('deterministic: two renders are byte-identical', () => {+ expect(renderToolCatalogMarkdown()).toBe(md);+ });++ test('config-independent: contains no timestamps', () => {+ expect(md).not.toMatch(/\d{4}-\d{2}-\d{2}/);+ });++ test('every non-localOnly op appears exactly once; localOnly never', () => {+ for (const op of operations) {+ const cell = `| \`${op.name}\` |`;+ const count = md.split(cell).length - 1;+ if (op.localOnly) {+ expect(count).toBe(0);+ } else {+ expect(count).toBe(1);+ }+ }+ });++ test('starter members are marked; non-members are not', () => {+ for (const op of operations.filter((o) => !o.localOnly)) {+ const row = md.split('\n').find((l) => l.startsWith(`| \`${op.name}\` |`))!;+ const cells = row.split('|').map((c) => c.trim());+ // cells: ['', tool, description, scope, starter, gate, '']+ expect(cells[4]).toBe(STARTER_OPS.has(op.name) ? 'yes' : '');+ }+ });++ test('publish-gated ops carry their gate key', () => {+ const gated = operations.filter((o) => !o.localOnly && o.publishGateKey);+ expect(gated.length).toBeGreaterThan(0);+ for (const op of gated) {+ const row = md.split('\n').find((l) => l.startsWith(`| \`${op.name}\` |`))!;+ expect(row).toContain(`\`${op.publishGateKey}\``);+ }+ });++ test('one section per area, areas sorted', () => {+ const areas = [...new Set(operations.filter((o) => !o.localOnly).map((o) => o.area ?? 'other'))].sort();+ const headings = md.split('\n').filter((l) => l.startsWith('## ')).map((l) => l.slice(3));+ expect(headings).toEqual(areas);+ });+});++describe('freshness guard', () => {+ test('committed docs/TOOL_CATALOG.md matches a fresh render', () => {+ const committed = readFileSync(join(REPO_ROOT, 'docs', 'TOOL_CATALOG.md'), 'utf-8');+ expect(committed).toBe(renderToolCatalogMarkdown() + '\n');+ });++ test('check script exists and is wired into package.json + the verify chain', () => {+ expect(existsSync(join(REPO_ROOT, 'scripts', 'check-tool-catalog-fresh.sh'))).toBe(true);+ const pkg = JSON.parse(readFileSync(join(REPO_ROOT, 'package.json'), 'utf-8'));+ expect(pkg.scripts['check:tool-catalog']).toBe('bash scripts/check-tool-catalog-fresh.sh');+ const verify = readFileSync(join(REPO_ROOT, 'scripts', 'run-verify-parallel.sh'), 'utf-8');+ expect(verify).toContain('"check:tool-catalog"');+ });+});diff --git a/test/truthful-catalog.e2e-lite.test.ts b/test/truthful-catalog.e2e-lite.test.tsnew file mode 100644index 0000000000..4d53c7b69f--- /dev/null+++ b/test/truthful-catalog.e2e-lite.test.ts@@ -0,0 +1,784 @@+/**+ * E5 — the truthful-catalog invariant (T13; plan E5 + D10 carve-out, ENG-21+ * recipe, FOV-4/6c, amendment 31).+ *+ * THE INVARIANT: the catalog is an API promise. For each token class:+ * tools/list, then probe every listed tool — NO probe may return a+ * LIST-LEVEL denial (publish-gate `config_key=...`, bound-client op-fence+ * `fence=op`, scope `insufficient_scope`, or an unknown-tool envelope for a+ * name the list itself advertised). `invalid_params` is an acceptable probe+ * outcome. Inversely: what the list hides stays uncallable — surface-hidden+ * and localOnly ops return the no-leak unknown-tool envelope; gate-hidden+ * ops hit the fail-closed `config_key=` backstop; bound-fence-hidden ops hit+ * `fence=op`. Argument-level fence denials (out-of-prefix slugs on a LISTED+ * write op) are legitimate and excluded (D10) — pinned below as carrying NO+ * list-level marker.+ *+ * PLACEMENT (why not test/e2e/): the test/e2e/ tree runs only under+ * scripts/run-e2e.sh on a Postgres-equipped host; this file needs no+ * DATABASE_URL, so it lives in the unit tree (picked up by `bun test` /+ * run-unit-shard.sh) and guards the invariant in CI without Postgres.+ *+ * WHAT RUNS WHERE (ENG-21 recipe, adapted to a no-Postgres host):+ * (a) the legacy bearer HTTP transport runs FOR REAL — ONE+ * startHttpTransport server over a real PGLiteEngine, reused across+ * cells (per-request gate reads make config flips restart-free; the+ * surface axis for this transport is startup-bound, so surface cells+ * run on path (b)).+ * (b) the OAuth serve-http path runs through the SAME SEAMS serve-http.ts+ * composes — filterOpsForSurface + hasScope (with the FOV-4+ * agentCallable carve-out) + opAllowedForBoundClient ++ * disabledOpsForPublishGates for the list; the scope gate + the real+ * dispatchToolCall (allowedOps / auth / surface / surfaceCeiling) for+ * the call. The only serve-http code NOT under test here is its+ * express/SDK glue and verifyAccessToken; the full OAuth-server sweep+ * (real HTTP, real tokens) runs on a Postgres-equipped host via+ * test/e2e/serve-http-oauth.test.ts.+ *+ * Config is pinned on the DB plane (which wins the dual-plane read) so the+ * developer's real ~/.gbrain/config.json can never flip an assertion, and+ * GBRAIN_HOME is redirected to a tmpdir for the file plane. mcp.strict_params+ * is pinned 'reject' so no garbage-arg probe can ever execute a write handler+ * (FOV-6c: exactly ONE warn-mode case below, probing a READ op only).+ *+ * Wall-clock budget: the whole file should finish in < 3 minutes (ENG-21).+ * The budget is ENFORCED only under GBRAIN_ENFORCE_E5_BUDGET=1 (a loaded CI+ * shard or laptop makes wall-clock assertions flaky); otherwise an overrun+ * warns loudly so drift is still visible.+ */++import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { createHash } from 'crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import {+ operations,+ opAllowedForBoundClient,+ type Operation,+ type AuthInfo,+} from '../src/core/operations.ts';+import { hasScope } from '../src/core/scope.ts';+import {+ filterOpsForSurface,+ STARTER_OPS,+ effectiveSurfaceForClient,+ resolveClientRowSurface,+ resolveDefaultClientSurface,+ type McpSurface,+} from '../src/mcp/surface.ts';+import { disabledOpsForPublishGates } from '../src/mcp/publish-gates.ts';+import {+ dispatchToolCall,+ isListLevelDenialEnvelope,+ type ToolResult,+} from '../src/mcp/dispatch.ts';+import { startHttpTransport } from '../src/mcp/http-transport.ts';+import { RateLimiter } from '../src/mcp/rate-limit.ts';+import { __setUsageLogPathForTests } from '../src/core/verbs/usage-log.ts';+import { withEnv } from './helpers/with-env.ts';++// Set in beforeAll — module-load time would charge other files' transpile+// and collection work against this file's budget.+let T0 = 0;+const WALL_CLOCK_BUDGET_MS = 3 * 60 * 1000;++const SKILL_FIXTURE = join(import.meta.dir, 'fixtures', 'skill-catalog', 'skills');+const BOUND_PREFIX = 'e2e-bound/';+const LEGACY_TOKEN = 'e5-truthful-catalog-legacy-token';++/**+ * Hermetic env pins, applied via withEnv (the repo's R1-compliant pattern):+ * the file config plane reads $GBRAIN_HOME/.gbrain/config.json, and a stray+ * GBRAIN_MCP_FORCE_SURFACE would silently narrow every resolved surface.+ * All decision-relevant config is ALSO pinned on the DB plane (which wins+ * the dual-plane reads), so the pins are belt-and-suspenders.+ */+const home = mkdtempSync(join(tmpdir(), 'e5-truthful-catalog-'));+const ENV_PINS: Record<string, string | undefined> = {+ GBRAIN_HOME: home,+ GBRAIN_MCP_FORCE_SURFACE: undefined,+};++/** test() wrapper: every body runs under the hermetic env pins. */+function e5test(name: string, fn: () => Promise<void> | void): void {+ test(name, () => withEnv(ENV_PINS, async () => { await fn(); }));+}++let engine: PGLiteEngine;+let legacyUrl: string;+let legacyStop: (() => void) | null = null;++// ---------------------------------------------------------------------------+// Shared setup — ONE engine, ONE legacy server, reused across every cell+// (ENG-21). Gate/strict flips happen on the DB plane per cell, restart-free.+// ---------------------------------------------------------------------------++beforeAll(async () => {+ T0 = Date.now();+ __setUsageLogPathForTests(join(home, 'verb-usage.jsonl'));+ await withEnv(ENV_PINS, async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();++ // DB-plane pins (DB > file, so the dev's real config can't leak in):+ // strict_params=reject means a garbage-arg probe NEVER executes a handler;+ // gates start OFF (the default-off consent posture); the skill catalog+ // points at the test fixture so gate-ON probes are deterministic.+ await engine.setConfig('mcp.strict_params', 'reject');+ await setGates(false);+ await engine.setConfig('mcp.skills_dir', SKILL_FIXTURE);++ // One REAL legacy bearer server over the real engine, started inside the+ // env pins (its surface clamp + file-config snapshot resolve at startup).+ // Generous limiters — the full probe sweep would exhaust the default+ // 30 req/min IP bucket.+ await engine.executeRaw(+ `INSERT INTO access_tokens (name, token_hash) VALUES ($1, $2)`,+ ['e5-truthful-catalog', createHash('sha256').update(LEGACY_TOKEN).digest('hex')],+ );+ const server = await startHttpTransport({+ port: 0,+ engine,+ limiters: {+ ip: new RateLimiter({ limit: 100_000, windowMs: 60_000, lruCap: 100 }),+ token: new RateLimiter({ limit: 100_000, windowMs: 60_000, lruCap: 100 }),+ },+ surface: 'full',+ });+ legacyUrl = `http://localhost:${(server as { port: number }).port}`;+ legacyStop = () => (server as unknown as { stop: (force: boolean) => void }).stop(true);+ });+});++afterAll(async () => {+ legacyStop?.();+ await engine.disconnect();+ __setUsageLogPathForTests(null);+ try { rmSync(home, { recursive: true, force: true }); } catch { /* best-effort */ }+});++// ---------------------------------------------------------------------------+// Harness helpers+// ---------------------------------------------------------------------------++/** Flip BOTH publish gates together on the DB plane (per-key independence is+ * pinned by test/publish-gates.test.ts; the matrix treats gates as one axis). */+async function setGates(on: boolean): Promise<void> {+ await engine.setConfig('mcp.publish_skills', on ? 'true' : 'false');+ await engine.setConfig('mcp.publish_advisor', on ? 'true' : 'false');+}++interface Cell {+ label: string;+ /** OAuth token scopes; null = legacy bearer semantics (no scope checks). */+ scopes: string[] | null;+ surface: McpSurface;+ gatesOn: boolean;+ bound: boolean;+}++function cellAuth(cell: Cell): AuthInfo {+ return {+ token: 'e5-token',+ clientId: `e5-${cell.label}`,+ scopes: cell.scopes ?? [],+ ...(cell.bound ? { boundSlugPrefixes: [BOUND_PREFIX] } : {}),+ };+}++/**+ * The INDEPENDENTLY-composed expectation for what a cell's tools/list must+ * contain, written per-axis from the plan's rules (D7 localOnly, frozen+ * verbs / STARTER_OPS, scope hierarchy + FOV-4 carve-out, ENG-3 bound+ * predicate, WP1 gates). The probes below then assert the REAL dispatch+ * agrees with this set — listed means callable, hidden means denied.+ */+function expectedVisibleSet(cell: Cell): Set<string> {+ const out = new Set<string>();+ for (const op of operations) {+ if (op.localOnly) continue; // D7: network transport+ if (cell.surface === 'verbs' && op.verb !== true) continue; // frozen verb surface+ if (cell.surface === 'starter' && !STARTER_OPS.has(op.name)) continue;+ if (cell.scopes !== null) {+ const scopeOk = hasScope(cell.scopes, op.scope ?? 'read')+ || (op.agentCallable === true && hasScope(cell.scopes, 'agent')); // FOV-4+ if (!scopeOk) continue;+ }+ if (cell.bound && !opAllowedForBoundClient({ boundSlugPrefixes: [BOUND_PREFIX] }, op)) continue;+ if (op.publishGateKey && !cell.gatesOn) continue; // WP1 honest catalog+ out.add(op.name);+ }+ return out;+}++/**+ * The serve-http ListTools computation, composed from the exact seams the+ * real handler uses (serve-http.ts POST /mcp → ListToolsRequestSchema):+ * surface filter after the localOnly filter, then scope (+ agentCallable+ * carve-out), bound-client predicate, publish gates.+ */+async function oauthToolsList(cell: Cell): Promise<Set<string>> {+ const mcpOperations = filterOpsForSurface(operations.filter(op => !op.localOnly), cell.surface);+ const gateDisabled = await disabledOpsForPublishGates(engine, null);+ const auth = cellAuth(cell);+ const visible = mcpOperations.filter(op =>+ (hasScope(auth.scopes, op.scope ?? 'read')+ || (op.agentCallable === true && hasScope(auth.scopes, 'agent')))+ && opAllowedForBoundClient(auth, op)+ && !gateDisabled.has(op.name));+ return new Set(visible.map(o => o.name));+}++type ProbeKind =+ | 'success'+ | 'invalid_params'+ | 'unknown' // unknown_tool / unknown_operation+ | 'list_level_denial' // config_key= / fence=op / insufficient_scope+ | 'arg_level_denial' // permission_denied WITHOUT a list-level marker (D10: legitimate)+ | 'other_error';++interface ProbeVerdict { kind: ProbeKind; envelope: Record<string, unknown> | null }++function classify(result: ToolResult): ProbeVerdict {+ if (!result.isError) return { kind: 'success', envelope: null };+ let parsed: Record<string, unknown>;+ try {+ parsed = JSON.parse(result.content[0]?.text ?? '') as Record<string, unknown>;+ } catch {+ return { kind: 'other_error', envelope: null };+ }+ if (isListLevelDenialEnvelope(parsed)) return { kind: 'list_level_denial', envelope: parsed };+ if (parsed.error === 'insufficient_scope') return { kind: 'list_level_denial', envelope: parsed };+ if (parsed.error === 'unknown_tool' || parsed.error === 'unknown_operation') return { kind: 'unknown', envelope: parsed };+ if (parsed.error === 'invalid_params') return { kind: 'invalid_params', envelope: parsed };+ if (parsed.error === 'permission_denied') return { kind: 'arg_level_denial', envelope: parsed };+ return { kind: 'other_error', envelope: parsed };+}++/**+ * The serve-http CallTool path over the shared dispatcher: op resolution+ * against the surfaced set (unknown_operation outside it), the hasScope ++ * agentCallable gate (insufficient_scope — logged denied_after_list in+ * production), then the REAL dispatchToolCall with the same opts serve-http+ * passes (remote/http/allowedOps/auth/surface/surfaceCeiling).+ */+async function oauthToolCall(+ cell: Cell,+ name: string,+ args: Record<string, unknown>,+): Promise<ProbeVerdict> {+ const mcpOperations = filterOpsForSurface(operations.filter(op => !op.localOnly), cell.surface);+ const op = mcpOperations.find(o => o.name === name);+ if (!op) return { kind: 'unknown', envelope: { error: 'unknown_operation' } };+ const auth = cellAuth(cell);+ const scopeSatisfied = hasScope(auth.scopes, op.scope ?? 'read')+ || (op.agentCallable === true && hasScope(auth.scopes, 'agent'));+ if (!scopeSatisfied) {+ return { kind: 'list_level_denial', envelope: { error: 'insufficient_scope' } };+ }+ const surfaceAllowedOps: ReadonlySet<string> | undefined =+ cell.surface === 'full' ? undefined : new Set(mcpOperations.map(o => o.name));+ const result = await dispatchToolCall(engine, name, args, {+ remote: true,+ transport: 'http',+ sourceId: 'default',+ auth,+ ...(surfaceAllowedOps ? { allowedOps: surfaceAllowedOps } : {}),+ surface: cell.surface,+ surfaceCeiling: cell.surface,+ });+ return classify(result);+}++/**+ * D10 probe semantics: WRONG-TYPED values for every required param (rejects+ * in warn AND reject modes, before any handler runs); ops with no required+ * params get one undeclared key, which the pinned strict_params=reject+ * refuses — so a full sweep can never execute a write handler.+ */+function probeArgsFor(op: Operation): Record<string, unknown> {+ const wrong: Record<string, unknown> = {};+ let hasRequired = false;+ for (const [key, def] of Object.entries(op.params)) {+ if (!def.required) continue;+ hasRequired = true;+ wrong[key] =+ def.type === 'string' ? 42+ : def.type === 'number' ? 'not-a-number'+ : def.type === 'boolean' ? 'not-a-boolean'+ : def.type === 'array' ? 'not-an-array'+ : 42; // object → number+ }+ return hasRequired ? wrong : { e5_garbage_probe: true };+}++/** Probe EVERY listed tool; return invariant violations (empty = truthful). */+async function sweepCell(cell: Cell, listed: ReadonlySet<string>): Promise<string[]> {+ const violations: string[] = [];+ for (const name of [...listed].sort()) {+ const op = operations.find(o => o.name === name);+ if (!op) { violations.push(`${cell.label}: listed "${name}" is not a known operation`); continue; }+ const verdict = await oauthToolCall(cell, name, probeArgsFor(op));+ // Garbage probes must die at validation — anything else means either a+ // list-level denial (the invariant breach) or a handler executed on+ // garbage args despite strict_params=reject.+ if (verdict.kind !== 'invalid_params') {+ violations.push(`${cell.label}: listed "${name}" → ${verdict.kind} ${JSON.stringify(verdict.envelope)}`);+ }+ }+ return violations;+}++function sortedArray(s: ReadonlySet<string>): string[] {+ return [...s].sort();+}++// --- legacy bearer transport (real HTTP) helpers ---------------------------++async function legacyRpc(method: string, params?: unknown): Promise<Record<string, unknown>> {+ const res = await fetch(`${legacyUrl}/mcp`, {+ method: 'POST',+ headers: { 'Authorization': `Bearer ${LEGACY_TOKEN}`, 'Content-Type': 'application/json' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, ...(params !== undefined ? { params } : {}) }),+ });+ expect(res.status).toBe(200);+ return await res.json() as Record<string, unknown>;+}++async function legacyToolsList(): Promise<Set<string>> {+ const body = await legacyRpc('tools/list');+ const tools = (body.result as { tools: Array<{ name: string }> }).tools;+ return new Set(tools.map(t => t.name));+}++async function legacyToolCall(name: string, args: Record<string, unknown>): Promise<ProbeVerdict> {+ const body = await legacyRpc('tools/call', { name, arguments: args });+ return classify(body.result as ToolResult);+}++// ---------------------------------------------------------------------------+// (a) The legacy bearer transport — real HTTP server, real engine+// ---------------------------------------------------------------------------++describe('E5 truthful catalog — legacy bearer transport (real HTTP, PGLite)', () => {+ e5test('gates off: tools/list is exactly the expected honest set (no gated, no localOnly)', async () => {+ await setGates(false);+ const listed = await legacyToolsList();+ const expected = expectedVisibleSet({+ label: 'legacy-full-gates-off', scopes: null, surface: 'full', gatesOn: false, bound: false,+ });+ expect(sortedArray(listed)).toEqual(sortedArray(expected));+ for (const gated of ['list_skills', 'get_skill', 'list_brain_skillpack', 'advisor']) {+ expect(listed.has(gated)).toBe(false);+ }+ for (const localOnly of ['file_list', 'file_upload', 'file_url', 'sync_brain']) {+ expect(listed.has(localOnly)).toBe(false);+ }+ });++ e5test('full probe sweep: every listed tool dies at validation, never at a list-level denial', async () => {+ await setGates(false);+ const listed = await legacyToolsList();+ expect(listed.size).toBeGreaterThan(50); // the sweep is real, not vacuous+ const violations: string[] = [];+ for (const name of sortedArray(listed)) {+ const op = operations.find(o => o.name === name);+ if (!op) { violations.push(`legacy: listed "${name}" is not a known operation`); continue; }+ const verdict = await legacyToolCall(name, probeArgsFor(op));+ if (verdict.kind !== 'invalid_params') {+ violations.push(`legacy: listed "${name}" → ${verdict.kind} ${JSON.stringify(verdict.envelope)}`);+ }+ }+ expect(violations).toEqual([]);+ });++ e5test('inverse: localOnly op is uncallable with the no-leak unknown_tool envelope', async () => {+ const denied = await legacyToolCall('file_list', {});+ expect(denied.kind).toBe('unknown');+ expect(denied.envelope?.message).toBe('Unknown tool: file_list');+ // Byte-identical error class to a nonexistent op — no existence oracle.+ const noSuchOp = await legacyToolCall('e5_no_such_op_xyz', {});+ expect(noSuchOp.kind).toBe('unknown');+ expect(denied.envelope?.error).toBe(noSuchOp.envelope?.error);+ });++ e5test('inverse: gate-hidden op is call-time-denied with the config_key grammar, never success', async () => {+ await setGates(false);+ expect((await legacyToolsList()).has('list_skills')).toBe(false);+ const verdict = await legacyToolCall('list_skills', {});+ expect(verdict.kind).toBe('list_level_denial');+ expect(verdict.envelope?.detail).toBe('config_key=mcp.publish_skills');+ });++ e5test('restart-free gate flip: ON lists + allows the gated ops; OFF hides them again (per-request read)', async () => {+ await setGates(true);+ const listedOn = await legacyToolsList();+ for (const gated of ['list_skills', 'get_skill', 'list_brain_skillpack', 'advisor']) {+ expect(listedOn.has(gated)).toBe(true);+ }+ // Listed means callable: the gate-on probe reaches the handler and is+ // never a list-level denial (the fixture catalog makes it a clean read).+ const skills = await legacyToolCall('list_skills', {});+ expect(skills.kind).toBe('success');+ const skill = await legacyToolCall('get_skill', { name: 'brain-ops' });+ expect(skill.kind).toBe('success');++ await setGates(false);+ const listedOff = await legacyToolsList();+ for (const gated of ['list_skills', 'get_skill', 'list_brain_skillpack', 'advisor']) {+ expect(listedOff.has(gated)).toBe(false);+ }+ });++ e5test('FOV-6c: the ONE warn-mode case — a READ op accepts the garbage key with a warning, never a denial', async () => {+ try {+ await engine.setConfig('mcp.strict_params', 'warn');+ const body = await legacyRpc('tools/call', {+ name: 'list_pages',+ arguments: { limit: 1, e5_garbage_probe: true },+ });+ const result = body.result as ToolResult;+ expect(result.isError ?? false).toBe(false); // warn mode accepts+ const meta = result._meta as { warnings?: Array<{ code: string; param: string }> } | undefined;+ expect(meta?.warnings?.[0]?.code).toBe('unknown_param');+ expect(meta?.warnings?.[0]?.param).toBe('e5_garbage_probe');+ // The model-visible grace-period notice rides the second content block.+ const blocks = result.content.map(c => c.text);+ expect(blocks.some(t => t.includes('unknown parameter "e5_garbage_probe"'))).toBe(true);+ } finally {+ await engine.setConfig('mcp.strict_params', 'reject');+ }+ });+});++// ---------------------------------------------------------------------------+// (b) The OAuth serve-http semantics — in-process over the real dispatcher+// ---------------------------------------------------------------------------++const SCOPE_ROWS: ReadonlyArray<[string, string[]]> = [+ ['read', ['read']],+ ['write', ['write']],+ ['admin', ['admin']],+ ['agent', ['agent']],+];+const SURFACES: ReadonlyArray<McpSurface> = ['verbs', 'starter', 'full'];++function makeCell(scopeName: string, scopes: string[], surface: McpSurface, gatesOn: boolean, bound: boolean): Cell {+ return {+ label: `${scopeName}+${surface}+gates-${gatesOn ? 'on' : 'off'}${bound ? '+bound' : ''}`,+ scopes, surface, gatesOn, bound,+ };+}++describe('E5 truthful catalog — OAuth-path cells (serve-http seams over dispatch)', () => {+ e5test('extreme cell: admin + full + gates-on — list-set equality + full probe sweep + gate reachability', async () => {+ await setGates(true);+ const cell = makeCell('admin', ['admin'], 'full', true, false);+ const listed = await oauthToolsList(cell);+ expect(sortedArray(listed)).toEqual(sortedArray(expectedVisibleSet(cell)));+ // Gated ops are LISTED with gates on…+ for (const gated of ['list_skills', 'get_skill', 'list_brain_skillpack', 'advisor']) {+ expect(listed.has(gated)).toBe(true);+ }+ // …and agent-lane ops are NOT (admin does not imply agent, v0.38 D13).+ expect(listed.has('submit_agent')).toBe(false);++ expect(await sweepCell(cell, listed)).toEqual([]);++ // Listed-gated ops are REACHABLE with valid args (the call-time gate+ // backstop must agree with the list): never a list-level denial.+ for (const [name, args] of [+ ['list_skills', {}],+ ['get_skill', { name: 'brain-ops' }],+ ['list_brain_skillpack', {}],+ ['advisor', {}],+ ] as Array<[string, Record<string, unknown>]>) {+ const verdict = await oauthToolCall(cell, name, args);+ expect(['list_level_denial', 'unknown']).not.toContain(verdict.kind);+ }+ });++ e5test('extreme cell: read + starter + gates-off — list-set equality + full probe sweep', async () => {+ await setGates(false);+ const cell = makeCell('read', ['read'], 'starter', false, false);+ const listed = await oauthToolsList(cell);+ expect(sortedArray(listed)).toEqual(sortedArray(expectedVisibleSet(cell)));+ // The starter read slice keeps discovery (FOV-4/D4) and hides writes.+ expect(listed.has('request_tools')).toBe(true);+ expect(listed.has('put_page')).toBe(false);+ // STARTER_OPS carries localOnly daily-driver names (file_list); the+ // network list must still exclude them (localOnly filters run FIRST).+ expect(listed.has('file_list')).toBe(false);++ expect(await sweepCell(cell, listed)).toEqual([]);+ });++ e5test('extreme cell: bound client + write + full + gates-on — sweep + ENG-3/D9/D10 fence pins', async () => {+ await setGates(true);+ const cell = makeCell('write', ['write'], 'full', true, true);+ const listed = await oauthToolsList(cell);+ expect(sortedArray(listed)).toEqual(sortedArray(expectedVisibleSet(cell)));+ // The fenced-write allow-list and the D9 discovery carve-out are listed;+ // unfenceable writes are not.+ expect(listed.has('put_page')).toBe(true);+ expect(listed.has('request_tools')).toBe(true);+ expect(listed.has('extract_facts')).toBe(false);++ expect(await sweepCell(cell, listed)).toEqual([]);++ // Listed fenced write is genuinely callable (dry-run, in-prefix).+ const inPrefix = await oauthToolCall(cell, 'put_page', {+ slug: `${BOUND_PREFIX}e5-probe`, content: '# probe', dry_run: true,+ });+ expect(inPrefix.kind).toBe('success');++ // D10 carve-out: an out-of-prefix slug on a LISTED op is an ARGUMENT-level+ // denial — permission_denied WITHOUT the fence=op marker, excluded from+ // the invariant (and from the denied_after_list metric).+ const outOfPrefix = await oauthToolCall(cell, 'put_page', {+ slug: 'wiki/other/e5-probe', content: '# probe', dry_run: true,+ });+ expect(outOfPrefix.kind).toBe('arg_level_denial');+ expect(isListLevelDenialEnvelope(outOfPrefix.envelope)).toBe(false);++ // Inverse (ENG-3, same predicate at list and call time): a fence-hidden+ // unfenceable write with VALID args denies with the fence=op marker.+ const fenced = await oauthToolCall(cell, 'extract_facts', { turn_text: 'e5 probe' });+ expect(fenced.kind).toBe('list_level_denial');+ expect(fenced.envelope?.detail).toBe('fence=op');++ // D9: discovery survives the fence for slug-bound clients.+ const discovery = await oauthToolCall(cell, 'request_tools', {});+ expect(discovery.kind).toBe('success');+ });++ e5test('matrix: list-set equality for every scope × surface × gates × bound cell (amendment 31)', async () => {+ const mismatches: string[] = [];+ for (const gatesOn of [true, false]) {+ await setGates(gatesOn);+ for (const [scopeName, scopes] of SCOPE_ROWS) {+ for (const surface of SURFACES) {+ for (const bound of [false, true]) {+ const cell = makeCell(scopeName, scopes, surface, gatesOn, bound);+ const actual = sortedArray(await oauthToolsList(cell));+ const expected = sortedArray(expectedVisibleSet(cell));+ if (JSON.stringify(actual) !== JSON.stringify(expected)) {+ mismatches.push(`${cell.label}: listed [${actual.join(',')}] != expected [${expected.join(',')}]`);+ }+ }+ }+ }+ }+ expect(mismatches).toEqual([]);+ });++ e5test('matrix: denial-class representative probes per cell (gated ×4, admin op, localOnly op, request_tools)', async () => {+ const violations: string[] = [];+ const record = (cell: Cell, name: string, msg: string) =>+ violations.push(`${cell.label} / ${name}: ${msg}`);++ for (const gatesOn of [true, false]) {+ await setGates(gatesOn);+ for (const [scopeName, scopes] of SCOPE_ROWS) {+ for (const surface of SURFACES) {+ const cell = makeCell(scopeName, scopes, surface, gatesOn, false);+ const expected = expectedVisibleSet(cell);++ // The four publish-gated ops, probed with VALID args so the+ // call-time gate backstop is actually reached. advisor's listed+ // case uses a garbage probe instead (its full run is exercised+ // once in the extreme cell; reachability is scope/surface-blind).+ const gatedProbes: Array<[string, Record<string, unknown>, Record<string, unknown> | null]> = [+ ['list_skills', {}, null],+ ['get_skill', { name: 'brain-ops' }, null],+ ['list_brain_skillpack', {}, null],+ ['advisor', {}, { e5_garbage_probe: true }],+ ];+ for (const [name, hiddenArgs, listedArgsOverride] of gatedProbes) {+ if (expected.has(name)) {+ const verdict = await oauthToolCall(cell, name, listedArgsOverride ?? hiddenArgs);+ if (verdict.kind === 'list_level_denial' || verdict.kind === 'unknown') {+ record(cell, name, `listed but ${verdict.kind}: ${JSON.stringify(verdict.envelope)}`);+ }+ } else {+ const verdict = await oauthToolCall(cell, name, hiddenArgs);+ if (verdict.kind === 'success') record(cell, name, 'hidden but callable');+ if (verdict.kind !== 'unknown' && verdict.kind !== 'list_level_denial') {+ record(cell, name, `hidden with unexpected verdict ${verdict.kind}: ${JSON.stringify(verdict.envelope)}`);+ }+ }+ }++ // One admin op: listed → dies at validation; hidden → scope/surface+ // denial, never success (the honest-catalog inverse).+ {+ const verdict = await oauthToolCall(cell, 'run_doctor', { e5_garbage_probe: true });+ if (expected.has('run_doctor')) {+ if (verdict.kind !== 'invalid_params') {+ record(cell, 'run_doctor', `listed but ${verdict.kind}: ${JSON.stringify(verdict.envelope)}`);+ }+ } else if (verdict.kind !== 'unknown' && verdict.kind !== 'list_level_denial') {+ record(cell, 'run_doctor', `hidden with unexpected verdict ${verdict.kind}`);+ }+ }++ // One localOnly op: never listed, always the no-leak unknown envelope.+ {+ if (expected.has('file_list')) record(cell, 'file_list', 'localOnly op in the expected list');+ const verdict = await oauthToolCall(cell, 'file_list', {});+ if (verdict.kind !== 'unknown') {+ record(cell, 'file_list', `expected unknown, got ${verdict.kind}: ${JSON.stringify(verdict.envelope)}`);+ }+ }++ // request_tools probed with {surface:'garbage'} → invalid_params on+ // the listed surfaces (never a persist), unknown on verbs (D4/D10).+ {+ const verdict = await oauthToolCall(cell, 'request_tools', { surface: 'garbage' });+ if (expected.has('request_tools')) {+ if (verdict.kind !== 'invalid_params') {+ record(cell, 'request_tools', `expected invalid_params, got ${verdict.kind}: ${JSON.stringify(verdict.envelope)}`);+ }+ } else if (verdict.kind !== 'unknown') {+ record(cell, 'request_tools', `expected unknown on ${cell.surface}, got ${verdict.kind}`);+ }+ const rows = await engine.executeRaw(+ `SELECT count(*)::int AS n FROM oauth_clients WHERE client_id = $1`,+ [`e5-${cell.label}`],+ ) as Array<{ n: number }>;+ if (rows[0].n !== 0) record(cell, 'request_tools', 'garbage surface probe persisted a client row');+ }+ }+ }+ }+ expect(violations).toEqual([]);+ });++ e5test('FOV-4: the agent-only token row lists exactly its callable set, and every member is callable', async () => {+ await setGates(false);+ const cell = makeCell('agent', ['agent'], 'full', false, false);+ const listed = await oauthToolsList(cell);+ expect(sortedArray(listed)).toEqual(['get_agent_job', 'request_tools', 'submit_agent']);++ // Probes: garbage args die at validation (proving the scope layer let+ // them through), and discovery genuinely works for the agent class.+ for (const name of ['submit_agent', 'get_agent_job']) {+ const op = operations.find(o => o.name === name)!;+ const verdict = await oauthToolCall(cell, name, probeArgsFor(op));+ expect(verdict.kind).toBe('invalid_params');+ }+ const discovery = await oauthToolCall(cell, 'request_tools', {});+ expect(discovery.kind).toBe('success');++ // Inverse: a read op is NOT listed and NOT callable for the agent class.+ expect(listed.has('get_page')).toBe(false);+ const denied = await oauthToolCall(cell, 'get_page', { slug: 'x' });+ expect(denied.kind).toBe('list_level_denial');+ });++ e5test('monotonicity: verbs ⊆ starter ⊆ full listing per token class (both gate states)', async () => {+ const rows: Array<[string, string[], boolean]> = [+ ...SCOPE_ROWS.map(([name, scopes]) => [name, scopes, false] as [string, string[], boolean]),+ ['bound-write', ['write'], true],+ ];+ for (const gatesOn of [true, false]) {+ await setGates(gatesOn);+ for (const [scopeName, scopes, bound] of rows) {+ const verbs = await oauthToolsList(makeCell(scopeName, scopes, 'verbs', gatesOn, bound));+ const starter = await oauthToolsList(makeCell(scopeName, scopes, 'starter', gatesOn, bound));+ const full = await oauthToolsList(makeCell(scopeName, scopes, 'full', gatesOn, bound));+ for (const name of verbs) {+ expect(starter.has(name)).toBe(true);+ }+ for (const name of starter) {+ expect(full.has(name)).toBe(true);+ }+ }+ }+ });+});++// ---------------------------------------------------------------------------+// persist → re-list flip (amendment 20: per-request recompute, no restart)+// ---------------------------------------------------------------------------++describe('E5 truthful catalog — request_tools persist flips the very next list', () => {+ e5test('{surface: starter} persist → the next per-request resolution serves the starter list, no restart', async () => {+ await setGates(false);+ const clientId = 'e5-flip-client';+ await engine.executeRaw(+ `INSERT INTO oauth_clients (client_id, client_name) VALUES ($1, $2)+ ON CONFLICT (client_id) DO NOTHING`,+ [clientId, 'e5 flip client'],+ );+ const auth: AuthInfo = { token: 't', clientId, scopes: ['read'] };++ // Request #1: NULL row surface + unset DCR default → the server ceiling+ // (full) — pre-WP4 behavior, existing clients untouched.+ const readRowSurface = async (): Promise<unknown> => {+ const rows = await engine.executeRaw(+ `SELECT surface FROM oauth_clients WHERE client_id = $1`, [clientId],+ ) as Array<{ surface: unknown }>;+ return rows[0]?.surface ?? null;+ };+ const resolveEffective = async (): Promise<McpSurface> => effectiveSurfaceForClient({+ ceiling: 'full',+ clientSurface: resolveClientRowSurface(await readRowSurface(), clientId),+ defaultSurface: await resolveDefaultClientSurface(engine, null),+ });++ const before = await resolveEffective();+ expect(before).toBe('full');+ const listBefore = await oauthToolsList({ label: 'flip-before', scopes: ['read'], surface: before, gatesOn: false, bound: false });++ // The REAL persist through the real dispatcher (the same seam serve-http+ // drives). NOTE the verifyAccessToken row-read leg of the loop is+ // emulated by re-reading the row below; the full OAuth-server round trip+ // is the Postgres-host assertion in test/e2e/serve-http-oauth.test.ts.+ const persist = await dispatchToolCall(engine, 'request_tools', { surface: 'starter' }, {+ remote: true, transport: 'http', sourceId: 'default', auth,+ surface: before, surfaceCeiling: 'full',+ });+ expect(persist.isError ?? false).toBe(false);+ const body = JSON.parse(persist.content[0].text) as { persisted: boolean; surface: string };+ expect(body.persisted).toBe(true);+ expect(body.surface).toBe('starter');++ // Request #2, same process, no restart: per-request recompute reads the+ // persisted row and the effective surface narrows to starter.+ const after = await resolveEffective();+ expect(after).toBe('starter');+ const listAfter = await oauthToolsList({ label: 'flip-after', scopes: ['read'], surface: after, gatesOn: false, bound: false });+ expect(sortedArray(listAfter)).toEqual(sortedArray(expectedVisibleSet({+ label: 'flip-expected', scopes: ['read'], surface: 'starter', gatesOn: false, bound: false,+ })));+ // Strictly narrower, and still a subset of what full served (ENG-1 ladder).+ expect(listAfter.size).toBeLessThan(listBefore.size);+ for (const name of listAfter) {+ expect(listBefore.has(name)).toBe(true);+ }+ });+});++// ---------------------------------------------------------------------------+// Wall-clock budget (ENG-21) — declared LAST so it runs after every cell.+// ---------------------------------------------------------------------------++describe('E5 budget', () => {+ test(`the whole file completes in < ${WALL_CLOCK_BUDGET_MS / 60000} minutes`, () => {+ const elapsed = Date.now() - T0;+ if (elapsed >= WALL_CLOCK_BUDGET_MS) {+ const msg =+ `E5 truthful-catalog run took ${(elapsed / 1000).toFixed(1)}s — past the ${WALL_CLOCK_BUDGET_MS / 1000}s ` ++ `budget (ENG-21). The invariant guard must stay cheap enough to run in every unit pass; ` ++ `trim probe work or split cells before raising this budget.`;+ // Machine load makes wall-clock assertions flaky — hard-fail only when+ // the budget gate is explicitly armed (dedicated perf lane / local run).+ if (process.env.GBRAIN_ENFORCE_E5_BUDGET === '1') throw new Error(msg);+ console.warn(msg);+ }+ });+});diff --git a/test/validate-params.test.ts b/test/validate-params.test.tsnew file mode 100644index 0000000000..90a0b28c20--- /dev/null+++ b/test/validate-params.test.ts@@ -0,0 +1,376 @@+/**+ * WP3 (T6) — strict/warn param validation + unknown_tool did-you-mean.+ *+ * Covers, per the plan's verify list:+ * 1. normalize→validate call order: null/'' optional-absence idioms are+ * normalized away BEFORE unknown-key detection (never reported unknown);+ * 2. warn mode: unknown keys accepted, `_meta.warnings` collected with the+ * amendment-13 shape, model-visible warn block appended;+ * 3. reject mode: invalid_params envelope, did-you-mean in `suggestion`,+ * raw unknown key NEVER in `message` (the one field persisted to+ * mcp_request_log.error_message);+ * 4. enum membership rejects in BOTH modes (type error, not unknown key);+ * 5. `_meta` / `dry_run` allowlist;+ * 6. unknown_tool leak pins: gated + localOnly names never suggested;+ * hidden-vs-nonexistent envelopes identical (same builder, same+ * candidate set).+ */++import { beforeEach, describe, expect, test } from 'bun:test';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import {+ normalizeOptionalParams,+ validateParams,+ findUnknownParams,+ buildUnknownParamWarnBlock,+ resolveStrictParamsMode,+ resetStrictParamsModeCache,+ parseStrictParamsMode,+ UNKNOWN_PARAM_ALLOWLIST,+} from '../src/mcp/validate-params.ts';+import { operations, operationsByName } from '../src/core/operations.ts';+import type { BrainEngine } from '../src/core/engine.ts';++/**+ * Minimal engine stub. `mcp.strict_params` resolves from the DB plane first,+ * so pinning the stub's getConfig makes each test deterministic regardless of+ * the runner's file config. resolveSlugs/getStats back the two trivial op+ * handlers the dispatch-level tests exercise.+ */+function stubEngine(strictMode: 'warn' | 'reject' | null): BrainEngine {+ return {+ kind: 'pglite',+ getConfig: async (k: string) => (k === 'mcp.strict_params' ? strictMode : null),+ resolveSlugs: async () => [],+ getStats: async () => ({ pages: 0 }),+ getTimeline: async () => [],+ } as unknown as BrainEngine;+}++const DISPATCH_OPTS = { remote: true, transport: 'http' as const, sourceId: 'default' };++function body(result: { content: Array<{ text: string }> }) {+ return JSON.parse(result.content[0].text);+}++// ---------------------------------------------------------------------------+// 1. normalize → validate → unknown-detection order+// ---------------------------------------------------------------------------++describe('normalize→validate order (absence idioms are not unknown keys)', () => {+ test('null / empty-string optional idioms are normalized away before unknown detection', () => {+ const recall = operationsByName['recall'];+ const normalized = normalizeOptionalParams(recall, { since: '', entity: null, query: 'x' });+ expect('since' in normalized).toBe(false);+ expect('entity' in normalized).toBe(false);+ expect(normalized.query).toBe('x');+ // The normalized object carries no unknown keys — the idioms were+ // DECLARED optionals, not stray keys.+ expect(findUnknownParams(recall, normalized)).toEqual([]);+ expect(validateParams(recall, normalized)).toBeNull();+ });++ test('dispatch accepts null/"" optional idioms without warnings (order pin)', async () => {+ const out = await dispatchToolCall(stubEngine('warn'), 'get_timeline', {+ slug: 'people/alice-example',+ since: null,+ until: '',+ }, DISPATCH_OPTS);+ expect(out.isError ?? false).toBe(false);+ expect(out._meta?.warnings).toBeUndefined();+ expect(out.content.length).toBe(1);+ });+});++// ---------------------------------------------------------------------------+// 2. warn mode+// ---------------------------------------------------------------------------++describe('warn mode (default) — accept + _meta.warnings + model-visible block', () => {+ test('unknown key collected with amendment-13 shape and nearest-declared suggestion', async () => {+ const out = await dispatchToolCall(stubEngine('warn'), 'resolve_slugs', {+ partial: 'alice-ex',+ partal: 'typo-key',+ }, DISPATCH_OPTS);+ expect(out.isError ?? false).toBe(false);+ expect(out._meta?.warnings).toEqual([+ { code: 'unknown_param', param: 'partal', suggestion: 'partial' },+ ]);+ // D8 second-block mechanism carries the grace-period notice.+ expect(out.content.length).toBe(2);+ expect(out.content[1].text).toBe(+ 'warning: unknown parameter "partal" ignored — did you mean "partial"? A future release rejects unknown parameters.',+ );+ });++ test('unresolved (absent) config defaults to warn', async () => {+ const out = await dispatchToolCall(stubEngine(null), 'resolve_slugs', {+ partial: 'a',+ totally_unrelated_key: 1,+ }, DISPATCH_OPTS);+ expect(out.isError ?? false).toBe(false);+ const warnings = out._meta?.warnings as Array<{ param: string; suggestion?: string }>;+ expect(warnings.length).toBe(1);+ expect(warnings[0].param).toBe('totally_unrelated_key');+ // Nothing within edit distance → no suggestion key at all.+ expect('suggestion' in warnings[0]).toBe(false);+ expect(out.content[1].text).toBe(+ 'warning: unknown parameter "totally_unrelated_key" ignored. A future release rejects unknown parameters.',+ );+ });++ test('suggestion candidates are the op\'s DECLARED params only', () => {+ // 'quer' is nearest to resolve_slugs' declared 'partial'? No — nothing+ // within distance; but against the search op it suggests 'query'. The+ // candidate pool is per-op, never the global param namespace.+ const search = operationsByName['search'];+ const found = findUnknownParams(search, { query: 'x', quer: 'y' });+ expect(found).toEqual([{ code: 'unknown_param', param: 'quer', suggestion: 'query' }]);+ const resolveSlugs = operationsByName['resolve_slugs'];+ const foreign = findUnknownParams(resolveSlugs, { partial: 'x', quer: 'y' });+ expect(foreign.length).toBe(1);+ expect(foreign[0].suggestion).not.toBe('query');+ });++ test('buildUnknownParamWarnBlock joins one line per unknown key', () => {+ const block = buildUnknownParamWarnBlock([+ { code: 'unknown_param', param: 'a', suggestion: 'b' },+ { code: 'unknown_param', param: 'c' },+ ]);+ const lines = block.split('\n');+ expect(lines.length).toBe(2);+ expect(lines[0]).toContain('"a"');+ expect(lines[0]).toContain('did you mean "b"');+ expect(lines[1]).toContain('"c"');+ expect(lines[1]).not.toContain('did you mean');+ });+});++// ---------------------------------------------------------------------------+// 3. reject mode+// ---------------------------------------------------------------------------++describe('reject mode — invalid_params envelope, raw key only in suggestion', () => {+ test('unknown key → invalid_params with did-you-mean in suggestion', async () => {+ const out = await dispatchToolCall(stubEngine('reject'), 'resolve_slugs', {+ partial: 'alice-ex',+ partal: 'typo-key',+ }, DISPATCH_OPTS);+ expect(out.isError).toBe(true);+ const envelope = body(out);+ expect(envelope.error).toBe('invalid_params');+ expect(envelope.suggestion).toContain('"partal"');+ expect(envelope.suggestion).toContain('did you mean "partial"');+ // Privacy (amendment 11): serve-http persists `message` to+ // mcp_request_log.error_message — the raw unknown key must not be there.+ expect(envelope.message).not.toContain('partal');+ expect(envelope.message).toContain('unknown parameter');+ });++ test('declared params + allowlisted keys still dispatch under reject', async () => {+ const out = await dispatchToolCall(stubEngine('reject'), 'resolve_slugs', {+ partial: 'alice-ex',+ _meta: { session_id: 'topic-1' },+ dry_run: false,+ }, DISPATCH_OPTS);+ expect(out.isError ?? false).toBe(false);+ });+});++// ---------------------------------------------------------------------------+// 4. enum membership — both modes+// ---------------------------------------------------------------------------++describe('enum membership rejects in BOTH strict modes', () => {+ for (const mode of ['warn', 'reject'] as const) {+ test(`list_pages sort=bogus → invalid_params naming the allowed values (${mode} mode)`, async () => {+ const out = await dispatchToolCall(stubEngine(mode), 'list_pages', {+ sort: 'bogus_order',+ }, DISPATCH_OPTS);+ expect(out.isError).toBe(true);+ const envelope = body(out);+ expect(envelope.error).toBe('invalid_params');+ expect(envelope.message).toBe(+ 'Parameter "sort" must be one of: updated_desc, updated_asc, created_desc, slug',+ );+ });+ }++ test('validateParams: valid enum value passes, non-member fails', () => {+ const listPages = operationsByName['list_pages'];+ expect(validateParams(listPages, { sort: 'slug' })).toBeNull();+ expect(validateParams(listPages, { sort: 'name' })).toContain('must be one of');+ });+});++// ---------------------------------------------------------------------------+// 5. `_meta` / `dry_run` allowlist+// ---------------------------------------------------------------------------++describe('_meta / dry_run allowlist', () => {+ test('the allowlist is exactly the two dispatch passthrough keys', () => {+ expect([...UNKNOWN_PARAM_ALLOWLIST].sort()).toEqual(['_meta', 'dry_run']);+ });++ test('allowlisted keys are never flagged (op with an empty param schema)', async () => {+ const out = await dispatchToolCall(stubEngine('warn'), 'get_stats', {+ _meta: { session_id: 'topic-1' },+ dry_run: false,+ }, DISPATCH_OPTS);+ expect(out.isError ?? false).toBe(false);+ expect(out._meta?.warnings).toBeUndefined();+ expect(out.content.length).toBe(1);+ });+});++// ---------------------------------------------------------------------------+// 6. unknown_tool did-you-mean — leak pins+// ---------------------------------------------------------------------------++const EXCLUDED_FROM_SUGGESTIONS = new Set(+ operations+ .filter(op => op.localOnly || op.publishGateKey)+ .map(op => op.name),+);++function suggestedName(envelope: { suggestion?: string }): string | null {+ const m = envelope.suggestion?.match(/^Did you mean "(.+)"\?$/);+ return m ? m[1] : null;+}++describe('unknown_tool did-you-mean (leak-hardened)', () => {+ test('a near-miss of a visible op gets a suggestion', async () => {+ const out = await dispatchToolCall(stubEngine(null), 'get_pag', {}, DISPATCH_OPTS);+ expect(out.isError).toBe(true);+ const envelope = body(out);+ expect(envelope.error).toBe('unknown_tool');+ expect(envelope.suggestion).toBe('Did you mean "get_page"?');+ });++ test('gated + localOnly names are NEVER suggested (near-miss sweep)', async () => {+ for (const hidden of EXCLUDED_FROM_SUGGESTIONS) {+ // Probe with the hidden name minus its last character — within edit+ // distance 1 of the hidden op, so it WOULD be the best suggestion if+ // the candidate set failed to exclude it.+ const probe = hidden.slice(0, -1);+ const out = await dispatchToolCall(stubEngine(null), probe, {}, DISPATCH_OPTS);+ expect(out.isError).toBe(true);+ const envelope = body(out);+ expect(envelope.error).toBe('unknown_tool');+ const suggested = suggestedName(envelope);+ if (suggested !== null) {+ expect(EXCLUDED_FROM_SUGGESTIONS.has(suggested)).toBe(false);+ }+ }+ });++ test('hidden-op path (allowedOps miss) and nonexistent path emit byte-identical envelopes', async () => {+ // Same input name through BOTH code paths: 'get_pag' does not exist+ // (nonexistent path when allowedOps admits it / is unset) and is not in+ // the allow set (hidden path when allowedOps is set). The builder and+ // candidate set are shared, so the envelopes must match byte-for-byte+ // when the candidate pools coincide.+ const viaNonexistent = await dispatchToolCall(stubEngine(null), 'get_pag', {}, DISPATCH_OPTS);+ const viaHidden = await dispatchToolCall(stubEngine(null), 'get_pag', {}, {+ ...DISPATCH_OPTS,+ allowedOps: new Set(operations.filter(op => !op.localOnly).map(o => o.name)),+ });+ expect(viaHidden.content[0].text).toBe(viaNonexistent.content[0].text);+ expect(viaHidden.isError).toBe(true);+ });++ test('a REAL hidden op is indistinguishable from a nonexistent one (same shape, no oracle)', async () => {+ const allowed: ReadonlySet<string> = new Set(['recall', 'remember', 'entity']);+ const hiddenReal = await dispatchToolCall(stubEngine(null), 'get_page', { slug: 'x' }, {+ ...DISPATCH_OPTS, allowedOps: allowed,+ });+ const nonexistent = await dispatchToolCall(stubEngine(null), 'zz_no_such_op', {}, {+ ...DISPATCH_OPTS, allowedOps: allowed,+ });+ expect(hiddenReal.isError).toBe(true);+ expect(nonexistent.isError).toBe(true);+ const a = body(hiddenReal);+ const b = body(nonexistent);+ // Identical key sets — no extra field betrays that get_page exists.+ expect(Object.keys(a)).toEqual(Object.keys(b));+ expect(a.error).toBe('unknown_tool');+ expect(b.error).toBe('unknown_tool');+ });++ test('localOnly op over HTTP uses the same builder (suggestion never names it)', async () => {+ const out = await dispatchToolCall(stubEngine(null), 'file_list', {}, DISPATCH_OPTS);+ expect(out.isError).toBe(true);+ const envelope = body(out);+ expect(envelope.error).toBe('unknown_tool');+ const suggested = suggestedName(envelope);+ if (suggested !== null) {+ expect(EXCLUDED_FROM_SUGGESTIONS.has(suggested)).toBe(false);+ }+ });+});++// ---------------------------------------------------------------------------+// resolveStrictParamsMode — dual-plane resolution+// ---------------------------------------------------------------------------++describe('resolveStrictParamsMode (DB > file > warn)', () => {+ const engineWith = (v: unknown) =>+ ({ getConfig: async () => v } as unknown as BrainEngine);+ const throwingEngine = {+ getConfig: async () => { throw new Error('no config table'); },+ } as unknown as BrainEngine;++ // The resolver holds the last successfully read DB mode per process+ // (adversarial fix: a transient outage must not re-open warn mode) —+ // isolate each case from its neighbors.+ beforeEach(() => resetStrictParamsModeCache());++ test('a failed DB read holds the last-known-good DB mode (reject survives an outage)', async () => {+ expect(await resolveStrictParamsMode(engineWith('reject'), null)).toBe('reject');+ // DB now unreadable + file plane says warn → cached reject still wins.+ expect(await resolveStrictParamsMode(throwingEngine, { engine: 'pglite', mcp: { strict_params: 'warn' } } as never)).toBe('reject');+ // A later successful read of "unset" clears the cache → file plane decides.+ expect(await resolveStrictParamsMode(engineWith(null), { engine: 'pglite', mcp: { strict_params: 'warn' } } as never)).toBe('warn');+ expect(await resolveStrictParamsMode(throwingEngine, null)).toBe('warn');+ });++ test('DB plane wins over the file plane', async () => {+ expect(await resolveStrictParamsMode(engineWith('reject'), { engine: 'pglite', mcp: { strict_params: 'warn' } } as never)).toBe('reject');+ });++ test('file plane decides when DB is unset or unreadable', async () => {+ expect(await resolveStrictParamsMode(engineWith(null), { engine: 'pglite', mcp: { strict_params: 'reject' } } as never)).toBe('reject');+ expect(await resolveStrictParamsMode(throwingEngine, { engine: 'pglite', mcp: { strict_params: 'reject' } } as never)).toBe('reject');+ });++ test('absent / garbage on both planes → warn (grace-period default)', async () => {+ expect(await resolveStrictParamsMode(engineWith(null), null)).toBe('warn');+ expect(await resolveStrictParamsMode(engineWith('yes'), { engine: 'pglite', mcp: { strict_params: 'strict' } } as never)).toBe('warn');+ });++ test('parseStrictParamsMode admits only the two modes', () => {+ expect(parseStrictParamsMode('warn')).toBe('warn');+ expect(parseStrictParamsMode('reject')).toBe('reject');+ expect(parseStrictParamsMode('true')).toBeNull();+ expect(parseStrictParamsMode(undefined)).toBeNull();+ });+});++// ---------------------------------------------------------------------------+// query op guard — neither `query` nor `image` → typed invalid_params+// ---------------------------------------------------------------------------++describe('query op with neither `query` nor `image` (WP3 typed envelope)', () => {+ test('dispatch classifies the caller mistake as invalid_params, never internal_error', async () => {+ // Both params are optional in the schema (image is the alternative entry+ // point), so validation passes and the HANDLER must throw the typed+ // OperationError — before any search runs (the stub engine has no search+ // methods; reaching one would blow up as internal_error).+ const out = await dispatchToolCall(stubEngine('reject'), 'query', {}, DISPATCH_OPTS);+ expect(out.isError).toBe(true);+ const envelope = body(out);+ expect(envelope.error).toBe('invalid_params');+ expect(envelope.message).toContain('either `query`');+ expect(envelope.message).toContain('`image`');+ });+});