Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

perf(mcp): stdio serve lists tools from a generated operation manifest and boots engine dependents after the handshake

time-attackc33963d0eac0
diff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.md
index 32699a23b0..15750ca251 100644
--- a/docs/architecture/key-files/core-minions-2.md
+++ b/docs/architecture/key-files/core-minions-2.md
@@ -16,7 +16,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/minions/tool-write-identity.ts` — Binds a journal mutation to the persisted subagent execution coordinates with a deterministic UUIDv8 before dispatch. Legacy, gateway and oneshot replay preserve the same logical request across process restart; explicit caller IDs remain authoritative. `awaitCommittedToolWrite(job, toolName, dispatch)` wraps every subagent tool dispatch (legacy loop and resume, gateway execute and resume reconciliation, oneshot write loop and recovery): while the write is admitted but still pending it replays the same request ID through `replayWhilePending` (no model call, nothing new admitted) until the write is terminal, the job's signal aborts (the pause ends and the last pending error, receipt included, is rethrown), or the job deadline is closer than `WIRE_WRITE_WAIT_MAX_MS` plus `WRITE_ADMISSION_HEADROOM_MS` (45 s); a job without a deadline replays for the `MaintenanceWriteWait` base (30 s). Only then does the write leave the handler as `write_pending`, so a write that never commits holds the job (and a serial dream drain behind it) until that point. A terminal `failed` receipt and non-mutation tools are never replayed. Pending receipts leave tool ledgers pending for retry and never count as written pages. Pinned by `test/subagent-handler.test.ts`, `test/minions/subagent-pending-write-runners.test.ts`, `test/minions/subagent-oneshot.test.ts` and `test/e2e/subagent-gateway-resume-reconciliation.test.ts`.
-- `src/core/minions/tools/brain-allowlist.ts` — derives the subagent tool registry from `src/core/operations.ts` (13-name allow-list, size pinned by `test/brain-allowlist.test.ts`). Attachment tools `file_list` and `file_url` are excluded. Registry construction and execution reject every `localOnly` operation; `selectAllowedTools` rejects malformed bindings and preserves explicit empty lists as no tools. Includes `add_timeline_entry` (the canonical timeline write), fenced server-side by the same `enforceSubagentSlugFence` policy as `put_page`. By default `put_page` schema is namespace-wrapped per subagent (`^wiki/agents/<subagentId>/.+`). When `BuildBrainToolsOpts.allowedSlugPrefixes` is set, the put_page schema describes the prefix list to the model and the OperationContext is threaded with `allowedSlugPrefixes` — trusted local jobs receive these from the submitter; remote-owned jobs receive the grant intersection plus `delegatedAuth`. Their per-call operation contexts carry the verified OAuth owner principal and current operation/source grant intersection into durable requests, and retain remote visibility policy, without requiring direct read/write scopes for independently bound delegated tools. `BuildBrainToolsOpts.deferEmbeds` (server-side-only, set by the oneshot runner for its programmatic writes; never hydrated from any wire payload) threads `OperationContext.deferEmbeds` so put_page defers chunk embeddings for the phase-end backfill. Allow-list includes `get_recent_salience` + `find_anomalies` but deliberately NOT `get_recent_transcripts` (all subagent calls run `ctx.remote === true` and the trust gate rejects remote callers, so it would always reject; the cycle synthesize phase calls `discoverTranscripts` directly instead). `paramsToInputSchema()` consumes `paramDefToSchema` from `src/mcp/tool-defs.ts`; required-aggregation at the tool-def level stays here (the shared helper is per-param). `execute()` runs the same `validateParams` the MCP dispatchers use before the op handler, so a call that omits a required parameter (or sends the wrong type / an unknown enum value) fails with `<tool>: Missing required parameter: <name>` the model can act on, instead of a handler crash. `putPageRejection` classifies legacy rejected import envelopes for subagent accounting; actual persistence errors keep the typed receipt contract. Scoped model-authored type normalization is performed by `persistence/page-input.ts` only after durable existing-request lookup, so registry execution never rewrites a replay using a newer schema pack.
+- `src/core/minions/tools/brain-allowlist.ts` — derives the subagent tool registry from `src/core/operations.ts` (13-name allow-list in the handler-free `brain-tool-allowlist.ts`, which `src/mcp/surface.ts` reads, size pinned by `test/brain-allowlist.test.ts`). Attachment tools `file_list` and `file_url` are excluded. Registry construction and execution reject every `localOnly` operation; `selectAllowedTools` rejects malformed bindings and preserves explicit empty lists as no tools. Includes `add_timeline_entry` (the canonical timeline write), fenced server-side by the same `enforceSubagentSlugFence` policy as `put_page`. By default `put_page` schema is namespace-wrapped per subagent (`^wiki/agents/<subagentId>/.+`). When `BuildBrainToolsOpts.allowedSlugPrefixes` is set, the put_page schema describes the prefix list to the model and the OperationContext is threaded with `allowedSlugPrefixes` — trusted local jobs receive these from the submitter; remote-owned jobs receive the grant intersection plus `delegatedAuth`. Their per-call operation contexts carry the verified OAuth owner principal and current operation/source grant intersection into durable requests, and retain remote visibility policy, without requiring direct read/write scopes for independently bound delegated tools. `BuildBrainToolsOpts.deferEmbeds` (server-side-only, set by the oneshot runner for its programmatic writes; never hydrated from any wire payload) threads `OperationContext.deferEmbeds` so put_page defers chunk embeddings for the phase-end backfill. Allow-list includes `get_recent_salience` + `find_anomalies` but deliberately NOT `get_recent_transcripts` (all subagent calls run `ctx.remote === true` and the trust gate rejects remote callers, so it would always reject; the cycle synthesize phase calls `discoverTranscripts` directly instead). `paramsToInputSchema()` consumes `paramDefToSchema` from `src/mcp/tool-defs.ts`; required-aggregation at the tool-def level stays here (the shared helper is per-param). `execute()` runs the same `validateParams` the MCP dispatchers use before the op handler, so a call that omits a required parameter (or sends the wrong type / an unknown enum value) fails with `<tool>: Missing required parameter: <name>` the model can act on, instead of a handler crash. `putPageRejection` classifies legacy rejected import envelopes for subagent accounting; actual persistence errors keep the typed receipt contract. Scoped model-authored type normalization is performed by `persistence/page-input.ts` only after durable existing-request lookup, so registry execution never rewrites a replay using a newer schema pack.
- `src/core/minions/transcript.ts` — renders `subagent_messages` + `subagent_tool_executions` to markdown. Tool rows splice under their owning assistant `tool_use` by `(message_idx, tool_use_id)` — raw provider tool ids may repeat across turns, so `tool_use_id` alone is not an identity; echoed `tool_result` blocks check ownership against the nearest preceding assistant turn's key. UTF-8-safe truncation; unknown block types fall through to fenced JSON.
diff --git a/docs/architecture/key-files/entrypoints-and-docs.md b/docs/architecture/key-files/entrypoints-and-docs.md
index 23cc7cfa19..cff0031673 100644
--- a/docs/architecture/key-files/entrypoints-and-docs.md
+++ b/docs/architecture/key-files/entrypoints-and-docs.md
@@ -127,6 +127,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `scripts/lib/cli-pipeline.ts` — flattens `handleCliOnly` (inlining `@cliPipelineStage` functions) and reads the command table by AST, for the W0 dispatch-shape extractor (`test/helpers/cli-dispatch-extract.ts`) and `scripts/generate-flag-registry.ts`.
+- `src/core/operation-manifest.generated.ts` + `scripts/build-operation-manifest.ts` (`bun run build:operation-manifest`, in `regen:all`) — every operation in `src/core/operations.ts` minus its handler, in registry order (`OperationMeta` in `src/core/ops/contract.ts`). `gbrain serve` (stdio initialize/tools/list, surface and publish-gate filtering, skill-resource permission checks) and the CLI dispatcher (`src/cli/op-manifest.ts`: command, alias, flag and help lookup plus the A1 fix-routing registration) read it, so neither loads the handler graph until an op runs. Freshness, equality with the live registry, and the absence of `operations.ts`/`dispatch.ts` from the serve and dispatcher import graphs are pinned by `test/operation-manifest.test.ts`.
- `src/core/cli-flag-registry.generated.ts` (strict flag validation in `src/cli/main.ts`) + `scripts/generate-flag-registry.ts` — pre-dispatch, pre-engine unknown-flag rejection for every command: a flag no handler consults fails loud (`unknown flag --x for 'gbrain <cmd>'`, exit 1; `--json` invocations also get a structured `{status:'error', reason:'invalid_flag'}` on stdout) instead of being silently ignored while the un-asked-for real operation runs. `validateCommandFlags(command, subArgs)` runs after the `--help` short-circuit and before any dispatch or engine connect, in two lanes mirroring dispatch order (CLI_ONLY first — `think`/`salience`/`anomalies` are both ops AND CLI_ONLY members whose handlers parse flags the op contract doesn't declare): CLI_ONLY commands validate against the generated `CLI_FLAG_REGISTRY` (per-command legal sets derived from each command's source — its `src/cli/commands/` module and pipeline branches + imported modules + one level of relative imports + `EXTRA_FLAGS` + `DELEGATED_MODULES`, the modules a command hands its argv to through a nested handler (auth → `persistence-admin.ts` and `grants/cli.ts`), scanned at module depth without their imports so their safety-flag reads count as consumption; deliberately over-inclusive, help-text mentions count, but `//` and `/* */` comments are stripped at every depth before the scan — a helper's doc comment naming `--fresh` must not legalise it for a command that only imports one function from that helper; regenerate via `bun run build:flag-registry`); op commands validate via `findUnknownOpFlag`, which mirrors `parseOpArgs`'s traversal (non-boolean flags consume their value token; `--key=value` inline form recognized) plus the CLI-local flags consumed outside the op contract (`json`, `explain`, `help`, `source`, `dry-run`); the CLI_ONLY token scan is the exported `findUnknownFlag(args, legal)`. `parseOpArgs` also refuses to let a non-boolean flag swallow a token that is itself a known flag of the same command (op-contract param, a CLI-local, or the `--no-<boolean>` form): `gbrain put x --content --source default` fails with `--content requires a value, but '--source' is a flag; omit --content (or put it last) to read stdin` (exit 1, pre-write) instead of storing the literal `--source` as the page body. A value that merely starts with `--` but names no flag of this command stays a value; the shared `isKnownOpFlag` predicate (`src/core/op-flag-tokens.ts`) sits next to `isBooleanLiteral` so parser and validator cannot disagree. In `parseOpArgs`, `json`/`dry_run` are CLI-local booleans that never consume a value token, so a trailing `--dry-run` is a real rehearsal switch feeding `makeContext`'s `ctx.dryRun`. Uppercase flag spellings are treated as unknown (every handler is case-sensitive-lowercase, so they'd be silently ignored downstream — the exact class the validator kills). Exempt by contract: `call` (arbitrary `--param` interface), `config` (arbitrary set values), `jobs submit` (handler-defined payload params); everything after a literal `--` is passthrough and never validated. A command missing from the registry fails OPEN at runtime (never bricks a command); `test/cli-flag-validation.test.ts` pins registry freshness, per-command drift, and consumption evidence — a safety flag (`--dry-run`, `--yes`, `--force`) may only be advertised if the command's source actually reads it. The generator segments `handleCliOnly` into per-command text blocks with `segmentDispatchBlocks`: both `case 'X':` labels and every `if (command === 'X' …)` head — plain, compound (`&& args[0] === 'sub'`: the no-DB `eval <sub>` bypasses such as `eval longmemeval`, the `<cmd> --help` pre-engine branches, `agent register`) and multi-line — are markers, and ownership follows the `command === 'X'` head, never the condition's tail, so a compound block's flags land on its own command's row (the `eval` row is a union across eval subcommands, the registry's shape for every multi-subcommand command); a bare `command === 'X'` inside a non-`if` expression is deliberately not a marker. Only `import('./commands/*.ts')` inside a block counts as a command module (core helpers a block reaches for directly are not scanned — a flag the block consumes through one is already a literal in the block's own text), and `isValueOnlyImport` skips a destructured import whose bindings are all SCREAMING_CASE constants (a borrowed message string, not a handler). Pinned by `test/generate-flag-registry.test.ts` (acceptance AND rejection: `--frobnicate` is still refused) and `test/eval-longmemeval-cli-smoke.test.ts` (the documented `gbrain eval longmemeval … --retrieval-only --by-type --no-trajectory --keyword-only` invocation exits 0 as a subprocess).
- `src/schema.sql` — Full Postgres + pgvector DDL: canonical for every table except the TS fragment tables, whose `BEGIN/END GENERATED` regions are rewritten from the fragment modules; `bun run build:schema` derives schema-embedded.generated.ts and the PGLite template from it (`docs/ENGINES.md#canonical-schema-sources`)
diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.md
index 49b958b759..3efddf2fe8 100644
--- a/docs/architecture/key-files/mcp.md
+++ b/docs/architecture/key-files/mcp.md
@@ -15,7 +15,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/mcp/resolve-ipc-binding.ts` — shared resolve-IPC listener wiring for BOTH serve transports. `bindResolveIpcForServe(engine, defaultSource)` binds the retrieval-reflex `resolve`, `turn_context`, and `context_pack` kinds (on Postgres the socket is keyed by `hash12(database_url)` plus `hash12(source)` of the serve's bound source under `~/.gbrain/run`, and the legacy URL-only socket is also bound when free; hooks pick theirs with `hookResolveSocketForConfig` — own source first, legacy fallback; the secret stays URL-keyed and the persistence socket brain-keyed; the bound-source posture rejects requests naming any other source; pinned by `test/resolve-ipc-source-keyed.test.ts`) plus the serve-delegated sync (`sync_start`/`sync_status`/`sync_abort` → `src/core/serve-sync-runner.ts`) and maintenance-sweep (`sweep_start`/`sweep_status` → `src/core/serve-sweep-runner.ts`) kinds — each delegation family in its OWN try/catch, so a runner failure logs `[serve-sync]`/`[serve-sweep] handlers unavailable` and the core kinds still start; both families share the `GBRAIN_SERVE_SYNC_IPC=0` kill switch. Engine-uniform: Postgres brains listen too (the hook lane is engine-free by design, so IPC through a serve is its only DB path there). Best-effort by contract — a bind failure never blocks the serve, and a socket already owned by a live listener (another serve) returns the null binding (that serve is the IPC provider). Reflex-channel event logging fires at DELIVERY (`onDelivered`/`onTurnContextDelivered`), never inside the resolver. Pinned by `test/resolve-ipc-binding.test.ts`.
-- `src/mcp/server.ts` — MCP stdio server (generated from operations). Status-only mode (F4, `src/mcp/status-mode.ts`): over a status engine it lists only `gbrain_status`, answers other tools with one `serve_status_only` block, and every tool call re-probes and may recover in place (then `tools/list_changed`). `gbrain://capabilities` carries readiness[], the probed worker status (`stdioCapabilityReadiness`), and `surface`/`surface_source`. One `StdioSurfaceState` (`createStdioSurfaceState` in `surface.ts`) per process is the allow-set tools/list, dispatch (`allowedOps`, `stdioSurface`), skill resources and `gbrain_status` read; `request_tools {surface}` widens it for the session (stderr `surface_widened` audit line, then `tools/list_changed`), and `mcp.allow_session_widen` is resolved at boot. An ignored `GBRAIN_SURFACE` (`invalidSurfaceEnv`) adds one `surface_env_invalid` notice to the first successful tool result. After the engine boots it starts the onboarding cache (`startOnboardingRefresher` from `src/core/onboard/mcp-onboarding.ts`) with an idle gate on the in-flight RPC counter. `startMcpServer`'s optional `onBootPhase` reports each boot phase (`source_preflight` … `startup_sweep`) so `serve`'s boot-deadline line can name the one that never finished. Its SDK `Server` is initialized with the shared contract from `src/mcp/instructions.ts`, so a real client's `getInstructions()` is populated during the initialize handshake. `createDefaultWriteAdvisory(engine, {enabled, write?})` is the stdio lane's once-per-process unscoped-default-write advisory: on a mutating call whose source resolved to tier `seed_default` it runs `assessUnscopedDefaultWrite` (`src/core/source-resolver.ts`) and prints the warning to stderr; it latches on the first SUCCESSFUL assessment whatever the verdict (the aggregate is expensive and its inputs are process-stable), never latches on a failed one (fail-open for that write; the next mutating seed_default call retries), coalesces concurrent calls onto one in-flight assessment, and never blocks a write (a throwing writer still counts as assessed). Non-mutating calls and non-seed tiers return early without latching. Tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path. Stdin `'end'` / `'close'` shutdown hooks are skipped when `process.env.MCP_STDIO === '1'` — gateway-piped stdio MCP wrappers (OpenClaw's `bundle-mcp`) pipe the handshake then close their stdin half, which would otherwise kill the server before the first tool call; signal handlers (SIGTERM/SIGINT/SIGHUP) + the parent-process watchdog still cover legitimate disconnects. `src/commands/serve.ts` exposes `ServeOptions.mcpStdio?: boolean` as a test seam so the guard is exercisable without process.env mutation. The resolve-IPC listener (retrieval-reflex resolve / turn_context / context_pack + the serve-delegated sync and sweep kinds) binds through `src/mcp/resolve-ipc-binding.ts` (next entry) on BOTH serve transports — stdio here and `gbrain serve --http`; the shutdown chain awaits `shutdownDelegatedSync()` before `engine.disconnect()`. Pinned by `test/serve-stdio-lifecycle.test.ts` and `test/serve-stdio-roundtrip.test.ts`.
+- `src/mcp/server.ts` — MCP stdio server. initialize and tools/list are built from `OPERATION_MANIFEST` (`src/core/operation-manifest.generated.ts`, every op minus its handler) so the handler graph behind `src/core/operations.ts` stays unloaded until it is needed; byte-identity with the eager registry across surfaces, strict params, read-only access, publish gates and the advertised surface is pinned by `test/mcp-tool-list-snapshot.test.ts`. Engine-dependent boot (`bootEngineDependents`: source scope, persistence consumer, resolve-IPC bind, startup sweep) and the dispatch/hot-memory imports wait for the handshake (`deferredBoot`, boot phase `initialize_wait`): they start when the first tools/list is answered, `BOOT_LIST_GRACE_MS` after initialize with no tools/list in flight, or `BOOT_WITHOUT_INITIALIZE_MS` after connect for a client that never initializes. Every tools/call and skill resource read awaits that boot, and a boot failure rejects them with the boot error while `startMcpServer` still rejects with it. Status-only mode (F4, `src/mcp/status-mode.ts`): over a status engine it lists only `gbrain_status`, answers other tools with one `serve_status_only` block, and every tool call re-probes and may recover in place (then `tools/list_changed`). `gbrain://capabilities` carries readiness[], the probed worker status (`stdioCapabilityReadiness`), and `surface`/`surface_source`. One `StdioSurfaceState` (`createStdioSurfaceState` in `surface.ts`) per process is the allow-set tools/list, dispatch (`allowedOps`, `stdioSurface`), skill resources and `gbrain_status` read; `request_tools {surface}` widens it for the session (stderr `surface_widened` audit line, then `tools/list_changed`), and `mcp.allow_session_widen` is resolved at boot. An ignored `GBRAIN_SURFACE` (`invalidSurfaceEnv`) adds one `surface_env_invalid` notice to the first successful tool result. After the engine boots it starts the onboarding cache (`startOnboardingRefresher` from `src/core/onboard/mcp-onboarding.ts`) with an idle gate on the in-flight RPC counter. `startMcpServer`'s optional `onBootPhase` reports each boot phase (`source_preflight` … `startup_sweep`) so `serve`'s boot-deadline line can name the one that never finished. Its SDK `Server` is initialized with the shared contract from `src/mcp/instructions.ts`, so a real client's `getInstructions()` is populated during the initialize handshake. `createDefaultWriteAdvisory(engine, {enabled, write?})` is the stdio lane's once-per-process unscoped-default-write advisory: on a mutating call whose source resolved to tier `seed_default` it runs `assessUnscopedDefaultWrite` (`src/core/source-resolver.ts`) and prints the warning to stderr; it latches on the first SUCCESSFUL assessment whatever the verdict (the aggregate is expensive and its inputs are process-stable), never latches on a failed one (fail-open for that write; the next mutating seed_default call retries), coalesces concurrent calls onto one in-flight assessment, and never blocks a write (a throwing writer still counts as assessed). Non-mutating calls and non-seed tiers return early without latching. Tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path. Stdin `'end'` / `'close'` shutdown hooks are skipped when `process.env.MCP_STDIO === '1'` — gateway-piped stdio MCP wrappers (OpenClaw's `bundle-mcp`) pipe the handshake then close their stdin half, which would otherwise kill the server before the first tool call; signal handlers (SIGTERM/SIGINT/SIGHUP) + the parent-process watchdog still cover legitimate disconnects. `src/commands/serve.ts` exposes `ServeOptions.mcpStdio?: boolean` as a test seam so the guard is exercisable without process.env mutation. The resolve-IPC listener (retrieval-reflex resolve / turn_context / context_pack + the serve-delegated sync and sweep kinds) binds through `src/mcp/resolve-ipc-binding.ts` (next entry) on BOTH serve transports — stdio here and `gbrain serve --http`; the shutdown chain awaits `shutdownDelegatedSync()` before `engine.disconnect()`. Pinned by `test/serve-stdio-lifecycle.test.ts` and `test/serve-stdio-roundtrip.test.ts`.
- `src/mcp/source-preflight.ts` — `assertStdioSourceBindable(engine, env?)`: stdio-lane boot preflight called first thing in `startMcpServer`, before any transport attaches. A well-formed `GBRAIN_SOURCE` that names no ACTIVE source row (`SELECT id FROM sources WHERE id = $1 AND archived = false`, the same predicate as `assertSourceExists` in `src/core/source-resolver.ts`) throws a message naming the value and the fix (`gbrain sources list`), so serve exits 1 instead of binding every call to a phantom scope where reads return `[]` and writes die on the sources FK while health stays green. An inherited `__all__` emits an engine-free stderr warning with a source-binding recovery action, without widening its fail-closed scope. Unset env and malformed values are left to the resolver; an engine error fail-opens (guards config, not connectivity); a degraded engine (`isEngineDegraded`) is never touched so the boot does not spend the proxy's reconnect attempt. HTTP is out of scope (tokens carry their own source grant). Pinned by `test/mcp-stdio-source-preflight.test.ts` and real PostgreSQL/PGLite processes in `test/e2e/mcp-search-transport-matrix.test.ts`.
diff --git a/package.json b/package.json
index 80d43b6f2e..07c54fbe13 100644
--- a/package.json
+++ b/package.json
@@ -57,6 +57,7 @@
"wave-security-scan": "bash scripts/wave-security-scan.sh",
"audit:contributors": "bun scripts/contributor-audit.ts",
"build:flag-registry": "bun run scripts/generate-flag-registry.ts",
+ "build:operation-manifest": "bun run scripts/build-operation-manifest.ts",
"weights:mine": "bun run scripts/mine-shard-weights.ts",
"build:pglite-snapshot": "bun run scripts/build-pglite-snapshot.ts",
"bench:efficiency": "bash scripts/bench/efficiency/run-all.sh",
diff --git a/scripts/bench/efficiency/README.md b/scripts/bench/efficiency/README.md
index 6f1226cf9a..b3051cf808 100644
--- a/scripts/bench/efficiency/README.md
+++ b/scripts/bench/efficiency/README.md
@@ -18,6 +18,9 @@ Requires Bun >= 1.4 (the repo's `engines.bun`) and Docker for the Postgres engin
| `probe-pg.ts` | Warm stdio MCP tool against a Postgres bench brain with `pg_stat_statements` reset around N calls: p50/p95, DB time per call, top statements (placeholders only). `--jit off` A/Bs Postgres JIT for the run. |
| `probe-cold.ts` | Cold CLI start split: bun start, module graph, `--version`, real reads, each with stdout piped and with `GBRAIN_FLUSH_GRACE_MS=0` (the non-TTY exit-flush grace). |
| `probe-rerank.ts` | Direct Voyage `/v1/rerank` grid over `top_n_in x max_doc_tokens` and models on candidate sets drawn from a Postgres bench brain: billed tokens/call, $/1k queries, p50/p95, top-5 agreement with the 25x1400 default (a drift signal, not quality). Spends ~$0.1 per 20-query grid. |
+| `probe-mcp-start.ts` | MCP stdio cold start: fresh `gbrain serve` per sample, spawn -> initialize, spawn -> tools/list, first tools/call latency and spawn -> first call, after each `--idle-ms` gap; interleaves several `--cli` trees and prints the tools/list size and hash per tree (equal hashes = byte-identical list). |
+| `bench-chunk.ts` | In-process chunk pass: parse every page of a synthetic brain directory (or `--cjk <pages>` for a generated mixed CJK / Latin / emoji corpus), then time the importer's `prepareMarkdownChunks` over all pages for `--n` passes after a warm-up. Prints p50/p95 per pass and a sha256 over every chunk, so a before/after pair doubles as an equivalence check. |
+| `vector-scope-share.ts` | Vector search latency and recall per source scope against an existing Postgres or PGLite brain (GBRA-71): `searchVector` per scope, recall of result pages against the exact statement, page share, the chunk count the engine routes on, underfilled exits; `--remote` adds the private-page rule. |
| `remote-rows.ts` | Rows for hosted-brain read latency recorded during a pull. |
| `report.ts` | JSONL -> markdown tables (`results/report.md`). |
| `run-all.sh` | Orchestrates data prep, both engines, all datasets, report. |
@@ -26,7 +29,7 @@ Requires Bun >= 1.4 (the repo's `engines.bun`) and Docker for the Postgres engin
```bash
export BENCH_WORK=~/.capy/work/brain # default
-scripts/bench/efficiency/run-all.sh default-pull synth-1x synth-full
+bun run bench:efficiency default-pull synth-1x synth-full # = scripts/bench/efficiency/run-all.sh
# one brain, one engine
bun scripts/bench/efficiency/bench-import.ts --engine pglite --data $BENCH_WORK/import/synth-1x --label synth-1x --embed --max-usd 1
bun scripts/bench/efficiency/bench-hot.ts --engine pglite --label synth-1x --n 20 --only search,query_expand
@@ -34,11 +37,14 @@ bun scripts/bench/efficiency/report.ts
# Postgres statement probe and cold-start split
bun scripts/bench/efficiency/probe-pg.ts --label synth-full --tool list_pages --args '{"limit":50}' --jit off
bun scripts/bench/efficiency/probe-cold.ts --label synth-full --engine postgres
+# chunk pass and scoped vector search, before/after from two pinned worktrees
+bun scripts/bench/efficiency/bench-chunk.ts --data $BENCH_WORK/import/synth-full --n 20
+bun scripts/bench/efficiency/vector-scope-share.ts postgresql://postgres:[email protected]:5440/bench_synth-full sessions notes-b all --queries 25 [--remote]
# CPU profile of one phase
bun scripts/bench/efficiency/bench-import.ts ... --cpu-prof # writes .cpuprofile under engines/<engine>-<label>/bench-run/
```
-Postgres uses a `pgvector/pgvector:pg16` container named `gbrain-bench-pg` on `127.0.0.1:5440`
+Postgres uses a `pgvector/pgvector:pg16` container named `gbrain-bench-pg` (`BENCH_PG_CONTAINER`) on `127.0.0.1:5440`
(`run-all.sh` starts it); each brain gets its own database `bench_<label>`.
## Caveats
diff --git a/scripts/bench/efficiency/probe-mcp-start.ts b/scripts/bench/efficiency/probe-mcp-start.ts
new file mode 100644
index 0000000000..8f38ca9fce
--- /dev/null
+++ b/scripts/bench/efficiency/probe-mcp-start.ts
@@ -0,0 +1,133 @@
+#!/usr/bin/env bun
+/**
+ * MCP stdio cold-start probe (GBRA-73). Opt-in, never run in CI.
+ *
+ * bun scripts/bench/efficiency/probe-mcp-start.ts --home <GBRAIN_HOME> \
+ * --cli <before>/src/cli.ts --cli <after>/src/cli.ts [--n 20] \
+ * [--slug <existing-slug>] [--label <brain-label>] [--engine pglite|postgres] \
+ * [--idle-ms 0,1000] [--json <out.jsonl>]
+ *
+ * Each sample is a fresh `gbrain serve` process (GBRAIN_SWEEP=0). Per sample:
+ * init spawn -> initialize response
+ * list spawn -> tools/list response (sent right after initialize)
+ * call1 first tools/call latency, from send to response
+ * total spawn -> first tools/call response (includes the idle gap)
+ * The first call is sent after an idle gap following tools/list (each
+ * --idle-ms value is its own row; 0 = back-to-back), and is either get_page
+ * on --slug or list_pages {limit:10}. With several --cli values the samples
+ * interleave (A, B, A, B ...) after one discarded warm-up each, so machine
+ * drift hits every side equally. Percentiles are nearest-rank at fractions
+ * 0.5 / 0.95. Prints a markdown table plus the tools/list payload size and
+ * hash per CLI (equal hashes = byte-identical list).
+ */
+import { createHash } from 'node:crypto';
+import { appendFileSync } from 'node:fs';
+import { machine as machineLabel, pct } from './lib.ts';
+
+const argv = process.argv.slice(2);
+const flags = (name: string): string[] => argv.flatMap((a, i) => (a === `--${name}` ? [argv[i + 1]] : []));
+const flag = (name: string, dflt?: string): string | undefined => flags(name)[0] ?? dflt;
+
+const home = flag('home');
+const clis = flags('cli');
+if (!home || clis.length === 0) throw new Error('usage: --home <GBRAIN_HOME> --cli <src/cli.ts> [--cli ...]');
+const N = Number(flag('n', '20'));
+const slug = flag('slug', 'bench/missing')!;
+const label = flag('label', 'unlabeled')!;
+const engine = flag('engine', 'pglite')!;
+const idles = flag('idle-ms', '0,1000')!.split(',').map(Number);
+const jsonOut = flag('json');
+
+interface Sample { init: number; list: number; call1: number; total: number; listHash: string; listBytes: number }
+
+async function sample(cli: string, call: { name: string; arguments: Record<string, unknown> }, idleMs: number): Promise<Sample> {
+ const t0 = performance.now();
+ const proc = Bun.spawn([process.execPath, cli, 'serve'], {
+ stdin: 'pipe', stdout: 'pipe', stderr: 'ignore',
+ env: { ...process.env, GBRAIN_HOME: home!, GBRAIN_SWEEP: '0' },
+ });
+ const send = (msg: unknown) => { proc.stdin.write(JSON.stringify(msg) + '\n'); proc.stdin.flush(); };
+ const waiters = new Map<number, (msg: any) => void>();
+ const reader = (async () => {
+ const decoder = new TextDecoder();
+ let buf = '';
+ for await (const chunk of proc.stdout) {
+ buf += decoder.decode(chunk, { stream: true });
+ let nl: number;
+ while ((nl = buf.indexOf('\n')) >= 0) {
+ const line = buf.slice(0, nl);
+ buf = buf.slice(nl + 1);
+ if (!line.trim()) continue;
+ const msg = JSON.parse(line);
+ if (typeof msg.id === 'number') waiters.get(msg.id)?.(msg);
+ }
+ }
+ })();
+ const request = (id: number, method: string, params: unknown) => new Promise<any>((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error(`${method} timed out`)), 60_000);
+ waiters.set(id, msg => { clearTimeout(timer); resolve(msg); });
+ send({ jsonrpc: '2.0', id, method, params });
+ });
+ try {
+ await request(1, 'initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'probe-mcp-start', version: '0' } });
+ const tInit = performance.now();
+ send({ jsonrpc: '2.0', method: 'notifications/initialized' });
+ const list = await request(2, 'tools/list', {});
+ const tList = performance.now();
+ if (idleMs > 0) await Bun.sleep(idleMs);
+ const tSend = performance.now();
+ const res = await request(3, 'tools/call', call);
+ const tCall = performance.now();
+ if (res.error || res.result?.isError) throw new Error(`tools/call failed: ${JSON.stringify(res.error ?? res.result).slice(0, 400)}`);
+ const listJson = JSON.stringify(list.result);
+ return {
+ init: tInit - t0, list: tList - t0, call1: tCall - tSend, total: tCall - t0,
+ listHash: createHash('sha256').update(listJson).digest('hex').slice(0, 12), listBytes: listJson.length,
+ };
+ } finally {
+ proc.stdin.end();
+ proc.kill();
+ await Promise.race([proc.exited, Bun.sleep(5000)]);
+ await reader.catch(() => {});
+ }
+}
+
+const calls = [
+ { label: 'get_page', call: { name: 'get_page', arguments: { slug } } },
+ { label: 'list_pages', call: { name: 'list_pages', arguments: { limit: 10 } } },
+];
+
+const machine = machineLabel();
+console.log(`machine: ${machine}`);
+console.log(`engine: ${engine} brain: ${label} command: gbrain serve (stdio) mode: cold (fresh process per sample) N: ${N} per row, interleaved percentiles: nearest-rank 0.5/0.95\n`);
+console.log('| cli | first call | idle after list ms | N | init p50 | init p95 | list p50 | list p95 | call1 p50 | call1 p95 | total p50 | total p95 |');
+console.log('|---|---|---|---|---|---|---|---|---|---|---|---|');
+const hashes = new Map<string, Set<string>>();
+for (const idleMs of idles) {
+ for (const { label: callLabel, call } of calls) {
+ const results = new Map<string, Sample[]>(clis.map(c => [c, []]));
+ for (const cli of clis) await sample(cli, call, idleMs);
+ for (let i = 0; i < N; i++) {
+ for (const cli of clis) {
+ const s = await sample(cli, call, idleMs);
+ results.get(cli)!.push(s);
+ const h = hashes.get(cli) ?? new Set();
+ h.add(`${s.listHash} (${s.listBytes} bytes)`);
+ hashes.set(cli, h);
+ }
+ }
+ for (const cli of clis) {
+ const rows = results.get(cli)!;
+ const f = (k: 'init' | 'list' | 'call1' | 'total', p: number) => pct(rows.map(r => r[k]), p).toFixed(0);
+ console.log(`| ${cli} | ${callLabel} | ${idleMs} | ${rows.length} | ${f('init', 0.5)} | ${f('init', 0.95)} | ${f('list', 0.5)} | ${f('list', 0.95)} | ${f('call1', 0.5)} | ${f('call1', 0.95)} | ${f('total', 0.5)} | ${f('total', 0.95)} |`);
+ if (jsonOut) {
+ appendFileSync(jsonOut, JSON.stringify({
+ machine, engine, brain: label, command: `gbrain serve stdio, first call ${callLabel}`, cli, idle_ms: idleMs, mode: 'cold', n: rows.length,
+ ...Object.fromEntries((['init', 'list', 'call1', 'total'] as const).flatMap(k => [[`${k}_p50`, pct(rows.map(r => r[k]), 0.5)], [`${k}_p95`, pct(rows.map(r => r[k]), 0.95)]])),
+ }) + '\n');
+ }
+ }
+ }
+}
+console.log('');
+for (const [cli, h] of hashes) console.log(`tools/list ${cli}: ${[...h].join(', ')}`);
diff --git a/scripts/build-operation-manifest.ts b/scripts/build-operation-manifest.ts
new file mode 100644
index 0000000000..54cc7c6b5a
--- /dev/null
+++ b/scripts/build-operation-manifest.ts
@@ -0,0 +1,44 @@
+#!/usr/bin/env bun
+/**
+ * Operation manifest generator: every operation's data (name, description,
+ * params, scope, flags, annotations, cliHints) without its handler.
+ *
+ * Output: src/core/operation-manifest.generated.ts (committed). `gbrain serve`
+ * builds initialize and tools/list from it and the CLI dispatcher resolves
+ * commands from it, so neither loads the ~760-module handler graph behind
+ * src/core/operations.ts until a call actually runs. Freshness is pinned by
+ * test/operation-manifest.test.ts; tools/list byte-identity against the eager
+ * registry by test/mcp-tool-list-snapshot.test.ts.
+ *
+ * Regenerate: bun run build:operation-manifest
+ */
+import { writeFileSync } from 'fs';
+import { join } from 'path';
+import { operations } from '../src/core/operations.ts';
+
+export const OPERATION_MANIFEST_PATH = join(import.meta.dir, '..', 'src', 'core', 'operation-manifest.generated.ts');
+
+export function renderOperationManifest(): string {
+ const meta = operations.map(({ handler: _handler, ...rest }) => rest);
+ return [
+ '// AUTO-GENERATED by scripts/build-operation-manifest.ts — do not edit by hand.',
+ '// Regenerate: bun run build:operation-manifest',
+ '// Freshness pinned by test/operation-manifest.test.ts.',
+ '//',
+ '// Merge conflict here? Take either side wholesale, then re-run the command above.',
+ '//',
+ '// Every operation in src/core/operations.ts minus its handler, in registry',
+ '// order. Read by the MCP stdio server (initialize, tools/list) and the CLI',
+ '// dispatcher so they stay off the handler module graph until a call runs.',
+ "import type { OperationMeta } from './ops/contract.ts';",
+ '',
+ `export const OPERATION_MANIFEST: OperationMeta[] = ${JSON.stringify(meta, null, 2)};`,
+ '',
+ ].join('\n');
+}
+
+if (import.meta.main) {
+ const out = renderOperationManifest();
+ writeFileSync(OPERATION_MANIFEST_PATH, out, 'utf-8');
+ console.log(`Wrote ${OPERATION_MANIFEST_PATH} (${operations.length} operations, ${out.length} bytes).`);
+}
diff --git a/scripts/regen-all.ts b/scripts/regen-all.ts
index 0fef4ab05c..a19a19d621 100644
--- a/scripts/regen-all.ts
+++ b/scripts/regen-all.ts
@@ -42,6 +42,7 @@ export const ARTIFACTS: Artifact[] = [
{ name: 'error-code registry docs', regen: ['bun', 'scripts/build-error-codes.ts'], check: ['bun', 'scripts/build-error-codes.ts', '--check'] },
{ name: 'agent operator protocol blocks', regen: ['bun', 'scripts/build-agent-protocol.ts'], check: ['bun', 'scripts/build-agent-protocol.ts', '--check'] },
{ name: 'harness adapter reference', regen: ['bun', 'run', 'scripts/build-harness-docs.ts'], check: ['bun', '-e', HARNESS_DOCS_CHECK] },
+ { name: 'operation manifest', regen: ['bun', 'run', 'scripts/build-operation-manifest.ts'], check: [...BUN_TEST, 'test/operation-manifest.test.ts'] },
{ name: 'MCP tool catalog', regen: ['bun', 'run', 'scripts/generate-tool-catalog.ts'], check: ['bash', 'scripts/check-tool-catalog-fresh.sh'] },
{ name: 'skills manifest', regen: ['bun', 'run', 'scripts/generate-skills-manifest.ts'], check: ['bash', 'scripts/check-skills-manifest-fresh.sh'] },
{ name: 'eval metric glossary', regen: ['bun', 'run', 'scripts/generate-metric-glossary.ts'], check: ['bash', 'scripts/check-eval-glossary-fresh.sh'] },
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 894aca065b..cbb0008c56 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -33,7 +33,8 @@ import { resolveBrainId as resolveBrainIdForDbMarker } from '../core/brain-resol
import type { GBrainConfig } from '../core/config.ts';
import type { AIGatewayConfig } from '../core/ai/types.ts';
import type { BrainEngine } from '../core/engine.ts';
-import { operations, OperationError } from '../core/operations.ts';
+import { OperationError, type OperationMeta } from '../core/ops/contract.ts';
+import { OPERATION_MANIFEST, cliOps } from './op-manifest.ts';
import { resolveSourceIdEngineFree } from '../core/source-resolver.ts';
import { installCliRoutingFor } from './fix-routing-provider.ts';
import { formatVolunteeredPage } from '../core/context/volunteer.ts';
@@ -88,15 +89,6 @@ function dbMarkerBrainId(): string | undefined {
}
}
-// Build CLI name -> operation lookup
-const cliOps = new Map<string, Operation>();
-for (const op of operations) {
- const name = op.cliHints?.name;
- if (name && !op.cliHints?.hidden) {
- cliOps.set(name, op);
- }
-}
-
// bigint → string JSON replacer: defined in core/utils.ts (commands must not
// reach into the dispatcher for it); re-exported here so existing importers
// and tests keep their surface. (#2450)
@@ -182,12 +174,12 @@ async function printSelfHelpWithoutEngine(command: string, args: string[]): Prom
// load — a silent route-shadow is worse than a loud boot failure. CLI_ONLY is
// derived from the command table (src/cli/command-table.ts), so the check runs
// over every table record. Exported for the table test's collision case.
-export function buildCliAliases(
- ops: readonly Operation[],
- primary: ReadonlyMap<string, Operation>,
+export function buildCliAliases<T extends OperationMeta>(
+ ops: readonly T[],
+ primary: ReadonlyMap<string, OperationMeta>,
cliOnly: ReadonlySet<string>,
-): Map<string, Operation> {
- const aliases = new Map<string, Operation>();
+): Map<string, T> {
+ const aliases = new Map<string, T>();
for (const op of ops) {
if (op.cliHints?.hidden) continue;
for (const alias of op.cliHints?.aliases ?? []) {
@@ -203,7 +195,7 @@ export function buildCliAliases(
return aliases;
}
-export const cliAliases = buildCliAliases(operations, cliOps, CLI_ONLY);
+export const cliAliases = buildCliAliases(OPERATION_MANIFEST, cliOps, CLI_ONLY);
/**
* Emit the self-upgrade marker on the hot path. CACHE-READ-ONLY: a statSync +
@@ -523,8 +515,9 @@ async function main() {
*/
async function runSharedOperation(command: string, subArgs: string[], cliOpts: CliOptions): Promise<void> {
// Shared operations (fall through to aliases, e.g. link-add -> add_link)
- const op = cliOps.get(command) ?? cliAliases.get(command);
- if (!op) exitCliError(usageError(`Unknown command: ${command}`, 'Run `gbrain --help` for available commands.', { code: 'unknown_command' }), command);
+ const meta = cliOps.get(command) ?? cliAliases.get(command);
+ if (!meta) exitCliError(usageError(`Unknown command: ${command}`, 'Run `gbrain --help` for available commands.', { code: 'unknown_command' }), command);
+ const op = (await import('../core/operations.ts')).operations.find(o => o.name === meta.name)!;
// v0.31.1 (Issue #734, CDX-1): parse CLI args BEFORE engine connect so
// the routing seam below can decide local-vs-remote without paying a
@@ -1317,7 +1310,7 @@ export function findUnknownFlag(args: string[], legal: ReadonlySet<string>): str
}
/** Op lane: mirrors parseOpArgs so flag VALUES starting with '--' are skipped. */
-export function findUnknownOpFlag(op: Operation, args: string[]): string | null {
+export function findUnknownOpFlag(op: OperationMeta, args: string[]): string | null {
for (let i = 0; i < args.length; i++) {
const a = args[i];
if (a === '--') break;
@@ -2937,7 +2930,7 @@ const OP_HELP_EXAMPLES: Record<string, string[]> = {
],
};
-export function printOpHelp(op: Operation, invokedName?: string) {
+export function printOpHelp(op: OperationMeta, invokedName?: string) {
const positional = (op.cliHints?.positional || []).map(p => `<${p}>`).join(' ');
// v114 (#1941): when invoked via an alias (e.g. `gbrain link-add --help`),
// show the alias the user typed, not the primary op name.
diff --git a/src/cli/op-manifest.ts b/src/cli/op-manifest.ts
new file mode 100644
index 0000000000..3eead5c82e
--- /dev/null
+++ b/src/cli/op-manifest.ts
@@ -0,0 +1,22 @@
+/**
+ * The CLI dispatcher's operation lookup, built from the handler-free
+ * manifest (src/core/operation-manifest.generated.ts) so resolving a command,
+ * its flags or its help never loads the handler graph behind
+ * src/core/operations.ts; runSharedOperation imports that only to run an op.
+ */
+import { OPERATION_MANIFEST } from '../core/operation-manifest.generated.ts';
+import { registerOpRoutes } from '../core/fix-routing.ts';
+import type { OperationMeta } from '../core/ops/contract.ts';
+
+export { OPERATION_MANIFEST };
+
+// operations.ts registers the op half of the A1 fix-routing pin as it loads;
+// fixes rendered before an op runs (flag errors, help) need it too.
+registerOpRoutes(OPERATION_MANIFEST);
+
+/** CLI name -> operation (hidden ops excluded). */
+export const cliOps = new Map<string, OperationMeta>();
+for (const op of OPERATION_MANIFEST) {
+ const name = op.cliHints?.name;
+ if (name && !op.cliHints?.hidden) cliOps.set(name, op);
+}
diff --git a/src/commands/serve.ts b/src/commands/serve.ts
index ef9038b20a..860b1789d8 100644
--- a/src/commands/serve.ts
+++ b/src/commands/serve.ts
@@ -5,7 +5,6 @@ export { serveFailFastRequested, writeServeFailFastEnvelope } from '../core/serv
import { isEngineDegraded as isEngineDegradedForServe } from '../core/degraded-marker.ts';
import { startMcpServer, stdioRpcsInFlightCount, resolveMcpStdioSourceScope } from '../mcp/server.ts';
import { VERB_NAMES } from '../core/verbs.ts';
-import { parseTokenTtl } from './auth.ts';
import { RESIDENT_POOL_FLOOR } from '../core/pg-access-classify.ts';
import { redirectStdoutLoggingToStderr } from '../core/console-prefix.ts';
import { startFactsDrainScheduler, type FactsDrainScheduler, type FactsDrainSchedulerOpts } from '../core/facts/drain-scheduler.ts';
@@ -276,6 +275,8 @@ export async function runServe(
const port = portIdx >= 0 ? parseInt(args[portIdx + 1]) || 3131 : 3131;
const ttlIdx = args.indexOf('--token-ttl');
+ // auth.ts reaches the whole operations graph; only --http needs it.
+ const { parseTokenTtl } = await import('./auth.ts');
const tokenTtl = ttlIdx >= 0 ? parseTokenTtl(args[ttlIdx + 1] ?? '', 'Omit the flag for the 3600-second default.') : 3600;
// #1353: --enable-dcr-insecure opts into the consent-bypassing
diff --git a/src/core/minions/tools/brain-allowlist.ts b/src/core/minions/tools/brain-allowlist.ts
index ac6dae808c..3af161a059 100644
--- a/src/core/minions/tools/brain-allowlist.ts
+++ b/src/core/minions/tools/brain-allowlist.ts
@@ -31,51 +31,11 @@ import { normalizeOptionalParams, validateParams } from '../../../mcp/validate-p
import { validateSourceId } from '../../utils.ts';
import type { ToolCtx, ToolDef } from '../types.ts';
import { putPageRejection } from './put-page-result.ts';
+import { BRAIN_TOOL_ALLOWLIST } from './brain-tool-allowlist.ts';
-/**
- * v0.15 brain-tool allow-list. Review carefully when extending. Op names
- * verified against origin/master:src/core/operations.ts (post shell-jobs +
- * Knowledge Runtime).
- *
- * Read-only (all safe):
- * query, search, get_page, list_pages,
- * get_backlinks, traverse_graph, resolve_slugs, get_ingest_log
- *
- * Conditional write:
- * put_page (namespace-enforced by the tool schema + server-side check)
- *
- * Every name below MUST exist in src/core/operations.ts OPERATIONS; the
- * brain-allowlist test pins this invariant so an upstream rename fails CI
- * instead of silently dropping a tool.
- */
-export const BRAIN_TOOL_ALLOWLIST: ReadonlySet<string> = new Set([
- 'query',
- 'search',
- 'get_page',
- 'list_pages',
- 'get_backlinks',
- 'traverse_graph',
- // v114 (#1941): read-only provenance discovery. Edge-WRITE ops (add_link /
- // remove_link) are deliberately NOT allowlisted — exposing graph writes to
- // subagents is a separate trust decision.
- 'list_link_sources',
- 'resolve_slugs',
- 'get_ingest_log',
- 'put_page',
- // #2778: the canonical timeline-write op. Fenced exactly like put_page —
- // operations.ts:enforceSubagentSlugFence confines the target slug to the
- // trusted-workspace allow-list (or the wiki/agents/<id>/ namespace) when
- // ctx.viaSubagent=true, so a subagent can only append timeline entries to
- // pages it could have written anyway.
- 'add_timeline_entry',
- // v0.29 — Salience + Anomaly Detection. Both read-only. `get_recent_transcripts`
- // is intentionally NOT included: subagent calls always have ctx.remote=true,
- // and the v0.29 trust gate rejects remote callers — adding it here would be
- // a footgun (subagent calls op, gets permission_denied, looks like a bug).
- // The cycle synthesize phase already calls discoverTranscripts directly.
- 'get_recent_salience',
- 'find_anomalies',
-]);
+// The allow-list itself lives in a handler-free module so the MCP surface
+// tiers (src/mcp/surface.ts) can read it without this module's operations import.
+export { BRAIN_TOOL_ALLOWLIST };
/**
* v0.41 Approach C: per-tool usage_hint surfaced verbatim in the subagent
diff --git a/src/core/minions/tools/brain-tool-allowlist.ts b/src/core/minions/tools/brain-tool-allowlist.ts
new file mode 100644
index 0000000000..274a3459e3
--- /dev/null
+++ b/src/core/minions/tools/brain-tool-allowlist.ts
@@ -0,0 +1,44 @@
+/**
+ * v0.15 brain-tool allow-list. Review carefully when extending. Op names
+ * verified against origin/master:src/core/operations.ts (post shell-jobs +
+ * Knowledge Runtime).
+ *
+ * Read-only (all safe):
+ * query, search, get_page, list_pages,
+ * get_backlinks, traverse_graph, resolve_slugs, get_ingest_log
+ *
+ * Conditional write:
+ * put_page (namespace-enforced by the tool schema + server-side check)
+ *
+ * Every name below MUST exist in src/core/operations.ts OPERATIONS; the
+ * brain-allowlist test pins this invariant so an upstream rename fails CI
+ * instead of silently dropping a tool.
+ */
+export const BRAIN_TOOL_ALLOWLIST: ReadonlySet<string> = new Set([
+ 'query',
+ 'search',
+ 'get_page',
+ 'list_pages',
+ 'get_backlinks',
+ 'traverse_graph',
+ // v114 (#1941): read-only provenance discovery. Edge-WRITE ops (add_link /
+ // remove_link) are deliberately NOT allowlisted — exposing graph writes to
+ // subagents is a separate trust decision.
+ 'list_link_sources',
+ 'resolve_slugs',
+ 'get_ingest_log',
+ 'put_page',
+ // #2778: the canonical timeline-write op. Fenced exactly like put_page —
+ // operations.ts:enforceSubagentSlugFence confines the target slug to the
+ // trusted-workspace allow-list (or the wiki/agents/<id>/ namespace) when
+ // ctx.viaSubagent=true, so a subagent can only append timeline entries to
+ // pages it could have written anyway.
+ 'add_timeline_entry',
+ // v0.29 — Salience + Anomaly Detection. Both read-only. `get_recent_transcripts`
+ // is intentionally NOT included: subagent calls always have ctx.remote=true,
+ // and the v0.29 trust gate rejects remote callers — adding it here would be
+ // a footgun (subagent calls op, gets permission_denied, looks like a bug).
+ // The cycle synthesize phase already calls discoverTranscripts directly.
+ 'get_recent_salience',
+ 'find_anomalies',
+]);
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
new file mode 100644
index 0000000000..bf6645df4a
--- /dev/null
+++ b/src/core/operation-manifest.generated.ts
@@ -0,0 +1,5561 @@
+// AUTO-GENERATED by scripts/build-operation-manifest.ts — do not edit by hand.
+// Regenerate: bun run build:operation-manifest
+// Freshness pinned by test/operation-manifest.test.ts.
+//
+// Merge conflict here? Take either side wholesale, then re-run the command above.
+//
+// Every operation in src/core/operations.ts minus its handler, in registry
+// order. Read by the MCP stdio server (initialize, tools/list) and the CLI
+// dispatcher so they stay off the handler module graph until a call runs.
+import type { OperationMeta } from './ops/contract.ts';
+
+export const OPERATION_MANIFEST: OperationMeta[] = [
+ {
+ "name": "remember",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "MEMORY VERB (v1): save facts with provenance. Set `entity` to the subject or entity recall misses it. Branch on `status` (inserted|duplicate|superseded); write_pending: poll get_write_request.",
+ "params": {
+ "source_id": {
+ "type": "string",
+ "description": "Write source."
+ },
+ "expected_revision": {
+ "type": "string",
+ "description": "Revision read; omit to create."
+ },
+ "force": {
+ "type": "boolean",
+ "description": "Ignore the revision."
+ },
+ "request_id": {
+ "type": "string",
+ "description": "UUID; retry with it on timeout."
+ },
+ "fact": {
+ "type": "string",
+ "description": "One claim."
+ },
+ "items": {
+ "type": "array",
+ "description": "≤20 facts: [{fact, provenance}]",
+ "items": {
+ "type": "object"
+ }
+ },
+ "provenance": {
+ "type": "string",
+ "description": "Fact source (max 500 chars)."
+ },
+ "ttl": {
+ "type": "string",
+ "description": "\"30d\", \"12h\" or ISO 8601 time; omit = never."
+ },
+ "entity": {
+ "type": "string",
+ "description": "Subject (name or slug)."
+ },
+ "infer_entity": {
+ "type": "boolean",
+ "description": "Default true."
+ },
+ "kind": {
+ "type": "string",
+ "description": "Default fact.",
+ "enum": [
+ "event",
+ "preference",
+ "commitment",
+ "belief",
+ "fact"
+ ]
+ },
+ "visibility": {
+ "type": "string",
+ "enum": [
+ "world",
+ "private"
+ ],
+ "description": "world (default) or private (local CLI only)."
+ },
+ "replaces": {
+ "type": "string",
+ "description": "fact_id this fact replaces (same entity).",
+ "fullSurfaceOnly": true
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "verb": true,
+ "annotations": {
+ "title": "remember (memory write)",
+ "idempotentHint": true
+ },
+ "cliHints": {
+ "name": "remember",
+ "positional": [
+ "fact"
+ ]
+ },
+ "area": "memory-verbs"
+ },
+ {
+ "name": "entity",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "MEMORY VERB (v1): person/company/account card, zero LLM. Previews are not evidence: fetch the page before stating status or dates. Miss: found:false with near matches and create_safety. Facts: recall.",
+ "params": {
+ "name": {
+ "type": "string",
+ "required": true,
+ "description": "Name, alias or slug (e.g. \"Alice Example\")."
+ }
+ },
+ "scope": "read",
+ "verb": true,
+ "annotations": {
+ "title": "entity (card lookup, zero LLM)",
+ "readOnlyHint": true
+ },
+ "cliHints": {
+ "name": "entity",
+ "positional": [
+ "name"
+ ]
+ },
+ "area": "memory-verbs"
+ },
+ {
+ "name": "synthesize",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "[EXPENSIVE / SLOW: LLM calls, costs money] MEMORY VERB (v1): answer a broad question across pages with citations. For lookups use recall or entity.",
+ "params": {
+ "question": {
+ "type": "string",
+ "description": "The question.",
+ "required": true
+ },
+ "since": {
+ "type": "string",
+ "description": "Window start (ISO 8601)."
+ },
+ "until": {
+ "type": "string",
+ "description": "Window end (ISO 8601)."
+ }
+ },
+ "scope": "read",
+ "verb": true,
+ "annotations": {
+ "title": "synthesize (slow, costly — LLM-backed)",
+ "readOnlyHint": true
+ },
+ "cliHints": {
+ "name": "synthesize",
+ "positional": [
+ "question"
+ ]
+ },
+ "area": "memory-verbs"
+ },
+ {
+ "name": "forget",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "MEMORY VERB (v1): expire a remembered fact by its fact_id (never a page slug). Idempotent; the audit trail is kept.",
+ "params": {
+ "request_id": {
+ "type": "string",
+ "description": "UUID; retry with it on timeout."
+ },
+ "id": {
+ "type": "string",
+ "required": true,
+ "description": "fact_id from remember or recall."
+ },
+ "reason": {
+ "type": "string",
+ "description": "Audit note (default \"forgotten\")."
+ },
+ "semantic_review": {
+ "type": "boolean",
+ "description": "false: skip overnight rewording review.",
+ "fullSurfaceOnly": true
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "verb": true,
+ "annotations": {
+ "title": "forget (expire a fact)",
+ "destructiveHint": true,
+ "idempotentHint": true
+ },
+ "area": "memory-verbs"
+ },
+ {
+ "name": "get_page",
+ "idempotent": true,
+ "outputRedaction": {
+ "exempt": "explicit page read by slug/id; governed by page visibility, not output redaction (CEO-17 raw-read exception)"
+ },
+ "description": "Read a page by slug. To edit, pass include_content:true and send `content` to put_page, or use edit_page.",
+ "params": {
+ "slug": {
+ "type": "string",
+ "description": "Page slug.",
+ "required": true
+ },
+ "fuzzy": {
+ "type": "boolean",
+ "description": "Fuzzy slug match."
+ },
+ "include_content": {
+ "type": "boolean",
+ "description": "Full markdown + revision, for editing."
+ },
+ "content_only": {
+ "type": "boolean",
+ "description": "Round-trip fields only."
+ },
+ "include_deleted": {
+ "type": "boolean",
+ "description": "Include soft-deleted pages."
+ },
+ "include_timeline_entries": {
+ "type": "boolean",
+ "description": "Also return timeline rows."
+ },
+ "grammar_diagnostics": {
+ "type": "boolean",
+ "description": "Also return every line-grammar finding for the page.",
+ "fullSurfaceOnly": true
+ },
+ "source_id": {
+ "type": "string",
+ "description": "One source, or '__all__'."
+ },
+ "include_quarantined": {
+ "type": "boolean",
+ "description": "Admin: quarantined body."
+ }
+ },
+ "scope": "read",
+ "mutating": false,
+ "cliHints": {
+ "name": "get",
+ "positional": [
+ "slug"
+ ]
+ },
+ "area": "pages"
+ },
+ {
+ "name": "put_page",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Complete content REPLACES the whole page: read get_page include_content:true; send its revision as expected_revision. Keep a request_id UUID; retry with identical arguments. Remote callers: existing-page [[links]] become mentions; typed links are skipped (stdio `gbrain serve` sweeps them later, `gbrain serve --http` does not self-sweep). Edits: edit_page; >3 pages: put_pages.",
+ "params": {
+ "source_id": {
+ "type": "string",
+ "description": "Write source."
+ },
+ "expected_revision": {
+ "type": "string",
+ "description": "Revision read; omit to create."
+ },
+ "force": {
+ "type": "boolean",
+ "description": "Ignore the revision."
+ },
+ "request_id": {
+ "type": "string",
+ "description": "UUID; retry with it on timeout."
+ },
+ "slug": {
+ "type": "string",
+ "description": "Page slug.",
+ "required": true
+ },
+ "content": {
+ "type": "string",
+ "required": true,
+ "description": "Complete markdown (get_page include_content:true)."
+ },
+ "allow_empty": {
+ "type": "boolean",
+ "required": false,
+ "description": "Allow emptying the page."
+ },
+ "drop_timeline": {
+ "type": "boolean",
+ "required": false,
+ "description": "No Timeline in content: delete its entries."
+ },
+ "wait_ms": {
+ "type": "number",
+ "description": "Commit wait ms (0-30000, default 5000)."
+ },
+ "source_kind": {
+ "type": "string",
+ "description": "Server-stamped remotely.",
+ "required": false
+ },
+ "source_uri": {
+ "type": "string",
+ "description": "Server-stamped remotely.",
+ "required": false
+ },
+ "ingested_via": {
+ "type": "string",
+ "description": "Server-stamped remotely.",
+ "required": false
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "cliHints": {
+ "name": "put",
+ "positional": [
+ "slug"
+ ],
+ "stdin": "content"
+ },
+ "area": "pages"
+ },
+ {
+ "name": "delete_page",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Soft-delete a page and remove its markdown file from the source working tree (the source local_path, or sync.repo_path when the source has none). File removal is skipped when sync.write_through is off; the committed receipt reports the persistence mode and write_through outcome. Read the page revision first and pass expected_revision; retain request_id for replay. The row is hidden from search and from get_page/list_pages, but is recoverable via restore_page within 72h, which re-creates the file. The autopilot purge phase hard-deletes after the recovery window. Pass include_deleted: true to get_page to verify the soft-delete landed. purge: true is trusted-local CLI only and removes the row, chunks, links and raw data immediately after its recorded markdown artifact is removed. Purge uses the same revision, request_id and recovery protocol, including for existing tombstones. A removal failure preserves the prior row and never reports purge success; repair the artifact and submit a new request_id. A committed purge warns that git history, synced copies, exports and derived rows may retain content; rotate exposed credentials.",
+ "params": {
+ "source_id": {
+ "type": "string",
+ "description": "#4329: source holding the row to soft-delete (a multi-source brain can hold the same slug in several sources). Defaults to ctx.sourceId. Remote callers may only target their write source — federated read grants do not confer delete access."
+ },
+ "expected_revision": {
+ "type": "string",
+ "description": "Revision read; omit to create."
+ },
+ "force": {
+ "type": "boolean",
+ "description": "Ignore the revision."
+ },
+ "request_id": {
+ "type": "string",
+ "description": "UUID; retry with it on timeout."
+ },
+ "slug": {
+ "type": "string",
+ "required": true,
+ "description": "Slug of the page to soft-delete, e.g. 'people/alice-example'."
+ },
+ "purge": {
+ "type": "boolean",
+ "description": "Hard-delete after coordinated artifact removal (no 72h recovery; status purged). Honored only for the trusted local CLI; remote/MCP callers get permission_denied (a non-boolean value is invalid_params) and keep the soft-delete path."
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "cliHints": {
+ "name": "delete",
+ "positional": [
+ "slug"
+ ]
+ },
+ "area": "pages"
+ },
+ {
+ "name": "list_pages",
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "List pages with filters. For 'what's recent / what did I touch this week' use sort=updated_desc. Default 50 rows (remote max 100); a full page may be truncated: continue with updated_after + updated_after_slug from the last row.",
+ "params": {
+ "type": {
+ "type": "string",
+ "description": "Page type."
+ },
+ "tag": {
+ "type": "string",
+ "description": "Tag."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Max rows (default 50; remote max 100)."
+ },
+ "offset": {
+ "type": "number",
+ "description": "Rows to skip."
+ },
+ "updated_after": {
+ "type": "string",
+ "description": "Only pages updated after this ISO time."
+ },
+ "updated_after_slug": {
+ "type": "string",
+ "description": "Last row's slug (with updated_after)."
+ },
+ "sort": {
+ "type": "string",
+ "description": "Default updated_desc.",
+ "enum": [
+ "updated_desc",
+ "updated_asc",
+ "created_desc",
+ "slug"
+ ]
+ },
+ "include_deleted": {
+ "type": "boolean",
+ "description": "Include soft-deleted pages."
+ },
+ "source_id": {
+ "type": "string",
+ "description": "One source, or '__all__'."
+ }
+ },
+ "scope": "read",
+ "mutating": false,
+ "cliHints": {
+ "name": "list"
+ },
+ "area": "pages"
+ },
+ {
+ "name": "restore_page",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Restore a soft-deleted page (clear deleted_at) and re-create its markdown file on disk (the counterpart to delete_page removing it; the result write_through field reports the outcome). Returns success only if the page was actually soft-deleted. After this op, the page reappears in search and in get_page/list_pages without the include_deleted flag.",
+ "params": {
+ "source_id": {
+ "type": "string",
+ "description": "#4329: source holding the row to restore (a multi-source brain can hold the same slug in several sources). Defaults to ctx.sourceId. Remote callers may only target their write source — federated read grants do not confer restore access."
+ },
+ "expected_revision": {
+ "type": "string",
+ "description": "Revision read; omit to create."
+ },
+ "force": {
+ "type": "boolean",
+ "description": "Ignore the revision."
+ },
+ "request_id": {
+ "type": "string",
+ "description": "UUID; retry with it on timeout."
+ },
+ "slug": {
+ "type": "string",
+ "required": true,
+ "description": "Slug of the soft-deleted page to restore, e.g. 'people/alice-example'."
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "cliHints": {
+ "name": "restore",
+ "positional": [
+ "slug"
+ ]
+ },
+ "area": "pages"
+ },
+ {
+ "name": "purge_deleted_pages",
+ "idempotent": false,
+ "outputRedaction": "no_stored_text",
+ "description": "Admin-only. Hard-deletes pages whose deleted_at is older than older_than_hours (default 72), in every source. Cascades through content_chunks, page_links, chunk_relations. Trusted local CLI only; the command is `gbrain pages purge-deleted`, which asks first (yes: true is the consent). Manual escape hatch alongside the autopilot purge phase.",
+ "params": {
+ "older_than_hours": {
+ "type": "number",
+ "description": "Age cutoff in hours. Default 72."
+ },
+ "yes": {
+ "type": "boolean",
+ "description": "Consent to the irreversible brain-wide purge. Ask the user first."
+ }
+ },
+ "mutating": true,
+ "scope": "admin",
+ "localOnly": true,
+ "cliOnly": {
+ "argv": [
+ "gbrain",
+ "pages",
+ "purge-deleted",
+ "--dry-run",
+ "--json"
+ ]
+ },
+ "cliHints": {
+ "name": "purge-deleted",
+ "hidden": true
+ },
+ "area": "pages"
+ },
+ {
+ "name": "capture",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Quick note (\"just remember this\"): auto-slugged under inbox/ by date + content hash, so recapturing is idempotent. Use put_page to control slug or type; remember for facts about entities.",
+ "params": {
+ "source_id": {
+ "type": "string",
+ "description": "Write source."
+ },
+ "expected_revision": {
+ "type": "string",
+ "description": "Revision read; omit to create."
+ },
+ "force": {
+ "type": "boolean",
+ "description": "Ignore the revision."
+ },
+ "request_id": {
+ "type": "string",
+ "description": "UUID; retry with it on timeout."
+ },
+ "who": {
+ "type": "string",
+ "description": "Event: comma-separated entity slugs."
+ },
+ "what": {
+ "type": "string",
+ "description": "Event."
+ },
+ "where": {
+ "type": "string",
+ "description": "Event place."
+ },
+ "kind": {
+ "type": "string",
+ "description": "Event kind."
+ },
+ "depth": {
+ "type": "string",
+ "description": "Event depth page to link."
+ },
+ "content": {
+ "type": "string",
+ "required": true,
+ "description": "Markdown or text (not a file path)."
+ },
+ "local_file": {
+ "type": "string",
+ "description": "Local CLI only.",
+ "required": false
+ },
+ "slug": {
+ "type": "string",
+ "required": false,
+ "description": "Default inbox/<date>-<hash>."
+ },
+ "type": {
+ "type": "string",
+ "required": false,
+ "description": "Schema-pack page type (default note)."
+ }
+ },
+ "scope": "write",
+ "mutating": true,
+ "area": "pages",
+ "cliHints": {
+ "name": "capture",
+ "hidden": true
+ }
+ },
+ {
+ "name": "fetch",
+ "idempotent": true,
+ "outputRedaction": {
+ "exempt": "explicit page read by slug/id; governed by page visibility, not output redaction (CEO-17 raw-read exception)"
+ },
+ "description": "Fetch the full text of one search result by its opaque, source-qualified `id` (OpenAI deep-research contract: the search/fetch pair). Pass the id unchanged; it does not grant access. Legacy slug ids work only when unambiguous within your current read scope. Returns { id, title, text, url, metadata } — `text` is the page's canonical markdown. For fuzzy slugs, soft-delete recovery, or lossless edit round-trips, use get_page.",
+ "params": {
+ "id": {
+ "type": "string",
+ "required": true,
+ "description": "Opaque result id from a prior `search` call. Pass unchanged. Unambiguous legacy slugs are also accepted."
+ },
+ "include_quarantined": {
+ "type": "boolean",
+ "description": "Admin: quarantined body."
+ }
+ },
+ "scope": "read",
+ "mutating": false,
+ "cliHints": {
+ "name": "fetch",
+ "positional": [
+ "id"
+ ]
+ },
+ "area": "pages"
+ },
+ {
+ "name": "edit_page",
+ "idempotent": true,
+ "outputRedaction": {
+ "exempt": "the diff is the caller's own authorized view of the page it just edited (the get_page boundary), secret-redacted when created because the receipt retains it"
+ },
+ "description": "Change part of a page: prefer this over put_page for small changes. expected_revision is the revision from get_page include_content:true. Each old_text must match exactly once; edits apply in order, all or none. Stale revision: revision_conflict.",
+ "params": {
+ "slug": {
+ "type": "string",
+ "description": "Page slug.",
+ "required": true
+ },
+ "expected_revision": {
+ "type": "string",
+ "required": true,
+ "description": "revision from get_page include_content:true."
+ },
+ "edits": {
+ "type": "array",
+ "required": true,
+ "description": "1 to 50 {old_text, new_text} replacements.",
+ "items": {
+ "type": "object",
+ "properties": {
+ "old_text": {
+ "type": "string",
+ "required": true,
+ "description": "Exact text to replace (must occur once)."
+ },
+ "new_text": {
+ "type": "string",
+ "required": true,
+ "description": "Replacement; empty deletes."
+ }
+ }
+ }
+ },
+ "source_id": {
+ "type": "string",
+ "description": "Write source."
+ },
+ "request_id": {
+ "type": "string",
+ "description": "UUID; retry with it on timeout."
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "area": "pages"
+ },
+ {
+ "name": "put_pages",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Write up to 50 complete Markdown pages (8 MB total) in one call; use instead of put_page for more than 3 pages. Each page replaces its whole page, like put_page. Keep one request_id UUID per batch: replaying the identical call never writes twice, and put_pages with ONLY request_id reports progress without resending content. Waits up to wait_ms (default 25000) for commits; follow the returned `next`. Needs put_page permission.",
+ "params": {
+ "pages": {
+ "type": "array",
+ "description": "1-50 pages; omit to read the batch status.",
+ "items": {
+ "type": "object",
+ "properties": {
+ "slug": {
+ "type": "string",
+ "required": true,
+ "description": "Page slug."
+ },
+ "content": {
+ "type": "string",
+ "required": true,
+ "description": "Complete markdown with frontmatter."
+ },
+ "expected_revision": {
+ "type": "string",
+ "description": "Revision read; omit to create."
+ },
+ "allow_empty": {
+ "type": "boolean",
+ "description": "Allow emptying a non-empty page."
+ },
+ "drop_timeline": {
+ "type": "boolean",
+ "description": "Content without a Timeline section deletes its dated entries."
+ }
+ }
+ }
+ },
+ "request_id": {
+ "type": "string",
+ "description": "Batch UUID; reuse it to replay or poll.",
+ "required": true
+ },
+ "source_id": {
+ "type": "string",
+ "description": "Write source."
+ },
+ "wait_ms": {
+ "type": "number",
+ "description": "Hold the reply up to this many ms (0-30000, from arrival) for commits. Default 25000. Not part of the write."
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "area": "pages",
+ "cliHints": {
+ "name": "put-pages"
+ }
+ },
+ {
+ "name": "get_write_request",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Read your write's receipt by request_id (after write_pending or a lost reply). Poll at retry_after_ms until final.",
+ "params": {
+ "request_id": {
+ "type": "string",
+ "required": true,
+ "description": "The UUID you sent with the write."
+ }
+ },
+ "scope": "write",
+ "mutating": false,
+ "area": "pages",
+ "cliHints": {
+ "name": "write-request",
+ "positional": [
+ "request_id"
+ ]
+ }
+ },
+ {
+ "name": "list_write_requests",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "List your write receipts in one source, newest first. Use when a request_id was lost.",
+ "params": {
+ "source_id": {
+ "type": "string",
+ "description": "Default: yours."
+ },
+ "limit": {
+ "type": "number",
+ "default": 25,
+ "description": "1-100 (default 25)."
+ },
+ "before": {
+ "type": "string",
+ "description": "next cursor from the previous page."
+ }
+ },
+ "scope": "write",
+ "mutating": false,
+ "area": "pages",
+ "cliHints": {
+ "name": "write-requests"
+ }
+ },
+ {
+ "name": "cancel_write_request",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Cancel your accepted write before it publishes. Returns the actual receipt.",
+ "params": {
+ "request_id": {
+ "type": "string",
+ "required": true,
+ "description": "The UUID you sent with the write."
+ }
+ },
+ "scope": "write",
+ "mutating": true,
+ "area": "pages",
+ "cliHints": {
+ "name": "cancel-write-request",
+ "positional": [
+ "request_id"
+ ]
+ }
+ },
+ {
+ "name": "search",
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Cheap hybrid search (vector + keyword), no LLM expansion, top 20: for exact tokens, names, field values. Results are NOT proof of coverage: concepts or landscape, use `query`; exhaustive lists, list_pages. return_unit returns whole sections or conversations. Personal: get_recent_salience; saved facts: recall. fields: \"full\" adds diagnostics.",
+ "params": {
+ "query": {
+ "type": "string",
+ "required": true,
+ "description": "Exact tokens or names, e.g. 'acme-example series A'."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Max results (default 20)."
+ },
+ "offset": {
+ "type": "number",
+ "description": "Rows to skip."
+ },
+ "mode": {
+ "type": "string",
+ "description": "Local callers only."
+ },
+ "source_id": {
+ "type": "string",
+ "description": "One source, or '__all__'."
+ },
+ "types": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Page types, e.g. ['person']."
+ },
+ "snippet_chars": {
+ "type": "number",
+ "description": "Max chars per chunk_text (0 = full)."
+ },
+ "return_unit": {
+ "type": "string",
+ "enum": [
+ "chunk",
+ "window",
+ "section",
+ "page",
+ "auto"
+ ],
+ "description": "auto (default) returns whole conversations."
+ },
+ "return_window": {
+ "type": "number",
+ "description": "Neighbor chunks each side for window (1-3)."
+ },
+ "token_budget": {
+ "type": "number",
+ "description": "Evidence token cap (default 6000)."
+ },
+ "salience": {
+ "type": "string",
+ "enum": [
+ "off",
+ "on",
+ "strong"
+ ],
+ "description": "Boost emotional pages (default: auto)."
+ },
+ "recency": {
+ "type": "string",
+ "enum": [
+ "off",
+ "on",
+ "strong"
+ ],
+ "description": "Boost recent pages (default: auto)."
+ },
+ "fields": {
+ "type": "string",
+ "enum": [
+ "lean",
+ "full"
+ ],
+ "description": "lean (remote default) or full."
+ }
+ },
+ "scope": "read",
+ "mutating": false,
+ "cliHints": {
+ "name": "search",
+ "positional": [
+ "query"
+ ]
+ },
+ "area": "search"
+ },
+ {
+ "name": "query",
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Hybrid search plus multi-query expansion for concept or landscape questions (expansion recovers synonym-phrased matches). Still top-K; return_unit returns whole sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no expansion LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent` on the host. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. fields: \"full\" adds diagnostics.",
+ "params": {
+ "query": {
+ "type": "string",
+ "required": false,
+ "description": "Question or topic (required unless image)."
+ },
+ "image": {
+ "type": "string",
+ "description": "Base64 image."
+ },
+ "image_mime": {
+ "type": "string",
+ "description": "MIME type of image."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Default 10/25/50 by search mode."
+ },
+ "offset": {
+ "type": "number",
+ "description": "Rows to skip."
+ },
+ "types": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Page types, e.g. ['person']."
+ },
+ "snippet_chars": {
+ "type": "number",
+ "description": "Max chars per chunk_text (0 = full)."
+ },
+ "return_unit": {
+ "type": "string",
+ "enum": [
+ "chunk",
+ "window",
+ "section",
+ "page",
+ "auto"
+ ],
+ "description": "auto (default) returns whole conversations."
+ },
+ "return_window": {
+ "type": "number",
+ "description": "Neighbor chunks each side for window (1-3)."
+ },
+ "token_budget": {
+ "type": "number",
+ "description": "Evidence token cap."
+ },
+ "expand": {
+ "type": "boolean",
+ "description": "Default true; false skips the LLM expansion."
+ },
+ "detail": {
+ "type": "string",
+ "description": "low (compiled truth), medium (default) or high (all chunks)."
+ },
+ "fields": {
+ "type": "string",
+ "enum": [
+ "lean",
+ "full"
+ ],
+ "description": "lean (remote default) or full."
+ },
+ "mode": {
+ "type": "string",
+ "description": "Local callers only."
+ },
+ "lang": {
+ "type": "string",
+ "description": "Code language."
+ },
+ "symbol_kind": {
+ "type": "string",
+ "description": "Code symbol type."
+ },
+ "near_symbol": {
+ "type": "string",
+ "description": "Anchor code symbol."
+ },
+ "walk_depth": {
+ "type": "number",
+ "description": "Code walk depth 1-2."
+ },
+ "salience": {
+ "type": "string",
+ "enum": [
+ "off",
+ "on",
+ "strong"
+ ],
+ "description": "Boost emotional pages (default: auto)."
+ },
+ "recency": {
+ "type": "string",
+ "enum": [
+ "off",
+ "on",
+ "strong"
+ ],
+ "description": "Boost recent pages (default: auto)."
+ },
+ "since": {
+ "type": "string",
+ "description": "On/after: YYYY-MM-DD or 7d/2w/1y."
+ },
+ "until": {
+ "type": "string",
+ "description": "On/before."
+ },
+ "source_id": {
+ "type": "string",
+ "description": "One source, or '__all__'."
+ },
+ "cross_modal": {
+ "type": "string",
+ "enum": [
+ "text",
+ "image",
+ "both",
+ "auto"
+ ],
+ "description": "Default auto."
+ },
+ "embedding_column": {
+ "type": "string",
+ "description": "Registered embedding column."
+ },
+ "adaptive_return": {
+ "type": "boolean",
+ "description": "true when one answer is wanted (fewer rows; never returns empty); omit for breadth."
+ },
+ "autocut": {
+ "type": "boolean",
+ "description": "Default on (never returns empty); false gives full top-K for breadth, unlike adaptive_return."
+ },
+ "relational": {
+ "type": "boolean",
+ "description": "Relationship-graph arm (default on)."
+ },
+ "explain": {
+ "type": "boolean",
+ "description": "Per-row score_details.",
+ "fullSurfaceOnly": true
+ },
+ "explain_target": {
+ "type": "string",
+ "description": "Expected page (slug or source:slug): why it is missing.",
+ "fullSurfaceOnly": true
+ }
+ },
+ "scope": "read",
+ "mutating": false,
+ "cliHints": {
+ "name": "query",
+ "positional": [
+ "query"
+ ]
+ },
+ "area": "search"
+ },
+ {
+ "name": "assemble_evidence",
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Deliver whole evidence for an ordered list of search hits (each {source_id, slug, chunk_id} from a prior search/query result): the same windows, sections or pages `query` returns with return_unit, packed into token_budget. Use it to widen hits you already have instead of calling get_page per hit. Returns { results, delivery, unresolved }; results carry chunk_text (the evidence) and `delivered`.",
+ "params": {
+ "hits": {
+ "type": "array",
+ "required": true,
+ "items": {
+ "type": "object"
+ },
+ "description": "Ordered hits, best first (max 50): [{ \"source_id\": \"default\", \"slug\": \"chat/session-0412\", \"chunk_id\": 8812 }]. chunk_id 0 addresses the page's first chunk."
+ },
+ "return_unit": {
+ "type": "string",
+ "enum": [
+ "chunk",
+ "window",
+ "section",
+ "page",
+ "auto"
+ ],
+ "description": "Evidence unit: 'chunk' | 'window' | 'section' | 'page' | 'auto' (default 'page')."
+ },
+ "return_window": {
+ "type": "number",
+ "description": "Neighbor chunks each side for window (1-3)."
+ },
+ "token_budget": {
+ "type": "number",
+ "description": "Token budget for the delivered evidence (default search.return_budget_default = 6000, auto search.return_budget_conversation = 24000; remote max 32000)."
+ },
+ "detail": {
+ "type": "string",
+ "enum": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "description": "As query: 'low' delivers compiled truth only (no timeline text)."
+ }
+ },
+ "scope": "read",
+ "mutating": false,
+ "annotations": {
+ "title": "assemble evidence",
+ "readOnlyHint": true
+ },
+ "area": "search"
+ },
+ {
+ "name": "search_stats",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Search observability over a window: cache hit rate, intent/mode mix, budget drops, rank-1 score drift, graph-signals failure counts. Same payload as the search-stats dashboard JSON. Coverage caveat: telemetry is best-effort (short-lived CLI calls may not flush), so zero counts can reflect the coverage gap rather than zero usage.",
+ "params": {
+ "days": {
+ "type": "number",
+ "required": false,
+ "description": "Window in days (default 7, clamped 1..365)."
+ }
+ },
+ "scope": "admin",
+ "area": "search"
+ },
+ {
+ "name": "search_modes",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Read-only search-mode dashboard: active mode, EVERY mode-bundle knob resolved with attribution (mode default vs config override), the three frozen bundles, and a reranker_readiness verdict (whether the resolved reranker will actually run; remote callers get the verdict without the host key inventory). Brain-level planes only — per-call SearchOpts overrides on individual searches are not shown (per_call_note in the payload spells this out). Never mutates; to change modes, tell the user to set the search.mode config key on the brain host.",
+ "params": {},
+ "scope": "read",
+ "mutating": false,
+ "area": "search"
+ },
+ {
+ "name": "search_tune",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Read-only tuning recommendations derived from the last 7 days of search telemetry: what should change, why, and the paste-ready config command per recommendation — relay them to the user. Applying is CLI-only by design [CDX-21]: this op NEVER mutates config.",
+ "params": {},
+ "scope": "admin",
+ "area": "search"
+ },
+ {
+ "name": "cache_stats",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Semantic query-cache introspection: resolved knobs (enabled, similarity threshold, TTL) plus row counts and total hits. Read-only; clearing/pruning the cache stays on the CLI.",
+ "params": {},
+ "scope": "admin",
+ "area": "search"
+ },
+ {
+ "name": "rate_answer",
+ "area": "search",
+ "outputRedaction": "no_stored_text",
+ "mutating": true,
+ "writeInference": "none",
+ "idempotent": true,
+ "description": "Rate how useful an answer's retrieved evidence was, so this brain ranks better next time (zero LLM calls). Pass the answer_id from a query/search/think/synthesize/recall response and rating 1-5, or rate single pages with pages: [{ ref: \"source_id:slug\", rating }]. Example: { answer_id: \"ans_01J…\", pages: [{ ref: \"default:people/alice-example\", rating: 1 }] }. Returns a receipt with each weight before/after; it never edits stored facts.",
+ "scope": "write",
+ "params": {
+ "answer_id": {
+ "type": "string",
+ "required": true,
+ "description": "The ans_… id from the answer you are rating."
+ },
+ "rating": {
+ "type": "number",
+ "description": "Whole-answer rating 1-5 (omit when using pages)."
+ },
+ "pages": {
+ "type": "array",
+ "description": "Per-page ratings: [{ ref: \"source_id:slug\", rating: 1-5 }]. Pages only; edges are not touched.",
+ "items": {
+ "type": "object"
+ }
+ }
+ },
+ "cliHints": {
+ "name": "rate",
+ "positional": [
+ "answer_id",
+ "rating"
+ ]
+ }
+ },
+ {
+ "name": "search_by_image",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Image-as-query retrieval. Accepts a local path (CLI), data: URI, or http(s):// URL (SSRF-defended). Returns visually-similar image chunks plus any OCR text they carry. Optional `query` text refinement merges via weighted RRF. Matching images to full-text knowledge needs multimodal indexing (`gbrain reindex --multimodal` + `search.unified_multimodal: true`).",
+ "params": {
+ "image_path": {
+ "type": "string",
+ "description": "Absolute path to image (local CLI callers only — rejected for remote MCP per D18)."
+ },
+ "image_url": {
+ "type": "string",
+ "description": "http(s):// URL to image. SSRF-defended; max 3 redirect hops; 10MB cap."
+ },
+ "image_data": {
+ "type": "string",
+ "description": "Base64-encoded image bytes (preferred for remote MCP callers). PNG/JPEG/WebP only."
+ },
+ "image_mime": {
+ "type": "string",
+ "description": "Optional MIME hint when ambiguous. Magic-byte sniff is authoritative."
+ },
+ "query": {
+ "type": "string",
+ "description": "Optional text refinement; runs hybrid intersect via D13 weighted RRF."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Max results (default 20)"
+ },
+ "offset": {
+ "type": "number",
+ "description": "Skip first N results (for pagination)"
+ },
+ "source_id": {
+ "type": "string",
+ "description": "Scope to a single source. Defaults to ctx.sourceId. '__all__' spans every source for trusted local callers, your granted sources for remote callers."
+ }
+ },
+ "scope": "read",
+ "cliHints": {
+ "name": "search-by-image"
+ },
+ "area": "search"
+ },
+ {
+ "name": "add_tag",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Add one tag to a page (idempotent). Use when filing or grouping pages for later get_tags / list_pages tag filters. Needs write scope. On page_not_found: resolve the slug with resolve_slugs, then call again.",
+ "params": {
+ "request_id": {
+ "type": "string",
+ "description": "UUID; retry with it on timeout."
+ },
+ "slug": {
+ "type": "string",
+ "required": true,
+ "description": "Slug of the page to tag, e.g. 'people/alice-example'."
+ },
+ "tag": {
+ "type": "string",
+ "required": true,
+ "description": "Tag to add — a plain string like 'founder' or 'follow-up', not a slug."
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "cliHints": {
+ "name": "tag",
+ "positional": [
+ "slug",
+ "tag"
+ ]
+ },
+ "area": "tags"
+ },
+ {
+ "name": "remove_tag",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Remove one tag from a page. Use when a tag was wrong or no longer applies. Needs write scope. On page_not_found: resolve the slug with resolve_slugs, then call again.",
+ "params": {
+ "request_id": {
+ "type": "string",
+ "description": "UUID; retry with it on timeout."
+ },
+ "slug": {
+ "type": "string",
+ "required": true,
+ "description": "Slug of the page to untag."
+ },
+ "tag": {
+ "type": "string",
+ "required": true,
+ "description": "Tag to remove (exact match against the tags get_tags returns)."
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "cliHints": {
+ "name": "untag",
+ "positional": [
+ "slug",
+ "tag"
+ ]
+ },
+ "area": "tags"
+ },
+ {
+ "name": "get_tags",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "List the tags on one page. Use when checking how a page is filed before adding or removing tags. Needs read scope. On page_not_found: resolve the slug with resolve_slugs.",
+ "params": {
+ "slug": {
+ "type": "string",
+ "required": true,
+ "description": "Slug of the page whose tags to list."
+ }
+ },
+ "scope": "read",
+ "cliHints": {
+ "name": "tags",
+ "positional": [
+ "slug"
+ ]
+ },
+ "area": "tags"
+ },
+ {
+ "name": "add_link",
+ "idempotent": false,
+ "outputRedaction": "no_stored_text",
+ "description": "Create a typed link (edge) from one page to another in the same source. Use when recording a relationship (works_at, invested_in, mentions); remote page writes already link [[wikilinks]] to existing pages as mentions (receipt auto_links), so add only typed links or ones the text lacks. Needs write scope; an explicit link_type must be declared by the active schema pack. On page_not_found: resolve both slugs with resolve_slugs.",
+ "params": {
+ "from": {
+ "type": "string",
+ "required": true,
+ "description": "Slug of the page the link originates from (the edge renders on this page), e.g. 'people/alice-example'. These are page slugs — there is no `source`/`target` pair."
+ },
+ "to": {
+ "type": "string",
+ "required": true,
+ "description": "Slug of the page the link points to, e.g. 'companies/acme-example'."
+ },
+ "link_type": {
+ "type": "string",
+ "description": "Link type (e.g., invested_in, works_at). When the active schema pack declares a link vocabulary, an explicit link_type must be one of its declared verbs (undeclared verbs are rejected, also under dry_run). Omitted = untyped edge."
+ },
+ "context": {
+ "type": "string",
+ "description": "Context for the link"
+ },
+ "link_source": {
+ "type": "string",
+ "description": "Provenance tag (kebab-case, e.g. 'citation-graph'). Defaults to 'manual'. Reconciliation-managed built-ins (markdown/frontmatter/mentions/wikilink-resolved) are rejected."
+ },
+ "valid_from": {
+ "type": "string",
+ "description": "When the relationship started (YYYY-MM-DD), for dated relations such as works_at or invested_in."
+ },
+ "valid_until": {
+ "type": "string",
+ "description": "When it ended (YYYY-MM-DD, exclusive). Re-run add_link with valid_until to record that a relationship ended."
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "cliHints": {
+ "name": "link",
+ "aliases": [
+ "link-add"
+ ],
+ "positional": [
+ "from",
+ "to"
+ ]
+ },
+ "area": "links"
+ },
+ {
+ "name": "remove_link",
+ "idempotent": false,
+ "outputRedaction": "no_stored_text",
+ "description": "Remove a link between two pages (optionally only one link_type or link_source). Use when a relationship was recorded wrongly. Needs write scope. On page_not_found: resolve both slugs with resolve_slugs.",
+ "params": {
+ "from": {
+ "type": "string",
+ "required": true,
+ "description": "Slug of the page the link originates from (same endpoint order as add_link)."
+ },
+ "to": {
+ "type": "string",
+ "required": true,
+ "description": "Slug of the page the link points to."
+ },
+ "link_type": {
+ "type": "string",
+ "description": "Only remove edges of this link type (omit = all types)"
+ },
+ "link_source": {
+ "type": "string",
+ "description": "Only remove edges of this provenance (e.g. citation-graph); omit = any provenance"
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "cliHints": {
+ "name": "unlink",
+ "aliases": [
+ "link-rm"
+ ],
+ "positional": [
+ "from",
+ "to"
+ ]
+ },
+ "area": "links"
+ },
+ {
+ "name": "get_links",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "List a page's outgoing links (typed edges to other pages). Use when exploring what a page points at; rows carry status and dates, live relationships by default (status: \"all\" for history, during: \"2022\" for a period). Pass source_id or all_sources to widen. Needs read scope. On page_not_found: resolve the slug with resolve_slugs.",
+ "params": {
+ "slug": {
+ "type": "string",
+ "required": true,
+ "description": "Slug of the page whose outgoing links to list."
+ },
+ "link_type": {
+ "type": "string",
+ "description": "Only this type."
+ },
+ "status": {
+ "type": "string",
+ "enum": [
+ "live",
+ "ended",
+ "all"
+ ],
+ "description": "Default live (true now)."
+ },
+ "as_of": {
+ "type": "string",
+ "description": "YYYY-MM-DD."
+ },
+ "during": {
+ "type": "string",
+ "description": "Period: 2022, 2022-03 or 2021..2023."
+ },
+ "source_id": {
+ "type": "string",
+ "description": "One source, or '__all__'."
+ },
+ "all_sources": {
+ "type": "boolean",
+ "description": "Same as source_id __all__."
+ }
+ },
+ "scope": "read",
+ "cliHints": {
+ "name": "links",
+ "aliases": [
+ "get_links"
+ ],
+ "positional": [
+ "slug"
+ ]
+ },
+ "area": "links"
+ },
+ {
+ "name": "get_backlinks",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Links to a page; group:\"page\" pages by referrer, newest first.",
+ "params": {
+ "slug": {
+ "type": "string",
+ "description": "Page slug.",
+ "required": true
+ },
+ "status": {
+ "type": "string",
+ "enum": [
+ "live",
+ "all"
+ ],
+ "description": "Default live."
+ },
+ "as_of": {
+ "type": "string",
+ "description": "YYYY-MM-DD"
+ },
+ "source_id": {
+ "type": "string",
+ "description": "One source, or '__all__'."
+ },
+ "all_sources": {
+ "type": "boolean",
+ "description": "Same as source_id __all__."
+ },
+ "type": {
+ "type": "string",
+ "description": "Referrer type."
+ },
+ "group": {
+ "type": "string",
+ "enum": [
+ "page"
+ ],
+ "description": "Per page."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Max 500."
+ },
+ "cursor": {
+ "type": "string",
+ "description": "Paging."
+ }
+ },
+ "scope": "read",
+ "cliHints": {
+ "name": "backlinks",
+ "positional": [
+ "slug"
+ ]
+ },
+ "area": "links"
+ },
+ {
+ "name": "list_link_sources",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Link provenances in the brain (e.g. markdown, manual) with edge counts.",
+ "params": {},
+ "scope": "read",
+ "cliHints": {
+ "name": "link-sources"
+ },
+ "area": "links"
+ },
+ {
+ "name": "traverse_graph",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Walk the link graph from a page. Remote callers get bidirectional paths at depth 2 by default.",
+ "params": {
+ "slug": {
+ "type": "string",
+ "description": "Start page slug.",
+ "required": true
+ },
+ "depth": {
+ "type": "number",
+ "description": "Max depth (cap 10)."
+ },
+ "link_type": {
+ "type": "string",
+ "description": "Follow only this link type."
+ },
+ "direction": {
+ "type": "string",
+ "description": "Remote default both.",
+ "enum": [
+ "in",
+ "out",
+ "both"
+ ]
+ },
+ "hops": {
+ "type": "array",
+ "description": "≤3 typed hops, e.g. [{\"link_type\":\"founded\",\"toward\":\"subject\"}]; toward: object|subject.",
+ "items": {
+ "type": "object",
+ "properties": {
+ "link_type": {
+ "type": "string"
+ },
+ "toward": {
+ "type": "string"
+ }
+ }
+ },
+ "fullSurfaceOnly": true
+ },
+ "source_id": {
+ "type": "string",
+ "description": "One source, or '__all__'."
+ },
+ "all_sources": {
+ "type": "boolean",
+ "description": "Same as source_id __all__."
+ }
+ },
+ "scope": "read",
+ "cliHints": {
+ "name": "graph",
+ "positional": [
+ "slug"
+ ]
+ },
+ "area": "links"
+ },
+ {
+ "name": "wanted_pages",
+ "mutating": false,
+ "writeInference": "none",
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Link targets that have no page yet, most-referenced first: each was written as a link but its page does not exist, so no edge exists. Use to find entities worth a page (enrichment) or typo links to fix. The edge appears on its own once the page is created.",
+ "params": {
+ "source_id": {
+ "type": "string",
+ "description": "Only targets referenced from this source (must be inside your source grant)."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Rows per page (default 50, max 100)."
+ },
+ "offset": {
+ "type": "number",
+ "description": "Skip the first N targets."
+ },
+ "count_only": {
+ "type": "boolean",
+ "description": "Return the total with no rows."
+ }
+ },
+ "scope": "read",
+ "cliHints": {
+ "name": "wanted"
+ },
+ "area": "links"
+ },
+ {
+ "name": "add_timeline_entry",
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Append a dated entry to a page timeline. Replaying the same entry changes nothing. A page's Timeline section needs no call.",
+ "params": {
+ "request_id": {
+ "type": "string",
+ "description": "UUID; retry with it on timeout."
+ },
+ "slug": {
+ "type": "string",
+ "description": "Page slug.",
+ "required": true
+ },
+ "date": {
+ "type": "string",
+ "required": true,
+ "description": "YYYY-MM-DD."
+ },
+ "summary": {
+ "type": "string",
+ "required": true,
+ "description": "One line."
+ },
+ "detail": {
+ "type": "string",
+ "description": "Longer text."
+ },
+ "source": {
+ "type": "string",
+ "description": "Provenance slug or URL."
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "cliHints": {
+ "name": "timeline-add",
+ "positional": [
+ "slug",
+ "date",
+ "summary"
+ ]
+ },
+ "area": "timeline"
+ },
+ {
+ "name": "get_timeline",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Get timeline entries for a page, optionally filtered by date window",
+ "params": {
+ "slug": {
+ "type": "string",
+ "required": true,
+ "description": "Slug of the page whose timeline entries to return."
+ },
+ "after": {
+ "type": "string",
+ "description": "Return entries on or after this date (YYYY-MM-DD)"
+ },
+ "before": {
+ "type": "string",
+ "description": "Return entries on or before this date (YYYY-MM-DD)"
+ },
+ "since": {
+ "type": "string",
+ "description": "Alias for after; accepted for agent callers"
+ },
+ "until": {
+ "type": "string",
+ "description": "Alias for before; accepted for agent callers"
+ },
+ "limit": {
+ "type": "number",
+ "description": "Maximum number of timeline entries to return"
+ }
+ },
+ "scope": "read",
+ "cliHints": {
+ "name": "timeline",
+ "positional": [
+ "slug"
+ ]
+ },
+ "area": "timeline"
+ },
+ {
+ "name": "get_stats",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Brain statistics (page count, chunk count, etc.) — remote callers see counters confined to their source grant.",
+ "params": {},
+ "scope": "admin",
+ "cliHints": {
+ "name": "stats"
+ },
+ "area": "admin"
+ },
+ {
+ "name": "get_health",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Brain health dashboard (embed coverage, stale pages, orphans) — remote callers see counters confined to their source grant. Includes a `migrations {pending, pending_fresh_install, partial, wedged, skipped_future}` block from the host migration ledger so remote agents can detect wedged/outstanding host migrations without shelling into the brain host (pending_fresh_install = setup a new brain has not run yet, not a broken upgrade). `computed_at` is when the counters were read: a repeat call within `health.cache_ttl_ms` (default 30000; env GBRAIN_HEALTH_CACHE_TTL_MS; 0 disables) with no page or config change returns the memoized numbers.",
+ "params": {},
+ "scope": "admin",
+ "cliHints": {
+ "name": "health"
+ },
+ "area": "admin"
+ },
+ {
+ "name": "run_doctor",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Run brain health checks and return a structured DoctorReport (thin-client doctor surface).",
+ "params": {},
+ "scope": "admin",
+ "localOnly": false,
+ "area": "admin"
+ },
+ {
+ "name": "get_versions",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": {
+ "exempt": "full page version snapshots by slug; a page read governed by visibility like get_page (CEO-17)"
+ },
+ "description": "Page version history, newest snapshot first. Trusted local and admin callers also get written_by and archived_by (who wrote each snapshot and whose write archived it). `limit` returns only the newest N; `include_body: false` returns metadata only.",
+ "params": {
+ "slug": {
+ "type": "string",
+ "required": true,
+ "description": "Slug of the page whose version history to list."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Return only the newest N versions (a positive integer). Omit for the full history."
+ },
+ "include_body": {
+ "type": "boolean",
+ "description": "false omits compiled_truth and timeline from every version (metadata only). Default true."
+ }
+ },
+ "scope": "read",
+ "cliHints": {
+ "name": "history",
+ "positional": [
+ "slug"
+ ]
+ },
+ "area": "pages"
+ },
+ {
+ "name": "revert_version",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Restore a page to an earlier version from its history (a new revision; history is kept). Use when an edit must be undone. Needs write scope. On a revision conflict: re-read the page with get_page and resubmit with its revision.",
+ "params": {
+ "source_id": {
+ "type": "string",
+ "description": "Write source."
+ },
+ "expected_revision": {
+ "type": "string",
+ "description": "Revision read; omit to create."
+ },
+ "force": {
+ "type": "boolean",
+ "description": "Ignore the revision."
+ },
+ "request_id": {
+ "type": "string",
+ "description": "UUID; retry with it on timeout."
+ },
+ "slug": {
+ "type": "string",
+ "required": true,
+ "description": "Slug of the page to revert."
+ },
+ "version_id": {
+ "type": "number",
+ "required": true,
+ "description": "Numeric version id to revert to, as returned by get_versions. Not a version NUMBER offset — pass the id field."
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "cliHints": {
+ "name": "revert",
+ "positional": [
+ "slug",
+ "version_id"
+ ]
+ },
+ "area": "pages"
+ },
+ {
+ "name": "get_brain_identity",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Brain identity + counters for thin-client banner — remote callers see counters confined to their source grant. Returns version, engine kind, and page/chunk counts. Read-scope.",
+ "params": {},
+ "scope": "read",
+ "area": "identity"
+ },
+ {
+ "name": "quarantine_list",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "List quarantined (hidden) and optionally content-flagged pages by scanning page frontmatter, newest-updated first. When truncated is true, count is a LOWER BOUND — raise max_scan/limit or run the quarantine list command on the brain host for the full set. Clearing a marker is a local-only trust decision (CLI).",
+ "params": {
+ "include_flagged": {
+ "type": "boolean",
+ "required": false,
+ "description": "Also list content_flag pages (searchable-but-warned). Default false."
+ },
+ "limit": {
+ "type": "number",
+ "required": false,
+ "description": "Max rows returned (default 200, cap 1000)."
+ },
+ "max_scan": {
+ "type": "number",
+ "required": false,
+ "description": "Max pages scanned (default 20000, cap 100000)."
+ }
+ },
+ "scope": "admin",
+ "area": "admin"
+ },
+ {
+ "name": "get_write_attribution",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Admin read: who created and who last changed a page, or one of its facts, takes or timeline entries. Each attribution names the request id, operation, principal (kind, id, current name), time and origin (request, maintenance or unrecorded). Remote callers stay inside their source grant and see only world facts.",
+ "params": {
+ "slug": {
+ "type": "string",
+ "required": true,
+ "description": "Slug of the page to attribute (or the page that holds the fact, take or timeline entry)."
+ },
+ "fact": {
+ "type": "number",
+ "description": "Attribute this fact id (a fact about or fenced on the page) instead of the page."
+ },
+ "take": {
+ "type": "number",
+ "description": "Attribute the take at this row number of the page's takes table."
+ },
+ "timeline": {
+ "type": "number",
+ "description": "Attribute this timeline entry id of the page."
+ },
+ "versions": {
+ "type": "boolean",
+ "description": "Also list every version snapshot with who wrote and who archived it."
+ }
+ },
+ "scope": "admin",
+ "localOnly": false,
+ "cliHints": {
+ "name": "attribution",
+ "positional": [
+ "slug"
+ ]
+ },
+ "area": "admin"
+ },
+ {
+ "name": "list_skills",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Skills: prose instruction sets (NOT executable code) for tasks with this server's tools, with triggers, usable_tools and unavailable_tools. Use one via get_skill.",
+ "publishGateKey": "mcp.publish_skills",
+ "params": {
+ "schema_version": {
+ "type": "number",
+ "description": "2 for the source-qualified catalog."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Version 2 page size (1-100)."
+ },
+ "cursor": {
+ "type": "string",
+ "description": "Version 2 cursor."
+ },
+ "source_id": {
+ "type": "string",
+ "description": "Version 2: one source."
+ },
+ "section": {
+ "type": "string",
+ "description": "Only this routing section."
+ }
+ },
+ "scope": "read",
+ "cliHints": {
+ "name": "skills",
+ "positional": []
+ },
+ "area": "skills"
+ },
+ {
+ "name": "get_skill",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": {
+ "exempt": "skill catalog files are installed instructions read verbatim; redaction would corrupt approved revisions"
+ },
+ "description": "Fetch a skill's prose and follow it: when it says search or store, call the same-named MCP tool here. There is nothing to execute. unavailable_tools won't work for you.",
+ "publishGateKey": "mcp.publish_skills",
+ "params": {
+ "schema_version": {
+ "type": "number",
+ "description": "2 for an exact canonical revision."
+ },
+ "qualified_id": {
+ "type": "string",
+ "description": "Version 2 skill id."
+ },
+ "expected_brain_id": {
+ "type": "string",
+ "description": "Version 2 brain id to assert."
+ },
+ "source_incarnation": {
+ "type": "string",
+ "description": "From discovery."
+ },
+ "pack_id": {
+ "type": "string",
+ "description": "Pack id."
+ },
+ "revision": {
+ "type": "string",
+ "description": "Exact revision (default: head)."
+ },
+ "name": {
+ "type": "string",
+ "description": "Skill name from list_skills."
+ },
+ "source_id": {
+ "type": "string",
+ "description": "Fetch a brain-resident pack skill from this source."
+ }
+ },
+ "scope": "read",
+ "cliHints": {
+ "name": "skill",
+ "positional": [
+ "name"
+ ]
+ },
+ "area": "skills"
+ },
+ {
+ "name": "list_brain_skillpack",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": {
+ "exempt": "skill catalog files are installed instructions read verbatim; redaction would corrupt approved revisions"
+ },
+ "description": "Skillpacks this brain ships, with skills and a scaffold spec to offer the user.",
+ "publishGateKey": "mcp.publish_skills",
+ "params": {},
+ "scope": "read",
+ "cliHints": {
+ "name": "brain-skillpack",
+ "positional": []
+ },
+ "area": "skills"
+ },
+ {
+ "name": "advisor",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Ranked, read-only \"what to do next\" for this brain: version drift, pending migrations, schema-pack issues, stalled jobs, usage-shape gaps, and setup smells. Each finding has a severity, why-it-matters, and the exact fix command. Never mutates. Tell the user; ask before running any fix. On by default for the local stdio server; remote HTTP callers need mcp.publish_advisor (separate from mcp.publish_skills because diagnostics are not prose skills).",
+ "publishGateKey": "mcp.publish_advisor",
+ "params": {},
+ "scope": "read",
+ "cliHints": {
+ "name": "advisor",
+ "hidden": true
+ },
+ "area": "advisor"
+ },
+ {
+ "name": "get_status_snapshot",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Snapshot for `gbrain status` thin-client mode: sync freshness + last cycle + queue depths + worker liveness. Admin-scope.",
+ "params": {},
+ "scope": "admin",
+ "localOnly": false,
+ "area": "admin"
+ },
+ {
+ "name": "get_skill_asset",
+ "description": "Read an approved file from an exact skill revision (data only; never executed).",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": {
+ "exempt": "skill catalog files are installed instructions read verbatim; redaction would corrupt approved revisions"
+ },
+ "scope": "read",
+ "publishGateKey": "mcp.publish_skills",
+ "cliHints": {
+ "name": "skill-asset",
+ "positional": []
+ },
+ "params": {
+ "source_id": {
+ "type": "string",
+ "description": "Exactly one granted source."
+ },
+ "source_incarnation": {
+ "type": "string",
+ "description": "From the qualified catalog."
+ },
+ "name": {
+ "type": "string",
+ "description": "Skill name."
+ },
+ "pack_id": {
+ "type": "string",
+ "description": "Pack id."
+ },
+ "qualified_id": {
+ "type": "string",
+ "description": "Version 2 skill id."
+ },
+ "expected_brain_id": {
+ "type": "string",
+ "description": "Brain id to assert."
+ },
+ "revision": {
+ "type": "string",
+ "required": true,
+ "description": "Revision from get_skill."
+ },
+ "path": {
+ "type": "string",
+ "required": true,
+ "description": "Path in that revision manifest."
+ }
+ },
+ "area": "skills"
+ },
+ {
+ "name": "put_skill",
+ "description": "Publish a complete file-canonical skill revision with CAS and a durable receipt. Requires explicit skill editor authority; cannot expand publication policy.",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "scope": "write",
+ "requiredScopes": [
+ "skill_editor"
+ ],
+ "mutating": true,
+ "cliHints": {
+ "name": "put-skill",
+ "positional": []
+ },
+ "params": {
+ "source_id": {
+ "type": "string",
+ "description": "Exactly one granted source."
+ },
+ "source_incarnation": {
+ "type": "string",
+ "description": "From the qualified catalog."
+ },
+ "pack_id": {
+ "type": "string",
+ "required": true,
+ "description": "Canonical pack identifier."
+ },
+ "name": {
+ "type": "string",
+ "required": true,
+ "description": "Canonical skill name."
+ },
+ "request_id": {
+ "type": "string",
+ "required": true,
+ "description": "Durable idempotency UUID; reuse only with identical intent."
+ },
+ "expected_revision": {
+ "type": "string",
+ "description": "Current revision UUID; JSON null for creation."
+ },
+ "description": {
+ "type": "string",
+ "description": "Compact routing description."
+ },
+ "triggers": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Routing phrases."
+ },
+ "requirements": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Approved runtime and tool requirement tokens."
+ },
+ "private": {
+ "type": "boolean",
+ "description": "Exclude this skill from remote publication."
+ },
+ "files": {
+ "type": "array",
+ "items": {
+ "type": "object"
+ },
+ "required": true,
+ "description": "Complete closure: path, content, encoding (utf8/base64), file_class, audience, media_type, depends_on."
+ }
+ },
+ "area": "skills"
+ },
+ {
+ "name": "delete_skill",
+ "description": "CAS-delete a canonical shared skill and revoke future managed activation. Previously downloaded bytes are not recalled.",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "scope": "write",
+ "requiredScopes": [
+ "skill_editor"
+ ],
+ "mutating": true,
+ "params": {
+ "source_id": {
+ "type": "string",
+ "description": "Exactly one granted source."
+ },
+ "source_incarnation": {
+ "type": "string",
+ "description": "From the qualified catalog."
+ },
+ "pack_id": {
+ "type": "string",
+ "required": true,
+ "description": "Canonical pack identifier."
+ },
+ "name": {
+ "type": "string",
+ "required": true,
+ "description": "Canonical skill name."
+ },
+ "request_id": {
+ "type": "string",
+ "required": true,
+ "description": "Durable idempotency UUID; reuse only with identical intent."
+ },
+ "expected_revision": {
+ "type": "string",
+ "description": "Current revision UUID; JSON null for creation."
+ }
+ },
+ "cliHints": {
+ "name": "delete-skill",
+ "positional": []
+ },
+ "area": "skills"
+ },
+ {
+ "name": "set_skill_policy",
+ "description": "Explicitly approve a versioned shared-skill disclosure and follow policy. Separate publisher authority is required; editing a skill never grants this permission.",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "scope": "admin",
+ "requiredScopes": [
+ "skill_publisher"
+ ],
+ "mutating": true,
+ "cliHints": {
+ "name": "set-skill-policy",
+ "positional": []
+ },
+ "params": {
+ "source_id": {
+ "type": "string",
+ "required": true,
+ "description": "Source whose publication policy is approved."
+ },
+ "expected_policy_epoch": {
+ "type": "string",
+ "description": "Previously reviewed policy epoch; null for initial policy."
+ },
+ "policy": {
+ "type": "object",
+ "required": true,
+ "description": "version:1, enabled, classes, audiences, requirements, allow_follow."
+ }
+ },
+ "area": "skills"
+ },
+ {
+ "name": "get_skill_policy",
+ "description": "Read the owner publication policy and CAS epoch, including when sharing is disabled. Does not approve or change disclosure.",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "scope": "admin",
+ "requiredScopes": [
+ "skill_publisher"
+ ],
+ "cliHints": {
+ "name": "skill-policy",
+ "positional": []
+ },
+ "params": {
+ "source_id": {
+ "type": "string",
+ "required": true,
+ "description": "Source whose publication policy is reviewed."
+ }
+ },
+ "area": "skills"
+ },
+ {
+ "name": "get_skill_retention",
+ "description": "Inspect retained shared-skill revision counts, protected leases and source storage capacity. Trusted host operator only.",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "scope": "admin",
+ "localOnly": true,
+ "cliOnly": {
+ "argv": [
+ "gbrain",
+ "skill-retention"
+ ]
+ },
+ "cliHints": {
+ "name": "skill-retention",
+ "positional": []
+ },
+ "params": {
+ "source_id": {
+ "type": "string",
+ "description": "Canonical source to inspect."
+ }
+ },
+ "area": "skills"
+ },
+ {
+ "name": "prune_skill_revisions",
+ "description": "Prune one bounded batch of expired shared-skill history. Preserves heads, tombstones, pending publication refs, delivery leases, pins and permanent write receipts.",
+ "idempotent": false,
+ "outputRedaction": "no_stored_text",
+ "scope": "admin",
+ "localOnly": true,
+ "cliOnly": {
+ "argv": [
+ "gbrain",
+ "prune-skill-revisions"
+ ]
+ },
+ "mutating": true,
+ "cliHints": {
+ "name": "prune-skill-revisions",
+ "positional": []
+ },
+ "params": {
+ "source_id": {
+ "type": "string",
+ "description": "Canonical source to prune."
+ }
+ },
+ "area": "skills"
+ },
+ {
+ "name": "retain_skill_revision",
+ "description": "Pin an exact shared-skill revision for up to 24 hours under a bounded operator quota. Does not grant read or execution permission.",
+ "idempotent": false,
+ "outputRedaction": "no_stored_text",
+ "scope": "admin",
+ "localOnly": true,
+ "cliOnly": {
+ "argv": [
+ "gbrain",
+ "retain-skill-revision"
+ ]
+ },
+ "mutating": true,
+ "cliHints": {
+ "name": "retain-skill-revision",
+ "positional": []
+ },
+ "params": {
+ "source_id": {
+ "type": "string",
+ "description": "Exactly one granted source."
+ },
+ "source_incarnation": {
+ "type": "string",
+ "required": true,
+ "description": "Exact source incarnation."
+ },
+ "pack_id": {
+ "type": "string",
+ "required": true,
+ "description": "Canonical pack identifier."
+ },
+ "name": {
+ "type": "string",
+ "required": true,
+ "description": "Canonical skill name."
+ },
+ "revision": {
+ "type": "string",
+ "required": true,
+ "description": "Exact existing immutable revision."
+ },
+ "hours": {
+ "type": "number",
+ "description": "Pin lifetime greater than zero and at most 24 hours."
+ }
+ },
+ "area": "skills"
+ },
+ {
+ "name": "import_skill_proposal",
+ "description": "Publish explicitly reviewed human-edited canonical skill files through the durable coordinator. Requires exact current file hashes and skill revision; trusted local operator only.",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "scope": "admin",
+ "localOnly": true,
+ "cliOnly": {
+ "argv": [
+ "gbrain",
+ "call",
+ "import_skill_proposal",
+ "<params_json>"
+ ]
+ },
+ "mutating": true,
+ "params": {
+ "source_id": {
+ "type": "string",
+ "description": "Exactly one granted source."
+ },
+ "source_incarnation": {
+ "type": "string",
+ "description": "From the qualified catalog."
+ },
+ "pack_id": {
+ "type": "string",
+ "required": true,
+ "description": "Canonical pack identifier."
+ },
+ "name": {
+ "type": "string",
+ "required": true,
+ "description": "Canonical skill name."
+ },
+ "request_id": {
+ "type": "string",
+ "required": true,
+ "description": "Durable idempotency UUID; reuse only with identical intent."
+ },
+ "expected_revision": {
+ "type": "string",
+ "description": "Current revision UUID; JSON null for creation."
+ },
+ "description": {
+ "type": "string",
+ "description": "Compact routing description."
+ },
+ "triggers": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Routing phrases."
+ },
+ "requirements": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Approved runtime and tool requirement tokens."
+ },
+ "private": {
+ "type": "boolean",
+ "description": "Exclude this skill from remote publication."
+ },
+ "files": {
+ "type": "array",
+ "items": {
+ "type": "object"
+ },
+ "required": true,
+ "description": "Complete closure: path, content, encoding (utf8/base64), file_class, audience, media_type, depends_on."
+ },
+ "expected_hashes": {
+ "type": "object",
+ "required": true,
+ "description": "Reviewed current SHA-256 hashes for every affected file and skillpack.json; null denotes an absent file."
+ }
+ },
+ "area": "skills"
+ },
+ {
+ "name": "join_brain",
+ "description": "Enroll this authenticated principal to follow approved shared skills. Shared credentials are one principal. Never grants memory-write or editor authority.",
+ "idempotent": false,
+ "outputRedaction": "no_stored_text",
+ "scope": "read",
+ "mutating": true,
+ "requiredScopes": [
+ "skills_member_self"
+ ],
+ "cliHints": {
+ "name": "join-brain",
+ "positional": []
+ },
+ "params": {
+ "adapter": {
+ "type": "string",
+ "required": true,
+ "description": "Registered harness adapter ID for this authenticated installation."
+ },
+ "follow_policy": {
+ "type": "object",
+ "required": true,
+ "description": "Explicit approved:true and optional source_ids narrowing."
+ }
+ },
+ "area": "skills"
+ },
+ {
+ "name": "sync_brain_skills",
+ "description": "Get a complete authorized shared-skills view and optionally record an own issued-batch delivery acknowledgment. Unavailable is never an empty catalog.",
+ "idempotent": false,
+ "outputRedaction": {
+ "exempt": "skill catalog files are installed instructions read verbatim; redaction would corrupt approved revisions"
+ },
+ "scope": "read",
+ "mutating": true,
+ "requiredScopes": [
+ "skills_member_self"
+ ],
+ "cliHints": {
+ "name": "sync-brain-skills",
+ "positional": []
+ },
+ "params": {
+ "installation_id": {
+ "type": "string",
+ "required": true,
+ "description": "Own server-issued installation UUID returned by join_brain."
+ },
+ "enrollment_epoch": {
+ "type": "number",
+ "required": true,
+ "description": "Current enrollment epoch returned by join_brain; stale epochs cannot reactivate membership."
+ },
+ "acknowledgment": {
+ "type": "object",
+ "description": "Optional issued batch token and exact delivery evidence for this installation, never proof of native use."
+ }
+ },
+ "area": "skills"
+ },
+ {
+ "name": "leave_brain",
+ "description": "Stop only this principal’s enrollment. Does not revoke credentials or prove native cached instructions were disabled.",
+ "idempotent": false,
+ "outputRedaction": "no_stored_text",
+ "scope": "read",
+ "mutating": true,
+ "requiredScopes": [
+ "skills_member_self"
+ ],
+ "cliHints": {
+ "name": "leave-brain",
+ "positional": []
+ },
+ "params": {
+ "installation_id": {
+ "type": "string",
+ "required": true,
+ "description": "Own server-issued installation UUID to leave."
+ },
+ "enrollment_epoch": {
+ "type": "number",
+ "required": true,
+ "description": "Current enrollment epoch; a previous installation cannot leave its replacement."
+ }
+ },
+ "area": "skills"
+ },
+ {
+ "name": "sync_brain",
+ "idempotent": false,
+ "outputRedaction": "no_stored_text",
+ "description": "Pull and import changes from a source's git repository (incremental; dry_run previews). Use when files changed on disk or upstream. Needs admin scope and the local stdio server. On a missing local_path: the error names the sources add command.",
+ "params": {
+ "repo": {
+ "type": "string",
+ "description": "Path to git repo (optional if configured)"
+ },
+ "source_id": {
+ "type": "string",
+ "description": "Explicit source to sync (wins over repo-derived and ambient routing)"
+ },
+ "dry_run": {
+ "type": "boolean",
+ "description": "Preview changes without applying"
+ },
+ "full": {
+ "type": "boolean",
+ "description": "Full re-sync (ignore checkpoint)"
+ },
+ "no_pull": {
+ "type": "boolean",
+ "description": "Skip git pull"
+ },
+ "no_embed": {
+ "type": "boolean",
+ "description": "Skip embedding generation"
+ }
+ },
+ "mutating": true,
+ "scope": "admin",
+ "localOnly": true,
+ "cliHints": {
+ "name": "sync",
+ "hidden": true
+ },
+ "area": "sync"
+ },
+ {
+ "name": "put_raw_data",
+ "idempotent": false,
+ "outputRedaction": "no_stored_text",
+ "description": "Store a raw provider payload (API response JSON) alongside a page, keyed by source. Use when keeping the original data an enrichment came from. Needs write scope. On page_not_found: create or resolve the page first.",
+ "params": {
+ "slug": {
+ "type": "string",
+ "required": true,
+ "description": "Slug of the page to attach the raw data to."
+ },
+ "source": {
+ "type": "string",
+ "required": true,
+ "description": "Data source (e.g., crustdata, happenstance)"
+ },
+ "data": {
+ "type": "object",
+ "required": true,
+ "description": "Raw data object"
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "area": "pages"
+ },
+ {
+ "name": "get_raw_data",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": {
+ "exempt": "explicit raw sidecar read by slug; governed by page visibility (CEO-17 raw-read exception)"
+ },
+ "description": "Retrieve raw data for a page. Raw data follows the page's soft-delete: a tombstoned (soft-deleted) page returns [] exactly like a missing page; restore_page brings the rows back, and get_page include_deleted: true verifies the tombstone.",
+ "params": {
+ "slug": {
+ "type": "string",
+ "required": true,
+ "description": "Slug of the page whose raw data to fetch."
+ },
+ "source": {
+ "type": "string",
+ "description": "Filter by source"
+ }
+ },
+ "scope": "read",
+ "area": "pages"
+ },
+ {
+ "name": "resolve_slugs",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Fuzzy-match a partial slug or title to page slugs. Use when a slug is uncertain. Needs read scope.",
+ "params": {
+ "partial": {
+ "type": "string",
+ "required": true,
+ "description": "Partial slug or title, e.g. 'alice-ex'."
+ },
+ "source_id": {
+ "type": "string",
+ "description": "One source, or '__all__'."
+ }
+ },
+ "scope": "read",
+ "area": "pages"
+ },
+ {
+ "name": "get_chunks",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": {
+ "exempt": "explicit chunk read by slug, the page-read twin of get_page (CEO-17 raw-read exception)"
+ },
+ "description": "Return a page's indexed content chunks (the units search ranks). Use when debugging why search did or did not match a page. Needs read scope. On page_not_found: resolve the slug with resolve_slugs.",
+ "params": {
+ "slug": {
+ "type": "string",
+ "required": true,
+ "description": "Slug of the page whose content chunks to return."
+ }
+ },
+ "scope": "read",
+ "area": "pages"
+ },
+ {
+ "name": "log_ingest",
+ "idempotent": false,
+ "outputRedaction": "no_stored_text",
+ "description": "Record one ingestion event (source type, reference, pages updated, summary) in the brain's ingest log. Use after importing or enriching content. Needs write scope.",
+ "params": {
+ "source_type": {
+ "type": "string",
+ "required": true,
+ "description": "Kind of ingest source, e.g. 'email', 'meeting', 'rss', 'api'."
+ },
+ "source_ref": {
+ "type": "string",
+ "required": true,
+ "description": "Identifier of the ingested item — a URL, message id, or file path."
+ },
+ "pages_updated": {
+ "type": "array",
+ "required": true,
+ "items": {
+ "type": "string"
+ },
+ "description": "Slugs of the pages this ingest created or updated."
+ },
+ "summary": {
+ "type": "string",
+ "required": true,
+ "description": "One-line human-readable summary of what was ingested."
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "area": "ingest"
+ },
+ {
+ "name": "get_ingest_log",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Recent ingestion log entries. Use when checking what was already imported.",
+ "params": {
+ "limit": {
+ "type": "number",
+ "description": "Default 20."
+ }
+ },
+ "scope": "read",
+ "area": "ingest"
+ },
+ {
+ "name": "get_usage",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Aggregate chat usage + cost from the chat_usage_log ledger (per-model and per-phase token counts, cache reads/writes, USD estimates) with explicit coverage fields.",
+ "params": {
+ "days": {
+ "type": "number",
+ "description": "Window in days (default 30, max 365)."
+ }
+ },
+ "scope": "admin",
+ "area": "admin"
+ },
+ {
+ "name": "file_list",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "List files stored in the brain's file storage, optionally for one page. Use when finding attachments before file_url. Needs admin scope and the local stdio server.",
+ "params": {
+ "slug": {
+ "type": "string",
+ "description": "Filter by page slug"
+ }
+ },
+ "scope": "admin",
+ "localOnly": true,
+ "area": "files"
+ },
+ {
+ "name": "file_upload",
+ "idempotent": false,
+ "outputRedaction": "no_stored_text",
+ "description": "Upload a local file into brain storage and attach it to a page. Use when a page needs its source document or image. Needs admin scope and the local stdio server; agent callers may only upload files under the server's working directory.",
+ "params": {
+ "path": {
+ "type": "string",
+ "required": true,
+ "description": "Local file path"
+ },
+ "page_slug": {
+ "type": "string",
+ "description": "Associate with page"
+ }
+ },
+ "mutating": true,
+ "scope": "admin",
+ "localOnly": true,
+ "area": "files"
+ },
+ {
+ "name": "file_url",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Return a URL for a stored file. Use when a user needs to open an attachment listed by file_list. Needs admin scope and the local stdio server. On storage_error: list the files again with file_list.",
+ "params": {
+ "storage_path": {
+ "type": "string",
+ "required": true
+ }
+ },
+ "scope": "admin",
+ "localOnly": true,
+ "area": "files"
+ },
+ {
+ "name": "submit_job",
+ "idempotent": false,
+ "outputRedaction": {
+ "exempt": "admin-scoped job introspection: job params and results are operator data, not retrieved brain text"
+ },
+ "description": "Submit a background job. Remote callers may submit sync, import, lint or lint-fix for their authenticated filesystem source. Other kinds require local CLI or a dedicated operation.",
+ "params": {
+ "name": {
+ "type": "string",
+ "required": true,
+ "description": "Remote job type: sync, import, lint, or lint-fix. Local CLI also supports other registered types."
+ },
+ "data": {
+ "type": "object",
+ "description": "Remote sync accepts optional pull/noPull (one boolean); other remote jobs accept no parameters. Source and paths are derived from the grant."
+ },
+ "queue": {
+ "type": "string",
+ "description": "Queue name (default: \"default\")"
+ },
+ "priority": {
+ "type": "number",
+ "description": "Priority (0 = highest, default: 0)"
+ },
+ "max_attempts": {
+ "type": "number",
+ "description": "Max retry attempts (default: 3)"
+ },
+ "delay": {
+ "type": "number",
+ "description": "Delay in ms before eligible"
+ },
+ "timeout_ms": {
+ "type": "number",
+ "description": "Per-job wall-clock timeout in ms; aborted job goes to dead"
+ },
+ "lock_duration_ms": {
+ "type": "number",
+ "description": "Per-job lock lease in ms (#4145). Out-of-range values are clamped to [5000, 3600000] — remote writers cannot pin an immortal lock. Omit to use the handler-type default (300s for long LLM handlers) or the worker default (30s)."
+ }
+ },
+ "mutating": true,
+ "scope": "admin",
+ "area": "jobs"
+ },
+ {
+ "name": "get_job",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": {
+ "exempt": "admin-scoped job introspection: job params and results are operator data, not retrieved brain text"
+ },
+ "description": "Get job status and details by ID. Agent-scoped tokens (no admin) see only jobs they own.",
+ "params": {
+ "id": {
+ "type": "number",
+ "required": true,
+ "description": "Job ID"
+ }
+ },
+ "scope": "admin",
+ "agentCallable": true,
+ "area": "jobs"
+ },
+ {
+ "name": "list_jobs",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": {
+ "exempt": "admin-scoped job introspection: job params and results are operator data, not retrieved brain text"
+ },
+ "description": "List background jobs with optional status/queue/name filters; pass fields to project each job to the columns you need. Use when checking queued or failed work. Needs admin scope (agent-scoped tokens see only jobs they own).",
+ "params": {
+ "status": {
+ "type": "string",
+ "description": "Filter by status (waiting, active, completed, failed, delayed, dead, cancelled)"
+ },
+ "queue": {
+ "type": "string",
+ "description": "Filter by queue name"
+ },
+ "name": {
+ "type": "string",
+ "description": "Filter by job type"
+ },
+ "limit": {
+ "type": "number",
+ "description": "Max results (default: 50)"
+ },
+ "fields": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Return only these job fields (e.g. [\"id\",\"name\",\"status\"]) to save tokens; omit for every field."
+ }
+ },
+ "scope": "admin",
+ "agentCallable": true,
+ "area": "jobs"
+ },
+ {
+ "name": "cancel_job",
+ "idempotent": false,
+ "outputRedaction": {
+ "exempt": "admin-scoped job introspection: job params and results are operator data, not retrieved brain text"
+ },
+ "description": "Cancel a waiting, active or delayed job you may manage. Needs admin scope.",
+ "params": {
+ "id": {
+ "type": "number",
+ "description": "Job id.",
+ "required": true
+ }
+ },
+ "mutating": true,
+ "scope": "admin",
+ "agentCallable": true,
+ "area": "jobs"
+ },
+ {
+ "name": "retry_job",
+ "idempotent": false,
+ "outputRedaction": {
+ "exempt": "admin-scoped job introspection: job params and results are operator data, not retrieved brain text"
+ },
+ "description": "Re-queue a failed or dead background job. Use when the cause of the failure is fixed. Needs admin scope. On not_found: list job ids with list_jobs.",
+ "params": {
+ "id": {
+ "type": "number",
+ "required": true,
+ "description": "Job ID"
+ }
+ },
+ "mutating": true,
+ "scope": "admin",
+ "area": "jobs"
+ },
+ {
+ "name": "get_job_progress",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": {
+ "exempt": "admin-scoped job introspection: job params and results are operator data, not retrieved brain text"
+ },
+ "description": "Get structured progress for a running job. Agent-scoped tokens (no admin) see only jobs they own.",
+ "params": {
+ "id": {
+ "type": "number",
+ "required": true,
+ "description": "Job ID"
+ }
+ },
+ "scope": "admin",
+ "agentCallable": true,
+ "area": "jobs"
+ },
+ {
+ "name": "pause_job",
+ "idempotent": false,
+ "outputRedaction": {
+ "exempt": "admin-scoped job introspection: job params and results are operator data, not retrieved brain text"
+ },
+ "description": "Pause a waiting, active or delayed background job. Use when a job must stop without being cancelled. Needs admin scope. On not_found: list job ids with list_jobs.",
+ "params": {
+ "id": {
+ "type": "number",
+ "required": true,
+ "description": "Job ID"
+ }
+ },
+ "mutating": true,
+ "scope": "admin",
+ "area": "jobs"
+ },
+ {
+ "name": "resume_job",
+ "idempotent": false,
+ "outputRedaction": {
+ "exempt": "admin-scoped job introspection: job params and results are operator data, not retrieved brain text"
+ },
+ "description": "Resume a paused background job (back to waiting). Use after pause_job once the job may continue. Needs admin scope. On not_found: list job ids with list_jobs.",
+ "params": {
+ "id": {
+ "type": "number",
+ "required": true,
+ "description": "Job ID"
+ }
+ },
+ "mutating": true,
+ "scope": "admin",
+ "area": "jobs"
+ },
+ {
+ "name": "replay_job",
+ "idempotent": false,
+ "outputRedaction": {
+ "exempt": "admin-scoped job introspection: job params and results are operator data, not retrieved brain text"
+ },
+ "description": "Replay a completed/failed/dead job, optionally with modified data",
+ "params": {
+ "id": {
+ "type": "number",
+ "required": true,
+ "description": "Source job ID to replay"
+ },
+ "data_overrides": {
+ "type": "object",
+ "required": false,
+ "description": "Data fields to override (merged with original)"
+ }
+ },
+ "scope": "admin",
+ "mutating": true,
+ "area": "jobs"
+ },
+ {
+ "name": "send_job_message",
+ "idempotent": false,
+ "outputRedaction": {
+ "exempt": "admin-scoped job introspection: job params and results are operator data, not retrieved brain text"
+ },
+ "description": "Send a sidechannel message to a running job's inbox (for jobs that read steering messages). Use when steering a long-running agent job. Needs admin scope. On not_found: list job ids with list_jobs.",
+ "params": {
+ "id": {
+ "type": "number",
+ "required": true,
+ "description": "Job ID to message"
+ },
+ "payload": {
+ "type": "object",
+ "required": true,
+ "description": "Message payload (arbitrary JSON)"
+ },
+ "sender": {
+ "type": "string",
+ "required": false,
+ "description": "Sender identity — honored for trusted local callers only (default: admin). Remote callers always send as their authenticated identity (mcp:<clientId8>); the param is ignored."
+ }
+ },
+ "scope": "admin",
+ "mutating": true,
+ "area": "jobs"
+ },
+ {
+ "name": "submit_agent",
+ "idempotent": false,
+ "outputRedaction": {
+ "exempt": "admin-scoped job introspection: job params and results are operator data, not retrieved brain text"
+ },
+ "description": "Submit an agent job (agent scope; tools and budget bound to your client). Poll get_agent_job.",
+ "params": {
+ "prompt": {
+ "type": "string",
+ "description": "Task prompt.",
+ "required": true
+ },
+ "model": {
+ "type": "string",
+ "description": "provider:model (default: subagent tier)."
+ },
+ "allowed_tools": {
+ "type": "array",
+ "description": "Subset of your bound tools.",
+ "items": {
+ "type": "string"
+ }
+ },
+ "allowed_slug_prefixes": {
+ "type": "array",
+ "description": "Subset of your write prefixes.",
+ "items": {
+ "type": "string"
+ }
+ },
+ "max_turns": {
+ "type": "number",
+ "description": "Default 20, max 100."
+ },
+ "queue": {
+ "type": "string",
+ "description": "Default \"default\"."
+ }
+ },
+ "mutating": true,
+ "scope": "agent",
+ "area": "jobs"
+ },
+ {
+ "name": "get_agent_job",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Poll a submit_agent job: status, result, queue_position. Needs agent scope.",
+ "params": {
+ "id": {
+ "type": "number",
+ "description": "Job id.",
+ "required": true
+ }
+ },
+ "scope": "agent",
+ "area": "jobs"
+ },
+ {
+ "name": "get_job_stats",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Job queue statistics. PER-BLOCK scoping: by_status and queue_health are GLOBAL (unfiltered); by_type is windowed by since_hours; only the wedge block is scoped to the queue param. wedged: true is the silent-halt signal (a worker is alive but claiming nothing while work waits) — suggest restarting the jobs supervisor on the brain host. no_worker: true means work is waiting and NO worker is running for the queue (always on PGLite unless a gbrain jobs work drain is live); wedged is then false and the no_worker notice names the fix. private_queue: true means the queue is a parent-owned dream-inline queue: wedged is NEVER true for it and a worker restart cannot help — recovery runs automatically at worker spawn / dream-cycle start; suggest gbrain doctor for the per-queue verdict. Host-process diagnostics (renice, backpressure hints) stay on the gbrain jobs stats CLI.",
+ "params": {
+ "queue": {
+ "type": "string",
+ "required": false,
+ "description": "Queue for the wedge signature (default 'default'). The other blocks stay global/windowed."
+ },
+ "since_hours": {
+ "type": "number",
+ "required": false,
+ "description": "Window for the by_type rollup in hours (default 24, clamped 1..720)."
+ }
+ },
+ "scope": "admin",
+ "area": "jobs"
+ },
+ {
+ "name": "find_orphans",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Find disconnected pages. Default mode \"islanded\" (no live inbound AND no outbound link) matches get_health.orphan_pages; mode \"inbound\" is the legacy no-inbound-only view. Essential for content enrichment cycles.",
+ "params": {
+ "include_pseudo": {
+ "type": "boolean",
+ "description": "Include auto-generated and pseudo pages (default: false)"
+ },
+ "mode": {
+ "type": "string",
+ "description": "#4524: orphan definition — 'islanded' (default; agrees with get_health.orphan_pages and doctor) or 'inbound' (legacy: no inbound links, even when the page links out)."
+ },
+ "source_id": {
+ "type": "string",
+ "description": "Only orphans from this source (it must be inside your source grant). Each row carries source_id and type."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Rows per page (default 100, max 1000); total_orphans counts every orphan and next_offset names the next page."
+ },
+ "offset": {
+ "type": "number",
+ "description": "Skip the first N orphans (ordered by source_id, then slug)."
+ },
+ "count_only": {
+ "type": "boolean",
+ "description": "Return the totals with no rows."
+ }
+ },
+ "scope": "read",
+ "cliHints": {
+ "name": "orphans",
+ "hidden": true
+ },
+ "area": "links"
+ },
+ {
+ "name": "get_calibration_profile",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Read the active calibration profile for a holder. Returns the latest row from calibration_profiles (per-source, per-holder) including Brier score, accuracy, pattern statements, and active bias tags. Source-scoped via sourceScopeOpts — federated_read scopes see the union of allowed sources, scalar source-bound clients see only their source. Returns null when no profile exists yet (cold-brain branch: builds after 5+ resolved takes + a calibration_profile phase run).",
+ "scope": "read",
+ "params": {
+ "holder": {
+ "type": "string",
+ "description": "Holder slug, e.g. 'self' or 'people/charlie-example'. Defaults to config emotional_weight.user_holder, else 'self', when omitted."
+ }
+ },
+ "area": "insights"
+ },
+ {
+ "name": "takes_list",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "List takes (typed/weighted/attributed claims) filtered by holder/kind/active/etc.",
+ "scope": "read",
+ "params": {
+ "page_slug": {
+ "type": "string",
+ "description": "Filter to this page"
+ },
+ "holder": {
+ "type": "string",
+ "description": "Filter to this holder (world|garry|brain|<slug>)"
+ },
+ "kind": {
+ "type": "string",
+ "description": "Filter to this kind (fact|take|bet|hunch)"
+ },
+ "active": {
+ "type": "boolean",
+ "description": "Active rows only (default true)"
+ },
+ "resolved": {
+ "type": "boolean",
+ "description": "true → only resolved bets; false → only unresolved"
+ },
+ "sort_by": {
+ "type": "string",
+ "description": "weight | since_date | created_at (default created_at)"
+ },
+ "limit": {
+ "type": "number",
+ "description": "Max rows (default 100, cap 500)"
+ },
+ "offset": {
+ "type": "number",
+ "description": "Skip first N rows"
+ }
+ },
+ "cliHints": {
+ "name": "takes-list"
+ },
+ "area": "takes"
+ },
+ {
+ "name": "takes_search",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Keyword search across takes (pg_trgm similarity over claim text)",
+ "scope": "read",
+ "params": {
+ "query": {
+ "type": "string",
+ "required": true,
+ "description": "Search text matched against take claim text via trigram similarity, e.g. 'valuation cap'. This is the search text param — there is no `text` param."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Max results (default 30, cap 100)"
+ }
+ },
+ "cliHints": {
+ "name": "takes-search",
+ "positional": [
+ "query"
+ ]
+ },
+ "area": "takes"
+ },
+ {
+ "name": "think",
+ "idempotent": false,
+ "outputRedaction": "retrieval",
+ "description": "Multi-hop synthesis across pages + takes + graph. Pulls relevant evidence and produces a cited answer with conflict + gap analysis. Needs a chat-model API key (Anthropic or OpenAI) for the synthesized answer, a paid call; a keyless brain returns the gathered evidence only (a synthesis_keyless notice explains). save/take persist for the local CLI only.",
+ "scope": "read",
+ "params": {
+ "question": {
+ "type": "string",
+ "required": true,
+ "description": "The question to think about"
+ },
+ "anchor": {
+ "type": "string",
+ "description": "Pull the entity subgraph around this slug"
+ },
+ "rounds": {
+ "type": "number",
+ "description": "Multi-pass: 1 (default). Round-loop scaffolding is in place; gap-driven retrieval ships in v0.29."
+ },
+ "save": {
+ "type": "boolean",
+ "description": "Persist a synthesis page (local-CLI only; ignored for MCP)"
+ },
+ "take": {
+ "type": "boolean",
+ "description": "Append a take row to the anchor page (requires anchor)"
+ },
+ "model": {
+ "type": "string",
+ "description": "Model override (alias or full id). Falls through models.think → models.default → GBRAIN_MODEL → opus."
+ },
+ "since": {
+ "type": "string",
+ "description": "Start of temporal window (YYYY-MM-DD or YYYY-MM)"
+ },
+ "until": {
+ "type": "string",
+ "description": "End of temporal window"
+ },
+ "reference_date": {
+ "type": "string",
+ "description": "YYYY-MM-DD the question's relative time words resolve against (default: today in brain.timezone)."
+ }
+ },
+ "mutating": true,
+ "cliHints": {
+ "name": "think",
+ "positional": [
+ "question"
+ ],
+ "hidden": true
+ },
+ "area": "takes"
+ },
+ {
+ "name": "takes_scorecard",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Calibration scorecard for resolved bets: counts, accuracy, Brier (correct ∨ incorrect only), partial_rate.",
+ "scope": "read",
+ "params": {
+ "holder": {
+ "type": "string",
+ "description": "Filter to this holder (world|garry|brain|<slug>)"
+ },
+ "domain_prefix": {
+ "type": "string",
+ "description": "Slug prefix (e.g. companies/) to scope the scorecard"
+ },
+ "since": {
+ "type": "string",
+ "description": "Window start (YYYY-MM-DD)"
+ },
+ "until": {
+ "type": "string",
+ "description": "Window end (YYYY-MM-DD)"
+ }
+ },
+ "cliHints": {
+ "name": "takes-scorecard"
+ },
+ "area": "takes"
+ },
+ {
+ "name": "takes_calibration",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Calibration curve: resolved correct/incorrect bets binned by stated weight; observed vs predicted per bucket.",
+ "scope": "read",
+ "params": {
+ "holder": {
+ "type": "string",
+ "description": "Filter to this holder"
+ },
+ "bucket_size": {
+ "type": "number",
+ "description": "Bucket width in (0,1]; default 0.1"
+ }
+ },
+ "cliHints": {
+ "name": "takes-calibration"
+ },
+ "area": "takes"
+ },
+ {
+ "name": "takes_add",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Record a take (typed claim) on a page: fact / take / bet / hunch, with a holder (who holds the belief: world, people/<slug>, companies/<slug>, or brain), weight 0..1, and optional source/since date. Writes the markdown takes fence first (markdown is canonical) and mirrors to the DB. Remote callers can only write holders in their allow-list (stdio default: world).",
+ "params": {
+ "request_id": {
+ "type": "string",
+ "description": "UUID; retry with it on timeout."
+ },
+ "local_dir": {
+ "type": "string",
+ "description": "Trusted CLI directory hint; must equal the registered source root."
+ },
+ "slug": {
+ "type": "string",
+ "required": true,
+ "description": "Page slug to attach the take to (page must exist)."
+ },
+ "claim": {
+ "type": "string",
+ "required": true,
+ "description": "The claim text (one line)."
+ },
+ "kind": {
+ "type": "string",
+ "required": true,
+ "enum": [
+ "fact",
+ "take",
+ "bet",
+ "hunch"
+ ],
+ "description": "Claim type. Base kinds only; pack-extended kinds are a filed follow-up."
+ },
+ "holder": {
+ "type": "string",
+ "required": true,
+ "description": "Who HOLDS this belief (said/clearly implied it): world | people/<slug> | companies/<slug> | brain. Remote callers: must be in the caller's takes-holder allow-list."
+ },
+ "weight": {
+ "type": "number",
+ "required": false,
+ "description": "Confidence 0..1 (default 0.5; clamped server-side)."
+ },
+ "source": {
+ "type": "string",
+ "required": false,
+ "description": "Where the claim came from (free text)."
+ },
+ "since": {
+ "type": "string",
+ "required": false,
+ "description": "When the belief started ('YYYY-MM' or 'YYYY-MM-DD')."
+ }
+ },
+ "scope": "write",
+ "mutating": true,
+ "area": "takes"
+ },
+ {
+ "name": "takes_update",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Update a take's mutable fields (weight, source, since date). Claim/kind/holder are immutable — supersede instead. Markdown-canonical: the target row must exist in the page's takes fence. Remote callers can only touch rows whose holder is in their allow-list; other rows present as not_found.",
+ "params": {
+ "request_id": {
+ "type": "string",
+ "description": "UUID; retry with it on timeout."
+ },
+ "local_dir": {
+ "type": "string",
+ "description": "Trusted CLI directory hint; must equal the registered source root."
+ },
+ "slug": {
+ "type": "string",
+ "required": true,
+ "description": "Page slug."
+ },
+ "row_num": {
+ "type": "number",
+ "required": true,
+ "description": "Take row number on the page (from takes_list)."
+ },
+ "weight": {
+ "type": "number",
+ "required": false,
+ "description": "New confidence 0..1."
+ },
+ "source": {
+ "type": "string",
+ "required": false,
+ "description": "New source text."
+ },
+ "since": {
+ "type": "string",
+ "required": false,
+ "description": "New since date ('YYYY-MM' or 'YYYY-MM-DD')."
+ }
+ },
+ "scope": "write",
+ "mutating": true,
+ "area": "takes"
+ },
+ {
+ "name": "takes_resolve",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Resolve a take: quality correct / incorrect / partial / unresolvable, with optional evidence text and measured value/unit. Resolutions feed the calibration scorecard. Remote callers: resolved_by is SERVER-STAMPED as mcp:<client> (any passed value is ignored) so agent resolutions stay segregable from owner ground truth; the target row must be in the caller's holder allow-list. Markdown-canonical.",
+ "params": {
+ "request_id": {
+ "type": "string",
+ "description": "UUID; retry with it on timeout."
+ },
+ "local_dir": {
+ "type": "string",
+ "description": "Trusted CLI directory hint; must equal the registered source root."
+ },
+ "slug": {
+ "type": "string",
+ "required": true,
+ "description": "Page slug."
+ },
+ "row_num": {
+ "type": "number",
+ "required": true,
+ "description": "Take row number to resolve."
+ },
+ "quality": {
+ "type": "string",
+ "required": true,
+ "enum": [
+ "correct",
+ "incorrect",
+ "partial",
+ "unresolvable"
+ ],
+ "description": "Resolution verdict."
+ },
+ "evidence": {
+ "type": "string",
+ "required": false,
+ "description": "What evidence resolved this (free text)."
+ },
+ "value": {
+ "type": "number",
+ "required": false,
+ "description": "Measured value, when the claim was quantitative."
+ },
+ "unit": {
+ "type": "string",
+ "required": false,
+ "description": "Unit for value (usd | pct | count | ...)."
+ },
+ "resolved_by": {
+ "type": "string",
+ "required": false,
+ "description": "Resolver identity. Remote callers: SERVER-STAMPED mcp:<client>, client value ignored. Local default: the configured owner holder."
+ }
+ },
+ "scope": "write",
+ "mutating": true,
+ "area": "takes"
+ },
+ {
+ "name": "takes_supersede",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Supersede a take with a replacement claim: the old row is struck through (kept for archaeology), the replacement appends at the next fence row number. Kind/holder inherit from the target row unless overridden; unset weight decays the target's by 0.1. Markdown-canonical; remote holder fencing as in takes_update.",
+ "params": {
+ "request_id": {
+ "type": "string",
+ "description": "UUID; retry with it on timeout."
+ },
+ "local_dir": {
+ "type": "string",
+ "description": "Trusted CLI directory hint; must equal the registered source root."
+ },
+ "slug": {
+ "type": "string",
+ "required": true,
+ "description": "Page slug."
+ },
+ "row_num": {
+ "type": "number",
+ "required": true,
+ "description": "Row number of the take being superseded."
+ },
+ "claim": {
+ "type": "string",
+ "required": true,
+ "description": "The replacement claim text."
+ },
+ "kind": {
+ "type": "string",
+ "required": false,
+ "enum": [
+ "fact",
+ "take",
+ "bet",
+ "hunch"
+ ],
+ "description": "Override kind (default: inherit from the target row)."
+ },
+ "holder": {
+ "type": "string",
+ "required": false,
+ "description": "Override holder (default: inherit). Remote callers: an override must be in the allow-list."
+ },
+ "weight": {
+ "type": "number",
+ "required": false,
+ "description": "Replacement confidence 0..1 (default: target's weight - 0.1)."
+ },
+ "source": {
+ "type": "string",
+ "required": false,
+ "description": "Source for the replacement."
+ },
+ "since": {
+ "type": "string",
+ "required": false,
+ "description": "Since date for the replacement."
+ }
+ },
+ "scope": "write",
+ "mutating": true,
+ "area": "takes"
+ },
+ {
+ "name": "takes_remove",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Remove one take row from a page's takes fence and the takes table together. Local-only. Other rows keep their numbers. Refuses a resolved row, a row another row cites as \"superseded by\" it, and a row whose database copy disagrees with the fence (run `gbrain takes rebuild <slug>` first). CLI: `gbrain takes remove <slug> --row N`.",
+ "params": {
+ "request_id": {
+ "type": "string",
+ "description": "UUID; retry with it on timeout."
+ },
+ "local_dir": {
+ "type": "string",
+ "description": "Trusted CLI directory hint; must equal the registered source root."
+ },
+ "slug": {
+ "type": "string",
+ "required": true,
+ "description": "Page slug."
+ },
+ "row_num": {
+ "type": "number",
+ "required": true,
+ "description": "Take row number to remove (from takes_list)."
+ }
+ },
+ "scope": "write",
+ "mutating": true,
+ "localOnly": true,
+ "area": "takes"
+ },
+ {
+ "name": "takes_rebuild",
+ "idempotent": true,
+ "outputRedaction": {
+ "exempt": "local-only: rebuild warnings quote malformed takes fence rows to the trusted local CLI owner, as the local rebuild always printed them"
+ },
+ "description": "Rebuild one page's takes index from the takes fence the page holds. Local-only. Rows whose number and claim still match keep their resolution; rows the index and the fence disagree on are re-inserted from the fence. CLI: `gbrain takes rebuild <slug>`.",
+ "params": {
+ "request_id": {
+ "type": "string",
+ "description": "UUID; retry with it on timeout."
+ },
+ "slug": {
+ "type": "string",
+ "required": true,
+ "description": "Page slug."
+ }
+ },
+ "scope": "write",
+ "mutating": true,
+ "localOnly": true,
+ "area": "takes"
+ },
+ {
+ "name": "whoami",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Your identity: transport, scopes and, over OAuth, client, source_id and federated_read.",
+ "params": {},
+ "scope": "read",
+ "cliHints": {
+ "name": "whoami"
+ },
+ "area": "identity"
+ },
+ {
+ "name": "sources_add",
+ "idempotent": false,
+ "outputRedaction": "no_stored_text",
+ "description": "Register a new source. Supports either path (a local directory) or url (a remote clone: parses the URL through the SSRF gate, clones into $GBRAIN_HOME/clones/<id>/ via temp-dir + rename atomicity, and stores remote_url in sources.config). Pre-flight collision check on id; rollback on either-side failure.",
+ "params": {
+ "id": {
+ "type": "string",
+ "required": true,
+ "description": "Source id ([a-z0-9-]{1,32}). Immutable citation key."
+ },
+ "name": {
+ "type": "string",
+ "description": "Display name (defaults to id)."
+ },
+ "path": {
+ "type": "string",
+ "description": "Local path. Mutually optional with url."
+ },
+ "url": {
+ "type": "string",
+ "description": "HTTPS git URL. Cloned into $GBRAIN_HOME/clones/<id>/. SSRF-guarded."
+ },
+ "federated": {
+ "type": "boolean",
+ "description": "true → cross-source default search. false → isolated."
+ },
+ "clone_dir": {
+ "type": "string",
+ "description": "Override clone destination (only valid with url). Default: $GBRAIN_HOME/clones/<id>/."
+ }
+ },
+ "mutating": true,
+ "scope": "sources_admin",
+ "cliHints": {
+ "name": "sources_add",
+ "hidden": true
+ },
+ "area": "sources"
+ },
+ {
+ "name": "sources_list",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "List registered sources with page counts and remote_url. remote_url lets a remote MCP caller confirm a source is managed by clone+pull rather than user-supplied path. Results are confined to the caller's resolved source scope (federated read grant > bound source) and carry no marker when rows were withheld, so a listing may be incomplete. Only the trusted local CLI (`gbrain sources list`) sees the full registry.",
+ "params": {
+ "include_archived": {
+ "type": "boolean",
+ "description": "Include soft-deleted sources."
+ }
+ },
+ "scope": "read",
+ "cliHints": {
+ "name": "sources_list",
+ "hidden": true
+ },
+ "area": "sources"
+ },
+ {
+ "name": "sources_remove",
+ "idempotent": false,
+ "outputRedaction": "no_stored_text",
+ "description": "Hard-remove a source (cascades pages/chunks/embeddings). Refuses to delete the auto-managed clone dir unless its resolved path is confined under $GBRAIN_HOME/clones/ (realpath+lstat — symlink-safe). For most workflows prefer the soft-delete path (`gbrain sources archive`). Confined to the caller's WRITE authority, not its read scope: an untrusted caller may remove only its own write source (a federated read grant naming a source does not make it removable); any other id answers not_found, indistinguishable from a nonexistent source. Only the trusted local CLI (`gbrain sources remove`) can remove any source.",
+ "params": {
+ "id": {
+ "type": "string",
+ "required": true,
+ "description": "Source id to remove, as listed by sources_list (e.g. 'wiki'). A source id, not a page slug."
+ },
+ "confirm_destructive": {
+ "type": "boolean",
+ "description": "Required when the source has data (pages, chunks). Without it the op refuses."
+ },
+ "dry_run": {
+ "type": "boolean",
+ "description": "Preview impact without side effects."
+ },
+ "keep_storage": {
+ "type": "boolean",
+ "description": "Skip clone-dir cleanup even when the source is auto-managed."
+ }
+ },
+ "mutating": true,
+ "scope": "sources_admin",
+ "cliHints": {
+ "name": "sources_remove",
+ "hidden": true
+ },
+ "area": "sources"
+ },
+ {
+ "name": "sources_status",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Per-source diagnostic. Returns clone_state (\"healthy\" | \"missing\" | \"not-a-dir\" | \"no-git\" | \"url-drift\" | \"corrupted\" | \"not-applicable\") so a remote MCP caller can diagnose whether the on-disk clone is syncable without SSH access to the brain host. Confined to the caller's resolved source scope; an out-of-scope id answers not_found, indistinguishable from a nonexistent source.",
+ "params": {
+ "id": {
+ "type": "string",
+ "required": true,
+ "description": "Source id to diagnose, as listed by sources_list (e.g. 'wiki'). A source id, not a page slug."
+ }
+ },
+ "scope": "read",
+ "cliHints": {
+ "name": "sources_status",
+ "hidden": true
+ },
+ "area": "sources"
+ },
+ {
+ "name": "sources_inspect",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Inspect committed company Markdown on the trusted local host without importing, registering a source, changing access, or invoking providers.",
+ "params": {
+ "path": {
+ "type": "string",
+ "required": true,
+ "description": "Local committed Git repository directory."
+ },
+ "profile": {
+ "type": "string",
+ "description": "Optional explicit company-brain profile; omission detects without activating."
+ },
+ "include": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Repository-relative include globs."
+ },
+ "exclude": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Repository-relative exclude globs."
+ }
+ },
+ "scope": "read",
+ "localOnly": true,
+ "cliOnly": {
+ "argv": [
+ "gbrain",
+ "sources",
+ "inspect",
+ "<path>"
+ ]
+ },
+ "mutating": false,
+ "cliHints": {
+ "name": "sources_inspect",
+ "hidden": true
+ }
+ },
+ {
+ "name": "request_tools",
+ "idempotent": false,
+ "outputRedaction": "no_stored_text",
+ "description": "More tools: no arguments lists your catalog; {tools: [names]} returns schemas; {surface} widens it (per OAuth client; stdio: this session).",
+ "area": "discovery",
+ "agentCallable": true,
+ "params": {
+ "tools": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "description": "A tool name from the catalog."
+ },
+ "description": "Tool names to fetch schemas for."
+ },
+ "surface": {
+ "type": "string",
+ "enum": [
+ "verbs",
+ "starter",
+ "full"
+ ],
+ "description": "Surface to widen to (stdio: this session only)."
+ }
+ },
+ "scope": "read",
+ "mutating": true
+ },
+ {
+ "name": "get_recent_salience",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Recently touched pages ranked by salience. Use this when the user asks what's been going on, what's notable, anything crazy happening. Do NOT run a semantic search for these.",
+ "scope": "read",
+ "params": {
+ "days": {
+ "type": "number",
+ "description": "Window in days (default 14)."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Max results (default 20)."
+ },
+ "slugPrefix": {
+ "type": "string",
+ "description": "Slug prefix, e.g. 'wiki/people'."
+ },
+ "recency_bias": {
+ "type": "string",
+ "enum": [
+ "flat",
+ "on"
+ ],
+ "description": "flat (default) or on (per-prefix decay)."
+ }
+ },
+ "cliHints": {
+ "name": "salience",
+ "hidden": true
+ },
+ "area": "insights"
+ },
+ {
+ "name": "find_anomalies",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Anomalies in recent page activity, grouped by cohort (tag or type) against a baseline. Use for what stood out, what's unusual or changed. Cohort kinds: tag, type.",
+ "scope": "read",
+ "params": {
+ "since": {
+ "type": "string",
+ "description": "YYYY-MM-DD (default today)."
+ },
+ "lookback_days": {
+ "type": "number",
+ "description": "Baseline days (default 30)."
+ },
+ "sigma": {
+ "type": "number",
+ "description": "Threshold (default 3)."
+ }
+ },
+ "cliHints": {
+ "name": "anomalies",
+ "hidden": true
+ },
+ "area": "insights"
+ },
+ {
+ "name": "get_recent_transcripts",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Returns one-line summaries of recent raw conversation transcripts (NOT polished reflections). Use this FIRST for questions about 'what's going on with me', 'what have I been thinking about', or anything personal/emotional. Raw transcripts are the canonical source for the user's own state — polished pages summarize and flatten. Local-only: rejects remote (MCP/HTTP) callers with a clear permission_denied; call via the gbrain CLI.",
+ "scope": "read",
+ "localOnly": true,
+ "cliOnly": {
+ "argv": [
+ "gbrain",
+ "transcripts",
+ "recent"
+ ]
+ },
+ "params": {
+ "days": {
+ "type": "number",
+ "description": "Window in days. Default 7."
+ },
+ "summary": {
+ "type": "boolean",
+ "description": "When true (default), return first ~300 chars per transcript. When false, full content (capped at 100 KB per file)."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Max transcripts (default 50)."
+ }
+ },
+ "cliHints": {
+ "name": "transcripts",
+ "hidden": true
+ },
+ "area": "insights"
+ },
+ {
+ "name": "connectors_status",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Per-provider chat-connector status: strategies, whether a credential is present and from where (env/file — never the value), token expiry, last_sync_at, auth_error_at, auto_sync, and the incremental watermark. Local-only; credentials never cross the wire.",
+ "scope": "read",
+ "localOnly": true,
+ "cliOnly": {
+ "argv": [
+ "gbrain",
+ "connectors",
+ "status"
+ ]
+ },
+ "params": {
+ "provider": {
+ "type": "string",
+ "description": "Restrict to one provider ('chatgpt'|'claude'). Omit for all."
+ }
+ },
+ "cliHints": {
+ "name": "connectors_status",
+ "hidden": true
+ }
+ },
+ {
+ "name": "connector_sync",
+ "idempotent": false,
+ "outputRedaction": "no_stored_text",
+ "description": "Sync a chat provider's conversation history into the brain: list new conversations since the watermark, fetch them, and ingest as pages under conversations/<provider>/. Incremental by default; `full: true` re-scans. Local-only (uses on-disk credentials).",
+ "scope": "write",
+ "mutating": true,
+ "localOnly": true,
+ "cliOnly": {
+ "argv": [
+ "gbrain",
+ "connectors",
+ "sync",
+ "<provider>"
+ ]
+ },
+ "params": {
+ "provider": {
+ "type": "string",
+ "required": true,
+ "description": "'chatgpt' or 'claude'."
+ },
+ "full": {
+ "type": "boolean",
+ "description": "Ignore the watermark and re-scan everything."
+ },
+ "dry_run": {
+ "type": "boolean",
+ "description": "List-only preview; no fetches, no writes."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Max conversations fetched this run."
+ }
+ },
+ "cliHints": {
+ "name": "connector_sync",
+ "hidden": true
+ }
+ },
+ {
+ "name": "chronicle_day",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Life Chronicle: events + timeline entries on a given day (or its ISO week when week=true), ordered chronologically; each row backlinks to its depth page. Distinct from `get_timeline`/`gbrain timeline <slug>`, which shows ONE page's timeline. CLI: `gbrain day <date>`.",
+ "scope": "read",
+ "params": {
+ "date": {
+ "type": "string",
+ "required": true,
+ "description": "Day as YYYY-MM-DD."
+ },
+ "week": {
+ "type": "boolean",
+ "description": "Expand to the ISO week (Mon–Sun) containing the date."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Max rows (default 200)."
+ },
+ "narrative": {
+ "type": "boolean",
+ "description": "Also return a prose day-by-day narrative."
+ }
+ },
+ "cliHints": {
+ "name": "day",
+ "positional": [
+ "date"
+ ]
+ },
+ "area": "chronicle"
+ },
+ {
+ "name": "chronicle_on_this_day",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Life Chronicle: events from the same calendar day in PRIOR years (\"on this day\"). CLI: `gbrain on-this-day [--date YYYY-MM-DD]`.",
+ "scope": "read",
+ "params": {
+ "date": {
+ "type": "string",
+ "description": "Anchor day YYYY-MM-DD (default today); matches its month-day in prior years."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Max rows (default 50)."
+ }
+ },
+ "cliHints": {
+ "name": "on-this-day"
+ },
+ "area": "chronicle"
+ },
+ {
+ "name": "chronicle_since",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Life Chronicle: events + timeline entries on or after a date, optionally filtered by event kind. CLI: `gbrain since <date> [--kind commitment]`.",
+ "scope": "read",
+ "params": {
+ "date": {
+ "type": "string",
+ "required": true,
+ "description": "Lower-bound day as YYYY-MM-DD (inclusive)."
+ },
+ "kind": {
+ "type": "string",
+ "description": "Filter event projections by event.kind (e.g. 'commitment')."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Max rows (default 200)."
+ }
+ },
+ "cliHints": {
+ "name": "since",
+ "positional": [
+ "date"
+ ]
+ },
+ "area": "chronicle"
+ },
+ {
+ "name": "chronicle_last_seen",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Life Chronicle: when an entity was last seen — its own timeline rows OR an event's `who`. Returns last_date, the event slug, and days_ago. CLI: `gbrain last-seen <entity-slug>`.",
+ "scope": "read",
+ "params": {
+ "entity": {
+ "type": "string",
+ "required": true,
+ "description": "Entity page slug (e.g. people/sarah-chen)."
+ },
+ "asof": {
+ "type": "string",
+ "description": "Reference day YYYY-MM-DD for days_ago (default today)."
+ }
+ },
+ "cliHints": {
+ "name": "last-seen",
+ "positional": [
+ "entity"
+ ]
+ },
+ "area": "chronicle"
+ },
+ {
+ "name": "ontology_get",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Life Chronicle: the current resolved per-entity ontology (dimension → value) at `asof` (default now), with provenance + confidence + validity. CLI: `gbrain ontology <entity> [--asof YYYY-MM-DD]`.",
+ "scope": "read",
+ "params": {
+ "entity": {
+ "type": "string",
+ "required": true,
+ "description": "Entity page slug (e.g. people/sarah-chen)."
+ },
+ "asof": {
+ "type": "string",
+ "description": "Valid-time as-of day YYYY-MM-DD (time-travel; default now)."
+ },
+ "min_confidence": {
+ "type": "number",
+ "description": "Only return observations at/above this confidence (0..1)."
+ },
+ "include_quarantined": {
+ "type": "boolean",
+ "description": "Include quarantined novel dimensions (default false)."
+ }
+ },
+ "cliHints": {
+ "name": "ontology",
+ "positional": [
+ "entity"
+ ]
+ },
+ "area": "ontology"
+ },
+ {
+ "name": "ontology_propose",
+ "idempotent": false,
+ "outputRedaction": "retrieval",
+ "description": "Life Chronicle: record one ontology observation (entity has dimension=value), sourced + confidence-weighted + bi-temporal. Idempotent on (entity,dimension,value,source). A new value supersedes the prior; a backdated conflict is flagged not rewritten. CLI: `gbrain ontology-add <entity> <dimension> <value>`.",
+ "scope": "write",
+ "mutating": true,
+ "params": {
+ "entity": {
+ "type": "string",
+ "required": true,
+ "description": "Entity page slug."
+ },
+ "dimension": {
+ "type": "string",
+ "required": true,
+ "description": "Dimension (e.g. role, risk_tolerance). Normalized at write."
+ },
+ "value": {
+ "type": "string",
+ "required": true,
+ "description": "The resolved value (e.g. advisor)."
+ },
+ "confidence": {
+ "type": "number",
+ "description": "0..1; default 0.7."
+ },
+ "source": {
+ "type": "string",
+ "description": "Provenance (page slug / uri); default \"manual\"."
+ },
+ "valid_from": {
+ "type": "string",
+ "description": "ISO date the value became true (default: now)."
+ },
+ "valid_to": {
+ "type": "string",
+ "description": "ISO date the value stopped being true (default: open)."
+ },
+ "visibility": {
+ "type": "string",
+ "enum": [
+ "private",
+ "world"
+ ],
+ "description": "Default private."
+ }
+ },
+ "cliHints": {
+ "name": "ontology-add",
+ "positional": [
+ "entity",
+ "dimension",
+ "value"
+ ]
+ },
+ "area": "ontology"
+ },
+ {
+ "name": "ontology_dimensions",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Life Chronicle meta-ontology: which dimensions the brain tracks across entities, with entity + observation counts. CLI: `gbrain ontology-dimensions`.",
+ "scope": "read",
+ "params": {},
+ "cliHints": {
+ "name": "ontology-dimensions"
+ },
+ "area": "ontology"
+ },
+ {
+ "name": "ontology_conflicts",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Life Chronicle: dimensions with ≥2 distinct current values from ≥2 provenances (genuine disagreement, not temporal supersession). CLI: `gbrain ontology-contradictions`.",
+ "scope": "read",
+ "params": {
+ "min_confidence": {
+ "type": "number",
+ "description": "Only consider observations at/above this confidence (0..1)."
+ }
+ },
+ "cliHints": {
+ "name": "ontology-contradictions"
+ },
+ "area": "ontology"
+ },
+ {
+ "name": "volunteer_chronicle",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Life Chronicle agent-orientation: the recent timeline (last N days) + the current validity-resolved ontology for the named entities, in one zero-LLM payload, so an agent orients before acting. Diary-sourced ontology is redacted for remote callers. CLI: `gbrain orient [--days 7] [--entities people/a,people/b]`.",
+ "scope": "read",
+ "params": {
+ "days": {
+ "type": "number",
+ "description": "Recent-timeline lookback in days (default 7)."
+ },
+ "entities": {
+ "type": "string",
+ "description": "Comma-separated entity slugs to resolve ontology for."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Max timeline rows (default 50)."
+ }
+ },
+ "cliHints": {
+ "name": "orient"
+ },
+ "area": "chronicle"
+ },
+ {
+ "name": "chronicle_backfill",
+ "idempotent": false,
+ "outputRedaction": "no_stored_text",
+ "description": "Life Chronicle: queue existing meeting/conversation/calendar pages (by type or under meetings/, conversations/, cal/, calendar/) for timeline-event extraction. One paid chat call per page, so it needs --yes; --dry-run reports the candidates, an estimated cost and skip reasons. The chronicle_page_state ledger skips content already extracted or queued, so repeats never pay twice. Queued pages run in the `chronicle` cycle phase (`gbrain dream --phase chronicle`), exempt from the daily limit. --max-usd is a hard bound counting retries: pages queue only while their worst case fits, and an unpriced chat model then refuses with no_pricing. Local-only bulk op. CLI: `gbrain chronicle-backfill [--since YYYY-MM-DD] [--dated-since YYYY-MM-DD] [--recent] [--limit N] [--max-usd USD] [--dry-run | --yes]`.",
+ "scope": "admin",
+ "mutating": true,
+ "localOnly": true,
+ "params": {
+ "since": {
+ "type": "string",
+ "description": "Only pages UPDATED on/after this date (YYYY-MM-DD). Use --dated-since for the page's own date."
+ },
+ "dated_since": {
+ "type": "string",
+ "description": "Only pages whose own date (authored effective date, else frontmatter date/start) is on/after this date (YYYY-MM-DD)."
+ },
+ "recent": {
+ "type": "boolean",
+ "description": "Only pages within chronicle.auto_recent_days (the automatic path's window)."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Max pages queued in this run, across all types and sources (default 1000)."
+ },
+ "dry_run": {
+ "type": "boolean",
+ "description": "Count candidates, estimate cost and report skip reasons without queuing."
+ },
+ "yes": {
+ "type": "boolean",
+ "description": "Consent to queue paid extraction (one chat call per page). Ask the user first."
+ },
+ "max_usd": {
+ "type": "number",
+ "description": "Hard spend bound in USD for everything this run queues, retries included; pages beyond it are not queued (cap_reached)."
+ }
+ },
+ "cliHints": {
+ "name": "chronicle-backfill"
+ },
+ "area": "chronicle"
+ },
+ {
+ "name": "volunteer_context",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Push-based context: volunteer brain pages relevant to a rolling conversation window WITHOUT being asked. Zero-LLM, confidence-gated (alias 0.9 / exact-title 0.8 / slug-suffix 0.6, +0.05 for multi-turn or newest-turn mentions; default gate 0.7), capped at 3 pages (max 5). Returns pointers with one-line rationales + synopses — open the page (get_page) before relying on details. Pass stats: true for the approximate volunteered-vs-used precision summary (the feedback loop).",
+ "scope": "read",
+ "params": {
+ "window": {
+ "type": "string",
+ "description": "Recent conversation turns, oldest → newest, as 'user:' / 'assistant:' prefixed lines (unprefixed text = one user turn). Required unless stats: true. CLI: piped stdin fills this."
+ },
+ "prior_context": {
+ "type": "string",
+ "description": "Already-surfaced context (pointer blocks / opened page bodies). Pages whose slug appears here are not re-volunteered."
+ },
+ "max_pages": {
+ "type": "number",
+ "description": "Max pages to volunteer (default 3, hard cap 5)."
+ },
+ "min_confidence": {
+ "type": "number",
+ "description": "Confidence gate 0..1 (default 0.7 — slug-suffix matches need an explicit lower gate)."
+ },
+ "session_id": {
+ "type": "string",
+ "description": "Optional caller session id, logged for attribution."
+ },
+ "turn": {
+ "type": "number",
+ "description": "Optional caller turn number, logged for attribution."
+ },
+ "stats": {
+ "type": "boolean",
+ "description": "Return the volunteered-vs-used precision summary instead of volunteering. APPROXIMATE: \"used\" = pages.last_retrieved_at > volunteered_at."
+ },
+ "days": {
+ "type": "number",
+ "description": "Stats window in days (default 30; stats mode only)."
+ }
+ },
+ "cliHints": {
+ "name": "volunteer-context",
+ "stdin": "window"
+ },
+ "area": "insights"
+ },
+ {
+ "name": "extract_entities",
+ "idempotent": false,
+ "outputRedaction": "retrieval",
+ "description": "Extract entity names (people, companies) from text and create/update their brain stub pages. Stubs from untrusted input land in the quarantine lane (frontmatter `provenance: auto-extracted` + `status: unverified`) — excluded from authoritative retrieval boosts until reviewed. Direct authoritative writes require the trusted local CLI with trusted_extraction set.",
+ "params": {
+ "text": {
+ "type": "string",
+ "required": true,
+ "description": "The text to extract entities from (email, transcript, pasted content, …). Max 200k characters — split larger inputs."
+ },
+ "source_slug": {
+ "type": "string",
+ "required": true,
+ "description": "Slug of the source page the text came from (used for backlinks + timeline attribution)."
+ },
+ "trusted_extraction": {
+ "type": "boolean",
+ "required": false,
+ "description": "Local CLI only: write stubs directly as authoritative pages, skipping the quarantine lane. Ignored (always quarantined) for remote callers."
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "cliHints": {
+ "name": "extract-entities"
+ },
+ "area": "entities"
+ },
+ {
+ "name": "extraction_pending",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "List unverified auto-extracted entity stubs awaiting owner review (the quarantine lane from extract_entities). Promote or reject them with extraction_review.",
+ "params": {
+ "limit": {
+ "type": "number",
+ "required": false,
+ "description": "Max rows (default 100, cap 500)."
+ },
+ "offset": {
+ "type": "number",
+ "required": false,
+ "description": "Pagination offset."
+ }
+ },
+ "scope": "read",
+ "cliHints": {
+ "name": "extraction-pending"
+ },
+ "area": "entities"
+ },
+ {
+ "name": "extraction_review",
+ "idempotent": false,
+ "outputRedaction": "no_stored_text",
+ "description": "Promote or reject unverified auto-extracted entity stubs (batch). Promote flips `status` to verified (provenance kept for audit); reject soft-deletes the stub. Owner-only: this op is refused for any non-local caller. (The markers are ordinary frontmatter — the boundary against rewriting them wholesale is put_page write authz, same as for any page.)",
+ "params": {
+ "action": {
+ "type": "string",
+ "required": true,
+ "description": "'promote' or 'reject'."
+ },
+ "slugs": {
+ "type": "array",
+ "required": true,
+ "items": {
+ "type": "string"
+ },
+ "description": "Stub slugs to act on (batch)."
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "localOnly": true,
+ "cliOnly": {
+ "argv": [
+ "gbrain",
+ "extraction-review",
+ "<action>",
+ "--slugs",
+ "<slugs>"
+ ]
+ },
+ "cliHints": {
+ "name": "extraction-review",
+ "positional": [
+ "action"
+ ]
+ },
+ "area": "entities"
+ },
+ {
+ "name": "entity_identity_link",
+ "idempotent": false,
+ "outputRedaction": "no_stored_text",
+ "description": "Link a page into a cross-source entity identity group (v1 manual-only; no auto-matching). The identity key is (source_id, slug); a page belongs to at most one group and re-linking moves it. Set canonical=true to mark the group's primary page (demotes any previous canonical).",
+ "params": {
+ "entity_id": {
+ "type": "string",
+ "required": true,
+ "description": "Opaque identity handle grouping the members, e.g. 'alice-chen'. Lowercase [a-z0-9._/-], max 128 chars."
+ },
+ "slug": {
+ "type": "string",
+ "required": true,
+ "description": "Slug of the member page to link."
+ },
+ "source_id": {
+ "type": "string",
+ "description": "Source the member page lives in. Defaults to the routed source ('default')."
+ },
+ "confidence": {
+ "type": "number",
+ "description": "Assertion confidence in [0,1]. Default 1.0 (manual assertions are certain)."
+ },
+ "canonical": {
+ "type": "boolean",
+ "description": "Mark this member as the identity's canonical/primary page (at most one per group)."
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "localOnly": true,
+ "cliHints": {
+ "name": "entity-identity-link",
+ "positional": [
+ "entity_id",
+ "slug"
+ ]
+ },
+ "area": "entities"
+ },
+ {
+ "name": "entity_identity_unlink",
+ "idempotent": false,
+ "outputRedaction": "no_stored_text",
+ "description": "Remove a page from a cross-source entity identity group (v1 manual-only).",
+ "params": {
+ "entity_id": {
+ "type": "string",
+ "required": true,
+ "description": "Identity handle the member currently belongs to."
+ },
+ "slug": {
+ "type": "string",
+ "required": true,
+ "description": "Slug of the member page to unlink."
+ },
+ "source_id": {
+ "type": "string",
+ "description": "Source the member page lives in. Defaults to the routed source ('default')."
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "localOnly": true,
+ "cliHints": {
+ "name": "entity-identity-unlink",
+ "positional": [
+ "entity_id",
+ "slug"
+ ]
+ },
+ "area": "entities"
+ },
+ {
+ "name": "entity_identity_list",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "List cross-source entity identity groups and their member pages. Filter by entity_id or by a member slug. Federated callers only see members in sources their grant covers.",
+ "params": {
+ "entity_id": {
+ "type": "string",
+ "description": "Restrict to one identity group."
+ },
+ "slug": {
+ "type": "string",
+ "description": "Restrict to the group(s) containing a page with this slug."
+ }
+ },
+ "scope": "read",
+ "cliHints": {
+ "name": "entity-identity-list"
+ },
+ "area": "entities"
+ },
+ {
+ "name": "extract_facts",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Extract personal-knowledge facts (events, preferences, commitments, beliefs, ideas, and plain facts) from a conversation turn into the per-source hot memory. Sanitizes turn_text via INJECTION_PATTERNS, calls the configured extraction model (key-aware: any servable provider — OpenAI or Anthropic key both work), runs the cosine fast-path + classifier dedup pipeline, INSERTs into facts. Returns counts by status. With NO servable chat model, returns skipped: extraction_unavailable + an agent_action telling YOU to extract and write via `remember` (visibility: \"private\"). Skips extraction when the turn is dream-generated content (anti-loop). For agent memory writes of a SINGLE already-formed fact, prefer the `remember` verb (zero LLM, mandatory provenance).",
+ "params": {
+ "request_id": {
+ "type": "string",
+ "description": "UUID; retry with it on timeout. Managed extraction returns durable receipts; when omitted, each call gets a new UUID. Unmanaged extraction retains its legacy non-journaled behavior."
+ },
+ "turn_text": {
+ "type": "string",
+ "required": true,
+ "description": "The user message or page body to extract facts from. Sanitized via INJECTION_PATTERNS before the LLM call."
+ },
+ "session_id": {
+ "type": "string",
+ "description": "Opaque session id (e.g. topic-id from MCP _meta.session_id, or CLI --session). Stored on each fact for the recall --session filter. Not an auth surface. NOTE (#4206): the session survives on the DB row at insert time, but the `## Facts` fence has no session column — a fence rebuild/reconcile re-derives rows session-less. Treat fence-backed facts as session-less across rebuilds."
+ },
+ "entity_hints": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Existing canonical entity slugs the agent has already resolved. Helps the extractor pick the right slug. Only the first 5 are forwarded to the extractor (#4209) — the response reports entity_hints_used / entity_hints_dropped; pass the most load-bearing slugs first."
+ },
+ "is_dream_generated": {
+ "type": "boolean",
+ "description": "When true, extraction is skipped (anti-loop). Caller flips this on for pages with dream_generated:true frontmatter."
+ },
+ "valid_from": {
+ "type": "string",
+ "description": "#4206: ISO 8601 event time for the extracted facts — use when the turn is historical (importing an old transcript) so facts do not get stamped with import time. Fallback only: a date the extractor derives from the turn itself wins. Default: now()."
+ },
+ "source_slug": {
+ "type": "string",
+ "description": "#4206: slug of the page/transcript this turn came from (e.g. 'meetings/2026-04-03'). Written to facts.context so recall/context_pack/delta consumers see the provenance."
+ },
+ "visibility": {
+ "type": "string",
+ "description": "Default visibility for extracted facts. private (default) | world."
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "area": "memory"
+ },
+ {
+ "name": "recall",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": {
+ "retrieval": {
+ "localVerbatim": [
+ "facts"
+ ]
+ }
+ },
+ "description": "MEMORY VERB (v1): read saved facts by entity, since or session_id; `query` also searches pages. Remote callers see world facts only. One card: entity; reasoning: synthesize.",
+ "params": {
+ "entity": {
+ "type": "string",
+ "description": "Entity slug; facts about it, newest first."
+ },
+ "query": {
+ "type": "string",
+ "description": "Also search pages (results[] arm)."
+ },
+ "budget_tokens": {
+ "type": "number",
+ "description": "Token budget; facts pack first."
+ },
+ "budget_policy": {
+ "type": "string",
+ "enum": [
+ "facts_first",
+ "query_first"
+ ],
+ "description": "facts_first (default) or query_first."
+ },
+ "source_id": {
+ "type": "string",
+ "description": "Narrow to one source you may read."
+ },
+ "since": {
+ "type": "string",
+ "description": "Facts since (ISO 8601 or \"8 hours ago\")."
+ },
+ "session_id": {
+ "type": "string",
+ "description": "Facts captured in this session."
+ },
+ "include_expired": {
+ "type": "boolean",
+ "description": "Include expired facts."
+ },
+ "supersessions": {
+ "type": "boolean",
+ "description": "Only the supersession audit log."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Per-arm max (default 50, cap 100)."
+ },
+ "grep": {
+ "type": "string",
+ "description": "Substring of the fact text."
+ },
+ "include_pending": {
+ "type": "boolean",
+ "description": "Add pending count."
+ },
+ "return_unit": {
+ "type": "string",
+ "enum": [
+ "chunk",
+ "window",
+ "section",
+ "page",
+ "auto"
+ ],
+ "description": "Evidence unit for results[] (see search)."
+ },
+ "return_window": {
+ "type": "number",
+ "description": "Window size 1-3."
+ }
+ },
+ "scope": "read",
+ "verb": true,
+ "annotations": {
+ "title": "recall (memory read)",
+ "readOnlyHint": true
+ },
+ "area": "memory-verbs"
+ },
+ {
+ "name": "context_pack",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": {
+ "retrieval": {
+ "localVerbatim": [
+ "facts"
+ ]
+ }
+ },
+ "description": "MEMORY VERB (v1): core memory, budget-packed cards, open threads and hot facts for up to 8 entities, zero LLM. Call at session start and after compaction.",
+ "params": {
+ "entities": {
+ "type": "string",
+ "description": "Comma-separated names or slugs (max 8)."
+ },
+ "budget_tokens": {
+ "type": "number",
+ "description": "Token budget; cards pack first."
+ },
+ "since": {
+ "type": "string",
+ "description": "Only open-thread events after this ISO time."
+ },
+ "session_id": {
+ "type": "string",
+ "description": "Opaque session id."
+ },
+ "include_private": {
+ "type": "boolean",
+ "description": "Local trusted callers only."
+ }
+ },
+ "scope": "read",
+ "verb": true,
+ "cliHints": {
+ "name": "context-pack"
+ },
+ "annotations": {
+ "title": "context_pack (boundary bundle)",
+ "readOnlyHint": true
+ },
+ "area": "memory-verbs"
+ },
+ {
+ "name": "delta",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": {
+ "retrieval": {
+ "localVerbatim": [
+ "facts"
+ ]
+ }
+ },
+ "description": "MEMORY VERB (v1): pages, facts, thread events changed since a cursor, zero LLM. Pass session_id, cursor or since.",
+ "params": {
+ "since": {
+ "type": "string",
+ "description": "ISO 8601 start time."
+ },
+ "since_slug": {
+ "type": "string",
+ "description": "Legacy: next_cursor.slug."
+ },
+ "cursor": {
+ "type": "string",
+ "description": "next_cursor.cursor (exact)."
+ },
+ "entities": {
+ "type": "string",
+ "description": "Entities for thread events (max 8)."
+ },
+ "budget_tokens": {
+ "type": "number",
+ "description": "Token budget; pages pack first."
+ },
+ "session_id": {
+ "type": "string",
+ "description": "Session id; keeps a cursor."
+ },
+ "include_private": {
+ "type": "boolean",
+ "description": "Local trusted callers only."
+ }
+ },
+ "scope": "read",
+ "verb": true,
+ "cliHints": {
+ "name": "delta"
+ },
+ "annotations": {
+ "title": "delta (what changed since)",
+ "readOnlyHint": true
+ },
+ "area": "memory-verbs"
+ },
+ {
+ "name": "forget_fact",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Forget a fact by recording a durable withdrawal in its source and visibility. Strikes the Markdown facts fence when writable; otherwise keeps the withdrawal in the database. Stale imports cannot reactivate the same normalized claim. This retracts memory; original prose, files and backups may retain the text. Idempotent on already-expired or unknown ids.",
+ "params": {
+ "request_id": {
+ "type": "string",
+ "description": "UUID; retry with it on timeout."
+ },
+ "id": {
+ "type": "number",
+ "required": true,
+ "description": "Fact id to forget."
+ },
+ "reason": {
+ "type": "string",
+ "required": false,
+ "description": "Optional reason; written to the fence row's context cell as \"forgotten: <reason>\". Default: \"forgotten\"."
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "area": "memory"
+ },
+ {
+ "name": "find_contradictions",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Stored contradiction reports are temporarily available only to trusted local callers without a source filter. Remote or source-scoped callers receive {contradictions: [], note} with an availability note. For eligible local callers, return suspected-contradiction findings from the most recent `gbrain eval suspected-contradictions` probe run, optionally filtered by slug and/or severity. Use this when the user asks 'what's inconsistent in my brain', 'show me contradictions about Acme', 'high-severity issues only', or wants to act on the probe's findings without re-running it. Returns {contradictions: [{a, b, severity, axis, confidence, resolution_command}]}. An eligible read loads the stored run without triggering a new probe; users run `gbrain eval suspected-contradictions` for that.",
+ "scope": "read",
+ "params": {
+ "slug": {
+ "type": "string",
+ "description": "Optional slug filter; matches either side of a pair (substring match on slug)."
+ },
+ "severity": {
+ "type": "string",
+ "enum": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "description": "Optional severity filter."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Max findings to return. Default 20."
+ }
+ },
+ "cliHints": {
+ "name": "find-contradictions"
+ },
+ "area": "insights"
+ },
+ {
+ "name": "find_experts",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Answers 'who in my brain knows about <topic>'. Returns ranked person/company pages by expertise depth (sub-linear match score), relationship recency (exp decay with 6-month half-life), and salience. Use this for questions like 'who should I talk to about X', 'who knows about Y', 'find me someone who's worked on Z', or any expertise-routing intent. Filters at SQL to person + company pages — does NOT return notes or articles. Pair with --explain (CLI) to surface the per-result factor breakdown.",
+ "scope": "read",
+ "params": {
+ "topic": {
+ "type": "string",
+ "description": "The topic to route. Free-form natural language."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Max results (default 5)."
+ },
+ "explain": {
+ "type": "boolean",
+ "description": "Include factor breakdown per result (expertise, recency, salience)."
+ }
+ },
+ "cliHints": {
+ "name": "whoknows",
+ "positional": [
+ "topic"
+ ],
+ "hidden": true
+ },
+ "area": "insights"
+ },
+ {
+ "name": "find_trajectory",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Return the chronological claim trajectory for an entity (typed metric values over time, plus auto-detected regressions and narrative drift). Use this when the user asks 'how has Acme's MRR trended', 'show me what alice-example said about runway over time', 'is this founder consistent', 'find regressions for fund-a's portfolio', or wants a time-series view of an entity's structured claims. Returns `{points: [{fact_id, valid_from, metric, value, unit, period, text, source_session, source_markdown_slug}], regressions: [{metric, from_value, from_date, to_value, to_date, delta_pct}], drift_score: number|null, schema_version: 1}`. Drift score 0 = stable narrative, 1 = every consecutive claim is unrelated; null when fewer than 3 typed points exist. Visibility-filtered for remote callers (world-only); source-scoped by the caller's OAuth source binding. Pair with `gbrain founder scorecard <slug>` for an aggregated rollup of the same data.",
+ "scope": "read",
+ "params": {
+ "entity_slug": {
+ "type": "string",
+ "description": "Required. Entity slug to chart (e.g. \"companies/acme-example\", \"people/alice-example\")."
+ },
+ "metric": {
+ "type": "string",
+ "description": "Optional. Filter to a single canonical metric (e.g. \"mrr\", \"arr\", \"team_size\"). When omitted, all metrics return."
+ },
+ "kind": {
+ "type": "string",
+ "enum": [
+ "metric",
+ "event",
+ "all"
+ ],
+ "description": "Optional. Filter by row shape: \"metric\" (typed-claim rows only), \"event\" (event_type rows only), or \"all\" (default). v0.40.2.0+."
+ },
+ "since": {
+ "type": "string",
+ "description": "Optional lower bound on valid_from (YYYY-MM-DD or ISO)."
+ },
+ "until": {
+ "type": "string",
+ "description": "Optional upper bound on valid_from (YYYY-MM-DD or ISO)."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Max points returned. Default 100, max 500."
+ }
+ },
+ "cliHints": {
+ "name": "find-trajectory"
+ },
+ "area": "insights"
+ },
+ {
+ "name": "code_callers",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "BEFORE editing any function, run code_callers with the symbol name to find every caller (the people who'd be affected by your change). Returns direct callers from the tree-sitter call graph. Use during plan-mode to size the change. Defaults to source-scoped; for multi-source brains pass source_id or all_sources=true. Returns: `{symbol, count, callers: [{from_symbol_qualified, to_symbol_qualified, edge_type, resolved}]}`. Example: `{symbol:'parseMarkdown', count:4, callers:[{from_symbol_qualified:'callerInA', to_symbol_qualified:'parseMarkdown', edge_type:'calls', resolved:true}]}`. Temporarily available only to trusted local CLI callers; agent-facing code reads are suspended.",
+ "params": {
+ "symbol": {
+ "type": "string",
+ "required": true,
+ "description": "Symbol to find callers of (bare or qualified name)."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Max edges returned. Default 100."
+ },
+ "source_id": {
+ "type": "string",
+ "description": "Scope to a single source. Defaults to ctx.sourceId; '__all__' spans every source for trusted local callers, your granted sources for remote callers."
+ },
+ "all_sources": {
+ "type": "boolean",
+ "description": "Span sources (equivalent to source_id=__all__): every source locally, your grant remotely."
+ }
+ },
+ "scope": "read",
+ "cliHints": {
+ "name": "code_callers",
+ "hidden": true
+ },
+ "area": "code"
+ },
+ {
+ "name": "code_callees",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "When tracing how a function flows to its dependencies (DB calls, HTTP calls, file I/O), run code_callees from the entry point. Forward view of the call graph: what does this symbol call? Use this when debugging unexpected behavior or when planning to extract / inline a function. Same shape as code_callers but the field is `callees` and the edge direction is reversed. Temporarily available only to trusted local CLI callers; agent-facing code reads are suspended.",
+ "params": {
+ "symbol": {
+ "type": "string",
+ "required": true,
+ "description": "Symbol to find callees of (bare or qualified name)."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Max edges returned. Default 100."
+ },
+ "source_id": {
+ "type": "string",
+ "description": "Scope to a single source. Defaults to ctx.sourceId; '__all__' spans every source for trusted local callers, your granted sources for remote callers."
+ },
+ "all_sources": {
+ "type": "boolean",
+ "description": "Span sources: every source locally, your grant remotely."
+ }
+ },
+ "scope": "read",
+ "cliHints": {
+ "name": "code_callees",
+ "hidden": true
+ },
+ "area": "code"
+ },
+ {
+ "name": "code_def",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Where is this symbol defined? Returns one row per definition site (function, class, type, interface, enum, struct, trait, module, contract). Use this BEFORE reaching for grep when you want to read a definition. Single-result is the common case; multiple results indicate same-name symbols across files (which is information in itself). Returns: `{symbol, count, defs: [{slug, file, language, symbol_type, start_line, end_line, snippet}]}`. Filter by --lang to scope a polyglot brain (e.g., lang='typescript'). Temporarily available only to trusted local CLI callers; agent-facing code reads are suspended.",
+ "params": {
+ "symbol": {
+ "type": "string",
+ "required": true,
+ "description": "Symbol name (bare token; e.g., parseMarkdown, BrainEngine)."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Max definition sites returned. Default 20."
+ },
+ "lang": {
+ "type": "string",
+ "description": "Filter by content_chunks.language (e.g. 'typescript', 'python')."
+ }
+ },
+ "scope": "read",
+ "cliHints": {
+ "name": "code_def",
+ "hidden": true
+ },
+ "area": "code"
+ },
+ {
+ "name": "code_refs",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "Find every reference to a symbol across the codebase (every file, every line). Differs from code_callers in two ways: (1) catches references in comments, strings, imports, type annotations — not just call sites; (2) returns line numbers, not symbol-qualified edges. Use this when planning a rename or deprecation where you need to touch every literal mention. Returns: `{symbol, count, refs: [{slug, file, language, line, context}]}`. Temporarily available only to trusted local CLI callers; agent-facing code reads are suspended.",
+ "params": {
+ "symbol": {
+ "type": "string",
+ "required": true,
+ "description": "Symbol to find references to."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Max references returned. Default 50."
+ },
+ "lang": {
+ "type": "string",
+ "description": "Filter by content_chunks.language."
+ }
+ },
+ "scope": "read",
+ "cliHints": {
+ "name": "code_refs",
+ "hidden": true
+ },
+ "area": "code"
+ },
+ {
+ "name": "code_blast",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "BEFORE editing any function, run code_blast with the symbol name to surface every transitive caller grouped by depth (direct → 2-hop → 3-hop). Use this during plan-mode to size the change. Returns up to 200 nodes. Trust an empty/not_found result only when ready=true; ready=false means impact is unknown and requires a safe fallback. Returns: {result, status, ready, depth_groups?, truncation?, cycles_detected?, did_you_mean?, candidates?}. Example ok: {result:\"ok\", status:\"ready\", ready:true, depth_groups:[{depth:1, nodes:[{symbol,chunk_id}], confidence:0.77}], truncation:\"none\"}. Temporarily available only to trusted local CLI callers; agent-facing code reads are suspended.",
+ "params": {
+ "symbol": {
+ "type": "string",
+ "required": true,
+ "description": "Bare or qualified symbol name (e.g. \"performSync\" or \"src/foo::performSync\")"
+ },
+ "depth": {
+ "type": "number",
+ "description": "Hop cap (default 5, max 8)"
+ },
+ "max_nodes": {
+ "type": "number",
+ "description": "Result-set cap (default 200)"
+ },
+ "exact": {
+ "type": "boolean",
+ "description": "Skip bare-name disambiguation; treat symbol as exact qualified name"
+ },
+ "source_id": {
+ "type": "string",
+ "description": "Source to traverse. Defaults to ctx.sourceId; federated clients with multiple granted sources must specify one."
+ }
+ },
+ "scope": "read",
+ "cliHints": {
+ "name": "code_blast",
+ "hidden": true
+ },
+ "area": "code"
+ },
+ {
+ "name": "code_flow",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "When tracing how a request flows through the codebase from entry point to side effect (DB write, HTTP call, file I/O), run code_flow from the entry point. Returns ordered execution chain with terminal-node tags. Returns: same envelope as code_blast plus terminal_nodes: [{symbol, sink_kind}] where sink_kind ∈ \"db_call\"|\"http_call\"|\"file_io\"|\"process_exec\"|\"unknown\". Temporarily available only to trusted local CLI callers; agent-facing code reads are suspended.",
+ "params": {
+ "entry_point": {
+ "type": "string",
+ "required": true,
+ "description": "Entry-point symbol name (bare or qualified)"
+ },
+ "depth": {
+ "type": "number",
+ "description": "Hop cap (default 8, max 12)"
+ },
+ "max_nodes": {
+ "type": "number",
+ "description": "Result-set cap (default 200)"
+ },
+ "exact": {
+ "type": "boolean",
+ "description": "Skip bare-name disambiguation"
+ },
+ "source_id": {
+ "type": "string",
+ "description": "Source to traverse. Defaults to ctx.sourceId; federated clients with multiple granted sources must specify one."
+ }
+ },
+ "scope": "read",
+ "cliHints": {
+ "name": "code_flow",
+ "hidden": true
+ },
+ "area": "code"
+ },
+ {
+ "name": "code_traversal_cache_clear",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Clear cached code_blast / code_flow traversal results. Source-scoped by default; pass all_sources=true to wipe everything (destructive: it is guarded).",
+ "params": {
+ "source_id": {
+ "type": "string",
+ "description": "Source to clear. Required unless all_sources=true."
+ },
+ "all_sources": {
+ "type": "boolean",
+ "description": "Wipe cache across every source. Explicit opt-out of source-scoping."
+ }
+ },
+ "mutating": true,
+ "scope": "admin",
+ "localOnly": true,
+ "cliHints": {
+ "name": "code_traversal_cache_clear",
+ "hidden": true
+ },
+ "area": "admin"
+ },
+ {
+ "name": "migrate_embeddings",
+ "idempotent": false,
+ "outputRedaction": "no_stored_text",
+ "description": "Re-embed the brain onto a different embedding provider/model: schema dimension transition, NULL-signature invalidation, query-cache purge, resumable re-embed. Without yes=true returns the plan + cost estimate only. Local-only admin op; the primary surface is `gbrain migrate embeddings`.",
+ "params": {
+ "to": {
+ "type": "string",
+ "required": true,
+ "description": "Target provider:model (e.g. openai:text-embedding-3-small)."
+ },
+ "dim": {
+ "type": "number",
+ "description": "Target dimensions. Defaults to the provider recipe's declared width; required when the recipe declares none."
+ },
+ "dry_run": {
+ "type": "boolean",
+ "description": "Plan + cost estimate only; change nothing."
+ },
+ "yes": {
+ "type": "boolean",
+ "description": "Confirm the re-embed spend + destructive schema change. Required for a live run."
+ },
+ "max_cost_usd": {
+ "type": "number",
+ "description": "Finite total paid authorization. Required for new work and must cover plan.worst_case_authorization (else refused with embedding_budget_below_worst_case before any change); requests settle to reported usage, resume preserves debits. Increase explicitly to renew."
+ },
+ "retarget": {
+ "type": "boolean",
+ "description": "Abandon a DIFFERENT in-flight migration target and start this one (the abandoned target is recorded in the marker history)."
+ },
+ "reranker": {
+ "type": "string",
+ "description": "Reranker companion action: auto (default), off, keep, or an explicit provider:model (e.g. voyage:rerank-2.5). Reranker config lives on the DB plane."
+ }
+ },
+ "mutating": true,
+ "scope": "admin",
+ "localOnly": true,
+ "cliOnly": {
+ "argv": [
+ "gbrain",
+ "migrate",
+ "embeddings",
+ "--to",
+ "<model>"
+ ]
+ },
+ "cliHints": {
+ "name": "migrate-embeddings",
+ "hidden": true
+ },
+ "area": "admin"
+ },
+ {
+ "name": "get_active_schema_pack",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Cheap identity packet for the active schema pack. Returns {pack_name, version, sha8, page_types_count, link_types_count, primitive_summary, source_tier}. Useful for agents to know which pack they are operating against without paying full manifest load cost.",
+ "params": {},
+ "scope": "read",
+ "area": "schema"
+ },
+ {
+ "name": "list_schema_packs",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "List installed schema packs (bundled + user-installed). Returns {bundled: string[], installed: string[]}. Read-only directory listing.",
+ "params": {},
+ "scope": "read",
+ "area": "schema"
+ },
+ {
+ "name": "schema_stats",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Per-type page counts + typed-coverage from the DB. Returns {schema_version:1, pack_identity, aggregate, per_source, dead_prefixes}. Multi-source aware via ctx.sourceId/allowedSources.",
+ "params": {},
+ "scope": "read",
+ "area": "schema"
+ },
+ {
+ "name": "schema_lint",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Lint the active (or named) schema pack. File-plane rules only over MCP — the with_db option is rejected for remote callers (DB-aware rules require local CLI). Returns {ok, errors, warnings} structured report.",
+ "params": {
+ "pack": {
+ "type": "string",
+ "description": "Pack name (default: active pack)"
+ }
+ },
+ "scope": "read",
+ "area": "schema"
+ },
+ {
+ "name": "schema_graph",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Schema pack graph as JSON edges. Returns {nodes: [{name, primitive}], edges: [{from, verb, to}]} derived from link_types inference + frontmatter_links.",
+ "params": {},
+ "scope": "read",
+ "area": "schema"
+ },
+ {
+ "name": "schema_explain_type",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Resolved settings for a single page_type in the active pack. Returns {pack, type, primitive, path_prefixes, aliases, extractable, expert_routing}.",
+ "params": {
+ "type": {
+ "type": "string",
+ "required": true,
+ "description": "Page type name to explain"
+ }
+ },
+ "scope": "read",
+ "area": "schema"
+ },
+ {
+ "name": "schema_review_orphans",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "List pages with no active-pack type match. Returns {orphan_count, orphans: [{slug, source_id}]}.",
+ "params": {
+ "limit": {
+ "type": "number",
+ "description": "Max orphans to return (default 100)"
+ }
+ },
+ "scope": "read",
+ "area": "schema"
+ },
+ {
+ "name": "schema_apply_mutations",
+ "idempotent": false,
+ "outputRedaction": "no_stored_text",
+ "description": "Batched schema pack mutation. ATOMIC: every mutation is validated against an in-memory manifest first, and the pack file is written to disk at most once, after the FULL batch has proven valid — so a failure at any point leaves the pack file byte-identical to its pre-batch state (never a partial write). Audit log records one batch_id. Admin scope; NOT localOnly so remote agents (your OpenClaw, etc.) can author packs over normal MCP. Mutation shape per ApplyMutationsRequest type — supports add_type / remove_type / update_type / add_alias / remove_alias / add_prefix / remove_prefix / add_link_type / remove_link_type / set_extractable / set_expert_routing.",
+ "params": {
+ "pack": {
+ "type": "string",
+ "required": true,
+ "description": "Pack to mutate (must not be bundled)"
+ },
+ "mutations": {
+ "type": "array",
+ "required": true,
+ "description": "Array of {op, ...args} mutation records to apply atomically",
+ "items": {
+ "type": "object"
+ }
+ },
+ "force": {
+ "type": "boolean",
+ "description": "Steal stale per-pack lock"
+ }
+ },
+ "scope": "admin",
+ "mutating": true,
+ "area": "schema"
+ },
+ {
+ "name": "reload_schema_pack",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Flush the in-process schema pack cache so the next loadActivePack re-reads from disk. Cascades through the extends chain. Admin scope; NOT localOnly. Returns {invalidated: string[]}.",
+ "params": {
+ "pack": {
+ "type": "string",
+ "description": "Pack name to invalidate (omit to flush all)"
+ }
+ },
+ "scope": "admin",
+ "mutating": false,
+ "area": "schema"
+ },
+ {
+ "name": "run_onboard",
+ "idempotent": false,
+ "outputRedaction": "no_stored_text",
+ "description": "Probe brain health + optionally submit onboard remediations. Admin scope required. Protected handlers (LLM-bearing) require run_protected_onboard scope ADDITIONALLY.",
+ "params": {
+ "mode": {
+ "type": "string",
+ "description": "'check' (default), 'auto', or 'auto-with-prompt'"
+ },
+ "target_score": {
+ "type": "number",
+ "description": "Target brain_score (default 90)"
+ },
+ "max_usd": {
+ "type": "number",
+ "description": "USD cap for autopilot path (required for auto modes)"
+ }
+ },
+ "mutating": true,
+ "scope": "admin",
+ "area": "admin"
+ },
+ {
+ "name": "run_skillopt",
+ "idempotent": true,
+ "outputRedaction": {
+ "exempt": "skill catalog files are installed instructions read verbatim; redaction would corrupt approved revisions"
+ },
+ "description": "Run SkillOpt against a single skill. Admin scope and remote skill allowlist required. shared_skill stages an exact catalog revision privately and requires explicit skill_editor and put_skill grants; only accepted body changes publish through the original revision CAS. Rate-limited per-skill via DB lock.",
+ "params": {
+ "skill_name": {
+ "type": "string",
+ "required": true,
+ "description": "Kebab-case skill name (resolves to skills/<name>/SKILL.md)"
+ },
+ "benchmark_path": {
+ "type": "string",
+ "description": "Absolute path to benchmark JSONL; defaults to skills/<name>/skillopt-benchmark.jsonl"
+ },
+ "epochs": {
+ "type": "number",
+ "description": "Default 4"
+ },
+ "batch_size": {
+ "type": "number",
+ "description": "Default 8"
+ },
+ "lr": {
+ "type": "number",
+ "description": "Default 4"
+ },
+ "max_cost_usd": {
+ "type": "number",
+ "description": "Default 5.00 (an unpriced model then warns and runs). When set, an unpriced model is refused with no_pricing. Remote callers must pass a positive value; 0 (uncapped) is host-only."
+ },
+ "reflect_max_tokens": {
+ "type": "number",
+ "description": "Optimizer output cap (positive integer, clamped to 256..32000). Default: skillopt.reflect_max_tokens config, else 32000 for thinking optimizers and 4096 otherwise."
+ },
+ "no_mutate": {
+ "type": "boolean",
+ "description": "Write proposed.md without replacing SKILL.md"
+ },
+ "allow_mutate_bundled": {
+ "type": "boolean",
+ "description": "Required to mutate bundled skills"
+ },
+ "held_out_path": {
+ "type": "string",
+ "description": "Path to a held-out test set (JSONL). REQUIRED (>=5 rows) to mutate a bundled skill in place — otherwise the run hard-refuses. Remote callers: must resolve within the skills directory."
+ },
+ "dry_run": {
+ "type": "boolean",
+ "description": "Preview: models plan, strict verdict and cost estimate, no LLM calls"
+ },
+ "shared_skill": {
+ "type": "boolean",
+ "description": "Optimize an exact shared catalog revision in a private proposal workspace and publish the accepted body through put_skill."
+ },
+ "source_id": {
+ "type": "string",
+ "description": "Required with shared_skill: canonical source."
+ },
+ "source_incarnation": {
+ "type": "string",
+ "description": "Required with shared_skill: exact catalog source incarnation."
+ },
+ "pack_id": {
+ "type": "string",
+ "description": "Required with shared_skill: exact catalog pack."
+ },
+ "expected_revision": {
+ "type": "string",
+ "description": "Required with shared_skill: original revision CAS."
+ },
+ "request_id": {
+ "type": "string",
+ "description": "Required with shared_skill: stable publication request UUID."
+ }
+ },
+ "mutating": true,
+ "scope": "admin",
+ "localOnly": false,
+ "area": "admin"
+ },
+ {
+ "name": "open_loops",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": "retrieval",
+ "description": "The open-loop engine's killer output: who is waiting on you, what you promised, and the context needed to respond. Grouped by counterparty (default, ranked; each group shows at most 5 loops, the rest counted in loops_omitted) or flat. Loops that name no counterparty are never ranked as a person: they come back in no_counterparty (null when none). Loops come from the deterministic Gmail thread-state detector and the LLM commitment extractor. Remote callers get redacted evidence (no verbatim quotes); trusted local callers also get quotes, Gmail deep links, entity-card context, and a pre-rendered text digest. Carries google-source freshness (stale flag) and completeness: when it is \"partial\", some mail in the window is held after repeated import failures; present the answer as partial and name the held items and their retry command.",
+ "params": {
+ "group_by": {
+ "type": "string",
+ "enum": [
+ "counterparty",
+ "none"
+ ],
+ "description": "Default 'counterparty' (ranked groups)."
+ },
+ "status": {
+ "type": "string",
+ "enum": [
+ "open",
+ "done",
+ "dropped",
+ "stale"
+ ],
+ "description": "Default 'open', except with `id`, where any status matches."
+ },
+ "id": {
+ "type": "number",
+ "description": "Fetch the single loop with this id (ids come from earlier open_loops results). Matches any status unless `status` is passed; the source scope still applies, and the grouped view omits `text`."
+ },
+ "loop_type": {
+ "type": "string",
+ "enum": [
+ "commitment_owed_by_me",
+ "commitment_owed_to_me",
+ "unanswered_inbound",
+ "unanswered_outbound",
+ "decision_pending"
+ ],
+ "description": "Filter to one loop type."
+ },
+ "counterparty": {
+ "type": "string",
+ "description": "Filter to one counterparty (slug or email)."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Grouped: max groups (default 3). Flat: max loops (default 50). The internal fetch is capped at 500 rows; `truncated: true` marks a hit."
+ },
+ "include_context": {
+ "type": "boolean",
+ "description": "Attach the counterparty entity card per group (trusted local only). Default true."
+ },
+ "source_id": {
+ "type": "string",
+ "description": "Scope to one source (e.g. the google source, when the caller's transport is bound elsewhere). Remote callers must hold a grant covering it."
+ },
+ "all_sources": {
+ "type": "boolean",
+ "description": "Trusted local: span every source in the brain. Remote callers stay inside their grant."
+ },
+ "as_of": {
+ "type": "string",
+ "description": "Reference time (ISO 8601) for due-date proximity, loop age and rendered ages. Default: now. Pin it to reproduce a ranking."
+ }
+ },
+ "scope": "read",
+ "annotations": {
+ "readOnlyHint": true
+ },
+ "area": "loops"
+ },
+ {
+ "name": "loops_close",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Close an open loop by id: status 'done' (handled) or 'dropped' (not going to). Closing is a state transition with an audit trail, never a delete. Thread loops also close automatically when a reply lands.",
+ "params": {
+ "id": {
+ "type": "number",
+ "required": true,
+ "description": "Loop id (from open_loops)."
+ },
+ "status": {
+ "type": "string",
+ "required": true,
+ "enum": [
+ "done",
+ "dropped"
+ ],
+ "description": "Terminal state."
+ },
+ "note": {
+ "type": "string",
+ "description": "Optional closed_by note (default: manual)."
+ },
+ "source_id": {
+ "type": "string",
+ "description": "The loop's home source (e.g. the google source, when the caller's transport is bound elsewhere). Remote callers must be write-bound to it — a federated read grant does not authorize the close. When omitted, the caller's bound write source is used."
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "area": "loops"
+ },
+ {
+ "name": "loops_mute",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Suppress a sender (email address) or thread id from opening NEW loops — the detector feedback primitive behind \"never track this sender\". Existing loops keep their state.",
+ "params": {
+ "kind": {
+ "type": "string",
+ "required": true,
+ "enum": [
+ "sender",
+ "thread"
+ ],
+ "description": "What to mute."
+ },
+ "value": {
+ "type": "string",
+ "required": true,
+ "description": "The sender email or Gmail thread id."
+ },
+ "source_id": {
+ "type": "string",
+ "description": "Google source to scope the mute to (default: routed source)."
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "area": "loops"
+ },
+ {
+ "name": "loops_unmute",
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Remove a sender/thread suppression added by loops_mute, so the detector can open NEW loops for it again. Exact-match only. Does not reopen loops closed while the mute was in place.",
+ "params": {
+ "kind": {
+ "type": "string",
+ "required": true,
+ "enum": [
+ "sender",
+ "thread"
+ ],
+ "description": "What to unmute."
+ },
+ "value": {
+ "type": "string",
+ "required": true,
+ "description": "The sender email or Gmail thread id."
+ },
+ "source_id": {
+ "type": "string",
+ "description": "Google source the mute was scoped to (default: routed source)."
+ }
+ },
+ "mutating": true,
+ "scope": "write",
+ "area": "loops"
+ },
+ {
+ "name": "mute_notice",
+ "mutating": true,
+ "idempotent": true,
+ "outputRedaction": "no_stored_text",
+ "description": "Stop a coaching or info notice (or first_run_decisions) from appearing for this client; muted: false unmutes.",
+ "params": {
+ "code": {
+ "type": "string",
+ "required": true,
+ "description": "Notice code, the word after `[gbrain notice` in the block."
+ },
+ "muted": {
+ "type": "boolean",
+ "description": "false unmutes. Default true."
+ }
+ },
+ "scope": "write",
+ "area": "admin"
+ }
+];
diff --git a/src/core/ops/callable.ts b/src/core/ops/callable.ts
index 3cfeb41d4a..a9e6a2a1d0 100644
--- a/src/core/ops/callable.ts
+++ b/src/core/ops/callable.ts
@@ -5,7 +5,7 @@
* (`RenderContext.isCallable`). Pure: the caller resolves its own scopes,
* publish gates and bound-tool allow-set first.
*/
-import { opError, type Operation, type OperationError } from './contract.ts';
+import { opError, type OperationMeta, type OperationError } from './contract.ts';
import type { Surface, Transport } from '../agent-output.ts';
import { operationScopesAllowed } from '../scope.ts';
import { filterOpsForSurface } from '../../mcp/surface.ts';
@@ -22,7 +22,7 @@ export interface CallableContext {
}
/** The one predicate behind tools/list AND dispatch. */
-export function isCallable(op: Operation, ctx: CallableContext): boolean {
+export function isCallable(op: OperationMeta, ctx: CallableContext): boolean {
if (ctx.allowedOps && !ctx.allowedOps.has(op.name)) return false;
if (filterOpsForSurface([op], ctx.surface).length === 0) return false;
if (ctx.transport === 'cli') return true;
@@ -37,7 +37,7 @@ export function isCallable(op: Operation, ctx: CallableContext): boolean {
* Publish gates keyed by gate key from the resolver's disabled-op set
* (`disabledOpsForPublishGates`): a gate is on when none of its ops is disabled.
*/
-export function publishGatesFromDisabled(ops: readonly Operation[], disabled: ReadonlySet<string>): Record<string, boolean> {
+export function publishGatesFromDisabled(ops: readonly OperationMeta[], disabled: ReadonlySet<string>): Record<string, boolean> {
const gates: Record<string, boolean> = {};
for (const op of ops) {
if (!op.publishGateKey) continue;
@@ -51,7 +51,7 @@ export function publishGatesFromDisabled(ops: readonly Operation[], disabled: Re
* there): the exact CLI command as the fix, relayed to the user. `error`
* keeps the historical `permission_denied`.
*/
-export function cliOnlyRefusal(op: Operation): OperationError {
+export function cliOnlyRefusal(op: OperationMeta): OperationError {
const argv = [...(op.cliOnly?.argv ?? ['gbrain', '--help'])];
const inputs = argv.filter(a => /^<[a-z_]+>$/.test(a)).map(a => ({ name: a.slice(1, -1), how: `The ${a.slice(1, -1)} value from your ${op.name} call.` }));
return opError('trusted_local_only', `${op.name} runs only from the trusted local CLI on the brain host, not over MCP.`,
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index 5cae0fbec2..7920aa4eb7 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -783,6 +783,14 @@ export interface Operation {
};
}
+/**
+ * Everything about an operation except its handler: the data tools/list,
+ * surface filtering, publish gates and CLI arg parsing read. Checked in as
+ * src/core/operation-manifest.generated.ts so `gbrain serve` and the CLI
+ * dispatcher can answer without loading every handler module.
+ */
+export type OperationMeta = Omit<Operation, 'handler'>;
+
/**
* An op that declares its own `source` param (timeline-add, ontology-add,
* takes add/update/supersede, raw data) takes `--source` as that param, e.g.
diff --git a/src/mcp/initialize-context.ts b/src/mcp/initialize-context.ts
index e5e2883e64..40801d5cde 100644
--- a/src/mcp/initialize-context.ts
+++ b/src/mcp/initialize-context.ts
@@ -7,8 +7,8 @@
*/
import type { BrainEngine } from '../core/engine.ts';
import type { GBrainConfig } from '../core/config.ts';
-import type { AuthInfo, Operation } from '../core/operations.ts';
-import { opAllowedForBoundClient } from '../core/operations.ts';
+import type { AuthInfo, OperationMeta } from '../core/ops/contract.ts';
+import { opAllowedForBoundClient } from '../core/ops/context.ts';
import { isCallable, publishGatesFromDisabled } from '../core/ops/callable.ts';
import { configReadiness, probedReadiness, readinessHttpView, readinessTail, type ReadinessCache, type ReadinessEntry } from '../core/readiness.ts';
import { isEngineDegraded } from '../core/degraded-marker.ts';
@@ -37,7 +37,7 @@ export async function instructionReadiness(
/** HTTP (OAuth and legacy bearer): the same filters tools/list applies, publish gates read on initialize. */
export async function httpInstructionTools(
engine: BrainEngine, config: GBrainConfig | null | undefined,
- opts: { ops: readonly Operation[]; surface: 'verbs' | 'starter' | 'full'; auth: AuthInfo; allowedOps?: ReadonlySet<string>; cache?: ReadinessCache },
+ opts: { ops: readonly OperationMeta[]; surface: 'verbs' | 'starter' | 'full'; auth: AuthInfo; allowedOps?: ReadonlySet<string>; cache?: ReadinessCache },
): Promise<InstructionTools> {
const gateDisabled = await disabledOpsForPublishGates(engine, config ?? undefined).catch(() => new Set(opts.ops.map(o => o.name)));
const publishGates = publishGatesFromDisabled(opts.ops, gateDisabled);
diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.ts
index 886c47430d..8f0a51059e 100644
--- a/src/mcp/instructions.ts
+++ b/src/mcp/instructions.ts
@@ -155,9 +155,10 @@ export function resolveMcpInstructions(
* handshake instead of at server construction. The constructor's static
* value stays the fallback when `compute` throws. Relies on the SDK Server's
* initialize handler reading `_instructions` (pinned by
- * test/mcp-initialize-instructions.test.ts).
+ * test/mcp-initialize-instructions.test.ts). `onAnswered` runs once the
+ * response is written (stdio serve starts its deferred boot there).
*/
-export function installInstructionsResolver(server: Server, compute: () => Promise<string>): void {
+export function installInstructionsResolver(server: Server, compute: () => Promise<string>, onAnswered?: () => void): void {
const s = server as unknown as {
_instructions?: string;
_oninitialize(request: unknown): Promise<unknown>;
@@ -167,6 +168,8 @@ export function installInstructionsResolver(server: Server, compute: () => Promi
s.removeRequestHandler('initialize');
server.setRequestHandler(InitializeRequestSchema, async (request) => {
try { s._instructions = await compute(); } catch { /* keep the constructor value */ }
+ // setImmediate fires after the SDK has written this response.
+ if (onAnswered) setImmediate(onAnswered);
return s._oninitialize(request) as never;
});
}
diff --git a/src/mcp/publish-gates.ts b/src/mcp/publish-gates.ts
index a894b31408..3f113c9e83 100644
--- a/src/mcp/publish-gates.ts
+++ b/src/mcp/publish-gates.ts
@@ -19,12 +19,13 @@
import type { BrainEngine } from '../core/engine.ts';
import type { GBrainConfig } from '../core/config.ts';
-import { operations, type Operation } from '../core/operations.ts';
+import type { OperationMeta } from '../core/ops/contract.ts';
+import { OPERATION_MANIFEST } from '../core/operation-manifest.generated.ts';
-export type PublishGateKey = NonNullable<Operation['publishGateKey']>;
+export type PublishGateKey = NonNullable<OperationMeta['publishGateKey']>;
/** Every config key an operation's publish gate reads; `config get` resolves these DB-first like the gate (#5358). */
-export const PUBLISH_GATE_KEYS: ReadonlySet<PublishGateKey> = new Set(operations.flatMap(op => (op.publishGateKey ? [op.publishGateKey] : [])));
+export const PUBLISH_GATE_KEYS: ReadonlySet<PublishGateKey> = new Set(OPERATION_MANIFEST.flatMap(op => (op.publishGateKey ? [op.publishGateKey] : [])));
/**
* Gates that default ON for the owner's stdio pipe when neither plane sets
@@ -69,7 +70,7 @@ export async function disabledOpsForPublishGates(
config: GBrainConfig | null | undefined,
opts: { transport?: string } = {},
): Promise<ReadonlySet<string>> {
- const gated = operations.filter(op => op.publishGateKey);
+ const gated = OPERATION_MANIFEST.filter(op => op.publishGateKey);
if (gated.length === 0) return new Set();
const keys = [...new Set(gated.map(op => op.publishGateKey as PublishGateKey))];
const resolved = new Map<PublishGateKey, boolean>();
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 73b7d9d137..2d7e9ce9ca 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -3,34 +3,90 @@ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import type { BrainEngine } from '../core/engine.ts';
-import { operations, opError, OperationError } from '../core/operations.ts';
+import { opError, type OperationMeta } from '../core/ops/contract.ts';
+import { OPERATION_MANIFEST } from '../core/operation-manifest.generated.ts';
import { isCallable, publishGatesFromDisabled } from '../core/ops/callable.ts';
import { VERSION } from '../version.ts';
import { buildToolDefs } from './tool-defs.ts';
-import { dispatchToolCall, buildOperationContext, dispatchRenderContext, requestMetaSessionId, type ToolResult } from './dispatch.ts';
+import type { ToolResult } from './dispatch.ts';
import { findInvalidParam, schemaInvalidParams, parseStrictParamsMode } from './validate-params.ts';
import { clampSurface, createStdioSurfaceState, resolveAdvertisedSurface, stdioToolListing, sessionWidenAllowed, surfaceEnvInvalidNotice, type McpAccess, type McpSurface, type SurfaceSource } from './surface.ts';
-import { startOnboardingRefresher } from '../core/onboard/mcp-onboarding.ts';
import { noticeBlock, renderNotice, type Notice } from '../core/agent-output.ts';
import { disabledOpsForPublishGates } from './publish-gates.ts';
import { parseResultRowsMode, resolveResultRowsMode } from './result-rows.ts';
-import type { Operation } from '../core/operations.ts';
-import { getBrainHotMemoryMeta } from '../core/facts/meta-hook.ts';
import { loadConfig } from '../core/config.ts';
import { gcSessionContextState } from '../core/context/session-state.ts';
-import { bindResolveIpcForServe } from './resolve-ipc-binding.ts';
-import { createPersistenceIpcProvider, residentPersistenceConfig } from '../core/persistence/provider.ts';
import { installInstructionsResolver, resolveMcpInstructions } from './instructions.ts';
import { instructionReadiness, stdioCapabilityReadiness } from './initialize-context.ts';
import { STATUS_TOOL_DEF, STATUS_TOOL_NAME, attemptStatusRecovery, statusHeadline, statusInstructionLine, statusModeErrorResult, statusModeOf, statusPayload, statusToolResult } from './status-mode.ts';
import { installCapabilitiesResource, mcpAdministrationGuidance } from './capabilities.ts';
-import { createSkillResources } from './skill-resources.ts';
-import { operationScopesAllowed } from '../core/scope.ts';
+import { createSkillResources, type SkillResources } from './skill-resources.ts';
import { readLocalWriter, verifyLocalWriter } from '../core/persistence/identity.ts';
import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writeback-config.ts';
import { isEngineDegraded, onEngineRecovered } from '../core/degraded-marker.ts';
import { assertStdioSourceBindable } from './source-preflight.ts';
+// initialize and tools/list read OPERATION_MANIFEST; the handler graph behind
+// dispatch.ts (src/core/operations.ts, ~760 modules) loads with the deferred
+// boot in startMcpServer, or on the first tools/call.
+type DispatchModule = typeof import('./dispatch.ts');
+const loadDispatch = (): Promise<DispatchModule> => import('./dispatch.ts');
+const loadMetaHook = () => import('../core/facts/meta-hook.ts');
+
+/**
+ * Engine-dependent boot waits for the handshake so initialize and the first
+ * tools/list don't queue behind its module loading. It starts when the first
+ * tools/list is answered, or BOOT_LIST_GRACE_MS after initialize is answered
+ * with no tools/list in flight (a client that calls without listing), or
+ * BOOT_WITHOUT_INITIALIZE_MS after connect for a client that never
+ * initializes (a supervisor probe, a test driver).
+ */
+export const BOOT_LIST_GRACE_MS = 25;
+export const BOOT_WITHOUT_INITIALIZE_MS = 1000;
+
+/** Skill resource reads dispatch ops, so they wait for the deferred boot; listing does not. */
+function bootGatedReads(skills: SkillResources, awaitBoot: () => Promise<void>): SkillResources {
+ return { list: () => skills.list(), read: async uri => { await awaitBoot(); return skills.read(uri); } };
+}
+
+/**
+ * The stdio deferred-boot gate. `run` waits for a trigger (see
+ * BOOT_LIST_GRACE_MS, or `awaitBoot` from a call), then boots; calls await
+ * `awaitBoot`, so none dispatches against a half-booted server, and a boot
+ * failure rejects them with the boot error while `run` rethrows it to
+ * startMcpServer (the fatal serve exit it always was). The handler graph
+ * starts loading at the trigger, alongside the boot.
+ */
+function deferredBoot(opts: { degraded: boolean }) {
+ let listsInFlight = 0;
+ let request!: () => void;
+ const requested = new Promise<void>(resolve => { request = resolve; });
+ const booted = Promise.withResolvers<void>();
+ // Degraded serve defers engine-dependent boot to its recovery hook, as before: calls never wait for it.
+ if (opts.degraded) booted.resolve();
+ booted.promise.catch(() => { /* rethrown by awaitBoot and run */ });
+ void requested.then(() => Promise.all([loadDispatch(), loadMetaHook()])).catch(() => { /* the first call's import reports it */ });
+ const awaitBoot = (): Promise<void> => { request(); return booted.promise; };
+ return {
+ awaitBoot,
+ /** Boot, then the dispatch and hot-memory modules a tools/call needs. */
+ awaitCall: async () => { await awaitBoot(); return Promise.all([loadDispatch(), loadMetaHook()]); },
+ initializeAnswered: (): void => { setTimeout(() => { if (listsInFlight === 0) request(); }, BOOT_LIST_GRACE_MS); },
+ async list<T>(work: () => Promise<T>): Promise<T> {
+ listsInFlight++;
+ try { return await work(); } finally { listsInFlight--; setImmediate(request); }
+ },
+ async run(bootPhase: (phase: string) => void, boot: () => Promise<void>): Promise<void> {
+ bootPhase('initialize_wait');
+ const fallback = setTimeout(request, BOOT_WITHOUT_INITIALIZE_MS);
+ fallback.unref?.();
+ await requested;
+ clearTimeout(fallback);
+ try { await boot(); booted.resolve(); } catch (e) { booted.reject(e); throw e; }
+ },
+ };
+}
+
export async function resolveMcpStdioSourceScope(
engine: BrainEngine,
cwd: string = process.cwd(),
@@ -144,10 +200,10 @@ export function createDefaultWriteAdvisory(
* rare). Fail-closed: a resolver failure hides every gated op rather than
* re-creating the listed-but-denied complaint.
*/
-export async function stdioVisibleTools(
+export async function stdioVisibleTools<T extends OperationMeta>(
engine: BrainEngine,
- surfacedOps: Operation[],
-): Promise<Operation[]> {
+ surfacedOps: T[],
+): Promise<T[]> {
let scopes: readonly string[] = [];
if (surfacedOps.some(op => op.requiredScopes?.length) && !isEngineDegraded(engine)) {
try {
@@ -219,7 +275,7 @@ function stdioSurfaceSession(
opts: { surface?: McpSurface; surfaceSource?: SurfaceSource; invalidSurfaceEnv?: string; access?: McpAccess },
server: () => Server | null,
) {
- const session = createStdioSurfaceState(operations, {
+ const session = createStdioSurfaceState(OPERATION_MANIFEST, {
surface: clampSurface(opts.surface ?? 'full'), source: opts.surfaceSource ?? (opts.surface ? 'flag' : 'default'), readOnly: opts.access === 'read-only',
onWiden: ({ from, to, added }) => {
process.stderr.write(`[gbrain-serve] surface_widened from=${from} to=${to} op=request_tools added=${added.length}\n`);
@@ -227,7 +283,7 @@ function stdioSurfaceSession(
},
});
let pending: Notice | null = opts.invalidSurfaceEnv ? surfaceEnvInvalidNotice(opts.invalidSurfaceEnv, session.surface, session.source) : null;
- const finishResult = (result: ToolResult): ToolResult => {
+ const finishResult = (result: ToolResult, dispatchRenderContext: DispatchModule['dispatchRenderContext']): ToolResult => {
if (!pending || result.isError) return result;
const rendered = renderNotice(pending, dispatchRenderContext({ transport: 'stdio', remote: true, surface: session.surface, allowedOps: session.allowedOps }));
result.content.push({ type: 'text', text: noticeBlock(rendered) });
@@ -264,6 +320,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
let server: Server | null = null;
const { session, finishResult, statusResult } = stdioSurfaceSession(opts, () => server);
+ const gate = deferredBoot({ degraded: isEngineDegraded(engine) }); // engine-dependent boot waits for the handshake
// Ambient writeback (opt-in, default off): resolved ONCE at boot — a
// config flip needs a serve restart on this lane, the same posture as
// `mcp.strict_params` below. Uses the fail-closed dual-plane resolver
@@ -306,7 +363,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
writeback: writebackOpts,
tools: { callable: n => visible.has(n), readiness: await instructionReadiness(engine, config, 'stdio'), hiddenCallable: visibleOps.length - (await listing.listed(visibleOps)).length },
});
- });
+ }, gate.initializeAnswered);
// WP3: strict-params schema emission, resolved ONCE at startup from the
installCapabilitiesResource(server, async () => {
@@ -327,11 +384,11 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
can_join: available.includes('join_brain'), can_edit: available.includes('put_skill') && available.includes('delete_skill'), native_activation: 'unverified' },
...await stdioCapabilityReadiness(engine, config),
note: 'This local MCP pipe has no OAuth profile; agent-facing operation restrictions still apply.' };
- }, createSkillResources(engine, async () => {
+ }, bootGatedReads(createSkillResources(engine, async () => {
const scope = await resolveMcpStdioSourceScope(engine);
return { remote: true, transport: 'stdio', sourceId: scope.sourceId,
localFederatedSourceIds: scope.localFederatedSourceIds, allowedOps: session.allowedOps, surface: session.surface, config: config ?? undefined };
- }));
+ }), gate.awaitBoot));
// FILE config plane only — stdio has no per-request list cycle, so a
// `mcp.strict_params` flip needs a serve restart here (deliberate; the
@@ -349,11 +406,11 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// subtraction happens per request (stdioVisibleTools) — no caching, so a
// `gbrain config set mcp.publish_skills true` takes effect on the next
// tools/list without a serve restart (matches the HTTP transports).
- server.setRequestHandler(ListToolsRequestSchema, async () => trackStdioRpc(async () => ({
+ server.setRequestHandler(ListToolsRequestSchema, async () => trackStdioRpc(() => gate.list(async () => ({
tools: statusMode && isEngineDegraded(engine)
? [STATUS_TOOL_DEF]
: buildToolDefs(await listing.listed(await stdioVisibleTools(engine, session.surfacedOps)), { strictParams }),
- })));
+ }))));
// #4583 (fixes #4564's misrouted-write symptom): once-per-process advisory
// for unscoped default writes on a multi-source brain; latch semantics live
@@ -368,6 +425,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// shape and cast through `any` (the SDK accepts it via the ServerResult union).
server.setRequestHandler(CallToolRequestSchema, async (request: any): Promise<any> => trackStdioRpc(async () => {
const { name, arguments: params } = request.params;
+ const [{ dispatchToolCall, dispatchRenderContext, requestMetaSessionId }, { getBrainHotMemoryMeta }] = await gate.awaitCall();
// F4: status-only mode answers gbrain_status and refuses the rest until
// a tool call's re-probe finds the brain openable (then dispatch normally).
if (statusMode) {
@@ -398,7 +456,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// this transport, so warn instead of refusing the agent's write.
await defaultWriteAdvisory(
sourceScope.tier,
- operations.find(o => o.name === name)?.mutating === true,
+ OPERATION_MANIFEST.find(o => o.name === name)?.mutating === true,
);
return finishResult(await dispatchToolCall(engine, name, params, {
remote: true,
@@ -430,7 +488,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// request_tools bounds its catalog by; its {surface} call widens the session.
surfaceCeiling: session.surface, stdioSurface: session, revealTools: listing.reveal,
resultRows,
- }));
+ }), dispatchRenderContext);
}));
const transport = new StdioServerTransport();
@@ -449,6 +507,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// (+ delegated sync/sweep) IPC listener. Wiring shared with `serve --http`
// via bindResolveIpcForServe (#4474) — best-effort; failure to bind never
// blocks the MCP server.
+ const [{ createPersistenceIpcProvider, residentPersistenceConfig }, { bindResolveIpcForServe }] = await Promise.all([import('../core/persistence/provider.ts'), import('./resolve-ipc-binding.ts')]);
bootPhase('source_scope');
const { sourceId: ipcSourceId } = await resolveMcpStdioSourceScope(engine);
bootPhase('persistence_consumer');
@@ -467,7 +526,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
// connect, unref'd (can never hold the process open), all errors
// swallowed inside armStartupSweep. Kill switch: GBRAIN_SWEEP=0 (checked
// inside the helper). Lazy import keeps sweep code off the boot path.
- startOnboardingRefresher(engine, { idle: () => _stdioRpcsInFlight === 0 }).catch(() => { /* coaching is best-effort */ });
+ import('../core/onboard/mcp-onboarding.ts').then(m => m.startOnboardingRefresher(engine, { idle: () => _stdioRpcsInFlight === 0 })).catch(() => { /* coaching is best-effort */ });
bootPhase('startup_sweep');
try {
const { armStartupSweep } = await import('../core/sweep.ts');
@@ -496,7 +555,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
bootEngineDependents().catch(() => { /* deferred boot is best-effort */ });
});
} else {
- await bootEngineDependents();
+ await gate.run(bootPhase, bootEngineDependents);
}
// Exit cleanly when MCP client disconnects (stdin EOF) or on signals.
@@ -554,6 +613,7 @@ export async function handleToolCall(
params: Record<string, unknown>,
opts?: { sourceId?: string; localFederatedSourceIds?: string[]; writeWaitMs?: number },
): Promise<unknown> {
+ const [{ operations }, { buildOperationContext }] = await Promise.all([import('../core/operations.ts'), loadDispatch()]);
const op = operations.find(o => o.name === tool);
if (!op) throw opError('unknown_tool', `Unknown tool: ${tool}`, 'Run `gbrain --tools-json` to list the tool names.');
diff --git a/src/mcp/skill-resources.ts b/src/mcp/skill-resources.ts
index b64c82fa3c..e21478a2ed 100644
--- a/src/mcp/skill-resources.ts
+++ b/src/mcp/skill-resources.ts
@@ -1,11 +1,11 @@
import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
import type { BrainEngine } from '../core/engine.ts';
-import { operations } from '../core/operations.ts';
+import { OPERATION_MANIFEST } from '../core/operation-manifest.generated.ts';
import { opAllowedForBoundClient } from '../core/ops/context.ts';
import { operationScopesAllowed } from '../core/scope.ts';
import { loadConfig } from '../core/config.ts';
import { disabledOpsForPublishGates } from './publish-gates.ts';
-import { dispatchToolCall, type DispatchOpts } from './dispatch.ts';
+import type { DispatchOpts } from './dispatch.ts';
import type { SharedSkillList, SharedSkillDetail } from '../core/shared-skills/model.ts';
export const SKILLS_RESOURCE_URI = 'gbrain://skills';
@@ -21,7 +21,7 @@ export function sharedSkillResourceUri(qualifiedId: string, revision: string, pa
export function createSkillResources(engine: BrainEngine, context: () => Promise<DispatchOpts>): SkillResources {
async function permitted(name: string, opts: DispatchOpts): Promise<boolean> {
- const op = operations.find(candidate => candidate.name === name);
+ const op = OPERATION_MANIFEST.find(candidate => candidate.name === name);
if (!op || (opts.allowedOps && !opts.allowedOps.has(name))) return false;
if (opts.remote === false) return true;
if (op.localOnly || !opAllowedForBoundClient(opts.auth, op)) return false;
@@ -30,6 +30,7 @@ export function createSkillResources(engine: BrainEngine, context: () => Promise
}
async function call<T>(name: string, params: Record<string, unknown>, opts: DispatchOpts): Promise<T> {
if (!await permitted(name, opts)) throw new McpError(ErrorCode.InvalidParams, 'Unknown or unavailable skill resource');
+ const { dispatchToolCall } = await import('./dispatch.ts');
const result = await dispatchToolCall(engine, name, params, opts);
const body = JSON.parse(result.content[0].text);
if (result.isError) throw new McpError(ErrorCode.InternalError, 'Skill resource could not be read', { error: body.error });
diff --git a/src/mcp/surface.ts b/src/mcp/surface.ts
index 34eb6e4dfb..c32ce47d4c 100644
--- a/src/mcp/surface.ts
+++ b/src/mcp/surface.ts
@@ -31,13 +31,13 @@
* an explicit `--surface` restart.
*/
-import type { Operation } from '../core/operations.ts';
+import type { OperationMeta } from '../core/ops/contract.ts';
import type { Notice } from '../core/agent-output.ts';
import type { GBrainConfig } from '../core/config.ts';
import type { BrainEngine } from '../core/engine.ts';
import { VERB_NAMES } from '../core/verbs.ts';
import { opError } from '../core/ops/contract.ts';
-import { BRAIN_TOOL_ALLOWLIST } from '../core/minions/tools/brain-allowlist.ts';
+import { BRAIN_TOOL_ALLOWLIST } from '../core/minions/tools/brain-tool-allowlist.ts';
export type McpSurface = 'verbs' | 'starter' | 'full';
@@ -169,7 +169,7 @@ export function parseAccessFlag(args: string[]): McpAccess {
return raw;
}
-export function isReadOnlyOperation(op: Pick<Operation, 'scope' | 'mutating' | 'requiredScopes'>): boolean {
+export function isReadOnlyOperation(op: Pick<OperationMeta, 'scope' | 'mutating' | 'requiredScopes'>): boolean {
return op.scope === 'read' && op.mutating !== true && !op.requiredScopes?.length;
}
@@ -214,7 +214,7 @@ export function resolveStdioSurface(
return { ...resolveSurfaceWithSource(flag, config), invalidEnv: env };
}
-export function filterOpsForSurface(ops: Operation[], surface: McpSurface): Operation[] {
+export function filterOpsForSurface<T extends OperationMeta>(ops: T[], surface: McpSurface): T[] {
if (surface === 'full') return ops;
// FROZEN: 'verbs' is EXACTLY `op.verb === true` (MEMORY_VERBS v1) — starter
// extends the ladder above it and must never alter these semantics.
@@ -223,13 +223,13 @@ export function filterOpsForSurface(ops: Operation[], surface: McpSurface): Oper
}
/** Starter ops advertise every param except the full-surface-only ones. */
-function starterParams(op: Operation): Operation {
+function starterParams<T extends OperationMeta>(op: T): T {
if (!Object.values(op.params).some(p => p.fullSurfaceOnly)) return op;
return { ...op, params: Object.fromEntries(Object.entries(op.params).filter(([, p]) => !p.fullSurfaceOnly)) };
}
/** The fail-closed allow-set handed to dispatchToolCall. */
-export function allowedOpNames(ops: Operation[], surface: McpSurface): ReadonlySet<string> {
+export function allowedOpNames(ops: OperationMeta[], surface: McpSurface): ReadonlySet<string> {
return new Set(filterOpsForSurface(ops, surface).map(o => o.name));
}
@@ -349,9 +349,9 @@ export async function resolveAdvertisedSurface(engine: BrainEngine | null, confi
}
/** The tools to list: the callable set narrowed to the advertised surface (never wider). */
-export function advertisedOps<T extends Operation>(callable: T[], callableSurface: McpSurface, advertised: McpSurface | null): T[] {
+export function advertisedOps<T extends OperationMeta>(callable: T[], callableSurface: McpSurface, advertised: McpSurface | null): T[] {
if (!advertised || !surfaceWiderThan(callableSurface, advertised)) return callable;
- const listed = new Set(filterOpsForSurface(callable as Operation[], advertised).map(op => op.name));
+ const listed = new Set(filterOpsForSurface(callable, advertised).map(op => op.name));
return callable.filter(op => listed.has(op.name));
}
@@ -368,7 +368,7 @@ export function stdioToolListing(advertised: () => Promise<McpSurface | null>, s
const startSurface = session.surface;
const notify = () => { Promise.resolve(server.sendToolListChanged()).catch(() => { /* best-effort */ }); };
return {
- async listed<T extends Operation>(visible: T[]): Promise<T[]> {
+ async listed<T extends OperationMeta>(visible: T[]): Promise<T[]> {
// A session the agent widened with request_tools {surface} lists everything it asked for.
if (session.surface !== startSurface) return visible;
const listed = advertisedOps(visible, session.surface, await advertised());
@@ -422,13 +422,13 @@ export interface StdioSurfaceState {
readonly readOnly: boolean;
/** `mcp.allow_session_widen` as last resolved (boot, then each request_tools call). */
widenAllowed: boolean;
- surfacedOps: Operation[];
+ surfacedOps: OperationMeta[];
allowedOps: ReadonlySet<string> | undefined;
widen(to: McpSurface): { from: McpSurface; to: McpSurface; added: string[] };
}
export function createStdioSurfaceState(
- ops: Operation[],
+ ops: OperationMeta[],
init: { surface: McpSurface; source: SurfaceSource; readOnly: boolean; onWiden?: (change: { from: McpSurface; to: McpSurface; added: string[] }) => void },
): StdioSurfaceState {
const compute = (surface: McpSurface) => {
diff --git a/src/mcp/tool-defs.ts b/src/mcp/tool-defs.ts
index 5910902c01..c80a337ed8 100644
--- a/src/mcp/tool-defs.ts
+++ b/src/mcp/tool-defs.ts
@@ -1,4 +1,4 @@
-import type { Operation, ParamDef } from '../core/operations.ts';
+import type { OperationMeta, ParamDef } from '../core/ops/contract.ts';
export interface McpToolDef {
name: string;
@@ -65,7 +65,7 @@ export function paramDefToSchema(p: ParamDef): Record<string, unknown> {
* the server. Declared only when the op doesn't already declare them
* (several ops carry a real `dry_run` param).
*/
-function strictPassthroughProperties(op: Operation): Record<string, unknown> {
+function strictPassthroughProperties(op: OperationMeta): Record<string, unknown> {
return {
...('_meta' in op.params ? {} : {
_meta: {
@@ -87,7 +87,7 @@ function strictPassthroughProperties(op: Operation): Record<string, unknown> {
* `destructiveHint` and `openWorldHint` keep the MCP defaults (no metadata
* separates additive from destructive writes yet).
*/
-export function toolAnnotations(op: Operation): McpToolDef['annotations'] | undefined {
+export function toolAnnotations(op: OperationMeta): McpToolDef['annotations'] | undefined {
if (op.annotations) return op.annotations;
if (op.mutating === false) return { readOnlyHint: true };
if (op.mutating === true) return op.idempotent === true ? { readOnlyHint: false, idempotentHint: true } : { readOnlyHint: false };
@@ -104,7 +104,7 @@ export function toolAnnotations(op: Operation): McpToolDef['annotations'] | unde
* the schema with `additionalProperties: false`, keeping client-side
* validation aligned with the server's reject posture.
*/
-export function buildToolDefs(ops: Operation[], opts?: { strictParams?: boolean }): McpToolDef[] {
+export function buildToolDefs(ops: OperationMeta[], opts?: { strictParams?: boolean }): McpToolDef[] {
const strict = opts?.strictParams === true;
return ops.map(op => {
const annotations = toolAnnotations(op);
diff --git a/test/fixtures/mcp-stdio-list-driver.ts b/test/fixtures/mcp-stdio-list-driver.ts
new file mode 100644
index 0000000000..cb40e13040
--- /dev/null
+++ b/test/fixtures/mcp-stdio-list-driver.ts
@@ -0,0 +1,32 @@
+// Real stdio MCP server on an in-memory PGLite brain, for
+// test/mcp-tool-list-snapshot.test.ts. SNAP_EAGER=1 swaps the generated
+// operation manifest for the live registry (src/core/operations.ts, handlers
+// included), so the same server code runs on the eager path it replaced.
+// SNAP_SURFACE / SNAP_ACCESS map to startMcpServer's surface / access.
+import { plugin } from 'bun';
+
+if (process.env.SNAP_EAGER === '1') {
+ plugin({
+ name: 'eager-operation-registry',
+ setup(build) {
+ build.onLoad({ filter: /operation-manifest\.generated\.ts$/ }, () => ({
+ contents: "export { operations as OPERATION_MANIFEST } from './operations.ts';",
+ loader: 'ts',
+ }));
+ },
+ });
+}
+
+// The PGLite schema snapshot's embedding shape, so an in-memory boot restores it.
+const { configureGateway } = await import('../../src/core/ai/gateway.ts');
+configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+const { PGLiteEngine } = await import('../../src/core/pglite-engine.ts');
+const { startMcpServer } = await import('../../src/mcp/server.ts');
+const engine = new PGLiteEngine();
+await engine.connect({});
+await engine.initSchema();
+const surface = process.env.SNAP_SURFACE as 'verbs' | 'starter' | 'full' | undefined;
+await startMcpServer(engine, {
+ ...(surface ? { surface } : {}),
+ ...(process.env.SNAP_ACCESS === 'read-only' ? { access: 'read-only' as const } : {}),
+});
diff --git a/test/mcp-tool-list-snapshot.test.ts b/test/mcp-tool-list-snapshot.test.ts
new file mode 100644
index 0000000000..df1b719f1e
--- /dev/null
+++ b/test/mcp-tool-list-snapshot.test.ts
@@ -0,0 +1,106 @@
+/**
+ * Stdio initialize + tools/list byte-identity: the server builds both from
+ * src/core/operation-manifest.generated.ts instead of loading every handler
+ * module. Each mode boots the real startMcpServer twice — once as shipped and
+ * once with the manifest swapped for the live operations registry
+ * (test/fixtures/mcp-stdio-list-driver.ts) — and requires the two initialize
+ * results and tools/list results to match byte for byte. Editing an op
+ * without `bun run build:operation-manifest` fails here (and in
+ * test/operation-manifest.test.ts).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join, resolve } from 'path';
+
+const REPO_ROOT = resolve(import.meta.dir, '..');
+const DRIVER = join(REPO_ROOT, 'test', 'fixtures', 'mcp-stdio-list-driver.ts');
+const CHILD_STRIP = ['GBRAIN_DATABASE_URL', 'DATABASE_URL', 'GBRAIN_BRAIN_ID', 'GBRAIN_SOURCE', 'GBRAIN_SURFACE', 'GBRAIN_MCP_FORCE_SURFACE', 'GBRAIN_MCP_INSTRUCTIONS'];
+const dirs: string[] = [];
+afterAll(() => { for (const d of dirs) rmSync(d, { recursive: true, force: true }); });
+
+interface Mode { name: string; surface?: 'verbs' | 'starter' | 'full'; access?: 'read-only'; mcp?: Record<string, unknown> }
+
+const MODES: Mode[] = [
+ { name: 'default (full)' },
+ { name: 'starter, strict params', surface: 'starter', mcp: { strict_params: 'reject' } },
+ { name: 'verbs', surface: 'verbs' },
+ { name: 'full, read-only access', access: 'read-only' },
+ { name: 'full, both publish gates on, strict params', mcp: { publish_skills: true, publish_advisor: true, strict_params: 'reject' } },
+ { name: 'full, advisor gate off, advertised starter', mcp: { publish_advisor: false, advertised_surface: 'starter' } },
+];
+
+async function handshake(mode: Mode, eager: boolean): Promise<{ initialize: string; tools: string }> {
+ const parent = mkdtempSync(join(tmpdir(), 'gb-snap-'));
+ dirs.push(parent);
+ mkdirSync(join(parent, '.gbrain'), { recursive: true });
+ writeFileSync(join(parent, '.gbrain', 'config.json'), JSON.stringify({
+ engine: 'pglite', database_path: join(parent, 'db'), embedding_dimensions: 1536, ...(mode.mcp ? { mcp: mode.mcp } : {}),
+ }));
+ const env = { ...process.env } as Record<string, string>;
+ for (const k of CHILD_STRIP) delete env[k];
+ Object.assign(env, {
+ GBRAIN_HOME: parent, HOME: parent, GBRAIN_SWEEP: '0', GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_SERVE_SYNC_IPC: '0',
+ SNAP_EAGER: eager ? '1' : '0', SNAP_SURFACE: mode.surface ?? '', SNAP_ACCESS: mode.access ?? '',
+ });
+ const proc = Bun.spawn([process.execPath, DRIVER], { cwd: parent, env, stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' });
+ const responses = new Map<number, string>();
+ const reader = (async () => {
+ const decoder = new TextDecoder();
+ let buf = '';
+ for await (const chunk of proc.stdout) {
+ buf += decoder.decode(chunk, { stream: true });
+ let nl: number;
+ while ((nl = buf.indexOf('\n')) >= 0) {
+ const msg = JSON.parse(buf.slice(0, nl));
+ buf = buf.slice(nl + 1);
+ if (typeof msg.id === 'number') responses.set(msg.id, JSON.stringify(msg.result ?? msg.error));
+ }
+ }
+ })();
+ const send = (msg: unknown) => { proc.stdin.write(JSON.stringify(msg) + '\n'); proc.stdin.flush(); };
+ const waitFor = async (id: number) => {
+ const deadline = Date.now() + 60_000;
+ while (!responses.has(id)) {
+ if (proc.exitCode !== null) throw new Error(`driver exited ${proc.exitCode}: ${await new Response(proc.stderr).text()}`);
+ if (Date.now() > deadline) throw new Error(`no response ${id}`);
+ await Bun.sleep(10);
+ }
+ return responses.get(id)!;
+ };
+ try {
+ send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'snapshot', version: '0' } } });
+ const initialize = await waitFor(1);
+ send({ jsonrpc: '2.0', method: 'notifications/initialized' });
+ send({ jsonrpc: '2.0', id: 2, method: 'tools/list', params: {} });
+ const tools = await waitFor(2);
+ return { initialize, tools };
+ } finally {
+ proc.kill('SIGKILL');
+ await proc.exited;
+ await reader.catch(() => {});
+ }
+}
+
+type Pair = { manifest: { initialize: string; tools: string }; eager: { initialize: string; tools: string } };
+let results: Pair[] = [];
+beforeAll(async () => {
+ results = await Promise.all(MODES.map(async mode => {
+ const [manifest, eager] = await Promise.all([handshake(mode, false), handshake(mode, true)]);
+ return { manifest, eager };
+ }));
+}, 180_000);
+
+describe('stdio initialize + tools/list: manifest path == eager registry path', () => {
+ MODES.forEach((mode, i) => {
+ test(mode.name, () => {
+ const { manifest, eager } = results[i];
+ expect(JSON.parse(manifest.tools).tools.length).toBeGreaterThan(0);
+ expect(manifest.tools).toBe(eager.tools);
+ expect(manifest.initialize).toBe(eager.initialize);
+ });
+ });
+ test('every mode lists a different tool set (the matrix is not degenerate)', () => {
+ expect(new Set(results.map(r => r.manifest.tools)).size).toBe(MODES.length);
+ });
+});
diff --git a/test/operation-manifest.test.ts b/test/operation-manifest.test.ts
new file mode 100644
index 0000000000..e48ec50e96
--- /dev/null
+++ b/test/operation-manifest.test.ts
@@ -0,0 +1,38 @@
+/**
+ * src/core/operation-manifest.generated.ts: freshness, equality with the
+ * live registry, and the startup graph it exists for. `gbrain serve` and the
+ * CLI dispatcher read the manifest so the ~760-module handler graph behind
+ * src/core/operations.ts loads only when an op runs; a static import of
+ * operations.ts on that path silently undoes the win, so it is pinned here.
+ */
+import { describe, expect, test } from 'bun:test';
+import { readFileSync } from 'fs';
+import { resolve } from 'path';
+import { OPERATION_MANIFEST_PATH, renderOperationManifest } from '../scripts/build-operation-manifest.ts';
+import { OPERATION_MANIFEST } from '../src/core/operation-manifest.generated.ts';
+import { operations } from '../src/core/operations.ts';
+
+const REPO_ROOT = resolve(import.meta.dir, '..');
+
+describe('operation manifest', () => {
+ test('committed file matches a fresh render (run `bun run build:operation-manifest`)', () => {
+ expect(readFileSync(OPERATION_MANIFEST_PATH, 'utf-8')).toBe(renderOperationManifest());
+ });
+
+ test('every operation minus its handler, same order, same key order', () => {
+ const live = operations.map(({ handler: _handler, ...meta }) => meta);
+ expect(JSON.stringify(OPERATION_MANIFEST)).toBe(JSON.stringify(live));
+ });
+
+ test('serve and CLI dispatcher modules do not load operations.ts at import', () => {
+ const probe = [
+ "await import('./src/cli/main.ts');",
+ "await import('./src/commands/serve.ts');",
+ "await import('./src/mcp/server.ts');",
+ "console.log(JSON.stringify(Object.keys(require.cache).filter(k => k.endsWith('/src/core/operations.ts') || k.endsWith('/src/mcp/dispatch.ts'))));",
+ ].join('\n');
+ const out = Bun.spawnSync([process.execPath, '-e', probe], { cwd: REPO_ROOT, env: { ...process.env, GBRAIN_HOME: '/nonexistent-gbrain-home' } });
+ expect(out.exitCode).toBe(0);
+ expect(JSON.parse(out.stdout.toString().trim().split('\n').pop()!)).toEqual([]);
+ });
+});