Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

F4: instruction 7 says the record in effect on the date asked about governs

garrytan77b21c65abe0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b0d838c873..43fe2751d5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,7 @@ identifiers and attribution are available in the pre-removal Git revision
## [Unreleased: cat40 next wave part 1, version stamped at merge] - 2026-10-12
+- **Served instructions (F4): the record in effect on the date asked about governs, not the newest one.** Instruction 7 now reads "The record whose terms are in effect on the date asked about governs: a page's `date`/`effective_date` is when it was written, not when its terms take effect, and a change not yet effective does not apply yet; drafts, proposals and agent-written notes do not override records." (`date` is named only where `entity` is callable). It replaces "prefer the newest governing source: a later correction, handoff or executed change outranks an older record". The rule now leads the answering clause and ends inside the first 2,048 characters capped harnesses read (starter 1,566–1,842, full 1,717–1,993; it started at 1,943 and 2,094). New key `mcp.instructions_governing_rule` (`in_effect` default, `newest` serves the earlier sentence for measurement). Budget: the sentence is 74 characters longer; 11 are paid by cutting "the best-ranked excerpts" to "top excerpts" in the same clause, and +63 is recorded in `test/mcp-schema-budget.test.ts` (5,108 for the maximal rendering). Tests: `test/mcp-instructions-governing-rule.test.ts`.
- **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
diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.md
index 7754974314..ef5e4ac44d 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. 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/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`). Instruction 7's governing rule (`mcp.instructions_governing_rule`: `in_effect` default, `newest` the earlier recency sentence) leads the answering clause so it ends inside the first 2,048 characters (`test/mcp-instructions-governing-rule.test.ts` records its offset per surface).
- `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/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index f5589a6d73..fd8b78255c 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -471,6 +471,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ 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.181.0', text: 'The MCP instructions now say the record whose terms are in effect on the date asked about governs, that a page\'s `date`/`effective_date` is when it was written (not when its terms take effect), and that a change not yet effective does not apply yet; they no longer say a later correction, handoff or executed change outranks an older record. Drafts, proposals and agent-written notes still do not override records. The rule now sits inside the first 2,048 characters. `gbrain config set mcp.instructions_governing_rule newest` serves the earlier sentence.' },
{ 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.ts
index 9152cd178e..15f968b42c 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1624,6 +1624,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// page types listed as `records` (comma-separated, default empty: no records).
'entity.names_references',
'entity.record_types',
+ // Instruction 7's governing rule (src/mcp/instructions.ts): in_effect (default, the record whose terms are in effect
+ // on the date asked about governs) | newest (the earlier "prefer the newest governing source" sentence).
+ 'mcp.instructions_governing_rule',
// 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/mcp/instructions.ts b/src/mcp/instructions.ts
index 61d034f8c2..1756904fa0 100644
--- a/src/mcp/instructions.ts
+++ b/src/mcp/instructions.ts
@@ -44,15 +44,30 @@ export interface InstructionTools {
*/
export interface InstructionReferences { namesRow: boolean; records: boolean }
+/**
+ * `mcp.instructions_governing_rule`: which record instruction 7 says governs.
+ * `in_effect` (default): the record whose terms are in effect on the date
+ * asked about. `newest`: the earlier "prefer the newest governing source"
+ * sentence, kept so the rule can be measured against it.
+ */
+export const GOVERNING_RULE_CONFIG_KEY = 'mcp.instructions_governing_rule';
+export const GOVERNING_RULES = ['in_effect', 'newest'] as const;
+export type GoverningRule = typeof GOVERNING_RULES[number];
+
/** The served-text options that follow brain config; every call site reads them with readInstructionContent. */
export interface InstructionContent {
references?: InstructionReferences;
+ governingRule?: GoverningRule;
}
/** 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 rule = await engine.getConfig(GOVERNING_RULE_CONFIG_KEY).catch(() => null);
+ return {
+ references: { namesRow: refs.namesRow, records: refs.recordTypes.length > 0 },
+ governingRule: rule?.trim() === 'newest' ? 'newest' : 'in_effect',
+ };
}
const ALL: CallablePredicate = () => true;
@@ -97,7 +112,15 @@ function contractClauses(c: CallablePredicate, writeback?: AmbientWritebackOpts
// but lists of names are batched and independent calls go out together (one call per name ran readers out of turns).
const batchVia = [c('entity') ? '`entity` with `names`' : null, c('search') ? 'one keyword `search` for "A" OR "B" OR …' : null].filter(Boolean);
const batch = `Keep separate parts of a question in separate searches, but batch lists: resolve many names or codes in one call${batchVia.length ? ` (${batchVia.join(' or ')})` : ''}, and issue independent calls together in one turn, not one per turn.`;
- out.push(`Answering from the brain: a search returns the best-ranked excerpts, not every relevant page, so keep going until the evidence is complete. ${batch} ${brief ?? 'People and companies appear under several names (abbreviations, codes, nicknames); when a page lists another name, search for that too.'} For what is true now, prefer the newest governing source: a later correction, handoff or executed change outranks an older record, and drafts, proposals and agent-written notes do not override records.`);
+ const names = brief ?? 'People and companies appear under several names (abbreviations, codes, nicknames); when a page lists another name, search for that too.';
+ if (content?.governingRule === 'newest') {
+ out.push(`Answering from the brain: a search returns the best-ranked excerpts, not every relevant page, so keep going until the evidence is complete. ${batch} ${names} For what is true now, prefer the newest governing source: a later correction, handoff or executed change outranks an older record, and drafts, proposals and agent-written notes do not override records.`);
+ } else {
+ // F4: validity, not recency, decides; page dates are named as page dates. The rule leads the clause so it ends
+ // inside the 2,048 characters capped harnesses read on every surface's default rendering.
+ const dates = c('entity') ? '`date`/`effective_date`' : '`effective_date`';
+ out.push(`Answering from the brain: a search returns top excerpts, not every relevant page, so keep going until the evidence is complete. The record whose terms are in effect on the date asked about governs: a page's ${dates} is when it was written, not when its terms take effect, and a change not yet effective does not apply yet; drafts, proposals and agent-written notes do not override records. ${batch} ${names}`);
+ }
}
if (c('list_skills') && c('get_skill')) {
out.push(`When the task calls for a procedure or workflow, discover available skills with list_skills using schema_version:2 when supported. Match descriptions and frontmatter triggers to the task, then read the matching skill in full with get_skill using its qualified_id, revision and schema_version:2.${c('get_skill_asset') ? ' Load approved dependencies from that exact revision with get_skill_asset.' : ''} If an older server explicitly rejects version 2, use its documented legacy discovery; an unavailable catalog is not empty.`);
diff --git a/test/mcp-initialize-instructions.test.ts b/test/mcp-initialize-instructions.test.ts
index 633a4920cb..2d1a7749be 100644
--- a/test/mcp-initialize-instructions.test.ts
+++ b/test/mcp-initialize-instructions.test.ts
@@ -101,8 +101,9 @@ describe('F1 generated instructions', () => {
// Cat 40 Hard round 4: instruction 7's batching clause (BATCHING_CLAUSE_BYTES); starter 4_630 -> 4_824 and full 4_781 -> 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 };
+ // F4: instruction 7's governing rule (in effect on the date asked about), +63 on starter and full; verbs serves no clause 7.
+ const recorded = { verbs: 2_225, starter: 4_926, full: 5_077 };
+ const maximal = { verbs: 2_256, starter: 4_957, full: 5_108 };
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;
diff --git a/test/mcp-instructions-governing-rule.test.ts b/test/mcp-instructions-governing-rule.test.ts
new file mode 100644
index 0000000000..93be2c75e4
--- /dev/null
+++ b/test/mcp-instructions-governing-rule.test.ts
@@ -0,0 +1,104 @@
+/**
+ * F4: instruction 7's governing rule. The record whose terms are in effect on
+ * the date asked about governs; a page's date says when it was written, not
+ * when its terms take effect; a change not yet effective does not apply yet;
+ * drafts, proposals and agent-written notes still do not override records.
+ * It replaces "prefer the newest governing source: a later correction,
+ * handoff or executed change outranks an older record", which
+ * `mcp.instructions_governing_rule: newest` still serves for measurement.
+ *
+ * Offsets: capped harnesses read the first 2,048 characters. The old sentence
+ * started at 2,094 on the full surface (1,943 on starter, ending past 2,048);
+ * the rule now leads the answering clause, and its recorded offsets below are
+ * the default rendering's (no writeback section, no hidden-tool sentence).
+ */
+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, GOVERNING_RULE_CONFIG_KEY, readInstructionContent } from '../src/mcp/instructions.ts';
+
+const SURFACES = ['verbs', 'starter', 'full'] as const;
+const RULE = 'The record whose terms are in effect on the date asked about governs';
+const KEEP = 'drafts, proposals and agent-written notes do not override records';
+const OLD = 'For what is true now, prefer the newest governing source';
+const HARNESS_READ_LIMIT = 2_048;
+/** [start, end) of the governing sentence per surface, default rendering. */
+const RECORDED_OFFSETS: Record<string, [number, number] | null> = { verbs: null, starter: [1_566, 1_842], full: [1_717, 1_993] };
+
+const render = (surface: typeof SURFACES[number], opts: Parameters<typeof buildMcpInstructions>[0] = {}) => {
+ const listed = new Set(filterOpsForSurface(operations, surface).map(o => o.name));
+ return { listed, text: buildMcpInstructions({ tools: { callable: n => listed.has(n) }, ...opts }) };
+};
+const sentence = (text: string): [number, number] | null => {
+ const start = text.indexOf(RULE);
+ return start < 0 ? null : [start, text.indexOf(`${KEEP}.`, start) + KEEP.length + 1];
+};
+
+describe('governing rule (F4)', () => {
+ for (const surface of SURFACES) {
+ test(`${surface}: recorded offset, inside the harness read limit on every names-row rendering`, () => {
+ const { listed, text } = render(surface);
+ expect(sentence(text)).toEqual(RECORDED_OFFSETS[surface]);
+ for (const namesRow of [false, true]) {
+ for (const records of [false, true]) {
+ const at = sentence(render(surface, { references: { namesRow, records } }).text);
+ if (!listed.has('search') && !listed.has('query')) { expect(at).toBeNull(); continue; }
+ expect(at).not.toBeNull();
+ expect(at![1]).toBeLessThanOrEqual(HARNESS_READ_LIMIT);
+ }
+ }
+ });
+ }
+
+ test('the replacement keeps the drafts rule and drops the recency rule; page dates are named as page dates', () => {
+ const line = GBRAIN_MCP_INSTRUCTIONS.split('\n').find(l => l.includes('Answering from the brain')) ?? '';
+ expect(line).toContain(`${RULE}: a page's \`date\`/\`effective_date\` is when it was written, not when its terms take effect, and a change not yet effective does not apply yet; ${KEEP}.`);
+ expect(line).not.toContain('outranks');
+ expect(line).not.toContain(OLD);
+ expect(line).toContain('keep going until the evidence is complete');
+ });
+
+ test('`date` is named only where `entity` (whose rows carry it) is callable', () => {
+ const searchOnly = new Set(['search', 'get_page']);
+ const text = buildMcpInstructions({ tools: { callable: n => searchOnly.has(n) } });
+ expect(text).toContain("a page's `effective_date` is when it was written");
+ expect(text).not.toContain('`date`/');
+ });
+
+ test('`newest` serves the earlier sentence at its earlier place, and nothing of the new rule', () => {
+ for (const surface of ['starter', 'full'] as const) {
+ const { text } = render(surface, { governingRule: 'newest' });
+ expect(text).toContain(`${OLD}: a later correction, handoff or executed change outranks an older record, and ${KEEP}.`);
+ expect(text).not.toContain(RULE);
+ expect(text).toContain('a search returns the best-ranked excerpts, not every relevant page');
+ }
+ });
+
+ test('the static contract is the `in_effect` rendering', () => {
+ expect(buildMcpInstructions({ governingRule: 'in_effect' })).toBe(GBRAIN_MCP_INSTRUCTIONS);
+ });
+
+ test('a read error fails closed to `in_effect`', async () => {
+ const broken = { getConfig: async () => { throw new Error('db down'); } };
+ expect((await readInstructionContent(broken)).governingRule).toBe('in_effect');
+ });
+
+ 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 reads `in_effect`; `newest` switches back; any other value reads `in_effect`', async () => {
+ expect((await readInstructionContent(engine)).governingRule).toBe('in_effect');
+ await engine.setConfig(GOVERNING_RULE_CONFIG_KEY, 'newest');
+ expect((await readInstructionContent(engine)).governingRule).toBe('newest');
+ await engine.setConfig(GOVERNING_RULE_CONFIG_KEY, 'bogus');
+ expect((await readInstructionContent(engine)).governingRule).toBe('in_effect');
+ });
+ });
+});
diff --git a/test/mcp-instructions-references.test.ts b/test/mcp-instructions-references.test.ts
index 9b58042b0f..098ea349a0 100644
--- a/test/mcp-instructions-references.test.ts
+++ b/test/mcp-instructions-references.test.ts
@@ -78,7 +78,7 @@ describe('entity references config reader', () => {
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 } });
+ expect((await readInstructionContent(broken)).references).toEqual({ namesRow: true, records: false });
});
describe('on PGLite', () => {
@@ -91,12 +91,12 @@ describe('entity references config reader', () => {
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 } });
+ expect((await readInstructionContent(engine)).references).toEqual({ 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 } });
+ expect(content.references).toEqual({ 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.ts
index 39579562f7..a08d6c55e7 100644
--- a/test/mcp-schema-budget.test.ts
+++ b/test/mcp-schema-budget.test.ts
@@ -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 = 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 do
+const INSTRUCTIONS_MAX_CHARS = 5_108; // #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 do; F4: +63 for instruction 7's governing rule (the record whose terms are in effect on the date asked about governs; page dates are named as page dates), 74 characters longer than the "prefer the newest governing source" sentence it replaces, 11 paid by cutting "the best-ranked excerpts" to "top excerpts" in the same clause
const DESCRIPTION_HARD_CAP = 1_200;
const PARAM_DESCRIPTION_HARD_CAP = 200;
@@ -157,13 +157,20 @@ describe('served starter tool list (Cat 40 configuration)', () => {
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 });
+ // Per-arm renderings: all off (names-row off, no records, `newest`), names-row on / records off, F4 only
+ // (`in_effect`, names-row off, no records), and the maximal one (records enrolled, names-row on, `in_effect`) at 5,108.
+ test('every per-arm rendering stays at or below the recorded size; the maximal one is the recorded size', () => {
+ let max = 0;
+ for (const governingRule of ['newest', 'in_effect'] as const) {
+ for (const namesRow of [false, true]) {
+ for (const records of [false, true]) {
+ const size = buildMcpInstructions({ references: { namesRow, records }, governingRule }).length;
+ max = Math.max(max, size);
+ expect({ governingRule, namesRow, records, fits: size <= INSTRUCTIONS_MAX_CHARS }).toEqual({ governingRule, namesRow, records, fits: true });
+ }
}
}
+ expect(buildMcpInstructions({ references: { namesRow: true, records: true }, governingRule: 'in_effect' }).length).toBe(max);
});
});