Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
d5b: served brief clause names only the fields entity names rows carry
garrytana1134c13f1ed
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f87d752f54..b0d838c873 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,10 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [Unreleased: cat40 next wave part 1, version stamped at merge] - 2026-10-12++- **Served instructions (d5b): the brief clause no longer recommends a `referenced_by` walk batch mode cannot do.** `src/mcp/instructions.ts`: the walk is on the single-name `entity` card, and the clause names what a compact `entity names` row carries on this brain (its `next` to the card while `entity.names_references` is on, the default; `records` by type once `entity.record_types` enrolls page types, empty by default). Every transport reads both keys at initialize through `readInstructionContent` (fail-closed to the defaults); the static contract, bootstrap's instructions file and the SDK constructor fallback are the defaults rendering. One reader module, `src/core/entity-references-config.ts`, serves both keys. Budget: +70 characters for the maximal rendering (+39 at the default), recorded in `test/mcp-schema-budget.test.ts` and `test/mcp-initialize-instructions.test.ts`. Tests: `test/mcp-instructions-references.test.ts`.+## [0.60.180.0] - 2026-10-12**When `remember` refuses a forgotten claim, the refusal now says when and how widely it was forgotten.** An agent that re-saves a claim the user forgot gets `fact_withdrawn` as before, and the refusal now carries `withdrawn: { at, subject, visibility }`, where `subject` is the entity the claim was forgotten for or `all_entities`. The agent can tell the user "you asked me to forget that on <date>" instead of retrying. The object rides the immediate refusal, the batch item error, the failed write receipt and `get_write_request`. It covers the exact claim only, the message, code and suggestion are unchanged, and nothing is ever restored.diff --git a/docs/architecture/key-files/core-services-3.md b/docs/architecture/key-files/core-services-3.mdindex c67094fa0e..1f34f6dc1d 100644--- a/docs/architecture/key-files/core-services-3.md+++ b/docs/architecture/key-files/core-services-3.md@@ -17,6 +17,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/verbs/conformance.ts` + `src/core/verbs/conformance-fixtures.ts` — the conformance runner core (transport-agnostic: minimal `ConformanceClient` = list_tools + call_tool) and the embedded fixture set. Deterministic by construction: shape/enum/behavior/round-trip checks only, never ranking quality. Validation is NON-STRICT on extra fields (additive-forever means unknown fields are always legal). Entity-card cases seed via put_page when the target exposes it and skip honestly on verbs-only targets; synthesize is cost-gated behind --synthesize. `validateAgainstSchema` is a minimal JSON-Schema-subset validator (type unions, required, properties, enum, const, items). Fixtures mirror to `test/fixtures/memory-verbs/cases.json` (BrainBench seeds; drift-guarded by the conformance test). The negative self-test (test/memory-verbs-conformance.test.ts) proves the runner FAILS a lying server.+- `src/core/entity-references-config.ts` — the one reader for `entity.names_references` (default on: found `names` rows and siblings carry `referenced_by_count` and a row-level `next` to the card) and `entity.record_types` (comma-separated canonical page types, default empty: no `records`). `readEntityReferencesConfig(engine)` fails closed to `{namesRow: true, recordTypes: []}`; the names verb and the MCP instruction builder (`readInstructionContent`) both read it. Test: `test/mcp-instructions-references.test.ts`.- `src/core/verbs/entity-card.ts` — `buildEntityCard(engine, sourceId, name, {remote})`: the zero-LLM sub-100ms card behind the `entity` verb. Resolution reuses the Retrieval Reflex precision arms (alias > exact slug > exact title > slug-suffix; exact-slug candidates include the RAW input because slugify flattens slashes in namespaced slugs). Within exact-title collisions, linkable entity types (the source pack's set, `mentions/policy.ts`) outrank note/conversation containers, then GREATEST(updated_at, last_retrieved_at) breaks same-shape ties; a lone non-entity exact-title page remains a valid fallback. Per-arm degradation: a pre-page_aliases brain still resolves via arm 2 (aka returns empty, never throws). Card assembly is a parallel Promise.all of depth-1 indexed reads (page row, alias reverse lookup, getLinks+getBacklinks mentions-excluded cap 10, getBacklinkCounts, getTimeline(5), listFactsByEntity world-only-when-remote); deliberately NOT the recursive-CTE traversePaths — the card is a latency contract (CI gate: test/entity-card-perf.slow.test.ts, p99 < 100ms × GBRAIN_TEST_PERF_BUDGET_MULTIPLIER + 50× getPage-p50 ratio guard on a 20K corpus). `summary` runs through the exported `safeSynopsis` (the get_page fence boundary). Miss → keyword near-miss suggestions with create_safety hints. `context_pack` cards add `newer_mentions` (next entry). With `includeReferences` (the `entity` verb only; context_pack and delta leave it off) the card adds `referenced_by_count`, `referenced_by` groups with `next` continuations (`requires_surface: 'starter'` on a verbs ceiling) and `coverage`, and a miss carries `coverage` (see [entity recall](entity-recall.md)).- `src/core/mentions/newer-mentions.ts` — `readNewerMentions(engine, sourceId, slug, {excludePrivate, keepVisibility, charBudget, eligibility, includeQuarantined})`: the entity page's `COALESCE(effective_date, updated_at)`, then `readReferrerPage` (limit `NEWER_MENTIONS_CAP` 8, the card's own source, its private-page and private-origin filters) cut to referrers dated after it, newest first, within `NEWER_MENTIONS_CARD_CHARS` (2,000) of rendered rows; `more` when further newer referrers exist; null when none or on any read failure. #5575: the pack passes its proactive eligibility and authorized `include_quarantined`; `renderNewerMentionRow` labels each preview with its page's trust fields (`renderTrustedInline`; a quarantined one as external data). `isNewerMentionsEnabled` reads `mentions.newer_on_cards` (unset = on). `assemblePack` (`src/core/context/turn-context.ts`) reads them after cards and hot facts under the pack deadline and `NEWER_MENTIONS_PACK_CHARS` (6,000), `renderPack` puts them in a section after hot memory, and the `context_pack` op packs them last under `budget_tokens`. Test: `test/context-pack-newer-mentions.test.ts`.diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.mdindex f2f910a7ad..7754974314 100644--- a/docs/architecture/key-files/mcp.md+++ b/docs/architecture/key-files/mcp.md@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/mcp/dispatch.ts` — shared tool-call dispatch consumed by both stdio (`server.ts`) and HTTP transports. Exports `dispatchToolCall(engine, name, params, opts)`, `buildOperationContext(engine, params, opts)`, and re-exports `normalizeOptionalParams`/`validateParams` from `src/mcp/validate-params.ts` (the validation module — call order normalize → validate → findUnknownParams is load-bearing). Single source of truth for `(ctx, params)` handler arg order and the `OperationContext` shape. Defaults `remote: true` (untrusted); local CLI callers pass `remote: false`. Deny layers, in order: `opts.allowedOps` surface enforcement (hidden op → `unknownToolEnvelope`, byte-identical to a nonexistent op; did-you-mean candidates drawn ONLY from the caller's visible surface minus localOnly minus gated names), unknown op, the localOnly transport backstop (`op.localOnly && transport !== 'stdio'` → same envelope; stdio IS the local surface), param validation, strict/warn unknown-arg handling (reject mode returns `invalid_params` with suggestions; warn mode attaches `_meta.warnings` + a model-visible notice block), then `enforceBoundClientOpAllowList` (the bound-client fence) inside the handler try. `_meta` assembly per docs/protocol/MCP_META_CHANNELS.md: handler-emitted keys via `ctx.emitResponseMeta` (retrieval, warnings) attach first and independently of the `metaHook` (`brain_hot_memory`, built by `src/core/facts/meta-hook.ts` — its 30s cache is keyed by ENGINE IDENTITY + source + visibility tier + session + allow-list hash, so a process hosting multiple engines can never serve one brain's cached facts into another's envelope; each entry's deadline is additionally CLAMPED to the earliest retained `valid_until`, so a fact expiring inside the window never outlives its read-time TTL by cache staleness; every mutating op, successful or not, drops the engine's entries via `invalidateHotMemoryForEngine`, a build that raced it is not stored, 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 v230: 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`). When callable tools are left out of the listed set (`hiddenCallable`) and `request_tools` is callable, the hidden-tool sentence leads the contract, inside the 2,048 characters capped harnesses read (D1). It always carries the error protocol (follow `fix.next`, then `fix.verify`) and the notice prefix, then the optional status-only line (F4), the opt-in ambient-writeback section (`src/core/facts/writeback-instructions.ts`) and the readiness tail (top two `missing`/`degraded` gaps among embeddings, chat_llm, migrations, worker — never a by-choice state). With no `tools` and no writeback it equals `GBRAIN_MCP_INSTRUCTIONS` (the every-tool rendering bootstrap writes to GBRAIN-INSTRUCTIONS.md). `resolveMcpInstructions(config, env?, opts)` appends the operator-set deployment identity LAST under `Deployment identity:` (`GBRAIN_MCP_INSTRUCTIONS` env when non-blank, else file-plane `mcp.instructions`). `installInstructionsResolver(server, compute)` swaps the SDK Server's initialize handler so the stdio and OAuth servers compute the contract (callable set + readiness tail via `src/mcp/initialize-context.ts`) when the client initializes; the constructor value stays the fallback on a throw. The legacy bearer transport builds it inline per initialize. Transport tests compare against the contract for that connection's own tools/list (`test/helpers/instructions-parity.ts`): `test/serve-stdio-roundtrip.test.ts`, `test/http-transport.test.ts`, `test/connect-bearer.test.ts`, `test/mcp-instructions-writeback.test.ts`; identity composition in `test/mcp-server-identity.test.ts` + `test/config-set-mcp-instructions.test.ts`. #6170: `contractClauses(c, writeback)` puts the short `Ambient writeback is ON (<mode>)` line (with `visibility "private"` under a private posture) in the memory clause when writeback is on, follows the data-not-instructions clause with the shortened error protocol and moves the forget caveat after the scope clause, so the writeback line, `Follow \`fix.next\``, `[gbrain notice`, `context_pack`, `put_page REPLACES` and `Writing:` end inside the first 2,048 characters on every surface (pinned per surface × mode × extract_facts × visibility in `test/mcp-initialize-instructions.test.ts`); the full writeback section stays appended last. Cat 40's measured "Answering from the brain" clause is verbatim; the change needs the D12 Cat 40 smoke before merge.+- `src/mcp/instructions.ts` — canonical MCP initialize-time agent operating contract, compile-time source text (no runtime filesystem dependency) shared by the stdio SDK server, the OAuth HTTP SDK server and the legacy raw HTTP initialize path. `buildMcpInstructions({writeback?, tools?})` GENERATES the contract from the caller's callable set (`tools.callable`, the tools/list predicate): a clause naming a tool (search/query/get_page, skills catalog, put_page, whoami, join/sync skills, put/delete skill, the memory loop's `context_pack`/`volunteer_context`/`remember`/`forget`) appears only when that tool is listed, so every tool named is in that surface's tools/list (`test/mcp-initialize-instructions.test.ts`). When callable tools are left out of the listed set (`hiddenCallable`) and `request_tools` is callable, the hidden-tool sentence leads the contract, inside the 2,048 characters capped harnesses read (D1). It always carries the error protocol (follow `fix.next`, then `fix.verify`) and the notice prefix, then the optional status-only line (F4), the opt-in ambient-writeback section (`src/core/facts/writeback-instructions.ts`) and the readiness tail (top two `missing`/`degraded` gaps among embeddings, chat_llm, migrations, worker — never a by-choice state). With no `tools` and no writeback it equals `GBRAIN_MCP_INSTRUCTIONS` (the every-tool rendering bootstrap writes to GBRAIN-INSTRUCTIONS.md). `resolveMcpInstructions(config, env?, opts)` appends the operator-set deployment identity LAST under `Deployment identity:` (`GBRAIN_MCP_INSTRUCTIONS` env when non-blank, else file-plane `mcp.instructions`). `installInstructionsResolver(server, compute)` swaps the SDK Server's initialize handler so the stdio and OAuth servers compute the contract (callable set + readiness tail via `src/mcp/initialize-context.ts`) when the client initializes; the constructor value stays the fallback on a throw. The legacy bearer transport builds it inline per initialize. Transport tests compare against the contract for that connection's own tools/list (`test/helpers/instructions-parity.ts`): `test/serve-stdio-roundtrip.test.ts`, `test/http-transport.test.ts`, `test/connect-bearer.test.ts`, `test/mcp-instructions-writeback.test.ts`; identity composition in `test/mcp-server-identity.test.ts` + `test/config-set-mcp-instructions.test.ts`. #6170: `contractClauses(c, writeback)` puts the short `Ambient writeback is ON (<mode>)` line (with `visibility "private"` under a private posture) in the memory clause when writeback is on, follows the data-not-instructions clause with the shortened error protocol and moves the forget caveat after the scope clause, so the writeback line, `Follow \`fix.next\``, `[gbrain notice`, `context_pack`, `put_page REPLACES` and `Writing:` end inside the first 2,048 characters on every surface (pinned per surface × mode × extract_facts × visibility in `test/mcp-initialize-instructions.test.ts`); the full writeback section stays appended last. Cat 40's measured "Answering from the brain" clause is verbatim; the change needs the D12 Cat 40 smoke before merge. The brief clause puts the `referenced_by` walk on the single-name `entity` card and names only the fields compact `names` rows carry on the brain (`references: {namesRow, records}`, read at every per-initialize call site by `readInstructionContent` from `src/core/entity-references-config.ts`; the static contract is the defaults rendering; `test/mcp-instructions-references.test.ts`).- `src/mcp/publish-gates.ts` — publish-gate resolution for the honest tools/list. `readPublishGate(engine, config, key)`: dual-plane (DB > file > false), never throws — a FAILED read resolves false (hide-on-doubt matches the default-off consent posture). `disabledOpsForPublishGates(engine, config)`: the op-name set tools/list subtracts; one getConfig read per distinct gate key per call, deliberately NOT memoized so `gbrain config set mcp.publish_skills true` takes effect on the next list without a restart. Call-time gates inside the handlers stay as the fail-closed backstop (their denials carry `detail: 'config_key=<key>'` — the machine-readable denial grammar). Pinned by test/publish-gates.test.ts. `PUBLISH_GATE_KEYS` (every operation's gate key) is the set `gbrain config get` resolves DB-first, matching this resolver (`test/config-get-plane.test.ts`).diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.tsindex 9bc8228d4c..81fedc4427 100644--- a/src/commands/serve-http-mcp.ts+++ b/src/commands/serve-http-mcp.ts@@ -14,7 +14,7 @@ import { opAllowedForBoundClient } from '../core/operations.ts';import { authTransport } from '../core/ops/contract.ts';import type { AuthInfo, Operation } from '../core/operations.ts';import { disabledOpsForPublishGates } from '../mcp/publish-gates.ts';-import { installInstructionsResolver, resolveMcpInstructions } from '../mcp/instructions.ts';+import { installInstructionsResolver, readInstructionContent, resolveMcpInstructions } from '../mcp/instructions.ts';import { httpInstructionTools } from '../mcp/initialize-context.ts';import { installCapabilitiesResource, mcpAdministrationGuidance } from '../mcp/capabilities.ts';import { createSkillResources } from '../mcp/skill-resources.ts';@@ -200,6 +200,7 @@ function createMcpRequestServer(installInstructionsResolver(server, async () => resolveMcpInstructions(config, process.env, {writeback: writebackOpts,tools: await httpInstructionTools(engine, config, { ops: mcpOperations, surface, auth: authInfo, allowedOps: surfaceAllowedOps, cache: ctx.readinessCache }),+ ...await readInstructionContent(engine),}));installCapabilitiesResource(server, async () => {return { transport: authTransport(authInfo), client_id: authInfo.clientId,diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex bc34ae7ce0..f5589a6d73 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -469,6 +469,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }// Cat 40 next wave, Part 3 step 1. `since` is provisional; the integrator restamps it at the merge slot.{ since: '0.60.180.0', text: 'A `remember` refused with `fact_withdrawn` now carries an additive `withdrawn` object (`at`, `subject`: the entity slug or `all_entities`, `visibility`) on the immediate refusal, the batch item error, the failed write receipt and `get_write_request`, so an agent can tell the user when and how widely the exact claim was forgotten instead of retrying. The message, code and suggestion are unchanged; the object is absent when the caller cannot read the forgotten rows.' },{ since: '0.60.177.0', text: 'A brain whose persistence mode cannot be read (no `persistence_brain` row, more than one, or an `enabled` value that is not a boolean) now refuses every write, sync, connector run, activation and maintenance step that depends on it with `storage_error` (`detail: persistence_mode_unknown`, fix: `gbrain sources writer status --probe --json`) instead of treating the brain as unmanaged and writing around the owner; only a well-formed `enabled: false` row selects the unmanaged path. A managed `gbrain sync --full` tree walk no longer soft-deletes a page it imported from an untracked working-tree file: a page whose stored import provenance is the working tree, or is unknown, is kept while its file is still present (`working_tree_kept` in the result), and a page imported from a Git blob still follows Git. A soft deletion is not harmless (recall stops at once and the purge lifecycle follows), so this applies on the next sync without opt-in. A first sync, a `--full` sync or one commit that alone exceeds the 100,000-entry / 16 MiB cursor bound now completes in path slices (every import slice, then bounded deletion slices, pinned at one target; the slice cursor is checkpointed with each slice and `last_commit` moves only when the whole target settles) instead of refusing with `request_too_large`; a scheduled sync takes one slice per run and `gbrain sync --drain` takes them all. One file whose manifest entry alone exceeds the byte bound still refuses by name.' },+ // Cat 40 next wave, Part 1. `since` is provisional; the integrator restamps it at the merge slot.+ { since: '0.60.181.0', text: 'The MCP instructions no longer tell agents to walk `referenced_by` after an `entity` `names` batch, whose rows carry no references: the brief clause now puts that walk on the single-name card and says what a `names` row holds on this brain (its `next` to the card, and `records` by type once `entity.record_types` names page types). `gbrain config set entity.names_references false` drops the names-row fields and that part of the clause.' },{ since: '0.60.179.0', text: 'A managed sync no longer parks forever on a pinned import whose canonical correction (a fixable fence, reflowed frontmatter) would rewrite a file that holds newer uncommitted bytes: the file is held `worktree_dirty` with the rest of the source synced, the cursor finishes, and committing the file (or `gbrain sync unblock --source <id> --apply`) imports it. Before, that refusal (`source_changed` / `pinned_git_worktree_conflict`, "Canonical sanitization cannot overwrite newer working-tree bytes.") blocked the cursor with no exit: `--retry-failed` replayed the same pin, `sources refresh` refused `sync_in_progress` and `--acknowledge-managed` refused `cursor_unfinished`. A cursor an older release left blocked this way converts on its next `--retry-failed` run. Working-tree bytes that already are the correction (gbrain\'s own writeback, published before its request settled) import without a second write.' },];diff --git a/src/core/config.ts b/src/core/config.tsindex 32ff08c483..9152cd178e 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1619,6 +1619,11 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['mcp.strict_params','mcp.result_rows', // C1 row shape, read dual-plane by src/mcp/result-rows.ts'mcp.allow_session_widen', // stdio request_tools session widening (default on), read dual-plane by src/mcp/surface.ts+ // Entity references on compact `entity names` rows (src/core/entity-references-config.ts, read by the names verb and+ // the MCP instruction builder): referenced_by_count + a row-level `next` to the card (default on), and the canonical+ // page types listed as `records` (comma-separated, default empty: no records).+ 'entity.names_references',+ 'entity.record_types',// Skill-nag suppression (#2180): brain-resident pack install nag off-switch.'skillpack.nag_disabled',// Self-upgrade (v0.42; file plane, read on the hot path)diff --git a/src/core/entity-references-config.ts b/src/core/entity-references-config.tsnew file mode 100644index 0000000000..ceb93b3fcb--- /dev/null+++ b/src/core/entity-references-config.ts@@ -0,0 +1,45 @@+/**+ * Entity references on compact `entity names` rows and record-type+ * enrollment: the one reader for both keys, shared by the names-mode verb and+ * the MCP instruction builder, so the served brief clause names only fields+ * the agent actually receives.+ *+ * - `entity.names_references` (boolean, default on): every found `names` row+ * (and each identity sibling) carries `referenced_by_count` and a row-level+ * `next` to the full card (`{tool: 'entity', arguments: {name}}`).+ * - `entity.record_types` (comma-separated canonical page types, default+ * empty): the page types whose referring pages are listed as `records` on+ * `names` rows. Empty means no records.+ *+ * Fail-closed: a read error yields the defaults (names rows on, no records),+ * never a field the agent would not receive.+ */++export const ENTITY_NAMES_REFERENCES_KEY = 'entity.names_references';+export const ENTITY_RECORD_TYPES_KEY = 'entity.record_types';++export interface EntityReferencesConfig {+ namesRow: boolean;+ recordTypes: string[];+}++const OFF_VALUES: ReadonlySet<string> = new Set(['false', 'off', '0', 'no']);++/** Off only for an explicit falsy value; unset or anything else keeps the default (on). */+export function parseNamesReferences(raw: string | null | undefined): boolean {+ return !OFF_VALUES.has((raw ?? '').trim().toLowerCase());+}++/** Comma-separated page types: trimmed, empty entries dropped, first occurrence kept, case preserved. */+export function parseRecordTypes(raw: string | null | undefined): string[] {+ return [...new Set((raw ?? '').split(',').map(t => t.trim()).filter(t => t.length > 0))];+}++export async function readEntityReferencesConfig(engine: { getConfig(key: string): Promise<string | null> }): Promise<EntityReferencesConfig> {+ try {+ const [names, types] = await Promise.all([engine.getConfig(ENTITY_NAMES_REFERENCES_KEY), engine.getConfig(ENTITY_RECORD_TYPES_KEY)]);+ return { namesRow: parseNamesReferences(names), recordTypes: parseRecordTypes(types) };+ } catch {+ return { namesRow: true, recordTypes: [] };+ }+}diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.tsindex 0057903ad0..7a20988518 100644--- a/src/mcp/http-transport.ts+++ b/src/mcp/http-transport.ts@@ -32,7 +32,7 @@ import { CAPABILITIES_URI } from './capabilities.ts';import { resolveAuthCapabilities } from '../core/harness/capabilities.ts';import type { BrainEngine } from '../core/engine.ts';import { buildToolDefs } from './tool-defs.ts';-import { resolveMcpInstructions } from './instructions.ts';+import { readInstructionContent, resolveMcpInstructions } from './instructions.ts';import { httpInstructionTools } from './initialize-context.ts';import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writeback-config.ts';import { operations, operationsByName, opAllowedForBoundClient } from '../core/operations.ts';@@ -448,6 +448,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {instructions: resolveMcpInstructions(fileConfig, process.env, {writeback: ambientOptsFrom(writeback, { remember: canWriteOp('remember'), extractFacts: canWriteOp('extract_facts') }),tools: await httpInstructionTools(engine, fileConfig, { ops: surfacedOps, surface, auth: auth.auth!, allowedOps: surfaceAllowedOps }), // F1+ ...await readInstructionContent(engine),}),},jsonrpc: '2.0',diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.tsindex e5ad127c81..61d034f8c2 100644--- a/src/mcp/instructions.ts+++ b/src/mcp/instructions.ts@@ -21,6 +21,7 @@ import type { GBrainConfig } from '../core/config.ts';import type { ReadinessEntry } from '../core/readiness.ts';import { buildAmbientWritebackSection } from '../core/facts/writeback-instructions.ts';import type { AmbientWritebackOpts } from '../core/facts/writeback-instructions.ts';+import { readEntityReferencesConfig } from '../core/entity-references-config.ts';/** Which tools this connection can call (the tools/list predicate). */export type CallablePredicate = (toolName: string) => boolean;@@ -35,9 +36,29 @@ export interface InstructionTools {hiddenCallable?: number;}+/**+ * Which reference fields compact `entity names` rows carry on this brain+ * (`entity.names_references`, `entity.record_types`), so the brief clause+ * names only fields the agent receives. Absent: the defaults (names-row+ * references on, no records).+ */+export interface InstructionReferences { namesRow: boolean; records: boolean }++/** The served-text options that follow brain config; every call site reads them with readInstructionContent. */+export interface InstructionContent {+ references?: InstructionReferences;+}++/** Brain config behind InstructionContent. Fail-closed: a read error yields the defaults. */+export async function readInstructionContent(engine: { getConfig(key: string): Promise<string | null> }): Promise<InstructionContent> {+ const refs = await readEntityReferencesConfig(engine);+ return { references: { namesRow: refs.namesRow, records: refs.recordTypes.length > 0 } };+}+const ALL: CallablePredicate = () => true;+const DEFAULT_REFERENCES: InstructionReferences = { namesRow: true, records: false };-function contractClauses(c: CallablePredicate, writeback?: AmbientWritebackOpts | null): string[] {+function contractClauses(c: CallablePredicate, writeback?: AmbientWritebackOpts | null, content?: InstructionContent): string[] {const out: string[] = [];const any = (...names: string[]) => names.some(c);if (any('search', 'query')) {@@ -65,8 +86,11 @@ function contractClauses(c: CallablePredicate, writeback?: AmbientWritebackOptsconst batch = c('put_pages');out.push(`Writing:${batch ? ' for more than 3 pages use put_pages (one request_id per batch, about 5-8 large pages per call).' : ''} Pass wait_ms (e.g. 25000) instead of polling; if still pending, ${batch ? 'follow the reply\'s `next`' : 'replay with the same request_id'} no sooner than retry_after_ms.`);}- // Entity recall: a brief starts from the entity card's referrers, wherever `entity` is served.- const brief = c('entity') ? `For a brief on an account, person or company, call \`entity\`, then walk \`referenced_by\`${c('get_backlinks') ? ' or `get_backlinks`' : ''} by type.` : null;+ // Entity recall: a brief starts from the single-name card's referrers, wherever `entity` is served; a `names` row+ // carries no `referenced_by`, so the clause names only the fields those rows carry on this brain.+ const refs = content?.references ?? DEFAULT_REFERENCES;+ const namesRow = refs.records ? `; a \`names\` row lists \`records\` by type${refs.namesRow ? ', and its `next` opens the card' : ''}` : refs.namesRow ? '; a `names` row\'s `next` opens the card' : '';+ const brief = c('entity') ? `For a brief on an account, person or company, walk the \`entity\` card's \`referenced_by\`${c('get_backlinks') ? ' or `get_backlinks`' : ''} by type${namesRow}.` : null;if (brief && !any('search', 'query')) out.push(brief);if (any('search', 'query')) {// Cat 40 (#5932): measured answer-completeness guidance. Cat 40 Hard round 4: separate parts stay separate,@@ -109,9 +133,9 @@ function readinessTail(entries: readonly ReadinessEntry[], callable: (op: string* tail. With no `tools` and no writeback the output is byte-identical to* `GBRAIN_MCP_INSTRUCTIONS`.*/-export function buildMcpInstructions(opts?: { writeback?: AmbientWritebackOpts | null; tools?: InstructionTools }): string {+export function buildMcpInstructions(opts?: { writeback?: AmbientWritebackOpts | null; tools?: InstructionTools } & InstructionContent): string {const tools = opts?.tools;- const clauses = contractClauses(tools?.callable ?? ALL, opts?.writeback);+ const clauses = contractClauses(tools?.callable ?? ALL, opts?.writeback, opts);// D1: capped harnesses read the first 2,048 characters, so the hidden-tool sentence leads the contract.const hidden = tools?.hiddenCallable && tools.callable('request_tools')? `The tool list shows the everyday tools; ${tools.hiddenCallable} more are callable. Call request_tools with no arguments to list them, or with tools: [names] for their schemas, then call them directly.\n`@@ -140,7 +164,7 @@ type Env = Record<string, string | undefined>;export function resolveMcpInstructions(config: Pick<GBrainConfig, 'mcp'> | null | undefined,env: Env = process.env,- opts?: { writeback?: AmbientWritebackOpts | null; tools?: InstructionTools },+ opts?: { writeback?: AmbientWritebackOpts | null; tools?: InstructionTools } & InstructionContent,): string {const base = buildMcpInstructions(opts);// An empty / whitespace-only env value is UNSET, not an override: with `??`diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex 2d7e9ce9ca..6587632c27 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -16,7 +16,7 @@ import { disabledOpsForPublishGates } from './publish-gates.ts';import { parseResultRowsMode, resolveResultRowsMode } from './result-rows.ts';import { loadConfig } from '../core/config.ts';import { gcSessionContextState } from '../core/context/session-state.ts';-import { installInstructionsResolver, resolveMcpInstructions } from './instructions.ts';+import { installInstructionsResolver, readInstructionContent, 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';@@ -362,6 +362,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpSreturn resolveMcpInstructions(config, process.env, {writeback: writebackOpts,tools: { callable: n => visible.has(n), readiness: await instructionReadiness(engine, config, 'stdio'), hiddenCallable: visibleOps.length - (await listing.listed(visibleOps)).length },+ ...await readInstructionContent(engine),});}, gate.initializeAnswered);diff --git a/test/mcp-initialize-instructions.test.ts b/test/mcp-initialize-instructions.test.tsindex 12af80746c..633a4920cb 100644--- a/test/mcp-initialize-instructions.test.ts+++ b/test/mcp-initialize-instructions.test.ts@@ -44,7 +44,12 @@ const WRITING_CLAUSE_BYTES = 240;* gbrain-evals#93 (round 4, pooled +4.9 points over fs).*/const BATCHING_CLAUSE_BYTES = 200;-const LANE_I_CEILING = Math.floor(PRE_F1_BYTES * 1.15) + WRITING_CLAUSE_BYTES + BATCHING_CLAUSE_BYTES;+/**+ * d5b (Cat 40 next wave): the brief clause says the walk is on the single-name card and names the fields compact+ * `entity names` rows carry on this brain (`next`, and `records` when record types are enrolled); 70 bytes at most.+ */+const NAMES_ROW_REFERENCES_BYTES = 70;+const LANE_I_CEILING = Math.floor(PRE_F1_BYTES * 1.15) + WRITING_CLAUSE_BYTES + BATCHING_CLAUSE_BYTES + NAMES_ROW_REFERENCES_BYTES;/** Claude Code reads only the first 2,048 characters of a server's initialize instructions. */const HARNESS_READ_LIMIT = 2_048;@@ -75,12 +80,14 @@ describe('F1 generated instructions', () => {});test('entity recall brief: on every surface serving entity; get_backlinks named only where callable', () => {- const brief = 'For a brief on an account, person or company, call `entity`, then walk `referenced_by`';+ // d5b: the walk is on the single-name card; a `names` row carries no `referenced_by`.+ const brief = "For a brief on an account, person or company, walk the `entity` card's `referenced_by`";for (const surface of SURFACES) {const listed = new Set(filterOpsForSurface(operations, surface).map(o => o.name));const text = buildMcpInstructions({ tools: { callable: n => listed.has(n) } });expect({ surface, brief: text.includes(brief) }).toEqual({ surface, brief: listed.has('entity') });- expect({ surface, backlinks: text.includes('or `get_backlinks` by type.') }).toEqual({ surface, backlinks: listed.has('entity') && listed.has('get_backlinks') });+ expect(text).not.toContain('call `entity`, then walk');+ expect({ surface, backlinks: text.includes('or `get_backlinks` by type') }).toEqual({ surface, backlinks: listed.has('entity') && listed.has('get_backlinks') });expect(text).not.toContain('appear under several names');}const noEntity = buildMcpInstructions({ tools: { callable: n => n !== 'entity' } });@@ -92,11 +99,16 @@ describe('F1 generated instructions', () => {// #6007: starter +140 and full +230 for the write guidance (wait_ms; put_pages where it is served), within WRITING_CLAUSE_BYTES.// #6170: the error clause was shortened and the forget caveat moved; every surface shrank (2_243 / 4_686 / 4_837 before).// Cat 40 Hard round 4: instruction 7's batching clause (BATCHING_CLAUSE_BYTES); starter 4_630 -> 4_824 and full 4_781 -> 4_975.- const recorded = { verbs: 2_186, starter: 4_824, full: 4_975 };+ // d5b: the brief names the fields compact `entity names` rows carry (NAMES_ROW_REFERENCES_BYTES): +39 at the default+ // (names-row references on, no records) on every surface serving entity; +70 with records enrolled (maximal).+ const recorded = { verbs: 2_225, starter: 4_863, full: 5_014 };+ const maximal = { verbs: 2_256, starter: 4_894, full: 5_045 };for (const surface of SURFACES) {const listed = new Set(filterOpsForSurface(operations, surface).map(o => o.name));const size = buildMcpInstructions({ tools: { callable: n => listed.has(n) } }).length;expect({ surface, fits: size <= recorded[surface] }).toEqual({ surface, fits: true });+ const max = buildMcpInstructions({ tools: { callable: n => listed.has(n) }, references: { namesRow: true, records: true } }).length;+ expect({ surface, fits: max <= maximal[surface] }).toEqual({ surface, fits: true });}});@@ -121,6 +133,7 @@ describe('F1 generated instructions', () => {test(`${surface}: tail-free contract stays within +15% of the pre-F1 contract`, () => {const listed = new Set(filterOpsForSurface(operations, surface).map(o => o.name));expect(Buffer.byteLength(buildMcpInstructions({ tools: { callable: n => listed.has(n) } }))).toBeLessThanOrEqual(LANE_I_CEILING);+ expect(Buffer.byteLength(buildMcpInstructions({ tools: { callable: n => listed.has(n) }, references: { namesRow: true, records: true } }))).toBeLessThanOrEqual(LANE_I_CEILING);});}diff --git a/test/mcp-instructions-references.test.ts b/test/mcp-instructions-references.test.tsnew file mode 100644index 0000000000..9b58042b0f--- /dev/null+++ b/test/mcp-instructions-references.test.ts@@ -0,0 +1,105 @@+/**+ * d5b: the served brief clause names only the reference fields the agent+ * receives. A compact `entity names` row carries no `referenced_by`, so the+ * clause puts the walk on the single-name card and says what a `names` row+ * holds on this brain: a row-level `next` to the card when+ * `entity.names_references` is on (default), `records` by type when+ * `entity.record_types` enrolls types (default none). Every transport reads+ * both keys through readInstructionContent; the static contract+ * (GBRAIN_MCP_INSTRUCTIONS, bootstrap's instructions file, the SDK+ * constructor fallback) is the defaults rendering.+ *+ * Protects: instruction 7 advised "call `entity`, then walk `referenced_by`"+ * while agents batched names with `entity` `names`, whose rows carried no+ * references.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { operations } from '../src/core/operations.ts';+import { filterOpsForSurface } from '../src/mcp/surface.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { buildMcpInstructions, GBRAIN_MCP_INSTRUCTIONS, readInstructionContent } from '../src/mcp/instructions.ts';+import {+ ENTITY_NAMES_REFERENCES_KEY, ENTITY_RECORD_TYPES_KEY, parseNamesReferences, parseRecordTypes, readEntityReferencesConfig,+} from '../src/core/entity-references-config.ts';++const SURFACES = ['verbs', 'starter', 'full'] as const;+const CARD = "walk the `entity` card's `referenced_by`";+const NEXT = "`next` opens the card";+const RECORDS = 'lists `records` by type';+const briefLine = (text: string) => text.split('\n').find(l => l.includes('For a brief on an account')) ?? '';+const render = (surface: typeof SURFACES[number], references?: { namesRow: boolean; records: boolean }) => {+ const listed = new Set(filterOpsForSurface(operations, surface).map(o => o.name));+ return { listed, text: buildMcpInstructions({ tools: { callable: n => listed.has(n) }, ...(references ? { references } : {}) }) };+};++describe('brief clause follows the names-row reference fields', () => {+ for (const surface of SURFACES) {+ for (const namesRow of [false, true]) {+ for (const records of [false, true]) {+ test(`${surface}: names-row ${namesRow ? 'on' : 'off'}, records ${records ? 'enrolled' : 'off'}`, () => {+ const { listed, text } = render(surface, { namesRow, records });+ const line = briefLine(text);+ if (!listed.has('entity')) {+ expect(text).not.toContain('`names` row');+ return;+ }+ expect(line).toContain(CARD);+ expect(line).not.toContain('call `entity`, then walk');+ expect(line.includes(NEXT)).toBe(namesRow);+ expect(line.includes(RECORDS)).toBe(records);+ expect(line.includes('`names` row')).toBe(namesRow || records);+ });+ }+ }+ }++ test('the standalone brief clause (no search or query) carries the same fields', () => {+ const only = new Set(['entity', 'recall', 'remember']);+ const text = buildMcpInstructions({ tools: { callable: n => only.has(n) }, references: { namesRow: true, records: true } });+ expect(text).not.toContain('Answering from the brain');+ expect(text).toContain("5. For a brief on an account, person or company, walk the `entity` card's `referenced_by` by type; a `names` row lists `records` by type, and its `next` opens the card.");+ });++ test('the static contract is the defaults rendering (names-row on, no records)', () => {+ expect(buildMcpInstructions({ references: { namesRow: true, records: false } })).toBe(GBRAIN_MCP_INSTRUCTIONS);+ expect(briefLine(GBRAIN_MCP_INSTRUCTIONS)).toContain("by type; a `names` row's `next` opens the card.");+ expect(GBRAIN_MCP_INSTRUCTIONS).not.toContain('`records`');+ });+});++describe('entity references config reader', () => {+ test('parsing: names-row off only for an explicit falsy value; record types trimmed and deduplicated in order', () => {+ expect([undefined, null, '', 'true', 'on', 'garbage'].map(v => parseNamesReferences(v))).toEqual([true, true, true, true, true, true]);+ expect(['false', 'OFF', ' 0 ', 'no'].map(v => parseNamesReferences(v))).toEqual([false, false, false, false]);+ expect(parseRecordTypes(' contract, amendment ,,contract,Order ')).toEqual(['contract', 'amendment', 'Order']);+ expect(parseRecordTypes(null)).toEqual([]);+ });++ test('a read error fails closed to the defaults', async () => {+ const broken = { getConfig: async () => { throw new Error('db down'); } };+ expect(await readEntityReferencesConfig(broken)).toEqual({ namesRow: true, recordTypes: [] });+ expect(await readInstructionContent(broken)).toEqual({ references: { namesRow: true, records: false } });+ });++ describe('on PGLite', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ }, 120_000);+ afterAll(async () => { await engine?.disconnect(); });++ test('unset keys read as the defaults; set keys drive the instruction content', async () => {+ expect(await readInstructionContent(engine)).toEqual({ references: { namesRow: true, records: false } });+ await engine.setConfig(ENTITY_NAMES_REFERENCES_KEY, 'false');+ await engine.setConfig(ENTITY_RECORD_TYPES_KEY, 'contract, amendment');+ expect(await readEntityReferencesConfig(engine)).toEqual({ namesRow: false, recordTypes: ['contract', 'amendment'] });+ const content = await readInstructionContent(engine);+ expect(content).toEqual({ references: { namesRow: false, records: true } });+ const line = briefLine(buildMcpInstructions(content));+ expect(line).toContain('a `names` row lists `records` by type.');+ expect(line).not.toContain(NEXT);+ });+ });+});diff --git a/test/mcp-schema-budget.test.ts b/test/mcp-schema-budget.test.tsindex e37e3395d5..39579562f7 100644--- a/test/mcp-schema-budget.test.ts+++ b/test/mcp-schema-budget.test.ts@@ -45,7 +45,7 @@ import { operations, type Operation } from '../src/core/operations.ts';import { filterOpsForSurface, STARTER_OPS } from '../src/mcp/surface.ts';import { buildToolDefs } from '../src/mcp/tool-defs.ts';import { stdioVisibleTools } from '../src/mcp/server.ts';-import { GBRAIN_MCP_INSTRUCTIONS } from '../src/mcp/instructions.ts';+import { buildMcpInstructions, GBRAIN_MCP_INSTRUCTIONS } from '../src/mcp/instructions.ts';import { cl100kAvailable, estimateTokens } from '../src/core/chunkers/token-estimate.ts';const SERVED_STARTER_MAX_CHARS = 25_000;@@ -53,7 +53,7 @@ const SERVED_STARTER_MAX_TOKENS = 5_700;/** The whole tools/list JSON, annotations included (25,735 measured at v0.60.46.0; traverse_graph's `hops` is full-surface-only, 25,941 measured; 26,402 once mute_notice, the dismissal for the coaching notices starter sessions receive, joined starter; 26,671 with #6007's put_page wait_ms param and write guidance, which carry the put_pages hint and the receipt poll rule starter agents need; 26,679 with delta's opaque `cursor` param, paid for by trimming delta's own descriptions, model-visible 24,985; 26,692 with recall's `question` param, paid for by trimming recall's own parameter text, model-visible 24,998; 24,996 after the #6446 merge, recall's grep text trimmed again). */const SERVED_STARTER_MAX_JSON_CHARS = 26_700;/** 4,042 at the cost wave + 586 for the operator contract's error protocol, notice prefix and memory loop (F1); no schema guidance moved here. */-const INSTRUCTIONS_MAX_CHARS = 4_975; // #6007: +240 for the issue-required write guidance (put_pages, wait_ms); Cat 40 Hard round 4: +107 for batching lists of names (entity names, keyword OR) and sending independent calls together+const INSTRUCTIONS_MAX_CHARS = 5_045; // #6007: +240 for the issue-required write guidance (put_pages, wait_ms); Cat 40 Hard round 4: +107 for batching lists of names (entity names, keyword OR) and sending independent calls together; d5b: +70 for the brief naming the fields compact `entity names` rows carry (the maximal rendering, record types enrolled; +39 at the default) instead of a `referenced_by` walk batch mode cannot doconst DESCRIPTION_HARD_CAP = 1_200;const PARAM_DESCRIPTION_HARD_CAP = 200;@@ -156,6 +156,15 @@ describe('served starter tool list (Cat 40 configuration)', () => {test('initialize instructions stay at or below their recorded size', () => {expect(GBRAIN_MCP_INSTRUCTIONS.length).toBeLessThanOrEqual(INSTRUCTIONS_MAX_CHARS);});++ test('every names-row reference rendering stays at or below the recorded size (maximal: records enrolled, names-row on)', () => {+ for (const namesRow of [false, true]) {+ for (const records of [false, true]) {+ expect({ namesRow, records, size: buildMcpInstructions({ references: { namesRow, records } }).length <= INSTRUCTIONS_MAX_CHARS })+ .toEqual({ namesRow, records, size: true });+ }+ }+ });});describe('per-tool schema budgets', () => {