Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(mcp): in-band hidden-tool discovery (D2) and caller-safe stale-grant notice (D4)
garrytan20a26c8b7ecd
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.mdindex 1a08a04848..a717c99314 100644--- a/docs/architecture/key-files/agent-contract.md+++ b/docs/architecture/key-files/agent-contract.md@@ -9,7 +9,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-- `src/core/error-registry.ts` — `CODES`: one row per literal error code thrown in `src/` (class, summary, optional why/reasons/docs/suggestion/diagnostic-only fix/effects/actor/`legacy_error`/`renamed_from`/`exit`/`retryable`); `RegistryCode` is its key union. `NOTICE_CODES`: notice codes with their kind (mute accepts coaching/info only). New codes: add a row, then `bun run build:error-codes`. Completeness is AST-checked by `test/error-catalogue.test.ts` and `scripts/check-agent-contract.ts`.- `src/core/error-docs.ts` — renders registry rows (meaning · why · next step · who acts/consent · verify · exit · retryable) for `docs/guides/error-codes.md` (`scripts/build-error-codes.ts`, `check:error-codes` in verify) and `gbrain errors` (`src/cli/commands/errors.ts`: `<code>`, `--changed`, list; `--json`; unknown code exits 2 with a did-you-mean).- `src/core/agent-contract-log.ts` — E11 seam: `recordAgentContractEvent` appends `{ts, op|command, transport, code, has_suggestion | effects, outcome, fault}` (never params or messages) to `<GBRAIN_HOME>/agent-contract/events.jsonl`, bounded (halved past 1 MiB), synchronous, fail-open. `readAgentContractEvents` feeds doctor's `agent_contract` check (`src/commands/doctor/checks/agent-contract.ts`).-- `src/core/notice-ledger.ts` — notice dedupe/budget/mute. `NoticeLedger.tally(audience, key)` counts per-session events (dispatch counts reranker-degraded search/query calls with it and records `_meta.retrieval.rerank_degraded`). `NoticeLedger.admit(notices, {transport, principal, sessionId}, muted)`: stdio uses `processNoticeLedger()`; HTTP passes `ServeHttpContext.noticeLedger` (keyed by principal + transport-resolved session id, 10k keys, 24 h TTL). Per-call codes (`PER_CALL_NOTICE_CODES`: `empty_retrieval`, `unknown_param`, `listing_truncated`, `source_binding_narrowed`, `local_transcripts`, `held_files`, `mention_index`) and, on HTTP, `degraded`/`safety` notices are never deduped; at most 2 coaching notices per session. Mutes apply to coaching/info notices and to `MUTEABLE_ASK_CODES` (only `first_run_decisions`). Mute store `<GBRAIN_HOME>/notices/muted.json`: owner list (global) + per-client lists; `mute_notice` op (`src/core/ops/notices.ts`, write scope; HTTP per client, stdio under the `stdio` audience that dispatch reads on stdio) and `gbrain notices mute|unmute|list` (`src/cli/commands/notices.ts`, owner; `unmuteNoticeForOwner` clears the global and the `stdio` lists, `list` shows both). Tests: `test/notice-ledger.test.ts`, `test/mcp-onboarding.test.ts` (stdio mute across a fresh process, MCP mute → CLI unmute).+- `src/core/notice-ledger.ts` — notice dedupe/budget/mute. `NoticeLedger.tally(audience, key)` counts per-session events (dispatch counts reranker-degraded search/query calls with it and records `_meta.retrieval.rerank_degraded`). `NoticeLedger.admit(notices, {transport, principal, sessionId}, muted)`: stdio uses `processNoticeLedger()`; HTTP passes `ServeHttpContext.noticeLedger` (keyed by principal + transport-resolved session id, 10k keys, 24 h TTL). Per-call codes (`PER_CALL_NOTICE_CODES`: `empty_retrieval`, `unknown_param`, `listing_truncated`, `source_binding_narrowed`, `local_transcripts`, `held_files`, `mention_index`) and, on HTTP, `degraded`/`safety` notices are never deduped; at most 2 coaching notices per session. Mutes apply to coaching/info notices and to `MUTEABLE_ASK_CODES` (only `first_run_decisions`). Mute store `<GBRAIN_HOME>/notices/muted.json`: owner list (global) + per-client lists; `mute_notice` op (`src/core/ops/notices.ts`, write scope; HTTP per client, stdio under the `stdio` audience that dispatch reads on stdio) and `gbrain notices mute|unmute|list` (`src/cli/commands/notices.ts`, owner; `unmuteNoticeForOwner` clears the global and the `stdio` lists, `list` shows both). Tests: `test/notice-ledger.test.ts`, `test/mcp-onboarding.test.ts` (stdio mute across a fresh process, MCP mute → CLI unmute). D4: `claim(key)` (true once per key) and `memoize(key, compute)` back the once-per-session `grant_blocked_operations` notice; codes in `SELF_DEDUPED_NOTICE_CODES` were deduped by their producer on its own key, so `admit` applies mute only. `hidden_tool_content` is per-call.- `src/core/ops/callable.ts` — `isCallable(op, {transport, surface, scopes, publishGates, allowedOps})`: the one predicate behind stdio `stdioVisibleTools`, serve-http `listMcpTools`, the legacy bearer transport's tools/list, and `dispatchRenderContext` (which tools a fix may name). `publishGatesFromDisabled` converts the gate resolver's disabled-op set. Test: `test/callable-predicate.test.ts` (list ⇔ pre-A2 filters; list ⇔ dispatch on surface/locality).- `src/cli/cli-error.ts` — the CLI's one error writer (D1): `writeCliError`/`exitCliError` render through `renderCliError` (human `Error [code]` / `Fix:` / `Why:` / `Docs:` on stderr; under `--json` one envelope on stdout plus the human lines on stderr) and record the code for the guard's fallback document; a `legacy` shape (unknown flag's `{status, reason:'invalid_flag', message}`, `pglite_busy`'s `next_action`) leads, keeps its values and stays one line. `usageError` (`invalid_params` / `unknown_flag` / `unknown_command`, exit 2), `unknownFlagError` (did-you-mean from the command's curated help flags, else the acceptance registry), `writeFatalCliError` (the `import.meta.main` seam; keeps the `GBRAIN_DB_ACCESS` marker + remediation on human output). Test: `test/cli-error-render.test.ts`.- `src/cli/help/<command>.ts` + `src/cli/help/render.ts` + `src/cli/help/validate.ts` — D3/D4 curated CLI help. Each spec module exports `help: CliHelpSpec` (`summary`, `usage`, `flags: [{name, type: boolean|string|number|enum, values?, desc, consent?}]`, 2–4 `examples`, `end_of_options?`) and is loaded lazily through its command-table record's `help: () => import('./help/<name>.ts')` (literal, so `bun build --compile` bundles it and `gbrain --version` loads none; pinned by `test/cli-command-table.test.ts` and `scripts/check-compile-autoload.sh`). Curated today: doctor, import, serve, apply-migrations, autopilot, status, onboard; every curated flag must be in the generated acceptance registry and `--yes` is listed wherever the handler parses it. `printCuratedHelp` answers `gbrain <cmd> --help`/`-h` first in main()'s help short-circuit, engine-free (human table with type/values/consent; `--help --json` one document `{command, …spec, contract_version}`). `curatedFlagError(command, args)` (called in main() after the unknown-flag check) refuses a missing/non-numeric `number` value or an out-of-set `enum` value with `invalid_params` (exit 2) via `flagValueError`, example value drawn from the spec's examples; `--flag=value` and `--flag value`, stops at a bare `--`; `string` flags (e.g. onboard's `--max-usd off`) are not checked. `unknownFlagError` draws did-you-mean candidates from the curated flags. Tests: `test/cli-help-curated.test.ts`, `test/cli-help-curated-cli.test.ts`.@@ -20,10 +20,10 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-- `test/cli-contract.test.ts` — D5: `--help` contract for every command-table record (exit 0, non-stub, curated flags only, `--yes` shown where parsed) against the shrink-only `test/fixtures/cli-contract/help-baseline.json`, and one success + one failure row per `json`-declared record.- `src/cli/json-guard.ts` — picks the `--json` guard mode for an invocation: on only when `jsonRequested(argv)` and the command-table record declares `json: 'document' | 'ndjson'`; wires the E11 `json_document_missing` hook. The guard itself is `installStdoutPipeDelivery({ json })` in `src/core/cli-force-exit.ts`: stdout writes and console.log/info/debug go to stderr, only `writeStdoutFinal`/`writeNdjsonLine` reach fd 1, a non-zero exit with no document writes the fallback document, `spawnCliChild` pipes child stdout to stderr. Test: `test/cli-json-guard.test.ts`. A record whose subcommands differ in shape declares `jsonSubcommands` (keyed by the first positional after the command; `eval`). `writeCliError` adds `status:'error'` to the envelope under the ndjson guard; `writeCliRefusal` (cli-error.ts) keeps a site's pre-v1 stderr line and writes the envelope under `--json`. D5 (`test/cli-contract.test.ts`) has one row per declaration, `<command> <sub>` included.- `scripts/check-agent-contract.ts` — syntax-only AST scanner (≈2 s) in `bun run verify` and `guards-manifest.tsv` (fixtures `test/fixtures/guards/check-agent-contract.ts/`). Rules: suggestion-less `OperationError`, `throw new Error` in ops/mcp/handlers, hand-built `fix`/`next_action` command strings, legacy advice keys, raw interactive stdin/readline/raw-mode outside `interaction.ts`/`consent.ts`, raw "re-run with --yes" strings outside `consent.ts`, `stdio: 'inherit'` outside `spawnCliChild`, marker literals outside `agent-output.ts`/`agent-markers.ts`, `verify.argv` naming a non-read-only command (read_only command-table records + a static read-only list), plus unregistered codes and code naming (never baselined). Two more never-baselined rules keep every refusal's next step site-specific: `defaulted-suggestion` (a function that builds an error through `opError`, `new OperationError`, `usageError`, `invalidParam` or `hostOnlyError` from a `*suggestion`/`*hint` parameter with a default, an optional marker or a `??` fallback) and `generic-suggestion` (a suggestion whose whole text is a denylisted phrase such as "see --help", "check your input" or "try again", at a constructor or at a call site of a file-local funnel). `funnelSites(files?)` lists every funnel call site (`invalid`, `fail`, `usage`, `deny`, …) with its literal suggestion texts, resolving file-level string constants; `test/helpers/agent-envelope.ts` (`expectFunnelSuggestions`, `envelopeFor`, `caught`) drives the per-funnel table tests in each module's owner test. Per-rule shrink-only baselines in `scripts/agent-contract-baselines/<rule>.tsv`; `--update` lowers them and refuses growth.-- `src/core/interop-notices.ts` — Lane F notice producers (pure; callers emit). `DEGRADED_STAGE_GUIDANCE` (closed, typed exhaustive over recall-affecting stages + the verbs' markers) → one `degraded_recall` notice (kind degraded: names the stages, says a thin result is not proof of absence; fix = the embeddings enablement or a doctor diagnostic; a `rerank_failed` stage names its reason, the `fused_order` fallback and the session's reranker-degraded call count, and when no other stage needs a fix its fix follows the reason: `timeout`/`rate_limited` repeat the same call after 5/20 s (`actor: provider`, `next: wait`), `auth` is the user's key (credentials), the rest run doctor verified by `reranker_health` (`test/rerank-degraded-notice.serial.test.ts`); none on a brain keyless by choice, whose why says no query text was sent and that `gbrain doctor --json` names the enable command). `embeddingOptedOutFor` reads the opt-out markers (search/query degraded reason `embedding_disabled`, recall `keyword_only_embedding_disabled` in `search_degraded` or `facts_degraded.reason`, think `QUESTION_EMBED_SKIPPED_EMBEDDING_DISABLED`); `factEmbeddingDisabled` (src/core/embedding-disabled.ts) gates every query and fact embed. `sourceBindingNarrowedNotice` (per-call info: a GBRAIN_SOURCE/.gbrain-source bound stdio read that came back empty while other sources are readable; fix = the explicit `source_id` read). `recallStagesFor` maps recall's `search_degraded` and `facts_degraded.reason` (question ranking) to stages. `recallInteropNotices` is dispatch's one producer call. `chatKeyFix` (credentials + paid, both providers, free fallback, never a key on a command line), `keylessThinkNotice`, `thinkNotSavedNotice`, `degradedDedupNotice`, `writeCliNotices` (terminal lines / `[AGENT]` block for non-interactive callers). Test: `test/mcp-notice-channels.test.ts`.+- `src/core/interop-notices.ts` — Lane F notice producers (pure; callers emit). `DEGRADED_STAGE_GUIDANCE` (closed, typed exhaustive over recall-affecting stages + the verbs' markers) → one `degraded_recall` notice (kind degraded: names the stages, says a thin result is not proof of absence; fix = the embeddings enablement or a doctor diagnostic; a `rerank_failed` stage names its reason, the `fused_order` fallback and the session's reranker-degraded call count, and when no other stage needs a fix its fix follows the reason: `timeout`/`rate_limited` repeat the same call after 5/20 s (`actor: provider`, `next: wait`), `auth` is the user's key (credentials), the rest run doctor verified by `reranker_health` (`test/rerank-degraded-notice.serial.test.ts`); none on a brain keyless by choice, whose why says no query text was sent and that `gbrain doctor --json` names the enable command). `embeddingOptedOutFor` reads the opt-out markers (search/query degraded reason `embedding_disabled`, recall `keyword_only_embedding_disabled` in `search_degraded` or `facts_degraded.reason`, think `QUESTION_EMBED_SKIPPED_EMBEDDING_DISABLED`); `factEmbeddingDisabled` (src/core/embedding-disabled.ts) gates every query and fact embed. `sourceBindingNarrowedNotice` (per-call info: a GBRAIN_SOURCE/.gbrain-source bound stdio read that came back empty while other sources are readable; fix = the explicit `source_id` read). `recallStagesFor` maps recall's `search_degraded` and `facts_degraded.reason` (question ranking) to stages. `recallInteropNotices` is dispatch's one producer call. `chatKeyFix` (credentials + paid, both providers, free fallback, never a key on a command line), `keylessThinkNotice`, `thinkNotSavedNotice`, `degradedDedupNotice`, `writeCliNotices` (terminal lines / `[AGENT]` block for non-interactive callers). Test: `test/mcp-notice-channels.test.ts`. D2: `hiddenTakesNotice(hidden, route, fix)` → `hidden_tool_content` (info, per-call): a get_page/search/query result left out takes (counts and the result's own slugs, never take text); the fix is the hidden-tool route's next step.- `src/mcp/status-mode.ts` + `src/commands/serve-status.ts` + `src/commands/serve-http-status.ts` + `src/core/serve-http-status-marker.ts` — F4 status-only serve, stdio and `--http`. cli.ts hands over a host-brain `serve` (not `--fail-fast`/`GBRAIN_SERVE_FAIL_FAST=1`) with no config, an unreadable config, a missing or repair-failed brain, or a PGLite lock held by a live holder; `runStatusModeServe` is the one entry point for both transports and logs `serve_status_mode_enter` / `serve_status_mode_recovered` (`reason`, `transport`, `elapsed_ms`) as one-line JSON on stderr. `probeStatus` reads config + `peekLock` only; `reprobe(state, connect)` is the one re-probe (no lock attempt while blocked, `resetReadinessMemo()` before the throw-only connect from `src/core/engine-connect.ts`); a check that must run on every re-probe hooks the `probeAgain` wrapper in `runStatusModeServe`. stdio: a gated lazy engine (`createDegradedEngine` with the configured `kind`, reconnect `statusReconnect`, ≤1 attempt / 5 s inside tool calls) marked with `StatusModeState`; `statusPayload` → `{status, reason, why (lock owner PID/transport, brain path, config path), fix, user_message, decisions, share_http_plan}`. `--http`: `runHttpStatusServe` binds one `node:http` listener with a mutable handler (`/health` 503 + `Retry-After: 5` + `instance`; `/mcp` stateless SDK server with only `gbrain_status`; every other route a 503 `serve_status_only` envelope), each response built from the allowlist in `httpStatusPayload`/`httpStatusEnvelope` with `reason` collapsed to `unavailable`; a single-flight chained 5 s tick runs the re-probe, and on a connect `runServe(..., { adoptServer })` builds the full app and swaps the handler on the same listener; a failed build disconnects the engine and stays status-only (`brain_unopenable`); SIGINT/SIGTERM during a recovery waits for it, then closes once. The marker `GBRAIN_HOME/serve-http-status-<port>.json` `{pid, instance_nonce, brain_id, bind, port, reason, since}` is removed only by its own instance; live = PID alive and written after the last boot (readiness), plus `/health` 503 with the nonce within 500 ms (`verifiedStatusMarkers`, doctor, which deletes dead markers). `statusFix(state, transport)` words the fix for how the server re-checks. A recovered HTTP server answers authenticated `gbrain_status` (read scope, never listed) with `status: recovered`. Tests: `test/serve-status-mode.serial.test.ts` (stdio recover → recall; shared `serve --http`; no brain → init; `--fail-fast`; stdio transition lines; Postgres `--http` keeps the degraded path), `test/serve-http-status-mode.serial.test.ts` (HTTP journey, doctor, thin client, recovery with re-auth, `serve_port_in_use`, no-config recovery, stale marker, single-flight tick, failed build, shutdown during recovery, two-port markers).- `src/mcp/initialize-context.ts` — per-initialize inputs for the generated instructions (`httpInstructionTools`: the tools/list filters with publish gates read on initialize; `instructionReadiness`: config plane + probed tier within 250 ms, HTTP view redacted) and `stdioCapabilityReadiness` (F2). Test: `test/mcp-capabilities-readiness.test.ts`.-- `src/mcp/hidden-tool-hint.ts` + `src/core/ops/cli-equivalent.ts` — F6: on the owner's stdio pipe a real tool outside the surface/read-only access gets `unknown_tool` naming itself and its CLI equivalent (`cliEquivalent`: `cliOnly` argv, curated overrides, `cliHints.name`, else `gbrain call`). Where `request_tools` is callable and session widening is on, the fix is `request_tools {surface:'full'}` (`next: run`, argv kept); otherwise the CLI equivalent with actor `user` and a `user_message`; `why` names the lasting route (`GBRAIN_SURFACE=full` in the harness's per-server env, or a `--surface full` re-registration) and that an inherited `GBRAIN_SURFACE` overrides a pinned `--surface`. Read-only access never offers a widen. HTTP stays opaque. `scripts/generate-plugin-tree.ts` appends the same map as a per-skill note to generated starter-gap skills. Test: `test/hidden-tool-hint.test.ts`.+- `src/mcp/hidden-tool-hint.ts` + `src/core/ops/cli-equivalent.ts` — F6: on the owner's stdio pipe a real tool outside the surface/read-only access gets `unknown_tool` naming itself and its CLI equivalent (`cliEquivalent`: `cliOnly` argv, curated overrides, `cliHints.name`, else `gbrain call`). Where `request_tools` is callable and session widening is on, the fix is `request_tools {surface:'full'}` (`next: run`, argv kept); otherwise the CLI equivalent with actor `user` and a `user_message`; `why` names the lasting route (`GBRAIN_SURFACE=full` in the harness's per-server env, or a `--surface full` re-registration) and that an inherited `GBRAIN_SURFACE` overrides a pinned `--surface`. Read-only access never offers a widen. HTTP stays opaque. `scripts/generate-plugin-tree.ts` appends the same map as a per-skill note to generated starter-gap skills. Test: `test/hidden-tool-hint.test.ts`. D2: `hiddenToolRoute(op, ToolConnection)` is the one decision for every transport (`callable` | `widen {surface}` | `host {read_only|surface|grant}`): a widen is offered only when the widened connection could call the tool (read-only access, `GBRAIN_MCP_FORCE_SURFACE`, the grant's snapshot/scopes and an operator pin all hold); dispatch builds the connection with `toolConnection(opts)`. `hiddenToolNext` turns a route into the D2 fix (the call itself; request_tools; on HTTP the D4 grant repair; on stdio the CLI equivalent with the call's arguments as flags).- `Operation.cliOnly` + `cliOnlyRefusal` (`src/core/ops/callable.ts`) — F5: owner-only ops (they refuse every MCP caller) are never listed on MCP; a call gets `trusted_local_only` (error `permission_denied`) with the exact CLI command.- `src/core/behavior-change-notice.ts` — the one-time `behavior_changes` safety notice: a live `chat_fallback_chain` (local view: entries, providers, refusal behavior, removal fix; HTTP view: only that a chain is configured), managed-brain lint repairs (`cycle.lint_fix`), smaller transcript parts re-embedded once (`TRANSCRIPT_REINGEST_MULTIPLIER`), a mention-linker rescan (v0.60.68.0), and fix wave 9's six upgrade-visible changes (v0.60.74.0). `BEHAVIOR_CHANGES` is the one table of disclosed changes, each with the release that introduced it (`FENCE_REPAIR_MEASURED` is the automatic fence repair row's measurement sentence, replaced by the Tier 3 eval's measured rates); `BEHAVIOR_NOTICE_SINCE` is the newest row's release (never `VERSION`), so the notice id `behavior_changes@<since>` moves only when a release appends rows. Content: the rows newer than the last notice release this brain × channel (× HTTP client) was shown, or than its baseline when never shown. Baseline: the brain's baseline under `GBRAIN_HOME/notices/behavior-changes/<brainKey>.baseline` (`gbrain init` stamps a database it creates; otherwise the first look records `0` when `upgrade-state.json` shows an upgrade from an older release or the oldest `sources.created_at` is past `FRESH_BRAIN_GRACE_MS`). Markers: CLI and stdio claim a `wx` file per notice × brain × channel (an unwritable home still delivers, once per process); the newest marker names the last release shown; HTTP keeps up to `HTTP_SHOWN_CAP` client ids, each with the release it was shown, in the `notices.behavior_changes.http` config row (a row from an older build counts its clients as shown its id's release) (no migration; a failed write still delivers). Delivery: `completeEngineStartup` in `src/cli.ts` (stderr; not `serve` or `doctor`), and `sessionSafetyNotices` in `src/mcp/dispatch.ts` on success and failure results. `gbrain doctor --only behavior_changes` reads every row newer than the baseline without writing. Pinned by `test/behavior-change-notice.test.ts` (both engines, plus upgrade steps in processes pinned to a `VERSION`) and `test/behavior-change-notice-cli.test.ts`.- `src/core/post-upgrade-notice.ts` — F7 `post_upgrade` safety notice (contract_version + behavior-table URL): `gbrain post-upgrade` writes it once; the first stdio MCP session per upgraded version gets it (persisted under GBRAIN_HOME). `src/cli/op-notices.ts` renders op notices on the local CLI (`--json` objects gain `notices`; human output on stderr).diff --git a/docs/architecture/key-files/google-and-loops.md b/docs/architecture/key-files/google-and-loops.mdindex ca1ddd8448..2a4843d848 100644--- a/docs/architecture/key-files/google-and-loops.md+++ b/docs/architecture/key-files/google-and-loops.md@@ -43,7 +43,7 @@ Historical Gmail repair selects explicit nested MIME metadata fields, excluding- `src/core/harness/credentials.ts` + `delivery.ts` + `install.ts` — Private credential handoff and host delivery journal, ownership-preserving native configuration and isolated thin launchers. A committed active client and matching current secret are prerequisites for recovery. Machine handoffs preserve optional POST/Basic authentication methods. Native setup is a distinct nested-client artifact; metadata reads never access journals or SDK client objects containing hashes. Configuration removal and server revocation are separate actions.- `src/core/harness/oauth-setup.ts` + `client-setup.ts` — explicit client metadata projection, flow selection, native OAuth setup/private-file validation, and live-row-locked secret delivery recovery. Public PKCE needs no journal; confidential exports validate the retained secret against current registration, and machine exports discard cached tokens. Unknown/mixed flows refuse until an explicit supported flow is selected.-- `src/core/harness/capabilities.ts` + `src/mcp/capabilities.ts` — Shared effective-grant orientation for OAuth whoami and authenticated `gbrain://capabilities`. A stored client token lifetime outside 60 to 7,776,000 seconds (`AuthInfo.tokenTtlSeconds`) reports `token_ttl_invalid`, and the delegation repair template then includes a `--token-ttl <APPROVED_TTL_SECONDS>` choice, since every grant write validates the merged lifetime. The resource preserves the exact seven-tool surface; source, operation, scope, fence and server-gate restrictions remain enforced at dispatch. `grant_diagnosis` (shared with doctor `grant_new_ops_available` through `grantOperationGaps`, `grantAge` and `grantRescopeArgvs`) counts the operations the grant's scopes allow but its operation snapshot, its client pin or the server ceiling block, names none of them, keeps inferred grant age apart (`intent_unknown` without catalog provenance), and builds host commands only from the verifier's principal. No worker probe or per-tool database query during discovery (one audit read for provenance when a snapshot excludes operations). Shared administration guidance explains separate owner authority, links the MCP admin runbook, and exposes an admin URL only for a configured credential-free HTTP MCP endpoint. Stdio never infers an HTTP address.+- `src/core/harness/capabilities.ts` + `src/mcp/capabilities.ts` — Shared effective-grant orientation for OAuth whoami and authenticated `gbrain://capabilities`. A stored client token lifetime outside 60 to 7,776,000 seconds (`AuthInfo.tokenTtlSeconds`) reports `token_ttl_invalid`, and the delegation repair template then includes a `--token-ttl <APPROVED_TTL_SECONDS>` choice, since every grant write validates the merged lifetime. The resource preserves the exact seven-tool surface; source, operation, scope, fence and server-gate restrictions remain enforced at dispatch. `grant_diagnosis` (shared with doctor `grant_new_ops_available` through `grantOperationGaps`, `grantAge` and `grantRescopeArgvs`) counts the operations the grant's scopes allow but its operation snapshot, its client pin or the server ceiling block, names none of them, keeps inferred grant age apart (`intent_unknown` without catalog provenance), and builds host commands only from the verifier's principal. No worker probe or per-tool database query during discovery (one audit read for provenance when a snapshot excludes operations). Shared administration guidance explains separate owner authority, links the MCP admin runbook, and exposes an admin URL only for a configured credential-free HTTP MCP endpoint. Stdio never infers an HTTP address. D4 in band: `grantBlockedNotice(diagnosis, {refused})` builds the `grant_blocked_operations` notice (blocker counts, grant age apart, missing scope only when refused) and `grantRepairAction` the host-owned repair (preview argv, `then` apply, verify = doctor `grant_new_ops_available` or `whoami`; server ceiling alone → the read-only doctor check). Dispatch (`grantBlockedNotices`) delivers it once per (principal, session) or, stateless, per (principal, grant revision).- `src/commands/mcp.ts` + `mcp-provision.ts` + `harness-connect.ts` — Host-side grant/preview/CAS and recoverable private delivery, followed by installation inside the intended harness. Codex, Claude Code and opencode installs (`src/core/harness/install.ts`) store the bearer token inline in the harness config; `inlineTokenReceipt` adds `token_storage`, `config_path`, `renew_command`, `if_exposed` (invalidate-tokens preview/apply, renew, reload; `renew_command` carries `--fresh-token` for renewable handoffs so it always exchanges a new token) and a `token_warning` when a Git working tree would commit the file, and `harness-connect.ts` repeats them on stderr in human mode without printing the token (#5775; `test/harness-token-receipt.test.ts`). Running PGLite hosts are administered through their authenticated API, never by opening a second database process. CLI status uses the delivery-aware exit verdict. `mcp-admin.ts` and `mcp-admin-http.ts` provide engine-free owner commands with explicit-file/env credential precedence, in-memory sessions, private native exports, versioned lifecycle previews, and safe stage/outcome/remedy receipts. Unknown mutation outcomes require inspection instead of automatic repetition. `runMcp` also dispatches `gbrain mcp expose` to `runMcpExpose` (dynamic import of `./mcp-expose.ts`; HELP carries the expose lines so the flag registry harvests them) and sets the CLI exit verdict from its returned code. `mcpNeedsEngine(args)` is true only for `grant` without an owner credential (`--admin-token-file` or `GBRAIN_ADMIN_BOOTSTRAP_TOKEN`) and outside help; `admin`, `expose`, and `verify` never open the database.- `src/commands/mcp-expose.ts` — `gbrain mcp expose [--port N] [--funnel] [--surface] [--enable-dcr] [--no-tailscale] [--no-service] [--no-install] [--force] [--dry-run] [--yes] [--json]` / `--status` / `--remove`: publishes `gbrain serve --http` on the user's Tailscale tailnet (Serve by default, Funnel only with the explicit flag) and keeps it running as a user service. `runMcpExpose(args, deps?)` returns the exit code (0 done, 1 failed, 2 needs `--yes`, the prompt was declined, or a step is pending — a tailnet feature to enable, Tailscale login, tailnet certificate). Arg validation via `validateHarnessArguments` (exclusive pairs `--status`/`--remove`, `--funnel`/`--no-tailscale`, `--dry-run`/`--status`); the help text names every flag and the `verify.local` / `verify.tailnet` checks. Ordered named checks — `plan` (platform, execution environment, engine kind from `loadConfig()`; thin clients are refused with "run on the brain host"; `engine === 'unknown'` — no config or an unreadable one — without `--no-service` is refused as `no_brain_config` / exit 1 with next action `gbrain init` BEFORE consent, because a service around a missing brain only crash-loops, while `--dry-run` still prints the plan with the refusal marked and exits 0; on a PGLite engine `deps.pgliteHolder` (default `probeLivePgliteHolder` from `src/core/bootstrap/uninstall.ts`, a read-only lock-file probe) is consulted with `cfg.database_path`, and a live holder that is not our own managed service — receipt present with `service.state` `running`/`loaded` — adds a `Lock` plan line plus a `pglite_lock` check with status `warn` (never a stop); `--no-tailscale` over an existing receipt whose `tailscale.dns_name` is set (a live Serve/Funnel mapping) is refused BEFORE consent as `tailscale_receipt_present` / exit 1 with next actions `gbrain mcp expose --remove --yes` and the re-run without the flag — `--dry-run` marks it `WOULD BE REFUSED`; then probes `127.0.0.1:<port>` with `probeOccupied(d, port, url)` — occupied when EITHER the injectable `deps.tcpProbe` (default `defaultTcpProbe`, one `node:net` connect, socket destroyed on every outcome; true on connect, false on refusal / timeout / throw) accepts a TCP connect OR the `/health` fetch RESOLVES with ANY status (2xx, 404, 500), so a non-HTTP listener counts too; only both rejecting is free — and refuses a foreign listener with no receipt claiming that port as `foreign_listener` BEFORE anything is published unless `--no-service`; the message names the interrupted-run escape hatch `gbrain mcp expose --remove --yes`; `probeHealth` (`res.ok`) stays the bar for `verify.local` / `verify.tailnet` / `--status`), `consent` (shared `confirmOrFinish` for publish and `--remove`: one stderr y/N prompt on a TTY; declining is `pending` / exit 2 / `declined` with "Nothing changed. Re-run with --yes to confirm."; non-interactive without `--yes` prints the plan and exits 2 / `confirmation_required`; every re-run hint is rendered by `rerunCommand(opts)` — the user's publish flags + `--yes`), `tailscale.binary` (install plan: brew cask on macOS — then `open -a Tailscale` and a bounded poll of `tailscale status --json`, up to 20 attempts 1s apart, breaking as soon as the app's daemon answers and otherwise falling through to the login step's daemon-not-running handling — official installer on Linux, `--no-install` → exit 1), `tailscale.login` (Linux `sudo tailscale set --operator=<user>` non-fatal then flagless `sudo tailscale up` — `sudo` is put in front of the binary ONLY when `isSystemTailscaleBinary(binary)` holds (one of `TAILSCALE_BINARY_CANDIDATES`, literally or via `realpathSync`); a user-writable `tailscale` found on PATH stops the step as `pending` / exit 2 / `tailscale_login_manual` with the message "tailscale at <path> is not a system install, so gbrain will not run it with sudo. If you trust that binary, sign in yourself (this runs it as root): `sudo <path> set --operator=$USER && sudo <path> up`, then re-run: <rerun>" — the command is `tailscaleManualLoginCommand(binary)`, naming the discovered path shell-quoted, because a binary outside sudo's `secure_path` is exactly this case — and never spawns `sudo`; macOS `tailscale up`; bounded wait via `GBRAIN_TAILSCALE_LOGIN_TIMEOUT_MS`), `tailscale.identity` (MagicDNS name → `public_url`; pre-checks so `tailscale serve`/`funnel` — which wait interactively instead of failing when a feature is off — are never started blind: empty `CertDomains` → `pending` / exit 2 / `tailscale_https_not_enabled` with `TAILSCALE_ADMIN_DNS_URL`; `--funnel` with `funnelCapable === false` → `tailscale_funnel_not_enabled` with the ACL admin + Funnel KB URLs; `funnelCapable === null` proceeds), `tailscale.publish` (reads the serve config through `readServeView`, which FAILS CLOSED — it returns `{ view: ServeStatusView | null, stderr, status }` with `view: null` when `tailscale serve status --json` exits non-zero / is killed (`status: null`) or when stdout is not a JSON object per `parseServeStatusStrict`; an empty document / `{}` / `null` from exit 0 is the legitimately empty view — a null view before `--bg` is described once by `describeServeReadFailure` (`{ kind, detail, fix }` from one `classifyTailscaleError` call), records `tailscale.publish` = fail and returns exit 1 with reason `tailscale_<kind>` without publishing; a null view after `--bg` is `tailscale_publish_unconfirmed` naming the read failure; refuses a `/` handler proxying a different port, a foreground session or a raw TCP forward without `--force` as `foreign_serve_config` — `next_actions` says `tailscale serve status`, only `message` explains `--force`; `PUBLISH_TIMEOUT_MS` (60s) bounds `--bg`, `SERVE_OFF_TIMEOUT_MS` (30s) every `--https=443 --set-path=/ off` and `STATUS_READ_TIMEOUT_MS` (15s) both status reads; a `status: null` timeout is `unknown` with a run-by-hand hint; stderr classified by `classifyTailscaleError` as the second line of defense; switching our own handler's shape pre-clears ONLY in the funnel → tailnet direction (`funnel --https=443 --set-path=/ off` before `serve --bg`, because `serve --bg` over a Funnel mount keeps `AllowFunnel`; tailnet → funnel is one atomic `funnel --bg`), and when that pre-off was followed by a failed publish (non-zero, timeout, or unconfirmed) `restorePrevious` best-effort re-publishes the previous shape with `tailscaleServeArgv(port, { funnel: true })`, re-reads the view, and appends to the `tailscale.publish` detail whether "the previous funnel handler was restored" or "could NOT be restored"; the existing receipt is never touched on those paths), `admin_token` (ensure the 0600 token file, never printed), `service` (launchd / systemd user unit / `manual` fallback with the exact foreground and `nohup` commands; a `--no-service` re-run carries the existing receipt's service block unchanged and does not rewrite the wrapper; `service_install_failed` still writes the receipt with `service.state: 'stopped'` before exit 1 so `--status`/`--remove` can clean up the published handler; the receipt is ALSO written right after a successful service step — service state as probed at that moment — before verify runs, so a kill during verify always leaves `--status`/`--remove` something to find), `verify.local` (wall-clock `/health` polling up to 20s, timeout → `warn`, exit 2, `verify.tailnet` skipped), `verify.tailnet` (up to 30s, `pending` is exit 2 — EXCEPT when the last probe's rejection was a name-resolution failure per `mcp-expose-probe.ts`: Bun's `fetch` rejects an unresolvable host and a refused connection with the same "Unable to connect. Is the computer able to access the url?" / `ConnectionRefused`, so after a rejected fetch the URL's hostname (never an IP literal or `localhost`) is handed to `deps.lookup` — default `dns.promises.lookup`, bounded by the probe timeout — and a rejection with code `ENOTFOUND` / `EAI_AGAIN` / `EAI_NONAME` / `EAI_NODATA` / `DNS_ENOTFOUND` (or a message naming one) is the verdict, the fetch-message regex staying a secondary hint; a name that resolves but does not answer stays `pending`: then the check is `warn` with `unresolvedDetail(dnsName)` — "this host cannot resolve <name> (MagicDNS may be off here: `tailscale set --accept-dns=true`); devices that do resolve it may already reach the server" — and the run exits 0, since this host's resolver says nothing about the server), `receipt` (rewrites the early receipt with the settled state — the supervisor is re-probed once verify.local ran — keeping `created_at`). The admin-token, service and verify steps run inside one try: a THROW there after this run's `--bg` succeeded but BEFORE the early receipt is rolled back by `rollbackAfterThrow(d, s, opts, published, error, receiptWritten)` — the fresh handler is turned off again with `tailscaleServeOffArgv({ funnel })` only when no `/` handler for our port existed before the run (a pre-existing one is left in place), a `rollback` check records what happened — "turned off again" is claimed only when a re-read of the serve view after an exit-0 `off` no longer shows our port; an exit-0 `off` whose re-read still shows it is a `warn` "NOT turned off (… the handler is still present)", an unreadable re-read is a `warn` "state unknown", and an `off` that exits non-zero or throws is a `warn` whose message says the handler was NOT turned off — no receipt is written, and the error is re-thrown so the outer catch reports `mcp_expose_failed` with a message naming the handler state; once the early receipt is on disk (`receiptWritten`, checked first) a throw tears nothing down (`rollback` = skipped pointing at `--status` / `--remove --yes`), because the receipt makes everything findable (the non-throwing `service_install_failed` path keeps its partial receipt). Success banner and `next_actions` gate the local-agent line on the engine: Postgres → `gbrain bootstrap harness --yes --port N`; PGLite → pre-mint (`gbrain auth create … --scopes read,write` before the service runs) + `--token`, or the scoped `mcp grant … --url http://127.0.0.1:N/mcp --admin-token-file …` + `gbrain connect … --install` path, and "host-side commands fail with `live_serve` — administer through the running server". `--json` emits one stdout document `{ status, receipt, checks[], next_actions, reason?, message? }` with prose on stderr; every `inherit` subprocess redirects its stdout to stderr under `--json`. `--status` and `--remove` read the receipt through `readExposeReceipt`'s shape guard (a partial receipt is `not_exposed` / "nothing to remove", never a crash) and execute the tailscale binary from `resolveReceiptBinary`: the receipt's recorded path is honored only when it still exists AND is either what `findTailscaleBinary` finds now or one of `TAILSCALE_BINARY_CANDIDATES`, otherwise discovery wins — a path in a receipt is data, never a licence to run it. the probes — `probeHealth` (`res.ok`), `probeOccupied` (any response, or an accepted TCP connect), the bounded never-throwing `tryFetch` → `FetchOutcome { res, unresolved }`, `pollHealth` → `{ ok, unresolved }` with the LAST probe's resolution verdict, `unresolvedDetail`, `defaultTcpProbe`, `defaultLookup` — live in `src/commands/mcp-expose-probe.ts` and take the narrow `ProbeDeps` slice of the resolved deps (`fetch`, `tcpProbe`, `lookup`, `now`, `sleep`, `healthIntervalMs`); `defaultTcpProbe` is re-exported here so its import site never moved; `isLiveService(state)` is the one definition of "the supervisor reports our service" (`running` or `loaded`) used by the lock-holder exemption, the service check, `--status` and both `--remove` paths; `serviceLabel` builds on `serviceKindLabel` (`launchd <label>` / `systemd (user) <unit>`). `--status` runs its four independent probes (serve config, supervisor state, local and tailnet `/health`) concurrently with `Promise.all` and still reports the checks in the fixed order `receipt`, `tailscale.publish`, `service`, `verify.local`, `verify.tailnet`; an unreadable serve config (null view) is a FAILED `tailscale.publish` check / exit 1, never "handler present"; a tailnet `/health` rejected for name resolution is `verify.tailnet` = warn (same `unresolvedDetail`), not `pending`, and does not by itself make the exit non-zero. `--status` with NO receipt is `runStatusWithoutReceipt`: it runs the read-only `probeLeftovers(d, opts.port)` (`--port` is honored) and, when the wrapper, the plist / unit or a live service, or a `/` handler on `:443` proxying the port is found, emits one `warn` check per artifact (`receipt`, `service`, `tailscale.publish`, `files`), pushes `recoveryCommand(port, force)` (`gbrain mcp expose --remove --yes`, `--force` only when a handler stands alone with no wrapper / service corroborating it, `--port N` when non-default) to `next_actions`, and finishes `error` / exit 1 / `leftovers_without_receipt` (also under `--json`); an unreadable serve status alone is a caveat warn, not a leftover; nothing found keeps the `not_exposed` answer (exit 0, `--json` exit 2). `--remove` (consent; decline is `pending` / exit 2) probes the supervisor and removes a service that exists even when the receipt says skipped — `recordServiceUninstall` prints the uninstall notes, and when `launchdBootoutFailed(result)` (a `launchctl bootout failed: …` / `unload failed: …` note, i.e. a non-"not loaded" failure) the `service` check is `warn` pointing at `launchctl print gui/$(id -u)/com.gbrain.serve` and "the launchd job (bootout failed)" is added to "Left in place"; it returns the one-line service summary quoted below — then clears only gbrain's own serve/funnel handler through `turnOffOurHandler` (Funnel off first; every `off` is `--https=443 --set-path=/ off`, scoped to our `/` mount; the serve config is re-read only after an `off` command ran, otherwise the view already read is reused; a failed re-read is reported as `unknown` — a warn, never "gone"; a foreign port on `:443` gets "nothing to turn off"). `--remove` never reports success while our handler survives: when `turnOffOurHandler` returns `remaining` as a handler (`tailscale.publish` = fail) or `'unknown'` (= warn), `finishHandlerNotRemoved` keeps the receipt AND the wrapper (mirroring the unreadable-status branch), records `receipt` = skipped "kept: …", pushes `tailscale serve status` + the re-run to `next_actions`, says which service outcome already happened, and exits 1 with reason `handler_not_removed`; `--remove` never runs `tailscale serve reset`, never uninstalls or logs out, keeps the admin token unless `--force` (deleted through the same `unlinkQuietly` as the wrapper and receipt), and unlinks the wrapper / receipt / token ONLY when the path's directory is the serve directory — a receipt path elsewhere is left untouched and named in "Left in place" (also in the plan). The receipt's recorded `plist_path` / `unit_path` are data, never a licence: `uninstallServeService` is always handed the computed `d.plistPath` / `d.unitPath` (home + the fixed label / unit name), and a recorded path that differs is not touched and is named in "Left in place" as "recorded in the receipt but not the expected location". A null serve view during `--remove` fails closed: `tailscale.publish` = fail "could not read tailscale serve status; handler left as is", reason `tailscale_serve_status_unreadable`, exit 1, and the receipt AND wrapper are kept so a re-run finishes the job. With NO receipt, `runRemoveWithoutReceipt` recovers from what is on disk through the same `probeLeftovers` `--status` uses (`wrapperPath(serveDir)`, the launchd plist / systemd unit or a `running`/`loaded` service, a `/` handler on `:443` proxying `opts.port` — `--port` may accompany `--remove`, default 3131); inside it the supervisor chain (`probeServiceTarget` → `serveServiceState`) and the `readServeView` read run concurrently under `Promise.all` (the binary is resolved synchronously first) and the plan / checks are emitted in the fixed order afterwards; the re-run hints come from `recoveryCommand`. The handler is turned off only with corroborating gbrain evidence — the wrapper present, our unit/plist present, or the supervisor reporting our service live — or with `--force`, because another tool may proxy `:443` to the same port: a handler standing alone is reported (`tailscale.publish` = warn naming the proxy target and `--force`, next action `gbrain mcp expose --remove --yes --force`) and left in place on the "not exposed — nothing to remove" exit-0 path; with `--force` the plan line says so. Otherwise it prints a "Recovering without a receipt" plan (`receipt` check = warn), takes consent as usual, removes exactly those artifacts (service via the supervisor — the same `recordServiceUninstall` bootout-failure warn applies — wrapper, the handler — funnel off first when `AllowFunnel` lists the host), leaves the admin token file, and finishes `removed` with reason `recovered_without_receipt`; a handler that survives the `off` is `handler_not_removed` / exit 1 here too, with the wrapper deliberately KEPT as the corroboration the re-run needs (`files` = skipped "kept: the wrapper"; the re-run hint carries `--force` when no wrapper is left); an unreadable serve status on this path (gbrain evidence present, `serveUnreadable` set) fails closed exactly like the receipt path — the service, when found, is still uninstalled, the plan says the handler cannot be checked and the wrapper is kept, `tailscale.publish` = fail "…; handler state unknown", `files` = skipped "kept: the wrapper" (or "nothing (no wrapper was found)"), `next_actions` = `tailscale serve status --json` + the recovery command (`--force` when no wrapper is left), exit 1 with reason `tailscale_serve_status_unreadable` and message "could not read tailscale serve status; handler state unknown"; when nothing of ours is found the answer stays "not exposed — nothing to remove", exit 0 (an unreadable serve status is then only the caveat warn — there is nothing to keep and a handler alone would not be touched anyway). Every filesystem/exec effect goes through injectable deps so tests run against a fake runner in a tmpdir. Success guidance separates owner login, native OAuth registration, and machine grant/install. It uses the expose-managed owner file only when installing or keeping that service; publication with `--no-service` and no managed service instead requires the existing server's independently configured owner credential. Publishing receipts and health checks do not certify client authorization or native activation.diff --git a/docs/guides/hosted-harness-access.md b/docs/guides/hosted-harness-access.mdindex 6cf1c97dda..233e265122 100644--- a/docs/guides/hosted-harness-access.md+++ b/docs/guides/hosted-harness-access.md@@ -119,7 +119,7 @@ are one principal. See [shared brain skills](shared-brain-skills.md).A **profile grants authority**. A **surface selects visible tools**. Full surface does not bypass a grant, and `admin` does not imply delegation, the named shared-skill scopes, or owner dashboard/client-management authority. Starter includes authorized skill discovery and membership; the exact seven-tool `verbs` surface is memory-only. Thin CLI adapters use the full surface while retaining their source, operation, and write restrictions. Direct local CLI access is trusted access to the local computer; OAuth profiles do not confine a local shell.-Clients granted a memory profile before the full-surface default keep their stored `starter` surface; no migration or repair widens it, and only an explicit `--profile` application regrants it. New grants snapshot operation names and source access. A later server upgrade does not silently give a snapshot-bound client new operations. The connection's own `whoami` reports `grant_diagnosis`: which blocker applies (scope, operation snapshot, client pin or server ceiling) and how many operations it hides, without naming them; `gbrain doctor` on the host reports the same as `grant_new_ops_available` with the commands. A grant written before snapshots recorded their operation catalog says "original intent unknown" rather than claiming it predates the operations. Explicitly regrant to include them: `gbrain auth rescope --client <client_id> --operations <op,...> --surface full --dry-run` (then without `--dry-run`; `--surface full` only when the stored surface also blocks) for OAuth clients, or `gbrain auth rescope-token <name> --refresh-operations` (preview) then `--add <op,...>` for legacy tokens ([grants that cannot reach new operations](../mcp/ADMIN.md#grants-that-cannot-reach-new-operations)). `gbrain auth rescope --client <client_id> --operations all` (alias: `gbrain auth rescope-client <client_id> --allowed-operations all`) stores no snapshot and clears the profile instead, so the scopes and the surface alone decide, including operations later upgrades add. `gbrain auth clients` marks such a client `operations: "all"` with `includes_future_operations: true` and the command that re-pins it. A `bootstrap harness` re-run carries the replaced token's grants and does not widen its snapshot ([legacy token grants](../mcp/ADMIN.md#legacy-token-grants)). Archived sources are excluded. Legacy clients with a `NULL` operation snapshot retain their prior operation behavior.+Clients granted a memory profile before the full-surface default keep their stored `starter` surface; no migration or repair widens it, and only an explicit `--profile` application regrants it. New grants snapshot operation names and source access. A later server upgrade does not silently give a snapshot-bound client new operations. The connection's own `whoami` reports `grant_diagnosis`: which blocker applies (scope, operation snapshot, client pin or server ceiling) and how many operations it hides, without naming them; `gbrain doctor` on the host reports the same as `grant_new_ops_available` with the commands. The connection is also told once per session, in band, by the `grant_blocked_operations` notice (same blockers and counts, the owner's preview-then-apply command as `fix`, `next: tell_user_to_run`; once per grant revision for stateless HTTP calls), and a read that left out takes a hidden tool serves carries `hidden_tool_content` with the next step that connection can actually take ([connection notices](repair.md#connection-notices)). Neither notice changes what the connection can call. A grant written before snapshots recorded their operation catalog says "original intent unknown" rather than claiming it predates the operations. Explicitly regrant to include them: `gbrain auth rescope --client <client_id> --operations <op,...> --surface full --dry-run` (then without `--dry-run`; `--surface full` only when the stored surface also blocks) for OAuth clients, or `gbrain auth rescope-token <name> --refresh-operations` (preview) then `--add <op,...>` for legacy tokens ([grants that cannot reach new operations](../mcp/ADMIN.md#grants-that-cannot-reach-new-operations)). `gbrain auth rescope --client <client_id> --operations all` (alias: `gbrain auth rescope-client <client_id> --allowed-operations all`) stores no snapshot and clears the profile instead, so the scopes and the surface alone decide, including operations later upgrades add. `gbrain auth clients` marks such a client `operations: "all"` with `includes_future_operations: true` and the command that re-pins it. A `bootstrap harness` re-run carries the replaced token's grants and does not widen its snapshot ([legacy token grants](../mcp/ADMIN.md#legacy-token-grants)). Archived sources are excluded. Legacy clients with a `NULL` operation snapshot retain their prior operation behavior.Snapshot-bound clients write through approved MCP operations such as `remember`, `capture`, or `put_page`. They cannot use the legacy `POST /ingest` webhook, whose queued writes do not yet enforce operation snapshots. Existing webhook clients with a `NULL` snapshot keep their legacy behavior.diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex 0d60532d80..014ba581b5 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -2025,6 +2025,64 @@ the hosted one. Manage that connection with `gbrain connect <mcp-url>--harness claude-code --install`; `gbrain doctor --only harness_wiring` showswhich brain the registration reaches.+## Connection notices++Two notices tell an agent, on its own MCP connection, why something it+expected is out of reach. Neither changes what the connection can call.++### Grant blocked operations++`grant_blocked_operations` (info): this connection's grant cannot call some+operations its scopes allow. The notice says which proven blocker applies,+with counts and never operation names: the grant's operation snapshot, the+client's stored tool surface (a pin the brain owner set), or the server's+tool surface. A missing scope is named only on a refused call, because it is+how the grant was issued. Grant age is kept apart from the blockers: a grant+whose snapshot was written before snapshots recorded their operation catalog+says "this grant's snapshot excludes N currently eligible operations;+original intent unknown", and only a grant with recorded catalog provenance+says it predates operations. Operations outside the grant's scopes are never+counted, so a writer is not told about admin-only operations.++It arrives once per session: once per (principal, transport session) on+stdio and HTTP, and for a stateless HTTP call with no session id once per+(principal, grant revision), so a rescoped grant is diagnosed afresh.+`fix.next` is `tell_user_to_run`: the brain owner previews the change on the+brain host and then applies it (`then`). For an OAuth client that is+`gbrain auth rescope --client <client_id> --operations <OPERATIONS> --surface full --dry-run`+(`--surface full` only when the stored surface also blocks), then the same+command without `--dry-run`; for a legacy token,+`gbrain auth rescope --id <token_id> --refresh-operations` and then+`... --add <OPERATIONS>`. The owner chooses `<OPERATIONS>`. When only the+server's tool surface blocks, no grant change lifts it, and the fix is the+read-only doctor check that names the setting. `fix.verify` is read-only:+`gbrain doctor --only grant_new_ops_available --json` on the host, or+`whoami` on the same connection (its `grant_diagnosis` field carries the same+diagnosis). Nothing widens automatically; see+[grants that cannot reach new operations](../mcp/ADMIN.md#grants-that-cannot-reach-new-operations).++### Hidden tool content++`hidden_tool_content` (info): a page read, search or query left out takes+(page reads and search never include the takes table for an agent-facing+reader) and the tool that lists them, `takes_list`, is not in this+connection's tool list. The notice counts the takes and names the result's+own pages, and its `fix` is the next step this connection can actually take:++- `takes_list` is callable but not listed (an advertised surface narrower+ than the callable one): the fix is the `takes_list` call itself, and a+ stdio session also adds it to its tool list. A client that ignores+ `tools/list_changed` can still call it by name.+- one `request_tools {surface}` call would make it callable: the fix is that+ call (stdio: this session only, nothing written; HTTP: the client's own+ surface, within the server ceiling and never past an operator pin).+- otherwise only the brain host can change it: on HTTP the fix is the grant+ repair from `grant_blocked_operations`; on stdio it is the tool's CLI+ equivalent, relayed to the user.++A fix never names a call the connection cannot make: read-only access,+operator pins, the grant's snapshot and `GBRAIN_MCP_FORCE_SURFACE` all hold.+## Related- [Write refusal reasons](write-refusals.md) — what a refused write means and the recovery commanddiff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.mdindex 9ddbd01715..ca7ba16ed2 100644--- a/docs/mcp/ADMIN.md+++ b/docs/mcp/ADMIN.md@@ -245,6 +245,22 @@ in `whoami` (`grant_diagnosis`) and `gbrain://capabilities`; operations outsidethe grant's scopes are never counted. On the host, `gbrain doctor` reports`grant_new_ops_available` with each grant's blockers and the operation names.+The connection is also told in band, without asking: the+`grant_blocked_operations` notice arrives once per session (once per+(principal, transport session); for a stateless HTTP call with no session id,+once per (principal, grant revision), so three stateless calls get one notice+and a rescope is diagnosed afresh). It names the same blockers with counts,+keeps grant age apart, and its `fix` (`next: tell_user_to_run`) is the preview+command, then the apply command in `then`, for the owner to run on the host;+`fix.verify` is this doctor check or `whoami` on the same connection. A+missing scope is named only on a refused call. When the server surface alone+blocks, the fix is the read-only doctor check, because no grant change lifts+it. A result that left out takes a hidden tool serves carries+`hidden_tool_content`, whose `fix` is the step that connection can take:+calling `takes_list`, one `request_tools {surface}` widen (within the server+ceiling, never past an operator pin), or this grant repair+([connection notices](../guides/repair.md#connection-notices)).+Grant age is reported apart from those blockers. A snapshot written beforethis release carries no record of the operation catalog it was writtenagainst, so an old profile snapshot and a deliberate restriction look thediff --git a/llms-full.txt b/llms-full.txtindex 4ae3aad621..cdf15fced5 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -1476,7 +1476,7 @@ are one principal. See [shared brain skills](shared-brain-skills.md).A **profile grants authority**. A **surface selects visible tools**. Full surface does not bypass a grant, and `admin` does not imply delegation, the named shared-skill scopes, or owner dashboard/client-management authority. Starter includes authorized skill discovery and membership; the exact seven-tool `verbs` surface is memory-only. Thin CLI adapters use the full surface while retaining their source, operation, and write restrictions. Direct local CLI access is trusted access to the local computer; OAuth profiles do not confine a local shell.-Clients granted a memory profile before the full-surface default keep their stored `starter` surface; no migration or repair widens it, and only an explicit `--profile` application regrants it. New grants snapshot operation names and source access. A later server upgrade does not silently give a snapshot-bound client new operations. The connection's own `whoami` reports `grant_diagnosis`: which blocker applies (scope, operation snapshot, client pin or server ceiling) and how many operations it hides, without naming them; `gbrain doctor` on the host reports the same as `grant_new_ops_available` with the commands. A grant written before snapshots recorded their operation catalog says "original intent unknown" rather than claiming it predates the operations. Explicitly regrant to include them: `gbrain auth rescope --client <client_id> --operations <op,...> --surface full --dry-run` (then without `--dry-run`; `--surface full` only when the stored surface also blocks) for OAuth clients, or `gbrain auth rescope-token <name> --refresh-operations` (preview) then `--add <op,...>` for legacy tokens ([grants that cannot reach new operations](../mcp/ADMIN.md#grants-that-cannot-reach-new-operations)). `gbrain auth rescope --client <client_id> --operations all` (alias: `gbrain auth rescope-client <client_id> --allowed-operations all`) stores no snapshot and clears the profile instead, so the scopes and the surface alone decide, including operations later upgrades add. `gbrain auth clients` marks such a client `operations: "all"` with `includes_future_operations: true` and the command that re-pins it. A `bootstrap harness` re-run carries the replaced token's grants and does not widen its snapshot ([legacy token grants](../mcp/ADMIN.md#legacy-token-grants)). Archived sources are excluded. Legacy clients with a `NULL` operation snapshot retain their prior operation behavior.+Clients granted a memory profile before the full-surface default keep their stored `starter` surface; no migration or repair widens it, and only an explicit `--profile` application regrants it. New grants snapshot operation names and source access. A later server upgrade does not silently give a snapshot-bound client new operations. The connection's own `whoami` reports `grant_diagnosis`: which blocker applies (scope, operation snapshot, client pin or server ceiling) and how many operations it hides, without naming them; `gbrain doctor` on the host reports the same as `grant_new_ops_available` with the commands. The connection is also told once per session, in band, by the `grant_blocked_operations` notice (same blockers and counts, the owner's preview-then-apply command as `fix`, `next: tell_user_to_run`; once per grant revision for stateless HTTP calls), and a read that left out takes a hidden tool serves carries `hidden_tool_content` with the next step that connection can actually take ([connection notices](repair.md#connection-notices)). Neither notice changes what the connection can call. A grant written before snapshots recorded their operation catalog says "original intent unknown" rather than claiming it predates the operations. Explicitly regrant to include them: `gbrain auth rescope --client <client_id> --operations <op,...> --surface full --dry-run` (then without `--dry-run`; `--surface full` only when the stored surface also blocks) for OAuth clients, or `gbrain auth rescope-token <name> --refresh-operations` (preview) then `--add <op,...>` for legacy tokens ([grants that cannot reach new operations](../mcp/ADMIN.md#grants-that-cannot-reach-new-operations)). `gbrain auth rescope --client <client_id> --operations all` (alias: `gbrain auth rescope-client <client_id> --allowed-operations all`) stores no snapshot and clears the profile instead, so the scopes and the surface alone decide, including operations later upgrades add. `gbrain auth clients` marks such a client `operations: "all"` with `includes_future_operations: true` and the command that re-pins it. A `bootstrap harness` re-run carries the replaced token's grants and does not widen its snapshot ([legacy token grants](../mcp/ADMIN.md#legacy-token-grants)). Archived sources are excluded. Legacy clients with a `NULL` operation snapshot retain their prior operation behavior.Snapshot-bound clients write through approved MCP operations such as `remember`, `capture`, or `put_page`. They cannot use the legacy `POST /ingest` webhook, whose queued writes do not yet enforce operation snapshots. Existing webhook clients with a `NULL` snapshot keep their legacy behavior.diff --git a/plugin-variants/gbrain-coding/skills/mcp-access/SKILL.md b/plugin-variants/gbrain-coding/skills/mcp-access/SKILL.mdindex 06e14201d3..e5d03430b4 100644--- a/plugin-variants/gbrain-coding/skills/mcp-access/SKILL.md+++ b/plugin-variants/gbrain-coding/skills/mcp-access/SKILL.md@@ -116,6 +116,8 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)- A failed transport after a mutation was sent means the outcome is unknown: re-read the client list before retrying, never re-send blind.- A list call fails: a failed list is not an empty list; report the error.- A tool the grant should reach is missing (`unknown_tool`, or a write such as `put_pages` absent): read `grant_diagnosis` from `whoami` or `gbrain://capabilities`. It names the blocker (scope, operation snapshot, client pin or server ceiling) and counts the operations it hides without naming them. Relay its `fix` (`next: tell_user_to_run`) to the brain owner; on the host, `gbrain doctor` check `grant_new_ops_available` shows the exact commands. New memory-profile grants are on the full surface; older ones keep their stored surface until the owner changes it. An "original intent unknown" grant may be restricted on purpose: never widen it unasked, and offer `--operations all` (no snapshot, including operations later upgrades add) only as the user's explicit choice.+- A `grant_blocked_operations` notice (once per session) is the same diagnosis delivered in band: relay its `fix` to the brain owner (preview, then the `then` command), confirm with `whoami` afterwards, and do not retry the blocked operations meanwhile. It never names operations, and a missing scope is named only when a call was refused.+- A `hidden_tool_content` notice means the result left out takes that a tool outside your tool list serves. Follow its `fix` as given: call `takes_list` when it names it, call `request_tools {surface}` when it names that (then `takes_list`), or relay the owner's repair when `next` is `tell_user_to_run`. Do not answer "not found" from that result alone.## Anti-Patternsdiff --git a/plugin-variants/gbrain-daily/skills/mcp-access/SKILL.md b/plugin-variants/gbrain-daily/skills/mcp-access/SKILL.mdindex 06e14201d3..e5d03430b4 100644--- a/plugin-variants/gbrain-daily/skills/mcp-access/SKILL.md+++ b/plugin-variants/gbrain-daily/skills/mcp-access/SKILL.md@@ -116,6 +116,8 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)- A failed transport after a mutation was sent means the outcome is unknown: re-read the client list before retrying, never re-send blind.- A list call fails: a failed list is not an empty list; report the error.- A tool the grant should reach is missing (`unknown_tool`, or a write such as `put_pages` absent): read `grant_diagnosis` from `whoami` or `gbrain://capabilities`. It names the blocker (scope, operation snapshot, client pin or server ceiling) and counts the operations it hides without naming them. Relay its `fix` (`next: tell_user_to_run`) to the brain owner; on the host, `gbrain doctor` check `grant_new_ops_available` shows the exact commands. New memory-profile grants are on the full surface; older ones keep their stored surface until the owner changes it. An "original intent unknown" grant may be restricted on purpose: never widen it unasked, and offer `--operations all` (no snapshot, including operations later upgrades add) only as the user's explicit choice.+- A `grant_blocked_operations` notice (once per session) is the same diagnosis delivered in band: relay its `fix` to the brain owner (preview, then the `then` command), confirm with `whoami` afterwards, and do not retry the blocked operations meanwhile. It never names operations, and a missing scope is named only when a call was refused.+- A `hidden_tool_content` notice means the result left out takes that a tool outside your tool list serves. Follow its `fix` as given: call `takes_list` when it names it, call `request_tools {surface}` when it names that (then `takes_list`), or relay the owner's repair when `next` is `tell_user_to_run`. Do not answer "not found" from that result alone.## Anti-Patternsdiff --git a/plugin/skills/mcp-access/SKILL.md b/plugin/skills/mcp-access/SKILL.mdindex 06e14201d3..e5d03430b4 100644--- a/plugin/skills/mcp-access/SKILL.md+++ b/plugin/skills/mcp-access/SKILL.md@@ -116,6 +116,8 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)- A failed transport after a mutation was sent means the outcome is unknown: re-read the client list before retrying, never re-send blind.- A list call fails: a failed list is not an empty list; report the error.- A tool the grant should reach is missing (`unknown_tool`, or a write such as `put_pages` absent): read `grant_diagnosis` from `whoami` or `gbrain://capabilities`. It names the blocker (scope, operation snapshot, client pin or server ceiling) and counts the operations it hides without naming them. Relay its `fix` (`next: tell_user_to_run`) to the brain owner; on the host, `gbrain doctor` check `grant_new_ops_available` shows the exact commands. New memory-profile grants are on the full surface; older ones keep their stored surface until the owner changes it. An "original intent unknown" grant may be restricted on purpose: never widen it unasked, and offer `--operations all` (no snapshot, including operations later upgrades add) only as the user's explicit choice.+- A `grant_blocked_operations` notice (once per session) is the same diagnosis delivered in band: relay its `fix` to the brain owner (preview, then the `then` command), confirm with `whoami` afterwards, and do not retry the blocked operations meanwhile. It never names operations, and a missing scope is named only when a call was refused.+- A `hidden_tool_content` notice means the result left out takes that a tool outside your tool list serves. Follow its `fix` as given: call `takes_list` when it names it, call `request_tools {surface}` when it names that (then `takes_list`), or relay the owner's repair when `next` is `tell_user_to_run`. Do not answer "not found" from that result alone.## Anti-Patternsdiff --git a/skills/mcp-access/SKILL.md b/skills/mcp-access/SKILL.mdindex a18af11b7b..fcfc22da93 100644--- a/skills/mcp-access/SKILL.md+++ b/skills/mcp-access/SKILL.md@@ -115,6 +115,8 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)- A failed transport after a mutation was sent means the outcome is unknown: re-read the client list before retrying, never re-send blind.- A list call fails: a failed list is not an empty list; report the error.- A tool the grant should reach is missing (`unknown_tool`, or a write such as `put_pages` absent): read `grant_diagnosis` from `whoami` or `gbrain://capabilities`. It names the blocker (scope, operation snapshot, client pin or server ceiling) and counts the operations it hides without naming them. Relay its `fix` (`next: tell_user_to_run`) to the brain owner; on the host, `gbrain doctor` check `grant_new_ops_available` shows the exact commands. New memory-profile grants are on the full surface; older ones keep their stored surface until the owner changes it. An "original intent unknown" grant may be restricted on purpose: never widen it unasked, and offer `--operations all` (no snapshot, including operations later upgrades add) only as the user's explicit choice.+- A `grant_blocked_operations` notice (once per session) is the same diagnosis delivered in band: relay its `fix` to the brain owner (preview, then the `then` command), confirm with `whoami` afterwards, and do not retry the blocked operations meanwhile. It never names operations, and a missing scope is named only when a call was refused.+- A `hidden_tool_content` notice means the result left out takes that a tool outside your tool list serves. Follow its `fix` as given: call `takes_list` when it names it, call `request_tools {surface}` when it names that (then `takes_list`), or relay the owner's repair when `next` is `tell_user_to_run`. Do not answer "not found" from that result alone.## Anti-Patternsdiff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex 412e3d7230..b7c3d423c7 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -96,7 +96,7 @@"ingest/SKILL.md": "1acc220ce6e9e65876fa2ccede6ce11f9c75457feb6695ef904955f8debecaae","maintain/SKILL.md": "2a1d99b68a58a6f67ee88c871bb1185f4f73b99d26a7ed38ac56b2e12a21e5ce","manifest.json": "357aa185d380f0a357cb15cd513317e290cbc5fcf5ca4e3860b0e829fdcbf1e4",- "mcp-access/SKILL.md": "c2ff223b4461ba5817c6c0e7b50a1006866204b6c1d4bd905e52809350ecd092",+ "mcp-access/SKILL.md": "1bc16338b89f476aa8c24ffec79c989fa60716793998af264d357f7886d2bc96","measure-before-you-fix/SKILL.md": "11906da29a1a31976b13d4796b686d9a9981825737846a85f32d88bf431b9b36","measure-before-you-fix/routing-eval.jsonl": "0661df9974a9cfe31216d574b1db0ef341945c2eb844ebf4ab6920fcbbc90d6c","media-ingest/SKILL.md": "d70374d3df21397380203f541ebdcc90c0bc6bc7207234349594a081e98f2719",diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.tsindex 9bc8228d4c..8d031edf6c 100644--- a/src/commands/serve-http-mcp.ts+++ b/src/commands/serve-http-mcp.ts@@ -21,7 +21,7 @@ import { createSkillResources } from '../mcp/skill-resources.ts';import { resolveAuthCapabilities } from '../core/harness/capabilities.ts';import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writeback-config.ts';import { hasScope, operationScopesAllowed } from '../core/scope.ts';-import { summarizeMcpParams, dispatchToolCall, requestLogStatusForResult, requestMetaSessionId, acceptedPendingReceipt, unknownToolEnvelope, errorResult, dispatchRenderContext, type ToolResult } from '../mcp/dispatch.ts';+import { summarizeMcpParams, dispatchToolCall, requestLogStatusForResult, requestMetaSessionId, acceptedPendingReceipt, unknownToolEnvelope, errorResult, dispatchRenderContext, grantBlockedNotices, admitNotices, type ToolResult } from '../mcp/dispatch.ts';import { toAgentError } from '../core/agent-output.ts';import { STATUS_TOOL_NAME, statusModeOf, statusToolResult } from '../mcp/status-mode.ts';import { isCallable, publishGatesFromDisabled } from '../core/ops/callable.ts';@@ -295,7 +295,7 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, requesif (statusMode && hasScope(authInfo.scopes, 'read')) return statusToolResult(statusMode, 'http');const op = mcpOperations.find(o => o.name === name);if (!op) {- return rejectUnknownMcpOperation(ctx, state, name);+ return rejectUnknownMcpOperation(ctx, state, name, requestMetaSessionId(request.params));}// Scope enforcement (v0.28: hasScope replaces exact-string-match so@@ -311,7 +311,7 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, reques// denial first would tell the operator to widen the grant for nothing.const scopeSatisfied = op.cliOnly !== undefined || operationScopesAllowed(authInfo.scopes, op);if (!scopeSatisfied) {- return rejectInsufficientMcpScope(ctx, state, name, requiredScope);+ return rejectInsufficientMcpScope(ctx, state, name, requiredScope, requestMetaSessionId(request.params));}// F8: redact request payload by default (declared keys only via the@@ -401,6 +401,8 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, requessurface,// WP4 (D2): request_tools bounds its catalog + persist by this.surfaceCeiling,+ // D2: a callable tool the advertised surface leaves out of tools/list (same rule as listMcpTools).+ isListed: async op => !!authInfo.surface || advertisedOps([op], surface, await resolveAdvertisedSurface(engine, ctx.config)).length > 0,resultRows,// v0.31 follow-up fix: thread auth so the whoami op (and any// future scope-aware handlers) can introspect the caller. The@@ -448,7 +450,7 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, requesreturn recordMcpToolResult(ctx, state, name, toolResult, logParamsObj, broadcastParams);}-async function rejectUnknownMcpOperation(ctx: ServeHttpContext, state: McpRequestState, name: string): Promise<ToolResult> {+async function rejectUnknownMcpOperation(ctx: ServeHttpContext, state: McpRequestState, name: string, sessionId?: string): Promise<ToolResult> {const { engine, broadcastEvent } = ctx;const { authInfo, agentName, startTime } = state;// v0.28.10: persist unknown-op attempts. Operators investigating@@ -474,8 +476,10 @@ async function rejectUnknownMcpOperation(ctx: ServeHttpContext, state: McpRequestimestamp: new Date().toISOString(),});// Frozen v1 pair: `error: unknown_operation` stays; `code: unknown_tool`.- return unknownToolEnvelope(name, { remote: true, transport: 'http', auth: authInfo, surface: state.surface,- ...(state.surfaceAllowedOps ? { allowedOps: state.surfaceAllowedOps } : {}) }, 'unknown_operation');+ const opts = { remote: true, transport: 'http' as const, auth: authInfo, surface: state.surface, config: ctx.config, surfaceCeiling: state.surfaceCeiling,+ ...(sessionId ? { sessionId } : {}), ...(ctx.noticeLedger ? { noticeLedger: ctx.noticeLedger } : {}),+ ...(state.surfaceAllowedOps ? { allowedOps: state.surfaceAllowedOps } : {}) };+ return unknownToolEnvelope(name, opts, 'unknown_operation', await grantBlockedNotices(engine, opts, true));}async function rejectInsufficientMcpScope(@@ -483,6 +487,7 @@ async function rejectInsufficientMcpScope(state: McpRequestState,name: string,requiredScope: string,+ sessionId?: string,): Promise<ToolResult> {const { engine, broadcastEvent } = ctx;const { authInfo, agentName, startTime } = state;@@ -514,7 +519,11 @@ async function rejectInsufficientMcpScope(timestamp: new Date().toISOString(),});const denial = scopeDeniedError({ op: name, required: [requiredScope], auth: authInfo, transport: 'http' });- const envelope = toAgentError(denial, { transport: 'http', op: name, render: dispatchRenderContext({ remote: true, transport: 'http', auth: authInfo }) });+ const opts = { remote: true, transport: 'http' as const, auth: authInfo, config: ctx.config, surfaceCeiling: state.surfaceCeiling,+ ...(sessionId ? { sessionId } : {}), ...(ctx.noticeLedger ? { noticeLedger: ctx.noticeLedger } : {}) };+ const notices = await grantBlockedNotices(engine, opts, true);+ if (notices.length) denial.notices = admitNotices(notices, opts);+ const envelope = toAgentError(denial, { transport: 'http', op: name, render: dispatchRenderContext(opts) });return { content: [{ type: 'text', text: JSON.stringify({ ...envelope, your_scopes: authInfo.scopes }) }], isError: true };}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 215c8b656f..a171694b6e 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -473,6 +473,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// #6529 (GBRA-79). `since` is provisional: stamped at the current VERSION because a `since` past VERSION discloses on every fresh brain (goldens, notice tests); the integrator restamps both rows to the release (0.60.182.0 placeholder) at the merge slot.{ since: '0.60.182.0', text: 'With `GBRAIN_EMBEDDING_MULTIMODAL=true`, managed sync now imports image files through the coordinated image importer (OCR text, image vector and `source_path` at import) instead of holding them as `managed_image_sync_unsupported`; existing image holds are re-screened and imported on the next `gbrain sync --source <id> --no-pull`. With it off, images stay held as before.' },{ since: '0.60.182.0', text: 'On a multimodal install, plain `gbrain embed --stale` now runs the image sweep (`--images`) before its text pass and reports it as `images` in `--json`; `gbrain embed --stale --images` works on managed brains, finds an image page with no recorded `source_path` by its slug, and exits non-zero naming the path it tried when no candidate has a file (it used to exit 0); the folded sweep only reports fileless pages. Doctor gains `image_embedding_coverage`.' },+ { since: '0.60.184.0', text: 'Two new info notices on MCP results; nothing a connection can call changes. `grant_blocked_operations` tells an authenticated connection once per session (once per grant revision for stateless HTTP) that its grant\'s operation snapshot, stored client surface or the server surface keeps operations its scopes allow out of reach, with counts and no operation names, and gives the brain owner\'s preview-then-apply rescope command (a missing scope is named only on a refused call). `hidden_tool_content` on get_page, search and query says when the result left out takes that a tool outside the tool list serves, with the next step that connection can take: the takes_list call (stdio also lists it), one request_tools {surface} widen, or the owner\'s repair. Fixes no longer name an MCP tool outside the grant\'s operation snapshot, and the stdio unknown-tool hint no longer offers a widen that read-only access or GBRAIN_MCP_FORCE_SURFACE would refuse.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex e23cbe639d..ba3ece651f 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -33,6 +33,9 @@ export interface CatalogueEntry {export const ERROR_CATALOGUE = {legacy_jobs_active: { code: 'legacy_jobs_active', docs: 'docs/guides/repair.md#legacy-jobs-active' },+ // D4 / D2 notice codes (agent-output Notice through the notice ledger).+ grant_blocked_operations: { code: 'grant_blocked_operations', docs: 'docs/guides/repair.md#grant-blocked-operations' },+ hidden_tool_content: { code: 'hidden_tool_content', docs: 'docs/guides/repair.md#hidden-tool-content' },legacy_job_selection_invalid: { code: 'legacy_job_selection_invalid', docs: 'docs/guides/repair.md#legacy-job-selection-invalid' },legacy_job_authority: { code: 'permission_denied', docs: 'docs/guides/repair.md#legacy-job-authority' },preview_changed: { code: 'preview_changed', docs: 'docs/guides/repair.md#preview-changed' },diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 1d1834c163..8d96afb60c 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -527,6 +527,8 @@ export const NOTICE_CODES = {onboard_link_coverage: { kind: 'coaching', summary: 'Few people/company pages have incoming links, so backlinks and graph answers are thin; the remedy is link extraction.' },onboard_timeline_coverage: { kind: 'coaching', summary: 'Few people/company pages have timeline entries, so dated answers are thin; the remedy is timeline extraction.' },onboard_no_takes: { kind: 'coaching', summary: 'The brain holds no takes, so think and recall cannot cite the user\'s own views; the remedy is recording or extracting takes.' },+ grant_blocked_operations: { kind: 'info', summary: 'Once per session (per grant revision for stateless HTTP): this connection\'s grant cannot call operations its scopes allow; the notice names the blocker (operation snapshot, client pin or server ceiling; a missing scope on a refused call) with counts only and the brain owner\'s preview-then-apply rescope command.' },+ hidden_tool_content: { kind: 'info', summary: 'A page read or search left out takes that a tool outside this connection\'s tool list serves; the fix is the next step this connection can take (call takes_list, widen with request_tools, or the brain owner\'s repair).' },surface_env_invalid: { kind: 'info', summary: 'GBRAIN_SURFACE holds a value other than verbs, starter or full; the server ignored it and names the surface it serves.' },features_auto_fix: { kind: 'coaching', summary: 'gbrain features found auto-fixable gaps; the fix is the auto-fix command (it may spend on embeddings).' },delta_incomplete: { kind: 'degraded', summary: 'delta delivered less than is waiting and moved no cursor past it: an arm failed or the deadline fired (retry after a short wait; report after 3 consecutive wakes), or budget_tokens cannot fit one item (the fix names the budget that does).' },diff --git a/src/core/harness/capabilities.ts b/src/core/harness/capabilities.tsindex 76937a51fc..6e240f3354 100644--- a/src/core/harness/capabilities.ts+++ b/src/core/harness/capabilities.ts@@ -5,6 +5,7 @@ import type { GBrainConfig } from '../config.ts';import { TOKEN_TTL_MAX_SECONDS, TOKEN_TTL_MIN_SECONDS, normalizeGrantBrain, validGrantPrefixes } from '../grants/model.ts';import { shellQuote } from '../mcp-registration.ts';import type { CatalogProvenance } from '../grants/profiles.ts';+import type { Action, Notice } from '../agent-output.ts';type GrantSurface = 'verbs' | 'starter' | 'full';@@ -204,6 +205,65 @@ export function describeGrantDiagnosis(gaps: GrantGaps, opts: {};}+export type GrantDiagnosis = ReturnType<typeof describeGrantDiagnosis>;++const GRANT_DOCS = 'docs/guides/repair.md#grant-blocked-operations';+const GRANT_VERIFY = { argv: ['gbrain', 'doctor', '--only', 'grant_new_ops_available', '--json'], mcp: { tool: 'whoami', arguments: {} } };++/**+ * The host-owned repair for a grant diagnosis as an agent-contract Action:+ * the preview command, then the apply command, relayed to the user (the+ * agent never runs it). A server ceiling alone gets the read-only doctor+ * check that names the setting, because no grant change lifts it.+ */+export function grantRepairAction(d: GrantDiagnosis): Action | null {+ if (d.fix) {+ return {+ argv: d.fix.argv, consent: ['credentials'], actor: 'host_admin', requires_exclusive: false,+ why: 'Previews the grant change on the brain host; the brain owner reviews it, then runs the command in `then`. Changing a grant widens what this credential can do, so nothing changes automatically.',+ user_message: d.fix.user_message, docs: GRANT_DOCS, verify: GRANT_VERIFY,+ ...(d.fix.inputs ? { inputs: d.fix.inputs } : {}),+ then: { argv: d.fix.then_argv, consent: ['credentials'], actor: 'host_admin', requires_exclusive: false, why: 'Applies the previewed grant change.' },+ };+ }+ if (!d.blockers.some(b => b.blocker === 'server_ceiling')) return null;+ return {+ argv: GRANT_VERIFY.argv, consent: [], actor: 'user', requires_exclusive: false, docs: GRANT_DOCS, verify: GRANT_VERIFY,+ why: 'The server tool surface (config mcp_surface, `gbrain serve --surface` or GBRAIN_MCP_FORCE_SURFACE) caps this connection, and no grant change lifts it; this read-only check on the brain host names the setting.',+ user_message: 'This gbrain connection is capped by the server\'s tool surface setting on the brain host. Running the command shown there names the setting; changing it is the brain owner\'s call.',+ };+}++function blockerPhrase(b: Record<string, unknown>): string {+ if (b.blocker === 'operation_snapshot') return `its operation snapshot (${b.excluded_count})`;+ if (b.blocker === 'client_pin') return `its stored ${b.surface} tool surface${b.set_by === 'operator' ? ', which the brain owner pinned' : ''} (${b.excluded_count})`;+ return `the server's ${b.surface} tool surface (${b.excluded_count})`;+}++/**+ * D4 `grant_blocked_operations`: the in-band stale-grant notice. Counts per+ * blocker, never operation names; the inferred grant age kept apart. A+ * missing scope is reported only on a refused call (it is how the grant was+ * issued, not a fault). Null when nothing applies.+ */+export function grantBlockedNotice(d: GrantDiagnosis, opts: { refused: boolean }): Notice | null {+ const reachable = d.blockers.filter(b => b.blocker !== 'scope');+ const scope = d.blockers.find(b => b.blocker === 'scope') as { missing_scopes: string[] } | undefined;+ const parts: string[] = [];+ if (reachable.length && d.unreachable_count > 0) {+ const n = d.unreachable_count;+ const age = 'statement' in d.grant_age ? ` ${d.grant_age.statement}` : '';+ parts.push(`This connection's grant cannot call ${n} operation${n === 1 ? '' : 's'} its scopes allow, blocked by ${reachable.map(blockerPhrase).join(' and by ')} (counted per blocker; an operation can sit behind more than one).${age}`+ + ' Only the brain owner can change this on the brain host, and nothing widens automatically; whoami reports the same diagnosis as grant_diagnosis.');+ }+ if (opts.refused && scope) {+ parts.push(`This grant has no ${scope.missing_scopes.join(' or ')} scope, so operations that need it are refused on this connection; that is how the grant was issued, and only the brain owner can change it.`);+ }+ if (!parts.length) return null;+ const fix = reachable.length ? grantRepairAction(d) : null;+ return { code: 'grant_blocked_operations', kind: 'info', why: parts.join(' '), ...(fix ? { fix } : {}) };+}+/*** `whoami.grant_diagnosis` for an authenticated connection. Identity is the* verifier's principal (never a display name); provenance is read only for andiff --git a/src/core/interop-notices.ts b/src/core/interop-notices.tsindex 374549ff84..5861c32550 100644--- a/src/core/interop-notices.ts+++ b/src/core/interop-notices.ts@@ -371,6 +371,29 @@ export function localTranscriptsNotice(presence: { dirs: string[]; count: number};}+// ── content a hidden tool serves (D2) ─────────────────────────────────────++/**+ * `hidden_tool_content`: this result left out takes (page reads, search and+ * query never show the takes table to an agent-facing reader) that a tool+ * outside this connection's tool list serves. The fix is the hidden-tool+ * route's next step (`hiddenToolNext`); a connection with none gets the+ * reason alone. Counts and the result's own slugs only, never take text.+ */+export function hiddenTakesNotice(hidden: { pages: string[]; count: number }, route: 'callable' | 'widen' | 'host', fix: Action | null): Notice {+ const n = hidden.count >= 100 ? '100+' : String(hidden.count);+ const pages = hidden.pages.length === 1 ? hidden.pages[0] : `${hidden.pages.slice(0, -1).join(', ')} and ${hidden.pages[hidden.pages.length - 1]}`;+ const reach = route === 'callable' ? 'takes_list lists them: call it as fix shows.'+ : route === 'widen' ? 'One request_tools call makes takes_list available here, as fix shows.'+ : fix ? 'This connection cannot list them; fix says who can change that.' : 'This connection cannot list them, and only the brain owner can change that.';+ return {+ code: 'hidden_tool_content',+ kind: 'info',+ why: `This result leaves out ${n} take${n === '1' ? '' : 's'} (attributed claims such as forecasts, estimates and bets) on ${pages}: page reads and search never include the takes table, so their absence here does not mean the brain has none. ${reach}`,+ ...(fix ? { fix } : {}),+ };+}+// ── CLI emission for commands without a result document (F7) ──────────────/**diff --git a/src/core/notice-ledger.ts b/src/core/notice-ledger.tsindex d92b4f2639..26eb32849f 100644--- a/src/core/notice-ledger.ts+++ b/src/core/notice-ledger.ts@@ -23,7 +23,10 @@ export const COACHING_BUDGET_PER_SESSION = 2;/** Notices that describe THIS call's result (never deduped): the diagnosis must ride every affected call. *//** The one muteable `ask`: an unanswered first-run bundle must stay dismissible. Every other ask always shows. */export const MUTEABLE_ASK_CODES: ReadonlySet<string> = new Set(['first_run_decisions']);-export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['empty_retrieval', 'unknown_param', 'listing_truncated', 'former_relationships_hidden', 'source_binding_narrowed', 'local_transcripts', 'held_files', 'relational_chain', 'mention_index', 'delta_incomplete', 'identity_siblings_capped', 'alias_fanout', 'facts_unembedded']);+export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['hidden_tool_content', 'empty_retrieval', 'unknown_param', 'listing_truncated', 'former_relationships_hidden', 'source_binding_narrowed', 'local_transcripts', 'held_files', 'relational_chain', 'mention_index', 'delta_incomplete', 'identity_siblings_capped', 'alias_fanout', 'facts_unembedded']);++/** Notices whose producer already deduped them with `claim` on its own key; admit applies mute only. */+export const SELF_DEDUPED_NOTICE_CODES: ReadonlySet<string> = new Set(['grant_blocked_operations']);export interface NoticeAudience {transport: Transport;@@ -37,6 +40,8 @@ export class NoticeLedger {private seen = new Map<string, number>();private coaching = new Map<string, { count: number; at: number }>();private tallies = new Map<string, { n: number; at: number }>();+ private claimed = new Map<string, number>();+ private memo = new Map<string, { value: unknown; at: number }>();constructor(private readonly now: () => number = Date.now) {}@@ -62,13 +67,31 @@ export class NoticeLedger {return n;}+ /** First call for `key` returns true and records it; later calls (within the TTL) return false. */+ claim(key: string): boolean {+ if (this.claimed.has(key)) return false;+ this.claimed.set(key, this.now());+ this.prune(this.claimed, at => at);+ return true;+ }++ /** `compute` once per `key` (within the TTL); later calls get the stored value. */+ async memoize<T>(key: string, compute: () => Promise<T>): Promise<T> {+ const hit = this.memo.get(key);+ if (hit) return hit.value as T;+ const value = await compute();+ this.memo.set(key, { value, at: this.now() });+ this.prune(this.memo, v => v.at);+ return value;+ }+/** Filter one call's notices: mute, dedupe and the coaching budget. Never throws. */admit(notices: readonly Notice[], audience: NoticeAudience, muted: ReadonlySet<string> = new Set()): Notice[] {const out: Notice[] = [];const session = this.session(audience);for (const n of notices) {if ((n.kind === 'coaching' || n.kind === 'info' || MUTEABLE_ASK_CODES.has(n.code)) && muted.has(n.code)) continue;- const always = PER_CALL_NOTICE_CODES.has(n.code)+ const always = PER_CALL_NOTICE_CODES.has(n.code) || SELF_DEDUPED_NOTICE_CODES.has(n.code)|| (audience.transport === 'http' && (n.kind === 'degraded' || n.kind === 'safety'));const key = `${session}|${n.code}`;if (!always && this.seen.has(key)) continue;diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.tsindex daffad09a7..1bdb2681ec 100644--- a/src/core/ops/takes.ts+++ b/src/core/ops/takes.ts@@ -22,6 +22,41 @@ import { embedQuery } from '../embedding.ts';import { ALL_SOURCES } from '../source-id.ts';import { privatePagesFilterFragment } from '../search/private-visibility.ts';+/** Result pages whose takes D2 checks: the page a get_page read returned, or the first distinct pages of a search/query. */+const HIDDEN_TAKES_PAGE_CAP = 3;++/**+ * D2: page reads, search and query never show the takes table to an+ * agent-facing reader. For the pages this result returned, the takes+ * `takes_list` would list on this connection (same source scope, holder+ * allow-list and read eligibility), counted, capped at 100 per page. Null+ * when the result has no page with such takes. Slugs come from the result.+ */+export async function takesHiddenFromResult(ctx: OperationContext, op: string, result: unknown): Promise<{ pages: string[]; count: number } | null> {+ if (ctx.remote === false) return null;+ const rows = op === 'get_page' ? [result] : (op === 'search' || op === 'query') && Array.isArray(result) ? result : [];+ const pages = new Map<string, string | undefined>();+ for (const row of rows) {+ if (pages.size >= HIDDEN_TAKES_PAGE_CAP) break;+ const r = row as { slug?: unknown; source_id?: unknown; result_type?: unknown } | null;+ if (!r || typeof r.slug !== 'string' || (r.result_type !== undefined && r.result_type !== 'page')) continue;+ const source = typeof r.source_id === 'string' ? r.source_id : undefined;+ const key = `${source ?? ''}\u0000${r.slug}`;+ if (!pages.has(key)) pages.set(key, source);+ }+ if (pages.size === 0) return null;+ const eligibility = await resolveReadEligibility(ctx, {});+ const counted = await Promise.all([...pages].map(async ([key, source]) => {+ const slug = key.slice(key.indexOf('\u0000') + 1);+ const policy = await readPolicyOpts(ctx, ...(source ? [{ sourceId: source }] : []));+ const takes = await ctx.engine.listTakes({ ...policy, page_slug: slug, takesHoldersAllowList: readHolders(ctx), eligibility, limit: 100 });+ return { slug, count: takes.length };+ }));+ const withTakes = counted.filter(c => c.count > 0);+ if (!withTakes.length) return null;+ return { pages: [...new Set(withTakes.map(c => c.slug))], count: withTakes.reduce((n, c) => n + c.count, 0) };+}+// --- v0.28: Takes ---const takes_list: Operation = {diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 2398f7405d..fd55e0d76d 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -10,6 +10,7 @@ import { affectsRecall } from '../core/types.ts';import type { BrainEngine } from '../core/engine.ts';import { operations, OperationError, enforceBoundClientOpAllowList, opError } from '../core/operations.ts';import type { OperationContext, AuthInfo } from '../core/operations.ts';+import type { OperationMeta } from '../core/ops/contract.ts';import { loadConfig } from '../core/config.ts';import { resolveBrainId } from '../core/brain-resolver.ts';import { getCliOptions } from '../core/cli-options.ts';@@ -21,8 +22,9 @@ import { mutedNoticeCodes, processNoticeLedger, __resetProcessNoticeLedgerForTesimport { logVerbUsage } from '../core/verbs/usage-log.ts';import { searchCountLine } from '../core/search/keyword-paging.ts';import { dateLabelLine } from '../core/search/date-labels.ts';-import { localTranscriptsNotice, recallInteropNotices, wantsTranscriptHint } from '../core/interop-notices.ts';-import { hiddenToolHint } from './hidden-tool-hint.ts';+import { hiddenTakesNotice, localTranscriptsNotice, recallInteropNotices, wantsTranscriptHint } from '../core/interop-notices.ts';+import { hiddenToolHint, hiddenToolNext, hiddenToolRoute, type ToolConnection } from './hidden-tool-hint.ts';+import { opAllowedForBoundClient } from '../core/ops/context.ts';import { takePostUpgradeMcpNotice } from '../core/post-upgrade-notice.ts';import { takeHttpBehaviorNotice, takeLocalBehaviorNotice } from '../core/behavior-change-notice.ts';import { takeChatFallbackHopNotices } from '../core/ai/fallback-hop-queue.ts';@@ -269,6 +271,12 @@ export interface DispatchOpts {stdioSurface?: OperationContext['stdioSurface'];/** Threaded into OperationContext.revealTools (stdio session tool reveal). */revealTools?: (names: string[]) => void;+ /**+ * D2: whether this connection's tools/list shows a callable tool (the+ * advertised surface can list fewer tools than the callable set). Unset =+ * every callable tool counts as listed.+ */+ isListed?: (op: OperationMeta) => Promise<boolean>;/** #5232: commit wait for coordinated writes (OperationContext.writeWaitMs); unset = agent default. */writeWaitMs?: number;/** C1: search/query row shape chosen by the transport (OperationContext.resultRows); unset = lean for remote callers. */@@ -540,18 +548,18 @@ export function requestLogStatusForResult(result: ToolResult): RequestLogStatus* gate state is unknown here, and a suggestion naming a hidden/gated op* would be the exact existence oracle this envelope exists to prevent.*/-export function unknownToolEnvelope(name: string, opts: DispatchOpts, legacyError?: 'unknown_operation'): ToolResult {+export function unknownToolEnvelope(name: string, opts: DispatchOpts, legacyError?: 'unknown_operation', notices: Notice[] = []): ToolResult {const allowedOps = opts.allowedOps;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 hint = hiddenToolHint(operations.find(o => o.name === name), opts, dispatchRenderContext(opts).isCallable('request_tools') && opts.stdioSurface?.widenAllowed !== false); // F6: owner's stdio pipe only+ const hint = hiddenToolHint(operations.find(o => o.name === name), { ...opts, readOnly: opts.stdioSurface?.readOnly }, toolConnection(opts).canWiden); // F6: owner's stdio pipe onlyconst suggestion = hint?.suggestion ?? (nearest? `Did you mean "${nearest}"?`: 'List the tools this connection can call (tools/list) and use one of those names.');return errorResult(opError('unknown_tool', legacyError ? `Unknown: ${name}` : `Unknown tool: ${name}`, suggestion,- { ...(legacyError ? { legacy_error: legacyError } : {}), ...(hint ? { fix: hint.fix } : {}) }), opts);+ { ...(legacyError ? { legacy_error: legacyError } : {}), ...(hint ? { fix: hint.fix } : {}) }), opts, { notices: admitNotices(notices, opts) });}/**@@ -574,7 +582,7 @@ export function dispatchRenderContext(opts: DispatchOpts): RenderContext {const op = byName.get(opName);return !!op && isCallable(op, {transport, surface, scopes: opts.auth?.scopes ?? [], publishGates: {}, allowedOps: opts.allowedOps,- });+ }) && (transport === 'cli' || opAllowedForBoundClient(opts.auth, op));},preapproved: () => false,...(opts.auth?.clientId ? { principal: opts.auth.clientId } : {}),@@ -600,7 +608,7 @@ function noticeAudience(opts: DispatchOpts): NoticeAudience {return { transport: opts.transport === 'stdio' ? 'stdio' : opts.remote === false ? 'cli' : 'http', principal: opts.auth?.clientId, sessionId: opts.sessionId };}-function admitNotices(notices: Notice[], opts: DispatchOpts): Notice[] {+export function admitNotices(notices: Notice[], opts: DispatchOpts): Notice[] {if (notices.length === 0) return notices;try {const audience = noticeAudience(opts);@@ -611,6 +619,104 @@ function admitNotices(notices: Notice[], opts: DispatchOpts): Notice[] {}}+/**+ * The hidden-tool route inputs for one dispatch caller (F6 and D2 share+ * them): stdio widens its own session when widening is on; an HTTP OAuth+ * client widens its own surface up to the server ceiling unless the brain+ * owner pinned it; the grant (scopes, snapshot, fence) bounds both.+ */+export function toolConnection(opts: DispatchOpts): ToolConnection {+ const render = dispatchRenderContext(opts);+ const http = render.transport === 'http';+ const auth = opts.auth;+ return {+ transport: render.transport,+ surface: opts.surface ?? 'full',+ readOnly: opts.stdioSurface?.readOnly,+ ceiling: http ? opts.surfaceCeiling ?? opts.surface ?? 'full' : 'full',+ canWiden: render.isCallable('request_tools') && (http+ ? auth?.principal?.kind === 'oauth_client' && auth.surfaceSetBy !== 'operator'+ : opts.stdioSurface?.widenAllowed !== false),+ isCallable: render.isCallable,+ grantAllows: op => opAllowedForBoundClient(auth, op) && (!http || operationScopesAllowed(auth?.scopes ?? [], op)),+ };+}++/** Reads whose result never shows the takes table to an agent-facing reader. */+const HIDDEN_TAKES_OPS: ReadonlySet<string> = new Set(['get_page', 'search', 'query']);++/**+ * D2 `hidden_tool_content`: a page read or search that left out takes says+ * so, with the next step this connection can actually take (the+ * hidden-tool route): call takes_list (stdio also lists it), widen with+ * request_tools, or the brain owner's repair. Silent when takes_list is+ * already in this connection's tool list. Never throws.+ */+async function hiddenContentNotices(engine: BrainEngine, name: string, result: unknown, ctx: OperationContext, opts: DispatchOpts): Promise<Notice[]> {+ if (opts.remote === false || !HIDDEN_TAKES_OPS.has(name)) return [];+ try {+ const op = operations.find(o => o.name === 'takes_list');+ const conn = toolConnection(opts);+ const route = hiddenToolRoute(op, conn);+ if (!op || !route) return [];+ if (route.kind === 'callable' && (!opts.isListed || await opts.isListed(op))) return [];+ const { takesHiddenFromResult } = await import('../core/ops/takes.ts');+ const hidden = await takesHiddenFromResult(ctx, name, result);+ if (!hidden) return [];+ const host = route.kind === 'host' && conn.transport === 'http' && opts.auth+ ? (await import('../core/harness/capabilities.ts')).grantRepairAction(await sessionGrantDiagnosis(engine, opts)) : null;+ const what = `the takes on ${hidden.pages[0]}`;+ const fix = hiddenToolNext(op, { tool: op.name, arguments: { page_slug: hidden.pages[0] } }, route, conn, what, host);+ if (route.kind === 'callable') opts.revealTools?.([op.name]);+ return [hiddenTakesNotice(hidden, route.kind, fix)];+ } catch {+ return [];+ }+}++/** A refusal a grant explains: a missing scope or an operation outside the grant's snapshot or fence. */+function refusedByGrant(e: unknown): boolean {+ return e instanceof OperationError && (e.code === 'insufficient_scope' || e.code === 'permission_denied');+}++/**+ * D4 `grant_blocked_operations` on the connection's own authenticated path:+ * the shared capabilities resolver diagnoses the verifier's principal+ * (never a display name) and the notice reaches it once per (principal,+ * transport session); a stateless call with no session id counts once per+ * (principal, grant revision), so three stateless calls get one notice and a+ * rescoped grant is diagnosed afresh. A missing scope is reported only on a+ * refused call. Never throws; a failure delivers nothing.+ */+export async function grantBlockedNotices(engine: BrainEngine, opts: DispatchOpts, refused: boolean): Promise<Notice[]> {+ const auth = opts.auth;+ const principal = auth?.principal;+ if (!auth || !principal || opts.remote === false) return [];+ try {+ const { grantBlockedNotice } = await import('../core/harness/capabilities.ts');+ const notice = grantBlockedNotice(await sessionGrantDiagnosis(engine, opts), { refused });+ return notice && (opts.noticeLedger ?? processNoticeLedger()).claim(`grant_blocked_operations|${grantSessionKey(auth, principal, opts.sessionId)}`) ? [notice] : [];+ } catch {+ return [];+ }+}++/** The D4 session: (principal, transport session), or (principal, grant revision) for a stateless call. */+function grantSessionKey(auth: AuthInfo, principal: NonNullable<AuthInfo['principal']>, sessionId: string | undefined): string {+ const revision = Number.isSafeInteger(auth.grantRevision) ? String(auth.grantRevision) : 'none';+ return `${principal.kind}:${principal.id}|${sessionId ? `session:${sessionId.slice(0, SESSION_ID_MAX_CHARS)}` : `revision:${revision}`}`;+}++/** The shared capabilities resolver's diagnosis for this caller, computed once per D4 session and grant revision. */+async function sessionGrantDiagnosis(engine: BrainEngine, opts: DispatchOpts) {+ const auth = opts.auth!;+ const { resolveGrantDiagnosis } = await import('../core/harness/capabilities.ts');+ const revision = Number.isSafeInteger(auth.grantRevision) ? String(auth.grantRevision) : 'none';+ const compute = () => resolveGrantDiagnosis(auth, engine, opts.config ?? loadConfig() ?? { engine: 'postgres' }, { surfaceCeiling: opts.surfaceCeiling });+ if (!auth.principal) return compute();+ return (opts.noticeLedger ?? processNoticeLedger()).memoize(`grant_diagnosis|${grantSessionKey(auth, auth.principal, opts.sessionId)}|${revision}`, compute);+}+/*** Cat 40 R0: a search/query whose reranker failed counts toward this* session's reranker-degraded calls, and its own `_meta.retrieval` records@@ -771,7 +877,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 unknownToolEnvelope(name, opts);+ return unknownToolEnvelope(name, opts, undefined, await grantBlockedNotices(engine, opts, true));}const op = operations.find(o => o.name === name);@@ -781,7 +887,7 @@ 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 unknownToolEnvelope(name, opts);+ return unknownToolEnvelope(name, opts, undefined, await grantBlockedNotices(engine, opts, true));}// localOnly backstop at the SHARED layer (WP1/D7): localOnly ops reach the@@ -792,7 +898,7 @@ export async function dispatchToolCall(// 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);+ return unknownToolEnvelope(name, opts, undefined, await grantBlockedNotices(engine, opts, true));}// F5: an owner-only op is never listed on MCP; a call gets the exact CLI command.if (op.cliOnly && opts.remote !== false) return errorResult(cliOnlyRefusal(op), opts, { op: name });@@ -981,6 +1087,7 @@ export async function dispatchToolCall(const rerankDegradedCalls = recordRerankDegradation(responseMeta, opts);notices.push(...recallInteropNotices(name, result, responseMeta, safeParams,{ config: ctx.config, transport: dispatchRenderContext(opts).transport, binding: ctx.explicitReadBinding, rerankDegradedCalls }));+ notices.push(...await hiddenContentNotices(engine, name, result, ctx, opts));// Monthly backup-coverage: one AGGREGATE notice per process (counts only —// never a local path or source id). The refresher runs on the stdio// transport ONLY — the WP1/D7 locality axis localOnly ops use; 'http' or@@ -999,6 +1106,7 @@ export async function dispatchToolCall(if (opts.transport === 'stdio' && opts.remote !== false) notices.push(...await mcpOnboardingNotices({ engine, op: name, result, meta: responseMeta, config: ctx.config, render: dispatchRenderContext(opts) }));if (opts.transport === 'stdio' && opts.remote !== false) { const drain = takeFactsDrainNotice(); if (drain) notices.push(drain); } // Lane D facts drainnotices.push(...await sessionSafetyNotices(engine, opts, ctx.config));+ notices.push(...await grantBlockedNotices(engine, opts, false));const out: ToolResult = toolResultWithNotices(result, admitNotices(notices, opts), dispatchRenderContext(opts));if (evidenceBlocks.length > 0) out.content.splice(1, 0, ...evidenceBlocks.map(text => ({ type: 'text' as const, text })));if (opts.transport === 'stdio') {@@ -1034,6 +1142,7 @@ export async function dispatchToolCall(// which redacts raw messages, keeps verbs on their frozen v1 codes, and// never tells a mutating op with an unknown outcome to retry.notices.push(...await sessionSafetyNotices(engine, opts, ctx.config));+ notices.push(...await grantBlockedNotices(engine, opts, refusedByGrant(e)));return errorResult(e, opts, { op: name, mutating: op.mutating === true, idempotent: op.idempotent === true, notices: admitNotices(notices, opts) });}}diff --git a/src/mcp/hidden-tool-hint.ts b/src/mcp/hidden-tool-hint.tsindex c294e98b42..d3f508a90e 100644--- a/src/mcp/hidden-tool-hint.ts+++ b/src/mcp/hidden-tool-hint.ts@@ -1,41 +1,93 @@/**- * F6: the hidden-tool hint on the owner's stdio pipe. A stdio caller that- * names a real tool outside this server's surface (or its read-only access)- * learns that the tool exists and how to reach it. Where `request_tools` is- * callable and session widening is on, the fix is one `request_tools- * {surface: 'full'}` call (no restart, nothing persists); otherwise it is the- * tool's CLI equivalent, relayed to the user. The stdio pipe is the brain+ * F6 + D2: the one hidden-tool decision. `hiddenToolRoute` says how a+ * connection reaches a tool it does not list: it is already callable (name+ * it; stdio reveals it), one `request_tools {surface}` call makes it+ * callable (stdio: this session only, nothing written; HTTP: the client's own+ * surface, within the server ceiling and never past an operator pin), or+ * only the brain host can change that (read-only access, the server surface,+ * the grant). A widen is offered only when the widened connection could+ * actually call the tool: never past `--access read-only`, the force-surface+ * clamp, the grant's snapshot or its scopes.+ *+ * `hiddenToolHint` is F6's unknown_tool hint on the owner's stdio pipe: a+ * stdio caller that names a real tool outside this server's surface learns+ * that the tool exists and how to reach it. The stdio pipe is the brain* owner's own process, so this is not an existence oracle; HTTP keeps the- * opaque unknown_tool envelope.+ * opaque unknown_tool envelope. D2's in-band `next` for content a hidden tool+ * serves (`hiddenToolNext`) uses the same route on every transport.*/-import type { Action } from '../core/agent-output.ts';-import type { Operation } from '../core/operations.ts';+import type { Action, McpCall } from '../core/agent-output.ts';+import type { Operation, OperationMeta } from '../core/ops/contract.ts';import { cliEquivalent } from '../core/ops/cli-equivalent.ts';+import { clampSurface, filterOpsForSurface, isReadOnlyOperation, surfaceWiderThan, type McpSurface } from './surface.ts';const PERSISTENT_ROUTE = 'To keep the full surface for new sessions, set GBRAIN_SURFACE=full in the env of this harness\'s MCP server entry for gbrain '+ '(`claude mcp add gbrain -e GBRAIN_SURFACE=full -- …`, the env table of the Codex server entry, or the plugin\'s GBRAIN_SURFACE setting on launcher installs), '+ 'or re-register the server with `--surface full`. An inherited GBRAIN_SURFACE overrides a pinned --surface.';+/** What the route decision reads about one connection. */+export interface ToolConnection {+ transport?: string;+ /** The surface this connection serves now. */+ surface?: McpSurface;+ /** stdio `--access read-only`: a widen never adds a write tool. */+ readOnly?: boolean;+ /** The widest surface a widen may reach before the force-surface clamp (stdio: full; HTTP: the server ceiling). */+ ceiling?: McpSurface;+ /** `request_tools {surface}` is callable here and this connection may use it (stdio: session widening on; HTTP: an OAuth client not pinned by the operator). */+ canWiden: boolean;+ /** The callability predicate behind tools/list and dispatch for this connection, as it stands now. */+ isCallable: (name: string) => boolean;+ /** Whether the grant itself (scopes, operation snapshot, write fence) allows the tool on any surface. Default: yes. */+ grantAllows?: (op: OperationMeta) => boolean;+}++export type HiddenToolRoute =+ | { kind: 'callable' }+ | { kind: 'widen'; surface: McpSurface }+ | { kind: 'host'; blocker: 'read_only' | 'surface' | 'grant' };++export function hiddenToolRoute(op: OperationMeta | undefined, conn: ToolConnection): HiddenToolRoute | null {+ if (!op || op.cliOnly || (op.localOnly && conn.transport !== 'stdio')) return null;+ if (conn.isCallable(op.name)) return { kind: 'callable' };+ if (conn.grantAllows && !conn.grantAllows(op)) return { kind: 'host', blocker: 'grant' };+ if (conn.readOnly && !isReadOnlyOperation(op)) return { kind: 'host', blocker: 'read_only' };+ const target = clampSurface(conn.ceiling ?? 'full', () => {});+ if (conn.canWiden && surfaceWiderThan(target, conn.surface ?? 'full') && filterOpsForSurface([op], target).length > 0) return { kind: 'widen', surface: target };+ return { kind: 'host', blocker: 'surface' };+}++function argInputs(argv: string[], name: string) {+ return argv.includes('<params_json>') ? { inputs: [{ name: 'params_json', how: `The arguments you passed to ${name}, as one JSON object.` }] } : {};+}+export function hiddenToolHint(op: Operation | undefined,- opts: { transport?: string; remote?: boolean; surface?: string; allowedOps?: ReadonlySet<string> },+ opts: { transport?: string; remote?: boolean; surface?: McpSurface; allowedOps?: ReadonlySet<string>; readOnly?: boolean },canWiden = false,): { suggestion: string; fix: Action } | null {- if (!op || op.localOnly || opts.transport !== 'stdio' || opts.remote === false || !opts.allowedOps || opts.allowedOps.has(op.name)) return null;+ if (!op || opts.transport !== 'stdio' || opts.remote === false || !opts.allowedOps || opts.allowedOps.has(op.name)) return null;+ const surface = opts.surface ?? 'full';+ const route = hiddenToolRoute(op, {+ transport: 'stdio', surface, canWiden, ceiling: 'full',+ // A full-surface stdio session that still hides a tool is a read-only session.+ readOnly: opts.readOnly ?? surface === 'full',+ isCallable: name => opts.allowedOps!.has(name),+ });+ if (!route || route.kind === 'callable') return null;const name = op.name;const argv = cliEquivalent(op);- const surface = opts.surface ?? 'full';- const inputs = argv.includes('<params_json>') ? { inputs: [{ name: 'params_json', how: `The arguments you passed to ${name}, as one JSON object.` }] } : {};- if (surface === 'full') {+ const inputs = argInputs(argv, name);+ if (route.kind === 'host' && route.blocker === 'read_only') {const why = `${name} exists, but this server is read-only (access read-only), so it is not listed. Its CLI equivalent does the same on the brain host; this connection stays read-only.`;return { suggestion: `${why} CLI equivalent: \`${argv.join(' ')}\`.`, fix: { argv, consent: [], actor: 'agent', requires_exclusive: false, why, ...inputs } };}- if (canWiden) {+ if (route.kind === 'widen') {const why = `${name} exists, but this session serves the ${surface} tool surface, which does not include it. `- + `Call request_tools {"surface":"full"} to add it to this session (no restart; nothing is written), then call ${name} by name. ${PERSISTENT_ROUTE}`;+ + `Call request_tools {"surface":"${route.surface}"} to add it to this session (no restart; nothing is written), then call ${name} by name. ${PERSISTENT_ROUTE}`;return {suggestion: `${why} CLI equivalent: \`${argv.join(' ')}\`.`,- fix: { mcp: { tool: 'request_tools', arguments: { surface: 'full' } }, argv, consent: [], actor: 'agent', requires_exclusive: false, why, ...inputs },+ fix: { mcp: { tool: 'request_tools', arguments: { surface: route.surface } }, argv, consent: [], actor: 'agent', requires_exclusive: false, why, ...inputs },};}const why = `${name} exists, but this server runs the ${surface} tool surface, which does not include it, and this session cannot widen it. `@@ -49,3 +101,35 @@ export function hiddenToolHint(},};}++/**+ * D2: the `fix` for content this result left out that `call.tool` serves.+ * Callable → the call itself (`next: run`). Widenable → the `request_tools+ * {surface}` call, then the tool. Otherwise the host-owned repair (`hostFix`,+ * relayed to the user), or on stdio the tool's CLI equivalent. Never names a+ * call the connection's ceiling refuses: the rendered fix drops any MCP call+ * the connection cannot make.+ */+export function hiddenToolNext(op: Operation, call: McpCall, route: HiddenToolRoute, conn: ToolConnection, what: string, hostFix: Action | null): Action | null {+ const name = op.name;+ if (route.kind === 'callable') {+ return { mcp: call, consent: [], actor: 'agent', requires_exclusive: false,+ why: `${name} lists ${what} on this connection; call it with the arguments shown (it may not be in your tool list yet).` };+ }+ if (route.kind === 'widen') {+ const scope = conn.transport === 'stdio' ? 'this session (no restart; nothing is written)' : 'this connection (your client\'s own tool surface, within the server ceiling)';+ return { mcp: { tool: 'request_tools', arguments: { surface: route.surface } }, consent: [], actor: 'agent', requires_exclusive: false,+ why: `${name} lists ${what}, but this connection serves the ${conn.surface ?? 'full'} tool surface, which does not include it. Call request_tools {"surface":"${route.surface}"} to add it to ${scope}, then call ${name} with ${JSON.stringify(call.arguments)}.` };+ }+ if (conn.transport === 'stdio') {+ const base = cliEquivalent(op);+ const argv = base.includes('<params_json>') ? base.map(a => a === '<params_json>' ? JSON.stringify(call.arguments) : a)+ : op.cliHints?.name && base[1] === op.cliHints.name ? [...base, ...Object.entries(call.arguments).flatMap(([k, v]) => [`--${k.replace(/_/g, '-')}`, String(v)])] : base;+ const why = route.blocker === 'read_only'+ ? `${name} lists ${what}, but this connection is read-only and cannot call it; its CLI equivalent does the same on the brain host.`+ : `${name} lists ${what}, but this session cannot add it to its tool surface; its CLI equivalent does the same on the brain host. ${PERSISTENT_ROUTE}`;+ return { argv, consent: [], actor: 'user', requires_exclusive: false, why,+ user_message: `This gbrain connection cannot list ${what}. You can run \`${argv.join(' ')}\` on the brain host.` };+ }+ return hostFix;+}diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex 2d7e9ce9ca..d954bcc592 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -486,7 +486,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpSsurface: session.surface,// WP4 (D2): stdio has no per-client rows; its surface is the ceiling// request_tools bounds its catalog by; its {surface} call widens the session.- surfaceCeiling: session.surface, stdioSurface: session, revealTools: listing.reveal,+ surfaceCeiling: session.surface, stdioSurface: session, revealTools: listing.reveal, isListed: listing.isListed,resultRows,}), dispatchRenderContext);}));diff --git a/src/mcp/surface.ts b/src/mcp/surface.tsindex c32ce47d4c..8ec7925e37 100644--- a/src/mcp/surface.ts+++ b/src/mcp/surface.ts@@ -374,6 +374,11 @@ export function stdioToolListing(advertised: () => Promise<McpSurface | null>, sconst listed = advertisedOps(visible, session.surface, await advertised());return listed.length === visible.length ? visible : visible.filter(op => revealed.has(op.name) || listed.includes(op));},+ /** D2: whether tools/list shows this (callable) tool now. */+ async isListed(op: OperationMeta): Promise<boolean> {+ if (session.surface !== startSurface || revealed.has(op.name)) return true;+ return advertisedOps([op], session.surface, await advertised()).length > 0;+ },reveal(names: string[]): void {const before = revealed.size;for (const name of names) revealed.add(name);diff --git a/test/grant-blocked-notice.test.ts b/test/grant-blocked-notice.test.tsnew file mode 100644index 0000000000..587d433f34--- /dev/null+++ b/test/grant-blocked-notice.test.ts@@ -0,0 +1,191 @@+/**+ * D4 `grant_blocked_operations`: the in-band stale-grant notice on the+ * connection's own authenticated path. Real OAuth grants on PGLite (the+ * verifier's principal, revision and catalog provenance), dispatched the way+ * serve-http resolves a client (effective surface, allow-set = surface ∩+ * snapshot). Counts per blocker, never operation names; once per (principal,+ * session), and once per (principal, grant revision) for stateless calls;+ * nothing widens.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { operations } from '../src/core/operations.ts';+import type { AuthInfo } from '../src/core/operations.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { readClientGrant, rescopeClientGrant, resolveGrantProfile } from '../src/core/grants/service.ts';+import { filterOpsForSurface, minSurface, type McpSurface } from '../src/mcp/surface.ts';+import { dispatchToolCall, type DispatchOpts } from '../src/mcp/dispatch.ts';+import { NoticeLedger } from '../src/core/notice-ledger.ts';+import { NOTICE_CODES } from '../src/core/error-registry.ts';+import { ERROR_CATALOGUE } from '../src/core/error-catalogue.ts';++let engine: PGLiteEngine;+let provider: GBrainOAuthProvider;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+ await engine.putPage('notes/grant-example', { title: 'Grant example', type: 'note', compiled_truth: 'A page.\n' });+}, 60_000);+afterAll(async () => { await engine?.disconnect(); }, 15_000);++type Rendered = { code: string; why: string; fix?: { argv?: string[]; mcp?: unknown; next: string; then?: { argv?: string[] }; verify?: { argv?: string[] } } };+const noticesOf = (r: { _meta?: Record<string, unknown>; content: Array<{ text: string }>; isError?: boolean }): Rendered[] =>+ r.isError ? JSON.parse(r.content[0].text).notices ?? [] : (r._meta?.gbrain_notices as Rendered[] | undefined) ?? [];+const grantNotice = (r: Parameters<typeof noticesOf>[0]) => noticesOf(r).filter(n => n.code === 'grant_blocked_operations');++async function client(name: string, profile: 'memory-writer' | 'memory-reader', patch: Record<string, unknown> = {}) {+ const created = await provider.registerClientManual(name, ['client_credentials'], profile === 'memory-reader' ? 'read' : 'read write', [], 'default',+ undefined, undefined, undefined, resolveGrantProfile({ profile, sourceId: 'default' }));+ if (Object.keys(patch).length) await rescopeClientGrant(engine, created.clientId, patch, { actor: 'test' });+ return created;+}++/** One HTTP connection as serve-http builds it, sharing one notice ledger across calls (the ServeHttpContext ledger). */+async function connect(created: { clientId: string; clientSecret?: string }, ledger = new NoticeLedger(), ceiling: McpSurface = 'full') {+ const token = await provider.exchangeClientCredentials(created.clientId, created.clientSecret!);+ const auth = await provider.verifyAccessToken(token.access_token) as unknown as AuthInfo;+ const surface = minSurface(ceiling, (auth.surface as McpSurface | undefined) ?? ceiling);+ auth.effectiveSurface = surface;+ const callable = filterOpsForSurface(operations.filter(o => !o.localOnly), surface)+ .filter(o => auth.allowedOperations == null || auth.allowedOperations.includes(o.name));+ return (sessionId?: string): DispatchOpts => ({+ remote: true, transport: 'http', sourceId: 'default', auth, surface, surfaceCeiling: ceiling, noticeLedger: ledger,+ allowedOps: new Set(callable.map(o => o.name)), config: { engine: 'pglite' } as any, ...(sessionId ? { sessionId } : {}),+ });+}++const read = (opts: DispatchOpts) => dispatchToolCall(engine, 'get_page', { slug: 'notes/grant-example' }, opts);+const dropFromCatalog = (clientId: string, name: string) => engine.executeRaw(+ `UPDATE oauth_grant_audit SET after_grant = jsonb_set(after_grant, '{catalogProvenance,operations}', (after_grant->'catalogProvenance'->'operations') - $2::text)+ WHERE client_id = $1 AND after_grant->'catalogProvenance' IS NOT NULL`, [clientId, name]);++describe('grant_blocked_operations', () => {+ test('registered as an info notice with a catalogue anchor', () => {+ expect(NOTICE_CODES.grant_blocked_operations.kind).toBe('info');+ expect(ERROR_CATALOGUE.grant_blocked_operations.docs).toBe('docs/guides/repair.md#grant-blocked-operations');+ });++ test('a fresh memory-writer gets no notice and can call put_pages', async () => {+ const opts = await connect(await client('fresh-writer-example', 'memory-writer'));+ expect(grantNotice(await read(opts()))).toEqual([]);+ const r = await dispatchToolCall(engine, 'put_pages', { pages: [] }, opts());+ expect(JSON.parse(r.content[0].text).code).not.toBe('unknown_tool');+ });++ test('an operator-pinned old client is reported, not widened: client pin named, preview then apply, nothing changes', async () => {+ const created = await client('pinned-old-example', 'memory-writer', { surface: 'starter', surfaceSetBy: 'operator' });+ const opts = await connect(created);+ const [n] = grantNotice(await read(opts()));+ expect(n.why).toContain('its stored starter tool surface, which the brain owner pinned');+ expect(n.why).not.toContain('operation snapshot');+ expect(n.fix!.next).toBe('tell_user_to_run');+ expect(n.fix!.mcp).toBeUndefined();+ expect(n.fix!.argv).toEqual(['gbrain', 'auth', 'rescope', '--client', created.clientId, '--surface', 'full', '--dry-run']);+ expect(n.fix!.then!.argv).toEqual(['gbrain', 'auth', 'rescope', '--client', created.clientId, '--surface', 'full']);+ expect(n.fix!.verify!.argv).toEqual(['gbrain', 'doctor', '--only', 'grant_new_ops_available', '--json']);+ const after = await readClientGrant(engine, created.clientId);+ expect(after.surface).toBe('starter');+ expect(after.surfaceSetBy).toBe('operator');+ });++ test('blocked by both snapshot and pin: both named, counts only, one command lifting both', async () => {+ const base = resolveGrantProfile({ profile: 'memory-writer', sourceId: 'default' }).allowedOperations!;+ const created = await client('both-example', 'memory-writer', { allowedOperations: base.filter(op => op !== 'put_pages'), surface: 'starter', surfaceSetBy: 'operator' });+ const r = await read((await connect(created))());+ const [n] = grantNotice(r);+ expect(n.why).toContain('its operation snapshot (1)');+ expect(n.why).toContain('its stored starter tool surface');+ expect(n.fix!.argv).toEqual(['gbrain', 'auth', 'rescope', '--client', created.clientId, '--operations', '<OPERATIONS>', '--surface', 'full', '--dry-run']);+ expect(JSON.stringify(noticesOf(r))).not.toContain('put_pages');+ });++ test('a deliberately restricted client stays unable to call put_pages, and the refusal says why', async () => {+ const base = resolveGrantProfile({ profile: 'memory-writer', sourceId: 'default' }).allowedOperations!;+ const created = await client('restricted-example', 'memory-writer', { allowedOperations: base.filter(op => op !== 'put_pages') });+ const opts = await connect(created);+ const r = await dispatchToolCall(engine, 'put_pages', { pages: [] }, opts());+ expect(r.isError).toBe(true);+ expect(JSON.parse(r.content[0].text).code).toBe('unknown_tool');+ const [n] = grantNotice(r);+ expect(n.why).toContain('its operation snapshot (1)');+ expect(n.why).toContain('all existed when the snapshot was written');+ expect(JSON.stringify(n)).not.toContain('put_pages');+ expect((await readClientGrant(engine, created.clientId)).allowedOperations).not.toContain('put_pages');+ });++ test('a memory-reader stays unable to call put_pages; the refusal names the missing write scope, a plain read says nothing', async () => {+ const opts = await connect(await client('reader-example', 'memory-reader'));+ expect(grantNotice(await read(opts('reader-session-a')))).toEqual([]);+ const r = await dispatchToolCall(engine, 'put_pages', { pages: [] }, opts('reader-session-a'));+ expect(r.isError).toBe(true);+ const [n] = grantNotice(r);+ expect(n.why).toContain('This grant has no write scope');+ expect(n.fix).toBeUndefined();+ });++ test('legacy grant (no catalog provenance): "original intent unknown"; post-D4 grant: "predates"', async () => {+ const base = resolveGrantProfile({ profile: 'memory-writer', sourceId: 'default' }).allowedOperations!;+ const legacy = await client('legacy-wording-example', 'memory-writer', { allowedOperations: base.filter(op => op !== 'put_pages') });+ await engine.executeRaw("UPDATE oauth_grant_audit SET after_grant = after_grant - 'catalogProvenance' WHERE client_id = $1", [legacy.clientId]);+ const [l] = grantNotice(await read((await connect(legacy))()));+ expect(l.why).toContain("This grant's snapshot excludes 1 currently eligible operation; original intent unknown.");+ expect(l.why).not.toContain('predates');++ const recent = await client('predates-wording-example', 'memory-writer', { allowedOperations: base.filter(op => op !== 'put_pages') });+ await dropFromCatalog(recent.clientId, 'put_pages');+ const [p] = grantNotice(await read((await connect(recent))()));+ expect(p.why).toContain('This grant predates 1 currently eligible operation');+ expect(p.why).not.toContain('original intent unknown');+ });++ test('a writer grant against a catalog with a new admin-only operation reports nothing (count 0)', async () => {+ const created = await client('admin-op-example', 'memory-writer');+ const adminOp = operations.find(op => !op.localOnly && op.scope === 'admin')!.name;+ await dropFromCatalog(created.clientId, adminOp);+ const opts = await connect(created);+ expect(grantNotice(await read(opts()))).toEqual([]);+ const refused = await dispatchToolCall(engine, adminOp, {}, opts());+ expect(refused.isError).toBe(true);+ expect(grantNotice(refused)).toEqual([]);+ });++ test('three stateless HTTP calls by one principal: exactly one notice; a rescope (new revision) is diagnosed afresh', async () => {+ const created = await client('stateless-example', 'memory-writer', { surface: 'starter', surfaceSetBy: 'operator' });+ const ledger = new NoticeLedger();+ let total = 0;+ for (let i = 0; i < 3; i++) total += grantNotice(await read((await connect(created, ledger))())).length;+ expect(total).toBe(1);+ const base = resolveGrantProfile({ profile: 'memory-writer', sourceId: 'default' }).allowedOperations!;+ await rescopeClientGrant(engine, created.clientId, { allowedOperations: base.filter(op => op !== 'put_pages') }, { actor: 'test' });+ let after = 0;+ for (let i = 0; i < 3; i++) after += grantNotice(await read((await connect(created, ledger))())).length;+ expect(after).toBe(1);+ });++ test('sessioned calls: one notice per (principal, session)', async () => {+ const created = await client('sessioned-example', 'memory-writer', { surface: 'starter', surfaceSetBy: 'operator' });+ const opts = await connect(created);+ const counts = [];+ for (const session of ['s1', 's1', 's2', 's1', 's2']) counts.push(grantNotice(await read(opts(session))).length);+ expect(counts).toEqual([1, 0, 1, 0, 0]);+ });++ test('a server ceiling alone: named, and the fix is the read-only doctor check (no grant change lifts it)', async () => {+ const created = await client('ceiling-example', 'memory-writer');+ const r = await read((await connect(created, new NoticeLedger(), 'starter'))());+ const [n] = grantNotice(r);+ expect(n.why).toContain("the server's starter tool surface");+ expect(n.fix!.next).toBe('tell_user_to_run');+ expect(n.fix!.argv!.slice(0, 5)).toEqual(['gbrain', 'doctor', '--only', 'grant_new_ops_available', '--json']);+ expect(n.fix!.then).toBeUndefined();+ });++ test('stdio and the local CLI never get it (no verified principal)', async () => {+ const r = await dispatchToolCall(engine, 'get_page', { slug: 'notes/grant-example' }, { remote: true, transport: 'stdio', sourceId: 'default', noticeLedger: new NoticeLedger() });+ expect(grantNotice(r)).toEqual([]);+ });+});diff --git a/test/hidden-tool-hint.test.ts b/test/hidden-tool-hint.test.tsindex 80485750da..079557fa60 100644--- a/test/hidden-tool-hint.test.ts+++ b/test/hidden-tool-hint.test.ts@@ -5,13 +5,22 @@* is callable and session widening is on, else the CLI equivalent relayed to* the user with the persistent routes (`tell_user_to_run`). Read-only access* never offers a widen; HTTP stays opaque.+ *+ * D2 reuses the same route (`hiddenToolRoute`) on every transport for+ * content a hidden tool serves: the hidden-takes scenario runs through the+ * installed configurations below, and every `next` a notice emits must be+ * callable on that connection (and, where it is an MCP call, succeed).*/-import { describe, expect, test } from 'bun:test';+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { operations } from '../src/core/operations.ts';-import { allowedOpNames, isReadOnlyOperation } from '../src/mcp/surface.ts';-import { hiddenToolHint } from '../src/mcp/hidden-tool-hint.ts';-import { dispatchRenderContext } from '../src/mcp/dispatch.ts';+import type { AuthInfo } from '../src/core/operations.ts';+import { allowedOpNames, createStdioSurfaceState, filterOpsForSurface, isReadOnlyOperation, stdioToolListing, type McpSurface } from '../src/mcp/surface.ts';+import { hiddenToolHint, hiddenToolRoute } from '../src/mcp/hidden-tool-hint.ts';+import { dispatchRenderContext, dispatchToolCall, toolConnection, type DispatchOpts } from '../src/mcp/dispatch.ts';import { renderAction } from '../src/core/agent-output.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { NoticeLedger } from '../src/core/notice-ledger.ts';+import { resolveGrantProfile } from '../src/core/grants/profiles.ts';const op = (name: string) => operations.find(o => o.name === name)!;const starter = allowedOpNames(operations, 'starter');@@ -52,9 +61,239 @@ describe('hidden-tool hint', () => {expect(hint.fix.why).toContain('this connection stays read-only');});+ test('read-only access at starter never offers a widen for a write tool (the widened session still could not call it)', () => {+ const roStarter = new Set([...starter].filter(name => isReadOnlyOperation(op(name))));+ const hint = hiddenToolHint(op('put_pages'), { transport: 'stdio', remote: true, surface: 'starter', allowedOps: roStarter, readOnly: true }, true)!;+ expect(hint.fix.mcp).toBeUndefined();+ expect(hint.fix.why).toContain('this connection stays read-only');+ });++ test('GBRAIN_MCP_FORCE_SURFACE=starter: no widen past the clamp', () => {+ const prev = process.env.GBRAIN_MCP_FORCE_SURFACE;+ process.env.GBRAIN_MCP_FORCE_SURFACE = 'starter';+ try {+ const { hint, fix } = rendered(stdio(starter, 'starter'), true);+ expect(fix.mcp).toBeUndefined();+ expect(hint.suggestion).toContain('cannot widen it');+ } finally {+ if (prev === undefined) delete process.env.GBRAIN_MCP_FORCE_SURFACE; else process.env.GBRAIN_MCP_FORCE_SURFACE = prev;+ }+ });+test('HTTP, the local CLI and visible tools get no hint', () => {expect(hiddenToolHint(op('get_health'), { transport: 'http', remote: true, surface: 'starter', allowedOps: starter }, true)).toBeNull();expect(hiddenToolHint(op('get_health'), { transport: 'stdio', remote: false, surface: 'starter', allowedOps: starter }, true)).toBeNull();expect(hiddenToolHint(op('search'), stdio(starter, 'starter'), true)).toBeNull();});});++// ---------------------------------------------------------------------------+// D2: the hidden-takes scenario through installed configurations. A page with+// world takes is read with get_page (which never shows the takes table); the+// result's `hidden_tool_content` notice must offer a next step this+// connection can take, and every MCP call it names must dispatch and work.+// ---------------------------------------------------------------------------++describe('D2 hidden-takes scenario, installed configurations', () => {+ const SLUG = 'companies/acme-example';+ let engine: PGLiteEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ const page = await engine.putPage(SLUG, { title: 'Acme', type: 'company', compiled_truth: 'Acme sells widgets.\n' });+ await engine.addTakesBatch([+ { page_id: page.id, row_num: 1, claim: 'Renewal ARR forecast 1.2M', kind: 'take', holder: 'world', weight: 0.8 },+ { page_id: page.id, row_num: 2, claim: 'Private hunch about churn', kind: 'hunch', holder: 'brain', weight: 0.3 },+ ]);+ }, 60_000);+ afterAll(async () => { await engine?.disconnect(); }, 15_000);++ type Notices = Array<{ code: string; why: string; fix?: { mcp?: { tool: string; arguments: Record<string, unknown> }; next: string; argv?: string[]; then?: unknown } }>;+ const noticesOf = (r: { _meta?: Record<string, unknown>; content: Array<{ text: string }>; isError?: boolean }): Notices =>+ r.isError ? JSON.parse(r.content[0].text).notices ?? [] : (r._meta?.gbrain_notices as Notices | undefined) ?? [];+ const hiddenNotice = (r: Parameters<typeof noticesOf>[0]) => noticesOf(r).find(n => n.code === 'hidden_tool_content');++ /** A stdio server as `gbrain serve` builds it: one session surface, a listing over the advertised surface, a reveal hook. */+ function stdioConnection(opts: { surface: McpSurface; advertised?: McpSurface | null; readOnly?: boolean; widenAllowed?: boolean }) {+ const reveals: string[][] = [];+ const listChanged = { count: 0 };+ const session = createStdioSurfaceState(operations, { surface: opts.surface, source: 'flag', readOnly: opts.readOnly ?? false });+ session.widenAllowed = opts.widenAllowed ?? true;+ const listing = stdioToolListing(async () => opts.advertised ?? null, session, { sendToolListChanged: async () => { listChanged.count++; } });+ const dispatchOpts = (): DispatchOpts => ({+ remote: true, transport: 'stdio', sourceId: 'default', takesHoldersAllowList: ['world'],+ ...(session.allowedOps ? { allowedOps: session.allowedOps } : {}), surface: session.surface, surfaceCeiling: session.surface,+ stdioSurface: session, revealTools: names => { reveals.push(names); listing.reveal(names); }, isListed: listing.isListed,+ noticeLedger: new NoticeLedger(),+ });+ return { session, listing, reveals, listChanged, dispatchOpts };+ }++ /** Every MCP call a notice names must pass dispatch's callability gate (never unknown_tool) and succeed. */+ async function assertNextCallable(n: Notices[number] | undefined, opts: () => DispatchOpts): Promise<string | null> {+ if (!n?.fix?.mcp) return null;+ expect(dispatchRenderContext(opts()).isCallable(n.fix.mcp.tool)).toBe(true);+ const r = await dispatchToolCall(engine, n.fix.mcp.tool, n.fix.mcp.arguments, opts());+ expect(r.isError, r.content[0]?.text).toBeFalsy();+ return n.fix.mcp.tool;+ }++ async function takesVisibleBy(opts: () => DispatchOpts): Promise<string[]> {+ const r = await dispatchToolCall(engine, 'takes_list', { page_slug: SLUG }, opts());+ expect(r.isError, r.content[0]?.text).toBeFalsy();+ return (JSON.parse(r.content[0].text) as Array<{ claim: string }>).map(t => t.claim);+ }++ test('callable starter (stdio --surface starter): next is request_tools {surface:"full"}; after it takes_list works', async () => {+ const c = stdioConnection({ surface: 'starter' });+ const n = hiddenNotice(await dispatchToolCall(engine, 'get_page', { slug: SLUG }, c.dispatchOpts()))!;+ expect(n.why).toContain('leaves out 1 take');+ expect(n.why).not.toContain('Private hunch');+ expect(n.fix!.mcp).toEqual({ tool: 'request_tools', arguments: { surface: 'full' } });+ expect(n.fix!.next).toBe('run');+ expect(await assertNextCallable(n, c.dispatchOpts)).toBe('request_tools');+ expect(await takesVisibleBy(c.dispatchOpts)).toEqual(['Renewal ARR forecast 1.2M']);+ });++ test('callable full, advertised starter: next is the takes_list call itself, stdio lists it (tools/list_changed)', async () => {+ const c = stdioConnection({ surface: 'full', advertised: 'starter' });+ const n = hiddenNotice(await dispatchToolCall(engine, 'get_page', { slug: SLUG }, c.dispatchOpts()))!;+ expect(n.fix!.mcp).toEqual({ tool: 'takes_list', arguments: { page_slug: SLUG } });+ expect(n.fix!.next).toBe('run');+ expect(c.reveals).toEqual([['takes_list']]);+ expect(c.listChanged.count).toBe(1);+ expect(await assertNextCallable(n, c.dispatchOpts)).toBe('takes_list');+ expect(hiddenNotice(await dispatchToolCall(engine, 'get_page', { slug: SLUG }, c.dispatchOpts()))).toBeUndefined();+ });++ test('a client that ignores tools/list_changed still calls the named tool by name', async () => {+ const c = stdioConnection({ surface: 'full', advertised: 'starter' });+ c.listing.reveal = () => {};+ const n = hiddenNotice(await dispatchToolCall(engine, 'get_page', { slug: SLUG }, c.dispatchOpts()))!;+ expect(c.listChanged.count).toBe(0);+ expect(await assertNextCallable(n, c.dispatchOpts)).toBe('takes_list');+ const widen = stdioConnection({ surface: 'starter' });+ const w = hiddenNotice(await dispatchToolCall(engine, 'get_page', { slug: SLUG }, widen.dispatchOpts()))!;+ expect(await assertNextCallable(w, widen.dispatchOpts)).toBe('request_tools');+ expect(await takesVisibleBy(widen.dispatchOpts)).toEqual(['Renewal ARR forecast 1.2M']);+ });++ test('full (callable and advertised): takes_list is listed, so no notice', async () => {+ const c = stdioConnection({ surface: 'full' });+ expect(hiddenNotice(await dispatchToolCall(engine, 'get_page', { slug: SLUG }, c.dispatchOpts()))).toBeUndefined();+ });++ test('verbs: get_page and request_tools are outside it, so nothing is read and no tool is named', async () => {+ const c = stdioConnection({ surface: 'verbs' });+ expect(c.session.allowedOps!.has('get_page')).toBe(false);+ expect(dispatchRenderContext(c.dispatchOpts()).isCallable('request_tools')).toBe(false);+ const r = await dispatchToolCall(engine, 'get_page', { slug: SLUG }, c.dispatchOpts());+ expect(r.isError).toBe(true);+ expect(hiddenNotice(r)).toBeUndefined();+ expect(hiddenToolRoute(op('takes_list'), toolConnection(c.dispatchOpts()))).toEqual({ kind: 'host', blocker: 'surface' });+ });++ test('verbs read: search on verbs never names a tool verbs cannot call', async () => {+ const c = stdioConnection({ surface: 'verbs' });+ for (const tool of ['search', 'query', 'get_page']) {+ const r = await dispatchToolCall(engine, tool, tool === 'get_page' ? { slug: SLUG } : { query: 'Acme widgets' }, c.dispatchOpts());+ for (const n of noticesOf(r)) if (n.fix?.mcp) expect(dispatchRenderContext(c.dispatchOpts()).isCallable(n.fix.mcp.tool)).toBe(true);+ }+ });++ test('read-only stdio grant (--access read-only): request_tools is not callable there, so the CLI equivalent, never a widen', async () => {+ const c = stdioConnection({ surface: 'starter', readOnly: true });+ expect(dispatchRenderContext(c.dispatchOpts()).isCallable('request_tools')).toBe(false);+ const n = hiddenNotice(await dispatchToolCall(engine, 'get_page', { slug: SLUG }, c.dispatchOpts()))!;+ expect(n.fix!.mcp).toBeUndefined();+ expect(n.fix!.next).toBe('tell_user_to_run');+ expect(n.fix!.argv!.slice(0, 4)).toEqual(['gbrain', 'takes-list', '--page-slug', SLUG]);+ const full = stdioConnection({ surface: 'full', readOnly: true });+ expect(hiddenNotice(await dispatchToolCall(engine, 'get_page', { slug: SLUG }, full.dispatchOpts()))).toBeUndefined();+ expect(await takesVisibleBy(full.dispatchOpts)).toEqual(['Renewal ARR forecast 1.2M']);+ });++ test('session widening off: the CLI equivalent, never request_tools', async () => {+ const c = stdioConnection({ surface: 'starter', widenAllowed: false });+ const n = hiddenNotice(await dispatchToolCall(engine, 'get_page', { slug: SLUG }, c.dispatchOpts()))!;+ expect(n.fix!.mcp).toBeUndefined();+ expect(n.fix!.next).toBe('tell_user_to_run');+ });++ /** An OAuth client as serve-http resolves it: effective surface, allow-set from surface ∩ snapshot. */+ function httpOpts(auth: Partial<AuthInfo>, ceiling: McpSurface = 'full'): () => DispatchOpts {+ const ledger = new NoticeLedger();+ const snapshot = auth.allowedOperations ?? null;+ const surface = (auth.surface && ['verbs', 'starter', 'full'].includes(auth.surface) ? auth.surface : ceiling) as McpSurface;+ const callable = filterOpsForSurface(operations.filter(o => !o.localOnly), surface).filter(o => !snapshot || snapshot.includes(o.name));+ const full: AuthInfo = { token: 't', clientId: 'gbrain_cl_hidden_example', clientName: 'hidden-example', scopes: ['read'], expiresAt: 1,+ principal: { kind: 'oauth_client', id: 'gbrain_cl_hidden_example' }, sourceId: 'default', allowedSources: ['default'], grantRevision: 3,+ effectiveSurface: surface, ...auth } as AuthInfo;+ return () => ({ remote: true, transport: 'http', sourceId: 'default', takesHoldersAllowList: ['world'], auth: full, surface, surfaceCeiling: ceiling,+ allowedOps: new Set(callable.map(o => o.name)), noticeLedger: ledger, config: { engine: 'pglite' } as any });+ }+ const readerSnapshot = () => resolveGrantProfile({ profile: 'memory-reader', sourceId: 'default' }).allowedOperations!;++ test('pinned HTTP client (operator pinned starter): the owner\'s repair, relayed; no MCP call', async () => {+ const opts = httpOpts({ surface: 'starter', surfaceSetBy: 'operator', allowedOperations: readerSnapshot() });+ expect(toolConnection(opts()).canWiden).toBe(false);+ const r = await dispatchToolCall(engine, 'get_page', { slug: SLUG }, opts());+ const n = hiddenNotice(r)!;+ expect(n.fix!.mcp).toBeUndefined();+ expect(n.fix!.next).toBe('tell_user_to_run');+ expect(n.fix!.argv).toEqual(['gbrain', 'auth', 'rescope', '--client', 'gbrain_cl_hidden_example', '--surface', 'full', '--dry-run']);+ const grant = noticesOf(r).find(x => x.code === 'grant_blocked_operations')!;+ expect(grant.why).toContain('which the brain owner pinned');+ expect(grant.fix!.next).toBe('tell_user_to_run');+ for (const x of noticesOf(r)) expect(x.fix?.mcp).toBeUndefined();+ });++ test('unpinned HTTP client on starter: next is request_tools {surface:"full"}, callable on that connection', async () => {+ const opts = httpOpts({ surface: 'starter', surfaceSetBy: 'self', allowedOperations: readerSnapshot() });+ const n = hiddenNotice(await dispatchToolCall(engine, 'get_page', { slug: SLUG }, opts()))!;+ expect(n.fix!.mcp).toEqual({ tool: 'request_tools', arguments: { surface: 'full' } });+ expect(dispatchRenderContext(opts()).isCallable('request_tools')).toBe(true);+ const r = await dispatchToolCall(engine, 'request_tools', { surface: 'full', dry_run: true }, opts());+ expect(r.isError, r.content[0].text).toBeFalsy();+ });++ test('HTTP server ceiling starter: no widen past the ceiling, no MCP call', async () => {+ const opts = httpOpts({ surface: null as any, allowedOperations: null }, 'starter');+ const n = hiddenNotice(await dispatchToolCall(engine, 'get_page', { slug: SLUG }, opts()))!;+ expect(n.fix?.mcp).toBeUndefined();+ });++ test('a snapshot that excludes takes_list: never request_tools (the widened surface still could not call it)', async () => {+ const opts = httpOpts({ surface: 'starter', surfaceSetBy: 'self', allowedOperations: readerSnapshot().filter(n => n !== 'takes_list') });+ expect(hiddenToolRoute(op('takes_list'), toolConnection(opts()))).toEqual({ kind: 'host', blocker: 'grant' });+ const n = hiddenNotice(await dispatchToolCall(engine, 'get_page', { slug: SLUG }, opts()))!;+ expect(n.fix?.mcp).toBeUndefined();+ expect(n.fix!.next).toBe('tell_user_to_run');+ });++ test('HTTP callable but advertised starter (P8 arm): the takes_list call, no reveal on HTTP', async () => {+ const base = httpOpts({ surface: null as any, allowedOperations: null });+ const opts = () => ({ ...base(), isListed: async () => false });+ const n = hiddenNotice(await dispatchToolCall(engine, 'get_page', { slug: SLUG }, opts()))!;+ expect(await assertNextCallable(n, opts)).toBe('takes_list');+ });++ test('a holder allow-list without world: nothing visible is hidden, so no notice', async () => {+ const c = stdioConnection({ surface: 'starter' });+ const opts = () => ({ ...c.dispatchOpts(), takesHoldersAllowList: ['nobody-example'] });+ expect(hiddenNotice(await dispatchToolCall(engine, 'get_page', { slug: SLUG }, opts()))).toBeUndefined();+ });++ test('search and query name the result\'s take-bearing page', async () => {+ const c = stdioConnection({ surface: 'starter' });+ for (const tool of ['search', 'query']) {+ const r = await dispatchToolCall(engine, tool, { query: 'Acme widgets' }, c.dispatchOpts());+ const rows = JSON.parse(r.content[0].text);+ if (!Array.isArray(rows) || !rows.some((row: { slug?: string }) => row.slug === SLUG)) continue;+ const n = hiddenNotice(r)!;+ expect(n.why).toContain(SLUG);+ expect(n.fix!.mcp!.tool).toBe('request_tools');+ }+ });+});diff --git a/test/notice-ledger.test.ts b/test/notice-ledger.test.tsindex f3e6822f92..1e32d4a66f 100644--- a/test/notice-ledger.test.ts+++ b/test/notice-ledger.test.ts@@ -93,3 +93,22 @@ describe('mute_notice op', () => {}});});++describe('claim, memoize and self-deduped codes (D4)', () => {+ test('claim is true once per key; memoize computes once per key', async () => {+ const ledger = new NoticeLedger();+ expect([ledger.claim('a'), ledger.claim('a'), ledger.claim('b')]).toEqual([true, false, true]);+ let calls = 0;+ const compute = async () => ++calls;+ expect([await ledger.memoize('k', compute), await ledger.memoize('k', compute), await ledger.memoize('j', compute)]).toEqual([1, 1, 2]);+ });++ test('a self-deduped code skips admit\'s per-code dedupe but still honors mute', () => {+ const ledger = new NoticeLedger();+ const n = { code: 'grant_blocked_operations', kind: 'info' as const, why: 'w' };+ const audience = { transport: 'http' as const, principal: 'p' };+ expect(ledger.admit([n], audience)).toHaveLength(1);+ expect(ledger.admit([n], audience)).toHaveLength(1);+ expect(ledger.admit([n], audience, new Set(['grant_blocked_operations']))).toHaveLength(0);+ });+});diff --git a/test/serve-http-mcp-dispatch-context.serial.test.ts b/test/serve-http-mcp-dispatch-context.serial.test.tsindex c5f280281d..f973d08e00 100644--- a/test/serve-http-mcp-dispatch-context.serial.test.ts+++ b/test/serve-http-mcp-dispatch-context.serial.test.ts@@ -88,7 +88,7 @@ async function rpc(base: string, token: string, method: string, params?: unknownreturn JSON.parse(dataLine ? dataLine.slice('data:'.length) : text).result;}-const FULL_SURFACE_KEYS = ['auth', 'logger', 'metaHook', 'noticeLedger', 'remote', 'resultRows', 'sourceId', 'surface', 'surfaceCeiling', 'takesHoldersAllowList', 'transport'];+const FULL_SURFACE_KEYS = ['auth', 'isListed', 'logger', 'metaHook', 'noticeLedger', 'remote', 'resultRows', 'sourceId', 'surface', 'surfaceCeiling', 'takesHoldersAllowList', 'transport'];describe('POST /mcp dispatch context', () => {test('full surface: remote http dispatch with the verified auth and token source scope', async () => {