Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

chore(trust): renumber provisional migrations to v220/v221/v222/v224, reserving v223 for L1a

garrytan7f42bd05011e
diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.md
index f9a6108ffb..ba36d6fb18 100644
--- a/docs/architecture/key-files/mcp.md
+++ b/docs/architecture/key-files/mcp.md
@@ -3,7 +3,7 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)`, `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts` — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash, so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness; every mutating op, successful or not, drops the engine's entries via `invalidateHotMemoryForEngine`, a build that raced it is not stored, each hit revalidates the source's `fact_withdrawals` watermark so a forget from any process is never served, the key folds the effective read eligibility and each hit revalidates the trust policy generation (`src/core/eligibility/generation.ts`, migration v234: deferred triggers bump `trust_policy_state` on tier changes, quarantine transitions, read floor and `trust.%` config changes, purges and `needs_rederive`), read before the rows; an unreadable generation delivers nothing; facts read through the `hot_memory` proactive eligibility and `partitionForActivation`, carry `trust_tier` and `origin`, and the payload's `suppressed` counts what activation control withheld), each producer isolated so one failure never drops another's key; A successful result's content[0] is compact `JSON.stringify(result)` (error envelopes stay indented); `opts.resultRows` threads the transport's row-shape choice into `OperationContext.resultRows`. empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. `retrievalNoticeBlocks` caps the saved-facts block at 1,500 characters and the other-names block at 400 (header included) with whole items only: the first item always shows, later items that would cross the ceiling are counted in a `(+N more…)` marker (pinned by `test/mcp-notice-ceilings.test.ts`). Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier: true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `accepted_pending` (a `write_pending` with an admitted non-terminal receipt, kept out of the admin error rate; `acceptedPendingReceipt` returns its receipt so serve-http logs the opaque `write_request_id`) / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). Logging paths route through this helper, not `JSON.stringify(params)`. Agent contract v1: every failure (unknown tool, source guard, validation, strict params, missing source scope, handler throws) goes through `errorResult` → `toAgentError` → exactly one content block; handlers emit advice through `ctx.emitNotice` and the empty-retrieval, unknown-param and backup-coverage blocks ride that channel (prefixed `[gbrain notice <code> kind=<kind>]` blocks + `_meta.gbrain_notices`), filtered by the notice ledger (`opts.noticeLedger` on HTTP). `dispatchRenderContext` binds `isCallable` for fixes; `unknownToolEnvelope(name, opts, 'unknown_operation')` keeps serve-http's frozen value; `localCallErrorEnvelope` is `gbrain call`'s envelope. `sessionSafetyNotices` adds the one-time `behavior_changes` disclosure (stdio: once per brain; HTTP: once per authenticated client, remote view) and, on stdio only, the queued `chat_fallback_hop` notice, on success and failure results alike. `requestMetaSessionId(request.params)` is the one reader of the request-level `_meta.session_id` (beside `arguments`); stdio (`server.ts`) and HTTP (`serve-http-mcp.ts`) both pass it as `opts.sessionId`, which wins over an arguments-level `_meta` and is clamped to `SESSION_ID_MAX_CHARS` (256). Caches keyed on it stay bounded: the hot-memory cache at `HOT_MEMORY_CACHE_MAX_ENTRIES` (1000) and the facts queue's per-session counter, deleted at zero. `retrievalNoticeBlocks` also appends the rate line for a rateable answer (`_meta.retrieval.answer_id` with `feedback.rateable`): `Rate after use: rate_answer { answer_id, rating: 1-5 }`, or the fuller wording when `how_to_rate` fired, capped at `RATE_LINE_MAX_CHARS` = 160 (#6192; `test/mcp-feedback-visible-answer-id.test.ts`).
+- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)`, `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts` — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash, so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness; every mutating op, successful or not, drops the engine's entries via `invalidateHotMemoryForEngine`, a build that raced it is not stored, each hit revalidates the source's `fact_withdrawals` watermark so a forget from any process is never served, the key folds the effective read eligibility and each hit revalidates the trust policy generation (`src/core/eligibility/generation.ts`, migration v224: deferred triggers bump `trust_policy_state` on tier changes, quarantine transitions, read floor and `trust.%` config changes, purges and `needs_rederive`), read before the rows; an unreadable generation delivers nothing; facts read through the `hot_memory` proactive eligibility and `partitionForActivation`, carry `trust_tier` and `origin`, and the payload's `suppressed` counts what activation control withheld), each producer isolated so one failure never drops another's key; A successful result's content[0] is compact `JSON.stringify(result)` (error envelopes stay indented); `opts.resultRows` threads the transport's row-shape choice into `OperationContext.resultRows`. empty retrieval results get a SECOND model-visible content block via `buildEmptyRetrievalBlock`. `retrievalNoticeBlocks` caps the saved-facts block at 1,500 characters and the other-names block at 400 (header included) with whole items only: the first item always shows, later items that would cross the ceiling are counted in a `(+N more…)` marker (pinned by `test/mcp-notice-ceilings.test.ts`). Exports `isListLevelDenialEnvelope(parsed)` — the honest-catalog metric classifier: true for op-level denials the tools/list filter should have prevented (`detail: 'config_key=...'` publish-gate backstop, `detail: 'fence=op'` fence op-level deny), false for argument-level denials; serve-http logs matches as `status='denied_after_list'`. Exports `requestLogStatusForResult(result)` — the ONE request-log status decision (`success` / `success_with_warnings` / `accepted_pending` (a `write_pending` with an admitted non-terminal receipt, kept out of the admin error rate; `acceptedPendingReceipt` returns its receipt so serve-http logs the opaque `write_request_id`) / `denied_after_list` / `error`); BOTH HTTP transports (serve-http.ts and the legacy-bearer http-transport.ts) route every tools/call row through it so the honest-catalog metric sees all HTTP traffic (pinned by test/denied-after-list.test.ts + test/http-transport.test.ts). Also exports `summarizeMcpParams(opName, params)` — privacy-preserving redactor for `mcp_request_log` and the admin SSE feed, returns `{redacted, kind, declared_keys, unknown_key_count, approx_bytes}`. Intersects submitted top-level keys against the operation's declared `params` allow-list (declared keys preserved sorted; unknown keys counted but never named, closing the attacker-controlled-key-name leak). Byte counts bucketed up to nearest 1KB so an attacker can't binary-search secret-content sizes by probing. Raw payload visibility is opt-in via `gbrain serve --http --log-full-params` (loud stderr warning). Logging paths route through this helper, not `JSON.stringify(params)`. Agent contract v1: every failure (unknown tool, source guard, validation, strict params, missing source scope, handler throws) goes through `errorResult` → `toAgentError` → exactly one content block; handlers emit advice through `ctx.emitNotice` and the empty-retrieval, unknown-param and backup-coverage blocks ride that channel (prefixed `[gbrain notice <code> kind=<kind>]` blocks + `_meta.gbrain_notices`), filtered by the notice ledger (`opts.noticeLedger` on HTTP). `dispatchRenderContext` binds `isCallable` for fixes; `unknownToolEnvelope(name, opts, 'unknown_operation')` keeps serve-http's frozen value; `localCallErrorEnvelope` is `gbrain call`'s envelope. `sessionSafetyNotices` adds the one-time `behavior_changes` disclosure (stdio: once per brain; HTTP: once per authenticated client, remote view) and, on stdio only, the queued `chat_fallback_hop` notice, on success and failure results alike. `requestMetaSessionId(request.params)` is the one reader of the request-level `_meta.session_id` (beside `arguments`); stdio (`server.ts`) and HTTP (`serve-http-mcp.ts`) both pass it as `opts.sessionId`, which wins over an arguments-level `_meta` and is clamped to `SESSION_ID_MAX_CHARS` (256). Caches keyed on it stay bounded: the hot-memory cache at `HOT_MEMORY_CACHE_MAX_ENTRIES` (1000) and the facts queue's per-session counter, deleted at zero. `retrievalNoticeBlocks` also appends the rate line for a rateable answer (`_meta.retrieval.answer_id` with `feedback.rateable`): `Rate after use: rate_answer { answer_id, rating: 1-5 }`, or the fuller wording when `how_to_rate` fired, capped at `RATE_LINE_MAX_CHARS` = 160 (#6192; `test/mcp-feedback-visible-answer-id.test.ts`).
- `src/mcp/instructions.ts` — canonical MCP initialize-time agent operating contract, compile-time source text (no runtime filesystem dependency) shared by the stdio SDK server, the OAuth HTTP SDK server and the legacy raw HTTP initialize path. `buildMcpInstructions({writeback?, tools?})` GENERATES the contract from the caller's callable set (`tools.callable`, the tools/list predicate): a clause naming a tool (search/query/get_page, skills catalog, put_page, whoami, join/sync skills, put/delete skill, the memory loop's `context_pack`/`volunteer_context`/`remember`/`forget`) appears only when that tool is listed, so every tool named is in that surface's tools/list (`test/mcp-initialize-instructions.test.ts`). It always carries the error protocol (follow `fix.next`, then `fix.verify`) and the notice prefix, then the optional status-only line (F4), the opt-in ambient-writeback section (`src/core/facts/writeback-instructions.ts`) and the readiness tail (top two `missing`/`degraded` gaps among embeddings, chat_llm, migrations, worker — never a by-choice state). With no `tools` and no writeback it equals `GBRAIN_MCP_INSTRUCTIONS` (the every-tool rendering bootstrap writes to GBRAIN-INSTRUCTIONS.md). `resolveMcpInstructions(config, env?, opts)` appends the operator-set deployment identity LAST under `Deployment identity:` (`GBRAIN_MCP_INSTRUCTIONS` env when non-blank, else file-plane `mcp.instructions`). `installInstructionsResolver(server, compute)` swaps the SDK Server's initialize handler so the stdio and OAuth servers compute the contract (callable set + readiness tail via `src/mcp/initialize-context.ts`) when the client initializes; the constructor value stays the fallback on a throw. The legacy bearer transport builds it inline per initialize. Transport tests compare against the contract for that connection's own tools/list (`test/helpers/instructions-parity.ts`): `test/serve-stdio-roundtrip.test.ts`, `test/http-transport.test.ts`, `test/connect-bearer.test.ts`, `test/mcp-instructions-writeback.test.ts`; identity composition in `test/mcp-server-identity.test.ts` + `test/config-set-mcp-instructions.test.ts`. #6170: `contractClauses(c, writeback)` puts the short `Ambient writeback is ON (<mode>)` line (with `visibility "private"` under a private posture) in the memory clause when writeback is on, follows the data-not-instructions clause with the shortened error protocol and moves the forget caveat after the scope clause, so the writeback line, `Follow \`fix.next\``, `[gbrain notice`, `context_pack`, `put_page REPLACES` and `Writing:` end inside the first 2,048 characters on every surface (pinned per surface × mode × extract_facts × visibility in `test/mcp-initialize-instructions.test.ts`); the full writeback section stays appended last. Cat 40's measured "Answering from the brain" clause is verbatim; the change needs the D12 Cat 40 smoke before merge.
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 2aad413601..a553c1c844 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -220,10 +220,10 @@ import { v216 } from './v216-chronicle-campaign-stamps.ts';
import { v217 } from './v217-persistence-request-claim-phase.ts';
import { v218 } from './v218-purge-legacy-worktree-manifest-files.ts';
import { v219 } from './v219-pages-reconcile-name-indexes.ts';
-import { v230 } from './v230-trust-tiers.ts';
-import { v231 } from './v231-write-gate.ts';
-import { v232 } from './v232-memory-purge.ts';
-import { v234 } from './v234-trust-generation.ts';
+import { v220 } from './v220-trust-tiers.ts';
+import { v221 } from './v221-write-gate.ts';
+import { v222 } from './v222-memory-purge.ts';
+import { v224 } from './v224-trust-generation.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -442,8 +442,8 @@ export const MIGRATIONS: Migration[] = [
v217,
v218,
v219,
- v230,
- v231,
- v232,
- v234,
+ v220,
+ v221,
+ v222,
+ v224,
];
diff --git a/src/core/schema-migrations/v230-trust-tiers.ts b/src/core/schema-migrations/v220-trust-tiers.ts
similarity index 96%
rename from src/core/schema-migrations/v230-trust-tiers.ts
rename to src/core/schema-migrations/v220-trust-tiers.ts
index 057a219b15..80581f2500 100644
--- a/src/core/schema-migrations/v230-trust-tiers.ts
+++ b/src/core/schema-migrations/v220-trust-tiers.ts
@@ -17,8 +17,8 @@ import { MANAGED_WRITER_GUARD_FUNCTION_SQL } from '../persistence/writer-guard-s
// The managed-writer guard function is re-created (no table lock) so a page
// tier change is guarded content like the page body. No schema.sql mirror:
// like write attribution, these columns exist only through migrations.
-export const v230: Migration = {
- version: 230,
+export const v220: Migration = {
+ version: 220,
name: 'trust_tiers',
idempotent: true,
sql: `${TRUST_SCHEMA_SQL}
diff --git a/src/core/schema-migrations/v231-write-gate.ts b/src/core/schema-migrations/v221-write-gate.ts
similarity index 91%
rename from src/core/schema-migrations/v231-write-gate.ts
rename to src/core/schema-migrations/v221-write-gate.ts
index e0c5c5ff50..5002357cf1 100644
--- a/src/core/schema-migrations/v231-write-gate.ts
+++ b/src/core/schema-migrations/v221-write-gate.ts
@@ -7,8 +7,8 @@ import { WRITE_GATE_SCHEMA_SQL } from '../write-gate-schema.ts';
// #5575 blocking write gate: verdict receipts and the holding table for
// quarantined facts and takes (src/core/write-gate-store.ts). New empty
// tables, so their indexes build inline on both engines.
-export const v231: Migration = {
- version: 231,
+export const v221: Migration = {
+ version: 221,
name: 'write_gate',
idempotent: true,
sql: WRITE_GATE_SCHEMA_SQL,
diff --git a/src/core/schema-migrations/v232-memory-purge.ts b/src/core/schema-migrations/v222-memory-purge.ts
similarity index 94%
rename from src/core/schema-migrations/v232-memory-purge.ts
rename to src/core/schema-migrations/v222-memory-purge.ts
index 8aa2fcf02e..8625d5060b 100644
--- a/src/core/schema-migrations/v232-memory-purge.ts
+++ b/src/core/schema-migrations/v222-memory-purge.ts
@@ -9,8 +9,8 @@ import { MEMORY_PURGE_GUARD_SQL, MEMORY_PURGE_SCHEMA_SQL } from '../facts/purge-
// walks to hide derived rows (derivation_inputs, needs_rederive), and the
// guards that raise typed purged_content when purged content is written
// again. New empty tables, so their indexes build inline on both engines.
-export const v232: Migration = {
- version: 232,
+export const v222: Migration = {
+ version: 222,
name: 'memory_purge',
idempotent: true,
sql: MEMORY_PURGE_SCHEMA_SQL + MEMORY_PURGE_GUARD_SQL,
diff --git a/src/core/schema-migrations/v234-trust-generation.ts b/src/core/schema-migrations/v224-trust-generation.ts
similarity index 95%
rename from src/core/schema-migrations/v234-trust-generation.ts
rename to src/core/schema-migrations/v224-trust-generation.ts
index c8620df6c4..ceb6704566 100644
--- a/src/core/schema-migrations/v234-trust-generation.ts
+++ b/src/core/schema-migrations/v224-trust-generation.ts
@@ -12,8 +12,8 @@ import { TRUST_GENERATION_SCHEMA_SQL } from '../eligibility/generation-schema.ts
// key their caches on it. No schema.sql mirror: the triggers read columns
// that exist only through the trust tiers migration, so a fresh install
// replays this migration like that one.
-export const v234: Migration = {
- version: 234,
+export const v224: Migration = {
+ version: 224,
name: 'trust_generation',
idempotent: true,
sql: TRUST_GENERATION_SCHEMA_SQL,
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 68d7cea1aa..64d4e64786 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -6,17 +6,7 @@
18,
19,
100,
- 220,
- 221,
- 222,
- 223,
- 224,
- 225,
- 226,
- 227,
- 228,
- 229,
- 233
+ 223
],
"helpers": {
"ALIAS_TABLES": "cddd37c636af42d862c08ca7754a57dfe9d12576b769fa8f74a5f02c803f67a0",
@@ -47,7 +37,7 @@
"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5",
"verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"
},
- "latest": 234,
+ "latest": 224,
"records": [
{
"handler": {
@@ -3277,7 +3267,7 @@
"sqlFor": "absent",
"transaction": "absent",
"verify": "absent",
- "version": 230
+ "version": 220
},
{
"handler": "absent",
@@ -3290,7 +3280,7 @@
"sqlFor": "absent",
"transaction": "absent",
"verify": "absent",
- "version": 231
+ "version": 221
},
{
"handler": "absent",
@@ -3303,7 +3293,7 @@
"sqlFor": "absent",
"transaction": "absent",
"verify": "absent",
- "version": 232
+ "version": 222
},
{
"handler": "absent",
@@ -3316,7 +3306,7 @@
"sqlFor": "absent",
"transaction": "absent",
"verify": "absent",
- "version": 234
+ "version": 224
}
],
"versions": [
@@ -3534,10 +3524,10 @@
217,
218,
219,
- 230,
- 231,
- 232,
- 234
+ 220,
+ 221,
+ 222,
+ 224
]
},
"normalizer": "migrations-record-v1"