Local-first 🧠memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.
TypeScript
fix(store): reach-safe store-open errors, cached pending-blob reads, remote-reach view fixes, split large modules (#299)
Serg Eroshe0cff58cf5508
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 96125ac6..7554693e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **Token callers are attributed to their token on `brain_note` and `brain_expire` even without an `agent` argument.** Both handlers refused a cross-agent claim but then let an omitted agent resolve through the process config, so a token-minted caller's log line and expiration audit stamp could name the config identity instead of the credential's agent; both now fall back to the request identity after the claim check only when the caller arrived by token, and a shared-key caller keeps the config-path resolution it always had.+- **A retried `brain_feedback` force-confirmed capture no longer stays unwritten - and a replay can no longer resurrect a forgotten rule.** A first call that failed after its signal landed left an idempotency receipt whose retry answered `deduped` and never created the confirmed rule; the call now leaves a pending capture marker in the idempotency ledger before the preference write and a completion marker after it, and a deduped retry resumes only on that pending marker, with the same capture payload (the marker hash names `force_confirmed` and the expiration, so a forced retry of an unforced capture and a retry with a different lifetime both stay true no-ops) and with the signal still present. A crash that landed after the preference write but before the completion marker leaves the rule already active, so a replay that finds an active rule matching the captured slug and payload now closes the ledger and answers deduped instead of attempting the write a second time and refusing on the existing rule - and only a rule this capture can prove it wrote: the rule must read `confirmed` and name the deduped signal under `evidenced_by`, so a pre-existing same-slug same-payload rule falls through and surfaces its conflict instead of being adopted. A capture completed once, a capture whose signal `delete-by-source` later forgot, and a first call made without `force_confirmed` all stay true no-ops on replay; receipts written before the marker existed simply never resume, so old keys stay readable. The marker keys are digests of the trimmed client key rather than the key plus a suffix, so a key near the ledger's 256-character limit still captures fresh and replays deduped instead of failing its marker lookup, and a retry whose key differs only in surrounding whitespace finds the original capture's marker just as it dedupes its signal; the resume also answers a signal that moved since the failed write (the dream pass files inbox pages under `Brain/inbox/processed/`, an applied staged signal moves out of `Brain/pending/` into `Brain/inbox/`) by looking the id up in those folders, honors the server's config path when it consults the store, and stands down when the rule was retired in the crash window. The ledger's per-shard lock guarantees sequential retries dedupe exactly once on a device and, once synced, across devices; two truly concurrent retries can both pass the marker check, narrowed to a same-slug preference merge.+- **`brain_foresight` withholds private continuity records below local reach.** The extract fold read the raw continuity store, whose private records the read model drops, and served a private record's text as an item title with its source refs; the fold now takes the same withholding flag every other report fold takes, and local reach is unchanged. The recurring projection takes the flag too: a recurrence event the writer classified private - its source, or its scope, can name a private page whose name the projected item title carries - has its support dropped before the cadences are built, so no private-derived routine, support count or commitment reaches a caller below local reach.+- **`brain_clusters` batches are filtered by the same visibility rules as the top-level result.** A caller passing `batch_size` could read the cluster-note paths, stale-removal list, community offsets and raw write errors of communities the answer withholds whole - the offsets counted hidden communities, and an error message names the failed note's file, which spells a hidden seed page's path; below local reach the batches are withheld whole - the same rule the top-level `removed` follows, since a batch's very existence counts hidden communities and a rebuild over the visible ones still reveals their number through the batch count - so a caller who sees no community gets no batch.+- **`brain_truth` folds answer at the caller's view.** `slots`, `conflicts`, `aggregate` and `collisions` folded the whole claim ledger while `events` withheld claims whose source the caller cannot read, exposing the withheld values, quantities, agents and source paths through the fold; all five operations now apply the same view before folding.+- **`brain_audit` gates the mutation history by the caller's reach.** The trail of a preference whose page the caller cannot read answers as an absent one (the empty history) instead of listing its agents, reasons and revisions.+- **`brain_recall_telemetry` `observed_reuse` answers at the caller's view.** The key list now applies the same request reach and ownership view the `dead_weight` branch applies, so keys the caller's reach withholds are dropped before `total` and the rates, with the local-reach result unchanged.+- **`brain_recall_telemetry` `list`, `summary`, `gate_list` and `gate_summary` answer at the caller's view.** Those operations returned every continuity record raw at remote reach - private records included, and with `top_artifacts` paths and source refs naming withheld pages - while the tool's `observed_reuse` and `dead_weight` branches already applied the request's reach and ownership view; the same view is now applied to the record list before `total` and before the summary counts, dropping private records and records whose artifact refs the caller cannot see - asked of both spellings an emitter carries, the page path when it had one and the bare Brain id when it did not. The ownership half applies at local reach too: under `integrity.owner_scope_delivery: fail` a record naming another owner's artifact is withheld from a local caller as well, while the `private` partition stays a remote-only withholding and a vault with the gate off keeps its local answer unchanged. The `limit` on `list` and `gate_list` cuts the page after the visibility filter, so a withheld newest record can no longer consume the caller's page and hide an older visible one behind it.+- **`brain_bridges` `discover` and `list` answer at the caller's ownership scope.** `discover` filtered its proposals by reach alone, so under `integrity.owner_scope_delivery: fail` a caller could receive a bridge naming another owner's page; the response now composes the ownership view into the same filter and drops such a proposal whole - the rule the reach filter already applies to one withheld end. `list` asks the same composed rule over the proposals artifact, so an owner-stamped artifact answers as an absent one to every other scope - and because the artifact is one shared file written vault-wide, its `proposals` count is recomputed row by row over the caller's view rather than read from the frontmatter; an artifact whose table cannot be read back into rows answers as an absent one instead of leaking an unfiltered count. The row read-back now takes each cell's path up to the cell's final parenthesis - the exact shape the writer emits - so a proposal whose path contains parentheses (`Notes/Design (v2).md`) parses and counts instead of making the whole artifact answer as absent.+- **A degraded lane fold's stamp now moves when its contributing records change.** Two partial folds over identically stamped shards - a transiently unreadable shard and a shard read in part past one corrupt line - produced the same `incomplete` fingerprint, so the entity-index and nickname memos could serve a build made over different records; the fingerprint now includes a digest of the records the fold saw, and stays stable while the degraded state lasts.+- **A lost private partition's name stays out of every remote answer.** A store that cannot be opened fails closed with an error whose cause names the lost partition's identity file; the error now carries a redacted twin of its message (the store's own redacted detail, and for a missing `shared` partition the correct wording), and every consumer that serves the text - the doctor's `permissions-unreadable` finding below local reach, an agent's refused settings write, an unreadable brain-settings read, the permissions document the write gates load, a refused signal forget (whose unreadable private shards are counted, not named, at any reach), and the lane fold's unreadable list - serves that twin, so no remote answer names `private/store.json` or the leave remedy. A local run still names the cause.+- **A store read that skipped a quarantined pending blob is now cached.** The entity read and the lane fold cache such a read against the availability of every blob the skipped record still references (one stat per blob), so a blob that never arrives no longer makes every call rescan the shards, and the record appears on the first read after the blob is delivered. A blob that is there but refused (a link, a mismatch) leaves the read uncached, and the lane fold's fingerprint - the change stamp the entity index and the nickname memo key on - includes the same availability, so a lane update whose body was a pending blob refreshes them the moment the blob arrives. A fold that must stay uncached (an unreadable or gone shard, a refused blob) now carries a deterministic `incomplete` stamp instead of a random one, so the memos keyed on it keep hitting - at the same degraded build - while the degraded state lasts, instead of turning every query into a full rebuild.- **Windows: `o2b search reindex` no longer fails with `EBUSY` on its own staging file.** A `bun:sqlite` connection with unfinalized statements survives `close()` until garbage collection and keeps `brain.sqlite.new` open, so the rename swap failed on every attempt on Windows (POSIX `rename(2)` ignores open handles). The rebuild now forces a collection cycle right before the swap renames.- **The active preference digest no longer lists a retired preference.** `brain reject`, a tombstone and setting or clearing a preference's expiration now refresh `Brain/active.md`, an explicitly expired preference leaves the digest at its deadline, and `o2b brain refresh --stale` detects and rebuilds a digest that differs from the current preference set.diff --git a/openclaw/index.js b/openclaw/index.jsindex b0817c6c..783ae779 100644--- a/openclaw/index.js+++ b/openclaw/index.js@@ -4402,7 +4402,7 @@ var init_safe_fs = __esm(() => {});// src/core/store/store-paths.ts-import { realpathSync as realpathSync2 } from "node:fs";+import { lstatSync as lstatSync3, realpathSync as realpathSync2 } from "node:fs";import { homedir as homedir3 } from "node:os";import { join as join9, posix as posix4, win32 as win322 } from "node:path";function pathsFor(platform) {@@ -4523,6 +4523,34 @@ function blobPath(partitionRoot, sha) {throw new Error(`"${sha}" is not a sha256 hex digest`);return join9(partitionRoot, STORE_BLOBS_DIR, sha.slice(0, 2), sha);}+function lstatIdentity(path) {+ const st = lstatSync3(path, { bigint: true });+ return `${st.dev}:${st.ino}:${st.size}:${st.mtimeNs}:${st.ctimeNs}`;+}+function blobStamp(partitionRoot, sha) {+ try {+ const blob = lstatIdentity(blobPath(partitionRoot, sha));+ const folder = lstatIdentity(join9(partitionRoot, STORE_BLOBS_DIR, sha.slice(0, 2)));+ return `${blob};${folder}`;+ } catch {+ return "absent";+ }+}+function pendingBlobStampLines(root, identities) {+ let lines = "";+ for (const identity of identities.toSorted()) {+ const slashAt = identity.indexOf("/");+ const partition = identity.slice(0, slashAt);+ const sha = identity.slice(slashAt + 1);+ const stamp = blobStamp(partitionDir(root, partition), sha);+ if (stamp === "absent")+ lines += `blob ${identity}=absent+`;+ else+ return null;+ }+ return lines;+}function shardLockTarget(deviceStateDir, partition, rel) {return join9(deviceStateDir, STORE_LOCKS_DIR, partition, ...rel.split("/"));}@@ -6093,6 +6121,9 @@ function monthOf2(rel) {const name = rel.slice(rel.lastIndexOf("/") + 1);return name.slice(0, 7);}+function blobRefSha(body) {+ return body[BLOB_REF_KEY];+}function streamPrefix(ref) {return ref.ledger !== undefined ? `${ref.stream}/${ref.ledger}` : ref.stream;}@@ -6100,14 +6131,21 @@ function readStreamRecords(root, partition, ref, options = {}) {const partitionRoot = partitionDir(root, partition);const records = [];const unreadable = [];+ const pendingBlobs = [];let shards;try {shards = listShards(partitionRoot, ref);} catch {- return { records, unreadable: [streamPrefix(ref)], skippedPending: false };+ return {+ records,+ unreadable: [streamPrefix(ref)],+ skippedPending: false,+ pendingBlobs: []+ };}const compactions = [];let skippedPending = false;+ const seenBlobs = new Set;for (const shard of shards) {if (options.device !== undefined && shard.device !== options.device)continue;@@ -6128,10 +6166,16 @@ function readStreamRecords(root, partition, ref, options = {}) {unreadable.push(shard.rel);compactions.push(...read.compactions);for (const entry of read.records) {- if (entry.bodyState !== "pending")+ if (entry.bodyState !== "pending") {records.push(entry.record);- else- skippedPending = true;+ continue;+ }+ skippedPending = true;+ const sha = blobRefSha(entry.record.body);+ if (!seenBlobs.has(sha)) {+ seenBlobs.add(sha);+ pendingBlobs.push(sha);+ }}}const gone = trackSeenShards(partitionRoot, {@@ -6139,9 +6183,15 @@ function readStreamRecords(root, partition, ref, options = {}) {...options.device !== undefined ? { device: options.device } : {},...options.month !== undefined ? { month: options.month } : {}}, shards.map((shard) => shard.rel), replacedShards(compactions));- return { records, unreadable: [...unreadable, ...gone], skippedPending };+ return {+ records,+ unreadable: [...unreadable, ...gone],+ skippedPending,+ pendingBlobs+ };}var init_stream_read = __esm(() => {+ init_constants();init_reader();init_seen_shards();init_shard_list();@@ -6420,7 +6470,7 @@ import {fsyncSync as fsyncSync4,openSync as openSync6,linkSync as linkSync3,- lstatSync as lstatSync3,+ lstatSync as lstatSync4,mkdirSync as mkdirSync12,readdirSync as readdirSync3,readFileSync as readFileSync13,@@ -6435,7 +6485,7 @@ import { basename as basename7, dirname as dirname13, join as join19, relative afunction filesBelow(path) {let stat;try {- stat = lstatSync3(path);+ stat = lstatSync4(path);} catch {return [];}@@ -6511,7 +6561,7 @@ function copyNoClobber(file, target) {function removeEmptyDirs(dir) {let stat;try {- stat = lstatSync3(dir);+ stat = lstatSync4(dir);} catch {return;}@@ -7756,10 +7806,13 @@ function build(store) {const unreadable = [];const pinned = new Map;let skippedPending = false;+ const pendingBlobs = [];for (const partition of store.partitions) {const read = readStreamRecords(store.root, partition, EVENTS);if (read.skippedPending)skippedPending = true;+ for (const sha of read.pendingBlobs)+ pendingBlobs.push(`${partition}/${sha}`);unreadable.push(...read.unreadable.map((rel) => `${partition}/${rel}`));for (const record of read.records)all.push({ record, partition });@@ -7790,16 +7843,29 @@ function build(store) {partitions: new Set(entry.history.map((r) => partitionOf.get(r.id) ?? "shared"))});}- return { store, preferences, signals, pinned, unreadable, skippedPending };+ return {+ store,+ preferences,+ signals,+ pinned,+ unreadable,+ skippedPending,+ pendingBlobs+ };}function readEntitiesOf(store) {- const fingerprint = fingerprintOf(store);const cached = cache.get(store.root);+ const cachedLines = cached === undefined ? null : pendingBlobStampLines(store.root, cached.entities.pendingBlobs);+ const shardStamp = fingerprintOf(store);+ const fingerprint = cachedLines === null ? null : `${shardStamp}+${cachedLines}`;if (cached !== undefined && cached.fingerprint === fingerprint)return cached.entities;const entities = build(store);- if (entities.unreadable.length === 0 && !entities.skippedPending)- cache.set(store.root, { fingerprint, entities });+ const blobLines = pendingBlobStampLines(store.root, entities.pendingBlobs);+ if (entities.unreadable.length === 0 && blobLines !== null)+ cache.set(store.root, { fingerprint: `${shardStamp}+${blobLines}`, entities });elsecache.delete(store.root);return entities;diff --git a/openspec/changes/brain-store-and-topics/tasks.md b/openspec/changes/brain-store-and-topics/tasks.mdindex c6987f3d..98d62021 100644--- a/openspec/changes/brain-store-and-topics/tasks.md+++ b/openspec/changes/brain-store-and-topics/tasks.md@@ -93,10 +93,10 @@ Phases follow design.md D13. Each phase ends in its own release PR, and the vers- [x] 3.16 Add an operator verb that takes a partition off this machine on purpose (for example `o2b store partition leave private`): held partitions are sticky per machine since the phase 2 review, so a machine that stops syncing `private/` refuses every store operation until the verb clears it from the held list. Verify: leaving `private` turns the machine shared-only with no refusal, and a lost `private/store.json` without the verb still fails closed. Done in change `store-hardening`.- [x] 3.17 Audit every reader that renders store log events to a caller below local reach without `logEntryAtReach` or `logEntriesAtReach` (the active-preferences digest's most-applied counts, the morning brief, temporal citations, status, backlinks, analytics, anything else built on `logDayReader`, `storeLogDays` or `readStoreLogEvents`), and make each withhold events marked `fromPrivatePartition` (change `lane-pages-split`, design D3). Verify: a remote-reach test per reader with one private event that names nothing. Done in change `store-hardening`.- [ ] 3.18 Decide and apply how private `apply-evidence` events take part in the dream and evidence computations (`evidence.ts`, `dream-refresh.ts`, the review candidates of the operator snapshot): today a private event moves a shared preference's confidence and status, which every machine and remote caller then sees (out of scope of change `store-hardening`). Verify: a dream test on a switched machine with private evidence on a shared preference, asserting the decided outcome.-- [ ] 3.19 Split the source files past the 700-line limit that the store readers touch (`src/core/brain/digest.ts`, `src/mcp/brain/query-tools.ts`, `src/mcp/resources.ts`, `src/mcp/brain/brief-tools.ts`, and the other MCP tool files past it), with no behaviour change. Verify: `wc -l` shows each under 700, and the suites of those modules pass unchanged.-- [ ] 3.20 Keep the name of a lost private partition out of fail-closed reader errors served below local reach: `src/core/store/read/protection-store.ts` copies the store-open error, which names `private/store.json`, into findings such as `permissions-unreadable` that a remote caller receives (found in the second repair round of change `store-hardening`; the store check's own finding is already redacted). Verify: a remote-reach doctor test with a lost `private/store.json` whose whole answer does not contain `private`.+- [x] 3.19 Split the source files past the 700-line limit that the store readers touch (`src/core/brain/digest.ts`, `src/mcp/brain/query-tools.ts`, `src/mcp/resources.ts`, `src/mcp/brain/brief-tools.ts`, and the other MCP tool files past it), with no behaviour change. Verify: `wc -l` shows each under 700, and the suites of those modules pass unchanged.+- [x] 3.20 Keep the name of a lost private partition out of fail-closed reader errors served below local reach: `src/core/store/read/protection-store.ts` copies the store-open error, which names `private/store.json`, into findings such as `permissions-unreadable` that a remote caller receives (found in the second repair round of change `store-hardening`; the store check's own finding is already redacted). Verify: a remote-reach doctor test with a lost `private/store.json` whose whole answer does not contain `private`.- [ ] 3.21 Serialize the seen-shards ledger's read-modify-write (`update` in `src/core/store/seen-shards.ts`) under the device-local lock: two processes on one machine can interleave, so a stale write from `trackSeenShards` can bring back entries `o2b store partition leave` just cleared, or a leave can drop a shard another process just recorded (pull-request review of change `store-hardening`). Verify: a two-process test in which a tracked shard and a partition removal both survive.-- [ ] 3.22 Cache a read that skipped a quarantined pending blob: the entity read and the lane fold do not cache such a read (change `store-hardening`), so a blob that never arrives makes them rescan their shards on every call. Put the availability of the pending blobs into the cache fingerprint instead. Verify: the read is cached while the blob is absent, and the record appears on the first read after the blob arrives.+- [x] 3.22 Cache a read that skipped a quarantined pending blob: the entity read and the lane fold do not cache such a read (change `store-hardening`), so a blob that never arrives makes them rescan their shards on every call. Put the availability of the pending blobs into the cache fingerprint instead. Verify: the read is cached while the blob is absent, and the record appears on the first read after the blob arrives.- [ ] 3.7 Integration. Run the full gate on Linux and Windows. Then the owner checks topics by hand on two machines and in a phone view, including a phone edit. Then open the release PR.## 4. Phase 4: decision-model uses and agent contextdiff --git a/src/core/brain/attestation/record.ts b/src/core/brain/attestation/record.tsindex 5e399168..df8a42ba 100644--- a/src/core/brain/attestation/record.ts+++ b/src/core/brain/attestation/record.ts@@ -369,7 +369,7 @@ function storeAttestationEntries(vault: string): AttestationEntry[] {const gone = protectionStoreUnavailable();return gone === null? []- : [{ path: "", name: `${UNREADABLE_NAME_PREFIX}store`, unreadable: gone.message }];+ : [{ path: "", name: `${UNREADABLE_NAME_PREFIX}store`, unreadable: gone.publicMessage }];}const root = source.store.root;const found: { record: StoreRecord; path: string }[] = [];diff --git a/src/core/brain/digest-analysis.ts b/src/core/brain/digest-analysis.tsnew file mode 100644index 00000000..14a6d5b5--- /dev/null+++ b/src/core/brain/digest-analysis.ts@@ -0,0 +1,160 @@+/**+ * The digest's ranking and connection analysis (task 3.19): the hot+ * section budget, the top-applied and top-referenced picks, the+ * connection-health computation and the empty-fold predicate, over the+ * preferences and backlinks the collection gathered. Split from+ * `digest.ts`.+ */++import { posix } from "node:path";+import { type ArtifactRefView } from "./artifact-ref-view.ts";+import { type BacklinkIndex } from "./backlinks.ts";+import { BRAIN_RETIRED_REL } from "./paths.ts";+import { normaliseWikilinkTarget } from "./wikilink.ts";+import { memoryFolderPages } from "./memory-pages.ts";+import { BRAIN_PREFERENCE_STATUS } from "./types.ts";+import type { BrainPreference } from "./types.ts";+import type {+ DigestData,+ DigestJsonConnectionHealth,+ DigestJsonTopApplied,+ DigestJsonTopReferenced,+} from "./digest-types.ts";++/**+ * How many entries to keep in each "hot" digest section. Small fixed+ * value — the digest is meant to be skimmable, not exhaustive.+ */+export const HOT_SECTION_LIMIT = 5;++export function pickTopApplied(+ preferences: ReadonlyArray<PreferenceWithPath>,+): ReadonlyArray<DigestJsonTopApplied> {+ const active = preferences.filter(+ ({ pref }) =>+ (pref.status === BRAIN_PREFERENCE_STATUS.confirmed ||+ pref.status === BRAIN_PREFERENCE_STATUS.quarantine) &&+ pref.applied_count > 0,+ );+ active.sort((a, b) => {+ const diff = b.pref.applied_count - a.pref.applied_count;+ if (diff !== 0) return diff;+ // Stable secondary key: id ascending. Without it the same input on+ // two filesystems (different readdir order) could swap ties.+ return a.pref.id.localeCompare(b.pref.id);+ });+ return active.slice(0, HOT_SECTION_LIMIT).map(({ pref }) => ({+ id: pref.id,+ topic: pref.topic,+ principle: pref.principle,+ scope: pref.scope ?? null,+ applied_count: pref.applied_count,+ violated_count: pref.violated_count,+ confidence: pref.confidence,+ status: pref.status,+ }));+}++/**+ * Inbound references to `target` whose source this reader may see. With+ * nothing filtered it is the index's own count.+ */+export function visibleBacklinkCount(+ index: BacklinkIndex,+ target: string,+ refs: ArtifactRefView,+): number {+ const sources = index.get(normaliseWikilinkTarget(target)) ?? [];+ return refs.filtersNothing+ ? sources.length+ : sources.filter((ref) => refs.visible(ref.source)).length;+}++export function pickTopReferenced(+ inbound: (id: string) => number,+ preferences: ReadonlyArray<PreferenceWithPath>,+): ReadonlyArray<DigestJsonTopReferenced> {+ const scored = preferences+ .map(({ pref }) => ({+ pref,+ count: inbound(pref.id),+ }))+ .filter((x) => x.count > 0);+ scored.sort((a, b) => {+ const diff = b.count - a.count;+ if (diff !== 0) return diff;+ return a.pref.id.localeCompare(b.pref.id);+ });+ return scored.slice(0, HOT_SECTION_LIMIT).map(({ pref, count }) => ({+ id: pref.id,+ topic: pref.topic,+ principle: pref.principle,+ scope: pref.scope ?? null,+ backlink_count: count,+ }));+}++/**+ * Compute vault-level connection-density health metrics from the+ * backlink index over all preferences and retired entries.+ */+export function computeConnectionHealth(+ vault: string,+ inbound: (id: string) => number,+ preferences: ReadonlyArray<PreferenceWithPath>,+ refs: ArtifactRefView,+): DigestJsonConnectionHealth {+ const allIds = preferences.map(({ pref }) => pref.id);+ // Also include retired entries.+ for (const entry of memoryFolderPages(vault, "retired", { regularFilesOnly: true })) {+ if (!entry.name.endsWith(".md")) continue;+ if (!entry.name.startsWith("ret-")) continue;+ if (!refs.visible(posix.join(BRAIN_RETIRED_REL, entry.name))) continue;+ allIds.push(entry.name.replace(/\.md$/, ""));+ }++ const totalNodes = allIds.length;+ const counts = allIds.map(inbound);+ const linkedNodes = counts.filter((c) => c > 0).length;+ const orphanNodes = totalNodes - linkedNodes;++ let meanBacklinks = 0;+ let medianBacklinks = 0;+ if (totalNodes > 0) {+ const sum = counts.reduce((a, b) => a + b, 0);+ meanBacklinks = Math.round((sum / totalNodes) * 100) / 100;+ const sorted = [...counts].toSorted((a, b) => a - b);+ const mid = Math.floor(sorted.length / 2);+ medianBacklinks =+ sorted.length % 2 === 0 ? (sorted[mid - 1]! + sorted[mid]!) / 2 : sorted[mid]!;+ }+ const linkDensity = totalNodes > 0 ? Math.round((linkedNodes / totalNodes) * 1000) / 1000 : 0;++ return Object.freeze({+ total_nodes: totalNodes,+ linked_nodes: linkedNodes,+ orphan_nodes: orphanNodes,+ mean_backlinks: meanBacklinks,+ median_backlinks: medianBacklinks,+ link_density: linkDensity,+ });+}++export function isEmpty(data: DigestData): boolean {+ return (+ data.new_unconfirmed.length === 0 &&+ data.confirmed.length === 0 &&+ data.retired.length === 0 &&+ data.confidence_shifts.length === 0 &&+ data.contradictions.length === 0 &&+ data.most_applied.entries.length === 0 &&+ data.agent_summary.length === 0+ );+}++// ----- Filesystem scan helpers ---------------------------------------------++export interface PreferenceWithPath {+ readonly pref: BrainPreference;+ readonly path: string;+}diff --git a/src/core/brain/digest-collect.ts b/src/core/brain/digest-collect.tsnew file mode 100644index 00000000..fbfef7c1--- /dev/null+++ b/src/core/brain/digest-collect.ts@@ -0,0 +1,509 @@+/**+ * The digest's data collection (task 3.19): the fold over the+ * preferences, retired records and log window the digest reports on,+ * the filesystem scan helpers it reads through, and the confidence-shift+ * and contradiction extractors. Split from `digest.ts`.+ */++import { posix } from "node:path";+import { everyArtifactRefView, type ArtifactRefView } from "./artifact-ref-view.ts";+import { logEntriesAtReach, logEntryAtReach } from "./log-events-at-reach.ts";+import { buildBacklinkIndex } from "./backlinks.ts";+import { computeAgentSummary } from "./digest-agent-summary.ts";+import { findMergeCandidates } from "./merge-candidates.ts";+import { computeMostApplied } from "./most-applied.ts";+import { BRAIN_RETIRED_REL, brainDirs, vaultRelative } from "./paths.ts";+import { collectMaintenanceActions, type MaintenanceCollectError } from "./maintenance/collect.ts";+import { loadActiveMostAppliedSafe } from "./policy.ts";+import { normaliseWikilinkTarget } from "./wikilink.ts";+import { parseRetiredMeta } from "./preference.ts";+import {+ collectPreferences,+ PREFERENCE_ID_PREFIX,+ resolveOwnerScopeDelivery,+} from "./preferences-collect.ts";+import { isPreferenceVisible } from "./owner-scoped-facts.ts";+import { gatedOwnerScopeView } from "./owner-scope-view.ts";+import type { BrainLogEntry } from "./log.ts";+import { memoryFolderPages } from "./memory-pages.ts";+import { logDayReader } from "./log-days.ts";+import {+ BRAIN_APPLY_RESULT,+ BRAIN_LOG_EVENT_KIND,+ BRAIN_PREFERENCE_STATUS,+ BRAIN_RETIRED_REASON,+} from "./types.ts";+import type { BrainRetired } from "./types.ts";+import type {+ DigestData,+ DigestJsonConfidenceShift,+ DigestJsonConfirmed,+ DigestJsonContradiction,+ DigestJsonMostApplied,+ DigestJsonNewUnconfirmed,+ DigestJsonRetired,+} from "./digest-types.ts";+import type { PreferenceWithPath } from "./digest-analysis.ts";+import {+ computeConnectionHealth,+ pickTopApplied,+ pickTopReferenced,+ visibleBacklinkCount,+} from "./digest-analysis.ts";++export const ONE_DAY_MS = 24 * 60 * 60 * 1000;++export function collectDigestData(+ vault: string,+ since: Date,+ until: Date,+ agentScope: string | undefined,+ refs: ArtifactRefView,+): DigestData {+ const sinceMs = since.getTime();+ const untilMs = until.getTime();+ const inWindow = (iso: string | null): boolean => {+ if (!iso) return false;+ const t = Date.parse(iso);+ if (!Number.isFinite(t)) return false;+ return t >= sinceMs && t < untilMs;+ };++ // 1. Iterate preferences/ for unconfirmed (created_at in window) and+ // confirmed (confirmed_at in window).+ const preferences = readAllPreferences(vault, agentScope, refs);+ const new_unconfirmed: DigestJsonNewUnconfirmed[] = [];+ const confirmed: DigestJsonConfirmed[] = [];++ for (const { pref, path } of preferences) {+ if (pref.status === "unconfirmed" && inWindow(pref.created_at)) {+ new_unconfirmed.push({+ id: pref.id,+ topic: pref.topic,+ principle: pref.principle,+ scope: pref.scope ?? null,+ signal_count: pref.evidenced_by.length,+ unconfirmed_until: pref.unconfirmed_until,+ path: vaultRelative(path, vault),+ });+ }+ if (pref.status === "confirmed" && inWindow(pref.confirmed_at)) {+ confirmed.push({+ id: pref.id,+ topic: pref.topic,+ principle: pref.principle,+ scope: pref.scope ?? null,+ confirmed_at: pref.confirmed_at!,+ first_applied_artifact: findFirstAppliedArtifact(vault, pref.id, refs),+ });+ }+ }++ // 2. Iterate retired/ for entries retired in window.+ const retiredEntries: DigestJsonRetired[] = [];+ const retiredAll = readAllRetired(vault, agentScope, refs);+ for (const { ret, path } of retiredAll) {+ void path;+ if (inWindow(ret.retired_at)) {+ const daysStale = daysStaleFor(ret);+ retiredEntries.push({+ id: ret.id,+ topic: ret.topic,+ principle: ret.principle,+ scope: ret.scope ?? null,+ retired_at: ret.retired_at,+ reason: ret.retired_reason,+ days_stale: daysStale,+ });+ }+ }++ // 3 & 4. Confidence shifts and contradictions — degraded gracefully+ // when payload data is missing. The extractors look principles up+ // against the combined pref + retired index so the markdown renderer+ // can emit titled wikilinks; ids that resolve to neither map fall+ // back to an empty principle (and a bare `[[id]]` link).+ const idToPrinciple = new Map<string, string>();+ for (const { pref } of preferences) idToPrinciple.set(pref.id, pref.principle);+ for (const { ret } of retiredAll) idToPrinciple.set(ret.id, ret.principle);+ const logEntries = logEntriesAtReach(refs, readLogsInWindow(vault, since, until));+ // A shift or contradiction line is one string naming its preference+ // inside other text, so the event-level filter above cannot resolve it;+ // the parsed id is asked on its own. The id resolves through the Brain+ // id-directories, so the enforced ownership rule joins the reach view+ // for these rows - the same composed view the actions below are kept+ // through, so every section that reads past the windowed records asks+ // one question about what "hidden" means.+ const scopedRefs = everyArtifactRefView(gatedOwnerScopeView(vault, agentScope), refs);+ const confidenceShifts = extractConfidenceShifts(logEntries, idToPrinciple).filter((row) =>+ scopedRefs.visible(row.id),+ );+ const contradictions = extractContradictions(logEntries, idToPrinciple).filter((row) =>+ scopedRefs.visible(row.id),+ );++ // Stable ordering — id ascending so two runs on the same fixture+ // produce byte-identical output.+ new_unconfirmed.sort((a, b) => a.id.localeCompare(b.id));+ confirmed.sort((a, b) => a.id.localeCompare(b.id));+ retiredEntries.sort((a, b) => a.id.localeCompare(b.id));++ const top_applied = pickTopApplied(preferences);+ // Built once and shared with `computeConnectionHealth` below: both+ // read the same vault state within this digest run, so one+ // full-history backlink scan replaces two.+ const backlinkIndex = buildBacklinkIndex(vault, undefined, {+ withholdsPrivate: refs.withholdsPrivate === true,+ });+ const inbound = (id: string): number => visibleBacklinkCount(backlinkIndex, id, refs);+ const top_referenced = pickTopReferenced(inbound, preferences);+ // `merge_suggestions` reflects current vault state, not windowed+ // change. It is independent of `since`/`until` on purpose —+ // operators should see pending duplicates regardless of the digest+ // window. Excluded from `isEmpty` for the same reason.+ // Reuse the already-parsed preferences from the digest scan+ // instead of asking the detector to walk `Brain/preferences/`+ // a second time. Same on-disk state, single read.+ const preferenceObjects = preferences.map(({ pref }) => pref);+ const merge_suggestions = findMergeCandidates(vault, {+ preferences: preferenceObjects,+ }).map((c) => ({+ a: c.a,+ b: c.b,+ principle_a: c.principle_a,+ principle_b: c.principle_b,+ topic: c.topic,+ scope: c.scope,+ jaccard: c.jaccard,+ }));++ const agent_summary = computeAgentSummary(+ vault,+ since,+ until,+ refs.filtersNothing ? undefined : (e) => logEntryAtReach(refs, e) !== null,+ );++ // Most-applied (Nd) — mirrors the section in `Brain/active.md`.+ // The window length / limit come from `_brain.yaml`. A vault that has+ // never run `brain init` has no window to read and lands on the+ // documented defaults; a config that is PRESENT but unreadable raises,+ // because re-windowing this section silently changes which rules it+ // names while the digest still reports as healthy.+ //+ // Unlike `active.md`, nothing earlier on this path raises for us: the+ // owner-scope gate consulted by `readAllPreferences` above is the+ // integrity reader, which resolves to its strict fallback rather than+ // throwing. The split has to happen at this read.+ const { window_days: mostAppliedWindowDays, limit: mostAppliedLimit } =+ loadActiveMostAppliedSafe(vault);+ const activePrefs = preferences+ .filter(+ ({ pref }) =>+ pref.status === BRAIN_PREFERENCE_STATUS.confirmed ||+ pref.status === BRAIN_PREFERENCE_STATUS.quarantine,+ )+ .map(({ pref }) => pref);+ const mostAppliedEntries = computeMostApplied(vault, activePrefs, {+ now: until,+ windowDays: mostAppliedWindowDays,+ limit: mostAppliedLimit,+ withholdsPrivate: refs.withholdsPrivate === true,+ }).map((e) => ({+ id: e.preference.id,+ principle: e.preference.principle,+ scope: e.preference.scope ?? null,+ applied_in_window: e.applied_30d,+ }));+ const most_applied: DigestJsonMostApplied = {+ window_days: mostAppliedWindowDays,+ limit: mostAppliedLimit,+ entries: mostAppliedEntries,+ };++ // The collector's absorbed scan failures (review M10): observed here so+ // the digest can say why its actions list came back thin.+ const collectErrors: MaintenanceCollectError[] = [];++ // The actions list is collected vault-wide (lint demotions, dedup+ // candidates, merged-link rewrites), so a row can name a preference+ // every section beside it already withholds. The enforced ownership+ // rule therefore joins the reach view for these rows too - the+ // `scopedRefs` composed above for the shift and contradiction lines.+ // `gatedOwnerScopeView` is the same adapter `brain_doctor`'s+ // `suggested_actions` and the operator summary's `top_actions` ask+ // over the same collector output, so the sinks cannot disagree+ // about what "hidden" means. The composed predicate is threaded INTO+ // the collector, so it applies to the candidate inputs before the+ // scorer caps: hidden top-ranked rows take no slot a visible one+ // could fill, and a dedup count excludes hidden secondaries. It+ // hides nothing until `integrity.owner_scope_delivery` is `fail`+ // with a scope, so an unscoped digest stays byte-identical; under+ // `warn` it withholds nothing too, matching every section above.+ return {+ new_unconfirmed,+ confirmed,+ retired: retiredEntries,+ confidence_shifts: confidenceShifts,+ contradictions,+ top_applied,+ top_referenced,+ merge_suggestions,+ agent_summary,+ most_applied,+ connection_health: computeConnectionHealth(vault, inbound, preferences, refs),+ actions: scopedRefs.keep(+ collectMaintenanceActions(vault, {+ onError: (e) => collectErrors.push(e),+ visible: scopedRefs.visible,+ withholdsPrivate: refs.withholdsPrivate === true,+ }),+ (action) => [action.target],+ ),+ collect_errors: collectErrors,+ };+}++export function readAllPreferences(+ vault: string,+ agentScope: string | undefined,+ refs: ArtifactRefView,+): ReadonlyArray<PreferenceWithPath> {+ const dirs = brainDirs(vault);+ // Shared delivery-path walk (context-integrity-gates, Unit A). This+ // surface's listing is the strictest of the five - regular files only,+ // and only `pref-*` names - so both rules are passed as options rather+ // than unified away. The doctor reports corruption; digest skips+ // silently, which is what the collector's parse already does.+ return collectPreferences(dirs.preferences, {+ namePrefix: PREFERENCE_ID_PREFIX,+ regularFilesOnly: true,+ ownerScope: resolveOwnerScopeDelivery(vault, agentScope),+ })+ .entries.filter(({ path }) => refs.visible(vaultRelative(path, vault)))+ .map(({ pref, path }) => ({ pref, path }));+}++export interface RetiredWithPath {+ readonly ret: BrainRetired;+ readonly path: string;+}++/**+ * Retirement KEEPS ownership (context-integrity-gates, A7): a retired+ * memory is withdrawn from the active set, never published to every+ * agent. Same gate resolution as {@link readAllPreferences}, so an+ * unscoped digest is byte-identical.+ */+export function readAllRetired(+ vault: string,+ agentScope: string | undefined,+ refs: ArtifactRefView,+): ReadonlyArray<RetiredWithPath> {+ const scope = resolveOwnerScopeDelivery(vault, agentScope).enforcedScope;+ const out: RetiredWithPath[] = [];+ for (const entry of memoryFolderPages(vault, "retired", { regularFilesOnly: true })) {+ if (!entry.name.endsWith(".md")) continue;+ if (!entry.name.startsWith("ret-")) continue;+ if (!refs.visible(posix.join(BRAIN_RETIRED_REL, entry.name))) continue;+ const path = entry.path;+ try {+ const ret = parseRetiredMeta(entry.read()[0], path);+ if (scope !== null && !isPreferenceVisible(ret, scope)) continue;+ out.push({ ret, path });+ } catch {+ // ditto+ }+ }+ return out;+}++export function readLogsInWindow(+ vault: string,+ since: Date,+ until: Date,+): ReadonlyArray<BrainLogEntry> {+ const sinceIso = since.toISOString();+ const untilIso = until.toISOString();+ // Restrict scans to dates intersecting the window — but we err+ // permissive (one day before / after) to avoid TZ off-by-ones.+ // Shard-aware (Memory Integrity Suite): dates come from listLogDates+ // and entries arrive merged across device shards via readLogDay.+ const sinceDay = sinceIso.slice(0, 10);+ const untilDay = untilIso.slice(0, 10);+ const out: BrainLogEntry[] = [];+ const log = logDayReader(vault);+ for (const date of log.dates) {+ if (date < addDays(sinceDay, -1)) continue;+ if (date > addDays(untilDay, 1)) continue;+ const { entries } = log.day(date);+ for (const e of entries) {+ if (e.timestamp >= sinceIso && e.timestamp < untilIso) {+ out.push(e);+ }+ }+ }+ out.sort((a, b) => a.timestamp.localeCompare(b.timestamp));+ return out;+}++export function addDays(day: string, delta: number): string {+ const t = Date.parse(`${day}T00:00:00Z`);+ if (!Number.isFinite(t)) return day;+ return new Date(t + delta * ONE_DAY_MS).toISOString().slice(0, 10);+}++/**+ * Best-effort lookup of the artifact wikilink for the first `applied`+ * apply-evidence event against a preference id. Returns null if no+ * applied evidence is found — e.g. a preference that was force-confirmed+ * without ever being applied. This matches design doc §8.2 example.+ */+export function findFirstAppliedArtifact(+ vault: string,+ prefId: string,+ refs: ArtifactRefView,+): string | null {+ const log = logDayReader(vault);+ for (const date of log.dates) {+ const { entries } = log.day(date);+ for (const e of logEntriesAtReach(refs, entries)) {+ if (e.eventType !== BRAIN_LOG_EVENT_KIND.applyEvidence) continue;+ if (e.body["result"] !== BRAIN_APPLY_RESULT.applied) continue;+ const prefPayload = e.body["preference"];+ if (typeof prefPayload === "string" && refersTo(prefPayload, prefId)) {+ const artifact = e.body["artifact"];+ if (typeof artifact === "string") return artifact;+ }+ }+ }+ return null;+}++export function refersTo(payload: string, prefId: string): boolean {+ return normaliseWikilinkTarget(payload) === prefId;+}++export function daysStaleFor(ret: BrainRetired): number | null {+ // For `stale-no-evidence`, the "days stale" is the gap between+ // `retired_at` and `last_evidence_at` (or `created_at` if there is+ // no evidence at all). Other reasons get null — the field is only+ // meaningful under stale-no-evidence per §8.2 example. We still+ // emit non-null for completeness on rebutted / expired-unconfirmed+ // when computable, but only for stale-no-evidence is it the canonical+ // metric the digest's "(91 days)" parenthetical refers to.+ if (ret.retired_reason !== BRAIN_RETIRED_REASON.staleNoEvidence) return null;+ const start = ret.last_evidence_at ?? ret.created_at;+ const startMs = Date.parse(start);+ const endMs = Date.parse(ret.retired_at);+ if (!Number.isFinite(startMs) || !Number.isFinite(endMs)) return null;+ return Math.max(0, Math.floor((endMs - startMs) / ONE_DAY_MS));+}++// ----- Confidence shifts & contradictions ----------------------------------+//+// Task 3 (`dream.ts`) is in progress as we ship this. It is the only+// component that can authoritatively emit confidence transitions and+// contradictions; without its payload data we cannot reconstruct+// transitions from filesystem state alone (the current `confidence`+// field has no `from` value to compare against). Per the §15 Task 4+// spec, the digest tolerates the absent payload as a graceful empty.+//+// When dream eventually emits these in its run summary, the parsers+// below will pick them up because we look in flexible payload shapes+// (the `dream` event's bullet list).++export function extractConfidenceShifts(+ entries: ReadonlyArray<BrainLogEntry>,+ idToPrinciple: ReadonlyMap<string, string>,+): ReadonlyArray<DigestJsonConfidenceShift> {+ const out: DigestJsonConfidenceShift[] = [];+ for (const e of entries) {+ if (e.eventType !== BRAIN_LOG_EVENT_KIND.dream) continue;+ // Pattern A: a `confidence_shifts` array, each item like+ // `[[pref-foo]] medium -> high (applied: 11, violated: 0)`.+ const shifts = e.body["confidence_shifts"];+ if (Array.isArray(shifts)) {+ for (const raw of shifts) {+ const parsed = parseShiftLine(raw, idToPrinciple);+ if (parsed) out.push(parsed);+ }+ }+ }+ return out;+}++export function parseShiftLine(+ raw: string,+ idToPrinciple: ReadonlyMap<string, string>,+): DigestJsonConfidenceShift | null {+ // Tolerant parser: accept `[[pref-x]] medium -> high (applied: N, violated: M)`+ // and variations (en-dash / em-dash for arrow, missing parens).+ const m = /^\s*(?:\[\[([^\]]+)\]\]|(\S+))\s+(\w+)\s*(?:->|→)\s*(\w+)(?:\s*\(([^)]*)\))?/.exec(+ raw,+ );+ if (!m) return null;+ const idRaw = (m[1] ?? m[2])!.split(/[|#]/)[0]!.trim();+ if (!idRaw) return null;+ const from = m[3]!;+ const to = m[4]!;+ let applied: number | null = null;+ let violated: number | null = null;+ if (m[5]) {+ const appMatch = /applied\s*[:=]?\s*(\d+)/i.exec(m[5]);+ if (appMatch) applied = parseInt(appMatch[1]!, 10);+ const violMatch = /violated\s*[:=]?\s*(\d+)/i.exec(m[5]);+ if (violMatch) violated = parseInt(violMatch[1]!, 10);+ }+ return {+ id: idRaw,+ principle: idToPrinciple.get(idRaw) ?? "",+ from,+ to,+ applied_count: applied,+ violated_count: violated,+ };+}++export function extractContradictions(+ entries: ReadonlyArray<BrainLogEntry>,+ idToPrinciple: ReadonlyMap<string, string>,+): ReadonlyArray<DigestJsonContradiction> {+ const out: DigestJsonContradiction[] = [];+ for (const e of entries) {+ if (e.eventType !== BRAIN_LOG_EVENT_KIND.dream) continue;+ const list = e.body["contradictions"];+ if (Array.isArray(list)) {+ for (const raw of list) {+ const parsed = parseContradictionLine(raw, idToPrinciple);+ if (parsed) out.push(parsed);+ }+ }+ }+ return out;+}++export function parseContradictionLine(+ raw: string,+ idToPrinciple: ReadonlyMap<string, string>,+): DigestJsonContradiction | null {+ // Best-effort: extract a wikilink as id and treat the rest as topic+ // or description. A missing wikilink means we cannot anchor the+ // contradiction to a preference; skip rather than fabricate.+ const wm = /\[\[([^\]]+)\]\]/.exec(raw);+ if (!wm) return null;+ const id = wm[1]!.split(/[|#]/)[0]!.trim();+ const description = raw.replace(wm[0], "").trim() || raw.trim();+ // The line may carry `(topic: foo)` — pull it out if present.+ let topic: string | null = null;+ const tm = /topic\s*[:=]\s*([A-Za-z0-9_-]+)/.exec(description);+ if (tm) topic = tm[1]!;+ return {+ id,+ principle: idToPrinciple.get(id) ?? "",+ topic,+ description,+ };+}++// ----- Markdown rendering --------------------------------------------------diff --git a/src/core/brain/digest-types.ts b/src/core/brain/digest-types.tsnew file mode 100644index 00000000..9ec583f3--- /dev/null+++ b/src/core/brain/digest-types.ts@@ -0,0 +1,307 @@+/**+ * The digest's public contract and its shared fold shape (task 3.19):+ * the format, options and result the entry point answers, the JSON+ * types every digest surface renders, and the `DigestData` fold the+ * collection, the analysis and the markdown renderer pass between+ * them. Split from `digest.ts`; that module re-exports the public+ * types so every import site keeps its specifier.+ */++import { type AgentSummaryEntry } from "./digest-agent-summary.ts";+import {+ type MaintenanceCollectError,+ type MaintenanceCollectSignal,+} from "./maintenance/collect.ts";+import type { ActionItem } from "./maintenance/action-scorer.ts";+import { type LinkOutputFormat } from "./wikilink.ts";+import type { BrainConfidence, TrustVerdict } from "./types.ts";++// ----- Public types ---------------------------------------------------------++export type DigestFormat = "markdown" | "json";++export interface RenderDigestOptions {+ /** Inclusive lower bound. Defaults to `until - 24h`. */+ readonly since?: Date;+ /** Exclusive upper bound. Defaults to `new Date()`. */+ readonly until?: Date;+ /** Output format. Defaults to `markdown`. */+ readonly format?: DigestFormat;+ /** Presentation link format for Markdown output. Defaults to Obsidian wikilinks. */+ readonly linkOutputFormat?: LinkOutputFormat;+ /**+ * Injection seam for deterministic tests: defaults the generated_at+ * timestamp. Production callers do not pass this — the renderer+ * picks `new Date()` itself.+ */+ readonly now?: Date;+ /**+ * Optional doctor result (v0.10.16). When supplied, `trust_verdict`+ * lands in the JSON payload and a `## Trust` section renders in+ * markdown.+ */+ readonly doctorResult?: import("./doctor.ts").RunDoctorResult;+ /**+ * Optional dream summary (v0.10.16). When supplied,+ * `uncertain_count` and `quarantined_count` reflect the+ * counterparts on the summary instead of defaulting to zero.+ */+ readonly dreamSummary?: import("./dream.ts").DreamRunSummary;+ /**+ * Owner scope for delivery isolation (context-integrity-gates, Unit+ * A). Enforced only when `integrity.owner_scope_delivery` is `fail`;+ * omitted, or under the default `off`, nothing is filtered and the+ * output is byte-identical to a vault without the gate.+ */+ readonly agentScope?: string;+ /**+ * May this reader see the record at a vault-relative path? A preference+ * or retired record it answers `false` for is treated as absent: its+ * rows, its counts, the log events naming it and the backlinks it is+ * the source of all go. Omitted, nothing is filtered and the output is+ * byte-identical to a digest without the option.+ */+ readonly readable?: (rel: string) => boolean;+ /**+ * The reader is below local reach: log events of the store's `private`+ * partition are withheld from every section, counts included.+ */+ readonly withholdsPrivate?: boolean;+}++export interface RenderDigestResult {+ /** Rendered Markdown (default) or JSON body. */+ readonly content: string;+ /** True when every section is empty (single-line output / `summary.empty`). */+ readonly empty: boolean;+}++// ----- JSON shape (mirrors §8.2) -------------------------------------------++export interface DigestJsonNewUnconfirmed {+ readonly id: string;+ readonly topic: string;+ readonly principle: string;+ readonly scope: string | null;+ readonly signal_count: number;+ readonly unconfirmed_until: string;+ readonly path: string;+}++export interface DigestJsonConfirmed {+ readonly id: string;+ readonly topic: string;+ readonly principle: string;+ readonly scope: string | null;+ readonly confirmed_at: string;+ readonly first_applied_artifact: string | null;+}++export interface DigestJsonRetired {+ readonly id: string;+ readonly topic: string;+ readonly principle: string;+ readonly scope: string | null;+ readonly retired_at: string;+ readonly reason: string;+ readonly days_stale: number | null;+}++export interface DigestJsonConfidenceShift {+ readonly id: string;+ /**+ * Human-readable title sourced from the referenced pref or retired's+ * `principle` field. Empty string when the id does not resolve to a+ * known artifact (the markdown renderer falls back to bare `[[id]]`).+ */+ readonly principle: string;+ readonly from: BrainConfidence | string;+ readonly to: BrainConfidence | string;+ readonly applied_count: number | null;+ readonly violated_count: number | null;+}++export interface DigestJsonContradiction {+ readonly id: string;+ /** See {@link DigestJsonConfidenceShift.principle}. */+ readonly principle: string;+ readonly topic: string | null;+ readonly description: string;+}++/**+ * "Hot" preference by lifetime evidence-application count. Reflects+ * the rules carrying real weight right now, regardless of whether+ * anything about them changed in the window. Source: current state+ * of `Brain/preferences/` (confirmed + quarantine).+ */+export interface DigestJsonTopApplied {+ readonly id: string;+ readonly topic: string;+ readonly principle: string;+ readonly scope: string | null;+ readonly applied_count: number;+ readonly violated_count: number;+ readonly confidence: BrainConfidence | string;+ readonly status: string;+}++/**+ * Preference with the most inbound wikilink references in the vault.+ * Source: the lifetime backlink index over preferences/retired/log.+ * Higher count → the rule is mentioned in more contexts.+ */+export interface DigestJsonTopReferenced {+ readonly id: string;+ readonly topic: string;+ readonly principle: string;+ readonly scope: string | null;+ readonly backlink_count: number;+}++/**+ * Most-applied entry: one preference + its applied-in-window count.+ * Drives the `Most-applied (Nd)` section in `brain_digest` Markdown+ * and the mirrored block in the JSON output. The window length and+ * limit come from `_brain.yaml:active.most_applied_*`.+ */+export interface DigestJsonMostAppliedEntry {+ readonly id: string;+ readonly principle: string;+ readonly scope: string | null;+ readonly applied_in_window: number;+}++export interface DigestJsonMostApplied {+ readonly window_days: number;+ readonly limit: number;+ readonly entries: ReadonlyArray<DigestJsonMostAppliedEntry>;+}++export interface DigestJsonAgentSummary {+ readonly agent: string;+ readonly total_events: number;+ readonly feedback_count: number;+ readonly apply_evidence_count: number;+ readonly note_count: number;+ readonly confirmed_attributed: number;+ readonly retired_attributed: number;+}++/**+ * Near-duplicate pair surfaced for operator review. Detected by+ * `findMergeCandidates`. Reflects current vault state, not windowed+ * change — does not gate the `isEmpty` predicate.+ */+export interface DigestJsonMergeSuggestion {+ readonly a: string;+ readonly b: string;+ readonly principle_a: string;+ readonly principle_b: string;+ readonly topic: string;+ readonly scope: string | null;+ readonly jaccard: number;+}++/**+ * Vault-level connection-density health metric (v0.10.14).+ * Surfaces the ratio of linked notes to total notes, orphan count,+ * and backlink distribution — answering whether the vault grows as a+ * network of ideas or as an "organized graveyard".+ */+export interface DigestJsonConnectionHealth {+ readonly total_nodes: number;+ readonly linked_nodes: number;+ readonly orphan_nodes: number;+ readonly mean_backlinks: number;+ readonly median_backlinks: number;+ readonly link_density: number;+}++export interface DigestJson {+ readonly schema_version: 1;+ readonly generated_at: string;+ readonly window: { readonly since: string; readonly until: string };+ readonly summary: {+ readonly new_unconfirmed_count: number;+ readonly confirmed_count: number;+ readonly retired_count: number;+ readonly confidence_shift_count: number;+ readonly contradiction_count: number;+ readonly empty: boolean;+ };+ readonly new_unconfirmed: ReadonlyArray<DigestJsonNewUnconfirmed>;+ readonly confirmed: ReadonlyArray<DigestJsonConfirmed>;+ readonly retired: ReadonlyArray<DigestJsonRetired>;+ readonly confidence_shifts: ReadonlyArray<DigestJsonConfidenceShift>;+ readonly contradictions: ReadonlyArray<DigestJsonContradiction>;+ readonly top_applied: ReadonlyArray<DigestJsonTopApplied>;+ readonly top_referenced: ReadonlyArray<DigestJsonTopReferenced>;+ readonly merge_suggestions: ReadonlyArray<DigestJsonMergeSuggestion>;+ readonly agent_summary: ReadonlyArray<DigestJsonAgentSummary>;+ /**+ * Window-scoped most-applied list (v0.10.11). Mirrors the+ * `Most-applied (Nd)` section of `Brain/active.md` and uses the+ * same `_brain.yaml:active.most_applied_*` settings.+ */+ readonly most_applied: DigestJsonMostApplied;+ /**+ * Vault-level connection-density health metric (v0.10.14).+ * Independent of the window — reflects current vault state.+ */+ readonly connection_health: DigestJsonConnectionHealth;+ /**+ * Ranked maintenance actions (v0.10.15). Aggregates page-dedup+ * candidates, lint demotions / merged-link rewrites, and token+ * footprint excess; deterministic ordering. Empty when nothing+ * needs doing. Independent of the window.+ */+ readonly actions: ReadonlyArray<ActionItem>;+ /**+ * The maintenance scans that refused while the digest was collected+ * (review M10), rendered as `{scan, message}` rows - the same shape the+ * operator-summary and doctor rows carry. A thin `actions` list must be+ * readable as healthy rather than indistinguishable from a scan that+ * failed. Present only when at least one scan refused, so a clean+ * payload stays byte-identical.+ */+ readonly collect_errors?: ReadonlyArray<{+ readonly scan: MaintenanceCollectSignal;+ readonly message: string;+ }>;+ /**+ * Aggregate vault trust verdict (v0.10.16). Absent when no+ * doctor input was threaded into the digest call; consumers that+ * only need the legacy preference-and-signal sections can ignore+ * the field.+ */+ readonly trust_verdict?: TrustVerdict;+ /**+ * Count of dream-pass uncertain entries in the most recent run+ * (v0.10.16). Zero when no dream input was provided.+ */+ readonly uncertain_count: number;+ /**+ * Count of dream-pass signal clusters held back by the+ * self-approval guardrail in the most recent run (v0.10.16).+ * Zero when no dream input was provided.+ */+ readonly quarantined_count: number;+}++export interface DigestData {+ readonly new_unconfirmed: ReadonlyArray<DigestJsonNewUnconfirmed>;+ readonly confirmed: ReadonlyArray<DigestJsonConfirmed>;+ readonly retired: ReadonlyArray<DigestJsonRetired>;+ readonly confidence_shifts: ReadonlyArray<DigestJsonConfidenceShift>;+ readonly contradictions: ReadonlyArray<DigestJsonContradiction>;+ readonly top_applied: ReadonlyArray<DigestJsonTopApplied>;+ readonly top_referenced: ReadonlyArray<DigestJsonTopReferenced>;+ readonly merge_suggestions: ReadonlyArray<DigestJsonMergeSuggestion>;+ readonly agent_summary: ReadonlyArray<AgentSummaryEntry>;+ readonly most_applied: DigestJsonMostApplied;+ readonly connection_health: DigestJsonConnectionHealth;+ readonly actions: ReadonlyArray<ActionItem>;+ /** Raw collected failures; rendered on the wire as `{scan, message}` rows. */+ readonly collect_errors: ReadonlyArray<MaintenanceCollectError>;+}diff --git a/src/core/brain/digest.ts b/src/core/brain/digest.tsindex 6882ce31..1f7fc4bd 100644--- a/src/core/brain/digest.ts+++ b/src/core/brain/digest.ts@@ -35,326 +35,40 @@* retired entries, the log, or the snapshots.*/-import { posix } from "node:path";--import { everyArtifactRefView, readerRefView, type ArtifactRefView } from "./artifact-ref-view.ts";-import { logEntriesAtReach, logEntryAtReach } from "./log-events-at-reach.ts";-import { buildBacklinkIndex, type BacklinkIndex } from "./backlinks.ts";-import { computeAgentSummary, type AgentSummaryEntry } from "./digest-agent-summary.ts";-import { findMergeCandidates } from "./merge-candidates.ts";-import { computeMostApplied } from "./most-applied.ts";-import { BRAIN_RETIRED_REL, brainDirs, vaultRelative } from "./paths.ts";-import {- closedCollectError,- collectMaintenanceActions,- type MaintenanceCollectError,- type MaintenanceCollectSignal,-} from "./maintenance/collect.ts";-import type { ActionItem } from "./maintenance/action-scorer.ts";-import { loadActiveMostAppliedSafe } from "./policy.ts";-import { normaliseWikilinkTarget, renderPrefLink, type LinkOutputFormat } from "./wikilink.ts";-import { parseRetiredMeta } from "./preference.ts";-import {- collectPreferences,- PREFERENCE_ID_PREFIX,- resolveOwnerScopeDelivery,-} from "./preferences-collect.ts";-import { isPreferenceVisible } from "./owner-scoped-facts.ts";-import { gatedOwnerScopeView } from "./owner-scope-view.ts";-import type { BrainLogEntry } from "./log.ts";-import { memoryFolderPages } from "./memory-pages.ts";-import { logDayReader } from "./log-days.ts";-import {- BRAIN_APPLY_RESULT,- BRAIN_LOG_EVENT_KIND,- BRAIN_PREFERENCE_STATUS,- BRAIN_RETIRED_REASON,-} from "./types.ts";-import type { BrainConfidence, BrainPreference, BrainRetired, TrustVerdict } from "./types.ts";--// ----- Public types -----------------------------------------------------------export type DigestFormat = "markdown" | "json";--export interface RenderDigestOptions {- /** Inclusive lower bound. Defaults to `until - 24h`. */- readonly since?: Date;- /** Exclusive upper bound. Defaults to `new Date()`. */- readonly until?: Date;- /** Output format. Defaults to `markdown`. */- readonly format?: DigestFormat;- /** Presentation link format for Markdown output. Defaults to Obsidian wikilinks. */- readonly linkOutputFormat?: LinkOutputFormat;- /**- * Injection seam for deterministic tests: defaults the generated_at- * timestamp. Production callers do not pass this — the renderer- * picks `new Date()` itself.- */- readonly now?: Date;- /**- * Optional doctor result (v0.10.16). When supplied, `trust_verdict`- * lands in the JSON payload and a `## Trust` section renders in- * markdown.- */- readonly doctorResult?: import("./doctor.ts").RunDoctorResult;- /**- * Optional dream summary (v0.10.16). When supplied,- * `uncertain_count` and `quarantined_count` reflect the- * counterparts on the summary instead of defaulting to zero.- */- readonly dreamSummary?: import("./dream.ts").DreamRunSummary;- /**- * Owner scope for delivery isolation (context-integrity-gates, Unit- * A). Enforced only when `integrity.owner_scope_delivery` is `fail`;- * omitted, or under the default `off`, nothing is filtered and the- * output is byte-identical to a vault without the gate.- */- readonly agentScope?: string;- /**- * May this reader see the record at a vault-relative path? A preference- * or retired record it answers `false` for is treated as absent: its- * rows, its counts, the log events naming it and the backlinks it is- * the source of all go. Omitted, nothing is filtered and the output is- * byte-identical to a digest without the option.- */- readonly readable?: (rel: string) => boolean;- /**- * The reader is below local reach: log events of the store's `private`- * partition are withheld from every section, counts included.- */- readonly withholdsPrivate?: boolean;-}--export interface RenderDigestResult {- /** Rendered Markdown (default) or JSON body. */- readonly content: string;- /** True when every section is empty (single-line output / `summary.empty`). */- readonly empty: boolean;-}--// ----- JSON shape (mirrors §8.2) ---------------------------------------------export interface DigestJsonNewUnconfirmed {- readonly id: string;- readonly topic: string;- readonly principle: string;- readonly scope: string | null;- readonly signal_count: number;- readonly unconfirmed_until: string;- readonly path: string;-}--export interface DigestJsonConfirmed {- readonly id: string;- readonly topic: string;- readonly principle: string;- readonly scope: string | null;- readonly confirmed_at: string;- readonly first_applied_artifact: string | null;-}--export interface DigestJsonRetired {- readonly id: string;- readonly topic: string;- readonly principle: string;- readonly scope: string | null;- readonly retired_at: string;- readonly reason: string;- readonly days_stale: number | null;-}--export interface DigestJsonConfidenceShift {- readonly id: string;- /**- * Human-readable title sourced from the referenced pref or retired's- * `principle` field. Empty string when the id does not resolve to a- * known artifact (the markdown renderer falls back to bare `[[id]]`).- */- readonly principle: string;- readonly from: BrainConfidence | string;- readonly to: BrainConfidence | string;- readonly applied_count: number | null;- readonly violated_count: number | null;-}--export interface DigestJsonContradiction {- readonly id: string;- /** See {@link DigestJsonConfidenceShift.principle}. */- readonly principle: string;- readonly topic: string | null;- readonly description: string;-}--/**- * "Hot" preference by lifetime evidence-application count. Reflects- * the rules carrying real weight right now, regardless of whether- * anything about them changed in the window. Source: current state- * of `Brain/preferences/` (confirmed + quarantine).- */-export interface DigestJsonTopApplied {- readonly id: string;- readonly topic: string;- readonly principle: string;- readonly scope: string | null;- readonly applied_count: number;- readonly violated_count: number;- readonly confidence: BrainConfidence | string;- readonly status: string;-}--/**- * Preference with the most inbound wikilink references in the vault.- * Source: the lifetime backlink index over preferences/retired/log.- * Higher count → the rule is mentioned in more contexts.- */-export interface DigestJsonTopReferenced {- readonly id: string;- readonly topic: string;- readonly principle: string;- readonly scope: string | null;- readonly backlink_count: number;-}--/**- * Most-applied entry: one preference + its applied-in-window count.- * Drives the `Most-applied (Nd)` section in `brain_digest` Markdown- * and the mirrored block in the JSON output. The window length and- * limit come from `_brain.yaml:active.most_applied_*`.- */-export interface DigestJsonMostAppliedEntry {- readonly id: string;- readonly principle: string;- readonly scope: string | null;- readonly applied_in_window: number;-}--export interface DigestJsonMostApplied {- readonly window_days: number;- readonly limit: number;- readonly entries: ReadonlyArray<DigestJsonMostAppliedEntry>;-}--export interface DigestJsonAgentSummary {- readonly agent: string;- readonly total_events: number;- readonly feedback_count: number;- readonly apply_evidence_count: number;- readonly note_count: number;- readonly confirmed_attributed: number;- readonly retired_attributed: number;-}--/**- * Near-duplicate pair surfaced for operator review. Detected by- * `findMergeCandidates`. Reflects current vault state, not windowed- * change — does not gate the `isEmpty` predicate.- */-export interface DigestJsonMergeSuggestion {- readonly a: string;- readonly b: string;- readonly principle_a: string;- readonly principle_b: string;- readonly topic: string;- readonly scope: string | null;- readonly jaccard: number;-}--/**- * Vault-level connection-density health metric (v0.10.14).- * Surfaces the ratio of linked notes to total notes, orphan count,- * and backlink distribution — answering whether the vault grows as a- * network of ideas or as an "organized graveyard".- */-export interface DigestJsonConnectionHealth {- readonly total_nodes: number;- readonly linked_nodes: number;- readonly orphan_nodes: number;- readonly mean_backlinks: number;- readonly median_backlinks: number;- readonly link_density: number;-}--export interface DigestJson {- readonly schema_version: 1;- readonly generated_at: string;- readonly window: { readonly since: string; readonly until: string };- readonly summary: {- readonly new_unconfirmed_count: number;- readonly confirmed_count: number;- readonly retired_count: number;- readonly confidence_shift_count: number;- readonly contradiction_count: number;- readonly empty: boolean;- };- readonly new_unconfirmed: ReadonlyArray<DigestJsonNewUnconfirmed>;- readonly confirmed: ReadonlyArray<DigestJsonConfirmed>;- readonly retired: ReadonlyArray<DigestJsonRetired>;- readonly confidence_shifts: ReadonlyArray<DigestJsonConfidenceShift>;- readonly contradictions: ReadonlyArray<DigestJsonContradiction>;- readonly top_applied: ReadonlyArray<DigestJsonTopApplied>;- readonly top_referenced: ReadonlyArray<DigestJsonTopReferenced>;- readonly merge_suggestions: ReadonlyArray<DigestJsonMergeSuggestion>;- readonly agent_summary: ReadonlyArray<DigestJsonAgentSummary>;- /**- * Window-scoped most-applied list (v0.10.11). Mirrors the- * `Most-applied (Nd)` section of `Brain/active.md` and uses the- * same `_brain.yaml:active.most_applied_*` settings.- */- readonly most_applied: DigestJsonMostApplied;- /**- * Vault-level connection-density health metric (v0.10.14).- * Independent of the window — reflects current vault state.- */- readonly connection_health: DigestJsonConnectionHealth;- /**- * Ranked maintenance actions (v0.10.15). Aggregates page-dedup- * candidates, lint demotions / merged-link rewrites, and token- * footprint excess; deterministic ordering. Empty when nothing- * needs doing. Independent of the window.- */- readonly actions: ReadonlyArray<ActionItem>;- /**- * The maintenance scans that refused while the digest was collected- * (review M10), rendered as `{scan, message}` rows - the same shape the- * operator-summary and doctor rows carry. A thin `actions` list must be- * readable as healthy rather than indistinguishable from a scan that- * failed. Present only when at least one scan refused, so a clean- * payload stays byte-identical.- */- readonly collect_errors?: ReadonlyArray<{- readonly scan: MaintenanceCollectSignal;- readonly message: string;- }>;- /**- * Aggregate vault trust verdict (v0.10.16). Absent when no- * doctor input was threaded into the digest call; consumers that- * only need the legacy preference-and-signal sections can ignore- * the field.- */- readonly trust_verdict?: TrustVerdict;- /**- * Count of dream-pass uncertain entries in the most recent run- * (v0.10.16). Zero when no dream input was provided.- */- readonly uncertain_count: number;- /**- * Count of dream-pass signal clusters held back by the- * self-approval guardrail in the most recent run (v0.10.16).- * Zero when no dream input was provided.- */- readonly quarantined_count: number;-}--/**- * How many entries to keep in each "hot" digest section. Small fixed- * value — the digest is meant to be skimmable, not exhaustive.- */-const HOT_SECTION_LIMIT = 5;+import { readerRefView } from "./artifact-ref-view.ts";+import { closedCollectError } from "./maintenance/collect.ts";+import { renderPrefLink, type LinkOutputFormat } from "./wikilink.ts";+import { BRAIN_RETIRED_REASON } from "./types.ts";+import type {+ DigestData,+ DigestJson,+ RenderDigestOptions,+ RenderDigestResult,+} from "./digest-types.ts";+import { ONE_DAY_MS, collectDigestData } from "./digest-collect.ts";+import { isEmpty } from "./digest-analysis.ts";++export type {+ DigestFormat,+ RenderDigestOptions,+ RenderDigestResult,+ DigestJsonNewUnconfirmed,+ DigestJsonConfirmed,+ DigestJsonRetired,+ DigestJsonConfidenceShift,+ DigestJsonContradiction,+ DigestJsonTopApplied,+ DigestJsonTopReferenced,+ DigestJsonMostAppliedEntry,+ DigestJsonMostApplied,+ DigestJsonAgentSummary,+ DigestJsonMergeSuggestion,+ DigestJsonConnectionHealth,+ DigestJson,+} from "./digest-types.ts";// ----- Entry point -----------------------------------------------------------const ONE_DAY_MS = 24 * 60 * 60 * 1000;-export function renderDigest(vault: string, opts: RenderDigestOptions = {}): RenderDigestResult {const format = opts.format ?? "markdown";const now = opts.now ?? new Date();@@ -467,602 +181,6 @@ function renderTrustSection(// ----- Data collection -------------------------------------------------------interface DigestData {- readonly new_unconfirmed: ReadonlyArray<DigestJsonNewUnconfirmed>;- readonly confirmed: ReadonlyArray<DigestJsonConfirmed>;- readonly retired: ReadonlyArray<DigestJsonRetired>;- readonly confidence_shifts: ReadonlyArray<DigestJsonConfidenceShift>;- readonly contradictions: ReadonlyArray<DigestJsonContradiction>;- readonly top_applied: ReadonlyArray<DigestJsonTopApplied>;- readonly top_referenced: ReadonlyArray<DigestJsonTopReferenced>;- readonly merge_suggestions: ReadonlyArray<DigestJsonMergeSuggestion>;- readonly agent_summary: ReadonlyArray<AgentSummaryEntry>;- readonly most_applied: DigestJsonMostApplied;- readonly connection_health: DigestJsonConnectionHealth;- readonly actions: ReadonlyArray<ActionItem>;- /** Raw collected failures; rendered on the wire as `{scan, message}` rows. */- readonly collect_errors: ReadonlyArray<MaintenanceCollectError>;-}--function collectDigestData(- vault: string,- since: Date,- until: Date,- agentScope: string | undefined,- refs: ArtifactRefView,-): DigestData {- const sinceMs = since.getTime();- const untilMs = until.getTime();- const inWindow = (iso: string | null): boolean => {- if (!iso) return false;- const t = Date.parse(iso);- if (!Number.isFinite(t)) return false;- return t >= sinceMs && t < untilMs;- };-- // 1. Iterate preferences/ for unconfirmed (created_at in window) and- // confirmed (confirmed_at in window).- const preferences = readAllPreferences(vault, agentScope, refs);- const new_unconfirmed: DigestJsonNewUnconfirmed[] = [];- const confirmed: DigestJsonConfirmed[] = [];-- for (const { pref, path } of preferences) {- if (pref.status === "unconfirmed" && inWindow(pref.created_at)) {- new_unconfirmed.push({- id: pref.id,- topic: pref.topic,- principle: pref.principle,- scope: pref.scope ?? null,- signal_count: pref.evidenced_by.length,- unconfirmed_until: pref.unconfirmed_until,- path: vaultRelative(path, vault),- });- }- if (pref.status === "confirmed" && inWindow(pref.confirmed_at)) {- confirmed.push({- id: pref.id,- topic: pref.topic,- principle: pref.principle,- scope: pref.scope ?? null,- confirmed_at: pref.confirmed_at!,- first_applied_artifact: findFirstAppliedArtifact(vault, pref.id, refs),- });- }- }-- // 2. Iterate retired/ for entries retired in window.- const retiredEntries: DigestJsonRetired[] = [];- const retiredAll = readAllRetired(vault, agentScope, refs);- for (const { ret, path } of retiredAll) {- void path;- if (inWindow(ret.retired_at)) {- const daysStale = daysStaleFor(ret);- retiredEntries.push({- id: ret.id,- topic: ret.topic,- principle: ret.principle,- scope: ret.scope ?? null,- retired_at: ret.retired_at,- reason: ret.retired_reason,- days_stale: daysStale,- });- }- }-- // 3 & 4. Confidence shifts and contradictions — degraded gracefully- // when payload data is missing. The extractors look principles up- // against the combined pref + retired index so the markdown renderer- // can emit titled wikilinks; ids that resolve to neither map fall- // back to an empty principle (and a bare `[[id]]` link).- const idToPrinciple = new Map<string, string>();- for (const { pref } of preferences) idToPrinciple.set(pref.id, pref.principle);- for (const { ret } of retiredAll) idToPrinciple.set(ret.id, ret.principle);- const logEntries = logEntriesAtReach(refs, readLogsInWindow(vault, since, until));- // A shift or contradiction line is one string naming its preference- // inside other text, so the event-level filter above cannot resolve it;- // the parsed id is asked on its own. The id resolves through the Brain- // id-directories, so the enforced ownership rule joins the reach view- // for these rows - the same composed view the actions below are kept- // through, so every section that reads past the windowed records asks- // one question about what "hidden" means.- const scopedRefs = everyArtifactRefView(gatedOwnerScopeView(vault, agentScope), refs);- const confidenceShifts = extractConfidenceShifts(logEntries, idToPrinciple).filter((row) =>- scopedRefs.visible(row.id),- );- const contradictions = extractContradictions(logEntries, idToPrinciple).filter((row) =>- scopedRefs.visible(row.id),- );-- // Stable ordering — id ascending so two runs on the same fixture- // produce byte-identical output.- new_unconfirmed.sort((a, b) => a.id.localeCompare(b.id));- confirmed.sort((a, b) => a.id.localeCompare(b.id));- retiredEntries.sort((a, b) => a.id.localeCompare(b.id));-- const top_applied = pickTopApplied(preferences);- // Built once and shared with `computeConnectionHealth` below: both- // read the same vault state within this digest run, so one- // full-history backlink scan replaces two.- const backlinkIndex = buildBacklinkIndex(vault, undefined, {- withholdsPrivate: refs.withholdsPrivate === true,- });- const inbound = (id: string): number => visibleBacklinkCount(backlinkIndex, id, refs);- const top_referenced = pickTopReferenced(inbound, preferences);- // `merge_suggestions` reflects current vault state, not windowed- // change. It is independent of `since`/`until` on purpose —- // operators should see pending duplicates regardless of the digest- // window. Excluded from `isEmpty` for the same reason.- // Reuse the already-parsed preferences from the digest scan- // instead of asking the detector to walk `Brain/preferences/`- // a second time. Same on-disk state, single read.- const preferenceObjects = preferences.map(({ pref }) => pref);- const merge_suggestions = findMergeCandidates(vault, {- preferences: preferenceObjects,- }).map((c) => ({- a: c.a,- b: c.b,- principle_a: c.principle_a,- principle_b: c.principle_b,- topic: c.topic,- scope: c.scope,- jaccard: c.jaccard,- }));-- const agent_summary = computeAgentSummary(- vault,- since,- until,- refs.filtersNothing ? undefined : (e) => logEntryAtReach(refs, e) !== null,- );-- // Most-applied (Nd) — mirrors the section in `Brain/active.md`.- // The window length / limit come from `_brain.yaml`. A vault that has- // never run `brain init` has no window to read and lands on the- // documented defaults; a config that is PRESENT but unreadable raises,- // because re-windowing this section silently changes which rules it- // names while the digest still reports as healthy.- //- // Unlike `active.md`, nothing earlier on this path raises for us: the- // owner-scope gate consulted by `readAllPreferences` above is the- // integrity reader, which resolves to its strict fallback rather than- // throwing. The split has to happen at this read.- const { window_days: mostAppliedWindowDays, limit: mostAppliedLimit } =- loadActiveMostAppliedSafe(vault);- const activePrefs = preferences- .filter(- ({ pref }) =>- pref.status === BRAIN_PREFERENCE_STATUS.confirmed ||- pref.status === BRAIN_PREFERENCE_STATUS.quarantine,- )- .map(({ pref }) => pref);- const mostAppliedEntries = computeMostApplied(vault, activePrefs, {- now: until,- windowDays: mostAppliedWindowDays,- limit: mostAppliedLimit,- withholdsPrivate: refs.withholdsPrivate === true,- }).map((e) => ({- id: e.preference.id,- principle: e.preference.principle,- scope: e.preference.scope ?? null,- applied_in_window: e.applied_30d,- }));- const most_applied: DigestJsonMostApplied = {- window_days: mostAppliedWindowDays,- limit: mostAppliedLimit,- entries: mostAppliedEntries,- };-- // The collector's absorbed scan failures (review M10): observed here so- // the digest can say why its actions list came back thin.- const collectErrors: MaintenanceCollectError[] = [];-- // The actions list is collected vault-wide (lint demotions, dedup- // candidates, merged-link rewrites), so a row can name a preference- // every section beside it already withholds. The enforced ownership- // rule therefore joins the reach view for these rows too - the- // `scopedRefs` composed above for the shift and contradiction lines.- // `gatedOwnerScopeView` is the same adapter `brain_doctor`'s- // `suggested_actions` and the operator summary's `top_actions` ask- // over the same collector output, so the sinks cannot disagree- // about what "hidden" means. The composed predicate is threaded INTO- // the collector, so it applies to the candidate inputs before the- // scorer caps: hidden top-ranked rows take no slot a visible one- // could fill, and a dedup count excludes hidden secondaries. It- // hides nothing until `integrity.owner_scope_delivery` is `fail`- // with a scope, so an unscoped digest stays byte-identical; under- // `warn` it withholds nothing too, matching every section above.- return {- new_unconfirmed,- confirmed,- retired: retiredEntries,- confidence_shifts: confidenceShifts,- contradictions,- top_applied,- top_referenced,- merge_suggestions,- agent_summary,- most_applied,- connection_health: computeConnectionHealth(vault, inbound, preferences, refs),- actions: scopedRefs.keep(- collectMaintenanceActions(vault, {- onError: (e) => collectErrors.push(e),- visible: scopedRefs.visible,- withholdsPrivate: refs.withholdsPrivate === true,- }),- (action) => [action.target],- ),- collect_errors: collectErrors,- };-}--function pickTopApplied(- preferences: ReadonlyArray<PreferenceWithPath>,-): ReadonlyArray<DigestJsonTopApplied> {- const active = preferences.filter(- ({ pref }) =>- (pref.status === BRAIN_PREFERENCE_STATUS.confirmed ||- pref.status === BRAIN_PREFERENCE_STATUS.quarantine) &&- pref.applied_count > 0,- );- active.sort((a, b) => {- const diff = b.pref.applied_count - a.pref.applied_count;- if (diff !== 0) return diff;- // Stable secondary key: id ascending. Without it the same input on- // two filesystems (different readdir order) could swap ties.- return a.pref.id.localeCompare(b.pref.id);- });- return active.slice(0, HOT_SECTION_LIMIT).map(({ pref }) => ({- id: pref.id,- topic: pref.topic,- principle: pref.principle,- scope: pref.scope ?? null,- applied_count: pref.applied_count,- violated_count: pref.violated_count,- confidence: pref.confidence,- status: pref.status,- }));-}--/**- * Inbound references to `target` whose source this reader may see. With- * nothing filtered it is the index's own count.- */-function visibleBacklinkCount(index: BacklinkIndex, target: string, refs: ArtifactRefView): number {- const sources = index.get(normaliseWikilinkTarget(target)) ?? [];- return refs.filtersNothing- ? sources.length- : sources.filter((ref) => refs.visible(ref.source)).length;-}--function pickTopReferenced(- inbound: (id: string) => number,- preferences: ReadonlyArray<PreferenceWithPath>,-): ReadonlyArray<DigestJsonTopReferenced> {- const scored = preferences- .map(({ pref }) => ({- pref,- count: inbound(pref.id),- }))- .filter((x) => x.count > 0);- scored.sort((a, b) => {- const diff = b.count - a.count;- if (diff !== 0) return diff;- return a.pref.id.localeCompare(b.pref.id);- });- return scored.slice(0, HOT_SECTION_LIMIT).map(({ pref, count }) => ({- id: pref.id,- topic: pref.topic,- principle: pref.principle,- scope: pref.scope ?? null,- backlink_count: count,- }));-}--/**- * Compute vault-level connection-density health metrics from the- * backlink index over all preferences and retired entries.- */-function computeConnectionHealth(- vault: string,- inbound: (id: string) => number,- preferences: ReadonlyArray<PreferenceWithPath>,- refs: ArtifactRefView,-): DigestJsonConnectionHealth {- const allIds = preferences.map(({ pref }) => pref.id);- // Also include retired entries.- for (const entry of memoryFolderPages(vault, "retired", { regularFilesOnly: true })) {- if (!entry.name.endsWith(".md")) continue;- if (!entry.name.startsWith("ret-")) continue;- if (!refs.visible(posix.join(BRAIN_RETIRED_REL, entry.name))) continue;- allIds.push(entry.name.replace(/\.md$/, ""));- }-- const totalNodes = allIds.length;- const counts = allIds.map(inbound);- const linkedNodes = counts.filter((c) => c > 0).length;- const orphanNodes = totalNodes - linkedNodes;-- let meanBacklinks = 0;- let medianBacklinks = 0;- if (totalNodes > 0) {- const sum = counts.reduce((a, b) => a + b, 0);- meanBacklinks = Math.round((sum / totalNodes) * 100) / 100;- const sorted = [...counts].toSorted((a, b) => a - b);- const mid = Math.floor(sorted.length / 2);- medianBacklinks =- sorted.length % 2 === 0 ? (sorted[mid - 1]! + sorted[mid]!) / 2 : sorted[mid]!;- }- const linkDensity = totalNodes > 0 ? Math.round((linkedNodes / totalNodes) * 1000) / 1000 : 0;-- return Object.freeze({- total_nodes: totalNodes,- linked_nodes: linkedNodes,- orphan_nodes: orphanNodes,- mean_backlinks: meanBacklinks,- median_backlinks: medianBacklinks,- link_density: linkDensity,- });-}--function isEmpty(data: DigestData): boolean {- return (- data.new_unconfirmed.length === 0 &&- data.confirmed.length === 0 &&- data.retired.length === 0 &&- data.confidence_shifts.length === 0 &&- data.contradictions.length === 0 &&- data.most_applied.entries.length === 0 &&- data.agent_summary.length === 0- );-}--// ----- Filesystem scan helpers -----------------------------------------------interface PreferenceWithPath {- readonly pref: BrainPreference;- readonly path: string;-}--function readAllPreferences(- vault: string,- agentScope: string | undefined,- refs: ArtifactRefView,-): ReadonlyArray<PreferenceWithPath> {- const dirs = brainDirs(vault);- // Shared delivery-path walk (context-integrity-gates, Unit A). This- // surface's listing is the strictest of the five - regular files only,- // and only `pref-*` names - so both rules are passed as options rather- // than unified away. The doctor reports corruption; digest skips- // silently, which is what the collector's parse already does.- return collectPreferences(dirs.preferences, {- namePrefix: PREFERENCE_ID_PREFIX,- regularFilesOnly: true,- ownerScope: resolveOwnerScopeDelivery(vault, agentScope),- })- .entries.filter(({ path }) => refs.visible(vaultRelative(path, vault)))- .map(({ pref, path }) => ({ pref, path }));-}--interface RetiredWithPath {- readonly ret: BrainRetired;- readonly path: string;-}--/**- * Retirement KEEPS ownership (context-integrity-gates, A7): a retired- * memory is withdrawn from the active set, never published to every- * agent. Same gate resolution as {@link readAllPreferences}, so an- * unscoped digest is byte-identical.- */-function readAllRetired(- vault: string,- agentScope: string | undefined,- refs: ArtifactRefView,-): ReadonlyArray<RetiredWithPath> {- const scope = resolveOwnerScopeDelivery(vault, agentScope).enforcedScope;- const out: RetiredWithPath[] = [];- for (const entry of memoryFolderPages(vault, "retired", { regularFilesOnly: true })) {- if (!entry.name.endsWith(".md")) continue;- if (!entry.name.startsWith("ret-")) continue;- if (!refs.visible(posix.join(BRAIN_RETIRED_REL, entry.name))) continue;- const path = entry.path;- try {- const ret = parseRetiredMeta(entry.read()[0], path);- if (scope !== null && !isPreferenceVisible(ret, scope)) continue;- out.push({ ret, path });- } catch {- // ditto- }- }- return out;-}--function readLogsInWindow(vault: string, since: Date, until: Date): ReadonlyArray<BrainLogEntry> {- const sinceIso = since.toISOString();- const untilIso = until.toISOString();- // Restrict scans to dates intersecting the window — but we err- // permissive (one day before / after) to avoid TZ off-by-ones.- // Shard-aware (Memory Integrity Suite): dates come from listLogDates- // and entries arrive merged across device shards via readLogDay.- const sinceDay = sinceIso.slice(0, 10);- const untilDay = untilIso.slice(0, 10);- const out: BrainLogEntry[] = [];- const log = logDayReader(vault);- for (const date of log.dates) {- if (date < addDays(sinceDay, -1)) continue;- if (date > addDays(untilDay, 1)) continue;- const { entries } = log.day(date);- for (const e of entries) {- if (e.timestamp >= sinceIso && e.timestamp < untilIso) {- out.push(e);- }- }- }- out.sort((a, b) => a.timestamp.localeCompare(b.timestamp));- return out;-}--function addDays(day: string, delta: number): string {- const t = Date.parse(`${day}T00:00:00Z`);- if (!Number.isFinite(t)) return day;- return new Date(t + delta * ONE_DAY_MS).toISOString().slice(0, 10);-}--/**- * Best-effort lookup of the artifact wikilink for the first `applied`- * apply-evidence event against a preference id. Returns null if no- * applied evidence is found — e.g. a preference that was force-confirmed- * without ever being applied. This matches design doc §8.2 example.- */-function findFirstAppliedArtifact(- vault: string,- prefId: string,- refs: ArtifactRefView,-): string | null {- const log = logDayReader(vault);- for (const date of log.dates) {- const { entries } = log.day(date);- for (const e of logEntriesAtReach(refs, entries)) {- if (e.eventType !== BRAIN_LOG_EVENT_KIND.applyEvidence) continue;- if (e.body["result"] !== BRAIN_APPLY_RESULT.applied) continue;- const prefPayload = e.body["preference"];- if (typeof prefPayload === "string" && refersTo(prefPayload, prefId)) {- const artifact = e.body["artifact"];- if (typeof artifact === "string") return artifact;- }- }- }- return null;-}--function refersTo(payload: string, prefId: string): boolean {- return normaliseWikilinkTarget(payload) === prefId;-}--function daysStaleFor(ret: BrainRetired): number | null {- // For `stale-no-evidence`, the "days stale" is the gap between- // `retired_at` and `last_evidence_at` (or `created_at` if there is- // no evidence at all). Other reasons get null — the field is only- // meaningful under stale-no-evidence per §8.2 example. We still- // emit non-null for completeness on rebutted / expired-unconfirmed- // when computable, but only for stale-no-evidence is it the canonical- // metric the digest's "(91 days)" parenthetical refers to.- if (ret.retired_reason !== BRAIN_RETIRED_REASON.staleNoEvidence) return null;- const start = ret.last_evidence_at ?? ret.created_at;- const startMs = Date.parse(start);- const endMs = Date.parse(ret.retired_at);- if (!Number.isFinite(startMs) || !Number.isFinite(endMs)) return null;- return Math.max(0, Math.floor((endMs - startMs) / ONE_DAY_MS));-}--// ----- Confidence shifts & contradictions -----------------------------------//-// Task 3 (`dream.ts`) is in progress as we ship this. It is the only-// component that can authoritatively emit confidence transitions and-// contradictions; without its payload data we cannot reconstruct-// transitions from filesystem state alone (the current `confidence`-// field has no `from` value to compare against). Per the §15 Task 4-// spec, the digest tolerates the absent payload as a graceful empty.-//-// When dream eventually emits these in its run summary, the parsers-// below will pick them up because we look in flexible payload shapes-// (the `dream` event's bullet list).--function extractConfidenceShifts(- entries: ReadonlyArray<BrainLogEntry>,- idToPrinciple: ReadonlyMap<string, string>,-): ReadonlyArray<DigestJsonConfidenceShift> {- const out: DigestJsonConfidenceShift[] = [];- for (const e of entries) {- if (e.eventType !== BRAIN_LOG_EVENT_KIND.dream) continue;- // Pattern A: a `confidence_shifts` array, each item like- // `[[pref-foo]] medium -> high (applied: 11, violated: 0)`.- const shifts = e.body["confidence_shifts"];- if (Array.isArray(shifts)) {- for (const raw of shifts) {- const parsed = parseShiftLine(raw, idToPrinciple);- if (parsed) out.push(parsed);- }- }- }- return out;-}--function parseShiftLine(- raw: string,- idToPrinciple: ReadonlyMap<string, string>,-): DigestJsonConfidenceShift | null {- // Tolerant parser: accept `[[pref-x]] medium -> high (applied: N, violated: M)`- // and variations (en-dash / em-dash for arrow, missing parens).- const m = /^\s*(?:\[\[([^\]]+)\]\]|(\S+))\s+(\w+)\s*(?:->|→)\s*(\w+)(?:\s*\(([^)]*)\))?/.exec(- raw,- );- if (!m) return null;- const idRaw = (m[1] ?? m[2])!.split(/[|#]/)[0]!.trim();- if (!idRaw) return null;- const from = m[3]!;- const to = m[4]!;- let applied: number | null = null;- let violated: number | null = null;- if (m[5]) {- const appMatch = /applied\s*[:=]?\s*(\d+)/i.exec(m[5]);- if (appMatch) applied = parseInt(appMatch[1]!, 10);- const violMatch = /violated\s*[:=]?\s*(\d+)/i.exec(m[5]);- if (violMatch) violated = parseInt(violMatch[1]!, 10);- }- return {- id: idRaw,- principle: idToPrinciple.get(idRaw) ?? "",- from,- to,- applied_count: applied,- violated_count: violated,- };-}--function extractContradictions(- entries: ReadonlyArray<BrainLogEntry>,- idToPrinciple: ReadonlyMap<string, string>,-): ReadonlyArray<DigestJsonContradiction> {- const out: DigestJsonContradiction[] = [];- for (const e of entries) {- if (e.eventType !== BRAIN_LOG_EVENT_KIND.dream) continue;- const list = e.body["contradictions"];- if (Array.isArray(list)) {- for (const raw of list) {- const parsed = parseContradictionLine(raw, idToPrinciple);- if (parsed) out.push(parsed);- }- }- }- return out;-}--function parseContradictionLine(- raw: string,- idToPrinciple: ReadonlyMap<string, string>,-): DigestJsonContradiction | null {- // Best-effort: extract a wikilink as id and treat the rest as topic- // or description. A missing wikilink means we cannot anchor the- // contradiction to a preference; skip rather than fabricate.- const wm = /\[\[([^\]]+)\]\]/.exec(raw);- if (!wm) return null;- const id = wm[1]!.split(/[|#]/)[0]!.trim();- const description = raw.replace(wm[0], "").trim() || raw.trim();- // The line may carry `(topic: foo)` — pull it out if present.- let topic: string | null = null;- const tm = /topic\s*[:=]\s*([A-Za-z0-9_-]+)/.exec(description);- if (tm) topic = tm[1]!;- return {- id,- principle: idToPrinciple.get(id) ?? "",- topic,- description,- };-}--// ----- Markdown rendering ---------------------------------------------------function renderEmptyMarkdown(until: Date): string {// Single-line collapse per §8 paragraph above the listing.const ymd = until.toISOString().slice(0, 10);diff --git a/src/core/brain/doctor/permissions-check.ts b/src/core/brain/doctor/permissions-check.tsindex 197fe116..7eb0d52a 100644--- a/src/core/brain/doctor/permissions-check.ts+++ b/src/core/brain/doctor/permissions-check.ts@@ -34,6 +34,8 @@ import { join } from "node:path";import { resolveAgentName } from "../../config.ts";import { canonicalJson } from "../../integrity/digest.ts";import { isStoreOnly } from "../../store/store-only.ts";+import { StoreUnavailableError } from "../../store/read/protection-store.ts";+import { storeOpenFailureDetail, withholdsPrivate } from "./store-check.ts";import {loadPermissionsDocumentFor,PERMISSIONS_SETTING_LABEL,@@ -88,13 +90,27 @@ export const permissionsDocumentCheck: DoctorCheck = {// A non-document failure is not this check's finding; the pass's// fail-soft wrapper records those its own way.if (!(err instanceof PermissionsDocumentError)) throw err;+ // The loader's error carries the `protectionStore` reason as its+ // cause; its text holds only the reach-safe twin. Below local+ // reach the finding keeps its code and the source it names+ // (`where`) and redacts the cause the way the store check's own+ // findings are (`storeOpenFailureDetail`). At local reach the+ // operator's own doctor reads the cause itself, whose message+ // names the held partition's file and the remedy.+ const cause = err.cause instanceof StoreUnavailableError ? err.cause : null;+ const detail =+ cause === null+ ? err.message+ : withholdsPrivate(ctx)+ ? storeOpenFailureDetail(cause, cause.root, ctx)+ : cause.message;out.issues.push({severity: "error",code: PERMISSIONS_UNREADABLE_CODE,path: at,message:`${where} could not be read, so its policy is not in force and ` +- `every gate fails closed until it is repaired (${err.message})`,+ `every gate fails closed until it is repaired (${detail})`,} satisfies DoctorIssue);return;}diff --git a/src/core/brain/doctor/store-check.ts b/src/core/brain/doctor/store-check.tsindex 92cb0801..bad4aaef 100644--- a/src/core/brain/doctor/store-check.ts+++ b/src/core/brain/doctor/store-check.ts@@ -79,6 +79,7 @@ import {type StoreInspection,} from "../../store/store-open.ts";import { isStoreOnly } from "../../store/store-only.ts";+import { StoreUnavailableError } from "../../store/read/protection-store.ts";import { removalBacklog } from "../../store/removal-backlog.ts";import { readStoreWriteStatus, storeWriteStatusPath } from "../../store/store-write.ts";import {@@ -95,7 +96,12 @@ import {looseModeIssues,reservedDeviceDirIssues,} from "./store-trust-check.ts";-import type { DoctorFindings, StoreSideCheckContext, StoreSideDoctorCheck } from "./check.ts";+import type {+ DoctorFindings,+ DoctorCheckContext,+ StoreSideCheckContext,+ StoreSideDoctorCheck,+} from "./check.ts";import { returnedRetiredIssues } from "./device-retire-check.ts";import {STORE_SHARD_UNREADABLE_CODE,@@ -419,9 +425,13 @@ function heldTailFindings(* Whether the caller is below local reach: a wire surface that names its* reach (`brain_doctor`) or one that only marks the caller as withheld from* private data (`brain_brief view=operator`, `brain_status`, the repair- * pass). Neither set reads as the operator's own shell.+ * pass). Neither set reads as the operator's own shell. Shared with the+ * other doctor checks whose findings can carry a store-unavailable reason+ * (`permissions-check.ts`), so the redaction of such a reason has one gate.*/-function withholdsPrivate(ctx: StoreSideCheckContext): boolean {+export function withholdsPrivate(+ ctx: Pick<DoctorCheckContext, "reach" | "withholdsPrivate">,+): boolean {return (ctx.withholdsPrivate === true ||(ctx.reach !== undefined && ctx.reach !== TRANSPORT_REACH.local)@@ -566,11 +576,24 @@ function lostPartitionFinding(* `private/store.json`) or the store ids that disagree, so below local* reach the finding keeps its code and the store root and says only that* the store did not open; the operator's own doctor reads the cause.+ * Exported for the other checks whose finding can be caused by the same+ * store-open failure (`permissions-check.ts` carries the+ * `protectionStore` reason in its `permissions-unreadable` finding), so+ * the redacted wording has one definition.*/-function storeOpenFailureDetail(err: unknown, root: string, ctx: StoreSideCheckContext): string {+export function storeOpenFailureDetail(+ err: unknown,+ root: string | null,+ ctx: Pick<DoctorCheckContext, "reach" | "withholdsPrivate">,+): string {if (!withholdsPrivate(ctx)) return err instanceof Error ? err.message : String(err);+ // A `protectionStore` failure that is not an open failure at all (the+ // shared partition is gone) carries its own redacted detail; the generic+ // wording below would wrongly say "could not be opened".+ if (err instanceof StoreUnavailableError && err.safeDetail !== "") return err.safeDetail;+ const at = root === null ? "" : ` at ${root}`;return (- `the brain store at ${root} could not be opened, so every protection fails closed. ` ++ `the brain store${at} could not be opened, so every protection fails closed. ` +"Run `o2b brain doctor` on this machine for the cause and the remedy");}diff --git a/src/core/brain/gate-telemetry.ts b/src/core/brain/gate-telemetry.tsindex ed8d1552..fa746965 100644--- a/src/core/brain/gate-telemetry.ts+++ b/src/core/brain/gate-telemetry.ts@@ -195,7 +195,18 @@ export function summarizeGateTelemetry(vault: string,filter: GateTelemetryFilter = {},): GateTelemetrySummary {- const records = listGateTelemetry(vault, filter);+ return summarizeGateTelemetryRecords(listGateTelemetry(vault, filter));+}++/**+ * The summary fold over an already-listed set of gate records. Split from+ * {@link summarizeGateTelemetry} for the same reason its recall-telemetry+ * sibling is: a reader that must drop withheld records BEFORE the counts+ * folds those counts over the filtered set without re-reading disk.+ */+export function summarizeGateTelemetryRecords(+ records: ReadonlyArray<ContinuityRecord>,+): GateTelemetrySummary {let retrieved = 0;const byReason: Record<string, number> = {};const byTier: Record<string, number> = {};diff --git a/src/core/brain/permissions/document-source.ts b/src/core/brain/permissions/document-source.tsindex c292a9ce..2400b330 100644--- a/src/core/brain/permissions/document-source.ts+++ b/src/core/brain/permissions/document-source.ts@@ -47,9 +47,17 @@ export function storedPermissionsText(configPath?: string): string | null {store = protectionStore(configPath, { needShared: true });} catch (err) {if (!(err instanceof StoreUnavailableError)) throw err;+ // The cause rides along, so a caller that serves the text below+ // local reach can tell a store-open failure from a document fault+ // and redact it the way the store check's own findings are+ // (`storeOpenFailureDetail`). The text carries the error's+ // reach-safe twin, not its raw message: the raw one names a held+ // partition's file and the leave remedy, and this refusal reaches+ // callers at remote reach through the write gates.throw new PermissionsDocumentError(- `${PERMISSIONS_SETTING_LABEL}: ${err.message}; writes the permissions document governs ` ++ `${PERMISSIONS_SETTING_LABEL}: ${err.publicMessage}; writes the permissions document governs ` +"are refused until then",+ { cause: err },);}if (store === null || !store.partitions.has("shared")) return null;diff --git a/src/core/brain/policy/settings-source.ts b/src/core/brain/policy/settings-source.tsindex 7237cde1..b70203d3 100644--- a/src/core/brain/policy/settings-source.ts+++ b/src/core/brain/policy/settings-source.ts@@ -245,7 +245,10 @@ function settingsStore(configPath: string | undefined): StoreInspection | null {return protectionStore(configPath, { needShared: true });} catch (err) {if (!(err instanceof StoreUnavailableError)) throw err;- throw new BrainSettingsUnreadableError(err.message, STORE_SETTINGS_SOURCE);+ // The reach-safe twin of the error's message: the raw one can name a+ // held partition's file, and this error travels to callers at remote+ // reach (every policy load on a switched machine raises it).+ throw new BrainSettingsUnreadableError(err.publicMessage, STORE_SETTINGS_SOURCE);}}diff --git a/src/core/brain/policy/settings-write.ts b/src/core/brain/policy/settings-write.tsindex e73c7f2a..f54910a9 100644--- a/src/core/brain/policy/settings-write.ts+++ b/src/core/brain/policy/settings-write.ts@@ -150,8 +150,10 @@ function sharedRead(ctx: BrainSettingsReadContext): SharedRead {} catch (err) {if (!(err instanceof StoreUnavailableError)) throw err;// A switched machine whose store cannot be opened: the operator's- // value is unknown, as with an unseen shard.- return { fold: foldSettings([]), unseen: [err.message] };+ // value is unknown, as with an unseen shard. The reach-safe twin of+ // the error's message goes out, not the raw one: it can name a held+ // partition's file, and this list reaches callers at remote reach.+ return { fold: foldSettings([]), unseen: [err.publicMessage] };}if (store === null || !store.partitions.has("shared")) {return { fold: foldSettings([]), unseen: [] };diff --git a/src/core/brain/recall-telemetry.ts b/src/core/brain/recall-telemetry.tsindex 5937406a..e5733ca1 100644--- a/src/core/brain/recall-telemetry.ts+++ b/src/core/brain/recall-telemetry.ts@@ -489,7 +489,19 @@ export function summarizeRecallTelemetry(vault: string | null,filter: RecallTelemetryFilter = {},): RecallTelemetrySummary {- const records = listRecallTelemetry(vault, filter);+ return summarizeRecallTelemetryRecords(listRecallTelemetry(vault, filter));+}++/**+ * The summary fold over an already-listed set of records. Split from+ * {@link summarizeRecallTelemetry} so a reader that must apply its own+ * record boundary first (the MCP tool applies the caller's reach and+ * ownership view, dropping withheld records BEFORE the counts) folds the+ * same numbers over the same shape without a second disk read.+ */+export function summarizeRecallTelemetryRecords(+ records: ReadonlyArray<ContinuityRecord>,+): RecallTelemetrySummary {const byMode: Partial<Record<RecallTelemetryMode, number>> = {};const byStatus: Partial<Record<RecallTelemetryStatus, number>> = {};const byChannel: Partial<Record<RecallChannel, number>> = {};diff --git a/src/core/brain/recurrence.ts b/src/core/brain/recurrence.tsindex 86cd0549..74cc661e 100644--- a/src/core/brain/recurrence.ts+++ b/src/core/brain/recurrence.ts@@ -108,10 +108,11 @@ export interface RecurrenceCadence {export function listRecurrenceCadences(vault: string,thresholds: RecurrenceThresholds = DEFAULT_THRESHOLDS,+ opts: RecurrenceReadOptions = {},): ReadonlyArray<RecurrenceCadence> {- const entries = listRecurrenceEntries(vault, thresholds);+ const entries = listRecurrenceEntries(vault, thresholds, opts);if (entries.length === 0) return Object.freeze([]);- const events = readEvents(vault);+ const events = readEvents(vault, opts);const purged = new Set(events.filter((e) => e.kind === "purge-source").map((e) => e.sourceId));const byHash = new Map<string, string[]>();for (const e of events) {@@ -152,8 +153,9 @@ export function listRecurrenceCadences(export function listRecurrenceEntries(vault: string,thresholds: RecurrenceThresholds = DEFAULT_THRESHOLDS,+ opts: RecurrenceReadOptions = {},): ReadonlyArray<RecurrenceEntry> {- const events = readEvents(vault);+ const events = readEvents(vault, opts);const state = new Map<string, { supportBySourceScope: Map<string, number> }>();for (const event of events) {@@ -284,12 +286,33 @@ function parseEvent(line: string): RecurrenceEvent | null {}}-function readEvents(vault: string): RecurrenceEvent[] {+/**+ * Read options for the recurrence fold. With `excludePrivateEvents`,+ * every support event the writer classified private is dropped BEFORE+ * the fold - the same verdicts the writer applied at append time+ * ({@link claimSourceIsPrivate} on the source, {@link rowNamesPrivatePage}+ * on the row) - so an entry's scopes, support count and commitment are+ * built only from evidence the caller may be shown, and no private+ * scope string survives into a projected title.+ */+export interface RecurrenceReadOptions {+ readonly excludePrivateEvents?: boolean;+}++function readEvents(vault: string, opts: RecurrenceReadOptions = {}): RecurrenceEvent[] {// A store-only machine reads the `recurrence` ledger rows in fold order,// the one order every machine agrees on (design D3).- return readLedgerRows<RecurrenceEvent>(DUAL_WRITE_LEDGERS.recurrence, readLegacyEvents, {+ const events = readLedgerRows<RecurrenceEvent>(DUAL_WRITE_LEDGERS.recurrence, readLegacyEvents, {vault,}).filter((event) => event !== null && typeof event === "object");+ if (opts.excludePrivateEvents !== true) return events;+ // Purge events carry no page name and only ever shrink the fold; the+ // support events they purge are already judged individually.+ return events.filter(+ (event) =>+ event.kind === "purge-source" ||+ !(claimSourceIsPrivate(vault, event.sourceId) || rowNamesPrivatePage(vault, event)),+ );}function readLegacyEvents(vault: string): RecurrenceEvent[] {diff --git a/src/core/brain/signal-state.ts b/src/core/brain/signal-state.tsindex 44554348..571658cc 100644--- a/src/core/brain/signal-state.ts+++ b/src/core/brain/signal-state.ts@@ -211,9 +211,12 @@ function partitionsShowingSignal(id: string, configPath?: string): StorePartitiostore = protectionStore(configPath, { needShared: true });} catch (err) {if (!(err instanceof StoreUnavailableError)) throw err;+ // The reach-safe twin of the error's message: the raw one can name a+ // held partition's file, and this refusal reaches callers at remote+ // reach.throw new StoreWriteError("store-error",- `the signal ${id} cannot be forgotten: ${err.message}`,+ `the signal ${id} cannot be forgotten: ${err.publicMessage}`,);}if (store === null) return [];@@ -221,10 +224,17 @@ function partitionsShowingSignal(id: string, configPath?: string): StorePartitioif (!store.partitions.has(partition)) return false;const read = readStreamRecords(store.root, partition, { stream: "events" });if (read.unreadable.length > 0) {+ // The same publicMessage approach the store-open refusal above+ // takes: this path carries no caller reach, so the private+ // partition's shard paths (which name a device) never go into the+ // message, at any reach. A shared shard names nothing private.+ const listed =+ partition === "private"+ ? `${read.unreadable.length} private events shard${read.unreadable.length === 1 ? "" : "s"}`+ : read.unreadable.map((rel) => `${partition}/${rel}`).join(", ");throw new StoreWriteError("store-error",- `the signal ${id} cannot be forgotten while an events shard cannot be read ` +- `(${read.unreadable.map((rel) => `${partition}/${rel}`).join(", ")})`,+ `the signal ${id} cannot be forgotten while an events shard cannot be read (${listed})`,);}return foldSignals(read.records).signals.has(id);diff --git a/src/core/brain/signal.ts b/src/core/brain/signal.tsindex 72bfbd2e..8d902586 100644--- a/src/core/brain/signal.ts+++ b/src/core/brain/signal.ts@@ -46,6 +46,8 @@ import { storeWrite } from "../store/store-write.ts";import { FileAlreadyExistsError } from "../fs-atomic.ts";import { processDirsEnv } from "../platform-dirs.ts";import { signalsStoreOnly, storeSignal } from "./signal-state.ts";+import { memoryPageNamed } from "./memory-pages.ts";+import { existsSync } from "node:fs";import { join, posix, relative, resolve } from "node:path";import type { WriteSubject } from "./write-disposition.ts";@@ -665,6 +667,37 @@ function writeVaultlessSignal(return { path, id, staged };}+/**+ * Whether a signal write's record still exists, in the coordinates a+ * deduped idempotency result carries (the receipt `ref`'s path and id).+ * A vault signal is its page; a store-only signal is its record in the+ * fold. A signal that stayed alive but MOVED does not answer at its+ * original path any more - the dream pass moves inbox pages into+ * `Brain/inbox/processed/`, and applying a staged signal moves it out+ * of `Brain/pending/` into `Brain/inbox/` - so the id is also looked up+ * in those three folders and found there counts as present. False for a record+ * `deleteBySource` forgot (archived is not looked up: archived is+ * gone), for a receipt with no `ref` (empty id or path), and for+ * anything unresolvable - callers use it as positive evidence, so every+ * doubt answers "gone".+ */+export function signalRecordExists(+ vault: string | null,+ path: string,+ id: string,+ configPath?: string,+): boolean {+ if (path === "" || id === "") return false;+ if (vault === null || signalsStoreOnly(vault, configPath))+ return storeSignal(id, configPath) !== undefined;+ if (existsSync(path)) return true;+ return (+ memoryPageNamed(vault, "inbox", `${id}.md`, { configPath }) !== null ||+ memoryPageNamed(vault, "processed", `${id}.md`, { configPath }) !== null ||+ memoryPageNamed(vault, "pending", `${id}.md`, { configPath }) !== null+ );+}+/** Device-local lock that serialises store-only signal id allocation on this machine. */function signalAllocationLock(): string {return join(storesStateDir(processDirsEnv()), "signal-ids");diff --git a/src/core/brain/temporal/foresight.ts b/src/core/brain/temporal/foresight.tsindex c45ed07b..ec613c70 100644--- a/src/core/brain/temporal/foresight.ts+++ b/src/core/brain/temporal/foresight.ts@@ -47,11 +47,29 @@ export interface ForesightEnvelope {export interface BuildForesightOptions {readonly now: Date;readonly horizonDays?: number;+ /**+ * Withhold private material from the whole fold: continuity records+ * flagged `private` from the extract fold, and support that comes+ * from private-classified recurrence events from the recurring+ * projection (the event's scope can name a private page, and that+ * scope becomes the item title). The MCP handler sets it for every+ * caller below local reach, the same withholding flag the other+ * report surfaces hand their folds; local reach keeps the unfiltered+ * output. Absent means false.+ */+ readonly withholdsPrivate?: boolean;}-function recurringItems(vault: string, nowMs: number, horizonDays: number): ForesightItem[] {+function recurringItems(+ vault: string,+ nowMs: number,+ horizonDays: number,+ withholdsPrivate: boolean,+): ForesightItem[] {const out: Array<{ item: ForesightItem; dueMs: number }> = [];- for (const cadence of listRecurrenceCadences(vault)) {+ for (const cadence of listRecurrenceCadences(vault, undefined, {+ excludePrivateEvents: withholdsPrivate,+ })) {if (cadence.meanIntervalDays === null) continue;const lastMs = Date.parse(cadence.lastAt);if (!Number.isFinite(lastMs)) continue;@@ -77,11 +95,16 @@ function recurringItems(vault: string, nowMs: number, horizonDays: number): Forereturn out.map((x) => x.item);}-function extractItems(vault: string, nowMs: number): ForesightItem[] {+function extractItems(vault: string, nowMs: number, withholdsPrivate: boolean): ForesightItem[] {const since = isoSecond(new Date(nowMs - FORESIGHT_EXTRACT_LOOKBACK_DAYS * DAY_MS));const records = listContinuityRecords(vault, { kind: "pre_compact_extract", since });const out: Array<{ item: ForesightItem; createdAt: string }> = [];for (const record of records) {+ // The fold reads the raw store, not the read model's private-record+ // masking, so the withholding flag is applied here: a private+ // record's text is the item title and its refs the sources, and a+ // caller it is withheld from must not receive either.+ if (withholdsPrivate && record.private === true) continue;const extractType = record.payload["extract_type"];if (extractType !== "commitment" && extractType !== "open_question") continue;const text = record.payload["text"];@@ -114,7 +137,10 @@ function extractItems(vault: string, nowMs: number): ForesightItem[] {export function buildForesight(vault: string, opts: BuildForesightOptions): ForesightEnvelope {const horizonDays = opts.horizonDays ?? FORESIGHT_HORIZON_DAYS;const nowMs = opts.now.getTime();- const upcoming = [...recurringItems(vault, nowMs, horizonDays), ...extractItems(vault, nowMs)];+ const upcoming = [+ ...recurringItems(vault, nowMs, horizonDays, opts.withholdsPrivate === true),+ ...extractItems(vault, nowMs, opts.withholdsPrivate === true),+ ];return Object.freeze({version: FORESIGHT_SCHEMA_VERSION,generatedAt: isoSecond(opts.now),diff --git a/src/core/search/visibility-surface-registry.ts b/src/core/search/visibility-surface-registry.tsindex 16d305b4..083ebd70 100644--- a/src/core/search/visibility-surface-registry.ts+++ b/src/core/search/visibility-surface-registry.ts@@ -481,7 +481,8 @@ export const VISIBILITY_SURFACE_REGISTRY: ReadonlyArray<VisibilitySurfaceEntry>kind: K.mcpTool,category: C.excluded,reason:- "swept into population because admin-tools.ts (its home file) also imports parseFrontmatter " ++ "swept into population because admin-policy-tools.ts, which admin-tools.ts (its home file) " ++ "imports, also imports parseFrontmatter " +"and Store for brain_labels/brain_tiers/brain_maintenance beside it - the handler itself " +"returns only secret names and run results, never a note path, title, or body. Listed for " +"completeness of the file-level population rule rather than as a real disclosure.",diff --git a/src/core/store/lane-fold-cache.ts b/src/core/store/lane-fold-cache.tsindex b5db1b2c..e2508774 100644--- a/src/core/store/lane-fold-cache.ts+++ b/src/core/store/lane-fold-cache.ts@@ -13,9 +13,12 @@* machine read before and that are gone now: an entry's records in one* are unknown, so a privacy decision over the fold fails closed while any* is listed. Such a fold is never cached, so a shard that reads again is- * folded at once; nor is a fold that left out a record whose body is a- * pending blob, so the record is folded as soon as its blob arrives. A switched machine whose store cannot be opened lists- * that reason the same way (`read/protection-store.ts`).+ * folded at once. A fold that left out a record whose body is a pending+ * blob is cached against the availability of every blob it skipped+ * (`pendingBlobs`): the stamp moves the moment a blob arrives, so the fold+ * is rebuilt then, and it stays cached while every one is absent. A+ * switched machine whose store cannot be opened lists that reason the same+ * way (`read/protection-store.ts`).*/import { createHash } from "node:crypto";@@ -37,7 +40,7 @@ import { quarantineStamp } from "./shard-quarantine.ts";import { protectionStore, StoreUnavailableError } from "./read/protection-store.ts";import { listShards } from "./shard-list.ts";import type { StoreInspection } from "./store-open.ts";-import { partitionDir } from "./store-paths.ts";+import { partitionDir, blobStamp, pendingBlobStampLines } from "./store-paths.ts";export interface LaneFolded {readonly fingerprint: string;@@ -51,6 +54,12 @@ export interface LaneFolded {* could not see (unreadable, or gone since this machine read it).*/readonly unreadable: ReadonlyArray<string>;+ /**+ * `<partition>/<sha>` of every blob a skipped pending record's body+ * still references (the identities the cache fingerprints against, one+ * stat each, instead of rescanning the shards).+ */+ readonly pendingBlobs: ReadonlyArray<string>;}const EMPTY_FOLD: LaneFolded = {@@ -59,16 +68,19 @@ const EMPTY_FOLD: LaneFolded = {clocks: new Map(),privateKeys: new Set(),unreadable: [],+ pendingBlobs: [],};const cache = new Map<string, LaneFolded>();/**- * A stamp of every `events` shard of `store`; it moves whenever a record- * lands, and with the quarantine ledger, which decides whether a shard- * reads whole without changing its bytes.+ * A stamp of every `events` shard of `store` and the quarantine ledger:+ * the shard-and-quarantine part of a stored fold's fingerprint. The+ * availability of the blobs a fold skipped is appended when the fold is+ * stored (`pendingBlobStampLines`), so the stored stamp moves the moment+ * one is delivered and stays put while it is absent.*/-export function laneFingerprintOf(store: StoreInspection): string {+function laneFingerprintOf(store: StoreInspection): string {const parts: string[] = [store.storeId, `quarantine=${quarantineStamp(store.root)}`];for (const partition of [...store.partitions].toSorted()) {for (const shard of listShards(partitionDir(store.root, partition), { stream: "events" })) {@@ -98,21 +110,29 @@ export function laneStoreFold(): LaneFolded {if (!(err instanceof StoreUnavailableError)) throw err;// A switched machine whose store cannot be opened sees no shard at// all: every privacy decision over the fold fails closed. Not cached.- return { ...EMPTY_FOLD, unreadable: [err.message] };+ // The reach-safe twin of the error's message goes into the list: it+ // reaches callers at remote reach.+ return { ...EMPTY_FOLD, unreadable: [err.publicMessage] };}if (store === null) return EMPTY_FOLD;- const fingerprint = laneFingerprintOf(store);const cached = cache.get(store.root);+ // The stamp a stored fold must still match: the shard part plus the+ // availability of the blobs that fold skipped (one stat each, no shard+ // is read). A fold whose stored stamp lists no blob lines is uncached.+ const cachedLines =+ cached === undefined ? null : pendingBlobStampLines(store.root, cached.pendingBlobs);+ const shardStamp = laneFingerprintOf(store);+ const fingerprint = cachedLines === null ? null : `${shardStamp}\n${cachedLines}`;if (cached !== undefined && cached.fingerprint === fingerprint) return cached;const records: StoreRecord[] = [];const inPrivate = new Set<string>();const unreadable: string[] = [];- let skippedPending = false;+ const pendingBlobs: string[] = [];for (const partition of STORE_PARTITIONS) {if (!store.partitions.has(partition)) continue;const read = readStreamRecords(store.root, partition, { stream: "events" });- if (read.skippedPending) skippedPending = true;for (const rel of read.unreadable) unreadable.push(`${partition}/${rel}`);+ for (const sha of read.pendingBlobs) pendingBlobs.push(`${partition}/${sha}`);for (const record of read.records) {if (record.kind !== LANE_ENTRY_KIND && record.kind !== LANE_ENTRY_REMOVE_KIND) continue;records.push(record);@@ -130,16 +150,80 @@ export function laneStoreFold(): LaneFolded {for (const h of state.history) newest = Math.max(newest, parseHlc(h.record.hlc)?.physical ?? 0);clocks.set(key, newest);}- const folded = { fingerprint, entries, clocks, privateKeys, unreadable };- // A shard that reads again after a permission change keeps its size and- // mtime, so the fingerprint would not move: an incomplete fold is never- // reused. Nor is one that left out a record whose body is a pending blob:- // the blob's arrival moves neither a shard stamp nor the quarantine stamp.- if (unreadable.length === 0 && !skippedPending) cache.set(store.root, folded);+ // The fold is cached against the availability of every blob it skipped,+ // stamped now: a blob absent after the build was absent during it, so+ // the skip was correct and those lines belong with the shard stamp. A+ // blob present after the build arrived during it (or is there but+ // refused), so no stored stamp can describe the fold - it is left+ // uncached and rebuilt on the next read. A shard that reads again after+ // a permission change keeps its size and mtime, so an incomplete fold+ // is never reused either. An uncached fold still carries a+ // deterministic stamp (`incompleteFingerprint`), so the memos keyed by+ // `laneStoreStamp` keep hitting while the degraded state stays the same+ // instead of forcing a full rebuild on every read.+ const blobLines = pendingBlobStampLines(store.root, pendingBlobs);+ const storedFingerprint =+ blobLines === null || unreadable.length > 0+ ? incompleteFingerprint(store, shardStamp, unreadable, pendingBlobs, records)+ : `${shardStamp}\n${blobLines}`;+ const folded = {+ fingerprint: storedFingerprint,+ entries,+ clocks,+ privateKeys,+ unreadable,+ pendingBlobs,+ };+ if (unreadable.length === 0 && blobLines !== null) cache.set(store.root, folded);else cache.delete(store.root);return folded;}+/**+ * The deterministic fingerprint of a fold that is left uncached (an+ * `events` shard this machine cannot read or read before and that is gone,+ * or a skipped blob that is present but refused): an `incomplete` prefix -+ * which no healthy fold's fingerprint can carry - then the shard stamp,+ * the shards the fold could not see, a digest of the records the fold+ * DID see, and one full `lstat` identity (`blobStamp`) per refused blob.+ * The record digest is what lets two degraded folds over identically+ * stamped shards disagree: a transient read failure of a shard and a read+ * gap inside it (one corrupt line) both name that shard `unreadable`+ * while its size and mtime stay put, but the first leaves the fold with+ * none of its records and the second with its readable ones - so the+ * stamp moves the moment the contributing records change, and a memo+ * keyed by it never serves a fold built over different records. It moves+ * when a shard reads again or a refused blob's identity changes, and+ * never collides with a stored fingerprint, so a memo keyed by it serves+ * the same degraded build while the state lasts and drops it the moment+ * it lifts.+ */+function incompleteFingerprint(+ store: StoreInspection,+ shardStamp: string,+ unreadable: ReadonlyArray<string>,+ pendingBlobs: ReadonlyArray<string>,+ records: ReadonlyArray<StoreRecord>,+): string {+ const recordDigest = createHash("sha256");+ for (const record of records) {+ recordDigest.update(`${record.id}\u0000${record.hlc}\u0001`);+ }+ const parts = [+ "incomplete",+ shardStamp,+ `unreadable=${unreadable.toSorted().join(",")}`,+ `records=${recordDigest.digest("hex")}`,+ ];+ for (const identity of pendingBlobs.toSorted()) {+ const slashAt = identity.indexOf("/");+ const partition = identity.slice(0, slashAt) as (typeof STORE_PARTITIONS)[number];+ const sha = identity.slice(slashAt + 1);+ parts.push(`blob ${identity}=${blobStamp(partitionDir(store.root, partition), sha)}`);+ }+ return parts.join("\n");+}+/*** The device-local lock target of the lane file at `path` (`salt` keeps a* create lock apart from the page lock). The path is resolved, and casediff --git a/src/core/store/lane-pages.ts b/src/core/store/lane-pages.tsindex 3cc5850e..f47f8ef1 100644--- a/src/core/store/lane-pages.ts+++ b/src/core/store/lane-pages.ts@@ -50,7 +50,7 @@ import {type WriteFrontmatterAtomicOptions,} from "../vault.ts";import { type DualWriteContext } from "./dual-write.ts";-import { laneFingerprintOf, laneLockTarget } from "./lane-fold-cache.ts";+import { laneLockTarget, laneStoreFold } from "./lane-fold-cache.ts";import {brainRelOf,entryRecord,@@ -73,7 +73,6 @@ import {} from "./lane-entry-store.ts";import { rawParsesBack, rawToKeep, renderLaneText } from "./lane-raw.ts";import { brainRelOfEntry, lanePlaceOf } from "./lane-paths.ts";-import { configuredStore } from "./read/store-entities.ts";import { acquireDirLock, STORE_LOCK_STALE_MS, withLocalLock } from "./local-lock.ts";import { assertNoteVaultForWrite } from "../vault-adapter/index.ts";import { withOperationPrivacy } from "./operation-scope.ts";@@ -331,12 +330,16 @@ export function listLaneTree(vault: string, dir: string, ext = ".md"): string[]/*** A change stamp of the lane entries a store-only machine reads: it moves* whenever a lane record lands, so a reader's memo (the entity index) keyed- * by it never serves a stale build. Empty on an unswitched machine.+ * by it never serves a stale build. The stamp is the stored lane fold's+ * fingerprint, which includes the availability of the blobs a fold skipped+ * (`lane-fold-cache.ts`): a lane update whose body is a pending blob keeps+ * the stamp until its blob arrives, and moves it then, so a memo warmed on+ * the old page is not served after the update becomes readable. Empty on+ * an unswitched machine.*/export function laneStoreStamp(vault: string): string {if (!lanePagesInStore(vault)) return "";- const store = configuredStore();- return store === null ? "" : laneFingerprintOf(store);+ return laneStoreFold().fingerprint;}// ----- Writes -------------------------------------------------------------------diff --git a/src/core/store/read/protection-store.ts b/src/core/store/read/protection-store.tsindex 3039fd11..2a44ba49 100644--- a/src/core/store/read/protection-store.ts+++ b/src/core/store/read/protection-store.ts@@ -26,16 +26,53 @@ import { isStoreOnly, markedSwitched } from "../store-only.ts";import { HeldPartitionLostError, inspectStore, type StoreInspection } from "../store-open.ts";import { resolveConfiguredStoreRoot } from "../store-paths.ts";-/** The store of a switched machine cannot be opened, so its rules are unknown. */+/**+ * The store of a switched machine cannot be opened, so its rules are+ * unknown. `root` is the store root the open failed for, when it was+ * resolved before the failure. `message` carries the raw cause (it can+ * name a held partition's file, so only a caller at local reach may show+ * it); `publicMessage` is the same sentence with the cause replaced, and+ * `safeDetail` is the redacted detail the doctor's findings carry below+ * local reach (`storeOpenFailureDetail` in the doctor's store check) -+ * neither names a partition's file, the store ids or the leave remedy, so+ * any consumer may embed them in what it hands a caller at remote reach.+ */export class StoreUnavailableError extends Error {override readonly name = "StoreUnavailableError";+ constructor(+ message: string,+ readonly root: string | null = null,+ readonly publicMessage: string = message,+ readonly safeDetail: string = "",+ ) {+ super(message);+ }}-function unavailable(reason: string, switched = true): StoreUnavailableError {- return new StoreUnavailableError(- `this machine ${switched ? "switched to" : "writes to"} the brain store and ${reason}; the ` +- "rules stored there are unknown until it opens again. Run `o2b brain doctor`",- );+const DETAIL_TAIL =+ ", so every protection fails closed. Run `o2b brain doctor` on this machine " ++ "for the cause and the remedy";++function unavailable(+ reason: string,+ switched: boolean,+ root: string | null,+ safeReason: string,+ safeDetail: string,+): StoreUnavailableError {+ const frame = (cause: string): string =>+ `this machine ${switched ? "switched to" : "writes to"} the brain store and ${cause}; the ` ++ "rules stored there are unknown until it opens again. Run `o2b brain doctor`";+ return new StoreUnavailableError(frame(reason), root, frame(safeReason), safeDetail);+}++/** The store-open cause, phrased for a caller this machine does not trust. */+function openSafe(root: string | null): { safeReason: string; safeDetail: string } {+ const at = root === null ? "" : ` at ${root}`;+ return {+ safeReason: `the store${at} could not be opened`,+ safeDetail: `the brain store${at} could not be opened${DETAIL_TAIL}`,+ };}/**@@ -59,30 +96,46 @@ export function protectionStore(): StoreInspection | null {let store: StoreInspection | null = null;let reason = "";+ let safeReason = "";+ let safeDetail = "";let lost = false;let openError = false;+ let root: string | null = null;try {- const { root } = resolveConfiguredStoreRoot(configPath);- store = inspectStore(root);- if (store === null) reason = `the store at ${root} cannot be found (no store.json)`;+ const resolved = resolveConfiguredStoreRoot(configPath);+ root = resolved.root;+ store = inspectStore(resolved.root);+ if (store === null) {+ reason = `the store at ${root} cannot be found (no store.json)`;+ safeReason = reason;+ safeDetail = `the brain store at ${root} cannot be found (no store.json)${DETAIL_TAIL}`;+ }} catch (err) {lost = err instanceof HeldPartitionLostError;openError = true;reason = `the store cannot be opened (${(err as Error).message})`;+ ({ safeReason, safeDetail } = openSafe(root));}const context = configPath !== undefined ? { configPath } : {};const switched = (): boolean => markedSwitched(context);if (store === null) {- if (switched()) throw unavailable(reason);+ if (switched()) throw unavailable(reason, true, root, safeReason, safeDetail);const storeOnly = (): boolean =>isStoreOnly(options.vault !== undefined ? { ...context, vault: options.vault } : context);if ((lost || (openError && options.openErrorFails === true)) && storeOnly()) {- throw unavailable(reason, false);+ throw unavailable(reason, false, root, safeReason, safeDetail);}return null;}if (options.needShared === true && !store.partitions.has("shared") && switched()) {- throw unavailable(`the shared partition of the store at ${store.root} cannot be found`);+ const sharedReason = `the shared partition of the store at ${store.root} cannot be found`;+ throw unavailable(+ sharedReason,+ true,+ store.root,+ sharedReason,+ `the shared partition of the brain store at ${store.root} cannot be found${DETAIL_TAIL}`,+ );}return store;}diff --git a/src/core/store/read/store-entities.ts b/src/core/store/read/store-entities.tsindex 70ba4fd3..055bd6c3 100644--- a/src/core/store/read/store-entities.ts+++ b/src/core/store/read/store-entities.ts@@ -10,8 +10,10 @@* (`../store-privacy.ts`). It is cached per store root and re-read only* when an `events` shard of a held partition appears, grows or changes,* so a writer operation that judges many references reads the store once.- * A read that left out a record whose body is a pending blob is not- * cached, because the blob's arrival moves no stamp the cache compares.+ * A read that left out a record whose body is a pending blob is cached+ * against the availability of every blob it skipped (`pendingBlobs`): the+ * stamp moves the moment a blob arrives, so the read is rebuilt then, and+ * it stays cached while every one is absent.** Signals fold their `signal` and `signal-state` records* (`../fold-signals.ts`), so a reader tells an inbox signal from a@@ -44,7 +46,7 @@ import {import { foldPreferences, type PreferenceState } from "../fold-preferences.ts";import { listShards } from "../shard-list.ts";import { inspectStore, type StoreInspection } from "../store-open.ts";-import { partitionDir, resolveConfiguredStoreRoot } from "../store-paths.ts";+import { partitionDir, pendingBlobStampLines, resolveConfiguredStoreRoot } from "../store-paths.ts";import { readStreamRecords } from "./stream-read.ts";import { quarantineStamp } from "../shard-quarantine.ts";@@ -82,6 +84,12 @@ export interface StoreEntities {readonly unreadable: ReadonlyArray<string>;/** Whether a record was left out because its body is a pending blob. */readonly skippedPending: boolean;+ /**+ * `<partition>/<sha>` of every blob a skipped pending record's body+ * still references (the identities the cache fingerprints against, one+ * stat each, instead of rescanning the shards).+ */+ readonly pendingBlobs: ReadonlyArray<string>;}interface Cached {@@ -94,8 +102,11 @@ const cache = new Map<string, Cached>();const EVENTS = { stream: "events" } as const;/**- * What a read depends on: every `events` shard, and the quarantine ledger,+ * What a read depends on: every `events` shard and the quarantine ledger,* which decides whether a shard reads whole without changing its bytes.+ * The availability of the blobs a read skipped is stamped when the read is+ * stored (`pendingBlobStampLines`), so the stored stamp moves the moment+ * one is delivered and stays put while it is absent.*/function fingerprintOf(store: StoreInspection): string {const parts: string[] = [store.storeId, `quarantine=${quarantineStamp(store.root)}`];@@ -139,9 +150,11 @@ function build(store: StoreInspection): StoreEntities {const unreadable: string[] = [];const pinned = new Map<StorePartition, PinnedFold>();let skippedPending = false;+ const pendingBlobs: string[] = [];for (const partition of store.partitions) {const read = readStreamRecords(store.root, partition, EVENTS);if (read.skippedPending) skippedPending = true;+ for (const sha of read.pendingBlobs) pendingBlobs.push(`${partition}/${sha}`);unreadable.push(...read.unreadable.map((rel) => `${partition}/${rel}`));for (const record of read.records) all.push({ record, partition });pinned.set(@@ -203,22 +216,41 @@ function build(store: StoreInspection): StoreEntities {partitions: new Set(entry.history.map((r) => partitionOf.get(r.id) ?? "shared")),});}- return { store, preferences, signals, pinned, unreadable, skippedPending };+ return {+ store,+ preferences,+ signals,+ pinned,+ unreadable,+ skippedPending,+ pendingBlobs,+ };}/** The entities of the store at `store.root`, cached until an `events` shard changes. */export function readEntitiesOf(store: StoreInspection): StoreEntities {- const fingerprint = fingerprintOf(store);const cached = cache.get(store.root);+ // The stamp a stored read must still match: the shard part plus the+ // availability of the blobs that read skipped (one stat each, no shard+ // is read). A read whose stored stamp lists no blob lines is uncached.+ const cachedLines =+ cached === undefined ? null : pendingBlobStampLines(store.root, cached.entities.pendingBlobs);+ const shardStamp = fingerprintOf(store);+ const fingerprint = cachedLines === null ? null : `${shardStamp}\n${cachedLines}`;if (cached !== undefined && cached.fingerprint === fingerprint) return cached.entities;const entities = build(store);// A shard unreadable for a moment (a Windows sharing violation) keeps its- // size and mtime, so a cached incomplete read would never be retried. A- // read that left out a pending record is not cached either: when its blob- // arrives no stamp of the fingerprint moves (a quarantined pending blob- // opens no gap, so it is not in `unreadable`).- if (entities.unreadable.length === 0 && !entities.skippedPending)- cache.set(store.root, { fingerprint, entities });+ // size and mtime, so a cached incomplete read would never be retried, and+ // an incomplete read is never cached. The read is cached against the+ // availability of every blob it skipped, stamped now: a blob absent after+ // the build was absent during it, so the skip was correct and those lines+ // belong with the shard part (a quarantined pending blob opens no gap, so+ // it is not in `unreadable`). A blob present after the build arrived+ // during it, or is there but refused, so the read is left uncached and+ // rebuilt on the next read.+ const blobLines = pendingBlobStampLines(store.root, entities.pendingBlobs);+ if (entities.unreadable.length === 0 && blobLines !== null)+ cache.set(store.root, { fingerprint: `${shardStamp}\n${blobLines}`, entities });else cache.delete(store.root);return entities;}diff --git a/src/core/store/read/stream-read.ts b/src/core/store/read/stream-read.tsindex 516549a4..0af81ae2 100644--- a/src/core/store/read/stream-read.ts+++ b/src/core/store/read/stream-read.ts@@ -18,7 +18,7 @@* Nothing here writes: no store is created, no partition copy refreshed.*/-import type { StorePartition } from "../constants.ts";+import { BLOB_REF_KEY, type StorePartition } from "../constants.ts";import type { StoreRecord } from "../envelope.ts";import { readShard, replacedShards, shardReadGap, type Compaction } from "../reader.ts";import { trackSeenShards } from "../seen-shards.ts";@@ -40,10 +40,18 @@ export interface StreamRead {* blob. A quarantined pending blob opens no gap, so `unreadable` does* not name its shard; and when the blob arrives, neither the shard's* bytes nor the quarantine ledger change. A caller that caches a read- * on those stamps must not cache one that skipped a pending record, or- * it keeps answering without that record after the blob is delivered.+ * on those stamps caches it against the availability of `pendingBlobs`+ * instead: the fingerprint moves the moment a blob is delivered, so the+ * read is rebuilt then and stays cached while every one is absent.*/readonly skippedPending: boolean;+ /**+ * Blob names (the sha a blob is stored under, `blobPath`) of the records+ * left out because their body is a pending blob, in shard order without+ * duplicates. The identities a caching caller stats, one per skipped+ * record, instead of rescanning the shards.+ */+ readonly pendingBlobs: ReadonlyArray<string>;}export interface StreamReadOptions {@@ -59,6 +67,16 @@ function monthOf(rel: string): string {return name.slice(0, 7);}+/**+ * The blob name a pending record's body still holds (the sha the blob is+ * stored under). `resolveBody` marks a body pending only for a blob+ * reference, whose key is always a string (`isBlobRef`), so every pending+ * entry has one.+ */+function blobRefSha(body: StoreRecord["body"]): string {+ return body[BLOB_REF_KEY] as string;+}+/** The partition-relative folder of a stream: `events`, `ledgers/<name>`. */function streamPrefix(ref: StreamRef): string {return ref.ledger !== undefined ? `${ref.stream}/${ref.ledger}` : ref.stream;@@ -74,6 +92,7 @@ export function readStreamRecords(const partitionRoot = partitionDir(root, partition);const records: StoreRecord[] = [];const unreadable: string[] = [];+ const pendingBlobs: string[] = [];let shards: ReturnType<typeof listShards>;try {shards = listShards(partitionRoot, ref);@@ -81,10 +100,16 @@ export function readStreamRecords(// A stream that cannot be listed (its folder, or any device folder// below it: EACCES, EBUSY) is named whole, as an unreadable shard is,// and none of its shards is read; the other streams still read.- return { records, unreadable: [streamPrefix(ref)], skippedPending: false };+ return {+ records,+ unreadable: [streamPrefix(ref)],+ skippedPending: false,+ pendingBlobs: [],+ };}const compactions: Compaction[] = [];let skippedPending = false;+ const seenBlobs = new Set<string>();for (const shard of shards) {if (options.device !== undefined && shard.device !== options.device) continue;if (options.month !== undefined && !options.month(monthOf(shard.rel))) continue;@@ -102,8 +127,18 @@ export function readStreamRecords(if (shardReadGap(read) !== null) unreadable.push(shard.rel);compactions.push(...read.compactions);for (const entry of read.records) {- if (entry.bodyState !== "pending") records.push(entry.record);- else skippedPending = true;+ if (entry.bodyState !== "pending") {+ records.push(entry.record);+ continue;+ }+ // The body is still the blob reference (reader.ts): the sha names+ // the blob the caller stats for availability.+ skippedPending = true;+ const sha = blobRefSha(entry.record.body);+ if (!seenBlobs.has(sha)) {+ seenBlobs.add(sha);+ pendingBlobs.push(sha);+ }}}const gone = trackSeenShards(@@ -116,5 +151,10 @@ export function readStreamRecords(shards.map((shard) => shard.rel),replacedShards(compactions),);- return { records, unreadable: [...unreadable, ...gone], skippedPending };+ return {+ records,+ unreadable: [...unreadable, ...gone],+ skippedPending,+ pendingBlobs,+ };}diff --git a/src/core/store/store-paths.ts b/src/core/store/store-paths.tsindex e4a76ea4..cfc3cb12 100644--- a/src/core/store/store-paths.ts+++ b/src/core/store/store-paths.ts@@ -16,7 +16,7 @@* running process.*/-import { realpathSync } from "node:fs";+import { lstatSync, realpathSync } from "node:fs";import { homedir } from "node:os";import { join, posix, win32 } from "node:path";@@ -293,6 +293,63 @@ export function blobPath(partitionRoot: string, sha: string): string {return join(partitionRoot, STORE_BLOBS_DIR, sha.slice(0, 2), sha);}+/** The `lstat` identity a stamp reads off one fs entry (`bigint`, so ctime is ns). */+function lstatIdentity(path: string): string {+ const st = lstatSync(path, { bigint: true });+ return `${st.dev}:${st.ino}:${st.size}:${st.mtimeNs}:${st.ctimeNs}`;+}++/**+ * Availability stamp of the blob `sha` under `partitionRoot`: the `lstat`+ * identity of the blob file plus that of its `blobs/<ab>` folder, or+ * `"absent"`. `lstat`, not `stat`: the reader accepts a blob only as a+ * regular file of the recorded size and sha (and its folder only as a real+ * folder). The identity is never stored - it is compared only inside+ * fingerprints. `pendingBlobStampLines` keeps the `"absent"` lines of a+ * cached read, so there a stamp moves whenever an identity changes without+ * size or mtime moving - a symlink replaced by the real file or folder+ * (`mv`, `cp -p`, `rsync -a` keeps both), or a same-size blob repaired in+ * place with its mtime kept, where only ctime moves. The incomplete-fold+ * stamp (`lane-fold-cache.ts`) uses the full identity itself, so its memo+ * moves with a refused blob's repair too. A malformed sha reads as+ * absent, like a blob that is not there.+ */+export function blobStamp(partitionRoot: string, sha: string): string {+ try {+ const blob = lstatIdentity(blobPath(partitionRoot, sha));+ const folder = lstatIdentity(join(partitionRoot, STORE_BLOBS_DIR, sha.slice(0, 2)));+ return `${blob};${folder}`;+ } catch {+ return "absent";+ }+}++/**+ * The fingerprint lines for the `<partition>/<sha>` identities a cached+ * read or fold skipped: one `"blob <identity>=<stamp>"` line each, or+ * `null` when any of them is present. Callers stamp after the build: a+ * blob absent then was absent during it, so the skip was correct and the+ * lines belong with the shard part of the fingerprint. A blob present+ * after the build arrived during it (or is there but refused), so no line+ * a later read could match exists - `null` tells the caller to leave the+ * read uncached.+ */+export function pendingBlobStampLines(+ root: string,+ identities: ReadonlyArray<string>,+): string | null {+ let lines = "";+ for (const identity of identities.toSorted()) {+ const slashAt = identity.indexOf("/");+ const partition = identity.slice(0, slashAt) as StorePartition;+ const sha = identity.slice(slashAt + 1);+ const stamp = blobStamp(partitionDir(root, partition), sha);+ if (stamp === "absent") lines += `blob ${identity}=absent\n`;+ else return null;+ }+ return lines;+}+/** Device-local lock target of one shard (the lock is `<target>.lock`, never in the store). */export function shardLockTarget(deviceStateDir: string,diff --git a/src/mcp/brain/admin-policy-tools.ts b/src/mcp/brain/admin-policy-tools.tsnew file mode 100644index 00000000..237a7f3a--- /dev/null+++ b/src/mcp/brain/admin-policy-tools.ts@@ -0,0 +1,319 @@+/**+ * The vault-policy tools of the admin family: the label vocabulary+ * (`brain_labels`), the frontmatter tier guard (`brain_tiers`) and the+ * secret custody surface (`brain_secrets`). Split from `admin-tools.ts`+ * (task 3.19); registration happens through that module's registry,+ * which preserves the public ADMIN_TOOLS surface.+ */++import { existsSync } from "node:fs";+import { relative } from "node:path";+import { toPosix } from "../../core/path-safety.ts";+import { reachView } from "../../core/brain/reach-view.ts";+import { resolveAgentName } from "../../core/config.ts";+import { resolveSearchConfig } from "../../core/search/index.ts";+import { Store } from "../../core/search/store.ts";+import {+ assignNoteLabel,+ LabelVocabularyError,+ readLabels,+ removeNoteLabel,+} from "../../core/brain/labels.ts";+import { LabelSuggestPrivateNoteError, suggestNoteLabels } from "../../core/brain/label-suggest.ts";+import { StandingRulesWriteRefusedError } from "../../core/brain/standing-rules.ts";+import { GovernedPathWriteRefusedError } from "../../core/write-binding/index.ts";+import { assertVaultIdentityForWrite } from "../../core/brain/vault-identity.ts";+import { loadSchemaPack } from "../../core/brain/schema-pack.ts";+import { listSecrets } from "../../core/brain/secrets/store.ts";+import { runWithSecret, SecretExecDeniedError } from "../../core/brain/secrets/exec.ts";+import { readableAtContextReach, readableAtContextReachOrUndefined } from "./reach-readable.ts";+import { requiredStringArg } from "./shared.ts";+import { writeFrontmatterAtomic } from "../../core/vault.ts";+import { resolveNotePath } from "../../core/brain/note-path.ts";+import type { FrontmatterMap } from "../../core/types.ts";+import { parseFrontmatter } from "../../core/vault.ts";+import { normalizeAgentArgument } from "../../core/agent-identity.ts";+import { coerceStrList, unknownOperationError } from "../coerce.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import type { ServerContext } from "../tool-contract.ts";+import { contextReach } from "../tool-contract.ts";++/**+ * `brain_labels suggest`: advisory decision-model suggestions (use+ * `labels`). Read-only; never assigns.+ */+export async function labelsSuggest(+ ctx: ServerContext,+ args: Record<string, unknown>,+ path: string,+): Promise<Record<string, unknown>> {+ const abs = vaultContainedPath(ctx.vault, path, "brain_labels suggest");+ // Same reach rule as `show`: a page reserved against remote reads+ // answers exactly as an absent one.+ const view = reachView(ctx.vault, contextReach(ctx));+ if (!view.visible(toPosix(relative(ctx.vault, abs)))) {+ throw new MCPError(INVALID_PARAMS, `brain_labels suggest: note does not exist: ${path}`);+ }+ const dimensions = coerceStrList(args, "dimensions");+ try {+ const result = await suggestNoteLabels(ctx.vault, path, {+ pack: loadSchemaPack(ctx.vault),+ ...(dimensions.length > 0 ? { dimensions } : {}),+ configPath: ctx.configPath,+ });+ return { ...result };+ } catch (exc) {+ if (exc instanceof LabelVocabularyError || exc instanceof LabelSuggestPrivateNoteError) {+ throw new MCPError(INVALID_PARAMS, `brain_labels suggest: ${exc.message}`);+ }+ throw exc;+ }+}++/** Controlled-vocabulary classification over the schema pack's labels. */+export function toolBrainLabels(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Record<string, unknown> | Promise<Record<string, unknown>> {+ const op = args["operation"];+ if (op !== "assign" && op !== "remove" && op !== "show" && op !== "suggest") {+ throw unknownOperationError("brain_labels: operation must be assign|remove|show|suggest");+ }+ // a-label-is-not-a-boundary, U12: the ARGUMENT is right and the+ // VALIDATOR's message was wrong. `path` is the only name this tool+ // declares for the note - a caller passing `id` is refused by name by+ // the unknown-argument gate (`src/mcp/argument-guard.ts`) before the+ // handler runs - but this check answered an ABSENT `path` with a+ // sentence about its SHAPE, so a caller who sent the wrong name read+ // it as "my path is malformed" and retried the same call. The shared+ // coercion already tells absence and malformation apart, and stamps+ // the operation into both, so the two failures no longer share a+ // sentence.+ const path = requiredStringArg(`brain_labels ${op}`, args, "path");+ if (op === "suggest") return labelsSuggest(ctx, args, path);+ if (op === "show") {+ const abs = vaultContainedPath(ctx.vault, path, "brain_labels show");+ // A metadata oracle otherwise (audit L8): at remote reach a page+ // reserved against remote reads answers exactly as an absent one, so+ // the reply cannot prove it exists. At local reach the view is a no-op.+ const view = reachView(ctx.vault, contextReach(ctx));+ if (!view.visible(toPosix(relative(ctx.vault, abs)))) {+ throw new MCPError(INVALID_PARAMS, `brain_labels show: note does not exist: ${path}`);+ }+ const [metadata] = parseFrontmatter(abs);+ return { path, labels: readLabels(metadata) };+ }+ const pack = loadSchemaPack(ctx.vault);+ const dimension = args["dimension"];+ if (typeof dimension !== "string" || dimension.trim() === "") {+ throw new MCPError(INVALID_PARAMS, `brain_labels ${op}: dimension must be non-empty`);+ }+ // A note the caller may not read at its reach is refused as a missing+ // one, before its frontmatter is read or written.+ const readable = readableAtContextReachOrUndefined(ctx);+ const reach = readable !== undefined ? { readable } : {};+ try {+ if (op === "remove") {+ return { ...removeNoteLabel(ctx.vault, path, { dimension, pack, ...reach }) };+ }+ const value = args["value"];+ if (typeof value !== "string" || value.trim() === "") {+ throw new MCPError(INVALID_PARAMS, "brain_labels assign: value must be non-empty");+ }+ const agentArg = args["agent"];+ const agent =+ normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??+ resolveAgentName(ctx.configPath ?? undefined);+ return {+ ...assignNoteLabel(ctx.vault, path, {+ dimension,+ value,+ pack,+ agent,+ now: new Date(),+ ...reach,+ }),+ };+ } catch (exc) {+ if (exc instanceof LabelVocabularyError) {+ throw new MCPError(INVALID_PARAMS, `brain_labels ${op}: ${exc.message}`);+ }+ // A refused target is a bad argument, not a server fault: the caller+ // named a file this surface will not rewrite, and the message says+ // which one so the agent stops trying rather than retrying blind.+ if (exc instanceof StandingRulesWriteRefusedError) {+ throw new MCPError(INVALID_PARAMS, `brain_labels ${op}: ${exc.message}`);+ }+ // The Brain machinery root and the operator's declared write binding+ // refuse the same way: the caller named a target the governance+ // envelope does not admit, and naming it back is the whole answer.+ if (exc instanceof GovernedPathWriteRefusedError) {+ throw new MCPError(INVALID_PARAMS, `brain_labels ${op}: ${exc.message}`);+ }+ throw exc;+ }+}++// ----- brain_tiers (t_3f92d3f1) ----------------------------------------------++/** Staged repair surface for identity-tier frontmatter hand-edits. */+export async function toolBrainTiers(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const op = args["operation"];+ if (op !== "check" && op !== "restore" && op !== "accept") {+ throw unknownOperationError("brain_tiers: operation must be check|restore|accept");+ }+ const searchConfig = resolveSearchConfig({+ vault: ctx.vault,+ configPath: ctx.configPath ?? undefined,+ });+ if (op === "check") {+ // Fail-soft: a vault that was never indexed has no snapshots and+ // therefore no drift - not an error.+ if (!existsSync(searchConfig.dbPath)) return { findings: [] };+ // A drift row names a page's path and both values of one of its+ // identity fields, so only the rows of pages the caller may read at+ // its reach are listed.+ const readable = readableAtContextReach(ctx);+ const store = await Store.open(searchConfig, { mode: "read" });+ try {+ return { findings: store.listTierDrift().filter((row) => readable(row.path)) };+ } finally {+ await store.close();+ }+ }+ // Same conflation as `brain_labels` above, same cure: `path` is+ // optional for `check` and required for the two write operations, and+ // "you did not send it" is a different sentence from "what you sent is+ // not a path".+ const path = requiredStringArg(`brain_tiers ${op}`, args, "path");+ if (op === "restore" && args["apply"] !== true) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_tiers restore: pass apply=true - restore writes the file",+ );+ }+ // Both remaining operations WRITE - `restore` rewrites the note's+ // frontmatter, `accept` rewrites the tier snapshot - so both answer to+ // the freeze the way every other content write does. The dispatcher+ // turns the thrown `VaultFrozenError` into the structured refusal and+ // records the attempt, so a frozen vault is not writable through this+ // surface merely because it is a repair surface.+ assertVaultIdentityForWrite(ctx.vault);+ const field = typeof args["field"] === "string" ? (args["field"] as string) : undefined;+ if (!existsSync(searchConfig.dbPath)) {+ throw new MCPError(INVALID_PARAMS, `brain_tiers ${op}: the vault has no search index yet`);+ }+ const store = await Store.open(searchConfig, { mode: "write" });+ try {+ // A page the caller may not read at its reach is refused as one the+ // index never saw, before anything about its drift is read or written.+ const docId = readableAtContextReach(ctx)(path) ? store.getDocumentIdByPath(path) : null;+ if (docId === null) {+ throw new MCPError(INVALID_PARAMS, `brain_tiers ${op}: not indexed: ${path}`);+ }+ const rows = store+ .listTierDrift()+ .filter((r) => r.documentId === docId && (field === undefined || r.field === field));+ if (rows.length === 0) {+ throw new MCPError(INVALID_PARAMS, `brain_tiers ${op}: no open drift for ${path}`);+ }+ if (op === "restore") {+ const absolute = vaultContainedPath(ctx.vault, path, "brain_tiers restore");+ const [metadata, body] = parseFrontmatter(absolute);+ const next = { ...metadata };+ for (const r of rows) {+ next[r.field] = frontmatterValueFromSnapshot(r.expected, r.field);+ }+ writeFrontmatterAtomic(absolute, next, body, { overwrite: true });+ for (const r of rows) store.clearTierDrift(docId, r.field);+ return { restored: rows.map((r) => r.field), path };+ }+ const snapshot: Record<string, unknown> = { ...store.getTierSnapshot(docId) };+ for (const r of rows) {+ snapshot[r.field] = r.actual;+ store.clearTierDrift(docId, r.field);+ }+ store.setTierSnapshot(docId, snapshot);+ return { accepted: rows.map((r) => r.field), path };+ } finally {+ await store.close();+ }+}++/** Resolve a vault-relative path, refusing traversal and symlink escapes. */+export function vaultContainedPath(vault: string, relPath: string, label: string): string {+ try {+ return resolveNotePath(vault, relPath);+ } catch (exc) {+ throw new MCPError(INVALID_PARAMS, `${label}: ${(exc as Error).message}`);+ }+}++/** Narrow a snapshot value to the shapes frontmatter can carry. */+export function frontmatterValueFromSnapshot(+ value: unknown,+ field: string,+): FrontmatterMap[string] {+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {+ return value;+ }+ if (Array.isArray(value) && value.every((v): v is string => typeof v === "string")) {+ return value;+ }+ throw new MCPError(+ INVALID_PARAMS,+ `brain_tiers restore: snapshot value for "${field}" is not a frontmatter scalar or string array`,+ );+}++// ----- brain_secrets (t_0b134404) ---------------------------------------------++/**+ * Capability-gated custody, agent-facing subset: list metadata and+ * run an allowlisted command. Deliberately NO set/get over MCP - the+ * material enters via the operator's CLI and leaves only into a+ * subprocess env.+ */+export async function toolBrainSecrets(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const op = args["operation"];+ if (op !== "list" && op !== "run") {+ throw unknownOperationError("brain_secrets: operation must be list|run");+ }+ if (op === "list") {+ return { secrets: listSecrets(ctx.vault) };+ }+ const name = args["name"];+ if (typeof name !== "string" || name.trim() === "") {+ throw new MCPError(INVALID_PARAMS, "brain_secrets run: name must be non-empty");+ }+ const command = args["command"];+ if (+ !Array.isArray(command) ||+ command.length === 0 ||+ !command.every((part): part is string => typeof part === "string")+ ) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_secrets run: command must be a non-empty array of strings",+ );+ }+ const agentArg = args["agent"];+ const agent =+ normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??+ resolveAgentName(ctx.configPath ?? undefined);+ try {+ const result = await runWithSecret(ctx.vault, name, command, { agent, now: new Date() });+ return { exit_code: result.exitCode, stdout: result.stdout, stderr: result.stderr };+ } catch (exc) {+ if (exc instanceof SecretExecDeniedError) {+ throw new MCPError(INVALID_PARAMS, `brain_secrets run: ${exc.message}`);+ }+ throw exc;+ }+}diff --git a/src/mcp/brain/admin-tools.ts b/src/mcp/brain/admin-tools.tsindex d78b4475..4f182c95 100644--- a/src/mcp/brain/admin-tools.ts+++ b/src/mcp/brain/admin-tools.ts@@ -6,31 +6,11 @@* BRAIN_TOOLS surface.*/-import { existsSync } from "node:fs";-import { relative } from "node:path";--import { toPosix } from "../../core/path-safety.ts";import { TRANSPORT_REACH } from "../../core/graph/transport-reach.ts";-import { reachView } from "../../core/brain/reach-view.ts";import { resolveAgentName } from "../../core/config.ts";import { resolveSearchConfig } from "../../core/search/index.ts";-import { Store } from "../../core/search/store.ts";-import {- assignNoteLabel,- LabelVocabularyError,- readLabels,- removeNoteLabel,-} from "../../core/brain/labels.ts";-import { LabelSuggestPrivateNoteError, suggestNoteLabels } from "../../core/brain/label-suggest.ts";-import { StandingRulesWriteRefusedError } from "../../core/brain/standing-rules.ts";-import { GovernedPathWriteRefusedError } from "../../core/write-binding/index.ts";-import { assertVaultIdentityForWrite } from "../../core/brain/vault-identity.ts";-import { loadSchemaPack } from "../../core/brain/schema-pack.ts";-import { listSecrets } from "../../core/brain/secrets/store.ts";-import { runWithSecret, SecretExecDeniedError } from "../../core/brain/secrets/exec.ts";import type { ProgressSink } from "../../core/brain/progress.ts";-import { readableAtContextReach, readableAtContextReachOrUndefined } from "./reach-readable.ts";-import { requiredStringArg, toolSafeguard } from "./shared.ts";+import { toolSafeguard } from "./shared.ts";import { pageSlice } from "../../core/brain/offset-cursor.ts";import { cursorOffsetArg, CURSOR_SCHEMA } from "./pagination.ts";import { currentLease } from "../../core/brain/maintenance/lease.ts";@@ -56,293 +36,13 @@ import {type LaneTask,type LaneTaskId,} from "../../core/brain/maintenance/lane.ts";-import { writeFrontmatterAtomic } from "../../core/vault.ts";-import { resolveNotePath } from "../../core/brain/note-path.ts";-import type { FrontmatterMap } from "../../core/types.ts";-import { parseFrontmatter } from "../../core/vault.ts";import { normalizeAgentArgument } from "../../core/agent-identity.ts";import { coerceInt, coerceStrList, unknownOperationError } from "../coerce.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { contextReach } from "../tool-contract.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";--/**- * `brain_labels suggest`: advisory decision-model suggestions (use- * `labels`). Read-only; never assigns.- */-async function labelsSuggest(- ctx: ServerContext,- args: Record<string, unknown>,- path: string,-): Promise<Record<string, unknown>> {- const abs = vaultContainedPath(ctx.vault, path, "brain_labels suggest");- // Same reach rule as `show`: a page reserved against remote reads- // answers exactly as an absent one.- const view = reachView(ctx.vault, contextReach(ctx));- if (!view.visible(toPosix(relative(ctx.vault, abs)))) {- throw new MCPError(INVALID_PARAMS, `brain_labels suggest: note does not exist: ${path}`);- }- const dimensions = coerceStrList(args, "dimensions");- try {- const result = await suggestNoteLabels(ctx.vault, path, {- pack: loadSchemaPack(ctx.vault),- ...(dimensions.length > 0 ? { dimensions } : {}),- configPath: ctx.configPath,- });- return { ...result };- } catch (exc) {- if (exc instanceof LabelVocabularyError || exc instanceof LabelSuggestPrivateNoteError) {- throw new MCPError(INVALID_PARAMS, `brain_labels suggest: ${exc.message}`);- }- throw exc;- }-}--/** Controlled-vocabulary classification over the schema pack's labels. */-function toolBrainLabels(- ctx: ServerContext,- args: Record<string, unknown>,-): Record<string, unknown> | Promise<Record<string, unknown>> {- const op = args["operation"];- if (op !== "assign" && op !== "remove" && op !== "show" && op !== "suggest") {- throw unknownOperationError("brain_labels: operation must be assign|remove|show|suggest");- }- // a-label-is-not-a-boundary, U12: the ARGUMENT is right and the- // VALIDATOR's message was wrong. `path` is the only name this tool- // declares for the note - a caller passing `id` is refused by name by- // the unknown-argument gate (`src/mcp/argument-guard.ts`) before the- // handler runs - but this check answered an ABSENT `path` with a- // sentence about its SHAPE, so a caller who sent the wrong name read- // it as "my path is malformed" and retried the same call. The shared- // coercion already tells absence and malformation apart, and stamps- // the operation into both, so the two failures no longer share a- // sentence.- const path = requiredStringArg(`brain_labels ${op}`, args, "path");- if (op === "suggest") return labelsSuggest(ctx, args, path);- if (op === "show") {- const abs = vaultContainedPath(ctx.vault, path, "brain_labels show");- // A metadata oracle otherwise (audit L8): at remote reach a page- // reserved against remote reads answers exactly as an absent one, so- // the reply cannot prove it exists. At local reach the view is a no-op.- const view = reachView(ctx.vault, contextReach(ctx));- if (!view.visible(toPosix(relative(ctx.vault, abs)))) {- throw new MCPError(INVALID_PARAMS, `brain_labels show: note does not exist: ${path}`);- }- const [metadata] = parseFrontmatter(abs);- return { path, labels: readLabels(metadata) };- }- const pack = loadSchemaPack(ctx.vault);- const dimension = args["dimension"];- if (typeof dimension !== "string" || dimension.trim() === "") {- throw new MCPError(INVALID_PARAMS, `brain_labels ${op}: dimension must be non-empty`);- }- // A note the caller may not read at its reach is refused as a missing- // one, before its frontmatter is read or written.- const readable = readableAtContextReachOrUndefined(ctx);- const reach = readable !== undefined ? { readable } : {};- try {- if (op === "remove") {- return { ...removeNoteLabel(ctx.vault, path, { dimension, pack, ...reach }) };- }- const value = args["value"];- if (typeof value !== "string" || value.trim() === "") {- throw new MCPError(INVALID_PARAMS, "brain_labels assign: value must be non-empty");- }- const agentArg = args["agent"];- const agent =- normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??- resolveAgentName(ctx.configPath ?? undefined);- return {- ...assignNoteLabel(ctx.vault, path, {- dimension,- value,- pack,- agent,- now: new Date(),- ...reach,- }),- };- } catch (exc) {- if (exc instanceof LabelVocabularyError) {- throw new MCPError(INVALID_PARAMS, `brain_labels ${op}: ${exc.message}`);- }- // A refused target is a bad argument, not a server fault: the caller- // named a file this surface will not rewrite, and the message says- // which one so the agent stops trying rather than retrying blind.- if (exc instanceof StandingRulesWriteRefusedError) {- throw new MCPError(INVALID_PARAMS, `brain_labels ${op}: ${exc.message}`);- }- // The Brain machinery root and the operator's declared write binding- // refuse the same way: the caller named a target the governance- // envelope does not admit, and naming it back is the whole answer.- if (exc instanceof GovernedPathWriteRefusedError) {- throw new MCPError(INVALID_PARAMS, `brain_labels ${op}: ${exc.message}`);- }- throw exc;- }-}--// ----- brain_tiers (t_3f92d3f1) ------------------------------------------------/** Staged repair surface for identity-tier frontmatter hand-edits. */-async function toolBrainTiers(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const op = args["operation"];- if (op !== "check" && op !== "restore" && op !== "accept") {- throw unknownOperationError("brain_tiers: operation must be check|restore|accept");- }- const searchConfig = resolveSearchConfig({- vault: ctx.vault,- configPath: ctx.configPath ?? undefined,- });- if (op === "check") {- // Fail-soft: a vault that was never indexed has no snapshots and- // therefore no drift - not an error.- if (!existsSync(searchConfig.dbPath)) return { findings: [] };- // A drift row names a page's path and both values of one of its- // identity fields, so only the rows of pages the caller may read at- // its reach are listed.- const readable = readableAtContextReach(ctx);- const store = await Store.open(searchConfig, { mode: "read" });- try {- return { findings: store.listTierDrift().filter((row) => readable(row.path)) };- } finally {- await store.close();- }- }- // Same conflation as `brain_labels` above, same cure: `path` is- // optional for `check` and required for the two write operations, and- // "you did not send it" is a different sentence from "what you sent is- // not a path".- const path = requiredStringArg(`brain_tiers ${op}`, args, "path");- if (op === "restore" && args["apply"] !== true) {- throw new MCPError(- INVALID_PARAMS,- "brain_tiers restore: pass apply=true - restore writes the file",- );- }- // Both remaining operations WRITE - `restore` rewrites the note's- // frontmatter, `accept` rewrites the tier snapshot - so both answer to- // the freeze the way every other content write does. The dispatcher- // turns the thrown `VaultFrozenError` into the structured refusal and- // records the attempt, so a frozen vault is not writable through this- // surface merely because it is a repair surface.- assertVaultIdentityForWrite(ctx.vault);- const field = typeof args["field"] === "string" ? (args["field"] as string) : undefined;- if (!existsSync(searchConfig.dbPath)) {- throw new MCPError(INVALID_PARAMS, `brain_tiers ${op}: the vault has no search index yet`);- }- const store = await Store.open(searchConfig, { mode: "write" });- try {- // A page the caller may not read at its reach is refused as one the- // index never saw, before anything about its drift is read or written.- const docId = readableAtContextReach(ctx)(path) ? store.getDocumentIdByPath(path) : null;- if (docId === null) {- throw new MCPError(INVALID_PARAMS, `brain_tiers ${op}: not indexed: ${path}`);- }- const rows = store- .listTierDrift()- .filter((r) => r.documentId === docId && (field === undefined || r.field === field));- if (rows.length === 0) {- throw new MCPError(INVALID_PARAMS, `brain_tiers ${op}: no open drift for ${path}`);- }- if (op === "restore") {- const absolute = vaultContainedPath(ctx.vault, path, "brain_tiers restore");- const [metadata, body] = parseFrontmatter(absolute);- const next = { ...metadata };- for (const r of rows) {- next[r.field] = frontmatterValueFromSnapshot(r.expected, r.field);- }- writeFrontmatterAtomic(absolute, next, body, { overwrite: true });- for (const r of rows) store.clearTierDrift(docId, r.field);- return { restored: rows.map((r) => r.field), path };- }- const snapshot: Record<string, unknown> = { ...store.getTierSnapshot(docId) };- for (const r of rows) {- snapshot[r.field] = r.actual;- store.clearTierDrift(docId, r.field);- }- store.setTierSnapshot(docId, snapshot);- return { accepted: rows.map((r) => r.field), path };- } finally {- await store.close();- }-}--/** Resolve a vault-relative path, refusing traversal and symlink escapes. */-function vaultContainedPath(vault: string, relPath: string, label: string): string {- try {- return resolveNotePath(vault, relPath);- } catch (exc) {- throw new MCPError(INVALID_PARAMS, `${label}: ${(exc as Error).message}`);- }-}--/** Narrow a snapshot value to the shapes frontmatter can carry. */-function frontmatterValueFromSnapshot(value: unknown, field: string): FrontmatterMap[string] {- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {- return value;- }- if (Array.isArray(value) && value.every((v): v is string => typeof v === "string")) {- return value;- }- throw new MCPError(- INVALID_PARAMS,- `brain_tiers restore: snapshot value for "${field}" is not a frontmatter scalar or string array`,- );-}--// ----- brain_secrets (t_0b134404) -----------------------------------------------/**- * Capability-gated custody, agent-facing subset: list metadata and- * run an allowlisted command. Deliberately NO set/get over MCP - the- * material enters via the operator's CLI and leaves only into a- * subprocess env.- */-async function toolBrainSecrets(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const op = args["operation"];- if (op !== "list" && op !== "run") {- throw unknownOperationError("brain_secrets: operation must be list|run");- }- if (op === "list") {- return { secrets: listSecrets(ctx.vault) };- }- const name = args["name"];- if (typeof name !== "string" || name.trim() === "") {- throw new MCPError(INVALID_PARAMS, "brain_secrets run: name must be non-empty");- }- const command = args["command"];- if (- !Array.isArray(command) ||- command.length === 0 ||- !command.every((part): part is string => typeof part === "string")- ) {- throw new MCPError(- INVALID_PARAMS,- "brain_secrets run: command must be a non-empty array of strings",- );- }- const agentArg = args["agent"];- const agent =- normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??- resolveAgentName(ctx.configPath ?? undefined);- try {- const result = await runWithSecret(ctx.vault, name, command, { agent, now: new Date() });- return { exit_code: result.exitCode, stdout: result.stdout, stderr: result.stderr };- } catch (exc) {- if (exc instanceof SecretExecDeniedError) {- throw new MCPError(INVALID_PARAMS, `brain_secrets run: ${exc.message}`);- }- throw exc;- }-}+import { toolBrainLabels, toolBrainSecrets, toolBrainTiers } from "./admin-policy-tools.ts";// ----- brain_maintenance (t_166d1226) ------------------------------------------diff --git a/src/mcp/brain/brief-tools.ts b/src/mcp/brain/brief-tools.tsindex 629329ff..2927ad0c 100644--- a/src/mcp/brain/brief-tools.ts+++ b/src/mcp/brain/brief-tools.ts@@ -6,662 +6,23 @@* BRAIN_TOOLS surface.*/-import { resolveLinkOutputFormat, resolveTriggerCooldownDays } from "../../core/config.ts";-import { buildMorningBrief } from "../../core/brain/morning-brief.ts";-import {- deliverBriefTriggers,- renderTriggerBriefSection,-} from "../../core/brain/triggers/brief.ts";-import {- readTriggerQueueFailures,- renderTriggerQueueFailures,- unreadableTriggerJson,- type TriggerQueueFailures,-} from "../../core/brain/triggers/store.ts";-import { renderOpenDecisionsBriefSection } from "../../core/brain/decisions/brief.ts";-import { buildTimelineIndex } from "../../core/brain/temporal/build-index.ts";-import {- collectSourcePointers,- computeVaultDelta,- countByKind,- type PeriodStatusTransition,-} from "../../core/brain/temporal/period-common.ts";-import { selectEvents } from "../../core/brain/temporal/select-events.ts";-import type { TimelineIndex } from "../../core/brain/temporal/types.ts";-import { type ArtifactRef, type ArtifactRefView } from "../../core/brain/artifact-ref-view.ts";-import { PREF_ID_PREFIX } from "../../core/brain/dream-plan.ts";-import { buildTodayDashboard } from "../../core/brain/today-dashboard.ts";-import { buildDailyBrief } from "../../core/brain/temporal/daily-brief.ts";-import { buildWeeklySynthesis } from "../../core/brain/temporal/weekly-brief.ts";-import { loadTemporalConfigSafe } from "../../core/brain/policy.ts";-import { resolveOwnerScopeDelivery } from "../../core/brain/preferences-collect.ts";-import { renderDigest, type DigestFormat } from "../../core/brain/digest.ts";-import { dream } from "../../core/brain/dream.ts";-import {- buildMonthlyReview,- normalizeMonthlyReviewMonth,-} from "../../core/brain/monthly-review.ts";-import { buildOperatorSummary } from "../../core/brain/trust/operator-summary.ts";-import type { VerificationDeltaEntry } from "../../core/brain/trust/compute-verification-delta.ts";-import { everyArtifactRefView } from "../../core/brain/artifact-ref-view.ts";-import { doctorIssueRefs, type DoctorIssueNaming } from "../../core/brain/diagnostics.ts";-import type { ActionItem } from "../../core/brain/maintenance/action-scorer.ts";-import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";-import { reachView } from "../../core/brain/reach-view.ts";-import { isoDate } from "../../core/brain/time.ts";-import { captureReportDelta } from "../../core/brain/report-snapshot.ts";-import { TRANSPORT_REACH } from "../../core/graph/transport-reach.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";-import { contextReach, type ServerContext, type ToolDefinition } from "../tool-contract.ts";-import { readableAtContextReachOrUndefined } from "./reach-readable.ts";-import { eventAtReach, eventsAtReach, recordRefs, requestRefView } from "./reach-events.ts";-import { vaultPathField } from "../vault-path-field.ts";+import { type ServerContext, type ToolDefinition } from "../tool-contract.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";-import {- AGENT_SCOPE_ARG_NAME,- AGENT_SCOPE_SCHEMA,- coerceAgentScope,- coerceIsoDate,- coerceFormat,-} from "../coerce.ts";-import {- coerceIsoTimestampOrDate,- coerceNonNegativeInteger,- coercePositiveInteger,- dispatchByView,- localizeEnvelope,- toolSafeguard,-} from "./shared.ts";+import { AGENT_SCOPE_ARG_NAME, AGENT_SCOPE_SCHEMA } from "../coerce.ts";+import { dispatchByView, localizeEnvelope } from "./shared.ts";import type { ProgressSink } from "../../core/brain/progress.ts";-import { OPERATION } from "../../core/brain/safeguard.ts";+import {+ toolBrainDailyBrief,+ toolBrainDigest,+ toolBrainMonthlyReview,+ toolBrainMorningBrief,+ toolBrainOperatorSummary,+ toolBrainToday,+ toolBrainWeeklySynthesis,+} from "./brief-view-tools.ts";/** What a reader outside the operator's queue is told about it: nothing. */-const NO_TRIGGER_QUEUE_FAILURES: TriggerQueueFailures = Object.freeze({- unreadable: Object.freeze([]),- queueError: null,-});--async function toolBrainMorningBrief(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const topK = coercePositiveInteger("brain_brief view=morning", "top_k", args["top_k"]) ?? 10;- const lookbackDays =- coercePositiveInteger("brain_brief view=morning", "lookback_days", args["lookback_days"]) ?? 7;- const maxCharsPerMemory = coercePositiveInteger(- "brain_brief view=morning",- "max_chars_per_memory",- args["max_chars_per_memory"],- );- const maxTotalChars = coercePositiveInteger(- "brain_brief view=morning",- "max_total_chars",- args["max_total_chars"],- );- const now = new Date();- const agentScope = coerceAgentScope(ctx, args, true);- const readable = readableAtContextReachOrUndefined(ctx);- const brief = buildMorningBrief(ctx.vault, {- now,- topK,- ...(agentScope !== undefined ? { agentScope } : {}),- ...(readable !== undefined ? { readable } : {}),- withholdsPrivate: contextReach(ctx) !== TRANSPORT_REACH.local,- lookbackDays,- ...(maxCharsPerMemory !== undefined ? { maxCharsPerMemory } : {}),- ...(maxTotalChars !== undefined ? { maxTotalChars } : {}),- });- // Pending-trigger section (t_cd1fee79): renders only when a trigger- // scan persisted surfaceable triggers; included triggers are marked- // delivered so a prompt shows once per cooldown window.- //- // Still fail-soft - a broken queue must not cost the operator the rest- // of the brief - but no longer silent. The bare catch this replaces set- // the section to null, so a refusal rendered exactly like an empty- // queue: the one outcome the anti-nag ledger exists to rule out. The- // records that could not be read are collected first and reported- // alongside whatever did render.- //- // The queue and its delivery state belong to the local operator: a- // reader below local reach is shown no trigger, no queue failure, and- // marks nothing delivered.- const operatorQueue = contextReach(ctx) === TRANSPORT_REACH.local;- const triggerFailures: TriggerQueueFailures = operatorQueue- ? readTriggerQueueFailures(ctx.vault, now)- : NO_TRIGGER_QUEUE_FAILURES;- let triggerSection: ReturnType<typeof renderTriggerBriefSection> | null = null;- let triggerQueueError = triggerFailures.queueError;- if (operatorQueue) {- try {- triggerSection = renderTriggerBriefSection(ctx.vault, {- now,- cooldownDays: resolveTriggerCooldownDays(ctx.configPath ?? undefined),- });- if (triggerSection.triggers.length > 0) deliverBriefTriggers(ctx.vault, triggerSection, now);- } catch (err) {- triggerSection = null;- triggerQueueError = (err as Error).message ?? String(err);- }- }- const failureText = renderTriggerQueueFailures({- unreadable: triggerFailures.unreadable,- queueError: triggerQueueError,- });- // Open-decisions section (write-side-trust wave, Task 10): render-only- // - unlike the trigger section there is no delivery marking, because a- // parked question is a standing question with no cooldown. Same- // operator-queue boundary as the triggers: a reader below local reach- // is shown neither the questions nor the unreadable records.- const openDecisions = operatorQueue- ? renderOpenDecisionsBriefSection(ctx.vault)- : { text: "", records: [], unreadable: [] };- const sections = [- brief.text,- triggerSection !== null ? triggerSection.text : "",- failureText,- openDecisions.text,- ].filter((section) => section !== "");- return {- text: sections.join("\n\n"),- preferences: brief.preferences,- open_questions: brief.openQuestions,- recent_notes: brief.recentNotes,- total_chars: brief.totalChars,- ...(triggerSection !== null && triggerSection.triggers.length > 0- ? {- triggers: triggerSection.triggers.map((t) => ({- id: t.id,- kind: t.kind,- urgency: t.urgency,- reason: t.reason,- })),- }- : {}),- ...(triggerFailures.unreadable.length > 0- ? { triggers_unreadable: triggerFailures.unreadable.map(unreadableTriggerJson) }- : {}),- ...(triggerQueueError !== null ? { trigger_queue_error: triggerQueueError } : {}),- ...(openDecisions.records.length > 0- ? {- open_decisions: openDecisions.records.map((r) => ({- id: r.id,- question: r.question,- status: r.status,- })),- }- : {}),- ...(openDecisions.unreadable.length > 0- ? { open_decisions_unreadable: openDecisions.unreadable }- : {}),- };-}--async function toolBrainDigest(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const since = coerceIsoDate(args, "since");- const until = coerceIsoDate(args, "until");- const format = coerceFormat(args) satisfies DigestFormat;-- // Pin ONE effective until instant so the rendered content, the- // snapshot render, and the snapshot date key all describe the same- // window even when the caller omitted `until`.- const effectiveUntil = until ?? new Date();- const agentScope = coerceAgentScope(ctx, args, true);- // The digest is rendered for this reader whenever any rule is live: a- // record below the caller's reach, or withheld by the enforced ownership- // scope, is absent from every row and count. Passing the predicate- // whenever it would withhold anything - rather than only below local- // reach - is the view the `osb://digest/latest` resource renders the- // same caller with, so the agent summary, the backlink counts and the- // connection health cannot count the events and records those sections- // beside them already withhold. With no rule live the predicate is- // absent and the render stays byte-identical to the unfiltered one.- const restricted = contextReach(ctx) !== TRANSPORT_REACH.local;- // The enforced ownership scope (null unless- // `integrity.owner_scope_delivery` is `fail` with a resolved identity)- // decides the snapshot boundary below, beside the reach.- const enforcedScope = resolveOwnerScopeDelivery(ctx.vault, agentScope).enforcedScope;- const renderFor = (renderFormat: DigestFormat, readable?: (rel: string) => boolean) =>- renderDigest(ctx.vault, {- ...(since ? { since } : {}),- until: effectiveUntil,- format: renderFormat,- linkOutputFormat: resolveLinkOutputFormat(ctx.configPath ?? undefined),- ...(agentScope !== undefined ? { agentScope } : {}),- ...(readable !== undefined ? { readable } : {}),- ...(restricted ? { withholdsPrivate: true } : {}),- });- const result = renderFor(format, readableAtContextReachOrUndefined(ctx));-- const envelope: Record<string, unknown> = {- format,- empty: result.empty,- content: result.content,- };- // The snapshot is the vault's own run-over-run record, diffed over the- // digest every record feeds, so a reader below local reach neither- // takes one nor is shown the delta. The same holds for a caller the- // enforced ownership scope narrows: its render is one owner's slice of- // the vault, and persisting that slice under the shared date key would- // hand the next caller a delta whose key paths were computed against- // it - key paths naming artifact ids that caller was never shown.- if (restricted || enforcedScope !== null) return envelope;- // Snapshot the structured summary, not the rendered string: render- // a JSON digest for the snapshot regardless of the caller's format- // so the run-over-run diff keys on data.- const digestDate = isoDate(effectiveUntil);- const snapshotSource = format === "json" ? result.content : renderFor("json").content;- let parsedSnapshot: unknown = null;- try {- parsedSnapshot = JSON.parse(snapshotSource);- } catch {- parsedSnapshot = null;- }- const delta =- parsedSnapshot !== null- ? captureReportDelta(- ctx.vault,- "digest",- digestDate,- parsedSnapshot,- ctx.configPath ? { configPath: ctx.configPath } : {},- )- : null;- return delta !== null ? { ...envelope, delta } : envelope;-}--// ----- brain_query -----------------------------------------------------------/**- * The rows of a daily or weekly envelope this request may see, or- * `null` when no rule is live - local reach with the ownership gate off -- * and the envelope is the builder's own (the digest precedent: a reader- * below local reach is shown only what it may read, and takes no report- * snapshot).- *- * Two rules are asked, through the one adapter the digest's actions rows- * use: the enforced ownership rule (`gatedOwnerScopeView`, live only- * under `integrity.owner_scope_delivery: fail` with a resolved identity)- * and the request's reach-and-readability view. Local reach no longer- * short-circuits past the ownership rule - an enforced identity on the- * operator's own transport is exactly the caller that gate exists to- * scope, and its envelope was otherwise the builder's unfiltered own.- *- * Status transitions, retirements and contradictions are dropped when a- * record they name is withheld. Source pointers are deduplicated- * artifacts with no record left on them, so they are recollected from- * the window's events the reader may see: an artifact cited only by- * evidence on a withheld preference is absent. The counts- * (`events_by_kind`, `vault_delta`) are recomputed from the same- * selection, so a withheld record moves no count either. Because a live- * rule means the envelope is one caller's slice, no report snapshot is- * taken for it - the shared date key must not hold one caller's slice- * for the next caller's delta to diff against.- */-function periodRowsAtReach(- ctx: ServerContext,- index: TimelineIndex,- window: { readonly since: string; readonly until: string },-): PeriodRowsView | null {- const refs = everyArtifactRefView(- gatedOwnerScopeView(ctx.vault, ctx.agentName),- requestRefView(ctx),- );- if (refs.filtersNothing) return null;- const events = eventsAtReach(refs, selectEvents(index, window));- return {- refs,- sourcePointers: collectSourcePointers(events),- eventsByKind: countByKind(events),- vaultDelta: (transitions) => computeVaultDelta(events, transitions),- };-}--interface PeriodRowsView {- readonly refs: ArtifactRefView;- readonly sourcePointers: ReadonlyArray<string>;- readonly eventsByKind: ReturnType<typeof countByKind>;- /** The window's delta over the visible events and the transitions kept for the reader. */- readonly vaultDelta: (- transitions: ReadonlyArray<PeriodStatusTransition>,- ) => ReturnType<typeof computeVaultDelta>;-}--/** A transition or retirement row: the record id and the link it was logged with. */-function transitionRefs(row: {- readonly prefId: string;- readonly link: string;-}): ReadonlyArray<ArtifactRef> {- return [row.link, ...recordRefs(row.prefId)];-}--/** A contradiction row: its record, the topic's record and its evidence artifact. */-function contradictionRefs(row: {- readonly prefId?: string;- readonly topic?: string;- readonly artifact?: string;-}): ReadonlyArray<ArtifactRef> {- return [- row.artifact,- ...recordRefs(row.prefId),- ...(row.topic !== undefined ? recordRefs(`${PREF_ID_PREFIX}${row.topic}`) : []),- ];-}--/**- * `brain_daily_brief` - structured counters + transitions + source- * pointers for one day. Defaults `date` to today UTC when omitted.- */-async function toolBrainDailyBrief(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const dateRaw = args["date"];- const dateCoerced = coerceIsoTimestampOrDate("brain_daily_brief", "date", dateRaw, "date-only");- const date = dateCoerced ?? new Date().toISOString().slice(0, 10);- const cfg = loadTemporalConfigSafe(ctx.vault);- const index = buildTimelineIndex(ctx.vault, {- withholdsPrivate: requestRefView(ctx).withholdsPrivate === true,- });- const brief = buildDailyBrief(index, ctx.vault, date, {- offsetHours: cfg.daily_window_offset_hours,- });- const atReach = periodRowsAtReach(ctx, index, brief.window);- const statusTransitions =- atReach?.refs.keep(brief.statusTransitions, transitionRefs) ?? brief.statusTransitions;- const envelope: Record<string, unknown> = {- vault_path: vaultPathField(ctx),- date: brief.date,- window: brief.window,- events_by_kind: atReach?.eventsByKind ?? brief.eventsByKind,- status_transitions: statusTransitions,- vault_delta: atReach?.vaultDelta(statusTransitions) ?? brief.vaultDelta,- source_pointers: atReach?.sourcePointers ?? brief.sourcePointers,- generated_at: brief.generatedAt,- };- // When any rule is live - below local reach, or an enforced owner- // scope - the envelope is this caller's slice: no snapshot is taken- // under the shared date key and no delta is reported.- if (atReach !== null) return envelope;- // Dual-output: persist a machine snapshot and report the run-over-run- // delta when report snapshots are enabled.- const delta = captureReportDelta(- ctx.vault,- "daily",- brief.date,- envelope,- ctx.configPath ? { configPath: ctx.configPath } : {},- );- return delta !== null ? { ...envelope, delta } : envelope;-}--/**- * `brain_weekly_synthesis` - 7-day deterministic summary plus retired- * and contradictions lists.- */-async function toolBrainWeeklySynthesis(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const weekEndRaw = args["week_end"];- const weekEndCoerced = coerceIsoTimestampOrDate(- "brain_weekly_synthesis",- "week_end",- weekEndRaw,- "date-only",- );- const weekEnd = weekEndCoerced ?? new Date().toISOString().slice(0, 10);- const cfg = loadTemporalConfigSafe(ctx.vault);- const index = buildTimelineIndex(ctx.vault, {- withholdsPrivate: requestRefView(ctx).withholdsPrivate === true,- });- const synth = buildWeeklySynthesis(index, ctx.vault, weekEnd, cfg);- const atReach = periodRowsAtReach(ctx, index, {- since: synth.windowStart,- until: synth.windowEnd,- });- const statusTransitions =- atReach?.refs.keep(synth.statusTransitions, transitionRefs) ?? synth.statusTransitions;- const envelope: Record<string, unknown> = {- vault_path: vaultPathField(ctx),- window_start: synth.windowStart,- window_end: synth.windowEnd,- events_by_kind: atReach?.eventsByKind ?? synth.eventsByKind,- status_transitions: statusTransitions,- retired: atReach?.refs.keep(synth.retired, transitionRefs) ?? synth.retired,- contradictions:- atReach?.refs.keep(synth.contradictions, contradictionRefs) ?? synth.contradictions,- vault_delta: atReach?.vaultDelta(statusTransitions) ?? synth.vaultDelta,- source_pointers: atReach?.sourcePointers ?? synth.sourcePointers,- generated_at: synth.generatedAt,- };- // When any rule is live - below local reach, or an enforced owner- // scope - the envelope is this caller's slice: no snapshot is taken- // under the shared date key and no delta is reported.- if (atReach !== null) return envelope;- const delta = captureReportDelta(- ctx.vault,- "weekly",- weekEnd,- envelope,- ctx.configPath ? { configPath: ctx.configPath } : {},- );- return delta !== null ? { ...envelope, delta } : envelope;-}--// ----- brain_intention (Agent Surface Suite) ----------------------------------async function toolBrainMonthlyReview(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const monthRaw = args["month"];- let month: string | undefined;- if (monthRaw !== undefined && monthRaw !== null) {- if (typeof monthRaw !== "string") {- throw new MCPError(INVALID_PARAMS, "brain_brief view=monthly: month must be YYYY-MM");- }- try {- month = normalizeMonthlyReviewMonth(monthRaw);- } catch {- throw new MCPError(INVALID_PARAMS, "brain_brief view=monthly: month must be YYYY-MM");- }- }- // Below local reach (or under the ownership gate) the month is counted- // over the events this caller may see, in the form it may see them.- const refs = requestRefView(ctx);- const report = buildMonthlyReview(ctx.vault, {- ...(month ? { month } : {}),- ...(refs.filtersNothing ? {} : { eventAtReach: (ev) => eventAtReach(refs, ev) }),- });- return {- schema_version: report.schema_version,- generated_at: report.generated_at,- month: report.month,- window: report.window,- summary: report.summary,- };-}--/**- * Aggregate operator dashboard: trust verdict, doctor / dream- * counts, verification delta summary, ranked maintenance actions,- * and instruction-file ceiling warnings - one read-only call so an- * operator does not run `brain_digest` + `brain_doctor` separately.- */-async function toolBrainOperatorSummary(- ctx: ServerContext,- args: Record<string, unknown>,- onProgress?: ProgressSink,-): Promise<Record<string, unknown>> {- const topRaw = args["top_actions"];- let topActionsN: number | undefined;- if (topRaw !== undefined && topRaw !== null) {- // Strict integer coercion: reject `"3abc"`, `"2.5"`, and other- // shapes `Number.parseInt` would silently accept. Only a pure- // integer literal is allowed.- if (typeof topRaw === "number") {- if (!Number.isInteger(topRaw) || topRaw < 0) {- throw new MCPError(- INVALID_PARAMS,- "brain_brief view=operator: top_actions must be a non-negative integer",- );- }- topActionsN = topRaw;- } else if (typeof topRaw === "string") {- const trimmed = topRaw.trim();- if (trimmed === "" || !/^[0-9]+$/.test(trimmed)) {- throw new MCPError(- INVALID_PARAMS,- "brain_brief view=operator: top_actions must be a non-negative integer",- );- }- topActionsN = Number.parseInt(trimmed, 10);- } else {- throw new MCPError(- INVALID_PARAMS,- "brain_brief view=operator: top_actions must be a non-negative integer",- );- }- }-- const includeDreamRaw = args["include_dream"];- let includeDream: boolean;- if (includeDreamRaw === undefined || includeDreamRaw === null) {- includeDream = true;- } else if (typeof includeDreamRaw === "boolean") {- includeDream = includeDreamRaw;- } else {- throw new MCPError(- INVALID_PARAMS,- "brain_brief view=operator: include_dream must be a boolean",- );- }-- let dreamSummary;- let dreamError: string | undefined;- if (includeDream) {- try {- // The one view behind this dispatcher that runs a consolidation- // pass. It is a DRY RUN, and it still walks the whole Brain tree,- // so it is the slow half of an operator summary on a large vault.- dreamSummary = dream(ctx.vault, {- dryRun: true,- // A dry run is still a full synchronous pass over the Brain tree,- // so it is bounded on the same terms as `brain_dream` itself -- // the budget the operator set for `dream` governs every MCP call- // that reaches one, not just the tool that carries its name.- safeguard: toolSafeguard(ctx, OPERATION.dream),- ...(onProgress !== undefined ? { onProgress } : {}),- });- } catch (err) {- // Surface the failure so callers know the dashboard is missing- // verification + dream signals; do not silently produce a- // partial envelope.- dreamError = (err as Error).message ?? String(err);- }- }- // The doctor, digest and top-action fields - and the trust verdict over- // them - answer at the caller's reach, through the view brain_doctor- // filters its own findings and actions by, and so do the verification- // entries, which name the records the dream claimed. The dry-run- // dream's own warning, uncertain and quarantined counts are taken over- // the whole Brain layer and name no record.- const view = everyArtifactRefView(- gatedOwnerScopeView(ctx.vault, ctx.agentName),- reachView(ctx.vault, contextReach(ctx)),- );- const readable = readableAtContextReachOrUndefined(ctx);- const summary = buildOperatorSummary(ctx.vault, {- ...(dreamSummary ? { dreamSummary } : {}),- ...(topActionsN !== undefined ? { topActionsN } : {}),- ...(readable !== undefined ? { readable } : {}),- withholdsPrivate: view.withholdsPrivate === true,- ...(view.filtersNothing- ? {}- : {- keepIssue: (issue: DoctorIssueNaming) => view.row(...doctorIssueRefs(ctx.vault, issue)),- keepAction: (action: ActionItem) => view.row(action.target),- // Candidate-level visibility for the maintenance collector:- // applied before the scorer caps, so a hidden top-ranked- // action takes no slot a visible one could fill - the same- // question brain_doctor's suggested_actions and the digest's- // actions ask over the same collector output.- visibleRef: view.visible,- keepVerification: (entry: VerificationDeltaEntry) =>- view.row(...recordRefs(entry.id), entry.path),- }),- });- return {- vault_path: vaultPathField(ctx),- trust_verdict: summary.trust_verdict,- digest_summary: summary.digest_summary,- doctor_summary: {- warning_count: summary.doctor_summary.warning_count,- error_count: summary.doctor_summary.error_count,- },- dream_summary: summary.dream_summary,- verification_delta: {- summary: summary.verification_delta.summary,- entries: summary.verification_delta.entries,- },- top_actions: summary.top_actions,- instruction_file_warnings: summary.instruction_file_warnings,- ...(dreamError !== undefined ? { dream_error: dreamError } : {}),- };-}--// ----- brain_unlinked_mentions (v0.10.17) ------------------------------------/**- * `brain_brief view=today` - the today operator dashboard: due/overdue- * obligations, one-off pledges, open loops, merged recent activity, and- * a totals rollup. Read-only; the clock is resolved at the tool boundary- * so the core builder stays deterministic. Write-back (the `@osb set`- * engine) stays CLI-only in this release and is deliberately not- * exposed here.- */-async function toolBrainToday(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- // Non-negative (0 allowed): the core `buildTodayDashboard` and the CLI- // both accept a zero-day window and a zero-entry limit, so the MCP surface- // must not reject what they honour.- const lookbackDays = coerceNonNegativeInteger(- "brain_brief view=today",- "lookback_days",- args["lookback_days"],- );- const limit = coerceNonNegativeInteger("brain_brief view=today", "limit", args["limit"]);- // The recent-activity section renders log events; below local reach- // (or under the ownership gate) it shows them as this caller may see- // them, before the limit and the totals.- const refs = requestRefView(ctx);- // Obligation pages, pledge pages and open-loop notes are listed only- // when the caller may read them, before the totals.- const readable = readableAtContextReachOrUndefined(ctx);- const dashboard = buildTodayDashboard(ctx.vault, {- now: new Date(),- ...(refs.filtersNothing ? {} : { eventAtReach: (ev) => eventAtReach(refs, ev) }),- ...(readable === undefined ? {} : { readable }),- ...(lookbackDays !== undefined ? { activityLookbackDays: lookbackDays } : {}),- ...(limit !== undefined ? { activityLimit: limit } : {}),- });- return {- vault_path: vaultPathField(ctx),- text: dashboard.text,- obligations: dashboard.obligations,- pledges: dashboard.pledges,- open_loops: dashboard.openLoops,- recent_activity: dashboard.recentActivity,- totals: dashboard.totals,- errors: dashboard.errors,- };-}-const BRIEF_VIEW_HANDLERS: Readonly<Record<string,diff --git a/src/mcp/brain/brief-view-tools.ts b/src/mcp/brain/brief-view-tools.tsnew file mode 100644index 00000000..5c73d2b9--- /dev/null+++ b/src/mcp/brain/brief-view-tools.ts@@ -0,0 +1,654 @@+/**+ * The per-view brief handlers (task 3.19): the morning brief, the+ * compiled digest, the daily, weekly and monthly reviews, the operator+ * summary and the today view, each answered at the caller's reach. Split+ * from `brief-tools.ts`; registration happens through that module's+ * dispatcher and registry, which preserve the public BRIEF_TOOLS+ * surface.+ */++import { resolveLinkOutputFormat, resolveTriggerCooldownDays } from "../../core/config.ts";+import { buildMorningBrief } from "../../core/brain/morning-brief.ts";+import {+ deliverBriefTriggers,+ renderTriggerBriefSection,+} from "../../core/brain/triggers/brief.ts";+import {+ readTriggerQueueFailures,+ renderTriggerQueueFailures,+ unreadableTriggerJson,+ type TriggerQueueFailures,+} from "../../core/brain/triggers/store.ts";+import { renderOpenDecisionsBriefSection } from "../../core/brain/decisions/brief.ts";+import { buildTimelineIndex } from "../../core/brain/temporal/build-index.ts";+import {+ collectSourcePointers,+ computeVaultDelta,+ countByKind,+ type PeriodStatusTransition,+} from "../../core/brain/temporal/period-common.ts";+import { selectEvents } from "../../core/brain/temporal/select-events.ts";+import type { TimelineIndex } from "../../core/brain/temporal/types.ts";+import { type ArtifactRef, type ArtifactRefView } from "../../core/brain/artifact-ref-view.ts";+import { PREF_ID_PREFIX } from "../../core/brain/dream-plan.ts";+import { buildTodayDashboard } from "../../core/brain/today-dashboard.ts";+import { buildDailyBrief } from "../../core/brain/temporal/daily-brief.ts";+import { buildWeeklySynthesis } from "../../core/brain/temporal/weekly-brief.ts";+import { loadTemporalConfigSafe } from "../../core/brain/policy.ts";+import { resolveOwnerScopeDelivery } from "../../core/brain/preferences-collect.ts";+import { renderDigest, type DigestFormat } from "../../core/brain/digest.ts";+import { dream } from "../../core/brain/dream.ts";+import {+ buildMonthlyReview,+ normalizeMonthlyReviewMonth,+} from "../../core/brain/monthly-review.ts";+import { buildOperatorSummary } from "../../core/brain/trust/operator-summary.ts";+import type { VerificationDeltaEntry } from "../../core/brain/trust/compute-verification-delta.ts";+import { everyArtifactRefView } from "../../core/brain/artifact-ref-view.ts";+import { doctorIssueRefs, type DoctorIssueNaming } from "../../core/brain/diagnostics.ts";+import type { ActionItem } from "../../core/brain/maintenance/action-scorer.ts";+import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";+import { reachView } from "../../core/brain/reach-view.ts";+import { isoDate } from "../../core/brain/time.ts";+import { captureReportDelta } from "../../core/brain/report-snapshot.ts";+import { TRANSPORT_REACH } from "../../core/graph/transport-reach.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import { contextReach, type ServerContext } from "../tool-contract.ts";+import { readableAtContextReachOrUndefined } from "./reach-readable.ts";+import { eventAtReach, eventsAtReach, recordRefs, requestRefView } from "./reach-events.ts";+import { vaultPathField } from "../vault-path-field.ts";+import { coerceAgentScope, coerceIsoDate, coerceFormat } from "../coerce.ts";+import {+ coerceIsoTimestampOrDate,+ coerceNonNegativeInteger,+ coercePositiveInteger,+ toolSafeguard,+} from "./shared.ts";+import type { ProgressSink } from "../../core/brain/progress.ts";+import { OPERATION } from "../../core/brain/safeguard.ts";++export const NO_TRIGGER_QUEUE_FAILURES: TriggerQueueFailures = Object.freeze({+ unreadable: Object.freeze([]),+ queueError: null,+});++export async function toolBrainMorningBrief(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const topK = coercePositiveInteger("brain_brief view=morning", "top_k", args["top_k"]) ?? 10;+ const lookbackDays =+ coercePositiveInteger("brain_brief view=morning", "lookback_days", args["lookback_days"]) ?? 7;+ const maxCharsPerMemory = coercePositiveInteger(+ "brain_brief view=morning",+ "max_chars_per_memory",+ args["max_chars_per_memory"],+ );+ const maxTotalChars = coercePositiveInteger(+ "brain_brief view=morning",+ "max_total_chars",+ args["max_total_chars"],+ );+ const now = new Date();+ const agentScope = coerceAgentScope(ctx, args, true);+ const readable = readableAtContextReachOrUndefined(ctx);+ const brief = buildMorningBrief(ctx.vault, {+ now,+ topK,+ ...(agentScope !== undefined ? { agentScope } : {}),+ ...(readable !== undefined ? { readable } : {}),+ withholdsPrivate: contextReach(ctx) !== TRANSPORT_REACH.local,+ lookbackDays,+ ...(maxCharsPerMemory !== undefined ? { maxCharsPerMemory } : {}),+ ...(maxTotalChars !== undefined ? { maxTotalChars } : {}),+ });+ // Pending-trigger section (t_cd1fee79): renders only when a trigger+ // scan persisted surfaceable triggers; included triggers are marked+ // delivered so a prompt shows once per cooldown window.+ //+ // Still fail-soft - a broken queue must not cost the operator the rest+ // of the brief - but no longer silent. The bare catch this replaces set+ // the section to null, so a refusal rendered exactly like an empty+ // queue: the one outcome the anti-nag ledger exists to rule out. The+ // records that could not be read are collected first and reported+ // alongside whatever did render.+ //+ // The queue and its delivery state belong to the local operator: a+ // reader below local reach is shown no trigger, no queue failure, and+ // marks nothing delivered.+ const operatorQueue = contextReach(ctx) === TRANSPORT_REACH.local;+ const triggerFailures: TriggerQueueFailures = operatorQueue+ ? readTriggerQueueFailures(ctx.vault, now)+ : NO_TRIGGER_QUEUE_FAILURES;+ let triggerSection: ReturnType<typeof renderTriggerBriefSection> | null = null;+ let triggerQueueError = triggerFailures.queueError;+ if (operatorQueue) {+ try {+ triggerSection = renderTriggerBriefSection(ctx.vault, {+ now,+ cooldownDays: resolveTriggerCooldownDays(ctx.configPath ?? undefined),+ });+ if (triggerSection.triggers.length > 0) deliverBriefTriggers(ctx.vault, triggerSection, now);+ } catch (err) {+ triggerSection = null;+ triggerQueueError = (err as Error).message ?? String(err);+ }+ }+ const failureText = renderTriggerQueueFailures({+ unreadable: triggerFailures.unreadable,+ queueError: triggerQueueError,+ });+ // Open-decisions section (write-side-trust wave, Task 10): render-only+ // - unlike the trigger section there is no delivery marking, because a+ // parked question is a standing question with no cooldown. Same+ // operator-queue boundary as the triggers: a reader below local reach+ // is shown neither the questions nor the unreadable records.+ const openDecisions = operatorQueue+ ? renderOpenDecisionsBriefSection(ctx.vault)+ : { text: "", records: [], unreadable: [] };+ const sections = [+ brief.text,+ triggerSection !== null ? triggerSection.text : "",+ failureText,+ openDecisions.text,+ ].filter((section) => section !== "");+ return {+ text: sections.join("\n\n"),+ preferences: brief.preferences,+ open_questions: brief.openQuestions,+ recent_notes: brief.recentNotes,+ total_chars: brief.totalChars,+ ...(triggerSection !== null && triggerSection.triggers.length > 0+ ? {+ triggers: triggerSection.triggers.map((t) => ({+ id: t.id,+ kind: t.kind,+ urgency: t.urgency,+ reason: t.reason,+ })),+ }+ : {}),+ ...(triggerFailures.unreadable.length > 0+ ? { triggers_unreadable: triggerFailures.unreadable.map(unreadableTriggerJson) }+ : {}),+ ...(triggerQueueError !== null ? { trigger_queue_error: triggerQueueError } : {}),+ ...(openDecisions.records.length > 0+ ? {+ open_decisions: openDecisions.records.map((r) => ({+ id: r.id,+ question: r.question,+ status: r.status,+ })),+ }+ : {}),+ ...(openDecisions.unreadable.length > 0+ ? { open_decisions_unreadable: openDecisions.unreadable }+ : {}),+ };+}++export async function toolBrainDigest(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const since = coerceIsoDate(args, "since");+ const until = coerceIsoDate(args, "until");+ const format = coerceFormat(args) satisfies DigestFormat;++ // Pin ONE effective until instant so the rendered content, the+ // snapshot render, and the snapshot date key all describe the same+ // window even when the caller omitted `until`.+ const effectiveUntil = until ?? new Date();+ const agentScope = coerceAgentScope(ctx, args, true);+ // The digest is rendered for this reader whenever any rule is live: a+ // record below the caller's reach, or withheld by the enforced ownership+ // scope, is absent from every row and count. Passing the predicate+ // whenever it would withhold anything - rather than only below local+ // reach - is the view the `osb://digest/latest` resource renders the+ // same caller with, so the agent summary, the backlink counts and the+ // connection health cannot count the events and records those sections+ // beside them already withhold. With no rule live the predicate is+ // absent and the render stays byte-identical to the unfiltered one.+ const restricted = contextReach(ctx) !== TRANSPORT_REACH.local;+ // The enforced ownership scope (null unless+ // `integrity.owner_scope_delivery` is `fail` with a resolved identity)+ // decides the snapshot boundary below, beside the reach.+ const enforcedScope = resolveOwnerScopeDelivery(ctx.vault, agentScope).enforcedScope;+ const renderFor = (renderFormat: DigestFormat, readable?: (rel: string) => boolean) =>+ renderDigest(ctx.vault, {+ ...(since ? { since } : {}),+ until: effectiveUntil,+ format: renderFormat,+ linkOutputFormat: resolveLinkOutputFormat(ctx.configPath ?? undefined),+ ...(agentScope !== undefined ? { agentScope } : {}),+ ...(readable !== undefined ? { readable } : {}),+ ...(restricted ? { withholdsPrivate: true } : {}),+ });+ const result = renderFor(format, readableAtContextReachOrUndefined(ctx));++ const envelope: Record<string, unknown> = {+ format,+ empty: result.empty,+ content: result.content,+ };+ // The snapshot is the vault's own run-over-run record, diffed over the+ // digest every record feeds, so a reader below local reach neither+ // takes one nor is shown the delta. The same holds for a caller the+ // enforced ownership scope narrows: its render is one owner's slice of+ // the vault, and persisting that slice under the shared date key would+ // hand the next caller a delta whose key paths were computed against+ // it - key paths naming artifact ids that caller was never shown.+ if (restricted || enforcedScope !== null) return envelope;+ // Snapshot the structured summary, not the rendered string: render+ // a JSON digest for the snapshot regardless of the caller's format+ // so the run-over-run diff keys on data.+ const digestDate = isoDate(effectiveUntil);+ const snapshotSource = format === "json" ? result.content : renderFor("json").content;+ let parsedSnapshot: unknown = null;+ try {+ parsedSnapshot = JSON.parse(snapshotSource);+ } catch {+ parsedSnapshot = null;+ }+ const delta =+ parsedSnapshot !== null+ ? captureReportDelta(+ ctx.vault,+ "digest",+ digestDate,+ parsedSnapshot,+ ctx.configPath ? { configPath: ctx.configPath } : {},+ )+ : null;+ return delta !== null ? { ...envelope, delta } : envelope;+}++// ----- brain_query ---------------------------------------------------------++/**+ * The rows of a daily or weekly envelope this request may see, or+ * `null` when no rule is live - local reach with the ownership gate off -+ * and the envelope is the builder's own (the digest precedent: a reader+ * below local reach is shown only what it may read, and takes no report+ * snapshot).+ *+ * Two rules are asked, through the one adapter the digest's actions rows+ * use: the enforced ownership rule (`gatedOwnerScopeView`, live only+ * under `integrity.owner_scope_delivery: fail` with a resolved identity)+ * and the request's reach-and-readability view. Local reach no longer+ * short-circuits past the ownership rule - an enforced identity on the+ * operator's own transport is exactly the caller that gate exists to+ * scope, and its envelope was otherwise the builder's unfiltered own.+ *+ * Status transitions, retirements and contradictions are dropped when a+ * record they name is withheld. Source pointers are deduplicated+ * artifacts with no record left on them, so they are recollected from+ * the window's events the reader may see: an artifact cited only by+ * evidence on a withheld preference is absent. The counts+ * (`events_by_kind`, `vault_delta`) are recomputed from the same+ * selection, so a withheld record moves no count either. Because a live+ * rule means the envelope is one caller's slice, no report snapshot is+ * taken for it - the shared date key must not hold one caller's slice+ * for the next caller's delta to diff against.+ */+export function periodRowsAtReach(+ ctx: ServerContext,+ index: TimelineIndex,+ window: { readonly since: string; readonly until: string },+): PeriodRowsView | null {+ const refs = everyArtifactRefView(+ gatedOwnerScopeView(ctx.vault, ctx.agentName),+ requestRefView(ctx),+ );+ if (refs.filtersNothing) return null;+ const events = eventsAtReach(refs, selectEvents(index, window));+ return {+ refs,+ sourcePointers: collectSourcePointers(events),+ eventsByKind: countByKind(events),+ vaultDelta: (transitions) => computeVaultDelta(events, transitions),+ };+}++export interface PeriodRowsView {+ readonly refs: ArtifactRefView;+ readonly sourcePointers: ReadonlyArray<string>;+ readonly eventsByKind: ReturnType<typeof countByKind>;+ /** The window's delta over the visible events and the transitions kept for the reader. */+ readonly vaultDelta: (+ transitions: ReadonlyArray<PeriodStatusTransition>,+ ) => ReturnType<typeof computeVaultDelta>;+}++/** A transition or retirement row: the record id and the link it was logged with. */+export function transitionRefs(row: {+ readonly prefId: string;+ readonly link: string;+}): ReadonlyArray<ArtifactRef> {+ return [row.link, ...recordRefs(row.prefId)];+}++/** A contradiction row: its record, the topic's record and its evidence artifact. */+export function contradictionRefs(row: {+ readonly prefId?: string;+ readonly topic?: string;+ readonly artifact?: string;+}): ReadonlyArray<ArtifactRef> {+ return [+ row.artifact,+ ...recordRefs(row.prefId),+ ...(row.topic !== undefined ? recordRefs(`${PREF_ID_PREFIX}${row.topic}`) : []),+ ];+}++/**+ * `brain_daily_brief` - structured counters + transitions + source+ * pointers for one day. Defaults `date` to today UTC when omitted.+ */+export async function toolBrainDailyBrief(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const dateRaw = args["date"];+ const dateCoerced = coerceIsoTimestampOrDate("brain_daily_brief", "date", dateRaw, "date-only");+ const date = dateCoerced ?? new Date().toISOString().slice(0, 10);+ const cfg = loadTemporalConfigSafe(ctx.vault);+ const index = buildTimelineIndex(ctx.vault, {+ withholdsPrivate: requestRefView(ctx).withholdsPrivate === true,+ });+ const brief = buildDailyBrief(index, ctx.vault, date, {+ offsetHours: cfg.daily_window_offset_hours,+ });+ const atReach = periodRowsAtReach(ctx, index, brief.window);+ const statusTransitions =+ atReach?.refs.keep(brief.statusTransitions, transitionRefs) ?? brief.statusTransitions;+ const envelope: Record<string, unknown> = {+ vault_path: vaultPathField(ctx),+ date: brief.date,+ window: brief.window,+ events_by_kind: atReach?.eventsByKind ?? brief.eventsByKind,+ status_transitions: statusTransitions,+ vault_delta: atReach?.vaultDelta(statusTransitions) ?? brief.vaultDelta,+ source_pointers: atReach?.sourcePointers ?? brief.sourcePointers,+ generated_at: brief.generatedAt,+ };+ // When any rule is live - below local reach, or an enforced owner+ // scope - the envelope is this caller's slice: no snapshot is taken+ // under the shared date key and no delta is reported.+ if (atReach !== null) return envelope;+ // Dual-output: persist a machine snapshot and report the run-over-run+ // delta when report snapshots are enabled.+ const delta = captureReportDelta(+ ctx.vault,+ "daily",+ brief.date,+ envelope,+ ctx.configPath ? { configPath: ctx.configPath } : {},+ );+ return delta !== null ? { ...envelope, delta } : envelope;+}++/**+ * `brain_weekly_synthesis` - 7-day deterministic summary plus retired+ * and contradictions lists.+ */+export async function toolBrainWeeklySynthesis(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const weekEndRaw = args["week_end"];+ const weekEndCoerced = coerceIsoTimestampOrDate(+ "brain_weekly_synthesis",+ "week_end",+ weekEndRaw,+ "date-only",+ );+ const weekEnd = weekEndCoerced ?? new Date().toISOString().slice(0, 10);+ const cfg = loadTemporalConfigSafe(ctx.vault);+ const index = buildTimelineIndex(ctx.vault, {+ withholdsPrivate: requestRefView(ctx).withholdsPrivate === true,+ });+ const synth = buildWeeklySynthesis(index, ctx.vault, weekEnd, cfg);+ const atReach = periodRowsAtReach(ctx, index, {+ since: synth.windowStart,+ until: synth.windowEnd,+ });+ const statusTransitions =+ atReach?.refs.keep(synth.statusTransitions, transitionRefs) ?? synth.statusTransitions;+ const envelope: Record<string, unknown> = {+ vault_path: vaultPathField(ctx),+ window_start: synth.windowStart,+ window_end: synth.windowEnd,+ events_by_kind: atReach?.eventsByKind ?? synth.eventsByKind,+ status_transitions: statusTransitions,+ retired: atReach?.refs.keep(synth.retired, transitionRefs) ?? synth.retired,+ contradictions:+ atReach?.refs.keep(synth.contradictions, contradictionRefs) ?? synth.contradictions,+ vault_delta: atReach?.vaultDelta(statusTransitions) ?? synth.vaultDelta,+ source_pointers: atReach?.sourcePointers ?? synth.sourcePointers,+ generated_at: synth.generatedAt,+ };+ // When any rule is live - below local reach, or an enforced owner+ // scope - the envelope is this caller's slice: no snapshot is taken+ // under the shared date key and no delta is reported.+ if (atReach !== null) return envelope;+ const delta = captureReportDelta(+ ctx.vault,+ "weekly",+ weekEnd,+ envelope,+ ctx.configPath ? { configPath: ctx.configPath } : {},+ );+ return delta !== null ? { ...envelope, delta } : envelope;+}++// ----- brain_intention (Agent Surface Suite) --------------------------------++export async function toolBrainMonthlyReview(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const monthRaw = args["month"];+ let month: string | undefined;+ if (monthRaw !== undefined && monthRaw !== null) {+ if (typeof monthRaw !== "string") {+ throw new MCPError(INVALID_PARAMS, "brain_brief view=monthly: month must be YYYY-MM");+ }+ try {+ month = normalizeMonthlyReviewMonth(monthRaw);+ } catch {+ throw new MCPError(INVALID_PARAMS, "brain_brief view=monthly: month must be YYYY-MM");+ }+ }+ // Below local reach (or under the ownership gate) the month is counted+ // over the events this caller may see, in the form it may see them.+ const refs = requestRefView(ctx);+ const report = buildMonthlyReview(ctx.vault, {+ ...(month ? { month } : {}),+ ...(refs.filtersNothing ? {} : { eventAtReach: (ev) => eventAtReach(refs, ev) }),+ });+ return {+ schema_version: report.schema_version,+ generated_at: report.generated_at,+ month: report.month,+ window: report.window,+ summary: report.summary,+ };+}++/**+ * Aggregate operator dashboard: trust verdict, doctor / dream+ * counts, verification delta summary, ranked maintenance actions,+ * and instruction-file ceiling warnings - one read-only call so an+ * operator does not run `brain_digest` + `brain_doctor` separately.+ */+export async function toolBrainOperatorSummary(+ ctx: ServerContext,+ args: Record<string, unknown>,+ onProgress?: ProgressSink,+): Promise<Record<string, unknown>> {+ const topRaw = args["top_actions"];+ let topActionsN: number | undefined;+ if (topRaw !== undefined && topRaw !== null) {+ // Strict integer coercion: reject `"3abc"`, `"2.5"`, and other+ // shapes `Number.parseInt` would silently accept. Only a pure+ // integer literal is allowed.+ if (typeof topRaw === "number") {+ if (!Number.isInteger(topRaw) || topRaw < 0) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_brief view=operator: top_actions must be a non-negative integer",+ );+ }+ topActionsN = topRaw;+ } else if (typeof topRaw === "string") {+ const trimmed = topRaw.trim();+ if (trimmed === "" || !/^[0-9]+$/.test(trimmed)) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_brief view=operator: top_actions must be a non-negative integer",+ );+ }+ topActionsN = Number.parseInt(trimmed, 10);+ } else {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_brief view=operator: top_actions must be a non-negative integer",+ );+ }+ }++ const includeDreamRaw = args["include_dream"];+ let includeDream: boolean;+ if (includeDreamRaw === undefined || includeDreamRaw === null) {+ includeDream = true;+ } else if (typeof includeDreamRaw === "boolean") {+ includeDream = includeDreamRaw;+ } else {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_brief view=operator: include_dream must be a boolean",+ );+ }++ let dreamSummary;+ let dreamError: string | undefined;+ if (includeDream) {+ try {+ // The one view behind this dispatcher that runs a consolidation+ // pass. It is a DRY RUN, and it still walks the whole Brain tree,+ // so it is the slow half of an operator summary on a large vault.+ dreamSummary = dream(ctx.vault, {+ dryRun: true,+ // A dry run is still a full synchronous pass over the Brain tree,+ // so it is bounded on the same terms as `brain_dream` itself -+ // the budget the operator set for `dream` governs every MCP call+ // that reaches one, not just the tool that carries its name.+ safeguard: toolSafeguard(ctx, OPERATION.dream),+ ...(onProgress !== undefined ? { onProgress } : {}),+ });+ } catch (err) {+ // Surface the failure so callers know the dashboard is missing+ // verification + dream signals; do not silently produce a+ // partial envelope.+ dreamError = (err as Error).message ?? String(err);+ }+ }+ // The doctor, digest and top-action fields - and the trust verdict over+ // them - answer at the caller's reach, through the view brain_doctor+ // filters its own findings and actions by, and so do the verification+ // entries, which name the records the dream claimed. The dry-run+ // dream's own warning, uncertain and quarantined counts are taken over+ // the whole Brain layer and name no record.+ const view = everyArtifactRefView(+ gatedOwnerScopeView(ctx.vault, ctx.agentName),+ reachView(ctx.vault, contextReach(ctx)),+ );+ const readable = readableAtContextReachOrUndefined(ctx);+ const summary = buildOperatorSummary(ctx.vault, {+ ...(dreamSummary ? { dreamSummary } : {}),+ ...(topActionsN !== undefined ? { topActionsN } : {}),+ ...(readable !== undefined ? { readable } : {}),+ withholdsPrivate: view.withholdsPrivate === true,+ ...(view.filtersNothing+ ? {}+ : {+ keepIssue: (issue: DoctorIssueNaming) => view.row(...doctorIssueRefs(ctx.vault, issue)),+ keepAction: (action: ActionItem) => view.row(action.target),+ // Candidate-level visibility for the maintenance collector:+ // applied before the scorer caps, so a hidden top-ranked+ // action takes no slot a visible one could fill - the same+ // question brain_doctor's suggested_actions and the digest's+ // actions ask over the same collector output.+ visibleRef: view.visible,+ keepVerification: (entry: VerificationDeltaEntry) =>+ view.row(...recordRefs(entry.id), entry.path),+ }),+ });+ return {+ vault_path: vaultPathField(ctx),+ trust_verdict: summary.trust_verdict,+ digest_summary: summary.digest_summary,+ doctor_summary: {+ warning_count: summary.doctor_summary.warning_count,+ error_count: summary.doctor_summary.error_count,+ },+ dream_summary: summary.dream_summary,+ verification_delta: {+ summary: summary.verification_delta.summary,+ entries: summary.verification_delta.entries,+ },+ top_actions: summary.top_actions,+ instruction_file_warnings: summary.instruction_file_warnings,+ ...(dreamError !== undefined ? { dream_error: dreamError } : {}),+ };+}++// ----- brain_unlinked_mentions (v0.10.17) ----------------------------------++/**+ * `brain_brief view=today` - the today operator dashboard: due/overdue+ * obligations, one-off pledges, open loops, merged recent activity, and+ * a totals rollup. Read-only; the clock is resolved at the tool boundary+ * so the core builder stays deterministic. Write-back (the `@osb set`+ * engine) stays CLI-only in this release and is deliberately not+ * exposed here.+ */+export async function toolBrainToday(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ // Non-negative (0 allowed): the core `buildTodayDashboard` and the CLI+ // both accept a zero-day window and a zero-entry limit, so the MCP surface+ // must not reject what they honour.+ const lookbackDays = coerceNonNegativeInteger(+ "brain_brief view=today",+ "lookback_days",+ args["lookback_days"],+ );+ const limit = coerceNonNegativeInteger("brain_brief view=today", "limit", args["limit"]);+ // The recent-activity section renders log events; below local reach+ // (or under the ownership gate) it shows them as this caller may see+ // them, before the limit and the totals.+ const refs = requestRefView(ctx);+ // Obligation pages, pledge pages and open-loop notes are listed only+ // when the caller may read them, before the totals.+ const readable = readableAtContextReachOrUndefined(ctx);+ const dashboard = buildTodayDashboard(ctx.vault, {+ now: new Date(),+ ...(refs.filtersNothing ? {} : { eventAtReach: (ev) => eventAtReach(refs, ev) }),+ ...(readable === undefined ? {} : { readable }),+ ...(lookbackDays !== undefined ? { activityLookbackDays: lookbackDays } : {}),+ ...(limit !== undefined ? { activityLimit: limit } : {}),+ });+ return {+ vault_path: vaultPathField(ctx),+ text: dashboard.text,+ obligations: dashboard.obligations,+ pledges: dashboard.pledges,+ open_loops: dashboard.openLoops,+ recent_activity: dashboard.recentActivity,+ totals: dashboard.totals,+ errors: dashboard.errors,+ };+}diff --git a/src/mcp/brain/context-active-tools.ts b/src/mcp/brain/context-active-tools.tsnew file mode 100644index 00000000..d734d5bb--- /dev/null+++ b/src/mcp/brain/context-active-tools.ts@@ -0,0 +1,425 @@+/**+ * `brain_context` (task 3.19): the active-digest regeneration the agent+ * context opens with, with the standing-rules and scoped-rules blocks it+ * renders and the counts it reports. Split from `context-tools.ts`;+ * registration happens through that module's registry, which preserves+ * the public CONTEXT_TOOLS surface.+ */++import { existsSync, readFileSync } from "node:fs";+import {+ brainDirsOf,+ brainStandingRulesPath,+ BRAIN_ACTIVE_FILE,+ BRAIN_ROOT_REL,+} from "../../core/brain/paths.ts";+import {+ readStandingRules,+ renderStandingRules,+ renderStandingRulesFailure,+ type StandingRules,+} from "../../core/brain/standing-rules.ts";+import {+ loadBrainConfig,+ resolveScopedRulesMaxChars,+ resolveStandingRulesMaxChars,+} from "../../core/brain/policy.ts";+import {+ readScopedRules,+ type ScopedRuleIdentity,+ type ScopedRules,+} from "../../core/brain/scoped-rules.ts";+import { resolveHostScope, resolveProjectScope } from "../../core/brain/scope-identity.ts";+import type { BrainConfig } from "../../core/brain/types.ts";+import {+ regenerateActive,+ readerNarrowsActive,+ renderActiveForReader,+ type RegenerateActiveResult,+} from "../../core/brain/active.ts";+import {+ compiledDigestPath,+ digestsRenderedOnDemand,+} from "../../core/brain/compiled-digest-path.ts";+import { computeMaintenanceOverdueFlag } from "../../core/brain/status.ts";+import { TRANSPORT_REACH } from "../../core/graph/transport-reach.ts";+import { parseFrontmatter } from "../../core/vault.ts";+import { readVaultInstructionFile } from "../../core/brain/vault-instruction-file.ts";+import { readPinnedContext } from "../../core/brain/pinned.ts";+import { contextReach, contextVault, type ServerContext } from "../tool-contract.ts";+import { vaultPathField } from "../vault-path-field.ts";+import { deliveryView } from "./reach-events.ts";+import { readableAtContextReachOrUndefined } from "./reach-readable.ts";+import { toolPath } from "./device-path.ts";+import {+ appendPinnedToContextContent,+ serializePinnedContext,+ shapedPinnedContent,+} from "./context-pinned-tools.ts";++export type BrainContextCounts = RegenerateActiveResult["counts"];++export const EMPTY_CONTEXT_COUNTS: BrainContextCounts = {+ confirmed: 0,+ quarantine: 0,+ retired_recent: 0,+ most_applied_30d: 0,+};++/**+ * Pull-bootstrap of `Brain/active.md` + the active-preference counts.+ * Built for runtimes that have no `SessionStart` hook (Cursor, Aider,+ * raw Claude API): one tool call gives the agent the same shortcut card+ * the SessionStart-aware runtimes get injected automatically.+ *+ * Not a pure read: the bootstrap path calls `regenerateActive`, which+ * writes `Brain/active.md` whenever the on-disk body is absent or+ * stale, so the tool classifies `write` (write-mode-dominant,+ * `tool-contract.ts`) and the stdio transport never runs two bootstrap+ * calls beside each other on the concurrent read path.+ *+ * Behaviour matrix:+ * - Brain/ absent → present:false, zero counts, and content+ * carrying the standing-rules block or the+ * statement that it could not be read (empty+ * for the ordinary case, where there is no+ * such file either).+ * - Brain/ present, active.md absent → call regenerateActive (idempotent)+ * and read the regenerated file.+ * - Brain/ present, active.md fresh → idempotent regenerate leaves an+ * equal body on disk; the on-disk+ * body is returned verbatim.+ */+export async function toolBrainContext(ctx: ServerContext): Promise<Record<string, unknown>> {+ // `null` on a server with no vault (design D14): the digest renders from+ // the store's folds into the device-local cache, and there is no vault+ // file to read (standing rules, scoped rules, the instruction file).+ const vault = contextVault(ctx);+ const dirs = brainDirsOf(vault);+ // `Brain/active.md` on an unswitched machine; on a store-only one the+ // device-local cache the digest is rendered into on demand (D14 item 7).+ const activePath = compiledDigestPath(vault, "active");+ const onDemand = digestsRenderedOnDemand(vault);+ const pinned = readPinnedContext(vault);+ // The request's delivery binding, resolved ONCE and used for the active+ // body AND the pinned scratchpad beside it (delivery-trust, lane A): one+ // frontmatter cache serves the whole assembly, instead of the pinned+ // serializer building a second binding per call.+ const delivery = deliveryView(ctx);+ // Bounded to the single newest `Brain/log/` day - see+ // `computeMaintenanceOverdueFlag`'s docblock for the cost bound. This+ // is the always-loaded path, so the full `maintenance_debt` derivation+ // on `computeBrainStatus` never runs here.+ const maintenanceOverdue = computeMaintenanceOverdueFlag(vault, {+ withholdsPrivate: contextReach(ctx) !== TRANSPORT_REACH.local,+ });++ // The operator's standing rules, resolved before anything else this+ // surface assembles - INCLUDING the no-Brain return below. `brain_context`+ // is the pull-mode twin of the SessionStart hook, so the constitution has+ // to lead the content here for exactly the reason it leads the injected+ // payload: on the error branch further down, which zeroes `content` and+ // would otherwise hand a runtime the memory layer's failure and none of+ // the rules that still govern it, and equally on the branch that reports+ // `Brain/` as absent. That probe answers false for a directory it cannot+ // TRAVERSE as well as one that is not there, and it was the one return+ // path that said nothing at all about the rules - the last silent answer+ // on a surface where every other path either carries the block or states+ // why it could not be read.+ const standing = vault === null ? NO_STANDING_BLOCK : readStandingBlock(vault);+ // The scoped operator rules for the project, harness and host this+ // server was launched for - local reach only, see `readScopedBlock`.+ // Read beside the constitution, before the no-Brain return, for the+ // same reason: the rules govern a session whatever the memory layer did.+ const scoped = readScopedBlock(ctx);++ // A store-only machine keeps its memory in the store, `Brain/` or not.+ if (!onDemand && !existsSync(dirs.brain)) {+ return {+ vault_path: vaultPathField(ctx),+ present: false,+ active_path: activePath,+ content: prependBlock(standing.text, prependBlock(scoped?.text ?? "", "")),+ counts: EMPTY_CONTEXT_COUNTS,+ generated_at: null,+ pinned: serializePinnedContext(ctx, pinned, undefined, undefined, {+ shapeBody: true,+ delivery,+ }),+ maintenance_overdue: maintenanceOverdue,+ ...standingRulesField(ctx, standing),+ ...scopedRulesField(scoped),+ };+ }++ let counts: BrainContextCounts = EMPTY_CONTEXT_COUNTS;+ let error: string | undefined;+ try {+ // The SHARED file is regenerated unscoped, always. `active.md` is one+ // file for the whole vault - injected into every agent's SessionStart+ // by `hooks/active-inject.ts` and regenerated unscoped by the+ // `osb://preferences/active` resource - so narrowing the WRITE to this+ // caller would make it thrash and could drop an agent's own memories+ // from its session start (context-integrity-gates, A3).+ counts = regenerateActive(vault).counts;+ } catch (err) {+ error = (err as Error)?.message ?? String(err);+ }++ // After a successful regenerateActive, active.md is guaranteed to+ // exist (the function either wrote it or confirmed an equal body+ // already on disk). A read failure here is an unrelated filesystem+ // race, not a missing-file branch — handle it in the same `error`+ // slot the regenerate failure uses.+ let content = "";+ let generatedAt: string | null = null;+ if (!error) {+ try {+ content = readFileSync(activePath, "utf8");+ const [meta] = parseFrontmatter(activePath);+ const v = meta["generated_at"];+ if (typeof v === "string" && v.trim().length > 0) {+ generatedAt = v;+ }+ } catch (err) {+ error = (err as Error)?.message ?? String(err);+ content = "";+ generatedAt = null;+ }+ }+ // What this ONE caller is handed, not what is on disk, answers at its+ // reach and under the owner gate. This surface takes no arguments, so+ // `ServerContext.agentName` is its only source of identity and the+ // minted reach its only source of distance. A preference or retired+ // record the caller cannot read is absent from its digest - principle,+ // counts and most-applied entry alike. A local caller with no enforced+ // owner scope keeps the file's own bytes; any other caller gets the+ // reader render, decided on its reach rather than on what is withheld,+ // and stamped with the generation already on disk.+ if (!error) {+ const readable = readableAtContextReachOrUndefined(ctx);+ const reader = {+ ...(readable !== undefined ? { readable } : {}),+ restricted: contextReach(ctx) !== TRANSPORT_REACH.local,+ ...(ctx.agentName !== undefined ? { agentScope: ctx.agentName } : {}),+ };+ if (readerNarrowsActive(vault, reader)) {+ const narrowed = renderActiveForReader(vault, reader);+ content = narrowed.document;+ counts = narrowed.counts;+ }+ }++ // Constitution first, then the scoped rules, then the memory body -+ // and the body is shaped BEFORE the assembly (delivery-trust, lane A):+ // the fence wraps the stored-record bytes only. The constitution and+ // the scoped rules are the operator's own voice delivered local-only,+ // and the pinned scratchpad shapes through the same binding beside+ // this assembly, so neither slips past the fence the body carries.+ // An unfetchable body has nothing to fence: the pinned scratchpad's+ // shaper skips empty bodies, and the main body answers the same way+ // instead of wrapping an empty block in the fence.+ if (content.length > 0) {+ content = delivery.shape(content, `${BRAIN_ROOT_REL}/${BRAIN_ACTIVE_FILE}`);+ }+ content = prependBlock(standing.text, prependBlock(scoped?.text ?? "", content));+ content = appendPinnedToContextContent(content, shapedPinnedContent(ctx, pinned, delivery));++ // Optional vault-root instruction file (v0.10.17). Absent file =+ // field omitted so hosts that strip unknown fields stay+ // byte-identical.+ //+ // A THROW IS NOT AN ABSENCE. This used to be `catch { null }`, which+ // put an operator configuration error - an absolute path, a `..`+ // segment, an empty name - and an unreadable file on the same wire as+ // a vault that simply has no instruction file: the field vanished and+ // nothing said why. The reason now rides its own key, so the+ // enrichment stays best-effort without being silent.+ let vaultInstruction: ReturnType<typeof readVaultInstructionFile> = null;+ let vaultInstructionError: string | undefined;+ try {+ vaultInstruction = vault === null ? null : readVaultInstructionFile(vault);+ } catch (err) {+ vaultInstructionError = (err as Error)?.message ?? String(err);+ }++ return {+ vault_path: vaultPathField(ctx),+ present: true,+ active_path: activePath,+ content,+ counts,+ generated_at: generatedAt,+ pinned: serializePinnedContext(ctx, pinned, undefined, undefined, {+ shapeBody: true,+ delivery,+ }),+ maintenance_overdue: maintenanceOverdue,+ ...(error ? { error } : {}),+ ...standingRulesField(ctx, standing),+ ...scopedRulesField(scoped),+ ...(vaultInstruction+ ? {+ vault_instruction: {+ path: vaultInstruction.path,+ content: vaultInstruction.content,+ lines: vaultInstruction.lines,+ },+ }+ : {}),+ ...(vaultInstructionError !== undefined+ ? { vault_instruction_error: vaultInstructionError }+ : {}),+ };+}++/**+ * The standing-rules block and the record behind it, or neither.+ *+ * The two travel together because the response reports them in two+ * different places - the block is prepended to `content`, the record+ * becomes the `standing_rules` key - and a read that FAILED produces a+ * block but no record: there is no path/content/truncated triple to+ * report for bytes nobody could read, and the block itself is what says+ * so in words the agent will read.+ */+export interface StandingBlock {+ readonly text: string;+ readonly rules: StandingRules | null;+}++export const NO_STANDING_BLOCK: StandingBlock = Object.freeze({ text: "", rules: null });++export function readStandingBlock(vault: string): StandingBlock {+ const path = brainStandingRulesPath(vault);+ let cfg: BrainConfig | null = null;+ try {+ cfg = loadBrainConfig(vault);+ } catch {+ // A `_brain.yaml` this surface cannot read resolves the cap to its+ // default; the config failure itself surfaces through the `error`+ // slot that the regenerate arm above already populates.+ }+ try {+ const rules = readStandingRules(vault, { maxChars: resolveStandingRulesMaxChars(cfg) });+ if (rules === null) return NO_STANDING_BLOCK;+ return Object.freeze({ text: renderStandingRules(rules), rules });+ } catch (err) {+ return Object.freeze({ text: renderStandingRulesFailure(path, err), rules: null });+ }+}++/**+ * The optional `standing_rules` key, or nothing.+ *+ * Both return shapes spread it from here so the two cannot disagree about+ * when the key appears. It is omitted for a vault whose operator wrote no+ * rules AND for a read that failed - the failure has no path/content/+ * truncated triple to report, and the block inside `content` is what says+ * so in words.+ */+export function standingRulesField(+ ctx: ServerContext,+ standing: StandingBlock,+): Record<string, unknown> {+ if (standing.rules === null) return {};+ return {+ standing_rules: {+ path: toolPath(ctx, standing.rules.path),+ content: standing.rules.text,+ truncated: standing.rules.truncated,+ },+ };+}++/** Put a block at the head of the content, or leave the content alone. */+export function prependBlock(block: string, content: string): string {+ if (block.length === 0) return content;+ const trimmed = content.trimStart();+ return trimmed.length === 0 ? `${block}\n` : `${block}\n\n${trimmed}`;+}++/**+ * The scoped operator rules rendered for this server's scope, or nothing.+ *+ * LOCAL REACH ONLY. The scope is resolved from facts about the process+ * that serves the call - the directory it was launched in, the harness+ * its registration names, the device it runs on - and at remote reach+ * none of them describes the caller. So at remote reach nothing is read+ * at all: not the files, not the pointer, not the device id, and the+ * answer is byte-identical whether or not any scoped file exists.+ *+ * The identity comes from {@link ServerContext.ruleScope} and the device+ * id; no argument of this tool can name it (the tool takes none).+ */+export function readScopedBlock(ctx: ServerContext): ScopedRules | null {+ if (contextReach(ctx) !== TRANSPORT_REACH.local) return null;+ // Scoped rules are vault files; a server with no vault has none.+ if (contextVault(ctx) === null) return null;+ let host: { readonly host: string | null; readonly unreadable: boolean };+ try {+ host = resolveHostScope(ctx.configPath ?? undefined);+ } catch {+ // A device id that cannot be resolved for any other reason (a config+ // home that cannot be created, say) must not take the bootstrap+ // surface down with it. It matches no host file, and the block says+ // so when there is a host file it could have matched.+ host = { host: null, unreadable: true };+ }+ const identity: ScopedRuleIdentity = {+ project: resolveProjectScope(ctx.ruleScope?.workspaceDir ?? null, ctx.vault),+ harness: ctx.ruleScope?.harness ?? null,+ host: host.host,+ };+ let rules: ScopedRules;+ try {+ rules = readScopedRules(ctx.vault, identity, {+ maxChars: scopedRulesMaxChars(ctx.vault),+ hostUnreadable: host.unreadable,+ });+ } catch {+ // The reader renders every per-file failure as an `UNAVAILABLE:` line+ // and does not throw for one; anything that still escapes it must not+ // take the constitution and the memory layer down with the scoped block.+ return null;+ }+ return rules.text.length === 0 ? null : rules;+}++/**+ * The configured cap, or its default when `_brain.yaml` cannot be read+ * (that failure surfaces through the regenerate arm's `error` slot, as+ * for the constitution's cap).+ */+export function scopedRulesMaxChars(vault: string): number {+ let cfg: BrainConfig | null = null;+ try {+ cfg = loadBrainConfig(vault);+ } catch {+ // absorbed - see above+ }+ return resolveScopedRulesMaxChars(cfg);+}++/**+ * The optional `scoped_rules` key, or nothing: present only when a file+ * matched or the host notice applies, so a vault with no scoped rules -+ * and every remote caller - keeps today's bytes.+ */+export function scopedRulesField(scoped: ScopedRules | null): Record<string, unknown> {+ if (scoped === null) return {};+ return {+ scoped_rules: {+ scope: {+ project: scoped.identity.project,+ harness: scoped.identity.harness,+ host: scoped.identity.host,+ },+ files: scoped.files.map((file) => ({+ path: file.path,+ axis: file.axis,+ truncated: file.truncated,+ })),+ },+ };+}diff --git a/src/mcp/brain/context-pinned-tools.ts b/src/mcp/brain/context-pinned-tools.tsnew file mode 100644index 00000000..d16646d9--- /dev/null+++ b/src/mcp/brain/context-pinned-tools.ts@@ -0,0 +1,167 @@+/**+ * The pinned-context tool family (task 3.19): `brain_pinned_context`+ * with its operation coercion, the serialization a read or a batch+ * answers through, and the append helper the active-digest tool reuses.+ * Split from `context-tools.ts`; registration happens through that+ * module's registry, which preserves the public CONTEXT_TOOLS surface.+ */++import {+ PinnedBatchError,+ applyPinnedOperations,+ appendPinnedContext,+ clearPinnedContext,+ readPinnedContext,+ writePinnedContext,+ type PinnedBatchResult,+ type PinnedContext,+ type PinnedOperation,+} from "../../core/brain/pinned.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import { contextVault, type ServerContext } from "../tool-contract.ts";+import { coerceStr, unknownOperationError } from "../coerce.ts";+import { deliveryView } from "./reach-events.ts";+import { toolPath } from "./device-path.ts";++export type PinnedContextOperation = "read" | "write" | "append" | "clear";++export function coercePinnedContextOperation(+ args: Record<string, unknown>,+): PinnedContextOperation {+ const operation = coerceStr(args, "operation", false) ?? "read";+ if (+ operation !== "read" &&+ operation !== "write" &&+ operation !== "append" &&+ operation !== "clear"+ ) {+ throw unknownOperationError(+ "brain_pinned_context operation must be one of: read, write, append, clear",+ );+ }+ return operation;+}++/**+ * The scratchpad body as THIS request may receive it (delivery-trust,+ * lane A): stored text, so at remote reach it is shaped through the+ * request's delivery binding - fenced, naming the scratchpad file's own+ * derived provenance - and at local reach the stored bytes untouched. An+ * absent scratchpad has no body to fence. `delivery` may be handed in by+ * a caller that already holds the request's binding, so one request+ * keeps one frontmatter cache.+ */+export function shapedPinnedContent(+ ctx: ServerContext,+ pinned: PinnedContext,+ delivery: ReturnType<typeof deliveryView> = deliveryView(ctx),+): string {+ if (!pinned.present || pinned.content.length === 0) return pinned.content;+ return delivery.shape(pinned.content, toolPath(ctx, pinned.path));+}++export function serializePinnedContext(+ ctx: ServerContext,+ pinned: PinnedContext,+ operation?: PinnedContextOperation,+ done?: boolean,+ opts?: { shapeBody?: boolean; delivery?: ReturnType<typeof deliveryView> },+): Record<string, unknown> {+ return {+ ...(operation ? { operation } : {}),+ present: pinned.present,+ path: toolPath(ctx, pinned.path),+ absolute_path: pinned.path,+ // Only a READ shapes the body (delivery-trust, lane A). A write or+ // batch confirmation echoes bytes the caller just authored - the+ // terminal-ack contract stays byte-stable; the delivery contract is+ // about handing stored text to a caller that did not write it.+ content:+ opts?.shapeBody === true+ ? shapedPinnedContent(ctx, pinned, opts.delivery ?? deliveryView(ctx))+ : pinned.content,+ // Terminal/idempotent marker on successful writes so the agent does+ // not redundantly re-call after the store already committed.+ ...(done ? { done: true } : {}),+ };+}++export async function toolBrainPinnedContext(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ if (args["operations"] !== undefined) {+ return runPinnedContextBatch(ctx, args["operations"]);+ }+ const operation = coercePinnedContextOperation(args);+ if (operation === "read") {+ return serializePinnedContext(ctx, readPinnedContext(contextVault(ctx)), operation, undefined, {+ shapeBody: true,+ });+ }+ let pinned: PinnedContext;+ try {+ if (operation === "write") {+ pinned = writePinnedContext(contextVault(ctx), coerceStr(args, "content", true)!);+ } else if (operation === "append") {+ pinned = appendPinnedContext(contextVault(ctx), coerceStr(args, "content", true)!);+ } else {+ pinned = clearPinnedContext(contextVault(ctx));+ }+ } catch (err) {+ throw pinnedBatchErrorToMcp(err);+ }+ return serializePinnedContext(ctx, pinned, operation, true);+}++/**+ * Map a core {@link PinnedBatchError} (budget-exceeded, malformed op,+ * absent replace target) onto a structured INVALID_PARAMS so the agent+ * gets a machine-readable rejection — `code`, offending `index`, byte+ * sizes, and a consolidation hint — instead of an opaque message or, for+ * over-budget writes, a fake truncated success. Non-pinned errors pass+ * through unchanged.+ */+export function pinnedBatchErrorToMcp(err: unknown): unknown {+ if (err instanceof PinnedBatchError) {+ return new MCPError(INVALID_PARAMS, `brain_pinned_context: ${err.message}`, {+ code: err.code,+ index: err.index,+ ...err.details,+ });+ }+ return err;+}++/**+ * Atomic ordered-operations mode for `brain_pinned_context`. The whole+ * batch is validated and projected in memory by the core; a malformed op,+ * absent replace target, or over-budget final state aborts with zero+ * writes and surfaces as a structured INVALID_PARAMS error.+ */+export function runPinnedContextBatch(+ ctx: ServerContext,+ operationsRaw: unknown,+): Record<string, unknown> {+ let result: PinnedBatchResult;+ try {+ result = applyPinnedOperations(+ contextVault(ctx),+ operationsRaw as ReadonlyArray<PinnedOperation>,+ );+ } catch (err) {+ throw pinnedBatchErrorToMcp(err);+ }+ return {+ ...serializePinnedContext(ctx, result, undefined, true),+ operations_applied: result.applied,+ };+}++export function appendPinnedToContextContent(activeContent: string, pinnedContent: string): string {+ if (pinnedContent.length === 0) return activeContent;+ const pinnedBlock = `## Pinned context\n\n${pinnedContent}`;+ const trimmedActive = activeContent.trimEnd();+ if (trimmedActive.length === 0) return `${pinnedBlock}\n`;+ return `${trimmedActive}\n\n${pinnedBlock}\n`;+}diff --git a/src/mcp/brain/context-session-tools.ts b/src/mcp/brain/context-session-tools.tsnew file mode 100644index 00000000..e8fbee51--- /dev/null+++ b/src/mcp/brain/context-session-tools.ts@@ -0,0 +1,173 @@+/**+ * `brain_write_session` (task 3.19): the interactive write-session+ * lifecycle a caller drives operation by operation, answered in the+ * same JSON envelopes the CLI prints. Split from `context-tools.ts`;+ * registration happens through that module's registry, which preserves+ * the public CONTEXT_TOOLS surface.+ */++import { resolveAgentName } from "../../core/config.ts";+import { normalizeAgentArgument } from "../../core/agent-identity.ts";+import {+ WriteSessionRequestError,+ type WriteSessionRequestReason,+ abandonSession,+ approveSession,+ openArtifactSession,+ sessionEnvelope,+} from "../../core/brain/write-session/engine.ts";+import { dispatchSubmit, openPanelSession } from "../../core/brain/write-session/panel.ts";+import { listWriteSessions, readWriteSession } from "../../core/brain/write-session/store.ts";+import type { WriteSessionEnvelope } from "../../core/brain/write-session/types.ts";+import { pageSlice } from "../../core/brain/offset-cursor.ts";+import { cursorOffsetArg } from "./pagination.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import { TOOL_ERROR_CODE, type ToolErrorCode } from "../tool-error-codes.ts";+import { type ServerContext } from "../tool-contract.ts";+import { coerceStr, coerceInt, unknownOperationError } from "../coerce.ts";++export async function toolBrainWriteSession(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const op = coerceStr(args, "op", true)!;+ const sessionId = coerceStr(args, "session_id", false);+ const requireSessionId = (): string => {+ if (!sessionId) {+ throw new MCPError(INVALID_PARAMS, `brain_write_session: op '${op}' requires session_id`, {+ code: TOOL_ERROR_CODE.sessionIdRequired,+ });+ }+ return sessionId;+ };+ try {+ switch (op) {+ case "open": {+ const kind = coerceStr(args, "kind", false) ?? "artifact";+ const agent =+ normalizeAgentArgument(coerceStr(args, "agent", false) ?? null) ??+ resolveAgentName(ctx.configPath ?? undefined);+ const requireReview = args["require_review"] === true;+ if (kind === "panel") {+ const topic = coerceStr(args, "topic", true)!;+ const personasRaw = args["personas"];+ const personas = Array.isArray(personasRaw)+ ? personasRaw.filter((x): x is string => typeof x === "string")+ : undefined;+ const target = coerceStr(args, "target", false);+ return asRecord(+ openPanelSession(ctx.vault, {+ agent,+ topic,+ requireReview,+ ...(personas && personas.length > 0 ? { personas } : {}),+ ...(target ? { targetPath: target } : {}),+ }),+ );+ }+ if (kind !== "artifact") {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_write_session: kind must be 'artifact' or 'panel', got '${kind}'`,+ );+ }+ const target = coerceStr(args, "target", true)!;+ const intent = coerceStr(args, "intent", false) ?? "create";+ if (intent !== "create" && intent !== "overwrite" && intent !== "merge") {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_write_session: intent must be create|overwrite|merge, got '${intent}'`,+ );+ }+ const schemaType = coerceStr(args, "schema_type", false);+ const prompt = coerceStr(args, "prompt", false);+ const retryCap = args["retry_cap"];+ return asRecord(+ openArtifactSession(ctx.vault, {+ agent,+ targetPath: target,+ intent,+ requireReview,+ ...(schemaType ? { schemaType } : {}),+ ...(prompt ? { prompt } : {}),+ ...(typeof retryCap === "number" ? { retryCap } : {}),+ }),+ );+ }+ case "submit": {+ const id = requireSessionId();+ const text = coerceStr(args, "text", true)!;+ return asRecord(dispatchSubmit(ctx.vault, { sessionId: id, text }));+ }+ case "approve":+ return asRecord(approveSession(ctx.vault, { sessionId: requireSessionId() }));+ case "abandon":+ return asRecord(abandonSession(ctx.vault, { sessionId: requireSessionId() }));+ case "status": {+ const id = requireSessionId();+ const probe = readWriteSession(ctx.vault, id, new Date().toISOString());+ if (probe.error !== null) throw new MCPError(INVALID_PARAMS, probe.error);+ if (probe.session === null) {+ throw new MCPError(INVALID_PARAMS, `unknown write-session: ${id}`, {+ code: WRITE_SESSION_REASON_CODE["unknown-session"],+ });+ }+ return asRecord(sessionEnvelope(probe.session));+ }+ case "list": {+ const limit = coerceInt(args, "limit", 100, 1, 500);+ const offset = cursorOffsetArg("brain_write_session", args);+ const sessions = listWriteSessions(ctx.vault, new Date().toISOString());+ const page = pageSlice(sessions, offset, limit);+ return {+ // `total` counts every session in the list across pages; the+ // page itself is `sessions`.+ total: page.total,+ sessions: page.items.map((rec) => asRecord(sessionEnvelope(rec))),+ next_cursor: page.next_cursor,+ };+ }+ default:+ throw unknownOperationError(+ `brain_write_session: op must be open|submit|approve|abandon|status|list, got '${op}'`,+ );+ }+ } catch (err) {+ if (err instanceof WriteSessionRequestError) {+ // Preserve the {code, path, message} boundary contract: the+ // structured list rides MCPError's data slot, the message stays+ // human-readable prose.+ throw new MCPError(INVALID_PARAMS, err.message, writeSessionErrorData(err));+ }+ throw err;+ }+}++/**+ * The wire code for each session refusal the engine names. Total over the+ * core union, so a new reason fails the type check until it is mapped.+ */+export const WRITE_SESSION_REASON_CODE: Readonly<Record<WriteSessionRequestReason, ToolErrorCode>> =+ Object.freeze({+ "unknown-session": TOOL_ERROR_CODE.writeSessionUnknown,+ "terminal-session": TOOL_ERROR_CODE.writeSessionTerminal,+ });++/**+ * `data` for a request failure: the structured error list when there is+ * one, the precise code when the engine named a reason, nothing otherwise+ * - an absent code is filled by the boundary's `invalid_params` default.+ */+export function writeSessionErrorData(+ err: WriteSessionRequestError,+): Readonly<Record<string, unknown>> | undefined {+ const data = {+ ...(err.errors.length > 0 ? { errors: err.errors } : {}),+ ...(err.reason !== undefined ? { code: WRITE_SESSION_REASON_CODE[err.reason] } : {}),+ };+ return Object.keys(data).length > 0 ? data : undefined;+}++export function asRecord(envelope: WriteSessionEnvelope): Record<string, unknown> {+ return { ...envelope };+}diff --git a/src/mcp/brain/context-tools.ts b/src/mcp/brain/context-tools.tsindex b42cd033..d362485b 100644--- a/src/mcp/brain/context-tools.ts+++ b/src/mcp/brain/context-tools.ts@@ -6,85 +6,13 @@* BRAIN_TOOLS surface.*/-import { existsSync, readFileSync } from "node:fs";-import { resolveAgentName } from "../../core/config.ts";-import {- brainDirsOf,- brainStandingRulesPath,- BRAIN_ACTIVE_FILE,- BRAIN_ROOT_REL,-} from "../../core/brain/paths.ts";-import {- readStandingRules,- renderStandingRules,- renderStandingRulesFailure,- type StandingRules,-} from "../../core/brain/standing-rules.ts";-import {- loadBrainConfig,- resolveScopedRulesMaxChars,- resolveStandingRulesMaxChars,-} from "../../core/brain/policy.ts";-import {- SCOPED_RULE_AXES,- readScopedRules,- type ScopedRuleIdentity,- type ScopedRules,-} from "../../core/brain/scoped-rules.ts";-import { resolveHostScope, resolveProjectScope } from "../../core/brain/scope-identity.ts";-import type { BrainConfig } from "../../core/brain/types.ts";-import {- regenerateActive,- readerNarrowsActive,- renderActiveForReader,- type RegenerateActiveResult,-} from "../../core/brain/active.ts";-import {- compiledDigestPath,- digestsRenderedOnDemand,-} from "../../core/brain/compiled-digest-path.ts";-import { computeMaintenanceOverdueFlag } from "../../core/brain/status.ts";-import { TRANSPORT_REACH } from "../../core/graph/transport-reach.ts";-import { parseFrontmatter } from "../../core/vault.ts";-import { readVaultInstructionFile } from "../../core/brain/vault-instruction-file.ts";-import { normalizeAgentArgument } from "../../core/agent-identity.ts";-import {- WriteSessionRequestError,- type WriteSessionRequestReason,- abandonSession,- approveSession,- openArtifactSession,- sessionEnvelope,-} from "../../core/brain/write-session/engine.ts";-import { dispatchSubmit, openPanelSession } from "../../core/brain/write-session/panel.ts";-import { listWriteSessions, readWriteSession } from "../../core/brain/write-session/store.ts";-import type { WriteSessionEnvelope } from "../../core/brain/write-session/types.ts";-import { pageSlice } from "../../core/brain/offset-cursor.ts";-import { cursorOffsetArg, CURSOR_SCHEMA } from "./pagination.ts";-import {- PinnedBatchError,- applyPinnedOperations,- appendPinnedContext,- clearPinnedContext,- readPinnedContext,- writePinnedContext,- type PinnedBatchResult,- type PinnedContext,- type PinnedOperation,-} from "../../core/brain/pinned.ts";-import { INVALID_PARAMS, MCPError } from "../protocol.ts";-import { TOOL_ERROR_CODE, type ToolErrorCode } from "../tool-error-codes.ts";-import {- contextReach,- contextVault,- type ServerContext,- type ToolDefinition,-} from "../tool-contract.ts";-import { VAULT_PATH_OUTPUT_SCHEMA, vaultPathField } from "../vault-path-field.ts";-import { coerceStr, coerceInt, unknownOperationError } from "../coerce.ts";-import { deliveryView } from "./reach-events.ts";-import { readableAtContextReachOrUndefined } from "./reach-readable.ts";-import { toolPath } from "./device-path.ts";+import { SCOPED_RULE_AXES } from "../../core/brain/scoped-rules.ts";+import { CURSOR_SCHEMA } from "./pagination.ts";+import { type ToolDefinition } from "../tool-contract.ts";+import { VAULT_PATH_OUTPUT_SCHEMA } from "../vault-path-field.ts";+import { toolBrainWriteSession } from "./context-session-tools.ts";+import { toolBrainPinnedContext } from "./context-pinned-tools.ts";+import { toolBrainContext } from "./context-active-tools.ts";/*** One agent-facing surface for the write-session kernel: `op`@@ -94,659 +22,9 @@ import { toolPath } from "./device-path.ts";* Structured request failures surface as INVALID_PARAMS with the* machine-readable error list in the message.*/-async function toolBrainWriteSession(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const op = coerceStr(args, "op", true)!;- const sessionId = coerceStr(args, "session_id", false);- const requireSessionId = (): string => {- if (!sessionId) {- throw new MCPError(INVALID_PARAMS, `brain_write_session: op '${op}' requires session_id`, {- code: TOOL_ERROR_CODE.sessionIdRequired,- });- }- return sessionId;- };- try {- switch (op) {- case "open": {- const kind = coerceStr(args, "kind", false) ?? "artifact";- const agent =- normalizeAgentArgument(coerceStr(args, "agent", false) ?? null) ??- resolveAgentName(ctx.configPath ?? undefined);- const requireReview = args["require_review"] === true;- if (kind === "panel") {- const topic = coerceStr(args, "topic", true)!;- const personasRaw = args["personas"];- const personas = Array.isArray(personasRaw)- ? personasRaw.filter((x): x is string => typeof x === "string")- : undefined;- const target = coerceStr(args, "target", false);- return asRecord(- openPanelSession(ctx.vault, {- agent,- topic,- requireReview,- ...(personas && personas.length > 0 ? { personas } : {}),- ...(target ? { targetPath: target } : {}),- }),- );- }- if (kind !== "artifact") {- throw new MCPError(- INVALID_PARAMS,- `brain_write_session: kind must be 'artifact' or 'panel', got '${kind}'`,- );- }- const target = coerceStr(args, "target", true)!;- const intent = coerceStr(args, "intent", false) ?? "create";- if (intent !== "create" && intent !== "overwrite" && intent !== "merge") {- throw new MCPError(- INVALID_PARAMS,- `brain_write_session: intent must be create|overwrite|merge, got '${intent}'`,- );- }- const schemaType = coerceStr(args, "schema_type", false);- const prompt = coerceStr(args, "prompt", false);- const retryCap = args["retry_cap"];- return asRecord(- openArtifactSession(ctx.vault, {- agent,- targetPath: target,- intent,- requireReview,- ...(schemaType ? { schemaType } : {}),- ...(prompt ? { prompt } : {}),- ...(typeof retryCap === "number" ? { retryCap } : {}),- }),- );- }- case "submit": {- const id = requireSessionId();- const text = coerceStr(args, "text", true)!;- return asRecord(dispatchSubmit(ctx.vault, { sessionId: id, text }));- }- case "approve":- return asRecord(approveSession(ctx.vault, { sessionId: requireSessionId() }));- case "abandon":- return asRecord(abandonSession(ctx.vault, { sessionId: requireSessionId() }));- case "status": {- const id = requireSessionId();- const probe = readWriteSession(ctx.vault, id, new Date().toISOString());- if (probe.error !== null) throw new MCPError(INVALID_PARAMS, probe.error);- if (probe.session === null) {- throw new MCPError(INVALID_PARAMS, `unknown write-session: ${id}`, {- code: WRITE_SESSION_REASON_CODE["unknown-session"],- });- }- return asRecord(sessionEnvelope(probe.session));- }- case "list": {- const limit = coerceInt(args, "limit", 100, 1, 500);- const offset = cursorOffsetArg("brain_write_session", args);- const sessions = listWriteSessions(ctx.vault, new Date().toISOString());- const page = pageSlice(sessions, offset, limit);- return {- // `total` counts every session in the list across pages; the- // page itself is `sessions`.- total: page.total,- sessions: page.items.map((rec) => asRecord(sessionEnvelope(rec))),- next_cursor: page.next_cursor,- };- }- default:- throw unknownOperationError(- `brain_write_session: op must be open|submit|approve|abandon|status|list, got '${op}'`,- );- }- } catch (err) {- if (err instanceof WriteSessionRequestError) {- // Preserve the {code, path, message} boundary contract: the- // structured list rides MCPError's data slot, the message stays- // human-readable prose.- throw new MCPError(INVALID_PARAMS, err.message, writeSessionErrorData(err));- }- throw err;- }-}--/**- * The wire code for each session refusal the engine names. Total over the- * core union, so a new reason fails the type check until it is mapped.- */-const WRITE_SESSION_REASON_CODE: Readonly<Record<WriteSessionRequestReason, ToolErrorCode>> =- Object.freeze({- "unknown-session": TOOL_ERROR_CODE.writeSessionUnknown,- "terminal-session": TOOL_ERROR_CODE.writeSessionTerminal,- });--/**- * `data` for a request failure: the structured error list when there is- * one, the precise code when the engine named a reason, nothing otherwise- * - an absent code is filled by the boundary's `invalid_params` default.- */-function writeSessionErrorData(- err: WriteSessionRequestError,-): Readonly<Record<string, unknown>> | undefined {- const data = {- ...(err.errors.length > 0 ? { errors: err.errors } : {}),- ...(err.reason !== undefined ? { code: WRITE_SESSION_REASON_CODE[err.reason] } : {}),- };- return Object.keys(data).length > 0 ? data : undefined;-}--function asRecord(envelope: WriteSessionEnvelope): Record<string, unknown> {- return { ...envelope };-}// ----- brain_context (v0.10.10) ---------------------------------------------type PinnedContextOperation = "read" | "write" | "append" | "clear";--function coercePinnedContextOperation(args: Record<string, unknown>): PinnedContextOperation {- const operation = coerceStr(args, "operation", false) ?? "read";- if (- operation !== "read" &&- operation !== "write" &&- operation !== "append" &&- operation !== "clear"- ) {- throw unknownOperationError(- "brain_pinned_context operation must be one of: read, write, append, clear",- );- }- return operation;-}--/**- * The scratchpad body as THIS request may receive it (delivery-trust,- * lane A): stored text, so at remote reach it is shaped through the- * request's delivery binding - fenced, naming the scratchpad file's own- * derived provenance - and at local reach the stored bytes untouched. An- * absent scratchpad has no body to fence. `delivery` may be handed in by- * a caller that already holds the request's binding, so one request- * keeps one frontmatter cache.- */-function shapedPinnedContent(- ctx: ServerContext,- pinned: PinnedContext,- delivery: ReturnType<typeof deliveryView> = deliveryView(ctx),-): string {- if (!pinned.present || pinned.content.length === 0) return pinned.content;- return delivery.shape(pinned.content, toolPath(ctx, pinned.path));-}--function serializePinnedContext(- ctx: ServerContext,- pinned: PinnedContext,- operation?: PinnedContextOperation,- done?: boolean,- opts?: { shapeBody?: boolean; delivery?: ReturnType<typeof deliveryView> },-): Record<string, unknown> {- return {- ...(operation ? { operation } : {}),- present: pinned.present,- path: toolPath(ctx, pinned.path),- absolute_path: pinned.path,- // Only a READ shapes the body (delivery-trust, lane A). A write or- // batch confirmation echoes bytes the caller just authored - the- // terminal-ack contract stays byte-stable; the delivery contract is- // about handing stored text to a caller that did not write it.- content:- opts?.shapeBody === true- ? shapedPinnedContent(ctx, pinned, opts.delivery ?? deliveryView(ctx))- : pinned.content,- // Terminal/idempotent marker on successful writes so the agent does- // not redundantly re-call after the store already committed.- ...(done ? { done: true } : {}),- };-}--async function toolBrainPinnedContext(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- if (args["operations"] !== undefined) {- return runPinnedContextBatch(ctx, args["operations"]);- }- const operation = coercePinnedContextOperation(args);- if (operation === "read") {- return serializePinnedContext(ctx, readPinnedContext(contextVault(ctx)), operation, undefined, {- shapeBody: true,- });- }- let pinned: PinnedContext;- try {- if (operation === "write") {- pinned = writePinnedContext(contextVault(ctx), coerceStr(args, "content", true)!);- } else if (operation === "append") {- pinned = appendPinnedContext(contextVault(ctx), coerceStr(args, "content", true)!);- } else {- pinned = clearPinnedContext(contextVault(ctx));- }- } catch (err) {- throw pinnedBatchErrorToMcp(err);- }- return serializePinnedContext(ctx, pinned, operation, true);-}--/**- * Map a core {@link PinnedBatchError} (budget-exceeded, malformed op,- * absent replace target) onto a structured INVALID_PARAMS so the agent- * gets a machine-readable rejection — `code`, offending `index`, byte- * sizes, and a consolidation hint — instead of an opaque message or, for- * over-budget writes, a fake truncated success. Non-pinned errors pass- * through unchanged.- */-function pinnedBatchErrorToMcp(err: unknown): unknown {- if (err instanceof PinnedBatchError) {- return new MCPError(INVALID_PARAMS, `brain_pinned_context: ${err.message}`, {- code: err.code,- index: err.index,- ...err.details,- });- }- return err;-}--/**- * Atomic ordered-operations mode for `brain_pinned_context`. The whole- * batch is validated and projected in memory by the core; a malformed op,- * absent replace target, or over-budget final state aborts with zero- * writes and surfaces as a structured INVALID_PARAMS error.- */-function runPinnedContextBatch(- ctx: ServerContext,- operationsRaw: unknown,-): Record<string, unknown> {- let result: PinnedBatchResult;- try {- result = applyPinnedOperations(- contextVault(ctx),- operationsRaw as ReadonlyArray<PinnedOperation>,- );- } catch (err) {- throw pinnedBatchErrorToMcp(err);- }- return {- ...serializePinnedContext(ctx, result, undefined, true),- operations_applied: result.applied,- };-}--function appendPinnedToContextContent(activeContent: string, pinnedContent: string): string {- if (pinnedContent.length === 0) return activeContent;- const pinnedBlock = `## Pinned context\n\n${pinnedContent}`;- const trimmedActive = activeContent.trimEnd();- if (trimmedActive.length === 0) return `${pinnedBlock}\n`;- return `${trimmedActive}\n\n${pinnedBlock}\n`;-}--type BrainContextCounts = RegenerateActiveResult["counts"];--const EMPTY_CONTEXT_COUNTS: BrainContextCounts = {- confirmed: 0,- quarantine: 0,- retired_recent: 0,- most_applied_30d: 0,-};--/**- * Pull-bootstrap of `Brain/active.md` + the active-preference counts.- * Built for runtimes that have no `SessionStart` hook (Cursor, Aider,- * raw Claude API): one tool call gives the agent the same shortcut card- * the SessionStart-aware runtimes get injected automatically.- *- * Not a pure read: the bootstrap path calls `regenerateActive`, which- * writes `Brain/active.md` whenever the on-disk body is absent or- * stale, so the tool classifies `write` (write-mode-dominant,- * `tool-contract.ts`) and the stdio transport never runs two bootstrap- * calls beside each other on the concurrent read path.- *- * Behaviour matrix:- * - Brain/ absent → present:false, zero counts, and content- * carrying the standing-rules block or the- * statement that it could not be read (empty- * for the ordinary case, where there is no- * such file either).- * - Brain/ present, active.md absent → call regenerateActive (idempotent)- * and read the regenerated file.- * - Brain/ present, active.md fresh → idempotent regenerate leaves an- * equal body on disk; the on-disk- * body is returned verbatim.- */-async function toolBrainContext(ctx: ServerContext): Promise<Record<string, unknown>> {- // `null` on a server with no vault (design D14): the digest renders from- // the store's folds into the device-local cache, and there is no vault- // file to read (standing rules, scoped rules, the instruction file).- const vault = contextVault(ctx);- const dirs = brainDirsOf(vault);- // `Brain/active.md` on an unswitched machine; on a store-only one the- // device-local cache the digest is rendered into on demand (D14 item 7).- const activePath = compiledDigestPath(vault, "active");- const onDemand = digestsRenderedOnDemand(vault);- const pinned = readPinnedContext(vault);- // The request's delivery binding, resolved ONCE and used for the active- // body AND the pinned scratchpad beside it (delivery-trust, lane A): one- // frontmatter cache serves the whole assembly, instead of the pinned- // serializer building a second binding per call.- const delivery = deliveryView(ctx);- // Bounded to the single newest `Brain/log/` day - see- // `computeMaintenanceOverdueFlag`'s docblock for the cost bound. This- // is the always-loaded path, so the full `maintenance_debt` derivation- // on `computeBrainStatus` never runs here.- const maintenanceOverdue = computeMaintenanceOverdueFlag(vault, {- withholdsPrivate: contextReach(ctx) !== TRANSPORT_REACH.local,- });-- // The operator's standing rules, resolved before anything else this- // surface assembles - INCLUDING the no-Brain return below. `brain_context`- // is the pull-mode twin of the SessionStart hook, so the constitution has- // to lead the content here for exactly the reason it leads the injected- // payload: on the error branch further down, which zeroes `content` and- // would otherwise hand a runtime the memory layer's failure and none of- // the rules that still govern it, and equally on the branch that reports- // `Brain/` as absent. That probe answers false for a directory it cannot- // TRAVERSE as well as one that is not there, and it was the one return- // path that said nothing at all about the rules - the last silent answer- // on a surface where every other path either carries the block or states- // why it could not be read.- const standing = vault === null ? NO_STANDING_BLOCK : readStandingBlock(vault);- // The scoped operator rules for the project, harness and host this- // server was launched for - local reach only, see `readScopedBlock`.- // Read beside the constitution, before the no-Brain return, for the- // same reason: the rules govern a session whatever the memory layer did.- const scoped = readScopedBlock(ctx);-- // A store-only machine keeps its memory in the store, `Brain/` or not.- if (!onDemand && !existsSync(dirs.brain)) {- return {- vault_path: vaultPathField(ctx),- present: false,- active_path: activePath,- content: prependBlock(standing.text, prependBlock(scoped?.text ?? "", "")),- counts: EMPTY_CONTEXT_COUNTS,- generated_at: null,- pinned: serializePinnedContext(ctx, pinned, undefined, undefined, {- shapeBody: true,- delivery,- }),- maintenance_overdue: maintenanceOverdue,- ...standingRulesField(ctx, standing),- ...scopedRulesField(scoped),- };- }-- let counts: BrainContextCounts = EMPTY_CONTEXT_COUNTS;- let error: string | undefined;- try {- // The SHARED file is regenerated unscoped, always. `active.md` is one- // file for the whole vault - injected into every agent's SessionStart- // by `hooks/active-inject.ts` and regenerated unscoped by the- // `osb://preferences/active` resource - so narrowing the WRITE to this- // caller would make it thrash and could drop an agent's own memories- // from its session start (context-integrity-gates, A3).- counts = regenerateActive(vault).counts;- } catch (err) {- error = (err as Error)?.message ?? String(err);- }-- // After a successful regenerateActive, active.md is guaranteed to- // exist (the function either wrote it or confirmed an equal body- // already on disk). A read failure here is an unrelated filesystem- // race, not a missing-file branch — handle it in the same `error`- // slot the regenerate failure uses.- let content = "";- let generatedAt: string | null = null;- if (!error) {- try {- content = readFileSync(activePath, "utf8");- const [meta] = parseFrontmatter(activePath);- const v = meta["generated_at"];- if (typeof v === "string" && v.trim().length > 0) {- generatedAt = v;- }- } catch (err) {- error = (err as Error)?.message ?? String(err);- content = "";- generatedAt = null;- }- }- // What this ONE caller is handed, not what is on disk, answers at its- // reach and under the owner gate. This surface takes no arguments, so- // `ServerContext.agentName` is its only source of identity and the- // minted reach its only source of distance. A preference or retired- // record the caller cannot read is absent from its digest - principle,- // counts and most-applied entry alike. A local caller with no enforced- // owner scope keeps the file's own bytes; any other caller gets the- // reader render, decided on its reach rather than on what is withheld,- // and stamped with the generation already on disk.- if (!error) {- const readable = readableAtContextReachOrUndefined(ctx);- const reader = {- ...(readable !== undefined ? { readable } : {}),- restricted: contextReach(ctx) !== TRANSPORT_REACH.local,- ...(ctx.agentName !== undefined ? { agentScope: ctx.agentName } : {}),- };- if (readerNarrowsActive(vault, reader)) {- const narrowed = renderActiveForReader(vault, reader);- content = narrowed.document;- counts = narrowed.counts;- }- }-- // Constitution first, then the scoped rules, then the memory body -- // and the body is shaped BEFORE the assembly (delivery-trust, lane A):- // the fence wraps the stored-record bytes only. The constitution and- // the scoped rules are the operator's own voice delivered local-only,- // and the pinned scratchpad shapes through the same binding beside- // this assembly, so neither slips past the fence the body carries.- // An unfetchable body has nothing to fence: the pinned scratchpad's- // shaper skips empty bodies, and the main body answers the same way- // instead of wrapping an empty block in the fence.- if (content.length > 0) {- content = delivery.shape(content, `${BRAIN_ROOT_REL}/${BRAIN_ACTIVE_FILE}`);- }- content = prependBlock(standing.text, prependBlock(scoped?.text ?? "", content));- content = appendPinnedToContextContent(content, shapedPinnedContent(ctx, pinned, delivery));-- // Optional vault-root instruction file (v0.10.17). Absent file =- // field omitted so hosts that strip unknown fields stay- // byte-identical.- //- // A THROW IS NOT AN ABSENCE. This used to be `catch { null }`, which- // put an operator configuration error - an absolute path, a `..`- // segment, an empty name - and an unreadable file on the same wire as- // a vault that simply has no instruction file: the field vanished and- // nothing said why. The reason now rides its own key, so the- // enrichment stays best-effort without being silent.- let vaultInstruction: ReturnType<typeof readVaultInstructionFile> = null;- let vaultInstructionError: string | undefined;- try {- vaultInstruction = vault === null ? null : readVaultInstructionFile(vault);- } catch (err) {- vaultInstructionError = (err as Error)?.message ?? String(err);- }-- return {- vault_path: vaultPathField(ctx),- present: true,- active_path: activePath,- content,- counts,- generated_at: generatedAt,- pinned: serializePinnedContext(ctx, pinned, undefined, undefined, {- shapeBody: true,- delivery,- }),- maintenance_overdue: maintenanceOverdue,- ...(error ? { error } : {}),- ...standingRulesField(ctx, standing),- ...scopedRulesField(scoped),- ...(vaultInstruction- ? {- vault_instruction: {- path: vaultInstruction.path,- content: vaultInstruction.content,- lines: vaultInstruction.lines,- },- }- : {}),- ...(vaultInstructionError !== undefined- ? { vault_instruction_error: vaultInstructionError }- : {}),- };-}--/**- * The standing-rules block and the record behind it, or neither.- *- * The two travel together because the response reports them in two- * different places - the block is prepended to `content`, the record- * becomes the `standing_rules` key - and a read that FAILED produces a- * block but no record: there is no path/content/truncated triple to- * report for bytes nobody could read, and the block itself is what says- * so in words the agent will read.- */-interface StandingBlock {- readonly text: string;- readonly rules: StandingRules | null;-}--const NO_STANDING_BLOCK: StandingBlock = Object.freeze({ text: "", rules: null });--function readStandingBlock(vault: string): StandingBlock {- const path = brainStandingRulesPath(vault);- let cfg: BrainConfig | null = null;- try {- cfg = loadBrainConfig(vault);- } catch {- // A `_brain.yaml` this surface cannot read resolves the cap to its- // default; the config failure itself surfaces through the `error`- // slot that the regenerate arm above already populates.- }- try {- const rules = readStandingRules(vault, { maxChars: resolveStandingRulesMaxChars(cfg) });- if (rules === null) return NO_STANDING_BLOCK;- return Object.freeze({ text: renderStandingRules(rules), rules });- } catch (err) {- return Object.freeze({ text: renderStandingRulesFailure(path, err), rules: null });- }-}--/**- * The optional `standing_rules` key, or nothing.- *- * Both return shapes spread it from here so the two cannot disagree about- * when the key appears. It is omitted for a vault whose operator wrote no- * rules AND for a read that failed - the failure has no path/content/- * truncated triple to report, and the block inside `content` is what says- * so in words.- */-function standingRulesField(ctx: ServerContext, standing: StandingBlock): Record<string, unknown> {- if (standing.rules === null) return {};- return {- standing_rules: {- path: toolPath(ctx, standing.rules.path),- content: standing.rules.text,- truncated: standing.rules.truncated,- },- };-}--/** Put a block at the head of the content, or leave the content alone. */-function prependBlock(block: string, content: string): string {- if (block.length === 0) return content;- const trimmed = content.trimStart();- return trimmed.length === 0 ? `${block}\n` : `${block}\n\n${trimmed}`;-}--/**- * The scoped operator rules rendered for this server's scope, or nothing.- *- * LOCAL REACH ONLY. The scope is resolved from facts about the process- * that serves the call - the directory it was launched in, the harness- * its registration names, the device it runs on - and at remote reach- * none of them describes the caller. So at remote reach nothing is read- * at all: not the files, not the pointer, not the device id, and the- * answer is byte-identical whether or not any scoped file exists.- *- * The identity comes from {@link ServerContext.ruleScope} and the device- * id; no argument of this tool can name it (the tool takes none).- */-function readScopedBlock(ctx: ServerContext): ScopedRules | null {- if (contextReach(ctx) !== TRANSPORT_REACH.local) return null;- // Scoped rules are vault files; a server with no vault has none.- if (contextVault(ctx) === null) return null;- let host: { readonly host: string | null; readonly unreadable: boolean };- try {- host = resolveHostScope(ctx.configPath ?? undefined);- } catch {- // A device id that cannot be resolved for any other reason (a config- // home that cannot be created, say) must not take the bootstrap- // surface down with it. It matches no host file, and the block says- // so when there is a host file it could have matched.- host = { host: null, unreadable: true };- }- const identity: ScopedRuleIdentity = {- project: resolveProjectScope(ctx.ruleScope?.workspaceDir ?? null, ctx.vault),- harness: ctx.ruleScope?.harness ?? null,- host: host.host,- };- let rules: ScopedRules;- try {- rules = readScopedRules(ctx.vault, identity, {- maxChars: scopedRulesMaxChars(ctx.vault),- hostUnreadable: host.unreadable,- });- } catch {- // The reader renders every per-file failure as an `UNAVAILABLE:` line- // and does not throw for one; anything that still escapes it must not- // take the constitution and the memory layer down with the scoped block.- return null;- }- return rules.text.length === 0 ? null : rules;-}--/**- * The configured cap, or its default when `_brain.yaml` cannot be read- * (that failure surfaces through the regenerate arm's `error` slot, as- * for the constitution's cap).- */-function scopedRulesMaxChars(vault: string): number {- let cfg: BrainConfig | null = null;- try {- cfg = loadBrainConfig(vault);- } catch {- // absorbed - see above- }- return resolveScopedRulesMaxChars(cfg);-}--/**- * The optional `scoped_rules` key, or nothing: present only when a file- * matched or the host notice applies, so a vault with no scoped rules -- * and every remote caller - keeps today's bytes.- */-function scopedRulesField(scoped: ScopedRules | null): Record<string, unknown> {- if (scoped === null) return {};- return {- scoped_rules: {- scope: {- project: scoped.identity.project,- harness: scoped.identity.harness,- host: scoped.identity.host,- },- files: scoped.files.map((file) => ({- path: file.path,- axis: file.axis,- truncated: file.truncated,- })),- },- };-}-// ----- brain_digest --------------------------------------------------------const PINNED_CONTEXT_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {diff --git a/src/mcp/brain/dream-tools.ts b/src/mcp/brain/dream-tools.tsnew file mode 100644index 00000000..de5c6390--- /dev/null+++ b/src/mcp/brain/dream-tools.ts@@ -0,0 +1,470 @@+/**+ * `brain_dream` (task 3.19): the dream pass and its dry-run preview,+ * with the gate overrides, the reach-scoped rows and the change list the+ * answer renders. Runs at local reach only. Split from+ * `feedback-tools.ts`; registration happens through that module's+ * registry, which preserves the public FEEDBACK_TOOLS surface.+ */++import { resolveAgentName, resolveNearDuplicateRetireSiblingsEnabled } from "../../core/config.ts";+import { dream, type DreamGateOverrides } from "../../core/brain/dream.ts";+import type { ProgressSink } from "../../core/brain/progress.ts";+import {+ DREAM_GATE_NAMES,+ DreamGateOverrideError,+ validateDreamGateOverrides,+} from "../../core/brain/dream-gates.ts";+import { DreamStepNotRunnableError, runDreamStep } from "../../core/brain/dream-step.ts";+import {+ applyDreamBundle,+ discardDreamBundle,+ DreamRetriageError,+ listDreamBundles,+ retriageDreamBundle,+ stageDream,+ validateDreamBundle,+ type DreamRetriageEntry,+} from "../../core/brain/dream-stage.ts";+import { gatedOwnerScopeView, type OwnerScopeView } from "../../core/brain/owner-scope-view.ts";+import { brainArtifactSlug } from "../../core/brain/wikilink.ts";+import { normalizeAgentArgument } from "../../core/agent-identity.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import { contextVault, type ServerContext } from "../tool-contract.ts";+import { coerceStr, coerceBool, coerceIsoDate, unknownOperationError } from "../coerce.ts";+import { enforceCountGuard, readCountGuardArgs, toolSafeguard } from "./shared.ts";+import { toolPath } from "./device-path.ts";+import { OPERATION } from "../../core/brain/safeguard.ts";+import { readableAtContextReach, readableAtContextReachOrUndefined } from "./reach-readable.ts";++// ----- brain_dream ---------------------------------------------------------++/** The set of preference ids a dream summary would create/confirm/retire/move. */+export function dreamChangeList(summary: {+ readonly new_unconfirmed: ReadonlyArray<string>;+ readonly confirmed: ReadonlyArray<string>;+ readonly retired: ReadonlyArray<{ readonly id: string }>;+ readonly moved_to_processed: ReadonlyArray<string>;+}): string[] {+ return [+ ...summary.new_unconfirmed,+ ...summary.confirmed,+ ...summary.retired.map((r) => r.id),+ ...summary.moved_to_processed,+ ];+}++/**+ * Read the optional `gates` argument (no-dead-ends, Unit E - operator+ * surface). JSON-RPC carries real objects and booleans, so the MCP form+ * is the override record itself rather than the CLI's `name=value`+ * strings; both go through the same validator in `dream-gates.ts`, so+ * the accepted gate names cannot diverge between the two surfaces.+ */+export function readDreamGates(args: Record<string, unknown>): DreamGateOverrides | undefined {+ const raw = args["gates"];+ if (raw === undefined || raw === null) return undefined;+ if (typeof raw !== "object" || Array.isArray(raw)) {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_dream: gates must be an object of <gate>: <boolean>; known gates: ${DREAM_GATE_NAMES.join(", ")}`,+ );+ }+ try {+ return validateDreamGateOverrides(raw as Record<string, unknown>);+ } catch (exc) {+ if (exc instanceof DreamGateOverrideError) {+ throw new MCPError(INVALID_PARAMS, `brain_dream: ${exc.message}`);+ }+ throw exc;+ }+}++/**+ * The rows of a dream plan or run summary the caller may see+ * (a-label-is-not-a-boundary, U3).+ *+ * Every list here names a preference or a signal by id, and the pass+ * that produced them is vault-wide by construction: consolidation reads+ * every topic, and clustering only half a vault would produce different+ * preferences for every caller. So the PASS stays unscoped and the+ * REPORT is filtered - a caller is told what it did to the artifacts+ * that caller may see, and nothing about the rest.+ *+ * `contradictions`, `quarantined` and `intent_reviews` are absent from+ * the fold on purpose: their subject is a TOPIC over inbox signals, and+ * a signal carries no `owner:` anywhere in this product, so there is no+ * ownership claim on disk to read.+ */+export function scopedDreamRows<R extends string>(+ view: OwnerScopeView,+ plan: {+ readonly new_unconfirmed: ReadonlyArray<string>;+ readonly confirmed: ReadonlyArray<string>;+ readonly retired: ReadonlyArray<{ readonly id: string; readonly reason: R }>;+ readonly moved_to_processed: ReadonlyArray<string>;+ readonly suppressed: ReadonlyArray<string>;+ },+): {+ new_unconfirmed: ReadonlyArray<string>;+ confirmed: ReadonlyArray<string>;+ retired: ReadonlyArray<{ id: string; reason: R }>;+ moved_to_processed: ReadonlyArray<string>;+ suppressed: ReadonlyArray<string>;+} {+ const ids = (list: ReadonlyArray<string>): ReadonlyArray<string> => view.keep(list, (id) => [id]);+ return {+ new_unconfirmed: ids(plan.new_unconfirmed),+ confirmed: ids(plan.confirmed),+ // A retire names the preference by BOTH spellings across the move:+ // `ret-<slug>` after the pass, `pref-<slug>` before it.+ retired: view+ .keep(plan.retired, (r) => [r.id, `pref-${brainArtifactSlug(r.id)}`])+ .map((r) => ({ id: r.id, reason: r.reason })),+ moved_to_processed: ids(plan.moved_to_processed),+ suppressed: ids(plan.suppressed),+ };+}++/** The one answer a caller below local reach gets for anything but a dry run. */+export const DREAM_LOCAL_REACH_ONLY =+ "brain_dream: below local reach only action=run with dry_run is served; a real pass, a step and the staged lifecycle run at local reach only";++export async function toolBrainDream(+ ctx: ServerContext,+ args: Record<string, unknown>,+ onProgress?: ProgressSink,+): Promise<Record<string, unknown>> {+ // `null` on a server with no vault: the inline pass runs over the store+ // alone (D14); a step and the staged lifecycle read `ctx.vault`, which+ // refuses with `vault_required` there.+ const vault = contextVault(ctx);+ const action = args["action"] ?? "run";+ if (+ action !== "run" &&+ action !== "stage" &&+ action !== "validate" &&+ action !== "apply" &&+ action !== "retriage" &&+ action !== "discard" &&+ action !== "list"+ ) {+ throw unknownOperationError(+ "brain_dream: action must be run|stage|validate|apply|retriage|discard|list",+ );+ }+ const dryRun = coerceBool(args, "dry_run");+ const nowDate = coerceIsoDate(args, "now");+ const agentArg = coerceStr(args, "agent", false);+ const agent = normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);+ const gates = readDreamGates(args);+ const stepArg = coerceStr(args, "step", false);+ // One view for the whole call: every branch below reports preference+ // and signal ids, and the staged lifecycle reports them twice.+ const dreamView = gatedOwnerScopeView(vault, ctx.agentName);+ // The rollup step's link candidates leave out a page the caller may not+ // read at its reach, exactly as an absent page.+ const readable = readableAtContextReach(ctx);+ // Below local reach only a dry run is served, planned over the records+ // the caller may read as if the others were absent. A real pass, a+ // single step and the staged lifecycle move, rewrite or report records+ // the caller may not read, so they are refused with one fixed answer+ // before anything is read or written, whatever the vault holds.+ const previewReadable = readableAtContextReachOrUndefined(ctx);+ if (previewReadable !== undefined && (action !== "run" || !dryRun || stepArg)) {+ throw new MCPError(INVALID_PARAMS, DREAM_LOCAL_REACH_ONLY);+ }+ const previewScope = previewReadable !== undefined ? { previewReadable } : {};++ // Single-step requests (no-dead-ends, Unit E - operator surface).+ // Deliberately checked before any environment work: a step the pass+ // cannot honour is refused by name, carrying the specific reason and+ // the runnable set, and nothing is read or written on that path.+ if (stepArg) {+ if (action !== "run") {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_dream: step applies to action=run; action=${action} drives the staged lifecycle, which has no single step`,+ );+ }+ const conflicting = dryRun+ ? "dry_run"+ : gates !== undefined+ ? "gates"+ : "expect" in args || "strict" in args+ ? "expect/strict"+ : null;+ if (conflicting !== null) {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_dream: step cannot be combined with ${conflicting} - a single step has no preview path, reads no gate, and produces none of the preference counters the guard asserts over`,+ );+ }+ try {+ // Bounded and observed on the same terms as every sibling branch.+ // This one had neither: it was the row `docs/mcp.md` marked+ // **none**, and `dream()` being synchronous is exactly why that+ // mattered - an unbounded step holds the server's event loop for+ // its whole duration and the client cannot even time out and+ // reissue. The budget is `dream`'s, because a step IS part of a+ // dream pass; the sink is the caller's, dropped here until now.+ return {+ ...runDreamStep(ctx.vault, stepArg, {+ safeguard: toolSafeguard(ctx, OPERATION.dream),+ ...(onProgress ? { onProgress } : {}),+ }),+ };+ } catch (exc) {+ if (exc instanceof DreamStepNotRunnableError) {+ throw new MCPError(INVALID_PARAMS, exc.message);+ }+ throw exc;+ }+ }++ if (action !== "run") {+ if (gates !== undefined) {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_dream: gates apply to action=run; action=${action} drives the staged lifecycle, whose bundle records the gates its own run resolved`,+ );+ }+ // Staged lifecycle (t_ae8a8ec0): stage -> validate -> apply over a+ // persisted bundle; dream() stays the only promotion engine.+ const runIdArg = coerceStr(args, "run_id", false);+ if (action !== "list" && action !== "stage" && !runIdArg) {+ throw new MCPError(INVALID_PARAMS, `brain_dream action=${action}: run_id is required`);+ }+ const now = nowDate ?? new Date();+ // The staged lifecycle runs the same consolidation pass `action=run`+ // does - `stage` previews it, `apply` promotes from it - so it is+ // bounded and reported on the same terms. Without the sink a client+ // that sent a progressToken for `action: "stage"` would be told+ // nothing and see nothing for the whole pass.+ const stageOpts = {+ now,+ safeguard: toolSafeguard(ctx, OPERATION.dream),+ readable,+ ...(agent ? { agentName: agent } : {}),+ ...(onProgress ? { onProgress } : {}),+ };+ switch (action) {+ case "stage": {+ const bundle = stageDream(ctx.vault, stageOpts);+ return {+ action,+ run_id: bundle.runId,+ plan: { ...bundle.plan, ...scopedDreamRows(dreamView, bundle.plan) },+ sources: bundle.sources.length,+ dir: `Brain/dream/staged/${bundle.runId}`,+ };+ }+ case "validate": {+ const verdict = validateDreamBundle(ctx.vault, runIdArg!, stageOpts);+ return { action, run_id: runIdArg, valid: verdict.valid, drift: [...verdict.drift] };+ }+ case "apply": {+ const outcome = applyDreamBundle(ctx.vault, runIdArg!, stageOpts);+ return {+ action,+ run_id: runIdArg,+ applied: outcome.applied,+ drift: [...outcome.validation.drift],+ ...(outcome.summary !== undefined+ ? { changed: outcome.summary.changed, ...scopedDreamRows(dreamView, outcome.summary) }+ : {}),+ };+ }+ case "retriage": {+ // Read-only: it re-runs the salience gate against the current+ // threshold and reports what would move. The bundle is not+ // rewritten, so a caller that likes the new partition re-stages.+ let outcome;+ try {+ outcome = retriageDreamBundle(ctx.vault, runIdArg!, stageOpts);+ } catch (exc) {+ if (exc instanceof DreamRetriageError) {+ throw new MCPError(INVALID_PARAMS, `brain_dream: ${exc.message}`);+ }+ throw exc;+ }+ const scopedDelta = (+ entries: ReadonlyArray<DreamRetriageEntry>,+ ): Array<Record<string, unknown>> =>+ dreamView+ .keep(entries, (entry) => [entry.pref_id, entry.path])+ .map((entry) => ({+ pref_id: entry.pref_id,+ path: entry.path,+ score: entry.score,+ staged_score: entry.staged_score,+ }));+ return {+ action,+ run_id: runIdArg,+ staged_threshold: outcome.stagedThreshold,+ current_threshold: outcome.currentThreshold,+ changed: outcome.changed,+ considered: outcome.considered,+ admitted: outcome.admitted,+ // Counts before the owner filter, names after it: a scoped+ // caller is still told HOW MANY facts moved, and only the+ // identities it may not see are withheld.+ newly_admitted_count: outcome.newlyAdmitted.length,+ newly_excluded_count: outcome.newlyExcluded.length,+ newly_admitted: scopedDelta(outcome.newlyAdmitted),+ newly_excluded: scopedDelta(outcome.newlyExcluded),+ notes: [...outcome.notes],+ };+ }+ case "discard": {+ return { action, run_id: runIdArg, removed: discardDreamBundle(ctx.vault, runIdArg!) };+ }+ default: {+ return {+ action,+ bundles: listDreamBundles(ctx.vault).map((b) => ({+ run_id: b.runId,+ status: b.status,+ staged_at: b.stagedAt,+ proposals: b.proposals,+ sources: b.sources,+ })),+ };+ }+ }+ }++ const { expect, strict } = readCountGuardArgs(args);+ // One deadline for the whole tool call, not one per pass. `dream()` is+ // synchronous, so an unbounded call blocks the server's event loop for+ // its entire duration and the client cannot even time out and reissue;+ // what has to be bounded is therefore the call, and a guarded run is+ // two passes over the same tree. Sharing the guard means a slow preview+ // spends the run's budget - which is the honest reading of a budget the+ // operator set for this operation.+ const safeguard = toolSafeguard(ctx, OPERATION.dream);+ // The retire-siblings key honours the server's own config file, as+ // `brain_review_candidates` does.+ const retireSiblingsEnabled = resolveNearDuplicateRetireSiblingsEnabled(+ ctx.configPath ?? undefined,+ );+ // Only pay for a preview pass when a guard is actually requested; otherwise+ // the run is byte-identical to before.+ if (expect !== null || strict) {+ const preview = dream(vault, {+ dryRun: true,+ safeguard,+ readable,+ retireSiblingsEnabled,+ ...previewScope,+ ...(nowDate ? { now: nowDate } : {}),+ ...(agent ? { agentName: agent } : {}),+ // Preview the run being guarded, overrides and all.+ ...(gates !== undefined ? { gates } : {}),+ });+ const previewList = dreamChangeList(preview);+ enforceCountGuard({+ matched: previewList.length,+ expect,+ strict,+ willMutate: !dryRun,+ matchList: previewList,+ });+ }++ // The count-guard preview above is deliberately NOT reported on: it is+ // a dry run whose only purpose is to decide whether the run below may+ // happen at all, and a client that saw the same five stages twice+ // would read the second pass as a restart. Progress describes the run+ // the caller asked for.+ const summary = dream(vault, {+ dryRun,+ safeguard,+ readable,+ retireSiblingsEnabled,+ ...previewScope,+ ...(nowDate ? { now: nowDate } : {}),+ ...(agent ? { agentName: agent } : {}),+ ...(gates !== undefined ? { gates } : {}),+ ...(onProgress ? { onProgress } : {}),+ });+ const changeList = dreamChangeList(summary);+ // A retire-sibling pair names two preferences; it is kept only when the+ // caller may see both, each in both spellings (`ret-<slug>` after the+ // pass, `pref-<slug>` before it).+ const bothSpellings = (id: string): ReadonlyArray<string> => {+ const slug = brainArtifactSlug(id);+ return [`pref-${slug}`, `ret-${slug}`];+ };+ const retireSiblings = dreamView.keep(summary.retire_siblings ?? [], (p) => [+ ...bothSpellings(p.retiring_id),+ ...bothSpellings(p.sibling_id),+ ]);++ // The summary is already a Plain Old Frozen Object — JSON-serialise+ // verbatim. We surface `snapshot_path` / `log_path` as vault-relative+ // for caller convenience while preserving the absolute path as well.+ return {+ run_id: summary.run_id,+ changed: summary.changed,+ // Honest matched-vs-changed: `matched` is what the pass would touch;+ // `changed_count` is what it actually wrote (0 on a dry run).+ matched: changeList.length,+ changed_count: dryRun ? 0 : changeList.length,+ dry_run: dryRun,+ ...scopedDreamRows(dreamView, summary),+ ...(retireSiblings.length > 0+ ? {+ retire_siblings: retireSiblings.map((p) => ({+ retiring_id: p.retiring_id,+ sibling_id: p.sibling_id,+ score: p.score,+ method: p.method,+ })),+ }+ : {}),+ // Inbox archive (issue #195): a count, not the ids. A first pass over a+ // long-lived vault archives thousands of signals; the run's log event+ // names every one of them.+ archived_signals_count: summary.archived_signals?.length ?? 0,+ contradictions: [...summary.contradictions],+ warnings: summary.warnings.map((w) => ({+ code: w.code,+ message: w.message,+ })),+ uncertain: summary.uncertain.map((u) => ({+ code: u.code,+ ...(u.topic !== undefined ? { topic: u.topic } : {}),+ message: u.message,+ })),+ quarantined: summary.quarantined.map((q) => ({+ topic: q.topic,+ signal_count: q.signal_count,+ distinct_agents: q.distinct_agents,+ age_days: q.age_days,+ failed_gates: [...q.failed_gates],+ })),+ // The salience gate over the rollup fold set. `threshold: null` says+ // the gate was absent, and the two counts are reported before the+ // owner filter so a scoped caller still learns how many facts were+ // held back even where it may not see their names.+ salience_gate: {+ threshold: summary.salience_gate.threshold,+ considered: summary.salience_gate.considered,+ admitted: summary.salience_gate.admitted,+ excluded_count: summary.salience_gate.excluded.length,+ excluded: dreamView+ .keep(summary.salience_gate.excluded, (entry) => [entry.pref_id, entry.path])+ .map((entry) => ({+ pref_id: entry.pref_id,+ path: entry.path,+ score: entry.score,+ mass: entry.mass,+ confidence: entry.confidence,+ reuse: entry.reuse,+ })),+ },+ snapshot_path: summary.snapshot_path ? toolPath(ctx, summary.snapshot_path) : null,+ log_path: summary.log_path ? toolPath(ctx, summary.log_path) : null,+ };+}diff --git a/src/mcp/brain/evidence-tools.ts b/src/mcp/brain/evidence-tools.tsnew file mode 100644index 00000000..6209cbd7--- /dev/null+++ b/src/mcp/brain/evidence-tools.ts@@ -0,0 +1,220 @@+/**+ * The evidence and observation tools (task 3.19): `brain_apply_evidence`,+ * `brain_observed_use` and `brain_note`, the three record writers of the+ * feedback family that are not the capture lane or the dream. Split+ * from `feedback-tools.ts`; registration happens through that module's+ * registry, which preserves the public FEEDBACK_TOOLS surface.+ */++import { resolve } from "node:path";+import { resolveAgentName } from "../../core/config.ts";+import {+ appendApplyEvidence,+ BrainPreferenceNotFoundError,+ type AppendApplyEvidenceInput,+} from "../../core/brain/apply-evidence.ts";+import { BRAIN_ROLES } from "../../core/brain/trust/role.ts";+import { normalizeAgentArgument } from "../../core/agent-identity.ts";+import { BRAIN_APPLY_RESULT, type BrainApplyResult } from "../../core/brain/types.ts";+import { appendBrainNote } from "../../core/brain/note.ts";+import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";+import { contextVault, type ServerContext } from "../tool-contract.ts";+import { refuseAgentClaim } from "./agent-claim.ts";+import {+ emitObservedUse,+ isObservedUseVerdict,+ type ObservedUseEntry,+} from "../../core/brain/observed-use.ts";+import { coerceStr } from "../coerce.ts";+import { toolPath } from "./device-path.ts";+import { readableAtContextReachOrUndefined } from "./reach-readable.ts";++// ----- brain_review_candidates --------------------------------------------++export async function toolBrainApplyEvidence(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ // `null` on a server with no vault: the writes are store records (D14).+ const vault = contextVault(ctx);+ const prefId = coerceStr(args, "pref_id", true)!;+ const artifact = coerceStr(args, "artifact", true)!;+ const resultRaw = coerceStr(args, "result", true)!;+ if (+ resultRaw !== BRAIN_APPLY_RESULT.applied &&+ resultRaw !== BRAIN_APPLY_RESULT.violated &&+ resultRaw !== BRAIN_APPLY_RESULT.outdated+ ) {+ throw new MCPError(+ INVALID_PARAMS,+ `argument 'result' must be 'applied', 'violated', or 'outdated'`,+ );+ }+ const agentArg = coerceStr(args, "agent", false);+ const note = coerceStr(args, "note", false);+ const outcomeRaw = coerceStr(args, "outcome", false);+ if (+ outcomeRaw !== null &&+ outcomeRaw !== "success" &&+ outcomeRaw !== "failure" &&+ outcomeRaw !== "unknown"+ ) {+ throw new MCPError(+ INVALID_PARAMS,+ `argument 'outcome' must be 'success', 'failure', or 'unknown'`,+ );+ }++ // The evidence row names who applied the rule; a token caller cannot+ // file that attribution under another agent's name.+ refuseAgentClaim(ctx.requestIdentity, agentArg, "brain_apply_evidence");+ const agent =+ normalizeAgentArgument(agentArg) ??+ ctx.requestIdentity?.agent ??+ resolveAgentName(ctx.configPath ?? undefined);++ const input: AppendApplyEvidenceInput = {+ pref_id: prefId,+ artifact,+ result: resultRaw as BrainApplyResult,+ agent,+ ...(outcomeRaw !== null ? { outcome: outcomeRaw } : {}),+ ...(note ? { note } : {}),+ };++ // Surface BrainPreferenceNotFoundError as a tool-level error envelope+ // (isError: true) rather than an MCP protocol error. The design doc+ // says "not an error condition" — the agent should see an informative+ // payload that explains what to do next, not a JSON-RPC error frame.+ // v0.10.16: assert applier role at the MCP boundary so the structural+ // permission gate fires before any I/O.+ // A preference the caller may not read is refused as a missing one,+ // before anything is written.+ const readable = readableAtContextReachOrUndefined(ctx);+ try {+ const res = appendApplyEvidence(vault, input, {+ role: BRAIN_ROLES.applier,+ ...(readable !== undefined ? { readable } : {}),+ });+ return {+ logged_at: res.logged_at,+ // With no vault the log is a store shard, named as the store names it.+ log_path: vault === null ? res.log_path : toolPath(ctx, res.log_path),+ absolute_log_path: vault === null ? res.log_path : resolve(res.log_path),+ agent,+ };+ } catch (exc) {+ if (exc instanceof BrainPreferenceNotFoundError) {+ // Re-throw as a non-MCPError so `server.handleToolsCall` packs it+ // into a `toolError` envelope (isError: true, single-text content).+ throw new Error(exc.message, { cause: exc });+ }+ throw exc;+ }+}++// ----- brain_observed_use (t_65588d8b) -------------------------------------++/**+ * Record session-end observed-use verdicts (USED / IGNORED / CONTRADICTED)+ * per injected memory, mirroring `brain_apply_evidence`: the host supplies+ * already-structured verdicts (no LLM in the kernel), which are folded into+ * the observed-reuse ranking signal. The kernel only stores and aggregates.+ */+export async function toolBrainObservedUse(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const rawEntries = args["entries"];+ if (!Array.isArray(rawEntries) || rawEntries.length === 0) {+ throw new MCPError(INVALID_PARAMS, "argument 'entries' must be a non-empty array");+ }+ const entries: ObservedUseEntry[] = rawEntries.map((raw, i) => {+ if (raw === null || typeof raw !== "object") {+ throw new MCPError(INVALID_PARAMS, `entries[${i}] must be an object`);+ }+ const e = raw as Record<string, unknown>;+ const id = typeof e["id"] === "string" ? e["id"].trim() : "";+ if (id === "") throw new MCPError(INVALID_PARAMS, `entries[${i}].id is required`);+ const verdict = e["verdict"];+ if (!isObservedUseVerdict(verdict)) {+ throw new MCPError(+ INVALID_PARAMS,+ `entries[${i}].verdict must be 'USED', 'IGNORED', or 'CONTRADICTED'`,+ );+ }+ const path = typeof e["path"] === "string" && e["path"] !== "" ? e["path"] : undefined;+ return { id, verdict, ...(path ? { path } : {}) };+ });++ const host = coerceStr(args, "host", false) ?? "mcp";+ const sessionId = coerceStr(args, "session_id", false) ?? undefined;+ const turnId = coerceStr(args, "turn_id", false) ?? undefined;+ const record = emitObservedUse(ctx.vault, {+ host,+ ...(sessionId ? { sessionId } : {}),+ ...(turnId ? { turnId } : {}),+ entries,+ });+ return {+ recorded: entries.length,+ record_id: record.id,+ created_at: record.createdAt,+ };+}++// ----- brain_note (§32B, v0.10.8) ------------------------------------------++/**+ * Append one narrative-milestone line to today's Brain log. Agents+ * record release / merged-PR / discovered-fact lines under the `note`+ * event kind in `Brain/log/<today>.md` (and the JSONL sidecar).+ *+ * The body lives in `appendBrainNote` so the CLI verb (`o2b brain+ * note`) and this MCP handler share one code path. Validation errors+ * land in MCP's `INVALID_PARAMS` envelope here; the CLI wrapper+ * pre-validates usage shape and surfaces the same condition as exit 2.+ */+export async function toolBrainNote(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ // `null` on a server with no vault: the writes are store records (D14).+ const vault = contextVault(ctx);+ const rawText = coerceStr(args, "text", true)!;+ const agentArg = coerceStr(args, "agent", false);+ // A token caller's log line is attributed to the token's agent; a+ // claim on somebody else's name is refused before anything is written.+ refuseAgentClaim(ctx.requestIdentity, agentArg, "brain_note");+ // A TOKEN caller that omits `agent` is attributed to the token's agent+ // all the same: `appendBrainNote` would otherwise resolve the absent+ // name through the process config, stamping the config identity where+ // the credential decided. A SHARED-KEY caller keeps the historical+ // config-path resolution: the shared key is the operator, whose+ // identity is the config's to name.+ const agent =+ agentArg ?? (ctx.requestIdentity?.via === "token" ? ctx.requestIdentity.agent : undefined);++ let res;+ try {+ res = appendBrainNote({+ vault: vault,+ text: rawText,+ ...(agent ? { agent } : {}),+ ...(ctx.configPath ? { configPath: ctx.configPath } : {}),+ });+ } catch (err) {+ // `appendBrainNote` throws one validation error ("text is required");+ // any other failure is an I/O / filesystem fault from `appendLogEvent`+ // and must not be reported as a client-side INVALID_PARAMS.+ const message = (err as Error).message ?? String(err);+ const code = message.startsWith("brain_note:") ? INVALID_PARAMS : INTERNAL_ERROR;+ throw new MCPError(code, message);+ }+ return {+ logged_at: res.logged_at,+ log_path: res.log_path,+ absolute_log_path: res.absolute_log_path,+ agent: res.agent,+ };+}diff --git a/src/mcp/brain/expire-tools.ts b/src/mcp/brain/expire-tools.tsnew file mode 100644index 00000000..135172b2--- /dev/null+++ b/src/mcp/brain/expire-tools.ts@@ -0,0 +1,89 @@+/**+ * `brain_expire` (task 3.19): the post-creation expiration mutation,+ * addressed by id rather than by the vault-relative path a lifecycle+ * action takes. Split from `feedback-tools.ts`; registration happens+ * through that module's registry, which preserves the public+ * FEEDBACK_TOOLS surface.+ */++import {+ ExpirationTargetNotFoundError,+ ExpirationValueError,+ InvalidExpirationTargetError,+ setExpiration,+} from "../../core/brain/expiration-set.ts";+import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";+import { type ServerContext } from "../tool-contract.ts";+import { refuseAgentClaim } from "./agent-claim.ts";+import { codeForError } from "../tool-error-codes.ts";+import { coerceStr } from "../coerce.ts";+import { readableAtContextReachOrUndefined } from "./reach-readable.ts";++// ----- brain_write_session (Agent Write Contract Suite, v0.41.0) ------------++/**+ * Post-creation expiration mutation (unit 3c).+ *+ * A tool of its own rather than an action on `brain_lifecycle`, and the+ * reason is how each addresses its subject: every `brain_lifecycle`+ * action takes a vault-relative PATH and runs it through a note-path+ * envelope, while a signal or preference is addressed by id and lives+ * under the `Brain/` root that envelope exists to refuse. Folding them+ * together would mean carving an exception into that refusal.+ */+export const EXPIRE_TOOL = "brain_expire";++export async function toolBrainExpire(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const id = coerceStr(args, "id", true)!;+ const expires = coerceStr(args, "expires", true)!;+ const agent = coerceStr(args, "agent", false);+ // The expiration's audit stamp names who set it; a token caller cannot+ // sign another agent's name to it.+ refuseAgentClaim(ctx.requestIdentity, agent, "brain_expire");+ // A TOKEN caller that omits `agent` still stamps its own name: the+ // audit log would otherwise record the writer's DEFAULT_AGENT instead+ // of the credential's agent. A SHARED-KEY caller keeps the historical+ // config-path resolution: the shared key is the operator, whose+ // identity is the config's to name.+ const effectiveAgent =+ agent ?? (ctx.requestIdentity?.via === "token" ? ctx.requestIdentity.agent : undefined);+ // A record the caller may not read is refused as an unknown id, before+ // anything is written.+ const readable = readableAtContextReachOrUndefined(ctx);+ try {+ const res = setExpiration(ctx.vault, id, expires, {+ ...(effectiveAgent ? { agent: effectiveAgent } : {}),+ ...(readable !== undefined ? { readable } : {}),+ });+ return {+ id: res.id,+ kind: res.kind,+ path: res.path,+ expiration: res.expiration,+ previous: res.previous,+ changed: res.changed,+ };+ } catch (err) {+ // Each of the three is the caller's fault and each has a different+ // next move: fix the date, fix the id, or use a surface that takes a+ // path. They keep their own class name as the reported code, read+ // from the boundary registry's classification rather than `err.name`.+ if (+ err instanceof ExpirationValueError ||+ err instanceof ExpirationTargetNotFoundError ||+ err instanceof InvalidExpirationTargetError+ ) {+ throw new MCPError(INVALID_PARAMS, `${EXPIRE_TOOL}: ${err.message}`, {+ code: codeForError(err),+ });+ }+ if (err instanceof MCPError) throw err;+ throw new MCPError(+ INTERNAL_ERROR,+ `${EXPIRE_TOOL}: ${err instanceof Error ? err.message : String(err)}`,+ );+ }+}diff --git a/src/mcp/brain/feedback-tool.ts b/src/mcp/brain/feedback-tool.tsnew file mode 100644index 00000000..cc7335f9--- /dev/null+++ b/src/mcp/brain/feedback-tool.ts@@ -0,0 +1,676 @@+/**+ * `brain_feedback` (task 3.19): the preference- and signal-feedback+ * capture lane, with the forced-confirmation gate, the write-refusal+ * mapping and the slug derivation it answers through. Split from+ * `feedback-tools.ts`; registration happens through that module's+ * registry, which preserves the public FEEDBACK_TOOLS surface.+ */++import { resolve } from "node:path";+import { loadPermissionsDocumentFor } from "../../core/brain/permissions/document-source.ts";+import { resolveAgentName } from "../../core/config.ts";+import { resolveEffectiveScope, signalRecordExists, writeSignal } from "../../core/brain/signal.ts";+import { computePayloadHash, lookupKey, rememberKey } from "../../core/brain/idempotency-ledger.ts";+import { preferencePathOf } from "../../core/brain/paths.ts";+import { ROUTE_STAGE, timeStageSync } from "../../core/route-scope.ts";+import {+ adviseIncomingFeedback,+ adviseUnroutableCapture,+ captureRoutingHintField,+ type CaptureRoutingHint,+ type WriteConflictAdvisory,+} from "../../core/brain/write-advisory.ts";+import { loadFeedbackDefaultScopeSafe } from "../../core/brain/policy.ts";+import {+ loadPreference,+ preferencePresence,+ writePreference,+} from "../../core/brain/preference.ts";+import { sha256Hex } from "../../core/integrity/digest.ts";+import { normalizeExpirationDate } from "../../core/brain/expiration.ts";+import { validateBrainFeedbackInput } from "../../core/brain/sessions/validate-feedback.ts";+import { isoDate, isoSecond } from "../../core/brain/time.ts";+import { slugify } from "../../core/vault.ts";+import { normalizeAgentArgument } from "../../core/agent-identity.ts";+import {+ BRAIN_LOG_EVENT_KIND,+ BRAIN_PREFERENCE_STATUS,+ type BrainSignalSign,+} from "../../core/brain/types.ts";+import { appendLogEvent } from "../../core/brain/log.ts";+import {+ mirrorReportFields,+ mirrorSignal,+ resolveSharedNamespace,+} from "../../core/brain/shared-namespace.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import {+ PENDING_STAGED_DIAGNOSTIC_CODE,+ WRITE_REFUSAL_CODES,+ WriteRefusedError,+} from "../../core/brain/pending/pending-lanes.ts";+import { nextCommandField, requireNextStep } from "../../core/brain/next-step.ts";+import { resolvePermission } from "../../core/brain/permissions/resolve.ts";+import { substrateSubject } from "../../core/brain/write-disposition.ts";+import { contextVault, type ServerContext } from "../tool-contract.ts";+import { refuseAgentClaim } from "./agent-claim.ts";+import { coerceStr, coerceIsoDate } from "../coerce.ts";+import { toolPath } from "./device-path.ts";+import { readableAtContextReachOrUndefined } from "./reach-readable.ts";++export const FORCE_CONFIRMED_EXIT = requireNextStep(+ WRITE_REFUSAL_CODES.forceConfirmedRequiresAllow,+).nextCommand;++/**+ * The MCP mapping of a document-deny refusal (write-side trust, Task+ * 12): named code, the rule that decided, the principal it named, and+ * the operator exit - the write never landed, so the refusal is the+ * whole answer. Shared by the writers on this surface that let the+ * disposition layer refuse through a typed error.+ */+export function writeRefusedToMcp(tool: string, err: WriteRefusedError): MCPError {+ return new MCPError(INVALID_PARAMS, `${tool}: ${err.message}`, {+ code: err.code,+ rule: err.rule,+ agent: err.agent,+ next_command: err.nextCommand,+ });+}++/**+ * Build the slug used in the signal / preference filename. We never let+ * the agent decide the slug directly — taking `topic` as the slug stem+ * is what the design doc §9.2 prescribes (slugs are deterministic from+ * topic). The slug is run through `slugify` defensively so a slightly+ * mis-shaped topic still yields a filesystem-safe basename.+ */+export function deriveSlug(topic: string): string {+ return slugify(topic);+}++/** How a result names a record written with no vault. */+export const STORE_RECORD_PREFIX = "store:";++/**+ * The ledger namespace of the force-confirmed capture markers. A marker+ * lives outside the shared key space so a client key reused across tools+ * never collides with one.+ */+export const PREFERENCE_MARKER_NAMESPACE = "brain-feedback-preference";++/**+ * Ledger keys of the force-confirmed capture marker: the PENDING marker+ * is appended right before the confirmed preference write is attempted,+ * the DONE marker right after it succeeded. The append-only ledger cannot+ * update a receipt, so completion is a second receipt, and "unfinished"+ * is positive evidence: PENDING present, DONE absent. Both carry the same+ * capture hash, so a retry whose force flag or expiration differs from+ * the original call never resumes the original's capture.+ *+ * Both keys are derived from a fixed-length digest of the client key,+ * never from the key itself: the ledger accepts keys up to 256+ * characters, and appending a suffix to a near-limit key would push the+ * marker past that limit - the PENDING/DONE appends would fail soft, but+ * every later `lookupKey` on the retry path would throw and turn the+ * documented deduped replay of a successful capture into an error. A+ * digest keeps every valid client key usable.+ *+ * Both keys hash the TRIMMED key: the receipt the ledger keeps for the+ * client key is normalised the same way (trimmed), so a retry that+ * spells the key with different surrounding whitespace dedupes the+ * original signal and must find its PENDING/DONE markers too - hashing+ * the untrimmed key would strand the marker behind a marker no retry+ * key can ever match.+ */+const preferenceMarkerKey = (idempotencyKey: string): string =>+ `pref-capture:${sha256Hex(idempotencyKey.trim())}`;+const preferenceDoneKey = (idempotencyKey: string): string =>+ `pref-capture-done:${sha256Hex(idempotencyKey.trim())}`;++/**+ * The payload identity of the force-confirmed preference write, hashed+ * into the marker pair: WHAT is captured (topic, principle, agent,+ * scope), THAT it is force-confirmed, and HOW LONG it lives. Two calls+ * that differ in any of these are different payloads, so a forced retry+ * of an unforced capture (no marker exists) and a forced retry with a+ * different expiration (marker hash differs) both stay true no-ops.+ * Old receipts stay readable: the marker namespace is new, so receipts+ * written before it existed simply never resume.+ */+function preferenceCaptureHash(input: {+ topic: string;+ principle: string;+ agent: string;+ scope: string | undefined;+ expires: string | undefined;+}): string {+ return computePayloadHash({+ force_confirmed: true,+ topic: input.topic,+ principle: input.principle,+ agent: input.agent,+ scope: input.scope ?? undefined,+ expiration_date: input.expires ?? undefined,+ });+}++/** Append one capture-marker receipt, failing soft: the marker is a+ * repair aid, so an unreadable key or a full disk must never break the+ * capture it guards (the same policy the log appends follow). */+function appendMarkerReceipt(+ vault: string | null,+ key: string,+ captureHash: string,+ createdAt: string,+): void {+ try {+ rememberKey(vault, {+ key,+ namespace: PREFERENCE_MARKER_NAMESPACE,+ contentHash: captureHash,+ createdAt,+ });+ } catch (err) {+ process.stderr.write(+ `warning: record feedback capture marker failed: ${(err as Error).message}\n`,+ );+ }+}++export async function toolBrainFeedback(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ // `null` on a server with no vault: the writes are store records (D14).+ const vault = contextVault(ctx);+ // Single source of truth for the brain_feedback payload contract —+ // session-replay (sessions/import.ts) and the MCP live path now go+ // through the same validator so rule shape cannot drift between the+ // two surfaces.+ const validated = validateBrainFeedbackInput(args);+ if (!validated.ok) {+ throw new MCPError(INVALID_PARAMS, validated.reason);+ }+ const {+ topic,+ signal: signalRaw,+ principle,+ scope,+ raw,+ source,+ force_confirmed,+ } = validated.value;+ const forceConfirmed = force_confirmed ?? false;++ // Identity, resolved once (write-side trust, Task 7). The+ // transport-minted identity WINS over the config resolution, and under+ // a token a caller-supplied `agent` that claims somebody else is+ // refused outright; resolveAgentName stays the stdio and CLI fallback.+ const identity = ctx.requestIdentity;+ const claimedAgent = normalizeAgentArgument(validated.value.agent ?? null);+ refuseAgentClaim(identity, claimedAgent, "brain_feedback");+ const agent = claimedAgent ?? identity?.agent ?? resolveAgentName(ctx.configPath ?? undefined);+ // The subject the write-side gates answer for: the credential-minted+ // one when the transport minted it, the config-shaped one otherwise.+ const subject = identity ?? { agent, via: "config" as const };++ // The force-confirmed rule (write-side trust, Task 12). `force_confirmed`+ // skips the dream trial window - the one write whose whole point is to+ // bypass a review - so under a permissions document that bypass belongs+ // to the operator, not the caller: the caller's `write` verdict must be+ // `allow`, and anything else refuses with the named token BEFORE any+ // write. With no document this block never runs, so the document-absent+ // behavior is byte-identically the pre-Task-12 one. The verdict consult+ // is the substrate resolver directly - no disposition row - because the+ // write it guards has its own gate; this check only polices the bypass,+ // and it answers for the credential-minted subject, never for a name+ // the request argued for.+ if (forceConfirmed) {+ // The permissions document: the operator's shared setting, or the legacy+ // file on an unswitched machine (document-source.ts).+ const { document } = loadPermissionsDocumentFor(vault);+ if (document !== null) {+ const decision = resolvePermission(document, substrateSubject(subject), "write");+ if (decision.verdict !== "allow") {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_feedback refused (${WRITE_REFUSAL_CODES.forceConfirmedRequiresAllow}): ` ++ "force_confirmed skips the dream trial window, which the permissions " ++ `document reserves for allow-verdict callers. Rule ${decision.source} ` ++ `(${decision.reason}) decided ${decision.verdict} for agent ` ++ `${JSON.stringify(subject.agent)}. The operator can review the policy: ` ++ FORCE_CONFIRMED_EXIT,+ {+ code: WRITE_REFUSAL_CODES.forceConfirmedRequiresAllow,+ rule: decision.source,+ verdict: decision.verdict,+ agent: subject.agent,+ },+ );+ }+ }+ }++ // Per-row event-time (A2 / t_7526e8d3): an optional caller-supplied+ // `event_time` lets a backfilled / imported "remember" carry when it+ // actually happened instead of the wall-clock. When present and valid,+ // it drives the signal's `created_at` / filename day and the+ // bi-temporal `valid_from` / `recorded_at` slots. The audit log and any+ // force-confirmed preference stay stamped at the real write moment+ // (`now`) so the audit chronology is not rewritten. Absent →+ // byte-identical to the historical wall-clock path.+ const eventTime = coerceIsoDate(args, "event_time");+ // Optional client idempotency key (C1 / t_213f356b): forwarded to the+ // signal writer so a retried / double-delivered feedback call dedupes+ // instead of appending a second signal. Absent → historical behaviour.+ const idempotencyKey = coerceStr(args, "idempotency_key", false);+ // Creation-time expiration (unit 3c). Validated through the one+ // chokepoint BEFORE the signal write, so an unparseable date refuses+ // the whole call rather than landing a signal and then failing on the+ // preference beside it.+ const expiresRaw = coerceStr(args, "expires", false);+ let expires: string | undefined;+ if (expiresRaw !== null && expiresRaw !== undefined) {+ try {+ expires = normalizeExpirationDate(expiresRaw);+ } catch (err) {+ throw new MCPError(INVALID_PARAMS, `brain_feedback: expires: ${(err as Error).message}`);+ }+ }+ const now = new Date();+ const createdAt = isoSecond(now);+ const signalStamp = eventTime ?? now;+ const signalCreatedAt = isoSecond(signalStamp);+ const signalDate = isoDate(signalStamp);+ const slug = deriveSlug(topic);++ // Vault-configured fallback scope (`feedback.default_scope`). Applied+ // only when the call passes no explicit scope. Compute one effective+ // scope so the signal, its mirror, and any force-confirmed preference+ // all land on the same scope.+ const defaultScope = loadFeedbackDefaultScopeSafe(vault);+ const effectiveScope = resolveEffectiveScope(scope, defaultScope);+ const writeOpts = defaultScope !== undefined ? { defaultScope } : {};++ // 1. Always write the signal to inbox/. Mirrors the CLI handler so the+ // audit trail in `Brain/log/` and `inbox/processed/` stays consistent+ // across CLI and MCP entry points. `--force-confirmed` ADDITIONALLY+ // creates a confirmed pref below. The transport-minted identity+ // rides to the review gate as its subject (write-side-trust, Task+ // 7): a document that denies the token's agent refuses this write+ // before any byte exists.+ const signalInput = {+ topic,+ signal: signalRaw as BrainSignalSign,+ agent,+ principle,+ created_at: signalCreatedAt,+ date: signalDate,+ slug,+ ...(scope ? { scope } : {}),+ ...(source && source.length > 0 ? { source: [...source] } : {}),+ ...(raw ? { raw } : {}),+ // Stamp the bi-temporal slots only when an explicit event_time was+ // supplied, so a live "remember" stays byte-identical.+ ...(eventTime ? { valid_from: signalCreatedAt, recorded_at: signalCreatedAt } : {}),+ ...(idempotencyKey ? { idempotency_key: idempotencyKey } : {}),+ ...(expires !== undefined ? { expiration_date: expires } : {}),+ };+ let sigResult;+ try {+ sigResult = writeSignal(vault, signalInput, {+ ...writeOpts,+ // The review disposition always answers for THIS tool's resolved+ // identity: the credential-minted subject when the transport minted+ // one, the config-shaped subject this tool resolved (config path+ // honored, caller claim refused) otherwise. Leaving the subject off+ // would make the disposition re-resolve the agent without this+ // context's config path and answer for a stranger.+ subject,+ });+ } catch (err) {+ if (err instanceof WriteRefusedError) throw writeRefusedToMcp("brain_feedback", err);+ throw err;+ }+ // A deduped signal means this whole feedback call is a retry of one+ // already recorded — skip the log event, the shared-namespace mirror,+ // and any force-confirmed pref so the retry stays a true no-op.+ // EXCEPT a capture the ledger shows is UNFINISHED: when the original+ // call was force-confirmed, its signal landed, and its preference+ // write never completed, the call leaves a PENDING capture marker in+ // the idempotency ledger (below) and the retry that finds PENDING+ // without DONE, with the same capture payload, and with the signal+ // still present, completes the write. Everything else stays a true+ // no-op:+ // - a completed capture (DONE exists),+ // - a capture whose signal delete-by-source later forgot (the+ // signal page / store record is gone - a user's forget must not+ // be undone by a replay),+ // - a first call made WITHOUT force_confirmed (no marker exists),+ // - a retry whose force flag or expiration differs from the+ // original (the marker hash names both, so it does not match).+ // "The preference is absent" proves none of this - a preference the+ // user removed by hand reads exactly like one never written - which is+ // why the resume reads the marker pair instead.+ // The force-confirmed preference write, spelled once so the deduped+ // retry path can resume it: same payload, same stamps, same writer.+ const writeConfirmedPreference = (): { path: string; id: string } =>+ timeStageSync(ROUTE_STAGE.preferenceWrite, () =>+ writePreference(+ vault,+ {+ slug,+ topic: topic.trim(),+ principle: principle.trim(),+ created_at: createdAt,+ unconfirmed_until: createdAt,+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by: [`[[${sigResult.id}]]`],+ confirmed_at: createdAt,+ // Issue #149: an explicit zero, not an absent value. The+ // on-disk encoding of "absent" is the literal `null`, and two+ // ranking surfaces (`pre-compress-pack`, `morning-brief`) map+ // `null` to negative infinity before sorting - so a rule+ // force-confirmed a second ago would sort BELOW every rule+ // that has a number, including one measured at zero. Zero is+ // also the true Wilson lower bound on no evidence, which is+ // why the dream pass already pre-seeds it for new+ // preferences. This writer now matches it.+ confidence_value: 0,+ ...(effectiveScope !== undefined ? { scope: effectiveScope } : {}),+ // The same lifetime the signal carries: a rule confirmed from an+ // observation that expires on a date does not outlive it.+ ...(expires !== undefined ? { expiration_date: expires } : {}),+ },+ // Ownership is resolved by the writer, never echoed from `agent`:+ // that argument is caller-supplied, and a caller must not be able to+ // name whose memory this becomes. The server's config path is handed+ // over rather than a resolved name for the same reason, and the+ // transport-minted identity rides as the credential-minted subject+ // (write-side-trust, Task 7) so the gate and the stamp answer for+ // the token's agent.+ {+ ...(ctx.configPath !== null ? { configPath: ctx.configPath } : {}),+ ...(identity !== undefined ? { subject: identity } : {}),+ },+ ),+ );+ const logConfirmedPreference = (preferenceId: string): void => {+ try {+ // Offset by 1s so the force-confirmed event sorts after the feedback+ // event on the same UTC second (parseLogDay is stable on ties, but a+ // visible chronology reads cleaner).+ timeStageSync(ROUTE_STAGE.logAppend, () =>+ appendLogEvent(vault, {+ timestamp: isoSecond(new Date(now.getTime() + 1000)),+ eventType: BRAIN_LOG_EVENT_KIND.forceConfirmed,+ body: {+ preference: `[[${preferenceId}]]`,+ agent,+ },+ }),+ );+ } catch (err) {+ process.stderr.write(+ `warning: append force-confirmed log failed: ${(err as Error).message}\n`,+ );+ }+ };+ // The capture hash and marker keys, computed once: both the fresh+ // path (before the write) and the deduped retry path (to decide the+ // resume) read them.+ const captureHash = preferenceCaptureHash({+ topic: topic.trim(),+ principle: principle.trim(),+ agent,+ scope: effectiveScope,+ expires,+ });+ const markerKey =+ idempotencyKey !== null && idempotencyKey !== undefined+ ? preferenceMarkerKey(idempotencyKey)+ : undefined;+ const doneKey =+ idempotencyKey !== null && idempotencyKey !== undefined+ ? preferenceDoneKey(idempotencyKey)+ : undefined;+ if (sigResult.deduped) {+ // Positive evidence this capture is unfinished: the marker pair from+ // a force-confirmed original, with the same payload as THIS retry,+ // and a signal that still exists on disk / in the store.+ const presence = preferencePresence(vault, slug, ctx.configPath ?? undefined);+ const resumable =+ markerKey !== undefined &&+ doneKey !== undefined &&+ forceConfirmed &&+ lookupKey(vault, markerKey, PREFERENCE_MARKER_NAMESPACE)?.contentHash === captureHash &&+ lookupKey(vault, doneKey, PREFERENCE_MARKER_NAMESPACE) === null &&+ // A rule the user retired in the crash window stays retired: the+ // resume must not write a fresh confirmed rule beside it.+ presence !== "retired" &&+ signalRecordExists(vault, sigResult.path, sigResult.id, ctx.configPath ?? undefined);+ if (resumable && presence === "active") {+ // The crash landed AFTER the preference write but BEFORE the DONE+ // marker: the rule the original call wrote is already active. An+ // active rule matching this capture's own slug and payload IS the+ // completed capture, so the replay closes the ledger instead of+ // attempting the write a second time (which would refuse on the+ // existing rule). A rule that exists under this slug but does not+ // match the payload is not this capture's write, so it falls+ // through to the resume below and surfaces the conflict.+ const existing = loadPreference(vault, slug, {+ ...(ctx.configPath !== null ? { configPath: ctx.configPath } : {}),+ });+ // An active rule under this slug proves nothing on its own: a rule+ // the caller wrote earlier under the same slug and payload would be+ // adopted here without this capture ever having completed its own+ // write. Only THIS capture's write closes it - the write at+ // `writeConfirmedPreference` stamps the rule `confirmed` and names+ // the deduped signal under `evidenced_by` - so both must be present+ // before the ledger is closed on the existing rule.+ const captureMatches =+ existing !== null &&+ existing.status === BRAIN_PREFERENCE_STATUS.confirmed &&+ existing.evidenced_by.some(+ (ref) =>+ typeof ref === "string" && ref.replace(/^\[\[|\]\]$/g, "").trim() === sigResult.id,+ ) &&+ existing.topic === topic.trim() &&+ existing.principle === principle.trim() &&+ existing.scope === effectiveScope &&+ existing.expiration_date === expires;+ if (captureMatches && doneKey !== undefined) {+ appendMarkerReceipt(vault, doneKey, captureHash, createdAt);+ logConfirmedPreference(existing.id);+ const existingPath = preferencePathOf(vault, slug);+ return {+ kind: "preference",+ deduped: true,+ staged: false,+ signal_path:+ vault === null+ ? `${STORE_RECORD_PREFIX}${sigResult.id}`+ : toolPath(ctx, sigResult.path),+ signal_absolute_path:+ vault === null ? `${STORE_RECORD_PREFIX}${sigResult.id}` : resolve(sigResult.path),+ signal_id: sigResult.id,+ preference_path:+ vault === null ? `${STORE_RECORD_PREFIX}${existing.id}` : toolPath(ctx, existingPath),+ preference_absolute_path:+ vault === null ? `${STORE_RECORD_PREFIX}${existing.id}` : resolve(existingPath),+ preference_id: existing.id,+ path:+ vault === null ? `${STORE_RECORD_PREFIX}${existing.id}` : toolPath(ctx, existingPath),+ absolute_path:+ vault === null ? `${STORE_RECORD_PREFIX}${existing.id}` : resolve(existingPath),+ id: existing.id,+ agent,+ };+ }+ }+ if (resumable) {+ const resumed = writeConfirmedPreference();+ if (doneKey !== undefined) appendMarkerReceipt(vault, doneKey, captureHash, createdAt);+ logConfirmedPreference(resumed.id);+ return {+ kind: "preference",+ deduped: true,+ // The signal was deduped, so the retry staged nothing new.+ staged: false,+ signal_path:+ vault === null ? `${STORE_RECORD_PREFIX}${sigResult.id}` : toolPath(ctx, sigResult.path),+ signal_absolute_path:+ vault === null ? `${STORE_RECORD_PREFIX}${sigResult.id}` : resolve(sigResult.path),+ signal_id: sigResult.id,+ preference_path:+ vault === null ? `${STORE_RECORD_PREFIX}${resumed.id}` : toolPath(ctx, resumed.path),+ preference_absolute_path:+ vault === null ? `${STORE_RECORD_PREFIX}${resumed.id}` : resolve(resumed.path),+ preference_id: resumed.id,+ path: vault === null ? `${STORE_RECORD_PREFIX}${resumed.id}` : toolPath(ctx, resumed.path),+ absolute_path:+ vault === null ? `${STORE_RECORD_PREFIX}${resumed.id}` : resolve(resumed.path),+ id: resumed.id,+ agent,+ };+ }+ return {+ kind: "signal",+ deduped: true,+ // A dedup wrote nothing, so it staged nothing.+ staged: false,+ signal_path:+ vault === null ? `${STORE_RECORD_PREFIX}${sigResult.id}` : toolPath(ctx, sigResult.path),+ signal_absolute_path:+ vault === null ? `${STORE_RECORD_PREFIX}${sigResult.id}` : resolve(sigResult.path),+ signal_id: sigResult.id,+ path:+ vault === null ? `${STORE_RECORD_PREFIX}${sigResult.id}` : toolPath(ctx, sigResult.path),+ absolute_path:+ vault === null ? `${STORE_RECORD_PREFIX}${sigResult.id}` : resolve(sigResult.path),+ id: sigResult.id,+ agent,+ };+ }+ // t_936a1a61: fail-soft mirror into the shared namespace AFTER the+ // primary write; `mirror` is reported only when the key is configured.+ const sharedNamespace = resolveSharedNamespace(ctx.configPath);+ // The mirror copies from a vault, so there is none without one.+ const mirror =+ sharedNamespace === null || vault === null+ ? undefined+ : mirrorSignal(sharedNamespace, vault, signalInput, writeOpts);++ try {+ timeStageSync(ROUTE_STAGE.logAppend, () =>+ appendLogEvent(vault, {+ timestamp: createdAt,+ eventType: BRAIN_LOG_EVENT_KIND.feedback,+ body: {+ signal: `[[${sigResult.id}]]`,+ topic: topic.trim(),+ sign: signalRaw,+ agent,+ },+ }),+ );+ } catch (err) {+ process.stderr.write(`warning: append feedback log failed: ${(err as Error).message}\n`);+ }++ // Write-time conflict advisory (A4): compare the incoming principle+ // against confirmed same-scope preferences and surface a non-blocking+ // advisory when it closely resembles an existing rule. Computed BEFORE+ // any force-confirmed write so it never matches the pref this very call+ // is about to create. The write has already landed; this never blocks it.+ // Both advisories answer at the caller's reach: a preference or signal+ // the caller may not read is never scored, named or counted.+ const readable = readableAtContextReachOrUndefined(ctx);+ const advisory: WriteConflictAdvisory | null = adviseIncomingFeedback(vault, {+ principle,+ ...(readable !== undefined ? { readable } : {}),+ ...(effectiveScope !== undefined ? { scope: effectiveScope } : {}),+ agent,+ now,+ });++ // Unroutable-capture routing hint (unit 4): the signal above resolved+ // no scope, so no scoped recall reaches it. Non-blocking like the+ // advisory, and absent entirely when this vault uses no scopes yet.+ const routingHint: CaptureRoutingHint | null = adviseUnroutableCapture(vault, {+ ...(readable !== undefined ? { readable } : {}),+ ...(effectiveScope !== undefined ? { scope: effectiveScope } : {}),+ agent,+ now,+ });++ let prefResult: { path: string; id: string } | null = null;+ if (forceConfirmed) {+ // Leave the PENDING capture marker BEFORE the write: the signal and+ // its own receipt have already landed, so a crash or refusal inside+ // `writePreference` leaves PENDING without DONE - the positive mark+ // a deduped retry reads to finish this capture (see the deduped+ // branch above). Fail-soft: without a client key there is nothing to+ // mark, and a marker that cannot be stored only costs the repair.+ if (markerKey !== undefined) appendMarkerReceipt(vault, markerKey, captureHash, createdAt);+ // Escape hatch: skip the dream pass and create the confirmed rule now.+ // `confirmed_at` is now; `unconfirmed_until` is also now so the trial+ // window collapses on inspection. The just-written signal is recorded+ // as the rule's origin under `evidenced_by`. A throw here leaves+ // PENDING without DONE in the ledger - exactly the resume mark.+ prefResult = writeConfirmedPreference();+ if (doneKey !== undefined) appendMarkerReceipt(vault, doneKey, captureHash, createdAt);+ logConfirmedPreference(prefResult.id);+ }++ // With no vault the records have no file: both fields name the record+ // (`store:<id>`), as the CLI does.+ const named = (path: string, id: string): string =>+ vault === null ? `${STORE_RECORD_PREFIX}${id}` : toolPath(ctx, path);+ const absolute = (path: string, id: string): string =>+ vault === null ? `${STORE_RECORD_PREFIX}${id}` : resolve(path);+ return {+ kind: prefResult ? "preference" : "signal",+ ...mirrorReportFields(mirror),+ ...(advisory !== null ? { advisory } : {}),+ // Same key and same resolution as the CLI's `--json` renderer, from+ // the one composer: an agent that learns the exit on one surface+ // reads it on the other.+ ...captureRoutingHintField(routingHint),+ // Write-side trust (Task 6): the gate resolved inside writeSignal, so+ // the receipt says which directory the bytes actually landed in. An+ // agent that reads `staged: true` knows the signal is awaiting review+ // under `Brain/pending/`, not recalled from `Brain/inbox/`. The+ // pending id and the queue command (Task 9) give that agent the+ // handle and the exit, since applying is an operator's move.+ staged: sigResult.staged,+ ...(sigResult.staged+ ? {+ pending_id: sigResult.id,+ ...nextCommandField(PENDING_STAGED_DIAGNOSTIC_CODE),+ }+ : {}),+ signal_path: named(sigResult.path, sigResult.id),+ signal_absolute_path: absolute(sigResult.path, sigResult.id),+ signal_id: sigResult.id,+ ...(prefResult+ ? {+ preference_path: named(prefResult.path, prefResult.id),+ preference_absolute_path: absolute(prefResult.path, prefResult.id),+ preference_id: prefResult.id,+ // Back-compat: top-level `path`/`id` previously pointed at the+ // pref on the force-confirmed branch. Keep them aligned for+ // callers that look at the bare fields.+ path: named(prefResult.path, prefResult.id),+ absolute_path: absolute(prefResult.path, prefResult.id),+ id: prefResult.id,+ }+ : {+ path: named(sigResult.path, sigResult.id),+ absolute_path: absolute(sigResult.path, sigResult.id),+ id: sigResult.id,+ }),+ agent,+ };+}diff --git a/src/mcp/brain/feedback-tools.ts b/src/mcp/brain/feedback-tools.tsindex 1167da4b..f2f3ca02 100644--- a/src/mcp/brain/feedback-tools.ts+++ b/src/mcp/brain/feedback-tools.ts@@ -6,99 +6,15 @@* BRAIN_TOOLS surface.*/-import { resolve } from "node:path";-import { loadPermissionsDocumentFor } from "../../core/brain/permissions/document-source.ts";-import { resolveAgentName, resolveNearDuplicateRetireSiblingsEnabled } from "../../core/config.ts";-import {- appendApplyEvidence,- BrainPreferenceNotFoundError,- type AppendApplyEvidenceInput,-} from "../../core/brain/apply-evidence.ts";-import { dream, type DreamGateOverrides } from "../../core/brain/dream.ts";-import type { ProgressSink } from "../../core/brain/progress.ts";-import {- DREAM_GATE_NAMES,- DreamGateOverrideError,- validateDreamGateOverrides,-} from "../../core/brain/dream-gates.ts";-import {- DREAM_STEP_RUNNABLE,- DreamStepNotRunnableError,- runDreamStep,-} from "../../core/brain/dream-step.ts";-import {- applyDreamBundle,- discardDreamBundle,- DreamRetriageError,- listDreamBundles,- retriageDreamBundle,- stageDream,- validateDreamBundle,- type DreamRetriageEntry,-} from "../../core/brain/dream-stage.ts";-import { BRAIN_ROLES } from "../../core/brain/trust/role.ts";-import { resolveEffectiveScope, writeSignal } from "../../core/brain/signal.ts";-import { ROUTE_STAGE, timeStageSync } from "../../core/route-scope.ts";-import {- adviseIncomingFeedback,- adviseUnroutableCapture,- captureRoutingHintField,- type CaptureRoutingHint,- type WriteConflictAdvisory,-} from "../../core/brain/write-advisory.ts";-import { loadFeedbackDefaultScopeSafe } from "../../core/brain/policy.ts";-import { writePreference } from "../../core/brain/preference.ts";-import { normalizeExpirationDate } from "../../core/brain/expiration.ts";-import {- EXPIRATION_CLEAR,- ExpirationTargetNotFoundError,- ExpirationValueError,- InvalidExpirationTargetError,- setExpiration,-} from "../../core/brain/expiration-set.ts";-import { gatedOwnerScopeView, type OwnerScopeView } from "../../core/brain/owner-scope-view.ts";-import { brainArtifactSlug } from "../../core/brain/wikilink.ts";-import { validateBrainFeedbackInput } from "../../core/brain/sessions/validate-feedback.ts";-import { isoDate, isoSecond } from "../../core/brain/time.ts";-import { slugify } from "../../core/vault.ts";-import { normalizeAgentArgument } from "../../core/agent-identity.ts";-import {- BRAIN_LOG_EVENT_KIND,- BRAIN_PREFERENCE_STATUS,- BRAIN_APPLY_RESULT,- type BrainApplyResult,- type BrainSignalSign,-} from "../../core/brain/types.ts";-import { appendLogEvent } from "../../core/brain/log.ts";-import { appendBrainNote } from "../../core/brain/note.ts";-import {- mirrorReportFields,- mirrorSignal,- resolveSharedNamespace,-} from "../../core/brain/shared-namespace.ts";-import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";-import {- PENDING_STAGED_DIAGNOSTIC_CODE,- WRITE_REFUSAL_CODES,- WriteRefusedError,-} from "../../core/brain/pending/pending-lanes.ts";-import { nextCommandField, requireNextStep } from "../../core/brain/next-step.ts";-import { resolvePermission } from "../../core/brain/permissions/resolve.ts";-import { substrateSubject } from "../../core/brain/write-disposition.ts";+import { DREAM_GATE_NAMES } from "../../core/brain/dream-gates.ts";+import { DREAM_STEP_RUNNABLE } from "../../core/brain/dream-step.ts";+import { EXPIRATION_CLEAR } from "../../core/brain/expiration-set.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";-import { contextVault, type ServerContext, type ToolDefinition } from "../tool-contract.ts";-import { refuseAgentClaim } from "./agent-claim.ts";-import { codeForError } from "../tool-error-codes.ts";-import {- emitObservedUse,- isObservedUseVerdict,- type ObservedUseEntry,-} from "../../core/brain/observed-use.ts";-import { coerceStr, coerceBool, coerceIsoDate, unknownOperationError } from "../coerce.ts";-import { enforceCountGuard, readCountGuardArgs, toolSafeguard } from "./shared.ts";-import { toolPath } from "./device-path.ts";-import { OPERATION } from "../../core/brain/safeguard.ts";-import { readableAtContextReach, readableAtContextReachOrUndefined } from "./reach-readable.ts";+import { type ToolDefinition } from "../tool-contract.ts";+import { toolBrainFeedback } from "./feedback-tool.ts";+import { toolBrainDream } from "./dream-tools.ts";+import { toolBrainApplyEvidence, toolBrainNote, toolBrainObservedUse } from "./evidence-tools.ts";+import { EXPIRE_TOOL, toolBrainExpire } from "./expire-tools.ts";/*** The registered exit the force-confirmed refusal names (write-side@@ -106,1064 +22,6 @@ import { readableAtContextReach, readableAtContextReachOrUndefined } from "./rea* precedent: an unregistered code is registry drift and fails at import* rather than inside the refusal it was meant to explain.*/-const FORCE_CONFIRMED_EXIT = requireNextStep(- WRITE_REFUSAL_CODES.forceConfirmedRequiresAllow,-).nextCommand;--/**- * The MCP mapping of a document-deny refusal (write-side trust, Task- * 12): named code, the rule that decided, the principal it named, and- * the operator exit - the write never landed, so the refusal is the- * whole answer. Shared by the writers on this surface that let the- * disposition layer refuse through a typed error.- */-function writeRefusedToMcp(tool: string, err: WriteRefusedError): MCPError {- return new MCPError(INVALID_PARAMS, `${tool}: ${err.message}`, {- code: err.code,- rule: err.rule,- agent: err.agent,- next_command: err.nextCommand,- });-}--/**- * Build the slug used in the signal / preference filename. We never let- * the agent decide the slug directly — taking `topic` as the slug stem- * is what the design doc §9.2 prescribes (slugs are deterministic from- * topic). The slug is run through `slugify` defensively so a slightly- * mis-shaped topic still yields a filesystem-safe basename.- */-function deriveSlug(topic: string): string {- return slugify(topic);-}--/** How a result names a record written with no vault. */-const STORE_RECORD_PREFIX = "store:";--async function toolBrainFeedback(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- // `null` on a server with no vault: the writes are store records (D14).- const vault = contextVault(ctx);- // Single source of truth for the brain_feedback payload contract —- // session-replay (sessions/import.ts) and the MCP live path now go- // through the same validator so rule shape cannot drift between the- // two surfaces.- const validated = validateBrainFeedbackInput(args);- if (!validated.ok) {- throw new MCPError(INVALID_PARAMS, validated.reason);- }- const {- topic,- signal: signalRaw,- principle,- scope,- raw,- source,- force_confirmed,- } = validated.value;- const forceConfirmed = force_confirmed ?? false;-- // Identity, resolved once (write-side trust, Task 7). The- // transport-minted identity WINS over the config resolution, and under- // a token a caller-supplied `agent` that claims somebody else is- // refused outright; resolveAgentName stays the stdio and CLI fallback.- const identity = ctx.requestIdentity;- const claimedAgent = normalizeAgentArgument(validated.value.agent ?? null);- refuseAgentClaim(identity, claimedAgent, "brain_feedback");- const agent = claimedAgent ?? identity?.agent ?? resolveAgentName(ctx.configPath ?? undefined);- // The subject the write-side gates answer for: the credential-minted- // one when the transport minted it, the config-shaped one otherwise.- const subject = identity ?? { agent, via: "config" as const };-- // The force-confirmed rule (write-side trust, Task 12). `force_confirmed`- // skips the dream trial window - the one write whose whole point is to- // bypass a review - so under a permissions document that bypass belongs- // to the operator, not the caller: the caller's `write` verdict must be- // `allow`, and anything else refuses with the named token BEFORE any- // write. With no document this block never runs, so the document-absent- // behavior is byte-identically the pre-Task-12 one. The verdict consult- // is the substrate resolver directly - no disposition row - because the- // write it guards has its own gate; this check only polices the bypass,- // and it answers for the credential-minted subject, never for a name- // the request argued for.- if (forceConfirmed) {- // The permissions document: the operator's shared setting, or the legacy- // file on an unswitched machine (document-source.ts).- const { document } = loadPermissionsDocumentFor(vault);- if (document !== null) {- const decision = resolvePermission(document, substrateSubject(subject), "write");- if (decision.verdict !== "allow") {- throw new MCPError(- INVALID_PARAMS,- `brain_feedback refused (${WRITE_REFUSAL_CODES.forceConfirmedRequiresAllow}): ` +- "force_confirmed skips the dream trial window, which the permissions " +- `document reserves for allow-verdict callers. Rule ${decision.source} ` +- `(${decision.reason}) decided ${decision.verdict} for agent ` +- `${JSON.stringify(subject.agent)}. The operator can review the policy: ` +- FORCE_CONFIRMED_EXIT,- {- code: WRITE_REFUSAL_CODES.forceConfirmedRequiresAllow,- rule: decision.source,- verdict: decision.verdict,- agent: subject.agent,- },- );- }- }- }-- // Per-row event-time (A2 / t_7526e8d3): an optional caller-supplied- // `event_time` lets a backfilled / imported "remember" carry when it- // actually happened instead of the wall-clock. When present and valid,- // it drives the signal's `created_at` / filename day and the- // bi-temporal `valid_from` / `recorded_at` slots. The audit log and any- // force-confirmed preference stay stamped at the real write moment- // (`now`) so the audit chronology is not rewritten. Absent →- // byte-identical to the historical wall-clock path.- const eventTime = coerceIsoDate(args, "event_time");- // Optional client idempotency key (C1 / t_213f356b): forwarded to the- // signal writer so a retried / double-delivered feedback call dedupes- // instead of appending a second signal. Absent → historical behaviour.- const idempotencyKey = coerceStr(args, "idempotency_key", false);- // Creation-time expiration (unit 3c). Validated through the one- // chokepoint BEFORE the signal write, so an unparseable date refuses- // the whole call rather than landing a signal and then failing on the- // preference beside it.- const expiresRaw = coerceStr(args, "expires", false);- let expires: string | undefined;- if (expiresRaw !== null && expiresRaw !== undefined) {- try {- expires = normalizeExpirationDate(expiresRaw);- } catch (err) {- throw new MCPError(INVALID_PARAMS, `brain_feedback: expires: ${(err as Error).message}`);- }- }- const now = new Date();- const createdAt = isoSecond(now);- const signalStamp = eventTime ?? now;- const signalCreatedAt = isoSecond(signalStamp);- const signalDate = isoDate(signalStamp);- const slug = deriveSlug(topic);-- // Vault-configured fallback scope (`feedback.default_scope`). Applied- // only when the call passes no explicit scope. Compute one effective- // scope so the signal, its mirror, and any force-confirmed preference- // all land on the same scope.- const defaultScope = loadFeedbackDefaultScopeSafe(vault);- const effectiveScope = resolveEffectiveScope(scope, defaultScope);- const writeOpts = defaultScope !== undefined ? { defaultScope } : {};-- // 1. Always write the signal to inbox/. Mirrors the CLI handler so the- // audit trail in `Brain/log/` and `inbox/processed/` stays consistent- // across CLI and MCP entry points. `--force-confirmed` ADDITIONALLY- // creates a confirmed pref below. The transport-minted identity- // rides to the review gate as its subject (write-side-trust, Task- // 7): a document that denies the token's agent refuses this write- // before any byte exists.- const signalInput = {- topic,- signal: signalRaw as BrainSignalSign,- agent,- principle,- created_at: signalCreatedAt,- date: signalDate,- slug,- ...(scope ? { scope } : {}),- ...(source && source.length > 0 ? { source: [...source] } : {}),- ...(raw ? { raw } : {}),- // Stamp the bi-temporal slots only when an explicit event_time was- // supplied, so a live "remember" stays byte-identical.- ...(eventTime ? { valid_from: signalCreatedAt, recorded_at: signalCreatedAt } : {}),- ...(idempotencyKey ? { idempotency_key: idempotencyKey } : {}),- ...(expires !== undefined ? { expiration_date: expires } : {}),- };- let sigResult;- try {- sigResult = writeSignal(vault, signalInput, {- ...writeOpts,- // The review disposition always answers for THIS tool's resolved- // identity: the credential-minted subject when the transport minted- // one, the config-shaped subject this tool resolved (config path- // honored, caller claim refused) otherwise. Leaving the subject off- // would make the disposition re-resolve the agent without this- // context's config path and answer for a stranger.- subject,- });- } catch (err) {- if (err instanceof WriteRefusedError) throw writeRefusedToMcp("brain_feedback", err);- throw err;- }- // A deduped signal means this whole feedback call is a retry of one- // already recorded — skip the log event, the shared-namespace mirror,- // and any force-confirmed pref so the retry stays a true no-op.- if (sigResult.deduped) {- return {- kind: "signal",- deduped: true,- // A dedup wrote nothing, so it staged nothing.- staged: false,- signal_path:- vault === null ? `${STORE_RECORD_PREFIX}${sigResult.id}` : toolPath(ctx, sigResult.path),- signal_absolute_path:- vault === null ? `${STORE_RECORD_PREFIX}${sigResult.id}` : resolve(sigResult.path),- signal_id: sigResult.id,- path:- vault === null ? `${STORE_RECORD_PREFIX}${sigResult.id}` : toolPath(ctx, sigResult.path),- absolute_path:- vault === null ? `${STORE_RECORD_PREFIX}${sigResult.id}` : resolve(sigResult.path),- id: sigResult.id,- agent,- };- }- // t_936a1a61: fail-soft mirror into the shared namespace AFTER the- // primary write; `mirror` is reported only when the key is configured.- const sharedNamespace = resolveSharedNamespace(ctx.configPath);- // The mirror copies from a vault, so there is none without one.- const mirror =- sharedNamespace === null || vault === null- ? undefined- : mirrorSignal(sharedNamespace, vault, signalInput, writeOpts);-- try {- timeStageSync(ROUTE_STAGE.logAppend, () =>- appendLogEvent(vault, {- timestamp: createdAt,- eventType: BRAIN_LOG_EVENT_KIND.feedback,- body: {- signal: `[[${sigResult.id}]]`,- topic: topic.trim(),- sign: signalRaw,- agent,- },- }),- );- } catch (err) {- process.stderr.write(`warning: append feedback log failed: ${(err as Error).message}\n`);- }-- // Write-time conflict advisory (A4): compare the incoming principle- // against confirmed same-scope preferences and surface a non-blocking- // advisory when it closely resembles an existing rule. Computed BEFORE- // any force-confirmed write so it never matches the pref this very call- // is about to create. The write has already landed; this never blocks it.- // Both advisories answer at the caller's reach: a preference or signal- // the caller may not read is never scored, named or counted.- const readable = readableAtContextReachOrUndefined(ctx);- const advisory: WriteConflictAdvisory | null = adviseIncomingFeedback(vault, {- principle,- ...(readable !== undefined ? { readable } : {}),- ...(effectiveScope !== undefined ? { scope: effectiveScope } : {}),- agent,- now,- });-- // Unroutable-capture routing hint (unit 4): the signal above resolved- // no scope, so no scoped recall reaches it. Non-blocking like the- // advisory, and absent entirely when this vault uses no scopes yet.- const routingHint: CaptureRoutingHint | null = adviseUnroutableCapture(vault, {- ...(readable !== undefined ? { readable } : {}),- ...(effectiveScope !== undefined ? { scope: effectiveScope } : {}),- agent,- now,- });-- let prefResult: { path: string; id: string } | null = null;- if (forceConfirmed) {- // Escape hatch: skip the dream pass and create the confirmed rule now.- // `confirmed_at` is now; `unconfirmed_until` is also now so the trial- // window collapses on inspection. The just-written signal is recorded- // as the rule's origin under `evidenced_by`.- prefResult = timeStageSync(ROUTE_STAGE.preferenceWrite, () =>- writePreference(- vault,- {- slug,- topic: topic.trim(),- principle: principle.trim(),- created_at: createdAt,- unconfirmed_until: createdAt,- status: BRAIN_PREFERENCE_STATUS.confirmed,- evidenced_by: [`[[${sigResult.id}]]`],- confirmed_at: createdAt,- // Issue #149: an explicit zero, not an absent value. The- // on-disk encoding of "absent" is the literal `null`, and two- // ranking surfaces (`pre-compress-pack`, `morning-brief`) map- // `null` to negative infinity before sorting - so a rule- // force-confirmed a second ago would sort BELOW every rule- // that has a number, including one measured at zero. Zero is- // also the true Wilson lower bound on no evidence, which is- // why the dream pass already pre-seeds it for new- // preferences. This writer now matches it.- confidence_value: 0,- ...(effectiveScope !== undefined ? { scope: effectiveScope } : {}),- // The same lifetime the signal carries: a rule confirmed from an- // observation that expires on a date does not outlive it.- ...(expires !== undefined ? { expiration_date: expires } : {}),- },- // Ownership is resolved by the writer, never echoed from `agent`:- // that argument is caller-supplied, and a caller must not be able to- // name whose memory this becomes. The server's config path is handed- // over rather than a resolved name for the same reason, and the- // transport-minted identity rides as the credential-minted subject- // (write-side-trust, Task 7) so the gate and the stamp answer for- // the token's agent.- {- ...(ctx.configPath !== null ? { configPath: ctx.configPath } : {}),- ...(identity !== undefined ? { subject: identity } : {}),- },- ),- );- try {- // Offset by 1s so the force-confirmed event sorts after the feedback- // event on the same UTC second (parseLogDay is stable on ties, but a- // visible chronology reads cleaner).- const preferenceId = prefResult.id;- timeStageSync(ROUTE_STAGE.logAppend, () =>- appendLogEvent(vault, {- timestamp: isoSecond(new Date(now.getTime() + 1000)),- eventType: BRAIN_LOG_EVENT_KIND.forceConfirmed,- body: {- preference: `[[${preferenceId}]]`,- agent,- },- }),- );- } catch (err) {- process.stderr.write(- `warning: append force-confirmed log failed: ${(err as Error).message}\n`,- );- }- }-- // With no vault the records have no file: both fields name the record- // (`store:<id>`), as the CLI does.- const named = (path: string, id: string): string =>- vault === null ? `${STORE_RECORD_PREFIX}${id}` : toolPath(ctx, path);- const absolute = (path: string, id: string): string =>- vault === null ? `${STORE_RECORD_PREFIX}${id}` : resolve(path);- return {- kind: prefResult ? "preference" : "signal",- ...mirrorReportFields(mirror),- ...(advisory !== null ? { advisory } : {}),- // Same key and same resolution as the CLI's `--json` renderer, from- // the one composer: an agent that learns the exit on one surface- // reads it on the other.- ...captureRoutingHintField(routingHint),- // Write-side trust (Task 6): the gate resolved inside writeSignal, so- // the receipt says which directory the bytes actually landed in. An- // agent that reads `staged: true` knows the signal is awaiting review- // under `Brain/pending/`, not recalled from `Brain/inbox/`. The- // pending id and the queue command (Task 9) give that agent the- // handle and the exit, since applying is an operator's move.- staged: sigResult.staged,- ...(sigResult.staged- ? {- pending_id: sigResult.id,- ...nextCommandField(PENDING_STAGED_DIAGNOSTIC_CODE),- }- : {}),- signal_path: named(sigResult.path, sigResult.id),- signal_absolute_path: absolute(sigResult.path, sigResult.id),- signal_id: sigResult.id,- ...(prefResult- ? {- preference_path: named(prefResult.path, prefResult.id),- preference_absolute_path: absolute(prefResult.path, prefResult.id),- preference_id: prefResult.id,- // Back-compat: top-level `path`/`id` previously pointed at the- // pref on the force-confirmed branch. Keep them aligned for- // callers that look at the bare fields.- path: named(prefResult.path, prefResult.id),- absolute_path: absolute(prefResult.path, prefResult.id),- id: prefResult.id,- }- : {- path: named(sigResult.path, sigResult.id),- absolute_path: absolute(sigResult.path, sigResult.id),- id: sigResult.id,- }),- agent,- };-}--// ----- brain_dream -----------------------------------------------------------/** The set of preference ids a dream summary would create/confirm/retire/move. */-function dreamChangeList(summary: {- readonly new_unconfirmed: ReadonlyArray<string>;- readonly confirmed: ReadonlyArray<string>;- readonly retired: ReadonlyArray<{ readonly id: string }>;- readonly moved_to_processed: ReadonlyArray<string>;-}): string[] {- return [- ...summary.new_unconfirmed,- ...summary.confirmed,- ...summary.retired.map((r) => r.id),- ...summary.moved_to_processed,- ];-}--/**- * Read the optional `gates` argument (no-dead-ends, Unit E - operator- * surface). JSON-RPC carries real objects and booleans, so the MCP form- * is the override record itself rather than the CLI's `name=value`- * strings; both go through the same validator in `dream-gates.ts`, so- * the accepted gate names cannot diverge between the two surfaces.- */-function readDreamGates(args: Record<string, unknown>): DreamGateOverrides | undefined {- const raw = args["gates"];- if (raw === undefined || raw === null) return undefined;- if (typeof raw !== "object" || Array.isArray(raw)) {- throw new MCPError(- INVALID_PARAMS,- `brain_dream: gates must be an object of <gate>: <boolean>; known gates: ${DREAM_GATE_NAMES.join(", ")}`,- );- }- try {- return validateDreamGateOverrides(raw as Record<string, unknown>);- } catch (exc) {- if (exc instanceof DreamGateOverrideError) {- throw new MCPError(INVALID_PARAMS, `brain_dream: ${exc.message}`);- }- throw exc;- }-}--/**- * The rows of a dream plan or run summary the caller may see- * (a-label-is-not-a-boundary, U3).- *- * Every list here names a preference or a signal by id, and the pass- * that produced them is vault-wide by construction: consolidation reads- * every topic, and clustering only half a vault would produce different- * preferences for every caller. So the PASS stays unscoped and the- * REPORT is filtered - a caller is told what it did to the artifacts- * that caller may see, and nothing about the rest.- *- * `contradictions`, `quarantined` and `intent_reviews` are absent from- * the fold on purpose: their subject is a TOPIC over inbox signals, and- * a signal carries no `owner:` anywhere in this product, so there is no- * ownership claim on disk to read.- */-function scopedDreamRows<R extends string>(- view: OwnerScopeView,- plan: {- readonly new_unconfirmed: ReadonlyArray<string>;- readonly confirmed: ReadonlyArray<string>;- readonly retired: ReadonlyArray<{ readonly id: string; readonly reason: R }>;- readonly moved_to_processed: ReadonlyArray<string>;- readonly suppressed: ReadonlyArray<string>;- },-): {- new_unconfirmed: ReadonlyArray<string>;- confirmed: ReadonlyArray<string>;- retired: ReadonlyArray<{ id: string; reason: R }>;- moved_to_processed: ReadonlyArray<string>;- suppressed: ReadonlyArray<string>;-} {- const ids = (list: ReadonlyArray<string>): ReadonlyArray<string> => view.keep(list, (id) => [id]);- return {- new_unconfirmed: ids(plan.new_unconfirmed),- confirmed: ids(plan.confirmed),- // A retire names the preference by BOTH spellings across the move:- // `ret-<slug>` after the pass, `pref-<slug>` before it.- retired: view- .keep(plan.retired, (r) => [r.id, `pref-${brainArtifactSlug(r.id)}`])- .map((r) => ({ id: r.id, reason: r.reason })),- moved_to_processed: ids(plan.moved_to_processed),- suppressed: ids(plan.suppressed),- };-}--/** The one answer a caller below local reach gets for anything but a dry run. */-const DREAM_LOCAL_REACH_ONLY =- "brain_dream: below local reach only action=run with dry_run is served; a real pass, a step and the staged lifecycle run at local reach only";--async function toolBrainDream(- ctx: ServerContext,- args: Record<string, unknown>,- onProgress?: ProgressSink,-): Promise<Record<string, unknown>> {- // `null` on a server with no vault: the inline pass runs over the store- // alone (D14); a step and the staged lifecycle read `ctx.vault`, which- // refuses with `vault_required` there.- const vault = contextVault(ctx);- const action = args["action"] ?? "run";- if (- action !== "run" &&- action !== "stage" &&- action !== "validate" &&- action !== "apply" &&- action !== "retriage" &&- action !== "discard" &&- action !== "list"- ) {- throw unknownOperationError(- "brain_dream: action must be run|stage|validate|apply|retriage|discard|list",- );- }- const dryRun = coerceBool(args, "dry_run");- const nowDate = coerceIsoDate(args, "now");- const agentArg = coerceStr(args, "agent", false);- const agent = normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);- const gates = readDreamGates(args);- const stepArg = coerceStr(args, "step", false);- // One view for the whole call: every branch below reports preference- // and signal ids, and the staged lifecycle reports them twice.- const dreamView = gatedOwnerScopeView(vault, ctx.agentName);- // The rollup step's link candidates leave out a page the caller may not- // read at its reach, exactly as an absent page.- const readable = readableAtContextReach(ctx);- // Below local reach only a dry run is served, planned over the records- // the caller may read as if the others were absent. A real pass, a- // single step and the staged lifecycle move, rewrite or report records- // the caller may not read, so they are refused with one fixed answer- // before anything is read or written, whatever the vault holds.- const previewReadable = readableAtContextReachOrUndefined(ctx);- if (previewReadable !== undefined && (action !== "run" || !dryRun || stepArg)) {- throw new MCPError(INVALID_PARAMS, DREAM_LOCAL_REACH_ONLY);- }- const previewScope = previewReadable !== undefined ? { previewReadable } : {};-- // Single-step requests (no-dead-ends, Unit E - operator surface).- // Deliberately checked before any environment work: a step the pass- // cannot honour is refused by name, carrying the specific reason and- // the runnable set, and nothing is read or written on that path.- if (stepArg) {- if (action !== "run") {- throw new MCPError(- INVALID_PARAMS,- `brain_dream: step applies to action=run; action=${action} drives the staged lifecycle, which has no single step`,- );- }- const conflicting = dryRun- ? "dry_run"- : gates !== undefined- ? "gates"- : "expect" in args || "strict" in args- ? "expect/strict"- : null;- if (conflicting !== null) {- throw new MCPError(- INVALID_PARAMS,- `brain_dream: step cannot be combined with ${conflicting} - a single step has no preview path, reads no gate, and produces none of the preference counters the guard asserts over`,- );- }- try {- // Bounded and observed on the same terms as every sibling branch.- // This one had neither: it was the row `docs/mcp.md` marked- // **none**, and `dream()` being synchronous is exactly why that- // mattered - an unbounded step holds the server's event loop for- // its whole duration and the client cannot even time out and- // reissue. The budget is `dream`'s, because a step IS part of a- // dream pass; the sink is the caller's, dropped here until now.- return {- ...runDreamStep(ctx.vault, stepArg, {- safeguard: toolSafeguard(ctx, OPERATION.dream),- ...(onProgress ? { onProgress } : {}),- }),- };- } catch (exc) {- if (exc instanceof DreamStepNotRunnableError) {- throw new MCPError(INVALID_PARAMS, exc.message);- }- throw exc;- }- }-- if (action !== "run") {- if (gates !== undefined) {- throw new MCPError(- INVALID_PARAMS,- `brain_dream: gates apply to action=run; action=${action} drives the staged lifecycle, whose bundle records the gates its own run resolved`,- );- }- // Staged lifecycle (t_ae8a8ec0): stage -> validate -> apply over a- // persisted bundle; dream() stays the only promotion engine.- const runIdArg = coerceStr(args, "run_id", false);- if (action !== "list" && action !== "stage" && !runIdArg) {- throw new MCPError(INVALID_PARAMS, `brain_dream action=${action}: run_id is required`);- }- const now = nowDate ?? new Date();- // The staged lifecycle runs the same consolidation pass `action=run`- // does - `stage` previews it, `apply` promotes from it - so it is- // bounded and reported on the same terms. Without the sink a client- // that sent a progressToken for `action: "stage"` would be told- // nothing and see nothing for the whole pass.- const stageOpts = {- now,- safeguard: toolSafeguard(ctx, OPERATION.dream),- readable,- ...(agent ? { agentName: agent } : {}),- ...(onProgress ? { onProgress } : {}),- };- switch (action) {- case "stage": {- const bundle = stageDream(ctx.vault, stageOpts);- return {- action,- run_id: bundle.runId,- plan: { ...bundle.plan, ...scopedDreamRows(dreamView, bundle.plan) },- sources: bundle.sources.length,- dir: `Brain/dream/staged/${bundle.runId}`,- };- }- case "validate": {- const verdict = validateDreamBundle(ctx.vault, runIdArg!, stageOpts);- return { action, run_id: runIdArg, valid: verdict.valid, drift: [...verdict.drift] };- }- case "apply": {- const outcome = applyDreamBundle(ctx.vault, runIdArg!, stageOpts);- return {- action,- run_id: runIdArg,- applied: outcome.applied,- drift: [...outcome.validation.drift],- ...(outcome.summary !== undefined- ? { changed: outcome.summary.changed, ...scopedDreamRows(dreamView, outcome.summary) }- : {}),- };- }- case "retriage": {- // Read-only: it re-runs the salience gate against the current- // threshold and reports what would move. The bundle is not- // rewritten, so a caller that likes the new partition re-stages.- let outcome;- try {- outcome = retriageDreamBundle(ctx.vault, runIdArg!, stageOpts);- } catch (exc) {- if (exc instanceof DreamRetriageError) {- throw new MCPError(INVALID_PARAMS, `brain_dream: ${exc.message}`);- }- throw exc;- }- const scopedDelta = (- entries: ReadonlyArray<DreamRetriageEntry>,- ): Array<Record<string, unknown>> =>- dreamView- .keep(entries, (entry) => [entry.pref_id, entry.path])- .map((entry) => ({- pref_id: entry.pref_id,- path: entry.path,- score: entry.score,- staged_score: entry.staged_score,- }));- return {- action,- run_id: runIdArg,- staged_threshold: outcome.stagedThreshold,- current_threshold: outcome.currentThreshold,- changed: outcome.changed,- considered: outcome.considered,- admitted: outcome.admitted,- // Counts before the owner filter, names after it: a scoped- // caller is still told HOW MANY facts moved, and only the- // identities it may not see are withheld.- newly_admitted_count: outcome.newlyAdmitted.length,- newly_excluded_count: outcome.newlyExcluded.length,- newly_admitted: scopedDelta(outcome.newlyAdmitted),- newly_excluded: scopedDelta(outcome.newlyExcluded),- notes: [...outcome.notes],- };- }- case "discard": {- return { action, run_id: runIdArg, removed: discardDreamBundle(ctx.vault, runIdArg!) };- }- default: {- return {- action,- bundles: listDreamBundles(ctx.vault).map((b) => ({- run_id: b.runId,- status: b.status,- staged_at: b.stagedAt,- proposals: b.proposals,- sources: b.sources,- })),- };- }- }- }-- const { expect, strict } = readCountGuardArgs(args);- // One deadline for the whole tool call, not one per pass. `dream()` is- // synchronous, so an unbounded call blocks the server's event loop for- // its entire duration and the client cannot even time out and reissue;- // what has to be bounded is therefore the call, and a guarded run is- // two passes over the same tree. Sharing the guard means a slow preview- // spends the run's budget - which is the honest reading of a budget the- // operator set for this operation.- const safeguard = toolSafeguard(ctx, OPERATION.dream);- // The retire-siblings key honours the server's own config file, as- // `brain_review_candidates` does.- const retireSiblingsEnabled = resolveNearDuplicateRetireSiblingsEnabled(- ctx.configPath ?? undefined,- );- // Only pay for a preview pass when a guard is actually requested; otherwise- // the run is byte-identical to before.- if (expect !== null || strict) {- const preview = dream(vault, {- dryRun: true,- safeguard,- readable,- retireSiblingsEnabled,- ...previewScope,- ...(nowDate ? { now: nowDate } : {}),- ...(agent ? { agentName: agent } : {}),- // Preview the run being guarded, overrides and all.- ...(gates !== undefined ? { gates } : {}),- });- const previewList = dreamChangeList(preview);- enforceCountGuard({- matched: previewList.length,- expect,- strict,- willMutate: !dryRun,- matchList: previewList,- });- }-- // The count-guard preview above is deliberately NOT reported on: it is- // a dry run whose only purpose is to decide whether the run below may- // happen at all, and a client that saw the same five stages twice- // would read the second pass as a restart. Progress describes the run- // the caller asked for.- const summary = dream(vault, {- dryRun,- safeguard,- readable,- retireSiblingsEnabled,- ...previewScope,- ...(nowDate ? { now: nowDate } : {}),- ...(agent ? { agentName: agent } : {}),- ...(gates !== undefined ? { gates } : {}),- ...(onProgress ? { onProgress } : {}),- });- const changeList = dreamChangeList(summary);- // A retire-sibling pair names two preferences; it is kept only when the- // caller may see both, each in both spellings (`ret-<slug>` after the- // pass, `pref-<slug>` before it).- const bothSpellings = (id: string): ReadonlyArray<string> => {- const slug = brainArtifactSlug(id);- return [`pref-${slug}`, `ret-${slug}`];- };- const retireSiblings = dreamView.keep(summary.retire_siblings ?? [], (p) => [- ...bothSpellings(p.retiring_id),- ...bothSpellings(p.sibling_id),- ]);-- // The summary is already a Plain Old Frozen Object — JSON-serialise- // verbatim. We surface `snapshot_path` / `log_path` as vault-relative- // for caller convenience while preserving the absolute path as well.- return {- run_id: summary.run_id,- changed: summary.changed,- // Honest matched-vs-changed: `matched` is what the pass would touch;- // `changed_count` is what it actually wrote (0 on a dry run).- matched: changeList.length,- changed_count: dryRun ? 0 : changeList.length,- dry_run: dryRun,- ...scopedDreamRows(dreamView, summary),- ...(retireSiblings.length > 0- ? {- retire_siblings: retireSiblings.map((p) => ({- retiring_id: p.retiring_id,- sibling_id: p.sibling_id,- score: p.score,- method: p.method,- })),- }- : {}),- // Inbox archive (issue #195): a count, not the ids. A first pass over a- // long-lived vault archives thousands of signals; the run's log event- // names every one of them.- archived_signals_count: summary.archived_signals?.length ?? 0,- contradictions: [...summary.contradictions],- warnings: summary.warnings.map((w) => ({- code: w.code,- message: w.message,- })),- uncertain: summary.uncertain.map((u) => ({- code: u.code,- ...(u.topic !== undefined ? { topic: u.topic } : {}),- message: u.message,- })),- quarantined: summary.quarantined.map((q) => ({- topic: q.topic,- signal_count: q.signal_count,- distinct_agents: q.distinct_agents,- age_days: q.age_days,- failed_gates: [...q.failed_gates],- })),- // The salience gate over the rollup fold set. `threshold: null` says- // the gate was absent, and the two counts are reported before the- // owner filter so a scoped caller still learns how many facts were- // held back even where it may not see their names.- salience_gate: {- threshold: summary.salience_gate.threshold,- considered: summary.salience_gate.considered,- admitted: summary.salience_gate.admitted,- excluded_count: summary.salience_gate.excluded.length,- excluded: dreamView- .keep(summary.salience_gate.excluded, (entry) => [entry.pref_id, entry.path])- .map((entry) => ({- pref_id: entry.pref_id,- path: entry.path,- score: entry.score,- mass: entry.mass,- confidence: entry.confidence,- reuse: entry.reuse,- })),- },- snapshot_path: summary.snapshot_path ? toolPath(ctx, summary.snapshot_path) : null,- log_path: summary.log_path ? toolPath(ctx, summary.log_path) : null,- };-}--// ----- brain_review_candidates ----------------------------------------------async function toolBrainApplyEvidence(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- // `null` on a server with no vault: the writes are store records (D14).- const vault = contextVault(ctx);- const prefId = coerceStr(args, "pref_id", true)!;- const artifact = coerceStr(args, "artifact", true)!;- const resultRaw = coerceStr(args, "result", true)!;- if (- resultRaw !== BRAIN_APPLY_RESULT.applied &&- resultRaw !== BRAIN_APPLY_RESULT.violated &&- resultRaw !== BRAIN_APPLY_RESULT.outdated- ) {- throw new MCPError(- INVALID_PARAMS,- `argument 'result' must be 'applied', 'violated', or 'outdated'`,- );- }- const agentArg = coerceStr(args, "agent", false);- const note = coerceStr(args, "note", false);- const outcomeRaw = coerceStr(args, "outcome", false);- if (- outcomeRaw !== null &&- outcomeRaw !== "success" &&- outcomeRaw !== "failure" &&- outcomeRaw !== "unknown"- ) {- throw new MCPError(- INVALID_PARAMS,- `argument 'outcome' must be 'success', 'failure', or 'unknown'`,- );- }-- // The evidence row names who applied the rule; a token caller cannot- // file that attribution under another agent's name.- refuseAgentClaim(ctx.requestIdentity, agentArg, "brain_apply_evidence");- const agent =- normalizeAgentArgument(agentArg) ??- ctx.requestIdentity?.agent ??- resolveAgentName(ctx.configPath ?? undefined);-- const input: AppendApplyEvidenceInput = {- pref_id: prefId,- artifact,- result: resultRaw as BrainApplyResult,- agent,- ...(outcomeRaw !== null ? { outcome: outcomeRaw } : {}),- ...(note ? { note } : {}),- };-- // Surface BrainPreferenceNotFoundError as a tool-level error envelope- // (isError: true) rather than an MCP protocol error. The design doc- // says "not an error condition" — the agent should see an informative- // payload that explains what to do next, not a JSON-RPC error frame.- // v0.10.16: assert applier role at the MCP boundary so the structural- // permission gate fires before any I/O.- // A preference the caller may not read is refused as a missing one,- // before anything is written.- const readable = readableAtContextReachOrUndefined(ctx);- try {- const res = appendApplyEvidence(vault, input, {- role: BRAIN_ROLES.applier,- ...(readable !== undefined ? { readable } : {}),- });- return {- logged_at: res.logged_at,- // With no vault the log is a store shard, named as the store names it.- log_path: vault === null ? res.log_path : toolPath(ctx, res.log_path),- absolute_log_path: vault === null ? res.log_path : resolve(res.log_path),- agent,- };- } catch (exc) {- if (exc instanceof BrainPreferenceNotFoundError) {- // Re-throw as a non-MCPError so `server.handleToolsCall` packs it- // into a `toolError` envelope (isError: true, single-text content).- throw new Error(exc.message, { cause: exc });- }- throw exc;- }-}--// ----- brain_observed_use (t_65588d8b) ---------------------------------------/**- * Record session-end observed-use verdicts (USED / IGNORED / CONTRADICTED)- * per injected memory, mirroring `brain_apply_evidence`: the host supplies- * already-structured verdicts (no LLM in the kernel), which are folded into- * the observed-reuse ranking signal. The kernel only stores and aggregates.- */-async function toolBrainObservedUse(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const rawEntries = args["entries"];- if (!Array.isArray(rawEntries) || rawEntries.length === 0) {- throw new MCPError(INVALID_PARAMS, "argument 'entries' must be a non-empty array");- }- const entries: ObservedUseEntry[] = rawEntries.map((raw, i) => {- if (raw === null || typeof raw !== "object") {- throw new MCPError(INVALID_PARAMS, `entries[${i}] must be an object`);- }- const e = raw as Record<string, unknown>;- const id = typeof e["id"] === "string" ? e["id"].trim() : "";- if (id === "") throw new MCPError(INVALID_PARAMS, `entries[${i}].id is required`);- const verdict = e["verdict"];- if (!isObservedUseVerdict(verdict)) {- throw new MCPError(- INVALID_PARAMS,- `entries[${i}].verdict must be 'USED', 'IGNORED', or 'CONTRADICTED'`,- );- }- const path = typeof e["path"] === "string" && e["path"] !== "" ? e["path"] : undefined;- return { id, verdict, ...(path ? { path } : {}) };- });-- const host = coerceStr(args, "host", false) ?? "mcp";- const sessionId = coerceStr(args, "session_id", false) ?? undefined;- const turnId = coerceStr(args, "turn_id", false) ?? undefined;- const record = emitObservedUse(ctx.vault, {- host,- ...(sessionId ? { sessionId } : {}),- ...(turnId ? { turnId } : {}),- entries,- });- return {- recorded: entries.length,- record_id: record.id,- created_at: record.createdAt,- };-}--// ----- brain_note (§32B, v0.10.8) --------------------------------------------/**- * Append one narrative-milestone line to today's Brain log. Agents- * record release / merged-PR / discovered-fact lines under the `note`- * event kind in `Brain/log/<today>.md` (and the JSONL sidecar).- *- * The body lives in `appendBrainNote` so the CLI verb (`o2b brain- * note`) and this MCP handler share one code path. Validation errors- * land in MCP's `INVALID_PARAMS` envelope here; the CLI wrapper- * pre-validates usage shape and surfaces the same condition as exit 2.- */-async function toolBrainNote(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- // `null` on a server with no vault: the writes are store records (D14).- const vault = contextVault(ctx);- const rawText = coerceStr(args, "text", true)!;- const agentArg = coerceStr(args, "agent", false);- // A token caller's log line is attributed to the token's agent; a- // claim on somebody else's name is refused before anything is written.- refuseAgentClaim(ctx.requestIdentity, agentArg, "brain_note");-- let res;- try {- res = appendBrainNote({- vault: vault,- text: rawText,- ...(agentArg ? { agent: agentArg } : {}),- ...(ctx.configPath ? { configPath: ctx.configPath } : {}),- });- } catch (err) {- // `appendBrainNote` throws one validation error ("text is required");- // any other failure is an I/O / filesystem fault from `appendLogEvent`- // and must not be reported as a client-side INVALID_PARAMS.- const message = (err as Error).message ?? String(err);- const code = message.startsWith("brain_note:") ? INVALID_PARAMS : INTERNAL_ERROR;- throw new MCPError(code, message);- }- return {- logged_at: res.logged_at,- log_path: res.log_path,- absolute_log_path: res.absolute_log_path,- agent: res.agent,- };-}--// ----- brain_write_session (Agent Write Contract Suite, v0.41.0) --------------/**- * Post-creation expiration mutation (unit 3c).- *- * A tool of its own rather than an action on `brain_lifecycle`, and the- * reason is how each addresses its subject: every `brain_lifecycle`- * action takes a vault-relative PATH and runs it through a note-path- * envelope, while a signal or preference is addressed by id and lives- * under the `Brain/` root that envelope exists to refuse. Folding them- * together would mean carving an exception into that refusal.- */-const EXPIRE_TOOL = "brain_expire";--async function toolBrainExpire(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const id = coerceStr(args, "id", true)!;- const expires = coerceStr(args, "expires", true)!;- const agent = coerceStr(args, "agent", false);- // The expiration's audit stamp names who set it; a token caller cannot- // sign another agent's name to it.- refuseAgentClaim(ctx.requestIdentity, agent, "brain_expire");- // A record the caller may not read is refused as an unknown id, before- // anything is written.- const readable = readableAtContextReachOrUndefined(ctx);- try {- const res = setExpiration(ctx.vault, id, expires, {- ...(agent ? { agent } : {}),- ...(readable !== undefined ? { readable } : {}),- });- return {- id: res.id,- kind: res.kind,- path: res.path,- expiration: res.expiration,- previous: res.previous,- changed: res.changed,- };- } catch (err) {- // Each of the three is the caller's fault and each has a different- // next move: fix the date, fix the id, or use a surface that takes a- // path. They keep their own class name as the reported code, read- // from the boundary registry's classification rather than `err.name`.- if (- err instanceof ExpirationValueError ||- err instanceof ExpirationTargetNotFoundError ||- err instanceof InvalidExpirationTargetError- ) {- throw new MCPError(INVALID_PARAMS, `${EXPIRE_TOOL}: ${err.message}`, {- code: codeForError(err),- });- }- if (err instanceof MCPError) throw err;- throw new MCPError(- INTERNAL_ERROR,- `${EXPIRE_TOOL}: ${err instanceof Error ? err.message : String(err)}`,- );- }-}export const FEEDBACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{diff --git a/src/mcp/brain/ingest-batch-tools.ts b/src/mcp/brain/ingest-batch-tools.tsnew file mode 100644index 00000000..f3f45f9a--- /dev/null+++ b/src/mcp/brain/ingest-batch-tools.ts@@ -0,0 +1,156 @@+/**+ * The batch plan (task 3.19): `brain_ingest_batch_plan` and the wire+ * serializer the tool, the CLI verb and the tests share. Split from+ * `ingest-tools.ts`; registration happens through that module's+ * registry, which preserves the public INGEST_TOOLS surface.+ */++import { serializeImportCensus } from "../../core/brain/import-census.ts";+import { planBatches, type BatchPlan } from "../../core/brain/ingest/batch-plan.ts";+import { clearCheckpoint } from "../../core/brain/ingest/checkpoint.ts";+import { reconcilePlan } from "../../core/brain/ingest/reconcile.ts";+import { coerceBoolOptional, coerceInt, coerceStr, coerceStrList } from "../coerce.ts";+import { type ServerContext } from "../tool-contract.ts";+import { readableAtContextReach } from "./reach-readable.ts";+import { DEFAULT_MAX_BATCH_BYTES, DEFAULT_MAX_BATCH_FILES } from "./ingest-source-tools.ts";++/**+ * The wire shape of a batch plan, shared by every surface that emits one: this+ * tool and `o2b brain batch-plan --json` (which spreads its own `reconcile` on+ * top). One serializer means a field added here cannot reach one surface and+ * miss the other.+ */+export function serializeBatchPlan(plan: BatchPlan): Record<string, unknown> {+ return {+ source_dir: plan.sourceDir,+ max_batch_bytes: plan.maxBatchBytes,+ max_batch_files: plan.maxBatchFiles,+ total_files: plan.totalFiles,+ total_bytes: plan.totalBytes,+ skipped: [...plan.skipped],+ // The H3 resurrect guard on the wire: sources whose manifest entry is+ // marked retired and whose bytes are unchanged. Only emitted when+ // non-empty, so a plan with no retired entry serializes byte-identically+ // to before.+ ...(plan.skippedRetired.length > 0 ? { skipped_retired: [...plan.skippedRetired] } : {}),+ // Only emitted when the manifest's recorded extraction contract differs+ // from the live one (t_586d5d8b), so a plan under an unchanged contract+ // serializes byte-identically to before. The count names how many files+ // reprocess because of the contract rather than their bytes.+ ...(plan.contractChanged+ ? { contract_changed: true, contract_changed_files: plan.contractChangedFiles }+ : {}),+ // Only emitted when the extractable gate skipped something, so a plan with+ // no extractable declaration serializes byte-identically to before. The+ // reason is the typed token (P4) and `detail` carries the value behind+ // it - the schema_type, or the format of a format skip - so a reader can+ // check the skip without re-reading.+ ...(plan.skippedNonExtractable.length > 0+ ? {+ skipped_non_extractable: plan.skippedNonExtractable.map((s) => ({+ path: s.path,+ reason: s.reason,+ detail: s.detail,+ })),+ }+ : {}),+ // Per-reason counts (P4), emitted only when something was skipped.+ ...(Object.keys(plan.skipReasonCounts).length > 0+ ? { skip_reason_counts: plan.skipReasonCounts }+ : {}),+ // Per-extension unclassifiable counts (P4), emitted only when the walk+ // dropped at least one non-ingestible file, so a tree that is all+ // ingestible serializes byte-identically to before.+ ...(plan.unclassifiable.total > 0+ ? {+ unclassifiable: {+ total: plan.unclassifiable.total,+ by_extension: plan.unclassifiable.byExtension,+ },+ }+ : {}),+ // Only emitted when the repository's own ignore files carried a malformed+ // pattern (t_4b2bd8f7), so a tree that declares none - or declares only+ // well-formed patterns - serializes byte-identically to before.+ ...(plan.ignoreWarnings.length > 0+ ? {+ ignore_warnings: plan.ignoreWarnings.map((w) => ({+ source: w.source,+ line: w.line,+ pattern: w.pattern,+ reason: w.reason,+ })),+ }+ : {}),+ plan_id: plan.planId,+ resumed_completed: plan.resumedCompleted,+ batches: plan.batches.map((b) => ({+ index: b.index,+ total_bytes: b.totalBytes,+ // `format` only for a non-text file, so a Markdown plan is unchanged.+ files: b.files.map((f) => ({+ path: f.path,+ bytes: f.bytes,+ status: f.status,+ ...(f.format !== undefined ? { format: f.format } : {}),+ })),+ })),+ };+}++export async function toolBrainIngestBatchPlan(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const sourceDir = coerceStr(args, "source_dir", true)!;+ const maxBatchBytes = coerceInt(+ args,+ "max_batch_bytes",+ DEFAULT_MAX_BATCH_BYTES,+ 1,+ Number.MAX_SAFE_INTEGER,+ );+ const maxBatchFiles = coerceInt(+ args,+ "max_batch_files",+ DEFAULT_MAX_BATCH_FILES,+ 1,+ Number.MAX_SAFE_INTEGER,+ );+ const resume = coerceBoolOptional(args, "resume") ?? false;+ const reconcile = coerceBoolOptional(args, "reconcile") ?? false;+ const srcSubpath = coerceStr(args, "src_subpath", false) ?? undefined;+ const exclude = coerceStrList(args, "exclude");+ // A file the caller may not read at its reach is planned as an absent one.+ const include = readableAtContextReach(ctx);+ const plan = planBatches(ctx.vault, sourceDir, {+ maxBatchBytes,+ maxBatchFiles,+ resume,+ include,+ ...(srcSubpath !== undefined ? { srcSubpath } : {}),+ ...(exclude.length > 0 ? { exclude } : {}),+ });+ // Reconcile BEFORE any checkpoint clear below, so the gap report reads a live+ // checkpoint. Read-only: it only diffs dispatched vs completed.+ const report = reconcile ? reconcilePlan(ctx.vault, plan, include) : undefined;+ // A resumed plan that comes back empty is fully drained: drop its checkpoint+ // (the content manifest is the authoritative final state from here on).+ if (resume && plan.batches.length === 0) {+ clearCheckpoint(ctx.vault, plan.planId);+ }+ const serialized = serializeBatchPlan(plan);+ return report === undefined+ ? serialized+ : {+ ...serialized,+ reconcile: {+ plan_id: report.planId,+ dispatched: [...report.dispatched],+ ingested: [...report.ingested],+ missing: [...report.missing],+ complete: report.complete,+ census: serializeImportCensus(report.census),+ },+ };+}diff --git a/src/mcp/brain/ingest-source-tools.ts b/src/mcp/brain/ingest-source-tools.tsnew file mode 100644index 00000000..a85310bf--- /dev/null+++ b/src/mcp/brain/ingest-source-tools.ts@@ -0,0 +1,630 @@+/**+ * The source-ingest tools (task 3.19): `brain_ingest_source`,+ * `brain_search_by_source` and `brain_delete_by_source`, with the+ * capacity refusal envelope they answer, the cleanup-plan serializers+ * and the archive-orphan helpers. Split from `ingest-tools.ts`;+ * registration happens through that module's registry, which preserves+ * the public INGEST_TOOLS surface.+ */++import { existsSync } from "node:fs";+import { join } from "node:path";+import { PLAN_ID_LABEL } from "../../core/brain/ingest/checkpoint.ts";+import { assertCheckpointId } from "../../core/brain/checkpoint-store.ts";+import { STORAGE_CAPACITY_CRITICAL_CODE } from "../../core/brain/doctor/storage-capacity.ts";+import { MAINTENANCE_CAPACITY_REMEDY } from "../../core/brain/maintenance/lane.ts";+import {+ StorageCapacityError,+ type StorageErrorCode,+} from "../../core/brain/storage/capacity-error.ts";+import {+ CAPACITY_GATE_DECISION,+ evaluateCapacityGate,+ type CapacityGateDecision,+} from "../../core/brain/storage/gate.ts";+import {+ loadGateStorageConfig,+ StorageGateConfigError,+} from "../../core/brain/storage/gate-config.ts";+import { ingestSource } from "../../core/brain/ingest/ingest.ts";+import type { PartsOutcome, TableOutcome } from "../../core/brain/ingest/extract-source.ts";+import type { CodeEdgeSeed, PreExtractResult } from "../../core/brain/ingest/pre-extract.ts";+import { IntakeValidationError } from "../../core/brain/intake/extract-intake.ts";+import {+ discardSourceArchive,+ isArchiveHash,+ SOURCE_ARCHIVE_HASH_KEY,+ sourceArchiveCitingPages,+ sourceArchiveEntryRel,+} from "../../core/brain/provenance/source-archive.ts";+import { parseFrontmatter } from "../../core/vault.ts";+import {+ deleteBySource,+ searchBySourceFile,+ type SourceCleanupEntry,+ type SourceCleanupPlan,+} from "../../core/brain/source-cleanup.ts";+import { resolveAgentName } from "../../core/config.ts";+import { normalizeAgentScope } from "../../core/graph/agent-scope.ts";+import { TRANSPORT_REACH, type TransportReach } from "../../core/graph/transport-reach.ts";+import { isPathOwnerVisible, type FrontmatterCache } from "../../core/search/result-filters.ts";+import { coerceAgentScope, coerceBoolOptional, coerceStr } from "../coerce.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import { codeForError } from "../tool-error-codes.ts";+import { contextReach, type ServerContext } from "../tool-contract.ts";+import { parseExtractionIntakeArgs } from "./intake-args.ts";+import { readableAtContextReach } from "./reach-readable.ts";+import {+ PENDING_STAGED_DIAGNOSTIC_CODE,+ PendingStageConflictError,+ WriteRefusedError,+} from "../../core/brain/pending/pending-lanes.ts";+import { nextCommandField } from "../../core/brain/next-step.ts";+import { enforceCountGuard, readCountGuardArgs, wrapToolErrors } from "./shared.ts";+import type { IngestSourceResult } from "../../core/brain/ingest/ingest.ts";+import { refuseAgentClaim } from "./agent-claim.ts";++export const TOOL = "brain_ingest_source";+export const SEARCH_TOOL = "brain_search_by_source";+export const DELETE_TOOL = "brain_delete_by_source";+export const BATCH_PLAN_TOOL = "brain_ingest_batch_plan";++/** Default batch caps when the caller omits them (1 MiB / 25 files per batch). */+export const DEFAULT_MAX_BATCH_BYTES = 1024 * 1024;+export const DEFAULT_MAX_BATCH_FILES = 25;++/** The wire code of the capacity admission refusal, from the leaf's closed union. */+export const ADMISSION_REFUSAL_CODE: StorageErrorCode = "capacity_exhausted";++/**+ * The registered wire code for an unreadable or invalid `_brain.yaml` - the+ * same code the error-code registry maps {@link BrainConfigError} to.+ */+export const CONFIG_GATE_REFUSAL_CODE = "config_invalid";++/**+ * Refuse the ingest when a fresh census measures the vault at its+ * critical storage tier - the interactive half of the storage lifecycle's+ * backpressure, beside the maintenance lane's gate.+ *+ * The check sits in the VALIDATE phase, before `ingestSource` opens the+ * write path: the commit phase is never entered, so there is nothing to+ * roll back, and a refusal leaves the vault byte-identical. Only a+ * MEASURED critical tier closes it, exactly as the lane's gate does - an+ * unmeasurable store stays open, because a census that could not be taken+ * is not a vault with room, but neither is it a vault without. No+ * configured cap is the documented default and means the check does not+ * exist: no gate, no byte walk, no cost.+ *+ * The gate itself is a write gate, not a secret, so it fires at every+ * reach - but the refusal throws the registered leaf carrying the+ * envelope's fields, and {@link admissionDetails} gates the whole-vault+ * figures by reach, for the same reason `brain_storage` refuses to take+ * its census below local reach.+ *+ * The remedy is the lane's own sentence, quoted rather than restated, so+ * the two walls an operator can hit - the paused lane and the refused+ * write - cannot disagree about what to do next.+ */+export function refuseWhenVaultExhausted(+ vault: string,+ reach: TransportReach,+ now: Date,+ configPath: string | null,+): void {+ const storage = loadGateStorageConfig(vault);+ if (storage.cap_bytes === null) return;+ const decision = evaluateCapacityGate(vault, {+ now,+ ...(configPath ? { configPath } : {}),+ capBytes: storage.cap_bytes,+ warnPercent: storage.warn_percent,+ criticalPercent: storage.critical_percent,+ warnDays: storage.warn_days,+ criticalDays: storage.critical_days,+ });+ if (decision.decision !== CAPACITY_GATE_DECISION.skip) return;+ throw new StorageCapacityError(+ ADMISSION_REFUSAL_CODE,+ `${TOOL}: refused (${ADMISSION_REFUSAL_CODE}): the vault measured at the ` ++ `${decision.tier} storage tier. ${MAINTENANCE_CAPACITY_REMEDY}.`,+ admissionDetails(decision, reach),+ );+}++/**+ * The structured fields beside the admission refusal's code. The tier and+ * the remedy ride at every reach; the whole-vault figures do not - they+ * are the same local-reach facts the storage report refuses to take below+ * local reach (`buildStorageReport`), and handing them to a remote caller+ * would answer the refusal with a census and a growth oracle in one+ * payload. The `next_command` field stays: the local remedy is the one+ * thing a refused caller still needs in hand.+ */+export function admissionDetails(+ decision: CapacityGateDecision,+ reach: TransportReach,+): Record<string, unknown> {+ const reading = decision.reading;+ return {+ tier: decision.tier,+ ...(reach === TRANSPORT_REACH.local+ ? {+ measured_bytes: reading?.measuredBytes ?? null,+ cap_bytes: reading?.capBytes ?? null,+ percent_used: reading?.percentUsed ?? null,+ }+ : {}),+ remedy: MAINTENANCE_CAPACITY_REMEDY,+ // The registered next step for a critical vault (the storage+ // report), resolved from the diagnostics registry - a refusal whose+ // value is the pointer never spells the command by hand.+ ...nextCommandField(STORAGE_CAPACITY_CRITICAL_CODE),+ };+}++/**+ * The MCP envelope for an admission refusal, from the thrown leaf: the+ * wire code is the code the registered `carried()` classification reads+ * off this leaf (`codeForError`), never a restated literal, and the data+ * fields are the leaf's own - so the envelope cannot drift from the+ * vocabulary the wire registry knows.+ */+export function capacityRefusalEnvelope(err: StorageCapacityError): MCPError {+ return new MCPError(INVALID_PARAMS, err.message, {+ code: codeForError(err),+ ...err.details,+ });+}++export async function toolBrainIngestSource(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const sourcePath = coerceStr(args, "source_path", true)!;+ const summary = coerceStr(args, "summary", true)!;+ const planId = coerceStr(args, "plan_id", false) ?? undefined;+ // `plan_id` is caller-supplied and becomes a checkpoint filename, so the+ // store's grammar is enforced HERE, where the caller can be told it is+ // their argument that is wrong. Left to the ingest it would surface as an+ // INTERNAL_ERROR, and before that it was swallowed entirely: the ingest+ // succeeded, resume never engaged, and `--reconcile` reported the whole+ // batch as never ingested.+ if (planId !== undefined) {+ try {+ assertCheckpointId(PLAN_ID_LABEL, planId);+ } catch (err) {+ throw new MCPError(INVALID_PARAMS, `${TOOL}: ${(err as Error).message}`);+ }+ }+ const preExtract = coerceBoolOptional(args, "pre_extract") ?? false;+ // This tool names its source as `source_path` and hands it to the pipeline+ // itself, so `source` is not part of its contract. Declaring that stops the+ // shared parser building a provenance out of an argument this schema never+ // declared and this handler never read.+ const parsed = parseExtractionIntakeArgs(args, TOOL, "absent");+ // The transport-minted identity wins over the config fallback, and a+ // token caller claiming another agent is refused outright+ // (write-side-trust, Task 7). resolveAgentName stays the stdio/CLI+ // fallback.+ const claimedAgent = parsed.agent && parsed.agent.trim().length > 0 ? parsed.agent : undefined;+ refuseAgentClaim(ctx.requestIdentity, claimedAgent ?? null, TOOL);+ const agent =+ claimedAgent ?? ctx.requestIdentity?.agent ?? resolveAgentName(ctx.configPath ?? undefined);++ return wrapToolErrors(TOOL, [IntakeValidationError], async () => {+ // The admission wall, in the validate phase: past this call the write+ // path opens, and the commit phase ahead of it is never rolled back.+ // The check throws the registered leaf; it is mapped onto its wire+ // envelope here, before the generic wrapper could flatten it into an+ // internal error.+ try {+ refuseWhenVaultExhausted(ctx.vault, contextReach(ctx), new Date(), ctx.configPath ?? null);+ } catch (err) {+ if (err instanceof StorageCapacityError) throw capacityRefusalEnvelope(err);+ // A broken config the gate cannot see through refuses by name, with+ // prose free of host paths (review M1) - never an internal error a+ // caller would retry into the same wall.+ if (err instanceof StorageGateConfigError) {+ throw new MCPError(INVALID_PARAMS, `${TOOL}: ${err.message}`, {+ code: CONFIG_GATE_REFUSAL_CODE,+ });+ }+ throw err;+ }+ let res: IngestSourceResult;+ try {+ res = ingestSource(+ ctx.vault,+ { sourcePath, summary, extraction: parsed.intake },+ {+ agent,+ now: new Date(),+ // A page the caller may not read at its reach answers as an absent one.+ readable: readableAtContextReach(ctx),+ // The review disposition answers for the credential-minted+ // subject, never for the caller-named agent.+ ...(ctx.requestIdentity !== undefined ? { subject: ctx.requestIdentity } : {}),+ ...(planId !== undefined ? { planId } : {}),+ ...(preExtract ? { preExtract: true } : {}),+ },+ );+ } catch (err) {+ // Write-side trust (Task 12): a permissions document rule denied the+ // ingest. Named code, the rule that decided, and the operator exit -+ // never an internal error a caller would retry into the same wall.+ if (err instanceof WriteRefusedError) {+ throw new MCPError(INVALID_PARAMS, `${TOOL}: ${err.message}`, {+ code: err.code,+ rule: err.rule,+ agent: err.agent,+ next_command: err.nextCommand,+ });+ }+ // An ingest retried while its first run is still staged: the queue+ // refuses by name, so the answer names the queue entry holding the+ // summary target instead of an internal error a caller would retry+ // into the same wall.+ if (err instanceof PendingStageConflictError) {+ throw new MCPError(INVALID_PARAMS, `${TOOL}: ${err.message}`, {+ code: err.code,+ existing_id: err.existingId,+ target: err.target,+ });+ }+ throw err;+ }+ return {+ summary_path: res.summaryPath,+ created: res.created,+ entities_created: [...res.entitiesCreated],+ entities_updated: [...res.entitiesUpdated],+ connections: [...res.connections],+ // How much of the source the vault holds, as the summary page records+ // it. Always present: absence would read as "full-local" to a caller+ // that never learned the key exists.+ capture_scope: res.captureScope,+ // The durable archive stamp (answer trust, Task C4), following the+ // capture_scope pattern: the hash is ALWAYS present, null when the+ // source was not archived, so absence never reads as a missing key.+ // The byte count rides only with a hash, mirroring the page's+ // frontmatter; the named refusal rides only when an ELIGIBLE source+ // could not be archived.+ source_archive_hash: res.sourceArchiveHash ?? null,+ ...(res.sourceArchiveHash !== undefined+ ? { source_archive_bytes: res.sourceArchiveBytes }+ : {}),+ ...(res.sourceArchiveRefusal !== undefined+ ? { source_archive_refusal: res.sourceArchiveRefusal }+ : {}),+ // Write-side trust (Task 9): a first publish of the summary page+ // stages under the review gate while registration completes. The+ // receipt names the queue entry and the command that publishes it,+ // so a staged ingest reads as staged, never as missing.+ ...(res.staged === true && res.pendingId !== undefined+ ? {+ staged: true,+ pending_id: res.pendingId,+ ...nextCommandField(PENDING_STAGED_DIAGNOSTIC_CODE),+ }+ : {}),+ // The appended delta this run proved (t_a9cd4221, review M14): the+ // boundary-safe byte range beside its named kind, absent on every+ // shape that is not a proven append - a first ingest, a rewrite, a+ // source with no watermark. The range lets the caller see what this+ // summary is newly about; extraction itself stays whole-source, so+ // the field is reporting, never a claim that only the tail was read.+ ...(res.extractionDelta !== undefined+ ? {+ extraction_delta: {+ kind: res.extractionDelta.kind,+ from_byte: res.extractionDelta.fromByte,+ to_byte: res.extractionDelta.toByte,+ },+ }+ : {}),+ // Only for an HTML or CSV/TSV source, so a text source's payload is+ // byte-identical to before. Counts and tokens only, never content.+ ...(res.parts !== undefined ? { parts: serializeParts(res.parts) } : {}),+ ...(res.table !== undefined ? { table: serializeTable(res.table) } : {}),+ // Only emitted when the pre-extract pass ran, so a call without it is+ // byte-identical to before (P4).+ ...(res.preExtract !== undefined ? { pre_extract: serializePreExtract(res.preExtract) } : {}),+ };+ });+}++/** The HTML outcome on the wire: `{extracted, count, omitted?}` or `{extracted: false, reason}`. */+export function serializeParts(parts: PartsOutcome): Record<string, unknown> {+ if (!parts.extracted) return { extracted: false, reason: parts.reason };+ return {+ extracted: true,+ count: parts.count,+ ...(parts.omitted !== undefined ? { omitted: parts.omitted } : {}),+ };+}++/** The table outcome on the wire, snake_case, `truncated` only when a cap cut it. */+export function serializeTable(table: TableOutcome): Record<string, unknown> {+ if (!table.rendered) {+ return {+ rendered: false,+ format: table.format,+ reason: table.reason,+ ...(table.detail !== undefined ? { detail: table.detail } : {}),+ };+ }+ return {+ rendered: true,+ format: table.format,+ delimiter: table.delimiter,+ columns: table.columns,+ rows: table.rows,+ rows_rendered: table.rowsRendered,+ ...(table.truncated.length > 0 ? { truncated: [...table.truncated] } : {}),+ redacted_cells: table.redactedCells,+ };+}++/** The pre-extract result with its edge keys in the payload's snake_case. */+export function serializePreExtract(result: PreExtractResult): Record<string, unknown> {+ if (!result.extracted) return { ...result };+ return { ...result, edges: result.edges.map(serializeEdgeSeed) };+}++export function serializeEdgeSeed(edge: CodeEdgeSeed): Record<string, unknown> {+ return {+ kind: edge.kind,+ from: edge.from,+ to: edge.to,+ ...(edge.resolvedTo !== undefined ? { resolved_to: edge.resolvedTo } : {}),+ };+}++export function serializeEntry(entry: SourceCleanupEntry): Record<string, unknown> {+ return {+ path: entry.path,+ id: entry.id,+ kind: entry.kind,+ match: entry.match,+ is_index_artifact: entry.isIndexArtifact,+ deletable: entry.deletable,+ };+}++/**+ * One archive entry a source cleanup takes with it (answer trust, Task C4),+ * reported as its own kind beside the page entries - the hash and the+ * vault-relative path, never a host path.+ */+export interface ArchiveCleanupEntry {+ readonly hash: string;+ readonly path: string;+}++/**+ * Harvest the archive digests stamped on the plan's summary pages, sorted.+ * Read BEFORE a confirmed deletion runs: once the pages are gone their+ * stamps are gone with them, and the entry orphan decision needs them.+ */+export function stampedArchiveHashes(+ vault: string,+ plan: SourceCleanupPlan,+): ReadonlyArray<string> {+ const hashes = new Set<string>();+ for (const entry of plan.derived) {+ if (entry.kind !== "summary" || !existsSync(join(vault, entry.path))) continue;+ const [meta] = parseFrontmatter(join(vault, entry.path));+ const value = meta[SOURCE_ARCHIVE_HASH_KEY];+ if (typeof value === "string" && isArchiveHash(value)) hashes.add(value);+ }+ return [...hashes].toSorted();+}++/**+ * Which of the plan's stamped entries this deletion orphans: an entry goes+ * only when EVERY page citing it is in the deleted set - removing a source+ * whose summary shares an entry with another source's page (identical+ * bytes, content-addressed dedup) leaves the entry standing. Vacuously+ * true when no citing page remains: the hash got here from the plan's own+ * pages, so an empty citation list means the last citing page is exactly+ * what this run deleted. A page the caller may not read is not in the+ * deleted set, so a hidden citation keeps the entry too: the fail-safe+ * direction.+ */+export function orphanedArchiveEntries(+ vault: string,+ hashes: ReadonlyArray<string>,+ deletedPaths: ReadonlySet<string>,+): ReadonlyArray<ArchiveCleanupEntry> {+ const out: ArchiveCleanupEntry[] = [];+ for (const hash of hashes) {+ const citing = sourceArchiveCitingPages(vault, hash);+ if (citing.every((page) => deletedPaths.has(page))) {+ out.push({ hash, path: sourceArchiveEntryRel(hash) });+ }+ }+ return out;+}++/**+ * Best-effort removal of one orphaned entry: false both when there was+ * nothing to remove and when the removal itself failed. The confirmed+ * deletion has already completed by the time this runs, so a cleanup that+ * throws - a permission denial, an entry replaced by something rmSync+ * cannot remove - must not fail the tool after the fact, and its error+ * message carries a host path this surface never reports. What is+ * tolerated here is exactly the transient half: the page deletion is done+ * and correct, and the leftover entry is durable evidence, not a lost+ * deletion - the doctor's archive section names it in its `uncited`+ * count, and a retry of the cleanup is harmless.+ */+export function discardOrphanedArchiveEntry(vault: string, hash: string): boolean {+ try {+ return discardSourceArchive(vault, hash);+ } catch {+ return false;+ }+}++export function serializePlan(+ plan: SourceCleanupPlan,+ archiveEntries: ReadonlyArray<ArchiveCleanupEntry>,+ local: boolean,+): Record<string, unknown> {+ return {+ source: plan.source,+ confirmed: plan.confirmed,+ include_originals: plan.includeOriginals,+ blast_radius: plan.blastRadius,+ // Honest matched-vs-changed accounting: `matched` is what the plan would+ // touch; `changed` is what was actually removed (0 on a dry run).+ matched: plan.blastRadius,+ changed: plan.deleted.length,+ derived: plan.derived.map(serializeEntry),+ mentions: plan.mentions.map(serializeEntry),+ originals: [...plan.originals],+ manifest_entry: plan.manifestEntry,+ deleted: [...plan.deleted],+ // The per-entry removal failures reach the tool answer (review M8): a+ // confirmed removal that could not delete a file must never read as a+ // clean run with a smaller count. Always carried (empty on a clean or+ // dry run) so an automations can read the field unconditionally, like+ // `deleted` beside it.+ // Below local reach the raised message, which can carry a host path,+ // is replaced by the errno code; the vault-relative path stays.+ failed: plan.failed.map((f) => ({+ path: f.path,+ message: local ? f.message : `removal failed (${f.code ?? "error"})`,+ })),+ manifest_entry_removed: plan.manifestEntryRemoved,+ audit_record_id: plan.auditRecordId,+ // The archive-entry cleanup kind (answer trust, Task C4), reported as+ // its own kind rather than folded into the page entries: on a dry run,+ // the entries removing the source's last citing page WOULD orphan; on+ // confirm, the entries actually removed. They are deterministic+ // consequences of the page deletion, never targets of their own, so+ // they sit outside the count guard's blast radius. Emitted only when+ // non-empty, so a plan over an unstamped source is byte-identical.+ ...(archiveEntries.length > 0 ? { archive_entries: archiveEntries } : {}),+ // The D1 recovery point. Only the run id is surfaced here (not the+ // absolute archive path) so the response stays free of host paths; the+ // archive lives at the deterministic `Brain/.snapshots/<run_id>.tar.zst`.+ snapshot_run_id: plan.snapshotRunId,+ // What that run id is worth. `include_originals` deletes files that+ // are outside `Brain/` by construction and therefore outside every+ // archive ever taken; reporting the run id with nothing beside it+ // told a caller the deletion was reversible when half of it was not.+ recoverability: {+ state: plan.recoverability.state,+ coverage: [...plan.recoverability.coverage],+ blockers: [...plan.recoverability.blockers],+ },+ };+}++/** The vault-relative identities a cleanup plan would touch (for guard output). */+export function planMatchList(plan: SourceCleanupPlan): string[] {+ return [+ ...plan.derived.map((e) => e.match ?? e.id),+ ...plan.mentions.map((e) => e.match ?? e.id),+ ...plan.originals,+ ];+}++export async function toolBrainSearchBySource(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const sourceFile = coerceStr(args, "source_file", true)!;+ // A page the caller may not read at its reach (a summary page that+ // inherited a reserved source's visibility) is answered as an absent one.+ const readable = readableAtContextReach(ctx);+ const hits = searchBySourceFile(ctx.vault, sourceFile).filter((entry) => readable(entry.path));+ // Owner-scope isolation (context-integrity-gates, Unit A). Every entry+ // names a Brain page, so the ownership rule applies through the same+ // path-based resolver the ranked search path uses - including its+ // fail-closed treatment of frontmatter that will not parse. `total`+ // counts what is returned; a total over the hidden pages would leak+ // their number. An absent scope filters nothing.+ const scope = normalizeAgentScope(coerceAgentScope(ctx, args, false));+ const cache: FrontmatterCache = new Map();+ const visible =+ scope === null+ ? hits+ : hits.filter((entry) => isPathOwnerVisible(ctx.vault, entry.path, scope, cache));+ return {+ source_file: sourceFile,+ total: visible.length,+ entries: visible.map(serializeEntry),+ };+}++export async function toolBrainDeleteBySource(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const sourceFile = coerceStr(args, "source_file", true)!;+ const confirm = coerceBoolOptional(args, "confirm") ?? false;+ const includeOriginals = coerceBoolOptional(args, "include_originals") ?? false;+ const agent = coerceStr(args, "agent", false) ?? undefined;+ const { expect, strict } = readCountGuardArgs(args);+ const now = new Date();+ // An original the caller may not read at its reach is planned and+ // deleted exactly as an absent one: never confirmed, never removed.+ const baseOpts = {+ includeOriginals,+ now,+ include: readableAtContextReach(ctx),+ // The deny consult answers for the credential-minted subject, never+ // for the caller-named agent (write-side-trust, Task 7).+ ...(ctx.requestIdentity !== undefined ? { subject: ctx.requestIdentity } : {}),+ ...(agent !== undefined ? { agent } : {}),+ };++ // Compute the (non-destructive) plan first so the count guard can assert the+ // blast radius BEFORE anything is deleted; only then confirm the removal.+ const preview = deleteBySource(ctx.vault, sourceFile, { confirm: false, ...baseOpts });+ enforceCountGuard({+ matched: preview.blastRadius,+ expect,+ strict,+ willMutate: confirm,+ matchList: planMatchList(preview),+ });+ // The stamps must be read BEFORE a confirmed deletion erases the pages+ // that carry them; the orphan decision then runs against whichever set+ // this run actually removed (a dry run answers with what confirm would+ // remove).+ const stamped = stampedArchiveHashes(ctx.vault, preview);+ try {+ let archiveEntries: ReadonlyArray<ArchiveCleanupEntry> = [];+ if (confirm) {+ const plan = deleteBySource(ctx.vault, sourceFile, { confirm: true, ...baseOpts });+ archiveEntries = orphanedArchiveEntries(ctx.vault, stamped, new Set(plan.deleted)).filter(+ (entry) => discardOrphanedArchiveEntry(ctx.vault, entry.hash),+ );+ return serializePlan(plan, archiveEntries, contextReach(ctx) === TRANSPORT_REACH.local);+ }+ archiveEntries = orphanedArchiveEntries(+ ctx.vault,+ stamped,+ new Set(preview.derived.map((entry) => entry.path)),+ );+ return serializePlan(preview, archiveEntries, contextReach(ctx) === TRANSPORT_REACH.local);+ } catch (err) {+ // Write-side trust (Task 12): a permissions document rule denied the+ // confirmed cleanup. Named code, the rule that decided, and the+ // operator exit - never an internal error a caller would retry into+ // the same wall.+ if (err instanceof WriteRefusedError) {+ throw new MCPError(INVALID_PARAMS, `${DELETE_TOOL}: ${err.message}`, {+ code: err.code,+ rule: err.rule,+ agent: err.agent,+ next_command: err.nextCommand,+ });+ }+ throw err;+ }+}diff --git a/src/mcp/brain/ingest-tools.ts b/src/mcp/brain/ingest-tools.tsindex 61557159..59c980e0 100644--- a/src/mcp/brain/ingest-tools.ts+++ b/src/mcp/brain/ingest-tools.ts@@ -9,776 +9,22 @@* Idempotent on the source path.*/-import { existsSync } from "node:fs";-import { join } from "node:path";--import { serializeImportCensus } from "../../core/brain/import-census.ts";-import { planBatches, type BatchPlan } from "../../core/brain/ingest/batch-plan.ts";-import { clearCheckpoint, PLAN_ID_LABEL } from "../../core/brain/ingest/checkpoint.ts";-import { assertCheckpointId } from "../../core/brain/checkpoint-store.ts";-import { STORAGE_CAPACITY_CRITICAL_CODE } from "../../core/brain/doctor/storage-capacity.ts";-import { MAINTENANCE_CAPACITY_REMEDY } from "../../core/brain/maintenance/lane.ts";-import {- StorageCapacityError,- type StorageErrorCode,-} from "../../core/brain/storage/capacity-error.ts";-import {- CAPACITY_GATE_DECISION,- evaluateCapacityGate,- type CapacityGateDecision,-} from "../../core/brain/storage/gate.ts";-import {- loadGateStorageConfig,- StorageGateConfigError,-} from "../../core/brain/storage/gate-config.ts";-import { ingestSource } from "../../core/brain/ingest/ingest.ts";-import type { PartsOutcome, TableOutcome } from "../../core/brain/ingest/extract-source.ts";-import type { CodeEdgeSeed, PreExtractResult } from "../../core/brain/ingest/pre-extract.ts";-import { reconcilePlan } from "../../core/brain/ingest/reconcile.ts";-import { IntakeValidationError } from "../../core/brain/intake/extract-intake.ts";-import {- discardSourceArchive,- isArchiveHash,- SOURCE_ARCHIVE_HASH_KEY,- sourceArchiveCitingPages,- sourceArchiveEntryRel,-} from "../../core/brain/provenance/source-archive.ts";-import { parseFrontmatter } from "../../core/vault.ts";-import {- deleteBySource,- searchBySourceFile,- type SourceCleanupEntry,- type SourceCleanupPlan,-} from "../../core/brain/source-cleanup.ts";-import { resolveAgentName } from "../../core/config.ts";-import { normalizeAgentScope } from "../../core/graph/agent-scope.ts";-import { TRANSPORT_REACH, type TransportReach } from "../../core/graph/transport-reach.ts";-import { isPathOwnerVisible, type FrontmatterCache } from "../../core/search/result-filters.ts";-import {- coerceAgentScope,- coerceBoolOptional,- coerceInt,- coerceStr,- coerceStrList,-} from "../coerce.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";-import { INVALID_PARAMS, MCPError } from "../protocol.ts";-import { codeForError } from "../tool-error-codes.ts";-import { contextReach, type ServerContext, type ToolDefinition } from "../tool-contract.ts";-import { parseExtractionIntakeArgs } from "./intake-args.ts";-import { readableAtContextReach } from "./reach-readable.ts";+import { type ToolDefinition } from "../tool-contract.ts";import {- PENDING_STAGED_DIAGNOSTIC_CODE,- PendingStageConflictError,- WriteRefusedError,-} from "../../core/brain/pending/pending-lanes.ts";-import { nextCommandField } from "../../core/brain/next-step.ts";-import { enforceCountGuard, readCountGuardArgs, wrapToolErrors } from "./shared.ts";-import type { IngestSourceResult } from "../../core/brain/ingest/ingest.ts";-import { refuseAgentClaim } from "./agent-claim.ts";--const TOOL = "brain_ingest_source";-const SEARCH_TOOL = "brain_search_by_source";-const DELETE_TOOL = "brain_delete_by_source";-const BATCH_PLAN_TOOL = "brain_ingest_batch_plan";--/** Default batch caps when the caller omits them (1 MiB / 25 files per batch). */-const DEFAULT_MAX_BATCH_BYTES = 1024 * 1024;-const DEFAULT_MAX_BATCH_FILES = 25;--/** The wire code of the capacity admission refusal, from the leaf's closed union. */-const ADMISSION_REFUSAL_CODE: StorageErrorCode = "capacity_exhausted";--/**- * The registered wire code for an unreadable or invalid `_brain.yaml` - the- * same code the error-code registry maps {@link BrainConfigError} to.- */-const CONFIG_GATE_REFUSAL_CODE = "config_invalid";--/**- * Refuse the ingest when a fresh census measures the vault at its- * critical storage tier - the interactive half of the storage lifecycle's- * backpressure, beside the maintenance lane's gate.- *- * The check sits in the VALIDATE phase, before `ingestSource` opens the- * write path: the commit phase is never entered, so there is nothing to- * roll back, and a refusal leaves the vault byte-identical. Only a- * MEASURED critical tier closes it, exactly as the lane's gate does - an- * unmeasurable store stays open, because a census that could not be taken- * is not a vault with room, but neither is it a vault without. No- * configured cap is the documented default and means the check does not- * exist: no gate, no byte walk, no cost.- *- * The gate itself is a write gate, not a secret, so it fires at every- * reach - but the refusal throws the registered leaf carrying the- * envelope's fields, and {@link admissionDetails} gates the whole-vault- * figures by reach, for the same reason `brain_storage` refuses to take- * its census below local reach.- *- * The remedy is the lane's own sentence, quoted rather than restated, so- * the two walls an operator can hit - the paused lane and the refused- * write - cannot disagree about what to do next.- */-function refuseWhenVaultExhausted(- vault: string,- reach: TransportReach,- now: Date,- configPath: string | null,-): void {- const storage = loadGateStorageConfig(vault);- if (storage.cap_bytes === null) return;- const decision = evaluateCapacityGate(vault, {- now,- ...(configPath ? { configPath } : {}),- capBytes: storage.cap_bytes,- warnPercent: storage.warn_percent,- criticalPercent: storage.critical_percent,- warnDays: storage.warn_days,- criticalDays: storage.critical_days,- });- if (decision.decision !== CAPACITY_GATE_DECISION.skip) return;- throw new StorageCapacityError(- ADMISSION_REFUSAL_CODE,- `${TOOL}: refused (${ADMISSION_REFUSAL_CODE}): the vault measured at the ` +- `${decision.tier} storage tier. ${MAINTENANCE_CAPACITY_REMEDY}.`,- admissionDetails(decision, reach),- );-}--/**- * The structured fields beside the admission refusal's code. The tier and- * the remedy ride at every reach; the whole-vault figures do not - they- * are the same local-reach facts the storage report refuses to take below- * local reach (`buildStorageReport`), and handing them to a remote caller- * would answer the refusal with a census and a growth oracle in one- * payload. The `next_command` field stays: the local remedy is the one- * thing a refused caller still needs in hand.- */-function admissionDetails(- decision: CapacityGateDecision,- reach: TransportReach,-): Record<string, unknown> {- const reading = decision.reading;- return {- tier: decision.tier,- ...(reach === TRANSPORT_REACH.local- ? {- measured_bytes: reading?.measuredBytes ?? null,- cap_bytes: reading?.capBytes ?? null,- percent_used: reading?.percentUsed ?? null,- }- : {}),- remedy: MAINTENANCE_CAPACITY_REMEDY,- // The registered next step for a critical vault (the storage- // report), resolved from the diagnostics registry - a refusal whose- // value is the pointer never spells the command by hand.- ...nextCommandField(STORAGE_CAPACITY_CRITICAL_CODE),- };-}--/**- * The MCP envelope for an admission refusal, from the thrown leaf: the- * wire code is the code the registered `carried()` classification reads- * off this leaf (`codeForError`), never a restated literal, and the data- * fields are the leaf's own - so the envelope cannot drift from the- * vocabulary the wire registry knows.- */-function capacityRefusalEnvelope(err: StorageCapacityError): MCPError {- return new MCPError(INVALID_PARAMS, err.message, {- code: codeForError(err),- ...err.details,- });-}--async function toolBrainIngestSource(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const sourcePath = coerceStr(args, "source_path", true)!;- const summary = coerceStr(args, "summary", true)!;- const planId = coerceStr(args, "plan_id", false) ?? undefined;- // `plan_id` is caller-supplied and becomes a checkpoint filename, so the- // store's grammar is enforced HERE, where the caller can be told it is- // their argument that is wrong. Left to the ingest it would surface as an- // INTERNAL_ERROR, and before that it was swallowed entirely: the ingest- // succeeded, resume never engaged, and `--reconcile` reported the whole- // batch as never ingested.- if (planId !== undefined) {- try {- assertCheckpointId(PLAN_ID_LABEL, planId);- } catch (err) {- throw new MCPError(INVALID_PARAMS, `${TOOL}: ${(err as Error).message}`);- }- }- const preExtract = coerceBoolOptional(args, "pre_extract") ?? false;- // This tool names its source as `source_path` and hands it to the pipeline- // itself, so `source` is not part of its contract. Declaring that stops the- // shared parser building a provenance out of an argument this schema never- // declared and this handler never read.- const parsed = parseExtractionIntakeArgs(args, TOOL, "absent");- // The transport-minted identity wins over the config fallback, and a- // token caller claiming another agent is refused outright- // (write-side-trust, Task 7). resolveAgentName stays the stdio/CLI- // fallback.- const claimedAgent = parsed.agent && parsed.agent.trim().length > 0 ? parsed.agent : undefined;- refuseAgentClaim(ctx.requestIdentity, claimedAgent ?? null, TOOL);- const agent =- claimedAgent ?? ctx.requestIdentity?.agent ?? resolveAgentName(ctx.configPath ?? undefined);-- return wrapToolErrors(TOOL, [IntakeValidationError], async () => {- // The admission wall, in the validate phase: past this call the write- // path opens, and the commit phase ahead of it is never rolled back.- // The check throws the registered leaf; it is mapped onto its wire- // envelope here, before the generic wrapper could flatten it into an- // internal error.- try {- refuseWhenVaultExhausted(ctx.vault, contextReach(ctx), new Date(), ctx.configPath ?? null);- } catch (err) {- if (err instanceof StorageCapacityError) throw capacityRefusalEnvelope(err);- // A broken config the gate cannot see through refuses by name, with- // prose free of host paths (review M1) - never an internal error a- // caller would retry into the same wall.- if (err instanceof StorageGateConfigError) {- throw new MCPError(INVALID_PARAMS, `${TOOL}: ${err.message}`, {- code: CONFIG_GATE_REFUSAL_CODE,- });- }- throw err;- }- let res: IngestSourceResult;- try {- res = ingestSource(- ctx.vault,- { sourcePath, summary, extraction: parsed.intake },- {- agent,- now: new Date(),- // A page the caller may not read at its reach answers as an absent one.- readable: readableAtContextReach(ctx),- // The review disposition answers for the credential-minted- // subject, never for the caller-named agent.- ...(ctx.requestIdentity !== undefined ? { subject: ctx.requestIdentity } : {}),- ...(planId !== undefined ? { planId } : {}),- ...(preExtract ? { preExtract: true } : {}),- },- );- } catch (err) {- // Write-side trust (Task 12): a permissions document rule denied the- // ingest. Named code, the rule that decided, and the operator exit -- // never an internal error a caller would retry into the same wall.- if (err instanceof WriteRefusedError) {- throw new MCPError(INVALID_PARAMS, `${TOOL}: ${err.message}`, {- code: err.code,- rule: err.rule,- agent: err.agent,- next_command: err.nextCommand,- });- }- // An ingest retried while its first run is still staged: the queue- // refuses by name, so the answer names the queue entry holding the- // summary target instead of an internal error a caller would retry- // into the same wall.- if (err instanceof PendingStageConflictError) {- throw new MCPError(INVALID_PARAMS, `${TOOL}: ${err.message}`, {- code: err.code,- existing_id: err.existingId,- target: err.target,- });- }- throw err;- }- return {- summary_path: res.summaryPath,- created: res.created,- entities_created: [...res.entitiesCreated],- entities_updated: [...res.entitiesUpdated],- connections: [...res.connections],- // How much of the source the vault holds, as the summary page records- // it. Always present: absence would read as "full-local" to a caller- // that never learned the key exists.- capture_scope: res.captureScope,- // The durable archive stamp (answer trust, Task C4), following the- // capture_scope pattern: the hash is ALWAYS present, null when the- // source was not archived, so absence never reads as a missing key.- // The byte count rides only with a hash, mirroring the page's- // frontmatter; the named refusal rides only when an ELIGIBLE source- // could not be archived.- source_archive_hash: res.sourceArchiveHash ?? null,- ...(res.sourceArchiveHash !== undefined- ? { source_archive_bytes: res.sourceArchiveBytes }- : {}),- ...(res.sourceArchiveRefusal !== undefined- ? { source_archive_refusal: res.sourceArchiveRefusal }- : {}),- // Write-side trust (Task 9): a first publish of the summary page- // stages under the review gate while registration completes. The- // receipt names the queue entry and the command that publishes it,- // so a staged ingest reads as staged, never as missing.- ...(res.staged === true && res.pendingId !== undefined- ? {- staged: true,- pending_id: res.pendingId,- ...nextCommandField(PENDING_STAGED_DIAGNOSTIC_CODE),- }- : {}),- // The appended delta this run proved (t_a9cd4221, review M14): the- // boundary-safe byte range beside its named kind, absent on every- // shape that is not a proven append - a first ingest, a rewrite, a- // source with no watermark. The range lets the caller see what this- // summary is newly about; extraction itself stays whole-source, so- // the field is reporting, never a claim that only the tail was read.- ...(res.extractionDelta !== undefined- ? {- extraction_delta: {- kind: res.extractionDelta.kind,- from_byte: res.extractionDelta.fromByte,- to_byte: res.extractionDelta.toByte,- },- }- : {}),- // Only for an HTML or CSV/TSV source, so a text source's payload is- // byte-identical to before. Counts and tokens only, never content.- ...(res.parts !== undefined ? { parts: serializeParts(res.parts) } : {}),- ...(res.table !== undefined ? { table: serializeTable(res.table) } : {}),- // Only emitted when the pre-extract pass ran, so a call without it is- // byte-identical to before (P4).- ...(res.preExtract !== undefined ? { pre_extract: serializePreExtract(res.preExtract) } : {}),- };- });-}--/** The HTML outcome on the wire: `{extracted, count, omitted?}` or `{extracted: false, reason}`. */-function serializeParts(parts: PartsOutcome): Record<string, unknown> {- if (!parts.extracted) return { extracted: false, reason: parts.reason };- return {- extracted: true,- count: parts.count,- ...(parts.omitted !== undefined ? { omitted: parts.omitted } : {}),- };-}--/** The table outcome on the wire, snake_case, `truncated` only when a cap cut it. */-function serializeTable(table: TableOutcome): Record<string, unknown> {- if (!table.rendered) {- return {- rendered: false,- format: table.format,- reason: table.reason,- ...(table.detail !== undefined ? { detail: table.detail } : {}),- };- }- return {- rendered: true,- format: table.format,- delimiter: table.delimiter,- columns: table.columns,- rows: table.rows,- rows_rendered: table.rowsRendered,- ...(table.truncated.length > 0 ? { truncated: [...table.truncated] } : {}),- redacted_cells: table.redactedCells,- };-}--/** The pre-extract result with its edge keys in the payload's snake_case. */-function serializePreExtract(result: PreExtractResult): Record<string, unknown> {- if (!result.extracted) return { ...result };- return { ...result, edges: result.edges.map(serializeEdgeSeed) };-}--function serializeEdgeSeed(edge: CodeEdgeSeed): Record<string, unknown> {- return {- kind: edge.kind,- from: edge.from,- to: edge.to,- ...(edge.resolvedTo !== undefined ? { resolved_to: edge.resolvedTo } : {}),- };-}--function serializeEntry(entry: SourceCleanupEntry): Record<string, unknown> {- return {- path: entry.path,- id: entry.id,- kind: entry.kind,- match: entry.match,- is_index_artifact: entry.isIndexArtifact,- deletable: entry.deletable,- };-}--/**- * One archive entry a source cleanup takes with it (answer trust, Task C4),- * reported as its own kind beside the page entries - the hash and the- * vault-relative path, never a host path.- */-interface ArchiveCleanupEntry {- readonly hash: string;- readonly path: string;-}--/**- * Harvest the archive digests stamped on the plan's summary pages, sorted.- * Read BEFORE a confirmed deletion runs: once the pages are gone their- * stamps are gone with them, and the entry orphan decision needs them.- */-function stampedArchiveHashes(vault: string, plan: SourceCleanupPlan): ReadonlyArray<string> {- const hashes = new Set<string>();- for (const entry of plan.derived) {- if (entry.kind !== "summary" || !existsSync(join(vault, entry.path))) continue;- const [meta] = parseFrontmatter(join(vault, entry.path));- const value = meta[SOURCE_ARCHIVE_HASH_KEY];- if (typeof value === "string" && isArchiveHash(value)) hashes.add(value);- }- return [...hashes].toSorted();-}--/**- * Which of the plan's stamped entries this deletion orphans: an entry goes- * only when EVERY page citing it is in the deleted set - removing a source- * whose summary shares an entry with another source's page (identical- * bytes, content-addressed dedup) leaves the entry standing. Vacuously- * true when no citing page remains: the hash got here from the plan's own- * pages, so an empty citation list means the last citing page is exactly- * what this run deleted. A page the caller may not read is not in the- * deleted set, so a hidden citation keeps the entry too: the fail-safe- * direction.- */-function orphanedArchiveEntries(- vault: string,- hashes: ReadonlyArray<string>,- deletedPaths: ReadonlySet<string>,-): ReadonlyArray<ArchiveCleanupEntry> {- const out: ArchiveCleanupEntry[] = [];- for (const hash of hashes) {- const citing = sourceArchiveCitingPages(vault, hash);- if (citing.every((page) => deletedPaths.has(page))) {- out.push({ hash, path: sourceArchiveEntryRel(hash) });- }- }- return out;-}--/**- * Best-effort removal of one orphaned entry: false both when there was- * nothing to remove and when the removal itself failed. The confirmed- * deletion has already completed by the time this runs, so a cleanup that- * throws - a permission denial, an entry replaced by something rmSync- * cannot remove - must not fail the tool after the fact, and its error- * message carries a host path this surface never reports. What is- * tolerated here is exactly the transient half: the page deletion is done- * and correct, and the leftover entry is durable evidence, not a lost- * deletion - the doctor's archive section names it in its `uncited`- * count, and a retry of the cleanup is harmless.- */-function discardOrphanedArchiveEntry(vault: string, hash: string): boolean {- try {- return discardSourceArchive(vault, hash);- } catch {- return false;- }-}--function serializePlan(- plan: SourceCleanupPlan,- archiveEntries: ReadonlyArray<ArchiveCleanupEntry>,- local: boolean,-): Record<string, unknown> {- return {- source: plan.source,- confirmed: plan.confirmed,- include_originals: plan.includeOriginals,- blast_radius: plan.blastRadius,- // Honest matched-vs-changed accounting: `matched` is what the plan would- // touch; `changed` is what was actually removed (0 on a dry run).- matched: plan.blastRadius,- changed: plan.deleted.length,- derived: plan.derived.map(serializeEntry),- mentions: plan.mentions.map(serializeEntry),- originals: [...plan.originals],- manifest_entry: plan.manifestEntry,- deleted: [...plan.deleted],- // The per-entry removal failures reach the tool answer (review M8): a- // confirmed removal that could not delete a file must never read as a- // clean run with a smaller count. Always carried (empty on a clean or- // dry run) so an automations can read the field unconditionally, like- // `deleted` beside it.- // Below local reach the raised message, which can carry a host path,- // is replaced by the errno code; the vault-relative path stays.- failed: plan.failed.map((f) => ({- path: f.path,- message: local ? f.message : `removal failed (${f.code ?? "error"})`,- })),- manifest_entry_removed: plan.manifestEntryRemoved,- audit_record_id: plan.auditRecordId,- // The archive-entry cleanup kind (answer trust, Task C4), reported as- // its own kind rather than folded into the page entries: on a dry run,- // the entries removing the source's last citing page WOULD orphan; on- // confirm, the entries actually removed. They are deterministic- // consequences of the page deletion, never targets of their own, so- // they sit outside the count guard's blast radius. Emitted only when- // non-empty, so a plan over an unstamped source is byte-identical.- ...(archiveEntries.length > 0 ? { archive_entries: archiveEntries } : {}),- // The D1 recovery point. Only the run id is surfaced here (not the- // absolute archive path) so the response stays free of host paths; the- // archive lives at the deterministic `Brain/.snapshots/<run_id>.tar.zst`.- snapshot_run_id: plan.snapshotRunId,- // What that run id is worth. `include_originals` deletes files that- // are outside `Brain/` by construction and therefore outside every- // archive ever taken; reporting the run id with nothing beside it- // told a caller the deletion was reversible when half of it was not.- recoverability: {- state: plan.recoverability.state,- coverage: [...plan.recoverability.coverage],- blockers: [...plan.recoverability.blockers],- },- };-}--/** The vault-relative identities a cleanup plan would touch (for guard output). */-function planMatchList(plan: SourceCleanupPlan): string[] {- return [- ...plan.derived.map((e) => e.match ?? e.id),- ...plan.mentions.map((e) => e.match ?? e.id),- ...plan.originals,- ];-}--async function toolBrainSearchBySource(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const sourceFile = coerceStr(args, "source_file", true)!;- // A page the caller may not read at its reach (a summary page that- // inherited a reserved source's visibility) is answered as an absent one.- const readable = readableAtContextReach(ctx);- const hits = searchBySourceFile(ctx.vault, sourceFile).filter((entry) => readable(entry.path));- // Owner-scope isolation (context-integrity-gates, Unit A). Every entry- // names a Brain page, so the ownership rule applies through the same- // path-based resolver the ranked search path uses - including its- // fail-closed treatment of frontmatter that will not parse. `total`- // counts what is returned; a total over the hidden pages would leak- // their number. An absent scope filters nothing.- const scope = normalizeAgentScope(coerceAgentScope(ctx, args, false));- const cache: FrontmatterCache = new Map();- const visible =- scope === null- ? hits- : hits.filter((entry) => isPathOwnerVisible(ctx.vault, entry.path, scope, cache));- return {- source_file: sourceFile,- total: visible.length,- entries: visible.map(serializeEntry),- };-}--async function toolBrainDeleteBySource(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const sourceFile = coerceStr(args, "source_file", true)!;- const confirm = coerceBoolOptional(args, "confirm") ?? false;- const includeOriginals = coerceBoolOptional(args, "include_originals") ?? false;- const agent = coerceStr(args, "agent", false) ?? undefined;- const { expect, strict } = readCountGuardArgs(args);- const now = new Date();- // An original the caller may not read at its reach is planned and- // deleted exactly as an absent one: never confirmed, never removed.- const baseOpts = {- includeOriginals,- now,- include: readableAtContextReach(ctx),- // The deny consult answers for the credential-minted subject, never- // for the caller-named agent (write-side-trust, Task 7).- ...(ctx.requestIdentity !== undefined ? { subject: ctx.requestIdentity } : {}),- ...(agent !== undefined ? { agent } : {}),- };-- // Compute the (non-destructive) plan first so the count guard can assert the- // blast radius BEFORE anything is deleted; only then confirm the removal.- const preview = deleteBySource(ctx.vault, sourceFile, { confirm: false, ...baseOpts });- enforceCountGuard({- matched: preview.blastRadius,- expect,- strict,- willMutate: confirm,- matchList: planMatchList(preview),- });- // The stamps must be read BEFORE a confirmed deletion erases the pages- // that carry them; the orphan decision then runs against whichever set- // this run actually removed (a dry run answers with what confirm would- // remove).- const stamped = stampedArchiveHashes(ctx.vault, preview);- try {- let archiveEntries: ReadonlyArray<ArchiveCleanupEntry> = [];- if (confirm) {- const plan = deleteBySource(ctx.vault, sourceFile, { confirm: true, ...baseOpts });- archiveEntries = orphanedArchiveEntries(ctx.vault, stamped, new Set(plan.deleted)).filter(- (entry) => discardOrphanedArchiveEntry(ctx.vault, entry.hash),- );- return serializePlan(plan, archiveEntries, contextReach(ctx) === TRANSPORT_REACH.local);- }- archiveEntries = orphanedArchiveEntries(- ctx.vault,- stamped,- new Set(preview.derived.map((entry) => entry.path)),- );- return serializePlan(preview, archiveEntries, contextReach(ctx) === TRANSPORT_REACH.local);- } catch (err) {- // Write-side trust (Task 12): a permissions document rule denied the- // confirmed cleanup. Named code, the rule that decided, and the- // operator exit - never an internal error a caller would retry into- // the same wall.- if (err instanceof WriteRefusedError) {- throw new MCPError(INVALID_PARAMS, `${DELETE_TOOL}: ${err.message}`, {- code: err.code,- rule: err.rule,- agent: err.agent,- next_command: err.nextCommand,- });- }- throw err;- }-}--/**- * The wire shape of a batch plan, shared by every surface that emits one: this- * tool and `o2b brain batch-plan --json` (which spreads its own `reconcile` on- * top). One serializer means a field added here cannot reach one surface and- * miss the other.- */-export function serializeBatchPlan(plan: BatchPlan): Record<string, unknown> {- return {- source_dir: plan.sourceDir,- max_batch_bytes: plan.maxBatchBytes,- max_batch_files: plan.maxBatchFiles,- total_files: plan.totalFiles,- total_bytes: plan.totalBytes,- skipped: [...plan.skipped],- // The H3 resurrect guard on the wire: sources whose manifest entry is- // marked retired and whose bytes are unchanged. Only emitted when- // non-empty, so a plan with no retired entry serializes byte-identically- // to before.- ...(plan.skippedRetired.length > 0 ? { skipped_retired: [...plan.skippedRetired] } : {}),- // Only emitted when the manifest's recorded extraction contract differs- // from the live one (t_586d5d8b), so a plan under an unchanged contract- // serializes byte-identically to before. The count names how many files- // reprocess because of the contract rather than their bytes.- ...(plan.contractChanged- ? { contract_changed: true, contract_changed_files: plan.contractChangedFiles }- : {}),- // Only emitted when the extractable gate skipped something, so a plan with- // no extractable declaration serializes byte-identically to before. The- // reason is the typed token (P4) and `detail` carries the value behind- // it - the schema_type, or the format of a format skip - so a reader can- // check the skip without re-reading.- ...(plan.skippedNonExtractable.length > 0- ? {- skipped_non_extractable: plan.skippedNonExtractable.map((s) => ({- path: s.path,- reason: s.reason,- detail: s.detail,- })),- }- : {}),- // Per-reason counts (P4), emitted only when something was skipped.- ...(Object.keys(plan.skipReasonCounts).length > 0- ? { skip_reason_counts: plan.skipReasonCounts }- : {}),- // Per-extension unclassifiable counts (P4), emitted only when the walk- // dropped at least one non-ingestible file, so a tree that is all- // ingestible serializes byte-identically to before.- ...(plan.unclassifiable.total > 0- ? {- unclassifiable: {- total: plan.unclassifiable.total,- by_extension: plan.unclassifiable.byExtension,- },- }- : {}),- // Only emitted when the repository's own ignore files carried a malformed- // pattern (t_4b2bd8f7), so a tree that declares none - or declares only- // well-formed patterns - serializes byte-identically to before.- ...(plan.ignoreWarnings.length > 0- ? {- ignore_warnings: plan.ignoreWarnings.map((w) => ({- source: w.source,- line: w.line,- pattern: w.pattern,- reason: w.reason,- })),- }- : {}),- plan_id: plan.planId,- resumed_completed: plan.resumedCompleted,- batches: plan.batches.map((b) => ({- index: b.index,- total_bytes: b.totalBytes,- // `format` only for a non-text file, so a Markdown plan is unchanged.- files: b.files.map((f) => ({- path: f.path,- bytes: f.bytes,- status: f.status,- ...(f.format !== undefined ? { format: f.format } : {}),- })),- })),- };-}--async function toolBrainIngestBatchPlan(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const sourceDir = coerceStr(args, "source_dir", true)!;- const maxBatchBytes = coerceInt(- args,- "max_batch_bytes",- DEFAULT_MAX_BATCH_BYTES,- 1,- Number.MAX_SAFE_INTEGER,- );- const maxBatchFiles = coerceInt(- args,- "max_batch_files",- DEFAULT_MAX_BATCH_FILES,- 1,- Number.MAX_SAFE_INTEGER,- );- const resume = coerceBoolOptional(args, "resume") ?? false;- const reconcile = coerceBoolOptional(args, "reconcile") ?? false;- const srcSubpath = coerceStr(args, "src_subpath", false) ?? undefined;- const exclude = coerceStrList(args, "exclude");- // A file the caller may not read at its reach is planned as an absent one.- const include = readableAtContextReach(ctx);- const plan = planBatches(ctx.vault, sourceDir, {- maxBatchBytes,- maxBatchFiles,- resume,- include,- ...(srcSubpath !== undefined ? { srcSubpath } : {}),- ...(exclude.length > 0 ? { exclude } : {}),- });- // Reconcile BEFORE any checkpoint clear below, so the gap report reads a live- // checkpoint. Read-only: it only diffs dispatched vs completed.- const report = reconcile ? reconcilePlan(ctx.vault, plan, include) : undefined;- // A resumed plan that comes back empty is fully drained: drop its checkpoint- // (the content manifest is the authoritative final state from here on).- if (resume && plan.batches.length === 0) {- clearCheckpoint(ctx.vault, plan.planId);- }- const serialized = serializeBatchPlan(plan);- return report === undefined- ? serialized- : {- ...serialized,- reconcile: {- plan_id: report.planId,- dispatched: [...report.dispatched],- ingested: [...report.ingested],- missing: [...report.missing],- complete: report.complete,- census: serializeImportCensus(report.census),- },- };-}+ BATCH_PLAN_TOOL,+ DEFAULT_MAX_BATCH_BYTES,+ DEFAULT_MAX_BATCH_FILES,+ DELETE_TOOL,+ SEARCH_TOOL,+ TOOL,+ toolBrainDeleteBySource,+ toolBrainIngestSource,+ toolBrainSearchBySource,+} from "./ingest-source-tools.ts";+import { toolBrainIngestBatchPlan } from "./ingest-batch-tools.ts";++export { serializeBatchPlan } from "./ingest-batch-tools.ts";export const INGEST_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{diff --git a/src/mcp/brain/knowledge-claim-tools.ts b/src/mcp/brain/knowledge-claim-tools.tsnew file mode 100644index 00000000..240d3289--- /dev/null+++ b/src/mcp/brain/knowledge-claim-tools.ts@@ -0,0 +1,325 @@+/**+ * The claim-ledger surface of the knowledge family (task 3.19):+ * `brain_claims` over the entity claim ledger, with the graph+ * resolution, node rendering, provenance and visibility helpers it+ * answers through, and the two exports the CLI truth subcommand shares+ * (`statedClaimEntities`, `claimEventsReport`). Split from+ * `knowledge-tools.ts`; registration happens through that module's+ * registry, which preserves the public KNOWLEDGE_TOOLS surface.+ */++import { reachView } from "../../core/brain/reach-view.ts";+import { everyArtifactRefView, type ArtifactRefView } from "../../core/brain/artifact-ref-view.ts";+import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";+import { recordRefs } from "../../core/brain/log-events-at-reach.ts";+import { deliveryView } from "./reach-events.ts";+import { normalizeEntityName } from "../../core/brain/entities/canonical.ts";+import { listEntities } from "../../core/brain/entities/registry.ts";+import {+ ENTITY_STATUS_SCOPE,+ entityStatusInScope,+} from "../../core/brain/entities/status-scope.ts";+import { readClaimEvents } from "../../core/brain/truth/store.ts";+import { matchClaimEvents } from "../../core/brain/truth/events-window.ts";+import {+ loadClaimProvenanceIndex,+ resolveClaimProvenanceFromIndex,+ type ClaimProvenance,+ type ClaimProvenanceOptions,+} from "../../core/brain/truth/claim-provenance.ts";+import type { ClaimEvent } from "../../core/brain/truth/types.ts";+import {+ allClaims,+ buildClaimGraph,+ currentTruth,+ loadClaimGraph,+ rebuildClaimGraph,+ truthAt,+ whatContests,+ whatReplaced,+ type ClaimGraph,+ type ClaimNode,+} from "../../core/brain/claim-graph.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import { contextReach } from "../tool-contract.ts";+import { TRANSPORT_REACH, type TransportReach } from "../../core/graph/transport-reach.ts";+import type { ServerContext } from "../tool-contract.ts";+import { coerceStr, unknownOperationError } from "../coerce.ts";+import { isOperatorRuleItem, isRuleOnlyInjection } from "./pack-tools.ts";++// ----- brain_claims (Belief lifecycle suite, A3) -----------------------------++export function renderClaimNode(+ delivery: ReturnType<typeof deliveryView>,+ n: ClaimNode,+): Record<string, unknown> {+ return {+ id: n.id,+ path: n.path,+ topic: n.topic,+ // The principle is the record's own stored text (delivery-trust,+ // lane A): shaped through the request's delivery binding at the+ // claim's own page - the same text brain_query fences inside the+ // preference payloads - so the graph view is not the unfenced copy.+ principle: delivery.shape(n.principle, n.path),+ valid_from: n.valid_from,+ valid_until: n.valid_until,+ superseded_by: n.superseded_by,+ contradicts: n.contradicts,+ provenance: n.provenance,+ tombstoned: n.tombstoned,+ };+}++export const CLAIMS_DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;++/** Load the persisted claim graph, or build a fresh in-memory one. */+export function resolveClaimGraph(vault: string): ClaimGraph {+ return loadClaimGraph(vault) ?? buildClaimGraph(vault);+}++/**+ * Claim-graph query surface: current truth (default), truth at an+ * instant, history, what replaced X, what contests X, or rebuild.+ */+export function toolBrainClaims(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Record<string, unknown> {+ const operation = coerceStr(args, "operation", false) ?? "current";+ // A claim row carries the artifact's id, its vault-relative path, its+ // topic AND its full principle text - the sharpest counter-example in+ // recon C6 to the "this bucket is metadata" label. Every row-returning+ // operation is filtered, and so is the rebuild count: a count the+ // caller cannot decompose still says how many claims exist.+ // At the caller's reach a row is asked over every record it names: its+ // page, its id under the pref- and ret- spellings, and the records that+ // superseded or contest it.+ const owner = gatedOwnerScopeView(ctx.vault, ctx.agentName);+ const reach = reachView(ctx.vault, contextReach(ctx));+ // The delivery binding (delivery-trust, lane A): one reach resolution+ // and one frontmatter cache for every principle this tool returns.+ const delivery = deliveryView(ctx);+ const shown = (n: ClaimNode): boolean =>+ owner.row(n.path, n.id) &&+ reach.row(+ n.path,+ ...recordRefs(n.id),+ ...recordRefs(n.superseded_by ?? undefined),+ ...n.contradicts.flatMap((id) => recordRefs(id)),+ );+ const visible = (rows: ReadonlyArray<ClaimNode>): ReadonlyArray<ClaimNode> => rows.filter(shown);+ switch (operation) {+ case "rebuild": {+ const graph = rebuildClaimGraph(ctx.vault);+ return {+ operation,+ rebuilt: true,+ node_count: visible(allClaims(graph)).length,+ truncated: graph.truncated,+ };+ }+ case "replaced": {+ const id = coerceStr(args, "id", true)!;+ const tip = whatReplaced(resolveClaimGraph(ctx.vault), id);+ return {+ operation,+ id,+ tip: tip !== null && shown(tip) ? renderClaimNode(delivery, tip) : null,+ };+ }+ case "contests": {+ const id = coerceStr(args, "id", true)!;+ const rows = visible(whatContests(resolveClaimGraph(ctx.vault), id));+ return { operation, id, claims: rows.map((n) => renderClaimNode(delivery, n)) };+ }+ case "at": {+ const at = coerceStr(args, "at", true)!;+ const iso = CLAIMS_DATE_ONLY_RE.test(at) ? `${at}T00:00:00Z` : at;+ const probe = Date.parse(iso);+ if (Number.isNaN(probe)) {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_claims: 'at' must be an ISO instant or YYYY-MM-DD date; got ${at}`,+ );+ }+ const rows = visible(truthAt(resolveClaimGraph(ctx.vault), probe));+ return {+ operation,+ at,+ count: rows.length,+ claims: rows.map((n) => renderClaimNode(delivery, n)),+ };+ }+ case "history": {+ const rows = visible(allClaims(resolveClaimGraph(ctx.vault)));+ return {+ operation,+ count: rows.length,+ claims: rows.map((n) => renderClaimNode(delivery, n)),+ };+ }+ case "current": {+ const rows = visible(currentTruth(resolveClaimGraph(ctx.vault)));+ return {+ operation,+ count: rows.length,+ claims: rows.map((n) => renderClaimNode(delivery, n)),+ };+ }+ default:+ throw unknownOperationError(+ "brain_claims: 'operation' must be one of current, at, history, replaced, contests, rebuild",+ );+ }+}++// ----- brain_truth (Entity Truth & Self-Improving Dream Suite) ---------------++/**+ * The registry slice the stated-claims anchoring consumes: canonical-+ * scope entities only (the anchoring kernel's status discipline,+ * applied where the registry is read), narrowed to AtomicEntityLike.+ * Shared by the MCP `state` operation and the CLI `brain truth state`+ * subcommand so the two surfaces anchor identically.+ */+export function statedClaimEntities(vault: string): ReadonlyArray<{+ readonly id: string;+ readonly name: string;+ readonly aliases: ReadonlyArray<string>;+ readonly status: string;+}> {+ return listEntities(vault)+ .filter((entity) => entityStatusInScope(entity.status, ENTITY_STATUS_SCOPE.canonical))+ .map(({ id, name, aliases, status }) => ({ id, name, aliases, status }));+}++/**+ * One windowed events query, shared by the MCP `events` operation and+ * the CLI `brain truth events` subcommand so the two surfaces cannot+ * drift on shape, ordering, gating or paging. Bounds arrive already+ * resolved (unix-ms); the page size must already be validated.+ *+ * Windowed recall (truth-correctable-time-aware, Tasks 8-9):+ * `sinceMs`/`untilMs` filter ASSERTION `ts` only; the per-claim+ * validity windows ride on the rows verbatim and are never consulted+ * here (contract item 1 keeps the two temporal vocabularies separate).+ * Every matched row passes the same per-row owner/reach gate+ * `brain_claims` asks, and the account covers ONLY the rows that pass+ * it: a withheld row is dropped and nothing counts it (the views'+ * identical-to-absent convention - a dropped-but-counted row would tell+ * the caller that a claim it may not see exists, and per entity or+ * window would let it measure the hidden population). A filtered answer+ * is therefore byte-identical to the answer over a vault that never+ * held the withheld rows. The same reach governs the provenance join+ * (see {@link claimProvenanceForPage}).+ */+export function claimEventsReport(+ vault: string,+ agentName: string | undefined,+ reach: TransportReach,+ query: {+ readonly entity?: string;+ readonly sinceMs: number | null;+ readonly untilMs: number | null;+ readonly limit: number;+ },+): Record<string, unknown> {+ const entityFilter =+ query.entity !== undefined && query.entity.trim() !== "" ? query.entity : undefined;+ const view = everyArtifactRefView(gatedOwnerScopeView(vault, agentName), reachView(vault, reach));+ const matched = matchClaimEvents(readClaimEvents(vault).events, {+ ...(entityFilter !== undefined ? { entity: entityFilter } : {}),+ sinceMs: query.sinceMs,+ untilMs: query.untilMs,+ });+ const gated = view.filtersNothing ? matched : matched.filter((event) => view.row(event.source));+ const page = gated.slice(0, query.limit);+ const provenance = claimProvenanceForPage(vault, reach, view, page);+ return {+ ok: true,+ operation: "events",+ entity: entityFilter === undefined ? null : normalizeEntityName(entityFilter),+ events: page.map((event, position) =>+ event.sample_id === undefined || provenance === null+ ? // A claim without a sample id renders exactly as today: no+ // provenance key, byte-identical row.+ event+ : {+ ...event,+ // Answer-trust (task B4): the claim's sample id resolves to+ // its receipt and outcome halves at read time. A missing+ // outcome half is null - "receipt known, outcome unknown" -+ // never a fabricated verdict.+ provenance: provenance[position]!,+ },+ ),+ total: gated.length,+ truncated: gated.length > query.limit,+ };+}++/**+ * The provenance half of one events page, resolved at the CALLER's+ * reach over ONE read per ledger.+ *+ * The resolutions come back aligned with the page by POSITION, one per+ * row: the inversion flag compares each claim's OWN assertion ts+ * against the claimed receipt, so two claims sharing one `sample_id`+ * (one stated before the receipt it names, one after) must resolve+ * independently - a per-id cache would hand both rows the last+ * claim's flag. Resolution from the prebuilt index is map lookups, so+ * resolving per event keeps the one-read-per-ledger bound the scans+ * suite pins.+ *+ * The receipts surface withholds the operator's rule injections below+ * local reach (list excludes them, show refuses them, receipts are+ * stripped of their items); this join answers for the same records, so+ * it binds the same rules here instead of leaking through a claim's+ * `sample_id` what `brain_context_receipts` refuses to say directly. A+ * rule-only receipt renders as the unknown-id answer; a mixed receipt+ * keeps its non-rule items; and a receipt item whose recorded path+ * names a page the caller may not read at its reach leaves the items+ * under the same visibility rule the event rows of this report are+ * gated by.+ *+ * Null when no row on the page carries a sample id: the ledgers are+ * never read and every row renders byte-identically to the+ * pre-attribution answer. Otherwise the array holds one entry per page+ * row, null at the unsampled positions.+ */+export function claimProvenanceForPage(+ vault: string,+ reach: TransportReach,+ view: ArtifactRefView,+ page: ReadonlyArray<ClaimEvent>,+): ReadonlyArray<ClaimProvenance | null> | null {+ if (!page.some((event) => event.sample_id !== undefined)) return null;+ const local = reach === TRANSPORT_REACH.local;+ const options: ClaimProvenanceOptions = {+ ...(local ? {} : { exclude: isRuleOnlyInjection }),+ ...(view.filtersNothing+ ? {}+ : {+ excludeItem: (item: unknown): boolean =>+ (!local && isOperatorRuleItem(item)) || itemPathHidden(item, view),+ }),+ };+ const index = loadClaimProvenanceIndex(vault);+ return page.map((event) =>+ event.sample_id === undefined+ ? null+ : resolveClaimProvenanceFromIndex(index, event.sample_id, event.ts, options),+ );+}++/**+ * A receipt item whose recorded path names a page the caller may not+ * read at its reach. An item with no path names no page and stays; an+ * extensionless or wikilink spelling resolves through the same+ * reference grammar the event-row gate uses.+ */+export function itemPathHidden(item: unknown, view: ArtifactRefView): boolean {+ const path = (item as { path?: unknown } | null)?.path;+ return typeof path === "string" && path !== "" && !view.visible(path);+}diff --git a/src/mcp/brain/knowledge-lane-tools.ts b/src/mcp/brain/knowledge-lane-tools.tsnew file mode 100644index 00000000..8d024d21--- /dev/null+++ b/src/mcp/brain/knowledge-lane-tools.ts@@ -0,0 +1,678 @@+/**+ * The lane and synthesis tools of the knowledge family (task 3.19):+ * foresight, bridges, clusters, the MOC audit, deep synthesis,+ * diarization and idea discovery, each reading its lane pages through+ * the visibility rule the caller holds. Split from `knowledge-tools.ts`;+ * registration happens through that module's registry, which preserves+ * the public KNOWLEDGE_TOOLS surface.+ */++import { join } from "node:path";+import { existsSync } from "node:fs";+import { resolveTriggerCooldownDays } from "../../core/config.ts";+import { resolveSearchConfig } from "../../core/search/index.ts";+import { Store } from "../../core/search/store.ts";+import { loadSchemaPack } from "../../core/brain/schema-pack.ts";+import {+ acceptBridge,+ bridgePairKey,+ discoverBridges,+ dismissBridge,+ readDismissedBridges,+ writeBridgeProposals,+} from "../../core/brain/link-graph/bridge-discovery.ts";+import {+ detectCommunities,+ materializeClusterNotes,+} from "../../core/brain/link-graph/communities.ts";+import { appendMetric } from "../../core/brain/metrics.ts";+import { OPERATION } from "../../core/brain/safeguard.ts";+import type { ProgressSink } from "../../core/brain/progress.ts";+import { createTriggers } from "../../core/brain/triggers/store.ts";+import {+ deepSynthesis,+ synthesisCandidates,+ synthesisFindingsJson,+} from "../../core/brain/deep-synthesis.ts";+import { diarize, DiarizationError } from "../../core/brain/diarization.ts";+import { discoverIdeas, ideaCandidates } from "../../core/brain/idea-discovery.ts";+import { auditMoc, MocAuditError } from "../../core/brain/link-graph/moc-audit.ts";+import { reachView } from "../../core/brain/reach-view.ts";+import { everyArtifactRefView } from "../../core/brain/artifact-ref-view.ts";+import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";+import { normaliseWikilinkTarget } from "../../core/brain/wikilink.ts";+import { isoSecond } from "../../core/brain/time.ts";+import { laneVault } from "./lane-vault.ts";+import { buildForesight, FORESIGHT_HORIZON_DAYS } from "../../core/brain/temporal/foresight.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import { contextReach } from "../tool-contract.ts";+import { TRANSPORT_REACH } from "../../core/graph/transport-reach.ts";+import type { ServerContext } from "../tool-contract.ts";+import { vaultPathField } from "../vault-path-field.ts";+import { coerceAgentScope, coerceStr, coerceBool, unknownOperationError } from "../coerce.ts";+import { coercePositiveInteger, toolSafeguard } from "./shared.ts";+import {+ lanePageExists,+ lanePagesInStore,+ listLaneFiles,+ parseLanePage,+} from "../../core/store/lane-pages.ts";+import { readableAtContextReach } from "./reach-readable.ts";++/**+ * Who may see a lane page by its vault-relative path: the reach view of+ * the vault's files on an unswitched machine, the store-aware predicate+ * (the page's record fields) once switched or with no vault.+ */+export function laneVisible(ctx: ServerContext, vault: string): (rel: string) => boolean {+ if (lanePagesInStore(vault)) return readableAtContextReach(ctx);+ // The reach view alone is not the whole rule: a lane page can carry an+ // owner, and under `integrity.owner_scope_delivery: fail` the ownership+ // rule must be asked of it too - the same composed view every sibling+ // reader applies.+ const view = everyArtifactRefView(+ gatedOwnerScopeView(vault, ctx.agentName),+ reachView(vault, contextReach(ctx)),+ );+ return (rel) => view.visible(rel);+}++/**+ * Vault-relative locations these two handlers read BY PATH, rather than+ * through one of the three read roots. Named here because each was+ * spelled twice - once to build the absolute path and once to report the+ * relative one - and the two spellings had to agree for the boundary+ * check below to be asking about the page it was returning.+ */+export const BRAIN_CLUSTERS_REL = "Brain/clusters";+export const BRAIN_PROPOSALS_REL = "Brain/proposals";+export const BRIDGE_PROPOSALS_FILE = "bridges.md";++/**+ * One row of the shared proposals artifact, as+ * {@link writeBridgeProposals} spells it. Only the two named paths are+ * asked of the caller's view.+ */+interface BridgeProposalRow {+ readonly source: string;+ readonly target: string;+}++/**+ * The proposal rows of the artifact body, or `null` when the table cannot+ * be read back into its rows - the shape {@link writeBridgeProposals}+ * emits, and the only shape a per-caller count can be computed from. The+ * table header starts the region: every line from there on is table, so+ * a row edited away from the writer's shape makes the whole count+ * unfilterable rather than silently skipped.+ */+function parseBridgeProposalRows(content: string): ReadonlyArray<BridgeProposalRow> | null {+ const lines = content.split("\n");+ const headerAt = lines.findIndex(+ (line) => line.trim() === "| source | target | similarity | inbound (src/tgt) |",+ );+ if (headerAt === -1) return [];+ const rows: BridgeProposalRow[] = [];+ for (const line of lines.slice(headerAt + 2)) {+ const trimmed = line.trim();+ if (trimmed === "") break;+ // A data row is+ // `| [[<id>]] (<path>) | [[<id>]] (<path>) | <sim> | <in/out> |`+ // - the exact cell shape `writeBridgeProposals` emits - and a path+ // may contain parentheses (`Notes/Design (v2).md`), so the path is+ // taken as everything between the id's `]] (` and the cell's final+ // `)`, not up to the first `)`. Splitting on `|` leaves a leading+ // empty cell.+ const cells = trimmed.split("|").map((cell) => cell.trim());+ if (cells.length !== 6) return null;+ const cellRef = (cell: string): string | undefined =>+ /^\[\[.*?\]\]\s*\((.*)\)$/.exec(cell)?.[1];+ const source = cellRef(cells[1] ?? "");+ const target = cellRef(cells[2] ?? "");+ if (source === undefined || target === undefined || source === "" || target === "") {+ return null;+ }+ rows.push({ source, target });+ }+ return rows;+}++/** Forward-looking projection envelope; read-only fold. */+export function toolBrainForesight(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Record<string, unknown> {+ const horizonRaw = args["horizon_days"];+ let horizonDays = FORESIGHT_HORIZON_DAYS;+ if (horizonRaw !== undefined && horizonRaw !== null) {+ if (typeof horizonRaw !== "number" || !Number.isInteger(horizonRaw) || horizonRaw < 1) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_foresight: horizon_days must be a positive integer",+ );+ }+ horizonDays = horizonRaw;+ }+ // A private continuity record is withheld below local reach, the same+ // withholding flag every other report fold here takes: its text is the+ // item title and its refs the sources, so an unfiltered fold would read+ // the private partition back to a remote caller.+ return {+ ...buildForesight(ctx.vault, {+ now: new Date(),+ horizonDays,+ withholdsPrivate: contextReach(ctx) !== TRANSPORT_REACH.local,+ }),+ };+}++// ----- brain_labels (t_7a41f42d) ---------------------------------------------++/**+ * Bridge discovery over the vec index: discover regenerates the+ * reviewable proposals artifact, accept writes one related wikilink,+ * dismiss persists a pair suppression, list reads the artifact back.+ */+export async function toolBrainBridges(+ ctx: ServerContext,+ args: Record<string, unknown>,+ onProgress?: ProgressSink,+): Promise<Record<string, unknown>> {+ const op = args["operation"];+ if (op !== "discover" && op !== "list" && op !== "accept" && op !== "dismiss") {+ throw unknownOperationError("brain_bridges: operation must be discover|list|accept|dismiss");+ }+ if (op === "accept" || op === "dismiss") {+ const source = args["source"];+ const target = args["target"];+ if (typeof source !== "string" || source.trim() === "") {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_bridges ${op}: source must be a vault-relative path`,+ );+ }+ if (typeof target !== "string" || target.trim() === "") {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_bridges ${op}: target must be a vault-relative path`,+ );+ }+ if (op === "dismiss") {+ return {+ dismissed: bridgePairKey(source, target),+ added: dismissBridge(ctx.vault, source, target),+ };+ }+ try {+ const pack = loadSchemaPack(ctx.vault);+ return { ...acceptBridge(ctx.vault, source, target, { pack }), source, target };+ } catch (exc) {+ const message = (exc as Error).message ?? String(exc);+ if (/outside the vault|does not exist|link constraint/.test(message)) {+ throw new MCPError(INVALID_PARAMS, `brain_bridges accept: ${message}`);+ }+ throw exc;+ }+ }+ if (op === "list") {+ const vault = laneVault(ctx);+ const rel = join(BRAIN_PROPOSALS_REL, BRIDGE_PROPOSALS_FILE);+ const path = join(vault, rel);+ // Root closure: this reads a vault page BY PATH without going through+ // one of the three read roots, so it asks the rule here. A reserved+ // proposals page answers exactly as an absent one - the same shape+ // the by-path read primitives hold. A lane page (a store record once+ // switched) is read through the lane page store.+ if (!lanePageExists(vault, path) || !laneVisible(ctx, vault)(rel)) {+ return { exists: false, proposals: 0 };+ }+ const [meta, content] = parseLanePage(vault, path);+ // The artifact is ONE shared file written vault-wide by `discover`,+ // so its frontmatter `proposals` count answers for rows the caller+ // may not see. Every row names two pages by path, so the count is+ // recomputed over the caller's composed owner and reach view, one+ // visible row at a time. A row that cannot be read back (an artifact+ // whose body was edited away from the known shape while its+ // frontmatter still counts proposals) cannot be filtered, and an+ // unfiltered answer would leak the number - so the artifact answers+ // as an absent one instead.+ const claimed = Number(meta["proposals"] ?? 0);+ const rows = parseBridgeProposalRows(content);+ // A positive claim with no rows read back (a missing table header+ // included) is just as unfilterable.+ if (claimed > 0 && (rows === null || rows.length === 0)) {+ return { exists: false, proposals: 0 };+ }+ const view = everyArtifactRefView(+ gatedOwnerScopeView(vault, ctx.agentName),+ reachView(vault, contextReach(ctx)),+ );+ const visible = (rows ?? []).filter((row) => view.row(row.source, row.target)).length;+ return {+ exists: true,+ path: rel,+ generated_at: meta["generated_at"] ?? null,+ proposals: visible,+ };+ }+ // discover+ const max = args["max"];+ if (max !== undefined && (!Number.isInteger(max) || (max as number) < 1)) {+ throw new MCPError(INVALID_PARAMS, "brain_bridges discover: max must be a positive integer");+ }+ const minSimilarity = args["min_similarity"];+ if (+ minSimilarity !== undefined &&+ (typeof minSimilarity !== "number" || minSimilarity <= 0 || minSimilarity > 1)+ ) {+ throw new MCPError(INVALID_PARAMS, "brain_bridges discover: min_similarity must be in (0, 1]");+ }+ const searchConfig = resolveSearchConfig({+ vault: ctx.vault,+ configPath: ctx.configPath ?? undefined,+ });+ if (!existsSync(searchConfig.dbPath)) {+ return { vec_available: false, proposals: [], reason: "index not built" };+ }+ const store = await Store.open(searchConfig, { mode: "read" });+ const now = new Date();+ try {+ const dismissed = readDismissedBridges(ctx.vault);+ const report = discoverBridges(store, {+ ...(max !== undefined ? { maxProposals: max as number } : {}),+ ...(minSimilarity !== undefined ? { minSimilarity } : {}),+ dismissed,+ safeguard: toolSafeguard(ctx, OPERATION.bridges),+ ...(onProgress ? { onProgress } : {}),+ });+ writeBridgeProposals(ctx.vault, report, { now });+ try {+ appendMetric(ctx.vault, {+ surface: "bridge_discovery",+ runAt: isoSecond(now),+ payload: {+ proposals: report.proposals.length,+ scanned_candidates: report.scannedCandidates,+ vec_available: report.vecAvailable,+ dismissed_total: dismissed.size,+ },+ });+ } catch {+ // Metrics are observability, not correctness.+ }+ // Root closure over what the CALLER is told. Detection stays+ // vault-wide - a bridge proposed from the visible half of a link+ // graph would differ per caller and the proposals are written to one+ // shared artifact - so the walk is unfiltered, the write is+ // unfiltered, and the response is not. A proposal names two pages by+ // path, so one withheld end withholds the proposal WHOLE: a bridge+ // reported with one end missing is not a narrower true finding but a+ // false one. `scanned_candidates` is a corpus size that names nothing+ // and is the same number at every reach, so it stays as measured.+ //+ // `list` reads the artifact this branch just wrote, and asks the rule+ // over the FILE - which is why writing it unfiltered is safe here.+ // The rule is the composed one: a proposal naming another owner's+ // page is withheld whole under `integrity.owner_scope_delivery: fail`,+ // exactly as the reach rule withholds one end below local reach.+ const view = everyArtifactRefView(+ gatedOwnerScopeView(ctx.vault, ctx.agentName),+ reachView(ctx.vault, contextReach(ctx)),+ );+ return {+ vec_available: report.vecAvailable,+ ...(report.reason !== undefined ? { reason: report.reason } : {}),+ scanned_candidates: report.scannedCandidates,+ proposals: report.proposals.filter((p) => view.row(p.source, p.target)),+ artifact: join(BRAIN_PROPOSALS_REL, BRIDGE_PROPOSALS_FILE),+ };+ } finally {+ await store.close();+ }+}++// ----- brain_clusters (t_4ba927ec) --------------------------------------------++/** Graph-wide community detection with materialized cluster notes. */+export async function toolBrainClusters(+ ctx: ServerContext,+ args: Record<string, unknown>,+ onProgress?: ProgressSink,+): Promise<Record<string, unknown>> {+ const op = args["operation"];+ if (op !== "run" && op !== "list") {+ throw unknownOperationError("brain_clusters: operation must be run|list");+ }+ if (op === "list") {+ const vault = laneVault(ctx);+ const dir = join(vault, BRAIN_CLUSTERS_REL);+ if (!lanePageExists(vault, dir)) return { clusters: [] };+ // Root closure: a directory listing by path, outside the three read+ // roots, so the rule is asked per page here. A withheld cluster is+ // dropped and nothing counts it - the caller cannot tell this listing+ // from one over a vault that never held the page.+ const visible = laneVisible(ctx, vault);+ const clusters = listLaneFiles(vault, dir)+ .map((f) => {+ const rel = join(BRAIN_CLUSTERS_REL, f);+ if (!visible(rel)) return null;+ const [meta] = parseLanePage(vault, join(dir, f));+ return meta["kind"] === "brain-cluster"+ ? {+ path: rel,+ cluster: String(meta["cluster"] ?? ""),+ size: Number(meta["size"] ?? 0),+ density: Number(meta["density"] ?? 0),+ generated_at: String(meta["generated_at"] ?? ""),+ }+ : null;+ })+ .filter((c) => c !== null);+ return { clusters };+ }+ const minSize = args["min_size"];+ if (minSize !== undefined && (!Number.isInteger(minSize) || (minSize as number) < 2)) {+ throw new MCPError(INVALID_PARAMS, "brain_clusters run: min_size must be an integer >= 2");+ }+ const batchSize = args["batch_size"];+ if (batchSize !== undefined && (!Number.isInteger(batchSize) || (batchSize as number) < 1)) {+ throw new MCPError(INVALID_PARAMS, "brain_clusters run: batch_size must be an integer >= 1");+ }+ const searchConfig = resolveSearchConfig({+ vault: ctx.vault,+ configPath: ctx.configPath ?? undefined,+ });+ if (!existsSync(searchConfig.dbPath)) {+ return { communities: [], reason: "index not built" };+ }+ const store = await Store.open(searchConfig, { mode: "read" });+ const now = new Date();+ try {+ const communities = detectCommunities(store, {+ ...(minSize !== undefined ? { minSize: minSize as number } : {}),+ safeguard: toolSafeguard(ctx, OPERATION.clusters),+ ...(onProgress ? { onProgress } : {}),+ });+ const materialized = materializeClusterNotes(ctx.vault, communities, {+ store,+ now,+ ...(batchSize !== undefined ? { batchSize: batchSize as number } : {}),+ });+ try {+ appendMetric(ctx.vault, {+ surface: "communities",+ runAt: isoSecond(now),+ payload: {+ communities: communities.length,+ sizes: communities.map((c) => c.size),+ written: materialized.written.length,+ removed: materialized.removed.length,+ ...(materialized.batches+ ? {+ batches: materialized.batches.length,+ failed_batches: materialized.batches.filter((b) => b.error !== undefined).length,+ }+ : {}),+ },+ });+ } catch {+ // Metrics are observability, not correctness.+ }+ // A community is reported by the pages it contains: `members` are+ // vault-relative paths, `id` is derived from the seed page's path,+ // and the materialised `written` note is named after the same seed+ // (a-label-is-not-a-boundary, U3). A community is dropped WHOLE+ // rather than trimmed - its `size` and `density` describe the+ // subgraph the detector measured, so a community of seven reported+ // as four is not a narrower true finding, it is a false one, and the+ // same argument `brain_health` makes about a batch-inflation burst.+ //+ // Detection and materialisation stay vault-wide: clustering the+ // visible half of a link graph would produce different communities+ // for every caller and write them over each other. This filters what+ // the CALLER is told, which is the boundary the gate declares.+ // Both rules, ANDed: a community naming a page EITHER rule withholds+ // is dropped whole. The reserved-token half arrived with the read+ // roots; the argument above for dropping rather than trimming is the+ // same for it, and detection stays vault-wide for the same reason -+ // clustering the visible half of a link graph would produce different+ // communities per caller and write them over each other.+ const view = everyArtifactRefView(+ gatedOwnerScopeView(ctx.vault, ctx.agentName),+ reachView(ctx.vault, contextReach(ctx)),+ );+ const visible = view.keep(communities, (c) => c.members.map((m) => m.path));+ // `written` / `removed` are the cluster NOTES, and a cluster note is+ // named `cluster-<community id>.md` after the seed page - so its own+ // frontmatter carries no owner while its filename spells one. They+ // are therefore filtered by which community they belong to, through+ // the materialiser's own naming rule, not by asking the note file+ // what it owns.+ const visibleNotes = new Set(visible.map((c) => `Brain/clusters/cluster-${c.id}.md`));+ return {+ communities: visible.map((c) => ({+ id: c.id,+ size: c.size,+ density: c.density,+ members: c.members.map((m) => m.path),+ })),+ written: materialized.written.filter((p) => visibleNotes.has(p)),+ // A removal names a community that no longer exists, so there is+ // no surviving membership to ask about. Whenever ANY rule is live+ // the list is withheld whole: it is the one field here whose+ // subject cannot be resolved, and a `removed` entry naming a hidden+ // seed is the same disclosure as a `written` one.+ removed: view.filtersNothing ? materialized.removed : [],+ // The batches are withheld whole whenever ANY rule is live - the+ // same rule the top-level `removed` follows. A batch's very+ // EXISTENCE is the disclosure: rebuilding them over the visible+ // communities would still count hidden ones through the offsets+ // and the renumbered indexes (with `batch_size: 2` and the order+ // visible, hidden, visible, hidden, two batches would appear where+ // an unrestricted vault shows one), and a raw `error` names a+ // `cluster-<community id>.md` file - the hidden seed's path.+ ...(materialized.batches ? { batches: view.filtersNothing ? materialized.batches : [] } : {}),+ };+ } finally {+ await store.close();+ }+}++// ----- brain_benchmark (t_e2215d49) -------------------------------------------++/**+ * Per-MOC coverage audit. Classifies cluster members into+ * `wellCovered` / `fragile` / `candidateMissing` and surfaces a+ * `suggestedNext` candidate. MOC detection is purely structural -+ * outbound link count + link density.+ */+export async function toolBrainMocAudit(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const idRaw = args["id"];+ if (typeof idRaw !== "string" || idRaw.trim().length === 0) {+ throw new MCPError(INVALID_PARAMS, "brain_moc_audit: id must be a non-empty string");+ }+ const targetId = normaliseWikilinkTarget(idRaw);+ try {+ // `fragile[].id`, `bodyChars` and the exists-vs-missing verdict all+ // describe cluster members; unscoped they described another owner's+ // (a-label-is-not-a-boundary, U3, recon C4).+ const report = auditMoc(ctx.vault, targetId, {+ ownerScope: gatedOwnerScopeView(ctx.vault, ctx.agentName).scope,+ readable: readableAtContextReach(ctx),+ withholdsPrivate: contextReach(ctx) !== TRANSPORT_REACH.local,+ });+ return {+ vault_path: vaultPathField(ctx),+ hub_id: report.hubId,+ outbound_count: report.outboundCount,+ well_covered: report.wellCovered,+ fragile: report.fragile,+ candidate_missing: report.candidateMissing,+ ...(report.suggestedNext ? { suggested_next: report.suggestedNext } : {}),+ };+ } catch (err) {+ if (err instanceof MocAuditError) {+ throw new MCPError(INVALID_PARAMS, `brain_moc_audit: ${err.message}`);+ }+ throw err;+ }+}++// ----- Temporal subsystem MCP wrappers (v0.10.18) --------------------------++export async function toolBrainDeepSynthesis(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const topic = coerceStr(args, "topic", true)!;+ const limit = coercePositiveInteger("brain_deep_synthesis", "limit", args["limit"]) ?? 30;+ if (limit > 100) {+ throw new MCPError(INVALID_PARAMS, "brain_deep_synthesis: limit must be at most 100");+ }+ const enqueue = coerceBool(args, "triggers");+ const now = new Date();+ const searchConfig = resolveSearchConfig({+ vault: ctx.vault,+ configPath: ctx.configPath ?? undefined,+ });+ const agentScope = coerceAgentScope(ctx, args, false);+ const report = await deepSynthesis(searchConfig, topic, {+ now,+ limit,+ ...(agentScope !== undefined ? { agentScope } : {}),+ transportReach: contextReach(ctx),+ });+ let triggersCreated: number | undefined;+ if (enqueue) {+ const result = createTriggers(ctx.vault, synthesisCandidates(report), {+ now,+ cooldownDays: resolveTriggerCooldownDays(ctx.configPath ?? undefined),+ });+ triggersCreated = result.created.length;+ }+ return {+ topic: report.topic,+ generated_at: report.generatedAt,+ checked: report.checked,+ notes: report.notes,+ agreements: report.agreements,+ contradictions: report.contradictions,+ stale_claims: report.staleClaims.map((s) => ({+ path: s.path,+ age_days: s.ageDays,+ superseded_by: s.supersededBy,+ })),+ gaps: report.gaps,+ contaminated: report.contaminated,+ strongest_objection: report.strongestObjection+ ? {+ basis: report.strongestObjection.basis,+ statement: report.strongestObjection.statement,+ source_artifacts: report.strongestObjection.sourceArtifacts,+ }+ : null,+ ...synthesisFindingsJson(report),+ ...(triggersCreated !== undefined ? { triggers_created: triggersCreated } : {}),+ };+}++// ----- brain_diarize (subject diarization, t_28ba3fc4) ----------------------++export async function toolBrainDiarize(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const query = coerceStr(args, "entity", true)!;+ const category = coerceStr(args, "category", false);+ try {+ const report = diarize(+ ctx.vault,+ { query, ...(category ? { category } : {}) },+ // The envelope's candidate list names Brain artifact ids, so it is+ // filtered through the same gated view every other report surface+ // here uses - an unscoped list would publish another owner's+ // preference ids as citation targets.+ // A page the caller may not read at its reach is withheld from the+ // candidates exactly as an absent one.+ {+ now: new Date(),+ ownerScope: gatedOwnerScopeView(ctx.vault, ctx.agentName).scope,+ readable: readableAtContextReach(ctx),+ },+ );+ return {+ entity_id: report.entityId,+ entity_name: report.entityName,+ category: report.category,+ generated_at: report.generatedAt,+ document_set: report.documentSet,+ stated_vs_evidenced: report.statedVsEvidenced.map((l) => ({+ kind: l.kind,+ statement: l.statement,+ evidence: l.evidence,+ evidence_frequency: l.evidenceFrequency,+ last_evidenced_at: l.lastEvidencedAt,+ })),+ excluded_line_count: report.excludedLineCount,+ skeleton: report.skeleton,+ llm_step: report.llmStep,+ };+ } catch (err) {+ if (err instanceof DiarizationError) {+ throw new MCPError(INVALID_PARAMS, `brain_diarize: ${err.message}`);+ }+ throw err;+ }+}++// ----- brain_idea_discovery (Workspace Insight Suite) ------------------------++export function toolBrainIdeaDiscovery(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Record<string, unknown> {+ const cap = coercePositiveInteger("brain_idea_discovery", "cap", args["cap"]) ?? 5;+ if (cap > 50) {+ throw new MCPError(INVALID_PARAMS, "brain_idea_discovery: cap must be at most 50");+ }+ const enqueue = coerceBool(args, "triggers");+ const now = new Date();+ // `source_artifacts` are vault-relative artifact paths and the `reason`+ // sentence spells one out, so an unscoped ranking named another owner's+ // notes (a-label-is-not-a-boundary, U3). Filtered BEFORE the trigger+ // pass so a hidden artifact cannot be enqueued either.+ const view = gatedOwnerScopeView(ctx.vault, ctx.agentName);+ // A page the caller may not read at its reach is left out of the walk+ // itself, before the ranking and the cap, so the list is the one a vault+ // without that page would give.+ const ideas = view.keep(+ discoverIdeas(ctx.vault, {+ now,+ cap,+ include: readableAtContextReach(ctx),+ withholdsPrivate: contextReach(ctx) !== TRANSPORT_REACH.local,+ }),+ (i) => i.sourceArtifacts,+ );+ let triggersCreated: number | undefined;+ if (enqueue) {+ const result = createTriggers(ctx.vault, ideaCandidates(ideas), {+ now,+ cooldownDays: resolveTriggerCooldownDays(ctx.configPath ?? undefined),+ });+ triggersCreated = result.created.length;+ }+ return {+ ideas: ideas.map((idea) => ({+ kind: idea.kind,+ title: idea.title,+ reason: idea.reason,+ score: idea.score,+ source_artifacts: idea.sourceArtifacts,+ })),+ ...(triggersCreated !== undefined ? { triggers_created: triggersCreated } : {}),+ };+}diff --git a/src/mcp/brain/knowledge-tools.ts b/src/mcp/brain/knowledge-tools.tsindex 23b786c8..109c8bf2 100644--- a/src/mcp/brain/knowledge-tools.ts+++ b/src/mcp/brain/knowledge-tools.ts@@ -6,1266 +6,26 @@* BRAIN_TOOLS surface.*/-import { join } from "node:path";-import { existsSync } from "node:fs";-import { resolveAgentName, resolveTriggerCooldownDays } from "../../core/config.ts";-import { resolveSearchConfig } from "../../core/search/index.ts";-import { Store } from "../../core/search/store.ts";-import { loadSchemaPack } from "../../core/brain/schema-pack.ts";-import {- acceptBridge,- bridgePairKey,- discoverBridges,- dismissBridge,- readDismissedBridges,- writeBridgeProposals,-} from "../../core/brain/link-graph/bridge-discovery.ts";-import {- detectCommunities,- materializeClusterNotes,-} from "../../core/brain/link-graph/communities.ts";-import { appendMetric } from "../../core/brain/metrics.ts";-import { OPERATION } from "../../core/brain/safeguard.ts";-import type { ProgressSink } from "../../core/brain/progress.ts";-import { createTriggers } from "../../core/brain/triggers/store.ts";-import {- deepSynthesis,- synthesisCandidates,- synthesisFindingsJson,-} from "../../core/brain/deep-synthesis.ts";-import { diarize, DiarizationError } from "../../core/brain/diarization.ts";-import { discoverIdeas, ideaCandidates } from "../../core/brain/idea-discovery.ts";-import { auditMoc, MocAuditError } from "../../core/brain/link-graph/moc-audit.ts";-import { reachView } from "../../core/brain/reach-view.ts";-import { everyArtifactRefView, type ArtifactRefView } from "../../core/brain/artifact-ref-view.ts";-import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";-import { recordRefs } from "../../core/brain/log-events-at-reach.ts";-import { normaliseWikilinkTarget } from "../../core/brain/wikilink.ts";-import { deliveryView } from "./reach-events.ts";-import { isoSecond } from "../../core/brain/time.ts";-import { normalizeAgentArgument } from "../../core/agent-identity.ts";-import { normalizeEntityName } from "../../core/brain/entities/canonical.ts";-import { listEntities } from "../../core/brain/entities/registry.ts";-import {- ENTITY_STATUS_SCOPE,- entityStatusInScope,-} from "../../core/brain/entities/status-scope.ts";-import {- appendStatedClaims,- StatedClaimsRefusal,- type StatedClaim,-} from "../../core/brain/truth/stated-claims.ts";-import { listDeadEnds, recordDeadEnd } from "../../core/brain/dead-ends.ts";-import { lanePath, laneVault } from "./lane-vault.ts";-import { buildCodegraphReport, type CodegraphReport } from "../../core/partner/codegraph-report.ts";-import { toolPath } from "./device-path.ts";-import { buildForesight, FORESIGHT_HORIZON_DAYS } from "../../core/brain/temporal/foresight.ts";-import { aggregateQuantities } from "../../core/brain/truth/aggregate.ts";-import { detectAgentCollisions } from "../../core/brain/truth/collision.ts";-import { computeTruthStateWithConflicts } from "../../core/brain/truth/conflicts.ts";-import {- appendClaimEvent,- ClaimWindowRefusal,- readClaimEvents,-} from "../../core/brain/truth/store.ts";-import { claimEventLimit, matchClaimEvents } from "../../core/brain/truth/events-window.ts";-import {- loadClaimProvenanceIndex,- resolveClaimProvenanceFromIndex,- type ClaimProvenance,- type ClaimProvenanceOptions,-} from "../../core/brain/truth/claim-provenance.ts";-import type { ClaimEvent } from "../../core/brain/truth/types.ts";-import {- allClaims,- buildClaimGraph,- currentTruth,- loadClaimGraph,- rebuildClaimGraph,- truthAt,- whatContests,- whatReplaced,- type ClaimGraph,- type ClaimNode,-} from "../../core/brain/claim-graph.ts";-import { INVALID_PARAMS, MCPError } from "../protocol.ts";-import { contextReach, contextVault } from "../tool-contract.ts";-import { TRANSPORT_REACH, type TransportReach } from "../../core/graph/transport-reach.ts";-import type { ServerContext, ToolDefinition } from "../tool-contract.ts";-import { vaultPathField } from "../vault-path-field.ts";+import type { ToolDefinition } from "../tool-contract.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";+import { AGENT_SCOPE_SCHEMA } from "../coerce.ts";+import { toolBrainClaims } from "./knowledge-claim-tools.ts";import {- AGENT_SCOPE_SCHEMA,- coerceAgentScope,- coerceStr,- coerceBool,- unknownOperationError,-} from "../coerce.ts";-import { coercePositiveInteger, toolSafeguard, vaultRelativeSafe } from "./shared.ts";-import { isOperatorRuleItem, isRuleOnlyInjection } from "./pack-tools.ts";-import { resolveTimeBounds } from "./time-bounds.ts";+ toolBrainCodegraphReport,+ toolBrainDeadEnds,+ toolBrainTruth,+} from "./knowledge-truth-tools.ts";import {- lanePageExists,- lanePagesInStore,- listLaneFiles,- parseLanePage,-} from "../../core/store/lane-pages.ts";-import { readableAtContextReach, readableAtContextReachOrUndefined } from "./reach-readable.ts";--/**- * Who may see a lane page by its vault-relative path: the reach view of- * the vault's files on an unswitched machine, the store-aware predicate- * (the page's record fields) once switched or with no vault.- */-function laneVisible(ctx: ServerContext, vault: string): (rel: string) => boolean {- if (lanePagesInStore(vault)) return readableAtContextReach(ctx);- const view = reachView(vault, contextReach(ctx));- return (rel) => view.visible(rel);-}--/**- * Vault-relative locations these two handlers read BY PATH, rather than- * through one of the three read roots. Named here because each was- * spelled twice - once to build the absolute path and once to report the- * relative one - and the two spellings had to agree for the boundary- * check below to be asking about the page it was returning.- */-const BRAIN_CLUSTERS_REL = "Brain/clusters";-const BRAIN_PROPOSALS_REL = "Brain/proposals";-const BRIDGE_PROPOSALS_FILE = "bridges.md";--/** Forward-looking projection envelope; read-only fold. */-function toolBrainForesight(- ctx: ServerContext,- args: Record<string, unknown>,-): Record<string, unknown> {- const horizonRaw = args["horizon_days"];- let horizonDays = FORESIGHT_HORIZON_DAYS;- if (horizonRaw !== undefined && horizonRaw !== null) {- if (typeof horizonRaw !== "number" || !Number.isInteger(horizonRaw) || horizonRaw < 1) {- throw new MCPError(- INVALID_PARAMS,- "brain_foresight: horizon_days must be a positive integer",- );- }- horizonDays = horizonRaw;- }- return { ...buildForesight(ctx.vault, { now: new Date(), horizonDays }) };-}--// ----- brain_labels (t_7a41f42d) -----------------------------------------------/**- * Bridge discovery over the vec index: discover regenerates the- * reviewable proposals artifact, accept writes one related wikilink,- * dismiss persists a pair suppression, list reads the artifact back.- */-async function toolBrainBridges(- ctx: ServerContext,- args: Record<string, unknown>,- onProgress?: ProgressSink,-): Promise<Record<string, unknown>> {- const op = args["operation"];- if (op !== "discover" && op !== "list" && op !== "accept" && op !== "dismiss") {- throw unknownOperationError("brain_bridges: operation must be discover|list|accept|dismiss");- }- if (op === "accept" || op === "dismiss") {- const source = args["source"];- const target = args["target"];- if (typeof source !== "string" || source.trim() === "") {- throw new MCPError(- INVALID_PARAMS,- `brain_bridges ${op}: source must be a vault-relative path`,- );- }- if (typeof target !== "string" || target.trim() === "") {- throw new MCPError(- INVALID_PARAMS,- `brain_bridges ${op}: target must be a vault-relative path`,- );- }- if (op === "dismiss") {- return {- dismissed: bridgePairKey(source, target),- added: dismissBridge(ctx.vault, source, target),- };- }- try {- const pack = loadSchemaPack(ctx.vault);- return { ...acceptBridge(ctx.vault, source, target, { pack }), source, target };- } catch (exc) {- const message = (exc as Error).message ?? String(exc);- if (/outside the vault|does not exist|link constraint/.test(message)) {- throw new MCPError(INVALID_PARAMS, `brain_bridges accept: ${message}`);- }- throw exc;- }- }- if (op === "list") {- const vault = laneVault(ctx);- const rel = join(BRAIN_PROPOSALS_REL, BRIDGE_PROPOSALS_FILE);- const path = join(vault, rel);- // Root closure: this reads a vault page BY PATH without going through- // one of the three read roots, so it asks the rule here. A reserved- // proposals page answers exactly as an absent one - the same shape- // the by-path read primitives hold. A lane page (a store record once- // switched) is read through the lane page store.- if (!lanePageExists(vault, path) || !laneVisible(ctx, vault)(rel)) {- return { exists: false, proposals: 0 };- }- const [meta] = parseLanePage(vault, path);- return {- exists: true,- path: rel,- generated_at: meta["generated_at"] ?? null,- proposals: Number(meta["proposals"] ?? 0),- };- }- // discover- const max = args["max"];- if (max !== undefined && (!Number.isInteger(max) || (max as number) < 1)) {- throw new MCPError(INVALID_PARAMS, "brain_bridges discover: max must be a positive integer");- }- const minSimilarity = args["min_similarity"];- if (- minSimilarity !== undefined &&- (typeof minSimilarity !== "number" || minSimilarity <= 0 || minSimilarity > 1)- ) {- throw new MCPError(INVALID_PARAMS, "brain_bridges discover: min_similarity must be in (0, 1]");- }- const searchConfig = resolveSearchConfig({- vault: ctx.vault,- configPath: ctx.configPath ?? undefined,- });- if (!existsSync(searchConfig.dbPath)) {- return { vec_available: false, proposals: [], reason: "index not built" };- }- const store = await Store.open(searchConfig, { mode: "read" });- const now = new Date();- try {- const dismissed = readDismissedBridges(ctx.vault);- const report = discoverBridges(store, {- ...(max !== undefined ? { maxProposals: max as number } : {}),- ...(minSimilarity !== undefined ? { minSimilarity } : {}),- dismissed,- safeguard: toolSafeguard(ctx, OPERATION.bridges),- ...(onProgress ? { onProgress } : {}),- });- writeBridgeProposals(ctx.vault, report, { now });- try {- appendMetric(ctx.vault, {- surface: "bridge_discovery",- runAt: isoSecond(now),- payload: {- proposals: report.proposals.length,- scanned_candidates: report.scannedCandidates,- vec_available: report.vecAvailable,- dismissed_total: dismissed.size,- },- });- } catch {- // Metrics are observability, not correctness.- }- // Root closure over what the CALLER is told. Detection stays- // vault-wide - a bridge proposed from the visible half of a link- // graph would differ per caller and the proposals are written to one- // shared artifact - so the walk is unfiltered, the write is- // unfiltered, and the response is not. A proposal names two pages by- // path, so one withheld end withholds the proposal WHOLE: a bridge- // reported with one end missing is not a narrower true finding but a- // false one. `scanned_candidates` is a corpus size that names nothing- // and is the same number at every reach, so it stays as measured.- //- // `list` reads the artifact this branch just wrote, and asks the rule- // over the FILE - which is why writing it unfiltered is safe here.- const view = reachView(ctx.vault, contextReach(ctx));- return {- vec_available: report.vecAvailable,- ...(report.reason !== undefined ? { reason: report.reason } : {}),- scanned_candidates: report.scannedCandidates,- proposals: report.proposals.filter((p) => view.row(p.source, p.target)),- artifact: join(BRAIN_PROPOSALS_REL, BRIDGE_PROPOSALS_FILE),- };- } finally {- await store.close();- }-}--// ----- brain_clusters (t_4ba927ec) ----------------------------------------------/** Graph-wide community detection with materialized cluster notes. */-async function toolBrainClusters(- ctx: ServerContext,- args: Record<string, unknown>,- onProgress?: ProgressSink,-): Promise<Record<string, unknown>> {- const op = args["operation"];- if (op !== "run" && op !== "list") {- throw unknownOperationError("brain_clusters: operation must be run|list");- }- if (op === "list") {- const vault = laneVault(ctx);- const dir = join(vault, BRAIN_CLUSTERS_REL);- if (!lanePageExists(vault, dir)) return { clusters: [] };- // Root closure: a directory listing by path, outside the three read- // roots, so the rule is asked per page here. A withheld cluster is- // dropped and nothing counts it - the caller cannot tell this listing- // from one over a vault that never held the page.- const visible = laneVisible(ctx, vault);- const clusters = listLaneFiles(vault, dir)- .map((f) => {- const rel = join(BRAIN_CLUSTERS_REL, f);- if (!visible(rel)) return null;- const [meta] = parseLanePage(vault, join(dir, f));- return meta["kind"] === "brain-cluster"- ? {- path: rel,- cluster: String(meta["cluster"] ?? ""),- size: Number(meta["size"] ?? 0),- density: Number(meta["density"] ?? 0),- generated_at: String(meta["generated_at"] ?? ""),- }- : null;- })- .filter((c) => c !== null);- return { clusters };- }- const minSize = args["min_size"];- if (minSize !== undefined && (!Number.isInteger(minSize) || (minSize as number) < 2)) {- throw new MCPError(INVALID_PARAMS, "brain_clusters run: min_size must be an integer >= 2");- }- const batchSize = args["batch_size"];- if (batchSize !== undefined && (!Number.isInteger(batchSize) || (batchSize as number) < 1)) {- throw new MCPError(INVALID_PARAMS, "brain_clusters run: batch_size must be an integer >= 1");- }- const searchConfig = resolveSearchConfig({- vault: ctx.vault,- configPath: ctx.configPath ?? undefined,- });- if (!existsSync(searchConfig.dbPath)) {- return { communities: [], reason: "index not built" };- }- const store = await Store.open(searchConfig, { mode: "read" });- const now = new Date();- try {- const communities = detectCommunities(store, {- ...(minSize !== undefined ? { minSize: minSize as number } : {}),- safeguard: toolSafeguard(ctx, OPERATION.clusters),- ...(onProgress ? { onProgress } : {}),- });- const materialized = materializeClusterNotes(ctx.vault, communities, {- store,- now,- ...(batchSize !== undefined ? { batchSize: batchSize as number } : {}),- });- try {- appendMetric(ctx.vault, {- surface: "communities",- runAt: isoSecond(now),- payload: {- communities: communities.length,- sizes: communities.map((c) => c.size),- written: materialized.written.length,- removed: materialized.removed.length,- ...(materialized.batches- ? {- batches: materialized.batches.length,- failed_batches: materialized.batches.filter((b) => b.error !== undefined).length,- }- : {}),- },- });- } catch {- // Metrics are observability, not correctness.- }- // A community is reported by the pages it contains: `members` are- // vault-relative paths, `id` is derived from the seed page's path,- // and the materialised `written` note is named after the same seed- // (a-label-is-not-a-boundary, U3). A community is dropped WHOLE- // rather than trimmed - its `size` and `density` describe the- // subgraph the detector measured, so a community of seven reported- // as four is not a narrower true finding, it is a false one, and the- // same argument `brain_health` makes about a batch-inflation burst.- //- // Detection and materialisation stay vault-wide: clustering the- // visible half of a link graph would produce different communities- // for every caller and write them over each other. This filters what- // the CALLER is told, which is the boundary the gate declares.- // Both rules, ANDed: a community naming a page EITHER rule withholds- // is dropped whole. The reserved-token half arrived with the read- // roots; the argument above for dropping rather than trimming is the- // same for it, and detection stays vault-wide for the same reason -- // clustering the visible half of a link graph would produce different- // communities per caller and write them over each other.- const view = everyArtifactRefView(- gatedOwnerScopeView(ctx.vault, ctx.agentName),- reachView(ctx.vault, contextReach(ctx)),- );- const visible = view.keep(communities, (c) => c.members.map((m) => m.path));- // `written` / `removed` are the cluster NOTES, and a cluster note is- // named `cluster-<community id>.md` after the seed page - so its own- // frontmatter carries no owner while its filename spells one. They- // are therefore filtered by which community they belong to, through- // the materialiser's own naming rule, not by asking the note file- // what it owns.- const visibleNotes = new Set(visible.map((c) => `Brain/clusters/cluster-${c.id}.md`));- return {- communities: visible.map((c) => ({- id: c.id,- size: c.size,- density: c.density,- members: c.members.map((m) => m.path),- })),- written: materialized.written.filter((p) => visibleNotes.has(p)),- // A removal names a community that no longer exists, so there is- // no surviving membership to ask about. Whenever ANY rule is live- // the list is withheld whole: it is the one field here whose- // subject cannot be resolved, and a `removed` entry naming a hidden- // seed is the same disclosure as a `written` one.- removed: view.filtersNothing ? materialized.removed : [],- ...(materialized.batches ? { batches: materialized.batches } : {}),- };- } finally {- await store.close();- }-}--// ----- brain_benchmark (t_e2215d49) ---------------------------------------------/**- * Per-MOC coverage audit. Classifies cluster members into- * `wellCovered` / `fragile` / `candidateMissing` and surfaces a- * `suggestedNext` candidate. MOC detection is purely structural -- * outbound link count + link density.- */-async function toolBrainMocAudit(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const idRaw = args["id"];- if (typeof idRaw !== "string" || idRaw.trim().length === 0) {- throw new MCPError(INVALID_PARAMS, "brain_moc_audit: id must be a non-empty string");- }- const targetId = normaliseWikilinkTarget(idRaw);- try {- // `fragile[].id`, `bodyChars` and the exists-vs-missing verdict all- // describe cluster members; unscoped they described another owner's- // (a-label-is-not-a-boundary, U3, recon C4).- const report = auditMoc(ctx.vault, targetId, {- ownerScope: gatedOwnerScopeView(ctx.vault, ctx.agentName).scope,- readable: readableAtContextReach(ctx),- withholdsPrivate: contextReach(ctx) !== TRANSPORT_REACH.local,- });- return {- vault_path: vaultPathField(ctx),- hub_id: report.hubId,- outbound_count: report.outboundCount,- well_covered: report.wellCovered,- fragile: report.fragile,- candidate_missing: report.candidateMissing,- ...(report.suggestedNext ? { suggested_next: report.suggestedNext } : {}),- };- } catch (err) {- if (err instanceof MocAuditError) {- throw new MCPError(INVALID_PARAMS, `brain_moc_audit: ${err.message}`);- }- throw err;- }-}--// ----- Temporal subsystem MCP wrappers (v0.10.18) ----------------------------async function toolBrainDeepSynthesis(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const topic = coerceStr(args, "topic", true)!;- const limit = coercePositiveInteger("brain_deep_synthesis", "limit", args["limit"]) ?? 30;- if (limit > 100) {- throw new MCPError(INVALID_PARAMS, "brain_deep_synthesis: limit must be at most 100");- }- const enqueue = coerceBool(args, "triggers");- const now = new Date();- const searchConfig = resolveSearchConfig({- vault: ctx.vault,- configPath: ctx.configPath ?? undefined,- });- const agentScope = coerceAgentScope(ctx, args, false);- const report = await deepSynthesis(searchConfig, topic, {- now,- limit,- ...(agentScope !== undefined ? { agentScope } : {}),- transportReach: contextReach(ctx),- });- let triggersCreated: number | undefined;- if (enqueue) {- const result = createTriggers(ctx.vault, synthesisCandidates(report), {- now,- cooldownDays: resolveTriggerCooldownDays(ctx.configPath ?? undefined),- });- triggersCreated = result.created.length;- }- return {- topic: report.topic,- generated_at: report.generatedAt,- checked: report.checked,- notes: report.notes,- agreements: report.agreements,- contradictions: report.contradictions,- stale_claims: report.staleClaims.map((s) => ({- path: s.path,- age_days: s.ageDays,- superseded_by: s.supersededBy,- })),- gaps: report.gaps,- contaminated: report.contaminated,- strongest_objection: report.strongestObjection- ? {- basis: report.strongestObjection.basis,- statement: report.strongestObjection.statement,- source_artifacts: report.strongestObjection.sourceArtifacts,- }- : null,- ...synthesisFindingsJson(report),- ...(triggersCreated !== undefined ? { triggers_created: triggersCreated } : {}),- };-}--// ----- brain_diarize (subject diarization, t_28ba3fc4) ------------------------async function toolBrainDiarize(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const query = coerceStr(args, "entity", true)!;- const category = coerceStr(args, "category", false);- try {- const report = diarize(- ctx.vault,- { query, ...(category ? { category } : {}) },- // The envelope's candidate list names Brain artifact ids, so it is- // filtered through the same gated view every other report surface- // here uses - an unscoped list would publish another owner's- // preference ids as citation targets.- // A page the caller may not read at its reach is withheld from the- // candidates exactly as an absent one.- {- now: new Date(),- ownerScope: gatedOwnerScopeView(ctx.vault, ctx.agentName).scope,- readable: readableAtContextReach(ctx),- },- );- return {- entity_id: report.entityId,- entity_name: report.entityName,- category: report.category,- generated_at: report.generatedAt,- document_set: report.documentSet,- stated_vs_evidenced: report.statedVsEvidenced.map((l) => ({- kind: l.kind,- statement: l.statement,- evidence: l.evidence,- evidence_frequency: l.evidenceFrequency,- last_evidenced_at: l.lastEvidencedAt,- })),- excluded_line_count: report.excludedLineCount,- skeleton: report.skeleton,- llm_step: report.llmStep,- };- } catch (err) {- if (err instanceof DiarizationError) {- throw new MCPError(INVALID_PARAMS, `brain_diarize: ${err.message}`);- }- throw err;- }-}--// ----- brain_idea_discovery (Workspace Insight Suite) --------------------------function toolBrainIdeaDiscovery(- ctx: ServerContext,- args: Record<string, unknown>,-): Record<string, unknown> {- const cap = coercePositiveInteger("brain_idea_discovery", "cap", args["cap"]) ?? 5;- if (cap > 50) {- throw new MCPError(INVALID_PARAMS, "brain_idea_discovery: cap must be at most 50");- }- const enqueue = coerceBool(args, "triggers");- const now = new Date();- // `source_artifacts` are vault-relative artifact paths and the `reason`- // sentence spells one out, so an unscoped ranking named another owner's- // notes (a-label-is-not-a-boundary, U3). Filtered BEFORE the trigger- // pass so a hidden artifact cannot be enqueued either.- const view = gatedOwnerScopeView(ctx.vault, ctx.agentName);- // A page the caller may not read at its reach is left out of the walk- // itself, before the ranking and the cap, so the list is the one a vault- // without that page would give.- const ideas = view.keep(- discoverIdeas(ctx.vault, {- now,- cap,- include: readableAtContextReach(ctx),- withholdsPrivate: contextReach(ctx) !== TRANSPORT_REACH.local,- }),- (i) => i.sourceArtifacts,- );- let triggersCreated: number | undefined;- if (enqueue) {- const result = createTriggers(ctx.vault, ideaCandidates(ideas), {- now,- cooldownDays: resolveTriggerCooldownDays(ctx.configPath ?? undefined),- });- triggersCreated = result.created.length;- }- return {- ideas: ideas.map((idea) => ({- kind: idea.kind,- title: idea.title,- reason: idea.reason,- score: idea.score,- source_artifacts: idea.sourceArtifacts,- })),- ...(triggersCreated !== undefined ? { triggers_created: triggersCreated } : {}),- };-}--// ----- brain_context_pack (v0.10.15) -----------------------------------------/**- * Operator/agent surface over the entity claim ledger: ingest one- * claim, render slots/conflicts from the fold, aggregate exact-match- * quantities, report cross-agent collisions, recall a windowed slice of- * the ledger via the events operation, and commit grounded agent-stated- * claims via the state operation with per-claim anchoring verdicts. The- * read ops are pure folds over the append-only ledger.- */-function toolBrainTruth(- ctx: ServerContext,- args: Record<string, unknown>,-): Record<string, unknown> {- const op = args["operation"];- if (- op !== "ingest" &&- op !== "slots" &&- op !== "conflicts" &&- op !== "aggregate" &&- op !== "collisions" &&- op !== "events" &&- op !== "state"- ) {- throw unknownOperationError(- "brain_truth: operation must be ingest|slots|conflicts|aggregate|collisions|events|state",- );- }- const requireStr = (name: string): string => {- const value = args[name];- if (typeof value !== "string" || value.trim() === "") {- throw new MCPError(INVALID_PARAMS, `brain_truth ${op}: ${name} must be a non-empty string`);- }- return value;- };- // An optional string parameter is either a string or absent; any other- // type is refused rather than silently ignored - a mistyped bound that- // read as "no filter" would widen what the caller sees.- const optionalStr = (name: string): string | undefined => {- const value = args[name];- if (value === undefined) return undefined;- if (typeof value !== "string") {- throw new MCPError(INVALID_PARAMS, `brain_truth ${op}: ${name} must be a string`);- }- return value;- };-- if (op === "ingest") {- const quantityValue = args["quantity_value"];- if (- (quantityValue === undefined || quantityValue === null) &&- (typeof args["quantity_unit"] === "string" || typeof args["quantity_action"] === "string")- ) {- throw new MCPError(- INVALID_PARAMS,- "brain_truth ingest: quantity_value is required when quantity_unit or quantity_action is provided",- );- }- let quantity: { value: number; unit: string | null; action: string | null } | undefined;- if (quantityValue !== undefined && quantityValue !== null) {- if (typeof quantityValue !== "number" || !Number.isFinite(quantityValue)) {- throw new MCPError(INVALID_PARAMS, "brain_truth ingest: quantity_value must be a number");- }- quantity = {- value: quantityValue,- unit: typeof args["quantity_unit"] === "string" ? (args["quantity_unit"] as string) : null,- action:- typeof args["quantity_action"] === "string" ? (args["quantity_action"] as string) : null,- };- }- const agentArg = args["agent"];- const agent =- normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??- resolveAgentName(ctx.configPath ?? undefined);- // Declared optional validity fields (design decision 3): explicit- // input wins outright, bound by bound, over what ingest resolves- // from the source record's frontmatter; absent fields leave every- // line byte-identical to the pre-window ledger.- const validFrom = optionalStr("valid_from");- const validUntil = optionalStr("valid_until");- // The source's window resolves at the CALLER's reach: a source page- // the caller cannot read is treated exactly like an absent one -- // windowless claim, no validity keys in the response, no signal- // distinguishing withheld from absent. Without this gate the ingest- // response would read a withheld page's validity frontmatter back- // and triple as an existence oracle. (The CLI verb runs at operator- // reach and passes no gate.)- const readable = readableAtContextReachOrUndefined(ctx);- // The store's window refusal is strict by design; here it is a- // mistyped parameter, so it answers as the same failure class as the- // sibling mistyped inputs (entity, since/until, limit) - typed- // INVALID_PARAMS, never an internal error.- let result;- try {- result = appendClaimEvent(- ctx.vault,- {- ts: isoSecond(new Date()),- agent,- entity: requireStr("entity"),- aspect: requireStr("aspect"),- value: requireStr("value"),- ...(quantity !== undefined ? { valueKind: "quantity" as const, quantity } : {}),- ...(validFrom !== undefined ? { validFrom } : {}),- ...(validUntil !== undefined ? { validUntil } : {}),- source: requireStr("source"),- },- readable !== undefined ? { readableSource: readable } : {},- );- } catch (exc) {- if (exc instanceof ClaimWindowRefusal) {- throw new MCPError(INVALID_PARAMS, `brain_truth ingest: ${(exc as Error).message}`);- }- throw exc;- }- return {- ok: true,- entity: result.event.entity,- aspect: result.event.aspect,- path: result.path,- ...(result.event.validFrom !== undefined ? { valid_from: result.event.validFrom } : {}),- ...(result.event.validUntil !== undefined ? { valid_until: result.event.validUntil } : {}),- };- }-- // Windowed recall over the ledger (truth-correctable-time-aware,- // Task 8): the response body is the shared claimEventsReport, so the- // CLI subcommand answers byte-identically at the same query.- if (op === "events") {- const bounds = resolveTimeBounds(optionalStr("since"), optionalStr("until"));- let limit: number;- try {- limit = claimEventLimit(args["limit"]);- } catch (exc) {- throw new MCPError(INVALID_PARAMS, `brain_truth events: ${(exc as Error).message}`);- }- return claimEventsReport(ctx.vault, ctx.agentName, contextReach(ctx), {- entity: optionalStr("entity"),- sinceMs: bounds.sinceMs,- untilMs: bounds.untilMs,- limit,- });- }-- // Grounded agent-stated claims (truth-correctable-time-aware, Task 8),- // through lane 1's grounded-claim core: the payload boundary refuses- // WHOLE calls (unknown relation, missing text, missing source, empty- // agent, malformed ts) before ANY write, and anchoring verdicts are- // per claim - the one- // partial-commit lane in this subsystem, safe because each event is an- // independent append in an append-only ledger and the response reports- // exactly what landed.- if (op === "state") {- const claims = args["claims"];- if (!Array.isArray(claims) || claims.length === 0) {- throw new MCPError(INVALID_PARAMS, "brain_truth state: claims must be a non-empty array");- }- const stated = claims.map((raw, index): StatedClaim => {- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {- throw new MCPError(INVALID_PARAMS, `brain_truth state: claims[${index}] must be an object`);- }- const claim = raw as Record<string, unknown>;- // Type-shaped fields only; an empty subject or object is not a- // refusal here but a per-claim ungrounded verdict downstream.- const readField = (name: string): string => {- const value = claim[name];- if (typeof value !== "string") {- throw new MCPError(- INVALID_PARAMS,- `brain_truth state: claims[${index}].${name} must be a string`,- );- }- return value;- };- return {- subject: readField("subject"),- relation: readField("relation"),- object: readField("object"),- };- });- const agentArg = args["agent"];- if (agentArg !== undefined && typeof agentArg !== "string") {- throw new MCPError(INVALID_PARAMS, "brain_truth state: agent must be a string");- }- const agent =- normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??- resolveAgentName(ctx.configPath ?? undefined);- // Sample id (answer-trust, task B4): an optional call-level id naming- // the recall/context-pack quality-sample these claims were stated- // against. A non-string type is refused here as a mistyped parameter;- // a blank string flows to the payload boundary's named refusal below- // (mapped to the same failure class), so an empty id is never coerced- // to an absent one. Committed events echo the id verbatim.- const sampleId = optionalStr("sample_id");- // The source's frontmatter window resolves at the CALLER's reach,- // exactly as ingest gates it: a withheld source freezes a windowless- // event and the committed rows carry no validity keys, so the state- // response reads a withheld page's frontmatter no more than an- // absent one's.- const readable = readableAtContextReachOrUndefined(ctx);- try {- const outcome = appendStatedClaims(- ctx.vault,- {- claims: stated,- text: requireStr("text"),- agent,- ts: isoSecond(new Date()),- source: requireStr("source"),- ...(sampleId !== undefined ? { sampleId } : {}),- },- {- entities: statedClaimEntities(ctx.vault),- ...(ctx.configPath !== null ? { configPath: ctx.configPath } : {}),- ...(readable !== undefined ? { readableSource: readable } : {}),- },- );- return {- ok: true,- operation: "state",- committed: outcome.committed.map((result) => ({ ...result.event })),- ungrounded: outcome.ungrounded.map(({ claim, reasons }) => ({- subject: claim.subject,- relation: claim.relation,- object: claim.object,- reasons,- })),- };- } catch (exc) {- // Both refusal channels are mistyped-input refusals - the payload- // boundary's, and the store's when the stated claim's window- // resolves from the source record's frontmatter and inverts there- // - so both answer as the same failure class the ingest operation- // maps, never an internal error.- if (exc instanceof StatedClaimsRefusal || exc instanceof ClaimWindowRefusal) {- throw new MCPError(INVALID_PARAMS, `brain_truth state: ${exc.message}`);- }- throw exc;- }- }-- const events = readClaimEvents(ctx.vault).events;- if (op === "slots" || op === "conflicts") {- const state = computeTruthStateWithConflicts(events);- if (op === "conflicts") return { events: state.events, conflicts: state.conflicts };- const entityFilter = args["entity"];- const slots =- typeof entityFilter === "string" && entityFilter.trim() !== ""- ? state.slots.filter((s) => s.entity === normalizeEntityName(entityFilter))- : state.slots;- return { events: state.events, slots };- }- if (op === "aggregate") {- const state = computeTruthStateWithConflicts(events);- return {- ...aggregateQuantities(state.slots, {- ...(typeof args["action"] === "string" ? { action: args["action"] as string } : {}),- unit: typeof args["unit"] === "string" ? (args["unit"] as string) : null,- ...(typeof args["entity"] === "string" ? { entity: args["entity"] as string } : {}),- }),- };- }- return {- collisions: detectAgentCollisions(events, { now: new Date() }),- };-}--// ----- brain_concept_synthesis (v0.10.17) ------------------------------------/**- * Negative-knowledge registry: record one tried-and-failed approach- * or list the bounded active set, newest first.- */-function toolBrainDeadEnds(- ctx: ServerContext,- args: Record<string, unknown>,-): Record<string, unknown> {- const op = args["operation"];- if (op !== "record" && op !== "list") {- throw unknownOperationError("brain_dead_ends: operation must be record|list");- }- // A dead-end page the caller cannot read at its reach is treated as- // absent: `list` leaves it out of the entries and the warnings.- const readable = readableAtContextReachOrUndefined(ctx);- const vault = laneVault(ctx);- if (op === "list") {- const listed = listDeadEnds(vault);- // With no vault a dead-end page is a store record: named `Brain/...`.- const named = <T extends { path: string }>(row: T): T =>- contextVault(ctx) === null ? { ...row, path: lanePath(ctx, row.path) } : row;- // The reach filter judges the absolute paths, before any is renamed:- // a renamed `Brain/...` path would resolve against the working- // directory, not the vault.- const shown = (row: { path: string }): boolean =>- readable === undefined || readable(vaultRelativeSafe(vault, row.path));- return {- entries: listed.entries.filter(shown).map(named),- warnings: listed.warnings.filter(shown).map(named),- };- }- const approach = args["approach"];- const reason = args["reason"];- if (typeof approach !== "string" || approach.trim() === "") {- throw new MCPError(INVALID_PARAMS, "brain_dead_ends record: approach must be non-empty");- }- if (typeof reason !== "string" || reason.trim() === "") {- throw new MCPError(INVALID_PARAMS, "brain_dead_ends record: reason must be non-empty");- }- const agentArg = args["agent"];- const agent =- normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??- resolveAgentName(ctx.configPath ?? undefined);- const result = recordDeadEnd(vault, {- approach,- reason,- ...(typeof args["context"] === "string" ? { context: args["context"] as string } : {}),- agent,- now: new Date(),- ...(readable !== undefined ? { readable } : {}),- });- // The overflow trim walks every active dead end, so below local reach the- // ids it archived are left out: they would name or count withheld pages.- // It archives only pages the caller can read; a withheld one stays put.- return {- ok: true,- id: result.entry.id,- path: contextVault(ctx) === null ? lanePath(ctx, result.entry.path) : result.entry.path,- ...(readable === undefined ? { archived: result.archived } : {}),- };-}--// ----- brain_codegraph_report (t_a1e76788) -------------------------------------/**- * Read-only codegraph partner report: index status plus structural Cargo- * workspace membership. Never installs, initializes, extracts, or mutates a- * partner index or the vault - a missing CLI, missing index, or non-Rust- * project are honest report states, not errors.- */-function toolBrainCodegraphReport(- ctx: ServerContext,- _args: Record<string, unknown>,-): Record<string, unknown> {- const report = buildCodegraphReport({ cwd: process.cwd(), vault: ctx.vault });- // The CLI binary, the project and the Cargo manifest are host paths- // that may sit outside every root the server's egress pass knows (a- // package manager's bin folder, a checkout under /srv): each is named- // at the caller's reach here, as `toolPath` names any host path.- const at = (path: string): string => toolPath(ctx, path);- const named: CodegraphReport = {- ...report,- project: report.project === null ? null : at(report.project),- cli: { ...report.cli, path: report.cli.path === null ? null : at(report.cli.path) },- cargo_workspace:- report.cargo_workspace === null- ? null- : { ...report.cargo_workspace, manifestPath: at(report.cargo_workspace.manifestPath) },- };- return named as unknown as Record<string, unknown>;-}--// ----- brain_claims (Belief lifecycle suite, A3) -------------------------------function renderClaimNode(- delivery: ReturnType<typeof deliveryView>,- n: ClaimNode,-): Record<string, unknown> {- return {- id: n.id,- path: n.path,- topic: n.topic,- // The principle is the record's own stored text (delivery-trust,- // lane A): shaped through the request's delivery binding at the- // claim's own page - the same text brain_query fences inside the- // preference payloads - so the graph view is not the unfenced copy.- principle: delivery.shape(n.principle, n.path),- valid_from: n.valid_from,- valid_until: n.valid_until,- superseded_by: n.superseded_by,- contradicts: n.contradicts,- provenance: n.provenance,- tombstoned: n.tombstoned,- };-}--const CLAIMS_DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;--/** Load the persisted claim graph, or build a fresh in-memory one. */-function resolveClaimGraph(vault: string): ClaimGraph {- return loadClaimGraph(vault) ?? buildClaimGraph(vault);-}--/**- * Claim-graph query surface: current truth (default), truth at an- * instant, history, what replaced X, what contests X, or rebuild.- */-function toolBrainClaims(- ctx: ServerContext,- args: Record<string, unknown>,-): Record<string, unknown> {- const operation = coerceStr(args, "operation", false) ?? "current";- // A claim row carries the artifact's id, its vault-relative path, its- // topic AND its full principle text - the sharpest counter-example in- // recon C6 to the "this bucket is metadata" label. Every row-returning- // operation is filtered, and so is the rebuild count: a count the- // caller cannot decompose still says how many claims exist.- // At the caller's reach a row is asked over every record it names: its- // page, its id under the pref- and ret- spellings, and the records that- // superseded or contest it.- const owner = gatedOwnerScopeView(ctx.vault, ctx.agentName);- const reach = reachView(ctx.vault, contextReach(ctx));- // The delivery binding (delivery-trust, lane A): one reach resolution- // and one frontmatter cache for every principle this tool returns.- const delivery = deliveryView(ctx);- const shown = (n: ClaimNode): boolean =>- owner.row(n.path, n.id) &&- reach.row(- n.path,- ...recordRefs(n.id),- ...recordRefs(n.superseded_by ?? undefined),- ...n.contradicts.flatMap((id) => recordRefs(id)),- );- const visible = (rows: ReadonlyArray<ClaimNode>): ReadonlyArray<ClaimNode> => rows.filter(shown);- switch (operation) {- case "rebuild": {- const graph = rebuildClaimGraph(ctx.vault);- return {- operation,- rebuilt: true,- node_count: visible(allClaims(graph)).length,- truncated: graph.truncated,- };- }- case "replaced": {- const id = coerceStr(args, "id", true)!;- const tip = whatReplaced(resolveClaimGraph(ctx.vault), id);- return {- operation,- id,- tip: tip !== null && shown(tip) ? renderClaimNode(delivery, tip) : null,- };- }- case "contests": {- const id = coerceStr(args, "id", true)!;- const rows = visible(whatContests(resolveClaimGraph(ctx.vault), id));- return { operation, id, claims: rows.map((n) => renderClaimNode(delivery, n)) };- }- case "at": {- const at = coerceStr(args, "at", true)!;- const iso = CLAIMS_DATE_ONLY_RE.test(at) ? `${at}T00:00:00Z` : at;- const probe = Date.parse(iso);- if (Number.isNaN(probe)) {- throw new MCPError(- INVALID_PARAMS,- `brain_claims: 'at' must be an ISO instant or YYYY-MM-DD date; got ${at}`,- );- }- const rows = visible(truthAt(resolveClaimGraph(ctx.vault), probe));- return {- operation,- at,- count: rows.length,- claims: rows.map((n) => renderClaimNode(delivery, n)),- };- }- case "history": {- const rows = visible(allClaims(resolveClaimGraph(ctx.vault)));- return {- operation,- count: rows.length,- claims: rows.map((n) => renderClaimNode(delivery, n)),- };- }- case "current": {- const rows = visible(currentTruth(resolveClaimGraph(ctx.vault)));- return {- operation,- count: rows.length,- claims: rows.map((n) => renderClaimNode(delivery, n)),- };- }- default:- throw unknownOperationError(- "brain_claims: 'operation' must be one of current, at, history, replaced, contests, rebuild",- );- }-}--// ----- brain_truth (Entity Truth & Self-Improving Dream Suite) -----------------/**- * The registry slice the stated-claims anchoring consumes: canonical-- * scope entities only (the anchoring kernel's status discipline,- * applied where the registry is read), narrowed to AtomicEntityLike.- * Shared by the MCP `state` operation and the CLI `brain truth state`- * subcommand so the two surfaces anchor identically.- */-export function statedClaimEntities(vault: string): ReadonlyArray<{- readonly id: string;- readonly name: string;- readonly aliases: ReadonlyArray<string>;- readonly status: string;-}> {- return listEntities(vault)- .filter((entity) => entityStatusInScope(entity.status, ENTITY_STATUS_SCOPE.canonical))- .map(({ id, name, aliases, status }) => ({ id, name, aliases, status }));-}--/**- * One windowed events query, shared by the MCP `events` operation and- * the CLI `brain truth events` subcommand so the two surfaces cannot- * drift on shape, ordering, gating or paging. Bounds arrive already- * resolved (unix-ms); the page size must already be validated.- *- * Windowed recall (truth-correctable-time-aware, Tasks 8-9):- * `sinceMs`/`untilMs` filter ASSERTION `ts` only; the per-claim- * validity windows ride on the rows verbatim and are never consulted- * here (contract item 1 keeps the two temporal vocabularies separate).- * Every matched row passes the same per-row owner/reach gate- * `brain_claims` asks, and the account covers ONLY the rows that pass- * it: a withheld row is dropped and nothing counts it (the views'- * identical-to-absent convention - a dropped-but-counted row would tell- * the caller that a claim it may not see exists, and per entity or- * window would let it measure the hidden population). A filtered answer- * is therefore byte-identical to the answer over a vault that never- * held the withheld rows. The same reach governs the provenance join- * (see {@link claimProvenanceForPage}).- */-export function claimEventsReport(- vault: string,- agentName: string | undefined,- reach: TransportReach,- query: {- readonly entity?: string;- readonly sinceMs: number | null;- readonly untilMs: number | null;- readonly limit: number;- },-): Record<string, unknown> {- const entityFilter =- query.entity !== undefined && query.entity.trim() !== "" ? query.entity : undefined;- const view = everyArtifactRefView(gatedOwnerScopeView(vault, agentName), reachView(vault, reach));- const matched = matchClaimEvents(readClaimEvents(vault).events, {- ...(entityFilter !== undefined ? { entity: entityFilter } : {}),- sinceMs: query.sinceMs,- untilMs: query.untilMs,- });- const gated = view.filtersNothing ? matched : matched.filter((event) => view.row(event.source));- const page = gated.slice(0, query.limit);- const provenance = claimProvenanceForPage(vault, reach, view, page);- return {- ok: true,- operation: "events",- entity: entityFilter === undefined ? null : normalizeEntityName(entityFilter),- events: page.map((event, position) =>- event.sample_id === undefined || provenance === null- ? // A claim without a sample id renders exactly as today: no- // provenance key, byte-identical row.- event- : {- ...event,- // Answer-trust (task B4): the claim's sample id resolves to- // its receipt and outcome halves at read time. A missing- // outcome half is null - "receipt known, outcome unknown" -- // never a fabricated verdict.- provenance: provenance[position]!,- },- ),- total: gated.length,- truncated: gated.length > query.limit,- };-}--/**- * The provenance half of one events page, resolved at the CALLER's- * reach over ONE read per ledger.- *- * The resolutions come back aligned with the page by POSITION, one per- * row: the inversion flag compares each claim's OWN assertion ts- * against the claimed receipt, so two claims sharing one `sample_id`- * (one stated before the receipt it names, one after) must resolve- * independently - a per-id cache would hand both rows the last- * claim's flag. Resolution from the prebuilt index is map lookups, so- * resolving per event keeps the one-read-per-ledger bound the scans- * suite pins.- *- * The receipts surface withholds the operator's rule injections below- * local reach (list excludes them, show refuses them, receipts are- * stripped of their items); this join answers for the same records, so- * it binds the same rules here instead of leaking through a claim's- * `sample_id` what `brain_context_receipts` refuses to say directly. A- * rule-only receipt renders as the unknown-id answer; a mixed receipt- * keeps its non-rule items; and a receipt item whose recorded path- * names a page the caller may not read at its reach leaves the items- * under the same visibility rule the event rows of this report are- * gated by.- *- * Null when no row on the page carries a sample id: the ledgers are- * never read and every row renders byte-identically to the- * pre-attribution answer. Otherwise the array holds one entry per page- * row, null at the unsampled positions.- */-function claimProvenanceForPage(- vault: string,- reach: TransportReach,- view: ArtifactRefView,- page: ReadonlyArray<ClaimEvent>,-): ReadonlyArray<ClaimProvenance | null> | null {- if (!page.some((event) => event.sample_id !== undefined)) return null;- const local = reach === TRANSPORT_REACH.local;- const options: ClaimProvenanceOptions = {- ...(local ? {} : { exclude: isRuleOnlyInjection }),- ...(view.filtersNothing- ? {}- : {- excludeItem: (item: unknown): boolean =>- (!local && isOperatorRuleItem(item)) || itemPathHidden(item, view),- }),- };- const index = loadClaimProvenanceIndex(vault);- return page.map((event) =>- event.sample_id === undefined- ? null- : resolveClaimProvenanceFromIndex(index, event.sample_id, event.ts, options),- );-}--/**- * A receipt item whose recorded path names a page the caller may not- * read at its reach. An item with no path names no page and stays; an- * extensionless or wikilink spelling resolves through the same- * reference grammar the event-row gate uses.- */-function itemPathHidden(item: unknown, view: ArtifactRefView): boolean {- const path = (item as { path?: unknown } | null)?.path;- return typeof path === "string" && path !== "" && !view.visible(path);-}+ toolBrainBridges,+ toolBrainClusters,+ toolBrainDeepSynthesis,+ toolBrainDiarize,+ toolBrainForesight,+ toolBrainIdeaDiscovery,+ toolBrainMocAudit,+} from "./knowledge-lane-tools.ts";++export { statedClaimEntities, claimEventsReport } from "./knowledge-claim-tools.ts";export const KNOWLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{diff --git a/src/mcp/brain/knowledge-truth-tools.ts b/src/mcp/brain/knowledge-truth-tools.tsnew file mode 100644index 00000000..d3b1520d--- /dev/null+++ b/src/mcp/brain/knowledge-truth-tools.ts@@ -0,0 +1,416 @@+/**+ * The truth tools of the knowledge family (task 3.19):+ * `brain_truth`, `brain_dead_ends` and `brain_codegraph_report`, the+ * operator and agent surfaces over the claim ledger's verdicts. Split+ * from `knowledge-tools.ts`; registration happens through that module's+ * registry, which preserves the public KNOWLEDGE_TOOLS surface.+ */++import { resolveAgentName } from "../../core/config.ts";+import { isoSecond } from "../../core/brain/time.ts";+import { normalizeAgentArgument } from "../../core/agent-identity.ts";+import { normalizeEntityName } from "../../core/brain/entities/canonical.ts";+import {+ appendStatedClaims,+ StatedClaimsRefusal,+ type StatedClaim,+} from "../../core/brain/truth/stated-claims.ts";+import { listDeadEnds, recordDeadEnd } from "../../core/brain/dead-ends.ts";+import { lanePath, laneVault } from "./lane-vault.ts";+import { buildCodegraphReport, type CodegraphReport } from "../../core/partner/codegraph-report.ts";+import { toolPath } from "./device-path.ts";+import { aggregateQuantities } from "../../core/brain/truth/aggregate.ts";+import { detectAgentCollisions } from "../../core/brain/truth/collision.ts";+import { computeTruthStateWithConflicts } from "../../core/brain/truth/conflicts.ts";+import {+ appendClaimEvent,+ ClaimWindowRefusal,+ readClaimEvents,+} from "../../core/brain/truth/store.ts";+import { claimEventLimit } from "../../core/brain/truth/events-window.ts";+import { everyArtifactRefView } from "../../core/brain/artifact-ref-view.ts";+import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";+import { reachView } from "../../core/brain/reach-view.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import { contextReach, contextVault } from "../tool-contract.ts";+import type { ServerContext } from "../tool-contract.ts";+import { unknownOperationError } from "../coerce.ts";+import { vaultRelativeSafe } from "./shared.ts";+import { resolveTimeBounds } from "./time-bounds.ts";+import { readableAtContextReachOrUndefined } from "./reach-readable.ts";+import { claimEventsReport, statedClaimEntities } from "./knowledge-claim-tools.ts";++// ----- brain_context_pack (v0.10.15) ---------------------------------------++/**+ * Operator/agent surface over the entity claim ledger: ingest one+ * claim, render slots/conflicts from the fold, aggregate exact-match+ * quantities, report cross-agent collisions, recall a windowed slice of+ * the ledger via the events operation, and commit grounded agent-stated+ * claims via the state operation with per-claim anchoring verdicts. The+ * read ops are pure folds over the append-only ledger.+ */+export function toolBrainTruth(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Record<string, unknown> {+ const op = args["operation"];+ if (+ op !== "ingest" &&+ op !== "slots" &&+ op !== "conflicts" &&+ op !== "aggregate" &&+ op !== "collisions" &&+ op !== "events" &&+ op !== "state"+ ) {+ throw unknownOperationError(+ "brain_truth: operation must be ingest|slots|conflicts|aggregate|collisions|events|state",+ );+ }+ const requireStr = (name: string): string => {+ const value = args[name];+ if (typeof value !== "string" || value.trim() === "") {+ throw new MCPError(INVALID_PARAMS, `brain_truth ${op}: ${name} must be a non-empty string`);+ }+ return value;+ };+ // An optional string parameter is either a string or absent; any other+ // type is refused rather than silently ignored - a mistyped bound that+ // read as "no filter" would widen what the caller sees.+ const optionalStr = (name: string): string | undefined => {+ const value = args[name];+ if (value === undefined) return undefined;+ if (typeof value !== "string") {+ throw new MCPError(INVALID_PARAMS, `brain_truth ${op}: ${name} must be a string`);+ }+ return value;+ };++ if (op === "ingest") {+ const quantityValue = args["quantity_value"];+ if (+ (quantityValue === undefined || quantityValue === null) &&+ (typeof args["quantity_unit"] === "string" || typeof args["quantity_action"] === "string")+ ) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_truth ingest: quantity_value is required when quantity_unit or quantity_action is provided",+ );+ }+ let quantity: { value: number; unit: string | null; action: string | null } | undefined;+ if (quantityValue !== undefined && quantityValue !== null) {+ if (typeof quantityValue !== "number" || !Number.isFinite(quantityValue)) {+ throw new MCPError(INVALID_PARAMS, "brain_truth ingest: quantity_value must be a number");+ }+ quantity = {+ value: quantityValue,+ unit: typeof args["quantity_unit"] === "string" ? (args["quantity_unit"] as string) : null,+ action:+ typeof args["quantity_action"] === "string" ? (args["quantity_action"] as string) : null,+ };+ }+ const agentArg = args["agent"];+ const agent =+ normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??+ resolveAgentName(ctx.configPath ?? undefined);+ // Declared optional validity fields (design decision 3): explicit+ // input wins outright, bound by bound, over what ingest resolves+ // from the source record's frontmatter; absent fields leave every+ // line byte-identical to the pre-window ledger.+ const validFrom = optionalStr("valid_from");+ const validUntil = optionalStr("valid_until");+ // The source's window resolves at the CALLER's reach: a source page+ // the caller cannot read is treated exactly like an absent one -+ // windowless claim, no validity keys in the response, no signal+ // distinguishing withheld from absent. Without this gate the ingest+ // response would read a withheld page's validity frontmatter back+ // and triple as an existence oracle. (The CLI verb runs at operator+ // reach and passes no gate.)+ const readable = readableAtContextReachOrUndefined(ctx);+ // The store's window refusal is strict by design; here it is a+ // mistyped parameter, so it answers as the same failure class as the+ // sibling mistyped inputs (entity, since/until, limit) - typed+ // INVALID_PARAMS, never an internal error.+ let result;+ try {+ result = appendClaimEvent(+ ctx.vault,+ {+ ts: isoSecond(new Date()),+ agent,+ entity: requireStr("entity"),+ aspect: requireStr("aspect"),+ value: requireStr("value"),+ ...(quantity !== undefined ? { valueKind: "quantity" as const, quantity } : {}),+ ...(validFrom !== undefined ? { validFrom } : {}),+ ...(validUntil !== undefined ? { validUntil } : {}),+ source: requireStr("source"),+ },+ readable !== undefined ? { readableSource: readable } : {},+ );+ } catch (exc) {+ if (exc instanceof ClaimWindowRefusal) {+ throw new MCPError(INVALID_PARAMS, `brain_truth ingest: ${(exc as Error).message}`);+ }+ throw exc;+ }+ return {+ ok: true,+ entity: result.event.entity,+ aspect: result.event.aspect,+ path: result.path,+ ...(result.event.validFrom !== undefined ? { valid_from: result.event.validFrom } : {}),+ ...(result.event.validUntil !== undefined ? { valid_until: result.event.validUntil } : {}),+ };+ }++ // Windowed recall over the ledger (truth-correctable-time-aware,+ // Task 8): the response body is the shared claimEventsReport, so the+ // CLI subcommand answers byte-identically at the same query.+ if (op === "events") {+ const bounds = resolveTimeBounds(optionalStr("since"), optionalStr("until"));+ let limit: number;+ try {+ limit = claimEventLimit(args["limit"]);+ } catch (exc) {+ throw new MCPError(INVALID_PARAMS, `brain_truth events: ${(exc as Error).message}`);+ }+ return claimEventsReport(ctx.vault, ctx.agentName, contextReach(ctx), {+ entity: optionalStr("entity"),+ sinceMs: bounds.sinceMs,+ untilMs: bounds.untilMs,+ limit,+ });+ }++ // Grounded agent-stated claims (truth-correctable-time-aware, Task 8),+ // through lane 1's grounded-claim core: the payload boundary refuses+ // WHOLE calls (unknown relation, missing text, missing source, empty+ // agent, malformed ts) before ANY write, and anchoring verdicts are+ // per claim - the one+ // partial-commit lane in this subsystem, safe because each event is an+ // independent append in an append-only ledger and the response reports+ // exactly what landed.+ if (op === "state") {+ const claims = args["claims"];+ if (!Array.isArray(claims) || claims.length === 0) {+ throw new MCPError(INVALID_PARAMS, "brain_truth state: claims must be a non-empty array");+ }+ const stated = claims.map((raw, index): StatedClaim => {+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {+ throw new MCPError(INVALID_PARAMS, `brain_truth state: claims[${index}] must be an object`);+ }+ const claim = raw as Record<string, unknown>;+ // Type-shaped fields only; an empty subject or object is not a+ // refusal here but a per-claim ungrounded verdict downstream.+ const readField = (name: string): string => {+ const value = claim[name];+ if (typeof value !== "string") {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_truth state: claims[${index}].${name} must be a string`,+ );+ }+ return value;+ };+ return {+ subject: readField("subject"),+ relation: readField("relation"),+ object: readField("object"),+ };+ });+ const agentArg = args["agent"];+ if (agentArg !== undefined && typeof agentArg !== "string") {+ throw new MCPError(INVALID_PARAMS, "brain_truth state: agent must be a string");+ }+ const agent =+ normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??+ resolveAgentName(ctx.configPath ?? undefined);+ // Sample id (answer-trust, task B4): an optional call-level id naming+ // the recall/context-pack quality-sample these claims were stated+ // against. A non-string type is refused here as a mistyped parameter;+ // a blank string flows to the payload boundary's named refusal below+ // (mapped to the same failure class), so an empty id is never coerced+ // to an absent one. Committed events echo the id verbatim.+ const sampleId = optionalStr("sample_id");+ // The source's frontmatter window resolves at the CALLER's reach,+ // exactly as ingest gates it: a withheld source freezes a windowless+ // event and the committed rows carry no validity keys, so the state+ // response reads a withheld page's frontmatter no more than an+ // absent one's.+ const readable = readableAtContextReachOrUndefined(ctx);+ try {+ const outcome = appendStatedClaims(+ ctx.vault,+ {+ claims: stated,+ text: requireStr("text"),+ agent,+ ts: isoSecond(new Date()),+ source: requireStr("source"),+ ...(sampleId !== undefined ? { sampleId } : {}),+ },+ {+ entities: statedClaimEntities(ctx.vault),+ ...(ctx.configPath !== null ? { configPath: ctx.configPath } : {}),+ ...(readable !== undefined ? { readableSource: readable } : {}),+ },+ );+ return {+ ok: true,+ operation: "state",+ committed: outcome.committed.map((result) => ({ ...result.event })),+ ungrounded: outcome.ungrounded.map(({ claim, reasons }) => ({+ subject: claim.subject,+ relation: claim.relation,+ object: claim.object,+ reasons,+ })),+ };+ } catch (exc) {+ // Both refusal channels are mistyped-input refusals - the payload+ // boundary's, and the store's when the stated claim's window+ // resolves from the source record's frontmatter and inverts there+ // - so both answer as the same failure class the ingest operation+ // maps, never an internal error.+ if (exc instanceof StatedClaimsRefusal || exc instanceof ClaimWindowRefusal) {+ throw new MCPError(INVALID_PARAMS, `brain_truth state: ${exc.message}`);+ }+ throw exc;+ }+ }++ // The fold operations answer at the caller's view, the same one the+ // events operation applies to its rows: slots, conflicts, aggregates+ // and collisions all name claim values, quantities, agents and source+ // paths, so an unfiltered fold would hand a narrower caller what+ // `events` withholds. The filter is applied BEFORE the fold - the+ // identical-to-absent convention the views hold everywhere else - so a+ // claim from a source the caller cannot read is absent from the slots,+ // the totals and the collision pairs alike, exactly as it is from the+ // event list.+ const view = everyArtifactRefView(+ gatedOwnerScopeView(ctx.vault, ctx.agentName),+ reachView(ctx.vault, contextReach(ctx)),+ );+ const allEvents = readClaimEvents(ctx.vault).events;+ const events = view.filtersNothing ? allEvents : allEvents.filter((e) => view.row(e.source));+ if (op === "slots" || op === "conflicts") {+ const state = computeTruthStateWithConflicts(events);+ if (op === "conflicts") return { events: state.events, conflicts: state.conflicts };+ const entityFilter = args["entity"];+ const slots =+ typeof entityFilter === "string" && entityFilter.trim() !== ""+ ? state.slots.filter((s) => s.entity === normalizeEntityName(entityFilter))+ : state.slots;+ return { events: state.events, slots };+ }+ if (op === "aggregate") {+ const state = computeTruthStateWithConflicts(events);+ return {+ ...aggregateQuantities(state.slots, {+ ...(typeof args["action"] === "string" ? { action: args["action"] as string } : {}),+ unit: typeof args["unit"] === "string" ? (args["unit"] as string) : null,+ ...(typeof args["entity"] === "string" ? { entity: args["entity"] as string } : {}),+ }),+ };+ }+ return {+ collisions: detectAgentCollisions(events, { now: new Date() }),+ };+}++// ----- brain_concept_synthesis (v0.10.17) ----------------------------------++/**+ * Negative-knowledge registry: record one tried-and-failed approach+ * or list the bounded active set, newest first.+ */+export function toolBrainDeadEnds(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Record<string, unknown> {+ const op = args["operation"];+ if (op !== "record" && op !== "list") {+ throw unknownOperationError("brain_dead_ends: operation must be record|list");+ }+ // A dead-end page the caller cannot read at its reach is treated as+ // absent: `list` leaves it out of the entries and the warnings.+ const readable = readableAtContextReachOrUndefined(ctx);+ const vault = laneVault(ctx);+ if (op === "list") {+ const listed = listDeadEnds(vault);+ // With no vault a dead-end page is a store record: named `Brain/...`.+ const named = <T extends { path: string }>(row: T): T =>+ contextVault(ctx) === null ? { ...row, path: lanePath(ctx, row.path) } : row;+ // The reach filter judges the absolute paths, before any is renamed:+ // a renamed `Brain/...` path would resolve against the working+ // directory, not the vault.+ const shown = (row: { path: string }): boolean =>+ readable === undefined || readable(vaultRelativeSafe(vault, row.path));+ return {+ entries: listed.entries.filter(shown).map(named),+ warnings: listed.warnings.filter(shown).map(named),+ };+ }+ const approach = args["approach"];+ const reason = args["reason"];+ if (typeof approach !== "string" || approach.trim() === "") {+ throw new MCPError(INVALID_PARAMS, "brain_dead_ends record: approach must be non-empty");+ }+ if (typeof reason !== "string" || reason.trim() === "") {+ throw new MCPError(INVALID_PARAMS, "brain_dead_ends record: reason must be non-empty");+ }+ const agentArg = args["agent"];+ const agent =+ normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??+ resolveAgentName(ctx.configPath ?? undefined);+ const result = recordDeadEnd(vault, {+ approach,+ reason,+ ...(typeof args["context"] === "string" ? { context: args["context"] as string } : {}),+ agent,+ now: new Date(),+ ...(readable !== undefined ? { readable } : {}),+ });+ // The overflow trim walks every active dead end, so below local reach the+ // ids it archived are left out: they would name or count withheld pages.+ // It archives only pages the caller can read; a withheld one stays put.+ return {+ ok: true,+ id: result.entry.id,+ path: contextVault(ctx) === null ? lanePath(ctx, result.entry.path) : result.entry.path,+ ...(readable === undefined ? { archived: result.archived } : {}),+ };+}++// ----- brain_codegraph_report (t_a1e76788) -----------------------------------++/**+ * Read-only codegraph partner report: index status plus structural Cargo+ * workspace membership. Never installs, initializes, extracts, or mutates a+ * partner index or the vault - a missing CLI, missing index, or non-Rust+ * project are honest report states, not errors.+ */+export function toolBrainCodegraphReport(+ ctx: ServerContext,+ _args: Record<string, unknown>,+): Record<string, unknown> {+ const report = buildCodegraphReport({ cwd: process.cwd(), vault: ctx.vault });+ // The CLI binary, the project and the Cargo manifest are host paths+ // that may sit outside every root the server's egress pass knows (a+ // package manager's bin folder, a checkout under /srv): each is named+ // at the caller's reach here, as `toolPath` names any host path.+ const at = (path: string): string => toolPath(ctx, path);+ const named: CodegraphReport = {+ ...report,+ project: report.project === null ? null : at(report.project),+ cli: { ...report.cli, path: report.cli.path === null ? null : at(report.cli.path) },+ cargo_workspace:+ report.cargo_workspace === null+ ? null+ : { ...report.cargo_workspace, manifestPath: at(report.cargo_workspace.manifestPath) },+ };+ return named as unknown as Record<string, unknown>;+}diff --git a/src/mcp/brain/notes-shared.ts b/src/mcp/brain/notes-shared.tsnew file mode 100644index 00000000..c6624a73--- /dev/null+++ b/src/mcp/brain/notes-shared.ts@@ -0,0 +1,208 @@+/**+ * The write plumbing the note tools share (task 3.19): the two+ * vocabularies a refused write speaks and the bridge between them, the+ * RPC code a surfaced fault maps to, the frontmatter argument's parser+ * with its template limits, and the fallback that turns a write-batch+ * failure into an MCP error. Split from `notes-tools.ts`.+ */++import type { FrontmatterMap, FrontmatterValue } from "../../core/types.ts";+import { NOTE_CONFIG_INVALID_CODE } from "../../core/brain/notes/create-note.ts";+import { WriteBatchError } from "../../core/brain/write-batch.ts";+import { nextCommandField } from "../../core/brain/next-step.ts";+import {+ PendingStageConflictError,+ WriteRefusedError,+} from "../../core/brain/pending/pending-lanes.ts";+import { WRITE_BINDING_REFUSED_CODE } from "../../core/write-binding/index.ts";+import { isFrontmatterKey } from "../../core/vault.ts";+import { rethrowVaultFrozen } from "../frozen-refusal.ts";+import { INTERNAL_ERROR, INVALID_PARAMS, type JsonRpcErrorCode, MCPError } from "../protocol.ts";++/**+ * The two vocabularies a refused write speaks, and the bridge between+ * them.+ *+ * A refusal has always carried TWO names for one concept: the surface+ * code in `data.code` (`write_binding`), which is snake_case because it+ * sits in the same enumeration as `invalid_path` and `excluded` and is+ * what a client branches on; and the advisory registry code+ * (`write-binding-refused`), which is kebab-case because that is the+ * registry's spelling and is what resolves the next command. Renaming+ * either would break the convention of the other, so instead the+ * relationship is made explicit: every refusal that HAS a registered+ * code reports it as `data.diagnostic_code` beside `data.code`, together+ * with the `next_command` it resolves to. An agent that received a code+ * can now find it, and `docs/mcp.md` documents both spellings.+ *+ * A surface code absent from this map has no registered advisory code -+ * stated by leaving it out, never by inventing one.+ */+export const DIAGNOSTIC_CODE_FOR_SURFACE_CODE: Readonly<Record<string, string>> = Object.freeze({+ write_binding: WRITE_BINDING_REFUSED_CODE,+ config_invalid: NOTE_CONFIG_INVALID_CODE,+});++/** Key under which a refusal reports the registry spelling of its code. */+export const DIAGNOSTIC_CODE_KEY = "diagnostic_code";++/**+ * The advisory fields a surface `code` contributes to an MCP error's+ * `data`, or nothing at all when the code has no registered exit.+ */+export function advisoryFields(code: string): Readonly<Record<string, unknown>> {+ const diagnosticCode = DIAGNOSTIC_CODE_FOR_SURFACE_CODE[code];+ if (diagnosticCode === undefined) return {};+ return Object.freeze({+ [DIAGNOSTIC_CODE_KEY]: diagnosticCode,+ ...nextCommandField(diagnosticCode),+ });+}++/**+ * Surface codes that are NOT the caller's fault. A malformed+ * `Brain/_brain.yaml` refuses every write on this surface no matter what+ * arguments arrive, and a target the process cannot read refuses this+ * one no matter how the request is rephrased - the path is right and the+ * host is what is broken. Reporting either as INVALID_PARAMS would send+ * the agent looking at its own request forever. Both are reported as an+ * INTERNAL_ERROR that is nonetheless typed and carries its details.+ * Frontmatter the scanner cannot round-trip joins them for the same+ * reason: the note on disk is what needs fixing, not the request.+ */+export const OPERATOR_FAULT_CODES: ReadonlySet<string> = new Set([+ "config_invalid",+ "target_unreadable",+ "target_frontmatter_lossy",+]);++/** JSON-RPC code for a refusal, split on whose fault the refusal is. */+export function rpcCodeFor(surfaceCode: string): JsonRpcErrorCode {+ return OPERATOR_FAULT_CODES.has(surfaceCode) ? INTERNAL_ERROR : INVALID_PARAMS;+}++/**+ * Template variable names are NOT frontmatter keys, and holding them to+ * the frontmatter key grammar would narrow a surface this change has no+ * business narrowing: a variable name never becomes a line of a file,+ * the template parser has its own name grammar, and an unmatched+ * placeholder is deliberately left intact so a typo surfaces in the+ * rendered note. Passing this keeps that arm byte-identical - only the+ * shared VALUE domain was ever meant to be shared.+ */+export const ANY_TEMPLATE_VARIABLE_NAME = (): boolean => true;++/**+ * Longest accepted body template. A template is a note skeleton, not a+ * payload; the rendered note is bounded separately by the artifact cap+ * that `strict` enforces.+ */+export const TEMPLATE_MAX_LEN = 32_768;++/**+ * Narrow an untrusted argument to a {@link FrontmatterMap}. Accepts a+ * plain object whose values are strings, numbers, booleans, or string+ * arrays (the frontmatter value domain); rejects anything else with+ * INVALID_PARAMS rather than silently dropping it. `tool` names the+ * calling surface and `field` the argument, so the rejection points at+ * the exact thing the caller got wrong - template variables share this+ * value domain deliberately rather than growing a second one.+ */+export function parseFrontmatterArg(+ value: unknown,+ tool: string,+ field = "frontmatter",+ isKeyLegal: (key: string) => boolean = isFrontmatterKey,+): FrontmatterMap | undefined {+ if (value === undefined || value === null) return undefined;+ if (typeof value !== "object" || Array.isArray(value)) {+ throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be an object`);+ }+ // Prototype-free target + explicit rejection of prototype-mutating keys:+ // `frontmatter` is untrusted, and a `__proto__`/`constructor`/`prototype`+ // key with an array value would otherwise pollute the object prototype.+ //+ // The prototype triad is not the whole check. A key is also a line of+ // the file the emitter writes, so it is held to the grammar the+ // frontmatter scanner can read back - the same rule+ // `formatFrontmatter` enforces, applied here so the caller learns+ // WHICH argument was wrong instead of receiving the emitter's fault.+ // `FrontmatterKeyError` rejects the prototype triad too (none matches+ // the key grammar); the triad stays named because prototype pollution+ // and an unreadable key are different reasons to say no.+ const out: FrontmatterMap = Object.create(null) as FrontmatterMap;+ for (const [key, raw] of Object.entries(value)) {+ if (key === "__proto__" || key === "constructor" || key === "prototype") {+ throw new MCPError(INVALID_PARAMS, `${tool}: invalid ${field} key "${key}"`);+ }+ if (!isKeyLegal(key)) {+ throw new MCPError(+ INVALID_PARAMS,+ `${tool}: ${field} key ${JSON.stringify(key)} is not a key this format can ` ++ "round-trip; use a letter or underscore followed by letters, digits, '_' or '-'",+ );+ }+ let coerced: FrontmatterValue;+ if (typeof raw === "string" || typeof raw === "number" || typeof raw === "boolean") {+ coerced = raw;+ } else if (Array.isArray(raw) && raw.every((item) => typeof item === "string")) {+ coerced = raw.filter((item): item is string => typeof item === "string");+ } else {+ throw new MCPError(+ INVALID_PARAMS,+ `${tool}: ${field}.${key} must be a string, number, boolean, or string array`,+ );+ }+ out[key] = coerced;+ }+ return out;+}++/**+ * Map a core {@link WriteBatchError} onto a structured MCPError so the+ * agent gets a machine-readable rejection (`code`, offending `index`,+ * and the advisory code / next command when the state has one) instead+ * of opaque prose. `tool` prefixes the message. The JSON-RPC code splits+ * exactly as it does for a single note write - see {@link rpcCodeFor} -+ * so a batch and a one-shot report the same state the same way. Any+ * other error is a genuine I/O fault; wrap it in an INTERNAL_ERROR+ * MCPError (mirroring the fallback in {@link toolBrainCreateNote}) so+ * every write surface returns a consistent structured MCPError rather+ * than an opaque throw.+ */+export function writeBatchErrorToMcp(err: unknown, tool: string): MCPError {+ rethrowVaultFrozen(err);+ if (err instanceof WriteBatchError) {+ return new MCPError(rpcCodeFor(err.code), `${tool}: ${err.message}`, {+ code: err.code,+ index: err.index,+ ...advisoryFields(err.code),+ ...err.details,+ });+ }+ // Write-side trust (Task 12): a permissions document rule denied one of+ // the batch's ops. Named code, the rule that decided, and the operator+ // exit - the batch aborted before any commit, so the refusal is the+ // whole answer.+ if (err instanceof WriteRefusedError) {+ return new MCPError(INVALID_PARAMS, `${tool}: ${err.message}`, {+ code: err.code,+ rule: err.rule,+ agent: err.agent,+ next_command: err.nextCommand,+ });+ }+ // A staged op retried while its first run is still pending: the queue+ // refuses by name, so the answer names the queue entry holding the+ // target instead of an internal error a caller would retry into.+ if (err instanceof PendingStageConflictError) {+ return new MCPError(INVALID_PARAMS, `${tool}: ${err.message}`, {+ code: err.code,+ existing_id: err.existingId,+ target: err.target,+ });+ }+ // An answer already shaped for the wire keeps its code.+ if (err instanceof MCPError) return err;+ return new MCPError(INTERNAL_ERROR, err instanceof Error ? err.message : String(err));+}diff --git a/src/mcp/brain/notes-tools.ts b/src/mcp/brain/notes-tools.tsindex b4a85af9..2aa7eabf 100644--- a/src/mcp/brain/notes-tools.ts+++ b/src/mcp/brain/notes-tools.ts@@ -24,665 +24,16 @@* when the pages the call committed are clean.*/-import type { FrontmatterMap, FrontmatterValue } from "../../core/types.ts";+import { CREATE_NOTE_IF_EXISTS } from "../../core/brain/notes/create-note.ts";+import type { ToolDefinition } from "../tool-contract.ts";import {- createNote,- CreateNoteError,- CREATE_NOTE_IF_EXISTS,- NOTE_CONFIG_INVALID_CODE,- type CreateNoteIfExists,-} from "../../core/brain/notes/create-note.ts";-import {- applyWriteBatch,- WriteBatchError,- type AppendNoteOperation,- type UpdateNoteOperation,- type NoteWriteAudit,- type WriteBatchOpResult,-} from "../../core/brain/write-batch.ts";-import type { ReadableRef } from "../../core/brain/near-duplicate.ts";-import { nextCommandField } from "../../core/brain/next-step.ts";-import {- PENDING_STAGED_DIAGNOSTIC_CODE,- PendingStageConflictError,- WriteRefusedError,-} from "../../core/brain/pending/pending-lanes.ts";-import {- lintWrittenPages,- pageLintField,- type LintWrittenPagesOptions,- type PageLintField,-} from "../../core/brain/page-lint.ts";-import {- collectWideningCandidates,- wideningUnavailable,- type WideningResult,-} from "../../core/brain/page-lint-widening.ts";-import { resolveNearDuplicateWriteWideningEnabled } from "../../core/config.ts";-import { ROUTE_STAGE, timeStage, timeStageSync } from "../../core/route-scope.ts";-import { resolveSearchConfig } from "../../core/search/index.ts";-import type { ResolvedSearchConfig } from "../../core/search/types.ts";-import {- claimNoteWriteRefresh,- type PostWriteRefreshClaim,-} from "../../core/brain/notes/index-refresh.ts";-import {- WRITE_PATH_ADVISORY_KEY,- type WritePathAdvisoryField,-} from "../../core/brain/write-path-advisory.ts";-import { WRITE_BINDING_REFUSED_CODE } from "../../core/write-binding/index.ts";-import { isFrontmatterKey } from "../../core/vault.ts";-import { rethrowVaultFrozen } from "../frozen-refusal.ts";-import { INTERNAL_ERROR, INVALID_PARAMS, type JsonRpcErrorCode, MCPError } from "../protocol.ts";-import type { ServerContext, ToolDefinition } from "../tool-contract.ts";-import { coerceBoolOptional, coerceStr, coerceStringOptional } from "../coerce.ts";-import { readableAtContextReach } from "./reach-readable.ts";--/**- * The two vocabularies a refused write speaks, and the bridge between- * them.- *- * A refusal has always carried TWO names for one concept: the surface- * code in `data.code` (`write_binding`), which is snake_case because it- * sits in the same enumeration as `invalid_path` and `excluded` and is- * what a client branches on; and the advisory registry code- * (`write-binding-refused`), which is kebab-case because that is the- * registry's spelling and is what resolves the next command. Renaming- * either would break the convention of the other, so instead the- * relationship is made explicit: every refusal that HAS a registered- * code reports it as `data.diagnostic_code` beside `data.code`, together- * with the `next_command` it resolves to. An agent that received a code- * can now find it, and `docs/mcp.md` documents both spellings.- *- * A surface code absent from this map has no registered advisory code -- * stated by leaving it out, never by inventing one.- */-const DIAGNOSTIC_CODE_FOR_SURFACE_CODE: Readonly<Record<string, string>> = Object.freeze({- write_binding: WRITE_BINDING_REFUSED_CODE,- config_invalid: NOTE_CONFIG_INVALID_CODE,-});--/** Key under which a refusal reports the registry spelling of its code. */-const DIAGNOSTIC_CODE_KEY = "diagnostic_code";--/**- * The advisory fields a surface `code` contributes to an MCP error's- * `data`, or nothing at all when the code has no registered exit.- */-export function advisoryFields(code: string): Readonly<Record<string, unknown>> {- const diagnosticCode = DIAGNOSTIC_CODE_FOR_SURFACE_CODE[code];- if (diagnosticCode === undefined) return {};- return Object.freeze({- [DIAGNOSTIC_CODE_KEY]: diagnosticCode,- ...nextCommandField(diagnosticCode),- });-}--/**- * Surface codes that are NOT the caller's fault. A malformed- * `Brain/_brain.yaml` refuses every write on this surface no matter what- * arguments arrive, and a target the process cannot read refuses this- * one no matter how the request is rephrased - the path is right and the- * host is what is broken. Reporting either as INVALID_PARAMS would send- * the agent looking at its own request forever. Both are reported as an- * INTERNAL_ERROR that is nonetheless typed and carries its details.- * Frontmatter the scanner cannot round-trip joins them for the same- * reason: the note on disk is what needs fixing, not the request.- */-const OPERATOR_FAULT_CODES: ReadonlySet<string> = new Set([- "config_invalid",- "target_unreadable",- "target_frontmatter_lossy",-]);--/** JSON-RPC code for a refusal, split on whose fault the refusal is. */-function rpcCodeFor(surfaceCode: string): JsonRpcErrorCode {- return OPERATOR_FAULT_CODES.has(surfaceCode) ? INTERNAL_ERROR : INVALID_PARAMS;-}--/**- * Template variable names are NOT frontmatter keys, and holding them to- * the frontmatter key grammar would narrow a surface this change has no- * business narrowing: a variable name never becomes a line of a file,- * the template parser has its own name grammar, and an unmatched- * placeholder is deliberately left intact so a typo surfaces in the- * rendered note. Passing this keeps that arm byte-identical - only the- * shared VALUE domain was ever meant to be shared.- */-const ANY_TEMPLATE_VARIABLE_NAME = (): boolean => true;--/**- * Longest accepted body template. A template is a note skeleton, not a- * payload; the rendered note is bounded separately by the artifact cap- * that `strict` enforces.- */-const TEMPLATE_MAX_LEN = 32_768;--/**- * Narrow an untrusted argument to a {@link FrontmatterMap}. Accepts a- * plain object whose values are strings, numbers, booleans, or string- * arrays (the frontmatter value domain); rejects anything else with- * INVALID_PARAMS rather than silently dropping it. `tool` names the- * calling surface and `field` the argument, so the rejection points at- * the exact thing the caller got wrong - template variables share this- * value domain deliberately rather than growing a second one.- */-export function parseFrontmatterArg(- value: unknown,- tool: string,- field = "frontmatter",- isKeyLegal: (key: string) => boolean = isFrontmatterKey,-): FrontmatterMap | undefined {- if (value === undefined || value === null) return undefined;- if (typeof value !== "object" || Array.isArray(value)) {- throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be an object`);- }- // Prototype-free target + explicit rejection of prototype-mutating keys:- // `frontmatter` is untrusted, and a `__proto__`/`constructor`/`prototype`- // key with an array value would otherwise pollute the object prototype.- //- // The prototype triad is not the whole check. A key is also a line of- // the file the emitter writes, so it is held to the grammar the- // frontmatter scanner can read back - the same rule- // `formatFrontmatter` enforces, applied here so the caller learns- // WHICH argument was wrong instead of receiving the emitter's fault.- // `FrontmatterKeyError` rejects the prototype triad too (none matches- // the key grammar); the triad stays named because prototype pollution- // and an unreadable key are different reasons to say no.- const out: FrontmatterMap = Object.create(null) as FrontmatterMap;- for (const [key, raw] of Object.entries(value)) {- if (key === "__proto__" || key === "constructor" || key === "prototype") {- throw new MCPError(INVALID_PARAMS, `${tool}: invalid ${field} key "${key}"`);- }- if (!isKeyLegal(key)) {- throw new MCPError(- INVALID_PARAMS,- `${tool}: ${field} key ${JSON.stringify(key)} is not a key this format can ` +- "round-trip; use a letter or underscore followed by letters, digits, '_' or '-'",- );- }- let coerced: FrontmatterValue;- if (typeof raw === "string" || typeof raw === "number" || typeof raw === "boolean") {- coerced = raw;- } else if (Array.isArray(raw) && raw.every((item) => typeof item === "string")) {- coerced = raw.filter((item): item is string => typeof item === "string");- } else {- throw new MCPError(- INVALID_PARAMS,- `${tool}: ${field}.${key} must be a string, number, boolean, or string array`,- );- }- out[key] = coerced;- }- return out;-}--/**- * Map a core {@link WriteBatchError} onto a structured MCPError so the- * agent gets a machine-readable rejection (`code`, offending `index`,- * and the advisory code / next command when the state has one) instead- * of opaque prose. `tool` prefixes the message. The JSON-RPC code splits- * exactly as it does for a single note write - see {@link rpcCodeFor} -- * so a batch and a one-shot report the same state the same way. Any- * other error is a genuine I/O fault; wrap it in an INTERNAL_ERROR- * MCPError (mirroring the fallback in {@link toolBrainCreateNote}) so- * every write surface returns a consistent structured MCPError rather- * than an opaque throw.- */-export function writeBatchErrorToMcp(err: unknown, tool: string): MCPError {- rethrowVaultFrozen(err);- if (err instanceof WriteBatchError) {- return new MCPError(rpcCodeFor(err.code), `${tool}: ${err.message}`, {- code: err.code,- index: err.index,- ...advisoryFields(err.code),- ...err.details,- });- }- // Write-side trust (Task 12): a permissions document rule denied one of- // the batch's ops. Named code, the rule that decided, and the operator- // exit - the batch aborted before any commit, so the refusal is the- // whole answer.- if (err instanceof WriteRefusedError) {- return new MCPError(INVALID_PARAMS, `${tool}: ${err.message}`, {- code: err.code,- rule: err.rule,- agent: err.agent,- next_command: err.nextCommand,- });- }- // A staged op retried while its first run is still pending: the queue- // refuses by name, so the answer names the queue entry holding the- // target instead of an internal error a caller would retry into.- if (err instanceof PendingStageConflictError) {- return new MCPError(INVALID_PARAMS, `${tool}: ${err.message}`, {- code: err.code,- existing_id: err.existingId,- target: err.target,- });- }- // An answer already shaped for the wire keeps its code.- if (err instanceof MCPError) return err;- return new MCPError(INTERNAL_ERROR, err instanceof Error ? err.message : String(err));-}--/**- * Read the occupied-target policy. An unrecognised value is refused- * rather than falling back to the default: a caller that asked for a- * disposition this tool does not have must not be told its write- * succeeded under a different one.- */-function coerceIfExists(args: Record<string, unknown>): CreateNoteIfExists | undefined {- const raw = coerceStringOptional(args, "if_exists", 16);- if (raw === undefined) return undefined;- const match = CREATE_NOTE_IF_EXISTS.find((policy) => policy === raw);- if (match === undefined) {- throw new MCPError(- INVALID_PARAMS,- `brain_create_note: if_exists must be one of ${CREATE_NOTE_IF_EXISTS.join(", ")}`,- );- }- return match;-}--async function toolBrainCreateNote(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const path = coerceStr(args, "path", true)!;- const content = coerceStr(args, "content", false);- const frontmatter = parseFrontmatterArg(args["frontmatter"], "brain_create_note");- const ifExists = coerceIfExists(args);- const strict = coerceBoolOptional(args, "strict");- const template = coerceStringOptional(args, "template", TEMPLATE_MAX_LEN);- const templateVariables = parseFrontmatterArg(- args["template_variables"],- "brain_create_note",- "template_variables",- ANY_TEMPLATE_VARIABLE_NAME,- );-- try {- const res = createNote(ctx.vault, {- path,- ...(frontmatter !== undefined ? { frontmatter } : {}),- ...(content !== null && content !== undefined ? { content } : {}),- ...(ifExists !== undefined ? { ifExists } : {}),- ...(strict !== undefined ? { strict } : {}),- ...(template !== undefined ? { template } : {}),- ...(templateVariables !== undefined ? { templateVariables } : {}),- // The note-write record names the agent this server runs as, which- // is the one THIS config declares - not the one a machine-default- // discovery would find (who-wrote-what, Task A).- ...(ctx.configPath !== null ? { configPath: ctx.configPath } : {}),- // The transport-minted identity wins as the permission subject and- // the owner gate's resolved identity (write-side-trust, Task 7): a- // token's create answers for the token's agent.- ...(ctx.requestIdentity !== undefined ? { subject: ctx.requestIdentity } : {}),- });- // `outcome` is the discriminant; `created` is the boolean this tool- // has always returned and stays in lockstep with it, so a skip can- // never be read as a create by either field. A skip authored no- // bytes, so it names no page for the lint. A STAGED create (review- // gate on) also authored nothing at the target: its receipt carries- // the pending id and the queue command that publishes it, and names- // no page for the lint because nothing was published.- if (res.outcome === "staged") {- return await noteWriteResult(ctx, [], {- created: false,- outcome: "staged",- staged: true,- path: res.path,- pending_id: res.pendingId,- ...nextCommandField(PENDING_STAGED_DIAGNOSTIC_CODE),- });- }- // An APPLIED create claims the same detached index refresh a- // lifecycle write claims: the card names created notes among the- // writes that must resolve without a reindex, and the PR says a- // create claims. Fire-and-forget, never failing the write it- // follows; a skip or a staged create authored nothing at the target,- // so neither claims and neither carries the marker. The claim- // resolves through the SERVER's own config path - the same file- // every other search-resolving call in this file reads - so a- // non-default config's index path and freshen settings are the ones- // the evidence reads and the child spawns with.- const claim = res.created- ? await claimNoteWriteRefresh(ctx.vault, undefined, undefined, ctx.configPath ?? undefined)- : null;- return await noteWriteResult(ctx, res.created ? [res.path] : [], {- created: res.created,- outcome: res.outcome,- path: res.path,- // The audit half rides on the receipt for a create and NOT for a- // skip (who-wrote-what, Task A): a skip authored no bytes, so it- // has no write to attribute and no null that could be mistaken for- // a lost one.- ...(res.outcome === "created" ? auditFields(res) : {}),- ...(claim !== null ? refreshClaimFields(claim) : {}),- });- } catch (err) {- // Almost every CreateNoteError is a client-input fault (bad path,- // excluded location, an existing target, an invalid document, a- // malformed template, a destination outside the declared binding);- // report it with the typed code, its registry spelling and exit, and- // the validator's fix list when there is one. `config_invalid` is- // the exception the split in `rpcCodeFor` exists for: no argument- // the caller could send would succeed. Anything else is a genuine- // I/O fault.- if (err instanceof CreateNoteError) {- throw new MCPError(rpcCodeFor(err.code), `brain_create_note: ${err.message}`, {- code: err.code,- ...advisoryFields(err.code),- ...(err.violations.length > 0 ? { violations: err.violations } : {}),- });- }- // Write-side trust (Task 12): a permissions document rule denied the- // create. Named code, the rule that decided, and the operator exit.- if (err instanceof WriteRefusedError) {- throw new MCPError(INVALID_PARAMS, `brain_create_note: ${err.message}`, {- code: err.code,- rule: err.rule,- agent: err.agent,- next_command: err.nextCommand,- });- }- // A create retried while its first run is still staged: the queue- // refuses by name, so the answer names the queue entry holding the- // target instead of an internal error a caller would retry into.- if (err instanceof PendingStageConflictError) {- throw new MCPError(INVALID_PARAMS, `brain_create_note: ${err.message}`, {- code: err.code,- existing_id: err.existingId,- target: err.target,- });- }- rethrowVaultFrozen(err);- // An answer already shaped for the wire (the `vault_required` refusal- // of a server with no vault) keeps its code.- if (err instanceof MCPError) throw err;- throw new MCPError(INTERNAL_ERROR, err instanceof Error ? err.message : String(err));- }-}+ toolBrainAppendNote,+ toolBrainCreateNote,+ toolBrainUpdateNote,+} from "./notes-write-tools.ts";-/**- * The `content` an update carries, distinguishing ABSENT from EMPTY.- *- * {@link coerceStr} collapses `""` and a whitespace-only string to- * `null`, which every other surface reads as "the caller did not send- * this argument". On an update that reading is wrong in a way that loses- * the caller's intent: `{path, frontmatter, content: ""}` asked for the- * body to be cleared and was answered with `updated: true` over a body- * left exactly as it was, and `{path, content: ""}` was refused as if no- * argument had arrived at all. Both are silent about what happened to- * the request. Reading presence directly lets the empty body reach the- * kernel, where it is either refused by name or - with `allow_empty` -- * honoured.- */-function updateBodyArgument(args: Record<string, unknown>): string | undefined {- const raw = args["content"];- if (raw === undefined || raw === null) return undefined;- if (typeof raw !== "string") {- throw new MCPError(INVALID_PARAMS, "brain_update_note: argument 'content' must be a string");- }- return raw;-}--/**- * Update an existing note: merge frontmatter keys and/or replace the- * body. A single-operation batch over kernel 2 so a mid-write failure- * leaves the target byte-identical. Requires at least one of frontmatter- * or content; a missing target is a typed error.- */-async function toolBrainUpdateNote(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const path = coerceStr(args, "path", true)!;- const frontmatter = parseFrontmatterArg(args["frontmatter"], "brain_update_note");- const content = updateBodyArgument(args);- const allowEmpty = coerceBoolOptional(args, "allow_empty");- if (frontmatter === undefined && content === undefined) {- throw new MCPError(- INVALID_PARAMS,- "brain_update_note: provide 'frontmatter', 'content', or both",- );- }- const op: UpdateNoteOperation = {- kind: "update_note",- path,- ...(frontmatter !== undefined ? { frontmatter } : {}),- ...(content !== undefined ? { body: content } : {}),- ...(allowEmpty !== undefined ? { allowEmpty } : {}),- };- const result = runSingleWrite(ctx, op, "brain_update_note");- // The flag comes off the kernel result rather than being restated here:- // one fact, one source. A skipped update wrote no bytes, so it names no- // page for the lint and carries no audit half - the same shape a- // skipped create spells.- //- // An APPLIED update - a content edit, frontmatter or both - claims the- // same detached index refresh the lifecycle's writes claim, with the- // marker on the receipt under the same vocabulary. A byte-identical- // re-apply wrote nothing, so it claims nothing and carries no marker.- // The claim resolves through the server's own config path, like every- // other search-resolving call here.- const claim = result.updated- ? await claimNoteWriteRefresh(ctx.vault, undefined, undefined, ctx.configPath ?? undefined)- : null;- return noteWriteResult(ctx, result.updated ? [result.path] : [], {- updated: result.updated,- path: result.path,- ...(result.updated ? auditFields(result) : {}),- ...pathAdvisoryFields(result),- ...(claim !== null ? refreshClaimFields(claim) : {}),- });-}--/**- * Append body text to an existing note. A single-operation batch over- * kernel 2; a missing target is a typed error.- */-async function toolBrainAppendNote(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const path = coerceStr(args, "path", true)!;- const content = coerceStr(args, "content", true)!;- const op: AppendNoteOperation = { kind: "append_note", path, content };- const result = runSingleWrite(ctx, op, "brain_append_note");- // Skipped-append receipts follow the skipped-update shape: no bytes- // landed, so no page to lint and no audit half to mistake.- //- // An APPLIED append wrote body bytes, so it is a content edit and- // claims the same detached index refresh the update claims - the one- // note-write surface left claiming nothing, and the only one whose- // receipt contradicted the "a content edit claims" line. The claim- // resolves through the server's own config path, like every other- // search-resolving call here.- const claim = result.appended- ? await claimNoteWriteRefresh(ctx.vault, undefined, undefined, ctx.configPath ?? undefined)- : null;- return noteWriteResult(ctx, result.appended ? [result.path] : [], {- appended: result.appended,- path: result.path,- ...(result.appended ? auditFields(result) : {}),- ...pathAdvisoryFields(result),- ...(claim !== null ? refreshClaimFields(claim) : {}),- });-}--/**- * The `write_id` (and, when it is null, the `audit_reason`) of one note- * write, as receipt fields.- *- * The bytes land before the event is appended, so `write_id: null` is a- * state the caller has to be able to see: the note exists and nothing- * attributes it. Both keys are always spelled together - the receipt- * never carries a bare null - so an agent reading the reply learns which- * of the two happened rather than inferring it from an absence.- */-function auditFields(audit: NoteWriteAudit): Record<string, unknown> {- return {- write_id: audit.write_id,- ...(audit.audit_reason !== undefined ? { audit_reason: audit.audit_reason } : {}),- };-}--/**- * The refresh-claim marker a landed create or content edit carries on- * its receipt, in the same vocabulary the note-lifecycle tool renders:- * `index_refresh` is `claimed` (a detached run is IN FLIGHT, never- * landed) or `not_claimed`, and `index_refresh_reason` spells why- * nothing was started - the freshen machinery's own skip token, or the- * error it raised. Both keys render together or not at all: a write- * that authored no bytes claims nothing, and its receipt is- * byte-identical to the one that shipped before this field existed.- */-function refreshClaimFields(claim: PostWriteRefreshClaim): Record<string, unknown> {- return {- index_refresh: claim.refresh,- index_refresh_reason: claim.refreshReason,- };-}--/**- * The absolute-path advisory a kernel result computed over the call's- * authored content, passed through under its own key. Byte-identical-- * when-absent: a clean write contributes nothing, exactly as the page- * lint does at the envelope level. The kernel already advises - this- * only lets the receipt say it.- */-function pathAdvisoryFields(result: NoteOpResult): WritePathAdvisoryField {- const report = result[WRITE_PATH_ADVISORY_KEY];- return report === undefined ? {} : { [WRITE_PATH_ADVISORY_KEY]: report };-}--/** The kernel results that name a note file: exactly the three note ops. */-type NoteOpResult = Extract<WriteBatchOpResult, { readonly path: string }>;--/** The single-note operations these two handlers submit. */-type SingleNoteOperation = UpdateNoteOperation | AppendNoteOperation;--/**- * Run a single-operation write batch and unwrap its one result, mapping- * a typed {@link WriteBatchError} to a structured INVALID_PARAMS.- *- * The result kind is tied to the operation kind, so the caller reads the- * kernel's own success flag back without restating it. This used to- * return `path: "path" in only ? only.path : ""` - an unreachable arm- * that, had it ever been reached, would have reported a successful write- * at no path at all. A result whose kind does not match the operation is- * a broken contract between this layer and the kernel, so it is raised as- * one rather than papered over with an empty string.- */-function runSingleWrite<K extends SingleNoteOperation["kind"]>(- ctx: ServerContext,- op: Extract<SingleNoteOperation, { readonly kind: K }>,- tool: string,-): Extract<NoteOpResult, { readonly kind: K }> {- let batch;- try {- // A target the caller may not read at its reach is refused exactly- // as a missing one. The transport-minted identity rides along as the- // batch's subject (write-side-trust, Task 7): a token's update or- // append answers for the token's agent, in the owner gate and the- // deny-only document consult alike.- batch = applyWriteBatch(ctx.vault, [op], {- readable: readableAtContextReach(ctx),- ...(ctx.configPath !== null ? { configPath: ctx.configPath } : {}),- ...(ctx.requestIdentity !== undefined ? { subject: ctx.requestIdentity } : {}),- });- } catch (err) {- throw writeBatchErrorToMcp(err, tool);- }- const only = batch.results[0]!;- if (only.kind !== op.kind) {- throw new MCPError(- INTERNAL_ERROR,- `${tool}: the write kernel returned a '${only.kind}' result for a '${op.kind}' operation`,- );- }- return only as Extract<NoteOpResult, { readonly kind: K }>;-}--/**- * The one write-result envelope, adopted by all four note-write tools- * (evidence-at-the-boundary, task A4).- *- * Before this there was no shared envelope at all: four handlers- * hand-built four shapes, two of them hardcoding a success flag the- * kernel result already carried. This composes the tool's own receipt- * with the write-time page lint over exactly the pages the call- * committed.- *- * The lint runs AFTER the commit and reads what is on disk, because the- * batch kernel wrote the bytes and the handler never composed them. It- * never gates the write, and it contributes NO key when there is nothing- * to say - so a receipt for a clean write is byte-identical to the one- * that shipped before. `pages` empty (a skipped create, a log-only batch)- * means no bytes were authored, so there is nothing to lint.- *- * The lint answers at the caller's reach: a near-duplicate sibling the- * caller may not read is never named, scored or counted on the receipt, a- * wikilink to a withheld Brain page reads as broken, and a merge chain- * ends at its first withheld hop, as they would if the page were absent.- *- * With `near_duplicate_write_widening_enabled` on, the near-duplicate hint- * also compares the pages with keyword-index candidates from other- * directories ({@link collectWideningCandidates}), and the report states- * whether that ran. With the key off nothing is opened and the receipt is- * exactly the one that shipped before.- *- * Under an open route scope the lint is timed as the `lint` stage and the- * widening as `near_duplicate_lookup`, the stage the lint's own- * near-duplicate scoring also adds to.- */-export async function noteWriteResult<T extends Record<string, unknown>>(- ctx: ServerContext,- pages: ReadonlyArray<string>,- receipt: T,-): Promise<T & PageLintField> {- if (pages.length === 0) return receipt;- const readable = readableAtContextReach(ctx);- const widening = await timeStage(ROUTE_STAGE.nearDuplicateLookup, () =>- widenNearDuplicates(ctx, pages, readable),- );- const opts: LintWrittenPagesOptions =- widening === undefined- ? { readable }- : {- readable,- extraCandidates: widening.candidates,- widening: widening.status,- ...(widening.detail !== undefined ? { wideningDetail: widening.detail } : {}),- };- const report = timeStageSync(ROUTE_STAGE.lint, () => lintWrittenPages(ctx.vault, pages, opts));- return { ...receipt, ...pageLintField(report) };-}--/**- * Keyword-index candidates for the near-duplicate hint, or `undefined`- * when widening is off. A search config that does not resolve leaves no- * index to read, which is the same named `index_unavailable` an index- * that will not open reports, with the failure named in its detail: the- * write is never failed by its hint.- */-async function widenNearDuplicates(- ctx: ServerContext,- pages: ReadonlyArray<string>,- readable: ReadableRef,-): Promise<WideningResult | undefined> {- const configPath = ctx.configPath ?? undefined;- if (!resolveNearDuplicateWriteWideningEnabled(configPath)) return undefined;- let config: ResolvedSearchConfig;- try {- config = resolveSearchConfig({ vault: ctx.vault, configPath });- } catch (err) {- return wideningUnavailable(err);- }- return collectWideningCandidates(config, ctx.vault, pages, readable);-}+export { advisoryFields, parseFrontmatterArg, writeBatchErrorToMcp } from "./notes-shared.ts";+export { noteWriteResult } from "./notes-write-tools.ts";export const NOTES_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{diff --git a/src/mcp/brain/notes-write-tools.ts b/src/mcp/brain/notes-write-tools.tsnew file mode 100644index 00000000..eecf7c4d--- /dev/null+++ b/src/mcp/brain/notes-write-tools.ts@@ -0,0 +1,483 @@+/**+ * The note write tools (`brain_create_note`, `brain_update_note`,+ * `brain_append_note`) with the single-write runner, the audit and+ * refresh-claim fields they answer, and the near-duplicate widening the+ * create hint reads. Split from `notes-tools.ts` (task 3.19);+ * registration happens through that module's registry, which preserves+ * the public NOTES_TOOLS surface.+ */++import {+ createNote,+ CreateNoteError,+ CREATE_NOTE_IF_EXISTS,+ type CreateNoteIfExists,+} from "../../core/brain/notes/create-note.ts";+import {+ applyWriteBatch,+ type AppendNoteOperation,+ type UpdateNoteOperation,+ type NoteWriteAudit,+ type WriteBatchOpResult,+} from "../../core/brain/write-batch.ts";+import type { ReadableRef } from "../../core/brain/near-duplicate.ts";+import { nextCommandField } from "../../core/brain/next-step.ts";+import {+ PENDING_STAGED_DIAGNOSTIC_CODE,+ PendingStageConflictError,+ WriteRefusedError,+} from "../../core/brain/pending/pending-lanes.ts";+import {+ lintWrittenPages,+ pageLintField,+ type LintWrittenPagesOptions,+ type PageLintField,+} from "../../core/brain/page-lint.ts";+import {+ collectWideningCandidates,+ wideningUnavailable,+ type WideningResult,+} from "../../core/brain/page-lint-widening.ts";+import { resolveNearDuplicateWriteWideningEnabled } from "../../core/config.ts";+import { ROUTE_STAGE, timeStage, timeStageSync } from "../../core/route-scope.ts";+import { resolveSearchConfig } from "../../core/search/index.ts";+import type { ResolvedSearchConfig } from "../../core/search/types.ts";+import {+ claimNoteWriteRefresh,+ type PostWriteRefreshClaim,+} from "../../core/brain/notes/index-refresh.ts";+import {+ WRITE_PATH_ADVISORY_KEY,+ type WritePathAdvisoryField,+} from "../../core/brain/write-path-advisory.ts";+import { rethrowVaultFrozen } from "../frozen-refusal.ts";+import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";+import type { ServerContext } from "../tool-contract.ts";+import { coerceBoolOptional, coerceStr, coerceStringOptional } from "../coerce.ts";+import { readableAtContextReach } from "./reach-readable.ts";+import {+ ANY_TEMPLATE_VARIABLE_NAME,+ TEMPLATE_MAX_LEN,+ advisoryFields,+ parseFrontmatterArg,+ rpcCodeFor,+ writeBatchErrorToMcp,+} from "./notes-shared.ts";++/**+ * Read the occupied-target policy. An unrecognised value is refused+ * rather than falling back to the default: a caller that asked for a+ * disposition this tool does not have must not be told its write+ * succeeded under a different one.+ */+export function coerceIfExists(args: Record<string, unknown>): CreateNoteIfExists | undefined {+ const raw = coerceStringOptional(args, "if_exists", 16);+ if (raw === undefined) return undefined;+ const match = CREATE_NOTE_IF_EXISTS.find((policy) => policy === raw);+ if (match === undefined) {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_create_note: if_exists must be one of ${CREATE_NOTE_IF_EXISTS.join(", ")}`,+ );+ }+ return match;+}++export async function toolBrainCreateNote(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const path = coerceStr(args, "path", true)!;+ const content = coerceStr(args, "content", false);+ const frontmatter = parseFrontmatterArg(args["frontmatter"], "brain_create_note");+ const ifExists = coerceIfExists(args);+ const strict = coerceBoolOptional(args, "strict");+ const template = coerceStringOptional(args, "template", TEMPLATE_MAX_LEN);+ const templateVariables = parseFrontmatterArg(+ args["template_variables"],+ "brain_create_note",+ "template_variables",+ ANY_TEMPLATE_VARIABLE_NAME,+ );++ try {+ const res = createNote(ctx.vault, {+ path,+ ...(frontmatter !== undefined ? { frontmatter } : {}),+ ...(content !== null && content !== undefined ? { content } : {}),+ ...(ifExists !== undefined ? { ifExists } : {}),+ ...(strict !== undefined ? { strict } : {}),+ ...(template !== undefined ? { template } : {}),+ ...(templateVariables !== undefined ? { templateVariables } : {}),+ // The note-write record names the agent this server runs as, which+ // is the one THIS config declares - not the one a machine-default+ // discovery would find (who-wrote-what, Task A).+ ...(ctx.configPath !== null ? { configPath: ctx.configPath } : {}),+ // The transport-minted identity wins as the permission subject and+ // the owner gate's resolved identity (write-side-trust, Task 7): a+ // token's create answers for the token's agent.+ ...(ctx.requestIdentity !== undefined ? { subject: ctx.requestIdentity } : {}),+ });+ // `outcome` is the discriminant; `created` is the boolean this tool+ // has always returned and stays in lockstep with it, so a skip can+ // never be read as a create by either field. A skip authored no+ // bytes, so it names no page for the lint. A STAGED create (review+ // gate on) also authored nothing at the target: its receipt carries+ // the pending id and the queue command that publishes it, and names+ // no page for the lint because nothing was published.+ if (res.outcome === "staged") {+ return await noteWriteResult(ctx, [], {+ created: false,+ outcome: "staged",+ staged: true,+ path: res.path,+ pending_id: res.pendingId,+ ...nextCommandField(PENDING_STAGED_DIAGNOSTIC_CODE),+ });+ }+ // An APPLIED create claims the same detached index refresh a+ // lifecycle write claims: the card names created notes among the+ // writes that must resolve without a reindex, and the PR says a+ // create claims. Fire-and-forget, never failing the write it+ // follows; a skip or a staged create authored nothing at the target,+ // so neither claims and neither carries the marker. The claim+ // resolves through the SERVER's own config path - the same file+ // every other search-resolving call in this file reads - so a+ // non-default config's index path and freshen settings are the ones+ // the evidence reads and the child spawns with.+ const claim = res.created+ ? await claimNoteWriteRefresh(ctx.vault, undefined, undefined, ctx.configPath ?? undefined)+ : null;+ return await noteWriteResult(ctx, res.created ? [res.path] : [], {+ created: res.created,+ outcome: res.outcome,+ path: res.path,+ // The audit half rides on the receipt for a create and NOT for a+ // skip (who-wrote-what, Task A): a skip authored no bytes, so it+ // has no write to attribute and no null that could be mistaken for+ // a lost one.+ ...(res.outcome === "created" ? auditFields(res) : {}),+ ...(claim !== null ? refreshClaimFields(claim) : {}),+ });+ } catch (err) {+ // Almost every CreateNoteError is a client-input fault (bad path,+ // excluded location, an existing target, an invalid document, a+ // malformed template, a destination outside the declared binding);+ // report it with the typed code, its registry spelling and exit, and+ // the validator's fix list when there is one. `config_invalid` is+ // the exception the split in `rpcCodeFor` exists for: no argument+ // the caller could send would succeed. Anything else is a genuine+ // I/O fault.+ if (err instanceof CreateNoteError) {+ throw new MCPError(rpcCodeFor(err.code), `brain_create_note: ${err.message}`, {+ code: err.code,+ ...advisoryFields(err.code),+ ...(err.violations.length > 0 ? { violations: err.violations } : {}),+ });+ }+ // Write-side trust (Task 12): a permissions document rule denied the+ // create. Named code, the rule that decided, and the operator exit.+ if (err instanceof WriteRefusedError) {+ throw new MCPError(INVALID_PARAMS, `brain_create_note: ${err.message}`, {+ code: err.code,+ rule: err.rule,+ agent: err.agent,+ next_command: err.nextCommand,+ });+ }+ // A create retried while its first run is still staged: the queue+ // refuses by name, so the answer names the queue entry holding the+ // target instead of an internal error a caller would retry into.+ if (err instanceof PendingStageConflictError) {+ throw new MCPError(INVALID_PARAMS, `brain_create_note: ${err.message}`, {+ code: err.code,+ existing_id: err.existingId,+ target: err.target,+ });+ }+ rethrowVaultFrozen(err);+ // An answer already shaped for the wire (the `vault_required` refusal+ // of a server with no vault) keeps its code.+ if (err instanceof MCPError) throw err;+ throw new MCPError(INTERNAL_ERROR, err instanceof Error ? err.message : String(err));+ }+}++/**+ * The `content` an update carries, distinguishing ABSENT from EMPTY.+ *+ * {@link coerceStr} collapses `""` and a whitespace-only string to+ * `null`, which every other surface reads as "the caller did not send+ * this argument". On an update that reading is wrong in a way that loses+ * the caller's intent: `{path, frontmatter, content: ""}` asked for the+ * body to be cleared and was answered with `updated: true` over a body+ * left exactly as it was, and `{path, content: ""}` was refused as if no+ * argument had arrived at all. Both are silent about what happened to+ * the request. Reading presence directly lets the empty body reach the+ * kernel, where it is either refused by name or - with `allow_empty` -+ * honoured.+ */+export function updateBodyArgument(args: Record<string, unknown>): string | undefined {+ const raw = args["content"];+ if (raw === undefined || raw === null) return undefined;+ if (typeof raw !== "string") {+ throw new MCPError(INVALID_PARAMS, "brain_update_note: argument 'content' must be a string");+ }+ return raw;+}++/**+ * Update an existing note: merge frontmatter keys and/or replace the+ * body. A single-operation batch over kernel 2 so a mid-write failure+ * leaves the target byte-identical. Requires at least one of frontmatter+ * or content; a missing target is a typed error.+ */+export async function toolBrainUpdateNote(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const path = coerceStr(args, "path", true)!;+ const frontmatter = parseFrontmatterArg(args["frontmatter"], "brain_update_note");+ const content = updateBodyArgument(args);+ const allowEmpty = coerceBoolOptional(args, "allow_empty");+ if (frontmatter === undefined && content === undefined) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_update_note: provide 'frontmatter', 'content', or both",+ );+ }+ const op: UpdateNoteOperation = {+ kind: "update_note",+ path,+ ...(frontmatter !== undefined ? { frontmatter } : {}),+ ...(content !== undefined ? { body: content } : {}),+ ...(allowEmpty !== undefined ? { allowEmpty } : {}),+ };+ const result = runSingleWrite(ctx, op, "brain_update_note");+ // The flag comes off the kernel result rather than being restated here:+ // one fact, one source. A skipped update wrote no bytes, so it names no+ // page for the lint and carries no audit half - the same shape a+ // skipped create spells.+ //+ // An APPLIED update - a content edit, frontmatter or both - claims the+ // same detached index refresh the lifecycle's writes claim, with the+ // marker on the receipt under the same vocabulary. A byte-identical+ // re-apply wrote nothing, so it claims nothing and carries no marker.+ // The claim resolves through the server's own config path, like every+ // other search-resolving call here.+ const claim = result.updated+ ? await claimNoteWriteRefresh(ctx.vault, undefined, undefined, ctx.configPath ?? undefined)+ : null;+ return noteWriteResult(ctx, result.updated ? [result.path] : [], {+ updated: result.updated,+ path: result.path,+ ...(result.updated ? auditFields(result) : {}),+ ...pathAdvisoryFields(result),+ ...(claim !== null ? refreshClaimFields(claim) : {}),+ });+}++/**+ * Append body text to an existing note. A single-operation batch over+ * kernel 2; a missing target is a typed error.+ */+export async function toolBrainAppendNote(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const path = coerceStr(args, "path", true)!;+ const content = coerceStr(args, "content", true)!;+ const op: AppendNoteOperation = { kind: "append_note", path, content };+ const result = runSingleWrite(ctx, op, "brain_append_note");+ // Skipped-append receipts follow the skipped-update shape: no bytes+ // landed, so no page to lint and no audit half to mistake.+ //+ // An APPLIED append wrote body bytes, so it is a content edit and+ // claims the same detached index refresh the update claims - the one+ // note-write surface left claiming nothing, and the only one whose+ // receipt contradicted the "a content edit claims" line. The claim+ // resolves through the server's own config path, like every other+ // search-resolving call here.+ const claim = result.appended+ ? await claimNoteWriteRefresh(ctx.vault, undefined, undefined, ctx.configPath ?? undefined)+ : null;+ return noteWriteResult(ctx, result.appended ? [result.path] : [], {+ appended: result.appended,+ path: result.path,+ ...(result.appended ? auditFields(result) : {}),+ ...pathAdvisoryFields(result),+ ...(claim !== null ? refreshClaimFields(claim) : {}),+ });+}++/**+ * The `write_id` (and, when it is null, the `audit_reason`) of one note+ * write, as receipt fields.+ *+ * The bytes land before the event is appended, so `write_id: null` is a+ * state the caller has to be able to see: the note exists and nothing+ * attributes it. Both keys are always spelled together - the receipt+ * never carries a bare null - so an agent reading the reply learns which+ * of the two happened rather than inferring it from an absence.+ */+export function auditFields(audit: NoteWriteAudit): Record<string, unknown> {+ return {+ write_id: audit.write_id,+ ...(audit.audit_reason !== undefined ? { audit_reason: audit.audit_reason } : {}),+ };+}++/**+ * The refresh-claim marker a landed create or content edit carries on+ * its receipt, in the same vocabulary the note-lifecycle tool renders:+ * `index_refresh` is `claimed` (a detached run is IN FLIGHT, never+ * landed) or `not_claimed`, and `index_refresh_reason` spells why+ * nothing was started - the freshen machinery's own skip token, or the+ * error it raised. Both keys render together or not at all: a write+ * that authored no bytes claims nothing, and its receipt is+ * byte-identical to the one that shipped before this field existed.+ */+export function refreshClaimFields(claim: PostWriteRefreshClaim): Record<string, unknown> {+ return {+ index_refresh: claim.refresh,+ index_refresh_reason: claim.refreshReason,+ };+}++/**+ * The absolute-path advisory a kernel result computed over the call's+ * authored content, passed through under its own key. Byte-identical-+ * when-absent: a clean write contributes nothing, exactly as the page+ * lint does at the envelope level. The kernel already advises - this+ * only lets the receipt say it.+ */+export function pathAdvisoryFields(result: NoteOpResult): WritePathAdvisoryField {+ const report = result[WRITE_PATH_ADVISORY_KEY];+ return report === undefined ? {} : { [WRITE_PATH_ADVISORY_KEY]: report };+}++/** The kernel results that name a note file: exactly the three note ops. */+export type NoteOpResult = Extract<WriteBatchOpResult, { readonly path: string }>;++/** The single-note operations these two handlers submit. */+export type SingleNoteOperation = UpdateNoteOperation | AppendNoteOperation;++/**+ * Run a single-operation write batch and unwrap its one result, mapping+ * a typed {@link WriteBatchError} to a structured INVALID_PARAMS.+ *+ * The result kind is tied to the operation kind, so the caller reads the+ * kernel's own success flag back without restating it. This used to+ * return `path: "path" in only ? only.path : ""` - an unreachable arm+ * that, had it ever been reached, would have reported a successful write+ * at no path at all. A result whose kind does not match the operation is+ * a broken contract between this layer and the kernel, so it is raised as+ * one rather than papered over with an empty string.+ */+export function runSingleWrite<K extends SingleNoteOperation["kind"]>(+ ctx: ServerContext,+ op: Extract<SingleNoteOperation, { readonly kind: K }>,+ tool: string,+): Extract<NoteOpResult, { readonly kind: K }> {+ let batch;+ try {+ // A target the caller may not read at its reach is refused exactly+ // as a missing one. The transport-minted identity rides along as the+ // batch's subject (write-side-trust, Task 7): a token's update or+ // append answers for the token's agent, in the owner gate and the+ // deny-only document consult alike.+ batch = applyWriteBatch(ctx.vault, [op], {+ readable: readableAtContextReach(ctx),+ ...(ctx.configPath !== null ? { configPath: ctx.configPath } : {}),+ ...(ctx.requestIdentity !== undefined ? { subject: ctx.requestIdentity } : {}),+ });+ } catch (err) {+ throw writeBatchErrorToMcp(err, tool);+ }+ const only = batch.results[0]!;+ if (only.kind !== op.kind) {+ throw new MCPError(+ INTERNAL_ERROR,+ `${tool}: the write kernel returned a '${only.kind}' result for a '${op.kind}' operation`,+ );+ }+ return only as Extract<NoteOpResult, { readonly kind: K }>;+}++/**+ * The one write-result envelope, adopted by all four note-write tools+ * (evidence-at-the-boundary, task A4).+ *+ * Before this there was no shared envelope at all: four handlers+ * hand-built four shapes, two of them hardcoding a success flag the+ * kernel result already carried. This composes the tool's own receipt+ * with the write-time page lint over exactly the pages the call+ * committed.+ *+ * The lint runs AFTER the commit and reads what is on disk, because the+ * batch kernel wrote the bytes and the handler never composed them. It+ * never gates the write, and it contributes NO key when there is nothing+ * to say - so a receipt for a clean write is byte-identical to the one+ * that shipped before. `pages` empty (a skipped create, a log-only batch)+ * means no bytes were authored, so there is nothing to lint.+ *+ * The lint answers at the caller's reach: a near-duplicate sibling the+ * caller may not read is never named, scored or counted on the receipt, a+ * wikilink to a withheld Brain page reads as broken, and a merge chain+ * ends at its first withheld hop, as they would if the page were absent.+ *+ * With `near_duplicate_write_widening_enabled` on, the near-duplicate hint+ * also compares the pages with keyword-index candidates from other+ * directories ({@link collectWideningCandidates}), and the report states+ * whether that ran. With the key off nothing is opened and the receipt is+ * exactly the one that shipped before.+ *+ * Under an open route scope the lint is timed as the `lint` stage and the+ * widening as `near_duplicate_lookup`, the stage the lint's own+ * near-duplicate scoring also adds to.+ */+export async function noteWriteResult<T extends Record<string, unknown>>(+ ctx: ServerContext,+ pages: ReadonlyArray<string>,+ receipt: T,+): Promise<T & PageLintField> {+ if (pages.length === 0) return receipt;+ const readable = readableAtContextReach(ctx);+ const widening = await timeStage(ROUTE_STAGE.nearDuplicateLookup, () =>+ widenNearDuplicates(ctx, pages, readable),+ );+ const opts: LintWrittenPagesOptions =+ widening === undefined+ ? { readable }+ : {+ readable,+ extraCandidates: widening.candidates,+ widening: widening.status,+ ...(widening.detail !== undefined ? { wideningDetail: widening.detail } : {}),+ };+ const report = timeStageSync(ROUTE_STAGE.lint, () => lintWrittenPages(ctx.vault, pages, opts));+ return { ...receipt, ...pageLintField(report) };+}++/**+ * Keyword-index candidates for the near-duplicate hint, or `undefined`+ * when widening is off. A search config that does not resolve leaves no+ * index to read, which is the same named `index_unavailable` an index+ * that will not open reports, with the failure named in its detail: the+ * write is never failed by its hint.+ */+export async function widenNearDuplicates(+ ctx: ServerContext,+ pages: ReadonlyArray<string>,+ readable: ReadableRef,+): Promise<WideningResult | undefined> {+ const configPath = ctx.configPath ?? undefined;+ if (!resolveNearDuplicateWriteWideningEnabled(configPath)) return undefined;+ let config: ResolvedSearchConfig;+ try {+ config = resolveSearchConfig({ vault: ctx.vault, configPath });+ } catch (err) {+ return wideningUnavailable(err);+ }+ return collectWideningCandidates(config, ctx.vault, pages, readable);+}diff --git a/src/mcp/brain/pack-context-tools.ts b/src/mcp/brain/pack-context-tools.tsnew file mode 100644index 00000000..6aa48e43--- /dev/null+++ b/src/mcp/brain/pack-context-tools.ts@@ -0,0 +1,472 @@+/**+ * `brain_context_pack` (task 3.19): the composed context the agent+ * session opens with, assembled at the caller's reach from the rules,+ * digests, pinned context and session evidence the caller may read.+ * Split from `pack-tools.ts`; registration happens through that+ * module's registry, which preserves the public PACK_TOOLS surface.+ */++import {+ resolveDensityRankingContextPack,+ resolveEntityFactsContextPack,+ resolveRecallAdequacyThresholds,+ resolveRecallGateTelemetry,+ resolveSearchFocusContextPack,+ resolveTailTrimContextPack,+} from "../../core/config.ts";+import { resolveSearchConfig } from "../../core/search/index.ts";+import {+ loadBeliefSemanticRelevance,+ spentQueryDisclosure,+} from "../../core/brain/belief-semantic.ts";+import { readActiveSessionFocus } from "../../core/search/session-focus.ts";+import {+ CONTEXT_PACK_QUERY_MODES,+ ContextPackPackingLaneEmptyError,+ isContextPackQueryMode,+ packContext,+} from "../../core/brain/context-pack.ts";+import {+ isPackingPolicy,+ PACKING_POLICIES,+ type PackingPolicy,+} from "../../core/brain/recall-budget.ts";+import { assessRecallAdequacy } from "../../core/brain/recall-adequacy.ts";+import { recordRecallAdequacyDemand } from "../../core/brain/query-demand.ts";+import { emitGatedTelemetry } from "../../core/brain/continuity/emit.ts";+import {+ presetForResolvedWindow,+ unrecognisedModelBudgetRefusal,+} from "../../core/brain/context-presets.ts";+import { type ModelWindowSource, type ResolvedModelWindow } from "../../core/brain/model-window.ts";+import { ownerScopeView } from "../../core/brain/owner-scope-view.ts";+import { resolveOwnerScopeDelivery } from "../../core/brain/preferences-collect.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import type { ServerContext } from "../tool-contract.ts";+import { contextReach } from "../tool-contract.ts";+import { reachView } from "../../core/brain/reach-view.ts";+import { TRANSPORT_REACH } from "../../core/graph/transport-reach.ts";+import { vaultPathField } from "../vault-path-field.ts";+import { exceedsMcpQueryCap, MCP_QUERY_CAP_MESSAGE } from "../search-tools.ts";+import {+ coerceAgentScope,+ coerceDecisionAnswerable,+ coerceRecallAdequacyInput,+ DECISION_ANSWERABLE_ARG_NAME,+ coerceStr,+ coerceStrList,+ coerceBool,+} from "../coerce.ts";+import { decisionAnswerableFor } from "../decision-answerable.ts";+import { coercePositiveInteger, telemetryOptionsFromArgs } from "./shared.ts";+import {+ RECALL_SCORES_ARG_NAME,+ configuredDegradation,+ discloseSpentPackQuery,+ optionalModelArg,+ receiptOptionsFromArgs,+ resolveSurfaceModelWindow,+ semanticReportField,+ vaultRelative,+ withSearchErrorsOnWire,+} from "./pack-shared.ts";++export async function toolBrainContextPack(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const model = optionalModelArg("brain_context_pack", args);+ const maxTokensArg = coercePositiveInteger(+ "brain_context_pack",+ "max_tokens",+ args["max_tokens"],+ );+ // The adequacy pairing is an input-SHAPE contract, declared in the+ // schema's `dependentRequired`, so it refuses an incomplete pair by+ // name before any semantic refusal can preempt it: `max_tokens` is now+ // optional behind the derivation below (t_a567cc12), and a payload+ // carrying one half of the pair must learn about the pairing, not about+ // a budget it never sent.+ const recallAttempt = coerceRecallAdequacyInput(+ "brain_context_pack",+ args,+ RECALL_SCORES_ARG_NAME,+ );+ const answerableArg = coerceDecisionAnswerable(+ "brain_context_pack",+ args,+ RECALL_SCORES_ARG_NAME,+ recallAttempt !== undefined,+ );+ // Derived budget (t_a567cc12): an explicit `max_tokens` is first-class+ // and untouched. When it is omitted, the budget derives from the model+ // context window the resolver resolves, through the matching preset's+ // `context_pack.max_tokens` - the curated mapping. A `default`-sourced+ // window defers to the model's hint preset, the same mapping+ // `brain_context_presets` suggest answers, so one model gets one budget+ // and one suggestion on every surface - and an id NOTHING places (no+ // table row, no suffix, no hint) refuses: the conservative posture this+ // tool held before derivation existed, never the default window's+ // long-context budget an 8k local model cannot hold. With nothing+ // resolvable the call refuses exactly as before: the pinned decision is+ // never a silent default budget.+ let maxTokens: number;+ let maxTokensSource: ModelWindowSource | undefined;+ if (maxTokensArg !== undefined) {+ maxTokens = maxTokensArg;+ } else {+ let resolved: ResolvedModelWindow | null;+ try {+ resolved = resolveSurfaceModelWindow(ctx.vault, model ?? undefined);+ } catch (e) {+ throw new MCPError(INVALID_PARAMS, `brain_context_pack: ${(e as Error).message}`);+ }+ if (resolved === null) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_context_pack: max_tokens must be a positive integer",+ );+ }+ const refusal = unrecognisedModelBudgetRefusal(model, resolved);+ if (refusal !== null) {+ throw new MCPError(INVALID_PARAMS, `brain_context_pack: ${refusal}`);+ }+ // The hint fallback rides along exactly when the resolver's answer is+ // the default-sourced assumption, so a hint-only model budgets the+ // preset `brain_context_presets` suggest names for it; the source+ // disclosed on the wire stays the window's.+ maxTokens = presetForResolvedWindow(model, resolved).context_pack.max_tokens;+ maxTokensSource = resolved.source;+ }+ const query = typeof args["query"] === "string" ? (args["query"] as string) : undefined;+ // Ranked query mode (v1.53.0). Enforced beside the `dependentRequired`+ // that declares it: a mode with no query would otherwise be accepted and+ // do nothing, which is the silent no-op this project refuses.+ const queryMode = coerceStr(args, "query_mode", false);+ if (queryMode !== null) {+ if (!isContextPackQueryMode(queryMode)) {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_context_pack: query_mode must be one of ${CONTEXT_PACK_QUERY_MODES.join(", ")}`,+ );+ }+ if (query === undefined) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_context_pack: query_mode requires query; a mode with nothing to read is inert",+ );+ }+ // The semantic query is embedded once, ungated: a blank one buys nothing.+ if (queryMode === "semantic" && query.trim() === "") {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_context_pack: query_mode requires a non-empty query",+ );+ }+ }+ // Opt-in packing policy (recall-lane-latency wave). Refused beside the+ // `dependentRequired` that declares it, exactly as query_mode is: a+ // policy with no query has no turn to pack for and would be the silent+ // no-op this project refuses. A blank or whitespace-only query is the+ // same refusal, not a pass: the empty string is dropped before the core+ // and the null query filter-passes every candidate, so the policy would+ // silently reorder an unordered pack - the exact evasion the raw read+ // above would otherwise allow.+ const packingPolicy = coerceStr(args, "packing_policy", false);+ if (packingPolicy !== null) {+ if (!isPackingPolicy(packingPolicy)) {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_context_pack: packing_policy must be one of ${PACKING_POLICIES.join(", ")}`,+ );+ }+ if (query === undefined || query.trim() === "") {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_context_pack: packing_policy requires query; a policy with nothing to order is inert",+ );+ }+ }+ if (query !== undefined && exceedsMcpQueryCap(query)) {+ throw new MCPError(INVALID_PARAMS, `brain_context_pack: ${MCP_QUERY_CAP_MESSAGE}`);+ }+ const includeLanes = coerceBool(args, "lanes");+ const cacheStable = coerceBool(args, "cache_stable");+ const dedupRepeated = coerceBool(args, "dedup_repeated");+ const attentionFlowIds = coerceStrList(args, "attention_flow_ids");+ const maxCharsPerMemory = coercePositiveInteger(+ "brain_context_pack",+ "max_chars_per_memory",+ args["max_chars_per_memory"],+ );+ const maxTotalChars = coercePositiveInteger(+ "brain_context_pack",+ "max_total_chars",+ args["max_total_chars"],+ );+ const receipt = receiptOptionsFromArgs("brain_context_pack", args, "context_pack", "mcp");+ const telemetry = telemetryOptionsFromArgs("brain_context_pack", args, "mcp");+ // The pairing coercions themselves ran above the budget derivation, so+ // an incomplete pair is refused by name; only the ASSESSMENT waits for+ // this point, beside the receipt and telemetry options it rides with.+ const adequacy =+ recallAttempt !== undefined+ ? assessRecallAdequacy(+ recallAttempt,+ resolveRecallAdequacyThresholds(ctx.configPath ?? undefined),+ )+ : undefined;+ // Advisory decision-model signal (issue #213, Part 8): annotates the+ // verdict and its receipt, never the level, the action or the pack.+ const answerable =+ adequacy !== undefined && answerableArg !== undefined+ ? decisionAnswerableFor(ctx, adequacy.level, answerableArg)+ : undefined;+ const answerableVerdict = answerable?.kind === "annotated" ? answerable.verdict : undefined;+ // signals-that-survive, unit 6: an unmet verdict is stamped onto the+ // cross-query demand log under the bucket key normalizeQueryTerms already+ // computes, so the knowledge-gap loop can aggregate recurrence without a+ // second identity concept.+ //+ // ONE opt-in for that log, on every surface that writes it: the+ // `recall_gate_telemetry` config key, exactly as `brain_recall_gate`+ // uses. It is a vault-level durable log feeding a vault-level loop, so+ // whether it is written is an operator decision, not a per-call one -+ // gating it here on this tool's `telemetry` ARGUMENT instead made one+ // feature answer to two different opt-ins and left the log's contents+ // depending on which surface a caller happened to use. That argument+ // keeps its own meaning: it selects whether THIS call emits its own+ // continuity records. Fail-open as ever - a log write never breaks the+ // pack.+ if (adequacy !== undefined && query !== undefined) {+ emitGatedTelemetry(resolveRecallGateTelemetry(ctx.configPath ?? undefined), () =>+ recordRecallAdequacyDemand(ctx.vault, { query, verdict: adequacy }),+ );+ }+ // Focus wiring (Agent Surface Suite, t_5b478e47): gated on the+ // search_focus_context_pack config key (default off) so the default+ // pack stays byte-identical. Fail-soft - a broken search config+ // never breaks the pack.+ let sessionFocus: ReturnType<typeof readActiveSessionFocus> = null;+ if (resolveSearchFocusContextPack(ctx.configPath ?? undefined)) {+ // Argument validation stays OUTSIDE the fail-soft block: an invalid+ // focus_session is a caller error (INVALID_PARAMS), not a config+ // read to swallow.+ const focusSession = coerceStr(args, "focus_session", false) ?? undefined;+ try {+ const searchConfig = resolveSearchConfig({+ vault: ctx.vault,+ configPath: ctx.configPath ?? undefined,+ });+ sessionFocus = readActiveSessionFocus(searchConfig, focusSession);+ } catch {+ sessionFocus = null;+ }+ }+ // Density-ranking wiring (impact-per-token allocation, t_affa3bd9):+ // gated on the density_ranking_context_pack config key (default off)+ // so the default pack stays byte-identical to the tier → recency order.+ const densityRanking = resolveDensityRankingContextPack(ctx.configPath ?? undefined);+ // Entity-facts wiring (dated commitments, t_43b0a379): gated on the+ // entity_facts_context_pack config key (default off) so the default+ // tool output carries no entity_facts key.+ const entityFacts = resolveEntityFactsContextPack(ctx.configPath ?? undefined);+ // Tail-trim wiring (t_cb6a5558): gated on the tail_trim_context_pack+ // config key (default off) so the default tool output carries no+ // tail_trim key and no trim ever runs.+ const tailTrim = resolveTailTrimContextPack(ctx.configPath ?? undefined);+ const agentScope = coerceAgentScope(ctx, args, true);+ // Root closure (t_sec_pack_reach): the pack reads page bodies by path,+ // outside the three read roots, so the reserved-token rule is asked per+ // candidate - the same shape `brain_clusters`/`brain_bridges` apply. It+ // is asked INSIDE the core, before ranking and budgeting, because every+ // other member of the report (`lanes`, `skipped`, tension `warnings`,+ // `deduped_from`, the receipt) is derived from the candidate set: a+ // filter over `items` alone left a reserved page's path and body in+ // `lanes` and its id in `skipped`. At local reach the view is the shared+ // no-op, so an operator's own transports see a byte-identical pack. The+ // core holds absolute paths; the view answers over vault-relative ones.+ const view = reachView(ctx.vault, contextReach(ctx));+ const remote = view.reach !== TRANSPORT_REACH.local;+ // Semantic mode (Honest Embedding Spend): the one async step - the query+ // embed and the stored-vector read - happens here, so `packContext`+ // stays synchronous for every other caller. Every refusal is a named+ // SearchError: a blocked tier and a missing sqlite-vec from the loader,+ // before any embed, and `BELIEF_VECTORS_MISSING` from the pack, after+ // the reach filter and before a receipt is written. The loader reads+ // only the beliefs this caller's pack can keep - the same reach and+ // owner views the pack applies - so its own pre-embed refusal never+ // answers for a withheld belief differently than for an absent one.+ const semantic =+ queryMode === "semantic" && query !== undefined+ ? await withSearchErrorsOnWire(() => {+ const owners = ownerScopeView(+ ctx.vault,+ resolveOwnerScopeDelivery(ctx.vault, agentScope).enforcedScope,+ );+ return loadBeliefSemanticRelevance(+ resolveSearchConfig({ vault: ctx.vault, configPath: ctx.configPath ?? undefined }),+ query,+ { reach: view.reach, inView: (rel) => view.visible(rel) && owners.visible(rel) },+ );+ })+ : null;+ let report: Awaited<ReturnType<typeof packContext>>;+ try {+ report = await withSearchErrorsOnWire(+ async () =>+ packContext(ctx.vault, {+ ...(remote+ ? { visible: (abs: string) => view.visible(vaultRelative(ctx.vault, abs)) }+ : {}),+ maxTokens,+ ...(agentScope !== undefined ? { agentScope } : {}),+ ...(densityRanking ? { densityRanking: true } : {}),+ ...(entityFacts ? { entityFacts: true } : {}),+ ...(tailTrim ? { tailTrim: true } : {}),+ ...(sessionFocus !== null ? { sessionFocus } : {}),+ ...(query ? { query } : {}),+ ...(queryMode !== null ? { queryMode } : {}),+ ...(packingPolicy !== null ? { packingPolicy: packingPolicy as PackingPolicy } : {}),+ ...(includeLanes ? { includeLanes: true } : {}),+ ...(receipt !== undefined ? { receipt } : {}),+ ...(adequacy !== undefined ? { recallAdequacy: adequacy } : {}),+ ...(answerableVerdict !== undefined ? { decisionAnswerable: answerableVerdict } : {}),+ ...(cacheStable || dedupRepeated+ ? {+ transforms: {+ ...(cacheStable ? { cacheStableOrdering: true } : {}),+ ...(dedupRepeated ? { deduplicateRepeatedContext: true } : {}),+ },+ }+ : {}),+ ...(maxCharsPerMemory !== undefined ? { maxCharsPerMemory } : {}),+ ...(maxTotalChars !== undefined ? { maxTotalChars } : {}),+ ...(configuredDegradation(ctx.vault) !== undefined+ ? { degradation: configuredDegradation(ctx.vault)! }+ : {}),+ ...(telemetry !== undefined ? { telemetry } : {}),+ // The synthesized attention-flow block has no page of its own to ask+ // the reach view about, so a remote caller does not get it (fail+ // closed, as the per-item filter this replaced did).+ ...(attentionFlowIds.length > 0 && !remote ? { attentionFlowIds } : {}),+ ...(semantic !== null ? { semanticRelevance: semantic.relevanceByPath } : {}),+ }),+ discloseSpentPackQuery(semantic),+ );+ } catch (e) {+ // A policy against a one-lane vault is a caller error the core+ // refuses by name; on the wire it is INVALID_PARAMS carrying that+ // same named message, never an internal error and never a no-op.+ if (e instanceof ContextPackPackingLaneEmptyError) {+ // The spend disclosure rides the refusal too: in semantic mode the+ // query embed was paid before the lanes were judged, and a refusal+ // that hides that spend under-discloses exactly when the caller+ // gets nothing back for it.+ throw new MCPError(+ INVALID_PARAMS,+ semantic !== null ? `${e.message} ${spentQueryDisclosure(semantic.report)}` : e.message,+ );+ }+ throw e;+ }+ const warnings = [+ ...(report.warnings ?? []),+ ...(semantic?.warnings ?? []),+ ...(answerable?.kind === "ignored" ? [answerable.warning] : []),+ ];+ return {+ vault_path: vaultPathField(ctx),+ max_tokens: report.maxTokens,+ // Present only when the budget was derived (t_a567cc12): the channel+ // that decided, so a caller can see a resolution was assumed rather+ // than paid for. An explicit `max_tokens` answers without it.+ ...(maxTokensSource !== undefined ? { max_tokens_source: maxTokensSource } : {}),+ tokens_used: report.tokensUsed,+ items: report.items.map((i) => ({+ id: i.id,+ path: i.path,+ tier: i.tier,+ tokens: i.tokens,+ body: i.body,+ trimmed: i.trimmed,+ epistemic: i.epistemic,+ ...(i.evidenceRefs.length > 0 ? { evidence_refs: i.evidenceRefs } : {}),+ ...(i.density !== undefined ? { density: i.density } : {}),+ ...(i.originalRank !== undefined ? { original_rank: i.originalRank } : {}),+ ...(i.stableRank !== undefined ? { stable_rank: i.stableRank } : {}),+ ...(i.dedupedFrom !== undefined ? { deduped_from: i.dedupedFrom } : {}),+ ...(i.referenceHint !== undefined ? { reference_hint: i.referenceHint } : {}),+ ...(i.safety ? { safety: i.safety } : {}),+ })),+ skipped: report.skipped.map((s) => ({+ id: s.id,+ tokens: s.tokens,+ reason: s.reason,+ })),+ ...(report.receiptId ? { receipt_id: report.receiptId } : {}),+ ...(report.telemetryId ? { telemetry_id: report.telemetryId } : {}),+ ...(report.lanes ? { lanes: report.lanes } : {}),+ // The core computes injection-time tension warnings and the+ // owner-scope observation and this projection dropped both, so the one+ // surface that puts vault text in front of a model every turn was the+ // one surface that could not say a memory it injected is contested.+ // `brain_pre_compress_pack` has forwarded them all along; absent when+ // empty, so a warning-free pack stays byte-identical.+ ...(warnings.length > 0 ? { warnings } : {}),+ ...(semantic !== null && report.semantic !== undefined+ ? { semantic: semanticReportField(semantic, report.semantic) }+ : {}),+ // The packing accounting appears only when the caller named a+ // policy - the same conditional shape as `semantic` above.+ ...(report.packing ? { packing: report.packing } : {}),+ // The entity-facts rollup appears only when the config key resolved+ // on - the same conditional shape as `packing` above. Fields project+ // to the tool's wire casing.+ ...(report.entityFacts+ ? {+ entity_facts: {+ entities: report.entityFacts.entities.map((e) => ({+ entity_id: e.entityId,+ name: e.name,+ item_ids: e.itemIds,+ })),+ },+ }+ : {}),+ // The trim block appears only when the config key resolved on AND+ // the pack actually trimmed - the same conditional shape as+ // `entity_facts` above. Fields project to the tool's wire casing.+ ...(report.tailTrim+ ? {+ tail_trim: {+ dropped: report.tailTrim.dropped,+ kept_by_query_terms: report.tailTrim.keptByQueryTerms,+ rescued: report.tailTrim.rescued,+ tokens_saved: report.tailTrim.tokensSaved,+ },+ }+ : {}),+ ...(adequacy !== undefined+ ? {+ adequacy: {+ level: adequacy.level,+ action: adequacy.action,+ escalate: adequacy.escalate,+ result_count: adequacy.resultCount,+ top_score: adequacy.topScore,+ mean_score: adequacy.meanScore,+ reason: adequacy.reason,+ ...(answerableVerdict !== undefined+ ? {+ [DECISION_ANSWERABLE_ARG_NAME]: {+ probability: answerableVerdict.probability,+ disagrees: answerableVerdict.disagrees,+ },+ }+ : {}),+ },+ }+ : {}),+ };+}diff --git a/src/mcp/brain/pack-preset-tools.ts b/src/mcp/brain/pack-preset-tools.tsnew file mode 100644index 00000000..6a159c7d--- /dev/null+++ b/src/mcp/brain/pack-preset-tools.ts@@ -0,0 +1,310 @@+/**+ * The preset and anticipatory tools of the pack family (task 3.19):+ * `brain_context_presets`, `brain_pre_compress_pack`,+ * `brain_pre_compact_extract` and `brain_anticipatory_context`. Split+ * from `pack-tools.ts`; registration happens through that module's+ * registry, which preserves the public PACK_TOOLS surface.+ */++import {+ buildReaderAnticipatoryContext,+ readAnticipatoryContext,+ refreshAnticipatoryCache,+ type ReadAnticipatoryContextResult,+} from "../../core/brain/anticipatory-cache.ts";+import { loadBrainConfig } from "../../core/brain/policy.ts";+import { buildPreCompressPack } from "../../core/brain/pre-compress-pack.ts";+import {+ diffContextPreset,+ getContextPreset,+ listContextPresets,+ presetForResolvedWindow,+ suggestContextPreset,+ type ContextPresetCurrentConfig,+} from "../../core/brain/context-presets.ts";+import {+ MODEL_CONTEXT_WINDOW_ENV_KEY,+ type ResolvedModelWindow,+} from "../../core/brain/model-window.ts";+import { extractPreCompactRecords } from "../../core/brain/pre-compact-extract.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import type { ServerContext } from "../tool-contract.ts";+import { contextReach } from "../tool-contract.ts";+import { readableAtContextReachOrUndefined } from "./reach-readable.ts";+import { reachView } from "../../core/brain/reach-view.ts";+import { TRANSPORT_REACH } from "../../core/graph/transport-reach.ts";+import { vaultPathField } from "../vault-path-field.ts";+import { coerceAgentScope, coerceStr, coerceBool, unknownOperationError } from "../coerce.ts";+import {+ coercePositiveInteger,+ optionalStringArg,+ requiredStringArg,+ telemetryOptionsFromArgs,+} from "./shared.ts";+import {+ configuredDegradation,+ optionalModelArg,+ receiptOptionsFromArgs,+ resolveSurfaceModelWindow,+ vaultRelative,+} from "./pack-shared.ts";++export async function toolBrainContextPresets(+ _ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const operation = optionalStringArg("brain_context_presets", args, "operation");+ if (operation === "show") {+ const presetId = optionalStringArg("brain_context_presets", args, "preset_id");+ const result =+ presetId === undefined ? { presets: listContextPresets() } : getContextPreset(presetId);+ if (result === null) {+ throw new MCPError(INVALID_PARAMS, `brain_context_presets: unknown preset ${presetId}`);+ }+ return Array.isArray(result) ? { presets: result } : { ...result };+ }+ if (operation === "suggest") {+ const model = optionalStringArg("brain_context_presets", args, "model");+ const window = coercePositiveInteger(+ "brain_context_presets",+ "context_window_tokens",+ args["context_window_tokens"],+ );+ return {+ ...suggestContextPreset({+ ...(model !== undefined ? { model } : {}),+ ...(window !== undefined ? { contextWindowTokens: window } : {}),+ }),+ };+ }+ if (operation === "diff") {+ const presetId = optionalStringArg("brain_context_presets", args, "preset_id");+ if (presetId === undefined) {+ throw new MCPError(INVALID_PARAMS, "brain_context_presets: preset_id is required for diff");+ }+ return {+ ...diffContextPreset(presetId, contextPresetCurrentConfig(args["current"])),+ };+ }+ throw unknownOperationError("brain_context_presets: operation must be show, suggest, or diff");+}++export function contextPresetCurrentConfig(raw: unknown): ContextPresetCurrentConfig {+ if (raw === undefined || raw === null) return {};+ if (typeof raw !== "object" || Array.isArray(raw)) {+ throw new MCPError(INVALID_PARAMS, "brain_context_presets: current must be an object");+ }+ return raw as ContextPresetCurrentConfig;+}++// ----- brain_pre_compact_extract ------------------------------------------++/**+ * Read-only bundle of the highest-confidence confirmed preferences plus+ * the head of active.md, rendered as a system-prompt addendum for a host+ * runtime to inject just before a context-compression event.+ */+export async function toolBrainPreCompressPack(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const model = optionalModelArg("brain_pre_compress_pack", args);+ const topK = coercePositiveInteger("brain_pre_compress_pack", "top_k", args["top_k"]) ?? 10;+ const maxCharsPerMemory = coercePositiveInteger(+ "brain_pre_compress_pack",+ "max_chars_per_memory",+ args["max_chars_per_memory"],+ );+ const maxTotalChars = coercePositiveInteger(+ "brain_pre_compress_pack",+ "max_total_chars",+ args["max_total_chars"],+ );+ // Derived caps (t_a567cc12): an absent cap used to mean unbounded - the+ // one injection surface with no ceiling at all. When a cap is absent+ // and a window resolves, the matching preset's `pre_compress` block+ // fills it; explicit caps stay first-class; with nothing resolvable the+ // historical unbounded addendum stands, byte-identical. `top_k` keeps+ // its own 10 default - the presets' top-k values are suggestion+ // diagnostics, not this tool's default.+ let resolvedCaps: ResolvedModelWindow | null = null;+ // A malformed OPEN_SECOND_BRAIN_MODEL_CONTEXT_WINDOW used to rethrow+ // here as INVALID_PARAMS - blaming the caller's parameters and losing+ // the addendum over an operator typo the caller cannot see and this+ // result never disclosed. On THIS path an unparseable env value means+ // nothing resolvable: the historical unbounded caps stand and a named+ // warning says which channel misread, never echoing the value itself.+ let windowWarning: string | undefined;+ if (maxCharsPerMemory === undefined || maxTotalChars === undefined) {+ try {+ resolvedCaps = resolveSurfaceModelWindow(ctx.vault, model ?? undefined);+ } catch {+ resolvedCaps = null;+ windowWarning =+ `${MODEL_CONTEXT_WINDOW_ENV_KEY} is not a well-formed positive integer; ` ++ "pre-compress caps stay unbounded and nothing was derived from it";+ }+ }+ // The hint fallback rides along here exactly as it does in the+ // context-pack budget above: when the resolver's answer is the+ // default-sourced assumption, a hint-only model's caps come from its+ // hint preset, the same mapping the pack and `brain_context_presets`+ // suggest name - one model, one mapping on every surface.+ const derivedCaps =+ resolvedCaps !== null ? presetForResolvedWindow(model, resolvedCaps).pre_compress : null;+ const effMaxCharsPerMemory = maxCharsPerMemory ?? derivedCaps?.max_chars_per_memory;+ const effMaxTotalChars = maxTotalChars ?? derivedCaps?.max_total_chars;+ const receipt = receiptOptionsFromArgs("brain_pre_compress_pack", args, "pre_compress", "mcp");+ const telemetry = telemetryOptionsFromArgs("brain_pre_compress_pack", args, "mcp");+ const agentScope = coerceAgentScope(ctx, args, true);+ const readable = readableAtContextReachOrUndefined(ctx);+ const pack = buildPreCompressPack(ctx.vault, {+ topK,+ // A preference the caller cannot read at its reach is absent from the+ // head and from the top-K walk alike; a caller from whom nothing can+ // be withheld is handed no filter.+ ...(readable !== undefined ? { readable } : {}),+ restricted: contextReach(ctx) !== TRANSPORT_REACH.local,+ ...(agentScope !== undefined ? { agentScope } : {}),+ ...(effMaxCharsPerMemory !== undefined ? { maxCharsPerMemory: effMaxCharsPerMemory } : {}),+ ...(effMaxTotalChars !== undefined ? { maxTotalChars: effMaxTotalChars } : {}),+ ...(configuredDegradation(ctx.vault) !== undefined+ ? { degradation: configuredDegradation(ctx.vault)! }+ : {}),+ ...(receipt !== undefined ? { receipt } : {}),+ ...(telemetry !== undefined ? { telemetry } : {}),+ });+ return {+ vault_path: vaultPathField(ctx),+ text: pack.text,+ active_head_included: pack.activeHeadIncluded,+ ...(pack.activeHeadSafety ? { active_head_safety: pack.activeHeadSafety } : {}),+ total_chars: pack.totalChars,+ // The pack's one degradation channel. This is the only surface the+ // builder has, so a warning dropped here is a broken `_brain.yaml`+ // nothing tells the caller about.+ ...(pack.warnings ? { warnings: pack.warnings } : {}),+ // The window channel's own warning: present only when the derivation+ // was skipped over an unparseable operator env value (M4), so a+ // normal answer stays byte-identical.+ ...(windowWarning !== undefined ? { window_warning: windowWarning } : {}),+ ...(pack.receiptId ? { receipt_id: pack.receiptId } : {}),+ ...(pack.telemetryId ? { telemetry_id: pack.telemetryId } : {}),+ items: pack.items.map((i) => ({+ id: i.id,+ principle: i.principle,+ trimmed: i.trimmed,+ ...(i.safety ? { safety: i.safety } : {}),+ })),+ };+}++export async function toolBrainPreCompactExtract(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const sessionId = requiredStringArg("brain_pre_compact_extract", args, "session_id");+ const turnStart = requiredStringArg("brain_pre_compact_extract", args, "turn_start");+ const turnEnd = requiredStringArg("brain_pre_compact_extract", args, "turn_end");+ const text = requiredStringArg("brain_pre_compact_extract", args, "text");+ const maxChars = coercePositiveInteger(+ "brain_pre_compact_extract",+ "max_chars",+ args["max_chars"],+ );+ const result = extractPreCompactRecords(ctx.vault, {+ sessionId,+ turnStart,+ turnEnd,+ text,+ ...(optionalStringArg("brain_pre_compact_extract", args, "host") !== undefined+ ? { host: optionalStringArg("brain_pre_compact_extract", args, "host") }+ : {}),+ ...(maxChars !== undefined ? { maxChars } : {}),+ ...(coerceBool(args, "interrupted") === true ? { interrupted: true } : {}),+ ...(coerceBool(args, "dry_run") === true ? { dryRun: true } : {}),+ });+ return { count: result.records.length, dry_run: coerceBool(args, "dry_run") === true, ...result };+}++// ----- session recall DAG --------------------------------------------------++export async function toolBrainAnticipatoryContext(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const sessionId = coerceStr(args, "session_id");+ if (sessionId === null || sessionId === undefined || sessionId.trim() === "") {+ throw new MCPError(INVALID_PARAMS, "'session_id' is required");+ }+ let ttlSeconds: number | undefined;+ let maxTokens: number | undefined;+ try {+ const anticipatory = loadBrainConfig(ctx.vault).anticipatory;+ ttlSeconds = anticipatory?.ttl_seconds;+ maxTokens = anticipatory?.max_tokens;+ } catch {+ // defaults apply; a broken config never blocks a read+ }+ const anticipatoryScope = coerceAgentScope(ctx, args, true);+ const now = new Date();+ // Below local reach the bundle is built for this caller with the same+ // candidate filter `brain_context_pack` applies, and the shared cache is+ // neither read nor written: a cached bundle may hold pages this caller+ // cannot read, and a filtered bundle must not replace the operator's.+ const view = reachView(ctx.vault, contextReach(ctx));+ const remote = view.reach !== TRANSPORT_REACH.local;+ if (remote) {+ // A refresh takes the caller's signal exactly as the cached path does;+ // a plain read has no cached signal to reuse here.+ const signal = coerceBool(args, "refresh") === true ? coerceStr(args, "signal_text") : null;+ const result = buildReaderAnticipatoryContext(ctx.vault, {+ sessionId,+ now,+ visible: (abs: string) => view.visible(vaultRelative(ctx.vault, abs)),+ ...(anticipatoryScope !== undefined ? { agentScope: anticipatoryScope } : {}),+ ...(maxTokens !== undefined ? { maxTokens } : {}),+ ...(typeof signal === "string" ? { signalText: signal } : {}),+ });+ return anticipatoryAnswer(result);+ }+ if (coerceBool(args, "refresh") === true) {+ const signal = coerceStr(args, "signal_text");+ refreshAnticipatoryCache(ctx.vault, {+ sessionId,+ ...(anticipatoryScope !== undefined ? { agentScope: anticipatoryScope } : {}),+ ...(typeof signal === "string" && signal.trim() !== "" ? { signalText: signal } : {}),+ now,+ ...(ttlSeconds !== undefined ? { ttlSeconds } : {}),+ ...(maxTokens !== undefined ? { maxTokens } : {}),+ });+ }+ const result = readAnticipatoryContext(ctx.vault, {+ sessionId,+ now,+ ...(anticipatoryScope !== undefined ? { agentScope: anticipatoryScope } : {}),+ ...(ttlSeconds !== undefined ? { ttlSeconds } : {}),+ ...(maxTokens !== undefined ? { maxTokens } : {}),+ });+ return anticipatoryAnswer(result);+}++export function anticipatoryAnswer(result: ReadAnticipatoryContextResult): Record<string, unknown> {+ return {+ cache_state: result.cache_state,+ root_session_id: result.root_session_id,+ ...(result.generated_at !== undefined ? { generated_at: result.generated_at } : {}),+ // Present only when a fresh-by-the-clock entry was refused on its+ // provenance stamp or validity window, so an ordinary miss stays+ // byte-identical (context-integrity-gates, Unit B).+ ...(result.cache_refusal !== undefined ? { cache_refusal: result.cache_refusal } : {}),+ items: result.context.items.map((item) => ({+ id: item.id,+ tier: item.tier,+ tokens: item.tokens,+ principle: item.principle,+ body: item.body,+ })),+ session_hits: result.context.session_hits,+ };+}diff --git a/src/mcp/brain/pack-receipt-tools.ts b/src/mcp/brain/pack-receipt-tools.tsnew file mode 100644index 00000000..f5e7ebb5--- /dev/null+++ b/src/mcp/brain/pack-receipt-tools.ts@@ -0,0 +1,512 @@+/**+ * The context receipt tools of the pack family (task 3.19):+ * `brain_context_receipts` with its verify operation, the reach rules+ * the receipts answer under, the aggregation, and `brain_event_trace`.+ * Split from `pack-tools.ts`; registration happens through that+ * module's registry, which preserves the public PACK_TOOLS surface.+ */++import {+ assertContextReceiptWindowBound,+ CONTEXT_RECEIPT_TRIGGERS,+ getContextReceipt,+ isContextReceiptTrigger,+ listContextReceipts,+ lookupReceiptReplyPresence,+ RECEIPT_ITEM_ACTIVE_BODY,+ RECEIPT_ITEM_LESSONS_BODY,+ RECEIPT_ITEM_SCOPED_RULES,+ RECEIPT_ITEM_STANDING_RULES,+ summarizeContextReceipt,+ summarizeContextReceiptSession,+} from "../../core/brain/context-receipts.ts";+import { verifyContextReceipt } from "../../core/brain/context-receipts-verify.ts";+import type { ContinuityRecord } from "../../core/brain/continuity/types.ts";+import { observedReuseRates } from "../../core/brain/observed-use.ts";+import { EventTraceSelectorError, resolveLogEventTraces } from "../../core/brain/event-trace.ts";+import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";+import { pageSlice } from "../../core/brain/offset-cursor.ts";+import { cursorOffsetArg } from "./pagination.ts";+import { BRAIN_LOG_EVENT_KIND_SET, type BrainLogEventKind } from "../../core/brain/types.ts";+import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";+import type { ServerContext } from "../tool-contract.ts";+import { contextReach } from "../tool-contract.ts";+import { reachView } from "../../core/brain/reach-view.ts";+import { TRANSPORT_REACH } from "../../core/graph/transport-reach.ts";+import { vaultPathField } from "../vault-path-field.ts";+import { coerceBool, unknownOperationError } from "../coerce.ts";+import { coercePositiveInteger, optionalStringArg } from "./shared.ts";++// ----- brain_context_receipts ---------------------------------------------++export async function toolBrainContextReceipts(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const operation = optionalStringArg("brain_context_receipts", args, "operation");+ if (operation === "list") {+ const trigger = optionalStringArg("brain_context_receipts", args, "trigger");+ if (trigger !== undefined && !isContextReceiptTrigger(trigger)) {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_context_receipts: trigger must be one of ${CONTEXT_RECEIPT_TRIGGERS.join(", ")}`,+ );+ }+ const host = optionalStringArg("brain_context_receipts", args, "host");+ const sessionId = optionalStringArg("brain_context_receipts", args, "session_id");+ const limit = coercePositiveInteger("brain_context_receipts", "limit", args["limit"]);+ const offset = cursorOffsetArg("brain_context_receipts", args);+ const local = contextReach(ctx) === TRANSPORT_REACH.local;+ // The full filtered set is read and one page is cut here, so `total`+ // stays the exact count matching the filter across all pages and the+ // walk continues through `next_cursor` (null when exhausted).+ const receipts = listContextReceipts(ctx.vault, {+ ...(trigger !== undefined ? { trigger } : {}),+ ...(host !== undefined ? { host } : {}),+ ...(sessionId !== undefined ? { sessionId } : {}),+ ...(local ? {} : { exclude: isRuleOnlyInjection }),+ });+ // The join is show-only: summarizeContextReceipt's second parameter+ // is the presence join, so the summaries are mapped through an arrow+ // - a point-free `.map(summarizeContextReceipt)` would hand every+ // row's ARRAY INDEX to that parameter.+ const summaries = receipts+ .map((receipt) => receiptAtReach(receipt, local))+ .map((receipt) => summarizeContextReceipt(receipt));+ const page = pageSlice(summaries, offset, limit ?? Math.max(summaries.length, 1));+ return {+ vault_path: vaultPathField(ctx),+ total: page.total,+ receipts: page.items,+ next_cursor: page.next_cursor,+ };+ }++ if (operation === "show") {+ const id = optionalStringArg("brain_context_receipts", args, "id");+ if (id === undefined) {+ throw new MCPError(INVALID_PARAMS, "brain_context_receipts: id is required for show");+ }+ const local = contextReach(ctx) === TRANSPORT_REACH.local;+ const stored = getContextReceipt(ctx.vault, id);+ // Below local reach a receipt that recorded only the operator rules+ // is answered as an unknown id: showing it would say rules applied.+ if (stored === null || (!local && isRuleOnlyInjection(stored))) {+ throw new MCPError(INVALID_PARAMS, `brain_context_receipts: receipt not found: ${id}`);+ }+ const receipt = receiptAtReach(stored, local);+ return {+ id: receipt.id,+ kind: receipt.kind,+ createdAt: receipt.createdAt,+ sourceRefs: receipt.sourceRefs,+ payload: receipt.payload,+ private: receipt.private,+ redacted: receipt.redacted,+ // The receipt's session reply-presence join (t_f8510c55): the+ // per-note verdicts of the session's latest reply_presence record,+ // or the named unjoined outcome - a receipt whose session checked+ // no turn, or that names no session at all, says so instead of+ // reading as silently absent. The lookup runs on the reach-adjusted+ // record, so a payload redacted below local reach joins only on+ // what it still carries - and through the caller's reach view, so+ // a note row naming a page reserved below local reach drops from+ // `per_note` (counted in `withheld`) instead of disclosing its+ // path, range and verdict to a caller the page withheld itself from.+ reply_presence: lookupReceiptReplyPresence(+ ctx.vault,+ receipt,+ reachView(ctx.vault, contextReach(ctx)),+ ),+ };+ }++ if (operation === "summary") return summarizeReceipts(ctx, args);++ if (operation === "verify") return verifyReceipt(ctx, args);++ throw unknownOperationError(+ "brain_context_receipts: operation must be list, show, summary, or verify",+ );+}++// ----- brain_context_receipts verify (t_4300e5fd) ---------------------------++/** The `operation` value a verify refusal names. */+export const RECEIPT_VERIFY_OPERATION = "verify" as const;++/** The refusal reason when the caller is below local reach. */+export const RECEIPT_VERIFY_REACH_REASON = "reach" as const;++/** The refusal reason when the receipt is flagged private or redacted. */+export const RECEIPT_VERIFY_WITHHELD_REASON = "receipt_withheld" as const;++export type ReceiptVerifyRefusalReason =+ | typeof RECEIPT_VERIFY_REACH_REASON+ | typeof RECEIPT_VERIFY_WITHHELD_REASON;++/**+ * A verify call that was not answered, in the shape the receipts+ * surfaces already use for a refused half (`ReceiptCompactRefusal`):+ * the operation names itself, `measured: false` says no item was+ * re-hashed, and the reason names which guard refused - never a partial+ * verification.+ */+export interface ReceiptVerifyRefusal {+ readonly operation: typeof RECEIPT_VERIFY_OPERATION;+ readonly measured: false;+ readonly reason: ReceiptVerifyRefusalReason;+ readonly detail: string;+}++/**+ * Re-hash verification of one stored receipt (t_4300e5fd).+ *+ * Read-only, and local-reach only: the kernel re-reads the vault pages+ * the receipt names, and page content is host-local, so a caller below+ * local reach gets the typed refusal instead of a partial answer - the+ * same posture the `brain_receipts` compact half takes. A receipt the+ * session fold withholds (`private` or `redacted`) is refused+ * symmetrically: the fold never unfolds it, and verify never re-hashes+ * it.+ */+export async function verifyReceipt(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const id = optionalStringArg("brain_context_receipts", args, "id");+ if (id === undefined) {+ throw new MCPError(INVALID_PARAMS, "brain_context_receipts: id is required for verify");+ }+ if (contextReach(ctx) !== TRANSPORT_REACH.local) {+ // Returned as the literal, `satisfies`-checked against the refusal+ // interface, mirroring the compact refusal's construction: the+ // handler's wire type is Record<string, unknown>, and a value held+ // in the interface's name would not carry the index signature.+ return {+ operation: RECEIPT_VERIFY_OPERATION,+ measured: false,+ reason: RECEIPT_VERIFY_REACH_REASON satisfies ReceiptVerifyRefusalReason,+ detail:+ "context receipt verification re-reads the vault pages the receipt names; " ++ "page content is host-local, so it answers at local reach only",+ } satisfies ReceiptVerifyRefusal;+ }+ const stored = getContextReceipt(ctx.vault, id);+ if (stored === null) {+ throw new MCPError(INVALID_PARAMS, `brain_context_receipts: receipt not found: ${id}`);+ }+ if (stored.private || stored.redacted) {+ return {+ operation: RECEIPT_VERIFY_OPERATION,+ measured: false,+ reason: RECEIPT_VERIFY_WITHHELD_REASON satisfies ReceiptVerifyRefusalReason,+ detail:+ "the receipt is flagged private or redacted and is refused symmetrically " ++ "with the session fold, which withholds it whole",+ } satisfies ReceiptVerifyRefusal;+ }+ // Spread, not returned in its own name: the kernel's frozen interface+ // carries no index signature, and the handler's wire type is+ // Record<string, unknown> (the members are unchanged by the spread).+ return { ...verifyContextReceipt(ctx.vault, stored) };+}++/** Predicate: a receipt item whose `id` is one of `ids`. */+export const itemIdIn =+ (ids: ReadonlySet<string>) =>+ (item: unknown): boolean => {+ const id = (item as { id?: unknown } | null)?.id;+ return typeof id === "string" && ids.has(id);+ };++/** Receipt items naming the operator-rule blocks the SessionStart hook injected. */+export const OPERATOR_RULE_ITEM_IDS: ReadonlySet<string> = new Set([+ RECEIPT_ITEM_STANDING_RULES,+ RECEIPT_ITEM_SCOPED_RULES,+]);++/**+ * One operator-rule receipt item. Exported beside+ * {@link isRuleOnlyInjection} for the brain_truth provenance join, which+ * strips these items from a mixed receipt below local reach - the same+ * shaping `receiptAtReach` applies to the receipts this tool serves.+ */+export const isOperatorRuleItem = itemIdIn(OPERATOR_RULE_ITEM_IDS);++/**+ * A measured injection receipt whose every item was an operator-rule+ * block: the hook recorded it only because rules applied (a session with+ * no `active.md` body to inject). Below local reach it+ * is withheld whole - left out of list and summary, refused by show -+ * since even its empty remainder would say that rules applied.+ *+ * Exported for the surfaces that must answer the same question the+ * receipts surface answers: the brain_truth provenance join excludes+ * these receipts below local reach, so a claim's provenance confirms no+ * more about the operator's rules than this tool does.+ */+export function isRuleOnlyInjection(record: ContinuityRecord): boolean {+ if (record.payload["trigger"] !== "session_inject") return false;+ // A degraded injection that served a cached body beside the rules is+ // recorded whether or not rules applied: it stays, emptied of them. One+ // with no cached body (`loader_source: "empty"`) exists only because the+ // rules were injected, so it is rule-only like a measured one.+ const injection = record.payload["injection"] as+ | { sources_measured?: unknown; loader_source?: unknown }+ | undefined;+ if (injection?.sources_measured === false && injection.loader_source !== "empty") return false;+ const items = record.payload["items"];+ return Array.isArray(items) && items.length > 0 && items.every(isOperatorRuleItem);+}++/** Receipt items charged against the injection budget besides the scoped rules. */+export const BUDGETED_BODY_ITEM_IDS: ReadonlySet<string> = new Set([+ RECEIPT_ITEM_ACTIVE_BODY,+ RECEIPT_ITEM_LESSONS_BODY,+]);++export const isBudgetedBodyItem = itemIdIn(BUDGETED_BODY_ITEM_IDS);++/** Payload fields of an injection receipt whose figures include the operator-rule blocks. */+export const INJECTION_TOTAL_FIELDS = ["final_text_hash", "final_text_chars"] as const;+export const INJECTION_EXTRA_TOTAL_FIELDS = ["total_bytes", "total_tokens"] as const;+export const BUDGET_RULE_FIELDS = ["scoped_rules_chars", "budgeted_source_count"] as const;++/**+ * A stored receipt as the caller may see it at its reach.+ *+ * At local reach the record is returned unchanged. Below it, an injection+ * receipt says nothing about the operator's standing and scoped rules:+ * their items and source references are dropped (the remaining items+ * re-ranked), and every figure that counts or measures them - the item+ * count, the whole-text hash and lengths, the scoped characters and the+ * budgeted source count - is removed, so a session that injected rules+ * answers like one that did not.+ */+export function receiptAtReach(record: ContinuityRecord, local: boolean): ContinuityRecord {+ if (local || record.payload["trigger"] !== "session_inject") return record;+ const payload: Record<string, unknown> = { ...record.payload };+ if (Array.isArray(payload["items"])) {+ const items = (payload["items"] as ReadonlyArray<unknown>).filter(+ (item) => !isOperatorRuleItem(item),+ );+ payload["items"] = items.map((item, index) =>+ typeof item === "object" && item !== null ? { ...item, original_rank: index + 1 } : item,+ );+ payload["item_count"] = items.length;+ }+ for (const field of INJECTION_TOTAL_FIELDS) delete payload[field];+ const injection = payload["injection"];+ if (typeof injection === "object" && injection !== null) {+ const kept: Record<string, unknown> = { ...(injection as Record<string, unknown>) };+ for (const field of INJECTION_EXTRA_TOTAL_FIELDS) delete kept[field];+ payload["injection"] = kept;+ }+ const budget = payload["budget"];+ const remaining = Array.isArray(payload["items"]) ? (payload["items"] as unknown[]) : [];+ if (!remaining.some(isBudgetedBodyItem)) {+ // The block exists only because the scoped rules were charged: with+ // no budgeted body left, a receipt without the rules carries none.+ delete payload["budget"];+ } else if (typeof budget === "object" && budget !== null) {+ const kept: Record<string, unknown> = { ...(budget as Record<string, unknown>) };+ for (const field of BUDGET_RULE_FIELDS) delete kept[field];+ payload["budget"] = kept;+ }+ return {+ ...record,+ sourceRefs: record.sourceRefs.filter((ref) => !isOperatorRuleItem(ref)),+ payload,+ };+}++/**+ * Session-scoped retrieval report (context-integrity-gates, Unit I): a+ * read-only fold over receipts that already exist, joined to the+ * observed-use verdicts for the same window.+ *+ * A window with no receipts reports exactly that. Receipt emission is+ * opt-in, so counters of zero would describe a mechanism nobody enabled+ * rather than a retrieval finding.+ */+export async function summarizeReceipts(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const trigger = optionalStringArg("brain_context_receipts", args, "trigger");+ if (trigger !== undefined && !isContextReceiptTrigger(trigger)) {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_context_receipts: trigger must be one of ${CONTEXT_RECEIPT_TRIGGERS.join(", ")}`,+ );+ }+ const host = optionalStringArg("brain_context_receipts", args, "host");+ const sessionId = optionalStringArg("brain_context_receipts", args, "session_id");+ const since = optionalStringArg("brain_context_receipts", args, "since");+ const until = optionalStringArg("brain_context_receipts", args, "until");+ // Both bounds are compared LEXICALLY against stored `createdAt`+ // strings. An uncomparable value (`"yesterday"`, a local-time stamp,+ // `2026-13-01`) silently filters the window to empty and the fold+ // reports "no receipts recorded for this filter" - "nothing happened"+ // for what is really malformed input. Refuse it instead.+ for (const [field, value] of [+ ["since", since],+ ["until", until],+ ] as const) {+ try {+ assertContextReceiptWindowBound(field, value);+ } catch (err) {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_context_receipts: ${err instanceof Error ? err.message : String(err)}`,+ );+ }+ }+ const maxReceipts = coercePositiveInteger(+ "brain_context_receipts",+ "max_receipts",+ args["max_receipts"],+ );+ const limit = coercePositiveInteger("brain_context_receipts", "limit", args["limit"]);++ const window = {+ ...(trigger !== undefined ? { trigger } : {}),+ ...(host !== undefined ? { host } : {}),+ ...(sessionId !== undefined ? { sessionId } : {}),+ ...(since !== undefined ? { since } : {}),+ ...(until !== undefined ? { until } : {}),+ };+ const local = contextReach(ctx) === TRANSPORT_REACH.local;+ const fold = summarizeContextReceiptSession(ctx.vault, {+ ...window,+ ...(maxReceipts !== undefined ? { maxReceipts } : {}),+ // Below local reach the operator-rule items leave the item figures,+ // and a receipt that recorded nothing else is not folded at all.+ ...(local ? {} : { exclude: isRuleOnlyInjection, excludeItem: isOperatorRuleItem }),+ });+ if (!fold.recorded) {+ return {+ vault_path: vaultPathField(ctx),+ recorded: false,+ max_receipts: fold.max_receipts,+ note: "no receipts recorded for this filter; receipt emission is opt-in per call",+ };+ }++ // Observed use is folded over the SAME window, so a per-item verdict+ // describes this session rather than the artifact's lifetime rate.+ const reuse = observedReuseRates(ctx.vault, {+ ...(sessionId !== undefined ? { sessionId } : {}),+ ...(since !== undefined ? { since } : {}),+ ...(until !== undefined ? { until } : {}),+ });+ const items = limit === undefined ? fold.items : fold.items.slice(0, limit);++ return {+ vault_path: vaultPathField(ctx),+ recorded: true,+ receipt_count: fold.receipt_count,+ item_total: fold.item_total,+ distinct_items: fold.distinct_items,+ withheld_receipts: fold.withheld_receipts,+ // Receipts that inflate `receipt_count` and contribute no items: an+ // injection that degraded to cache records `items: []` by design,+ // and a receipt with no item array at all cannot be unfolded. Both+ // used to vanish into the gap between `receipt_count` and+ // `item_total`.+ empty_receipts: fold.empty_receipts,+ malformed_receipts: fold.malformed_receipts,+ truncated: fold.truncated,+ max_receipts: fold.max_receipts,+ items: items.map((item) => {+ const observed = reuse.get(item.path ?? item.id);+ return {+ id: item.id,+ ...(item.path !== undefined ? { path: item.path } : {}),+ injections: item.injections,+ tokens: item.tokens,+ ...(observed !== undefined+ ? {+ observed: {+ used: observed.used,+ ignored: observed.ignored,+ contradicted: observed.contradicted,+ total: observed.total,+ score: observed.score,+ },+ }+ : {}),+ };+ }),+ };+}++// ----- brain_event_trace ---------------------------------------------------++export async function toolBrainEventTrace(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const kind = optionalStringArg("brain_event_trace", args, "kind");+ if (kind !== undefined && !BRAIN_LOG_EVENT_KIND_SET.has(kind)) {+ throw new MCPError(INVALID_PARAMS, `brain_event_trace: unknown event kind '${kind}'`);+ }+ const date = optionalStringArg("brain_event_trace", args, "date");+ const at = optionalStringArg("brain_event_trace", args, "at");+ const sessionId = optionalStringArg("brain_event_trace", args, "session_id");+ const limit = coercePositiveInteger("brain_event_trace", "limit", args["limit"]);+ const offset = cursorOffsetArg("brain_event_trace", args);+ const keepPrivate = coerceBool(args, "keep_private");++ let events;+ try {+ // The scan early-exits one event past the page's reach+ // (`offset + limit + 1`, evaluated by the core before the+ // trace-attachment work): the lookahead proves whether a next page+ // exists, so `next_cursor` never lies and the full day's matching+ // set stays reachable by walking, while one page fetch never re-runs+ // the attachment scan past its own reach. (The cursor rollout+ // dropped the caller cap that bounded this scan, making every page+ // fetch attach traces for the whole day - a quadratic walk under+ // forged cursors; the bound restores the early exit without+ // reintroducing silent truncation.) `total`/`trace_total` are exact+ // once the walk exhausts; before that they report the bound the+ // page reached. A limit-less call still reads the day whole: its+ // page is the answer, not a step of a walk.+ const scanBound = limit !== undefined ? offset + limit + 1 : undefined;+ events = resolveLogEventTraces(ctx.vault, {+ ...(date !== undefined ? { date } : {}),+ ...(at !== undefined ? { at } : {}),+ ...(kind !== undefined ? { kind: kind as BrainLogEventKind } : {}),+ ...(sessionId !== undefined ? { sessionId } : {}),+ ...(scanBound !== undefined ? { limit: scanBound } : {}),+ ...(keepPrivate === true ? { keepPrivate: true } : {}),+ // The event body is echoed verbatim and log payloads carry+ // artifact paths (a-label-is-not-a-boundary, U3).+ ownerScope: gatedOwnerScopeView(ctx.vault, ctx.agentName).scope,+ // A note-write body carries the page's whole-file digest and byte+ // size, so an event naming a page the caller may not read at its+ // reach is dropped exactly as an event about an absent page is.+ view: reachView(ctx.vault, contextReach(ctx)),+ });+ } catch (err) {+ // A selector-validation error (bad date/at/kind, checked before any IO) is+ // a caller error (INVALID_PARAMS). ANY OTHER throw is a runtime IO failure -+ // e.g. an existing-but-unreadable log dir (EACCES/EIO/ENOTDIR) - and must be+ // an internal error, not a parameter error.+ if (err instanceof EventTraceSelectorError) {+ throw new MCPError(INVALID_PARAMS, `brain_event_trace: ${err.message}`);+ }+ throw new MCPError(INTERNAL_ERROR, `brain_event_trace: ${(err as Error).message}`);+ }++ const page = pageSlice(events, offset, limit ?? Math.max(events.length, 1));+ return {+ vault_path: vaultPathField(ctx),+ total: page.total,+ trace_total: events.reduce((sum, e) => sum + e.traceCount, 0),+ events: page.items,+ next_cursor: page.next_cursor,+ };+}diff --git a/src/mcp/brain/pack-shared.ts b/src/mcp/brain/pack-shared.tsnew file mode 100644index 00000000..32fa05e6--- /dev/null+++ b/src/mcp/brain/pack-shared.ts@@ -0,0 +1,181 @@+/**+ * The argument and configuration plumbing the pack family shares (task+ * 3.19): the recall-scores pairing key, the error fencing, the context+ * window and model resolution, the delivery disclosure helpers, the+ * receipt options every receipt-writing tool reads, and the configured+ * degradation. Split from `pack-tools.ts`.+ */++import { isAbsolute, relative } from "node:path";+import { resolveModelContextWindowEnvTokens } from "../../core/config.ts";+import { SearchError } from "../../core/search/search-error.ts";+import {+ discloseSpentQuery,+ type BeliefSemanticRelevance,+} from "../../core/brain/belief-semantic.ts";+import { packContext } from "../../core/brain/context-pack.ts";+import { loadBrainConfig } from "../../core/brain/policy.ts";+import { type ContextReceiptOptions } from "../../core/brain/context-receipts.ts";+import {+ resolveModelContextWindowTokens,+ type ResolvedModelWindow,+} from "../../core/brain/model-window.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import { searchErrorToMcp } from "../search-tools.ts";+import { coerceBool } from "../coerce.ts";+import { optionalStringArg } from "./shared.ts";++/**+ * The argument name this tool spells its recall scores with.+ *+ * `brain_recall_gate` calls the same argument `scores`; the pairing keyword+ * and the handler's read both take the key from here so this tool's+ * declaration and its enforcement cannot drift onto different names.+ */+export const RECALL_SCORES_ARG_NAME = "recall_scores";++/**+ * Bounded-token vault slice ordered by importance tier then recency.+ * Lets an agent prime its context window under a strict budget.+ */+export function vaultRelative(vault: string, absOrRel: string): string {+ return isAbsolute(absOrRel) ? relative(vault, absOrRel) : absOrRel;+}++/** Run `fn`, answering a SearchError with its stable code on the wire. */+export async function withSearchErrorsOnWire<T>(+ fn: () => Promise<T>,+ refine: (e: SearchError) => SearchError = (e) => e,+): Promise<T> {+ try {+ return await fn();+ } catch (e) {+ if (e instanceof SearchError) throw searchErrorToMcp(refine(e));+ throw e;+ }+}++/**+ * The vault's declared `context.window_tokens`; `undefined` when the block+ * is absent or the file cannot be read. Fail-soft on purpose: a broken+ * `_brain.yaml` raises later, where the pack builds, exactly as it always+ * has - the derivation channel must not answer for the operator's config+ * before the real reader does.+ */+export function contextWindowConfigValue(vault: string): number | undefined {+ try {+ return loadBrainConfig(vault).context?.window_tokens;+ } catch {+ return undefined;+ }+}++/**+ * Resolve the model context window for one tool call (t_a567cc12) from+ * the three channels this server owns - the vault's `context:` block, the+ * environment override, and the caller's model hint - in the resolver's+ * precedence (config > env > declared table > `1m` suffix > default).+ *+ * `null` means NOTHING is resolvable: no model hint, no operator block,+ * no env value. Callers refuse on it - the pinned decision is never a+ * silent default budget. A malformed env value raises (an operator typo+ * must not shrink every budget to the default unnoticed); wrap the call+ * where the tool wants that on the wire as INVALID_PARAMS.+ *+ * Only invoked on the derivation path: a call that carries its explicit+ * budget never reads the vault or the environment, so the explicit path+ * behaves byte-identically to before the resolver existed.+ */+export function resolveSurfaceModelWindow(+ vault: string,+ model: string | undefined,+): ResolvedModelWindow | null {+ const operatorWindow = contextWindowConfigValue(vault);+ const envWindow = resolveModelContextWindowEnvTokens();+ if (model === undefined && operatorWindow === undefined && envWindow === undefined) return null;+ return resolveModelContextWindowTokens({+ ...(model !== undefined ? { model } : {}),+ ...(operatorWindow !== undefined ? { operatorWindowTokens: operatorWindow } : {}),+ ...(envWindow !== undefined ? { envWindowTokens: envWindow } : {}),+ });+}++/**+ * The caller's optional `model` id. A whitespace-only or empty value is+ * ABSENT - a blank name is no name - so the derivation answers+ * nothing-resolvable and refuses with the budget message, exactly as a+ * call without `model` does, instead of a model-argument complaint and+ * never a derived default budget. A non-string value stays a caller+ * error.+ */+export function optionalModelArg(tool: string, args: Record<string, unknown>): string | undefined {+ const raw = args["model"];+ if (raw === undefined || raw === null) return undefined;+ if (typeof raw !== "string") {+ throw new MCPError(INVALID_PARAMS, `${tool}: model must be a non-empty string`);+ }+ const trimmed = raw.trim();+ return trimmed === "" ? undefined : trimmed;+}++/**+ * A pack refusal raised after the query embed still names that spend. The+ * loader's pre-embed check reads every belief in view, while the pack keeps+ * fewer (no tombstones, chain tips only, and a dimension the query vector+ * decides), so the embed can be paid and the pack refused all the same.+ */+export function discloseSpentPackQuery(+ semantic: BeliefSemanticRelevance | null,+): (e: SearchError) => SearchError {+ return (e) => {+ if (semantic === null || e.code !== "BELIEF_VECTORS_MISSING") return e;+ return discloseSpentQuery(e, semantic.report);+ };+}++/**+ * The `semantic` member of a semantic-mode response: the one ungated+ * spend (the query embed) disclosed beside what the pack could score+ * after the reach filter.+ */+export function semanticReportField(+ loaded: BeliefSemanticRelevance,+ packed: NonNullable<ReturnType<typeof packContext>["semantic"]>,+): Record<string, unknown> {+ return {+ model: loaded.report.model,+ price_source: loaded.report.priceSource,+ query_tokens: loaded.report.queryTokens,+ estimated_usd: loaded.report.estimatedUsd,+ scored: packed.scored,+ unembedded: packed.unembedded,+ };+}++export function receiptOptionsFromArgs(+ tool: string,+ args: Record<string, unknown>,+ trigger: "context_pack" | "pre_compress",+ defaultHost: string,+): ContextReceiptOptions | undefined {+ if (!coerceBool(args, "receipt")) return undefined;+ return {+ host: optionalStringArg(tool, args, "receipt_host") ?? defaultHost,+ trigger,+ ...(optionalStringArg(tool, args, "session_id") !== undefined+ ? { sessionId: optionalStringArg(tool, args, "session_id") }+ : {}),+ ...(optionalStringArg(tool, args, "turn_id") !== undefined+ ? { turnId: optionalStringArg(tool, args, "turn_id") }+ : {}),+ };+}++/** Operator-configured trim strategy (`recall.degradation` in `_brain.yaml`). */+export function configuredDegradation(vault: string): "staged" | undefined {+ try {+ return loadBrainConfig(vault).recall?.degradation === "staged" ? "staged" : undefined;+ } catch {+ return undefined;+ }+}diff --git a/src/mcp/brain/pack-tools.ts b/src/mcp/brain/pack-tools.tsindex a2715324..ff72e901 100644--- a/src/mcp/brain/pack-tools.ts+++ b/src/mcp/brain/pack-tools.ts@@ -8,1415 +8,41 @@* BRAIN_TOOLS surface.*/-import { isAbsolute, relative } from "node:path";--import {- resolveDensityRankingContextPack,- resolveEntityFactsContextPack,- resolveModelContextWindowEnvTokens,- resolveRecallAdequacyThresholds,- resolveRecallGateTelemetry,- resolveSearchFocusContextPack,- resolveTailTrimContextPack,-} from "../../core/config.ts";-import { resolveSearchConfig } from "../../core/search/index.ts";-import { SearchError } from "../../core/search/search-error.ts";-import {- discloseSpentQuery,- loadBeliefSemanticRelevance,- spentQueryDisclosure,- type BeliefSemanticRelevance,-} from "../../core/brain/belief-semantic.ts";-import { readActiveSessionFocus } from "../../core/search/session-focus.ts";-import {- CONTEXT_PACK_QUERY_MODES,- ContextPackPackingLaneEmptyError,- isContextPackQueryMode,- packContext,-} from "../../core/brain/context-pack.ts";-import {- isPackingPolicy,- PACKING_POLICIES,- type PackingPolicy,-} from "../../core/brain/recall-budget.ts";-import { assessRecallAdequacy } from "../../core/brain/recall-adequacy.ts";-import { recordRecallAdequacyDemand } from "../../core/brain/query-demand.ts";-import { emitGatedTelemetry } from "../../core/brain/continuity/emit.ts";-import {- buildReaderAnticipatoryContext,- readAnticipatoryContext,- refreshAnticipatoryCache,- type ReadAnticipatoryContextResult,-} from "../../core/brain/anticipatory-cache.ts";-import { loadBrainConfig } from "../../core/brain/policy.ts";-import { buildPreCompressPack } from "../../core/brain/pre-compress-pack.ts";-import {- assertContextReceiptWindowBound,- CONTEXT_RECEIPT_TRIGGERS,- getContextReceipt,- isContextReceiptTrigger,- listContextReceipts,- lookupReceiptReplyPresence,- RECEIPT_ITEM_ACTIVE_BODY,- RECEIPT_ITEM_LESSONS_BODY,- RECEIPT_ITEM_SCOPED_RULES,- RECEIPT_ITEM_STANDING_RULES,- summarizeContextReceipt,- summarizeContextReceiptSession,- type ContextReceiptOptions,-} from "../../core/brain/context-receipts.ts";-import { verifyContextReceipt } from "../../core/brain/context-receipts-verify.ts";-import type { ContinuityRecord } from "../../core/brain/continuity/types.ts";-import { observedReuseRates } from "../../core/brain/observed-use.ts";-import {- diffContextPreset,- getContextPreset,- listContextPresets,- presetForResolvedWindow,- suggestContextPreset,- unrecognisedModelBudgetRefusal,- type ContextPresetCurrentConfig,-} from "../../core/brain/context-presets.ts";-import {- resolveModelContextWindowTokens,- MODEL_CONTEXT_WINDOW_ENV_KEY,- type ModelWindowSource,- type ResolvedModelWindow,-} from "../../core/brain/model-window.ts";-import { extractPreCompactRecords } from "../../core/brain/pre-compact-extract.ts";-import { EventTraceSelectorError, resolveLogEventTraces } from "../../core/brain/event-trace.ts";-import { gatedOwnerScopeView, ownerScopeView } from "../../core/brain/owner-scope-view.ts";-import { pageSlice } from "../../core/brain/offset-cursor.ts";-import { cursorOffsetArg, CURSOR_SCHEMA } from "./pagination.ts";-import { resolveOwnerScopeDelivery } from "../../core/brain/preferences-collect.ts";-import { BRAIN_LOG_EVENT_KIND_SET, type BrainLogEventKind } from "../../core/brain/types.ts";-import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";-import type { ServerContext, ToolDefinition } from "../tool-contract.ts";-import { contextReach } from "../tool-contract.ts";-import { readableAtContextReachOrUndefined } from "./reach-readable.ts";-import { reachView } from "../../core/brain/reach-view.ts";-import { TRANSPORT_REACH } from "../../core/graph/transport-reach.ts";-import { vaultPathField } from "../vault-path-field.ts";-import {- exceedsMcpQueryCap,- MCP_QUERY_CAP_MESSAGE,- MCP_QUERY_MAX_CHARS,- searchErrorToMcp,-} from "../search-tools.ts";+import { CONTEXT_PACK_QUERY_MODES } from "../../core/brain/context-pack.ts";+import { PACKING_POLICIES } from "../../core/brain/recall-budget.ts";+import { CONTEXT_RECEIPT_TRIGGERS } from "../../core/brain/context-receipts.ts";+import { CURSOR_SCHEMA } from "./pagination.ts";+import type { ToolDefinition } from "../tool-contract.ts";+import { MCP_QUERY_MAX_CHARS } from "../search-tools.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import {AGENT_SCOPE_SCHEMA,MATCH_QUALITY_ARG_NAME,matchQualitySchema,RECALL_SCORES_SCHEMA,- coerceAgentScope,- coerceDecisionAnswerable,- coerceRecallAdequacyInput,DECISION_ANSWERABLE_ARG_NAME,decisionAnswerablePairing,decisionAnswerableSchema,- coerceStr,- coerceStrList,- coerceBool,recallAdequacyPairing,- unknownOperationError,} from "../coerce.ts";-import { decisionAnswerableFor } from "../decision-answerable.ts";+import { RECALL_SCORES_ARG_NAME } from "./pack-shared.ts";+import { toolBrainContextPack } from "./pack-context-tools.ts";+import { toolBrainContextReceipts, toolBrainEventTrace } from "./pack-receipt-tools.ts";import {- coercePositiveInteger,- optionalStringArg,- requiredStringArg,- telemetryOptionsFromArgs,-} from "./shared.ts";--/**- * The argument name this tool spells its recall scores with.- *- * `brain_recall_gate` calls the same argument `scores`; the pairing keyword- * and the handler's read both take the key from here so this tool's- * declaration and its enforcement cannot drift onto different names.- */-const RECALL_SCORES_ARG_NAME = "recall_scores";--/**- * Bounded-token vault slice ordered by importance tier then recency.- * Lets an agent prime its context window under a strict budget.- */-function vaultRelative(vault: string, absOrRel: string): string {- return isAbsolute(absOrRel) ? relative(vault, absOrRel) : absOrRel;-}--/** Run `fn`, answering a SearchError with its stable code on the wire. */-async function withSearchErrorsOnWire<T>(- fn: () => Promise<T>,- refine: (e: SearchError) => SearchError = (e) => e,-): Promise<T> {- try {- return await fn();- } catch (e) {- if (e instanceof SearchError) throw searchErrorToMcp(refine(e));- throw e;- }-}--/**- * The vault's declared `context.window_tokens`; `undefined` when the block- * is absent or the file cannot be read. Fail-soft on purpose: a broken- * `_brain.yaml` raises later, where the pack builds, exactly as it always- * has - the derivation channel must not answer for the operator's config- * before the real reader does.- */-function contextWindowConfigValue(vault: string): number | undefined {- try {- return loadBrainConfig(vault).context?.window_tokens;- } catch {- return undefined;- }-}--/**- * Resolve the model context window for one tool call (t_a567cc12) from- * the three channels this server owns - the vault's `context:` block, the- * environment override, and the caller's model hint - in the resolver's- * precedence (config > env > declared table > `1m` suffix > default).- *- * `null` means NOTHING is resolvable: no model hint, no operator block,- * no env value. Callers refuse on it - the pinned decision is never a- * silent default budget. A malformed env value raises (an operator typo- * must not shrink every budget to the default unnoticed); wrap the call- * where the tool wants that on the wire as INVALID_PARAMS.- *- * Only invoked on the derivation path: a call that carries its explicit- * budget never reads the vault or the environment, so the explicit path- * behaves byte-identically to before the resolver existed.- */-function resolveSurfaceModelWindow(- vault: string,- model: string | undefined,-): ResolvedModelWindow | null {- const operatorWindow = contextWindowConfigValue(vault);- const envWindow = resolveModelContextWindowEnvTokens();- if (model === undefined && operatorWindow === undefined && envWindow === undefined) return null;- return resolveModelContextWindowTokens({- ...(model !== undefined ? { model } : {}),- ...(operatorWindow !== undefined ? { operatorWindowTokens: operatorWindow } : {}),- ...(envWindow !== undefined ? { envWindowTokens: envWindow } : {}),- });-}--/**- * The caller's optional `model` id. A whitespace-only or empty value is- * ABSENT - a blank name is no name - so the derivation answers- * nothing-resolvable and refuses with the budget message, exactly as a- * call without `model` does, instead of a model-argument complaint and- * never a derived default budget. A non-string value stays a caller- * error.- */-function optionalModelArg(tool: string, args: Record<string, unknown>): string | undefined {- const raw = args["model"];- if (raw === undefined || raw === null) return undefined;- if (typeof raw !== "string") {- throw new MCPError(INVALID_PARAMS, `${tool}: model must be a non-empty string`);- }- const trimmed = raw.trim();- return trimmed === "" ? undefined : trimmed;-}--/**- * A pack refusal raised after the query embed still names that spend. The- * loader's pre-embed check reads every belief in view, while the pack keeps- * fewer (no tombstones, chain tips only, and a dimension the query vector- * decides), so the embed can be paid and the pack refused all the same.- */-function discloseSpentPackQuery(- semantic: BeliefSemanticRelevance | null,-): (e: SearchError) => SearchError {- return (e) => {- if (semantic === null || e.code !== "BELIEF_VECTORS_MISSING") return e;- return discloseSpentQuery(e, semantic.report);- };-}--/**- * The `semantic` member of a semantic-mode response: the one ungated- * spend (the query embed) disclosed beside what the pack could score- * after the reach filter.- */-function semanticReportField(- loaded: BeliefSemanticRelevance,- packed: NonNullable<ReturnType<typeof packContext>["semantic"]>,-): Record<string, unknown> {- return {- model: loaded.report.model,- price_source: loaded.report.priceSource,- query_tokens: loaded.report.queryTokens,- estimated_usd: loaded.report.estimatedUsd,- scored: packed.scored,- unembedded: packed.unembedded,- };-}--async function toolBrainContextPack(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const model = optionalModelArg("brain_context_pack", args);- const maxTokensArg = coercePositiveInteger(- "brain_context_pack",- "max_tokens",- args["max_tokens"],- );- // The adequacy pairing is an input-SHAPE contract, declared in the- // schema's `dependentRequired`, so it refuses an incomplete pair by- // name before any semantic refusal can preempt it: `max_tokens` is now- // optional behind the derivation below (t_a567cc12), and a payload- // carrying one half of the pair must learn about the pairing, not about- // a budget it never sent.- const recallAttempt = coerceRecallAdequacyInput(- "brain_context_pack",- args,- RECALL_SCORES_ARG_NAME,- );- const answerableArg = coerceDecisionAnswerable(- "brain_context_pack",- args,- RECALL_SCORES_ARG_NAME,- recallAttempt !== undefined,- );- // Derived budget (t_a567cc12): an explicit `max_tokens` is first-class- // and untouched. When it is omitted, the budget derives from the model- // context window the resolver resolves, through the matching preset's- // `context_pack.max_tokens` - the curated mapping. A `default`-sourced- // window defers to the model's hint preset, the same mapping- // `brain_context_presets` suggest answers, so one model gets one budget- // and one suggestion on every surface - and an id NOTHING places (no- // table row, no suffix, no hint) refuses: the conservative posture this- // tool held before derivation existed, never the default window's- // long-context budget an 8k local model cannot hold. With nothing- // resolvable the call refuses exactly as before: the pinned decision is- // never a silent default budget.- let maxTokens: number;- let maxTokensSource: ModelWindowSource | undefined;- if (maxTokensArg !== undefined) {- maxTokens = maxTokensArg;- } else {- let resolved: ResolvedModelWindow | null;- try {- resolved = resolveSurfaceModelWindow(ctx.vault, model ?? undefined);- } catch (e) {- throw new MCPError(INVALID_PARAMS, `brain_context_pack: ${(e as Error).message}`);- }- if (resolved === null) {- throw new MCPError(- INVALID_PARAMS,- "brain_context_pack: max_tokens must be a positive integer",- );- }- const refusal = unrecognisedModelBudgetRefusal(model, resolved);- if (refusal !== null) {- throw new MCPError(INVALID_PARAMS, `brain_context_pack: ${refusal}`);- }- // The hint fallback rides along exactly when the resolver's answer is- // the default-sourced assumption, so a hint-only model budgets the- // preset `brain_context_presets` suggest names for it; the source- // disclosed on the wire stays the window's.- maxTokens = presetForResolvedWindow(model, resolved).context_pack.max_tokens;- maxTokensSource = resolved.source;- }- const query = typeof args["query"] === "string" ? (args["query"] as string) : undefined;- // Ranked query mode (v1.53.0). Enforced beside the `dependentRequired`- // that declares it: a mode with no query would otherwise be accepted and- // do nothing, which is the silent no-op this project refuses.- const queryMode = coerceStr(args, "query_mode", false);- if (queryMode !== null) {- if (!isContextPackQueryMode(queryMode)) {- throw new MCPError(- INVALID_PARAMS,- `brain_context_pack: query_mode must be one of ${CONTEXT_PACK_QUERY_MODES.join(", ")}`,- );- }- if (query === undefined) {- throw new MCPError(- INVALID_PARAMS,- "brain_context_pack: query_mode requires query; a mode with nothing to read is inert",- );- }- // The semantic query is embedded once, ungated: a blank one buys nothing.- if (queryMode === "semantic" && query.trim() === "") {- throw new MCPError(- INVALID_PARAMS,- "brain_context_pack: query_mode requires a non-empty query",- );- }- }- // Opt-in packing policy (recall-lane-latency wave). Refused beside the- // `dependentRequired` that declares it, exactly as query_mode is: a- // policy with no query has no turn to pack for and would be the silent- // no-op this project refuses. A blank or whitespace-only query is the- // same refusal, not a pass: the empty string is dropped before the core- // and the null query filter-passes every candidate, so the policy would- // silently reorder an unordered pack - the exact evasion the raw read- // above would otherwise allow.- const packingPolicy = coerceStr(args, "packing_policy", false);- if (packingPolicy !== null) {- if (!isPackingPolicy(packingPolicy)) {- throw new MCPError(- INVALID_PARAMS,- `brain_context_pack: packing_policy must be one of ${PACKING_POLICIES.join(", ")}`,- );- }- if (query === undefined || query.trim() === "") {- throw new MCPError(- INVALID_PARAMS,- "brain_context_pack: packing_policy requires query; a policy with nothing to order is inert",- );- }- }- if (query !== undefined && exceedsMcpQueryCap(query)) {- throw new MCPError(INVALID_PARAMS, `brain_context_pack: ${MCP_QUERY_CAP_MESSAGE}`);- }- const includeLanes = coerceBool(args, "lanes");- const cacheStable = coerceBool(args, "cache_stable");- const dedupRepeated = coerceBool(args, "dedup_repeated");- const attentionFlowIds = coerceStrList(args, "attention_flow_ids");- const maxCharsPerMemory = coercePositiveInteger(- "brain_context_pack",- "max_chars_per_memory",- args["max_chars_per_memory"],- );- const maxTotalChars = coercePositiveInteger(- "brain_context_pack",- "max_total_chars",- args["max_total_chars"],- );- const receipt = receiptOptionsFromArgs("brain_context_pack", args, "context_pack", "mcp");- const telemetry = telemetryOptionsFromArgs("brain_context_pack", args, "mcp");- // The pairing coercions themselves ran above the budget derivation, so- // an incomplete pair is refused by name; only the ASSESSMENT waits for- // this point, beside the receipt and telemetry options it rides with.- const adequacy =- recallAttempt !== undefined- ? assessRecallAdequacy(- recallAttempt,- resolveRecallAdequacyThresholds(ctx.configPath ?? undefined),- )- : undefined;- // Advisory decision-model signal (issue #213, Part 8): annotates the- // verdict and its receipt, never the level, the action or the pack.- const answerable =- adequacy !== undefined && answerableArg !== undefined- ? decisionAnswerableFor(ctx, adequacy.level, answerableArg)- : undefined;- const answerableVerdict = answerable?.kind === "annotated" ? answerable.verdict : undefined;- // signals-that-survive, unit 6: an unmet verdict is stamped onto the- // cross-query demand log under the bucket key normalizeQueryTerms already- // computes, so the knowledge-gap loop can aggregate recurrence without a- // second identity concept.- //- // ONE opt-in for that log, on every surface that writes it: the- // `recall_gate_telemetry` config key, exactly as `brain_recall_gate`- // uses. It is a vault-level durable log feeding a vault-level loop, so- // whether it is written is an operator decision, not a per-call one -- // gating it here on this tool's `telemetry` ARGUMENT instead made one- // feature answer to two different opt-ins and left the log's contents- // depending on which surface a caller happened to use. That argument- // keeps its own meaning: it selects whether THIS call emits its own- // continuity records. Fail-open as ever - a log write never breaks the- // pack.- if (adequacy !== undefined && query !== undefined) {- emitGatedTelemetry(resolveRecallGateTelemetry(ctx.configPath ?? undefined), () =>- recordRecallAdequacyDemand(ctx.vault, { query, verdict: adequacy }),- );- }- // Focus wiring (Agent Surface Suite, t_5b478e47): gated on the- // search_focus_context_pack config key (default off) so the default- // pack stays byte-identical. Fail-soft - a broken search config- // never breaks the pack.- let sessionFocus: ReturnType<typeof readActiveSessionFocus> = null;- if (resolveSearchFocusContextPack(ctx.configPath ?? undefined)) {- // Argument validation stays OUTSIDE the fail-soft block: an invalid- // focus_session is a caller error (INVALID_PARAMS), not a config- // read to swallow.- const focusSession = coerceStr(args, "focus_session", false) ?? undefined;- try {- const searchConfig = resolveSearchConfig({- vault: ctx.vault,- configPath: ctx.configPath ?? undefined,- });- sessionFocus = readActiveSessionFocus(searchConfig, focusSession);- } catch {- sessionFocus = null;- }- }- // Density-ranking wiring (impact-per-token allocation, t_affa3bd9):- // gated on the density_ranking_context_pack config key (default off)- // so the default pack stays byte-identical to the tier → recency order.- const densityRanking = resolveDensityRankingContextPack(ctx.configPath ?? undefined);- // Entity-facts wiring (dated commitments, t_43b0a379): gated on the- // entity_facts_context_pack config key (default off) so the default- // tool output carries no entity_facts key.- const entityFacts = resolveEntityFactsContextPack(ctx.configPath ?? undefined);- // Tail-trim wiring (t_cb6a5558): gated on the tail_trim_context_pack- // config key (default off) so the default tool output carries no- // tail_trim key and no trim ever runs.- const tailTrim = resolveTailTrimContextPack(ctx.configPath ?? undefined);- const agentScope = coerceAgentScope(ctx, args, true);- // Root closure (t_sec_pack_reach): the pack reads page bodies by path,- // outside the three read roots, so the reserved-token rule is asked per- // candidate - the same shape `brain_clusters`/`brain_bridges` apply. It- // is asked INSIDE the core, before ranking and budgeting, because every- // other member of the report (`lanes`, `skipped`, tension `warnings`,- // `deduped_from`, the receipt) is derived from the candidate set: a- // filter over `items` alone left a reserved page's path and body in- // `lanes` and its id in `skipped`. At local reach the view is the shared- // no-op, so an operator's own transports see a byte-identical pack. The- // core holds absolute paths; the view answers over vault-relative ones.- const view = reachView(ctx.vault, contextReach(ctx));- const remote = view.reach !== TRANSPORT_REACH.local;- // Semantic mode (Honest Embedding Spend): the one async step - the query- // embed and the stored-vector read - happens here, so `packContext`- // stays synchronous for every other caller. Every refusal is a named- // SearchError: a blocked tier and a missing sqlite-vec from the loader,- // before any embed, and `BELIEF_VECTORS_MISSING` from the pack, after- // the reach filter and before a receipt is written. The loader reads- // only the beliefs this caller's pack can keep - the same reach and- // owner views the pack applies - so its own pre-embed refusal never- // answers for a withheld belief differently than for an absent one.- const semantic =- queryMode === "semantic" && query !== undefined- ? await withSearchErrorsOnWire(() => {- const owners = ownerScopeView(- ctx.vault,- resolveOwnerScopeDelivery(ctx.vault, agentScope).enforcedScope,- );- return loadBeliefSemanticRelevance(- resolveSearchConfig({ vault: ctx.vault, configPath: ctx.configPath ?? undefined }),- query,- { reach: view.reach, inView: (rel) => view.visible(rel) && owners.visible(rel) },- );- })- : null;- let report: Awaited<ReturnType<typeof packContext>>;- try {- report = await withSearchErrorsOnWire(- async () =>- packContext(ctx.vault, {- ...(remote- ? { visible: (abs: string) => view.visible(vaultRelative(ctx.vault, abs)) }- : {}),- maxTokens,- ...(agentScope !== undefined ? { agentScope } : {}),- ...(densityRanking ? { densityRanking: true } : {}),- ...(entityFacts ? { entityFacts: true } : {}),- ...(tailTrim ? { tailTrim: true } : {}),- ...(sessionFocus !== null ? { sessionFocus } : {}),- ...(query ? { query } : {}),- ...(queryMode !== null ? { queryMode } : {}),- ...(packingPolicy !== null ? { packingPolicy: packingPolicy as PackingPolicy } : {}),- ...(includeLanes ? { includeLanes: true } : {}),- ...(receipt !== undefined ? { receipt } : {}),- ...(adequacy !== undefined ? { recallAdequacy: adequacy } : {}),- ...(answerableVerdict !== undefined ? { decisionAnswerable: answerableVerdict } : {}),- ...(cacheStable || dedupRepeated- ? {- transforms: {- ...(cacheStable ? { cacheStableOrdering: true } : {}),- ...(dedupRepeated ? { deduplicateRepeatedContext: true } : {}),- },- }- : {}),- ...(maxCharsPerMemory !== undefined ? { maxCharsPerMemory } : {}),- ...(maxTotalChars !== undefined ? { maxTotalChars } : {}),- ...(configuredDegradation(ctx.vault) !== undefined- ? { degradation: configuredDegradation(ctx.vault)! }- : {}),- ...(telemetry !== undefined ? { telemetry } : {}),- // The synthesized attention-flow block has no page of its own to ask- // the reach view about, so a remote caller does not get it (fail- // closed, as the per-item filter this replaced did).- ...(attentionFlowIds.length > 0 && !remote ? { attentionFlowIds } : {}),- ...(semantic !== null ? { semanticRelevance: semantic.relevanceByPath } : {}),- }),- discloseSpentPackQuery(semantic),- );- } catch (e) {- // A policy against a one-lane vault is a caller error the core- // refuses by name; on the wire it is INVALID_PARAMS carrying that- // same named message, never an internal error and never a no-op.- if (e instanceof ContextPackPackingLaneEmptyError) {- // The spend disclosure rides the refusal too: in semantic mode the- // query embed was paid before the lanes were judged, and a refusal- // that hides that spend under-discloses exactly when the caller- // gets nothing back for it.- throw new MCPError(- INVALID_PARAMS,- semantic !== null ? `${e.message} ${spentQueryDisclosure(semantic.report)}` : e.message,- );- }- throw e;- }- const warnings = [- ...(report.warnings ?? []),- ...(semantic?.warnings ?? []),- ...(answerable?.kind === "ignored" ? [answerable.warning] : []),- ];- return {- vault_path: vaultPathField(ctx),- max_tokens: report.maxTokens,- // Present only when the budget was derived (t_a567cc12): the channel- // that decided, so a caller can see a resolution was assumed rather- // than paid for. An explicit `max_tokens` answers without it.- ...(maxTokensSource !== undefined ? { max_tokens_source: maxTokensSource } : {}),- tokens_used: report.tokensUsed,- items: report.items.map((i) => ({- id: i.id,- path: i.path,- tier: i.tier,- tokens: i.tokens,- body: i.body,- trimmed: i.trimmed,- epistemic: i.epistemic,- ...(i.evidenceRefs.length > 0 ? { evidence_refs: i.evidenceRefs } : {}),- ...(i.density !== undefined ? { density: i.density } : {}),- ...(i.originalRank !== undefined ? { original_rank: i.originalRank } : {}),- ...(i.stableRank !== undefined ? { stable_rank: i.stableRank } : {}),- ...(i.dedupedFrom !== undefined ? { deduped_from: i.dedupedFrom } : {}),- ...(i.referenceHint !== undefined ? { reference_hint: i.referenceHint } : {}),- ...(i.safety ? { safety: i.safety } : {}),- })),- skipped: report.skipped.map((s) => ({- id: s.id,- tokens: s.tokens,- reason: s.reason,- })),- ...(report.receiptId ? { receipt_id: report.receiptId } : {}),- ...(report.telemetryId ? { telemetry_id: report.telemetryId } : {}),- ...(report.lanes ? { lanes: report.lanes } : {}),- // The core computes injection-time tension warnings and the- // owner-scope observation and this projection dropped both, so the one- // surface that puts vault text in front of a model every turn was the- // one surface that could not say a memory it injected is contested.- // `brain_pre_compress_pack` has forwarded them all along; absent when- // empty, so a warning-free pack stays byte-identical.- ...(warnings.length > 0 ? { warnings } : {}),- ...(semantic !== null && report.semantic !== undefined- ? { semantic: semanticReportField(semantic, report.semantic) }- : {}),- // The packing accounting appears only when the caller named a- // policy - the same conditional shape as `semantic` above.- ...(report.packing ? { packing: report.packing } : {}),- // The entity-facts rollup appears only when the config key resolved- // on - the same conditional shape as `packing` above. Fields project- // to the tool's wire casing.- ...(report.entityFacts- ? {- entity_facts: {- entities: report.entityFacts.entities.map((e) => ({- entity_id: e.entityId,- name: e.name,- item_ids: e.itemIds,- })),- },- }- : {}),- // The trim block appears only when the config key resolved on AND- // the pack actually trimmed - the same conditional shape as- // `entity_facts` above. Fields project to the tool's wire casing.- ...(report.tailTrim- ? {- tail_trim: {- dropped: report.tailTrim.dropped,- kept_by_query_terms: report.tailTrim.keptByQueryTerms,- rescued: report.tailTrim.rescued,- tokens_saved: report.tailTrim.tokensSaved,- },- }- : {}),- ...(adequacy !== undefined- ? {- adequacy: {- level: adequacy.level,- action: adequacy.action,- escalate: adequacy.escalate,- result_count: adequacy.resultCount,- top_score: adequacy.topScore,- mean_score: adequacy.meanScore,- reason: adequacy.reason,- ...(answerableVerdict !== undefined- ? {- [DECISION_ANSWERABLE_ARG_NAME]: {- probability: answerableVerdict.probability,- disagrees: answerableVerdict.disagrees,- },- }- : {}),- },- }- : {}),- };-}--// ----- brain_context_receipts -----------------------------------------------async function toolBrainContextReceipts(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const operation = optionalStringArg("brain_context_receipts", args, "operation");- if (operation === "list") {- const trigger = optionalStringArg("brain_context_receipts", args, "trigger");- if (trigger !== undefined && !isContextReceiptTrigger(trigger)) {- throw new MCPError(- INVALID_PARAMS,- `brain_context_receipts: trigger must be one of ${CONTEXT_RECEIPT_TRIGGERS.join(", ")}`,- );- }- const host = optionalStringArg("brain_context_receipts", args, "host");- const sessionId = optionalStringArg("brain_context_receipts", args, "session_id");- const limit = coercePositiveInteger("brain_context_receipts", "limit", args["limit"]);- const offset = cursorOffsetArg("brain_context_receipts", args);- const local = contextReach(ctx) === TRANSPORT_REACH.local;- // The full filtered set is read and one page is cut here, so `total`- // stays the exact count matching the filter across all pages and the- // walk continues through `next_cursor` (null when exhausted).- const receipts = listContextReceipts(ctx.vault, {- ...(trigger !== undefined ? { trigger } : {}),- ...(host !== undefined ? { host } : {}),- ...(sessionId !== undefined ? { sessionId } : {}),- ...(local ? {} : { exclude: isRuleOnlyInjection }),- });- // The join is show-only: summarizeContextReceipt's second parameter- // is the presence join, so the summaries are mapped through an arrow- // - a point-free `.map(summarizeContextReceipt)` would hand every- // row's ARRAY INDEX to that parameter.- const summaries = receipts- .map((receipt) => receiptAtReach(receipt, local))- .map((receipt) => summarizeContextReceipt(receipt));- const page = pageSlice(summaries, offset, limit ?? Math.max(summaries.length, 1));- return {- vault_path: vaultPathField(ctx),- total: page.total,- receipts: page.items,- next_cursor: page.next_cursor,- };- }-- if (operation === "show") {- const id = optionalStringArg("brain_context_receipts", args, "id");- if (id === undefined) {- throw new MCPError(INVALID_PARAMS, "brain_context_receipts: id is required for show");- }- const local = contextReach(ctx) === TRANSPORT_REACH.local;- const stored = getContextReceipt(ctx.vault, id);- // Below local reach a receipt that recorded only the operator rules- // is answered as an unknown id: showing it would say rules applied.- if (stored === null || (!local && isRuleOnlyInjection(stored))) {- throw new MCPError(INVALID_PARAMS, `brain_context_receipts: receipt not found: ${id}`);- }- const receipt = receiptAtReach(stored, local);- return {- id: receipt.id,- kind: receipt.kind,- createdAt: receipt.createdAt,- sourceRefs: receipt.sourceRefs,- payload: receipt.payload,- private: receipt.private,- redacted: receipt.redacted,- // The receipt's session reply-presence join (t_f8510c55): the- // per-note verdicts of the session's latest reply_presence record,- // or the named unjoined outcome - a receipt whose session checked- // no turn, or that names no session at all, says so instead of- // reading as silently absent. The lookup runs on the reach-adjusted- // record, so a payload redacted below local reach joins only on- // what it still carries - and through the caller's reach view, so- // a note row naming a page reserved below local reach drops from- // `per_note` (counted in `withheld`) instead of disclosing its- // path, range and verdict to a caller the page withheld itself from.- reply_presence: lookupReceiptReplyPresence(- ctx.vault,- receipt,- reachView(ctx.vault, contextReach(ctx)),- ),- };- }-- if (operation === "summary") return summarizeReceipts(ctx, args);-- if (operation === "verify") return verifyReceipt(ctx, args);-- throw unknownOperationError(- "brain_context_receipts: operation must be list, show, summary, or verify",- );-}--// ----- brain_context_receipts verify (t_4300e5fd) -----------------------------/** The `operation` value a verify refusal names. */-export const RECEIPT_VERIFY_OPERATION = "verify" as const;--/** The refusal reason when the caller is below local reach. */-export const RECEIPT_VERIFY_REACH_REASON = "reach" as const;--/** The refusal reason when the receipt is flagged private or redacted. */-export const RECEIPT_VERIFY_WITHHELD_REASON = "receipt_withheld" as const;--export type ReceiptVerifyRefusalReason =- | typeof RECEIPT_VERIFY_REACH_REASON- | typeof RECEIPT_VERIFY_WITHHELD_REASON;--/**- * A verify call that was not answered, in the shape the receipts- * surfaces already use for a refused half (`ReceiptCompactRefusal`):- * the operation names itself, `measured: false` says no item was- * re-hashed, and the reason names which guard refused - never a partial- * verification.- */-export interface ReceiptVerifyRefusal {- readonly operation: typeof RECEIPT_VERIFY_OPERATION;- readonly measured: false;- readonly reason: ReceiptVerifyRefusalReason;- readonly detail: string;-}--/**- * Re-hash verification of one stored receipt (t_4300e5fd).- *- * Read-only, and local-reach only: the kernel re-reads the vault pages- * the receipt names, and page content is host-local, so a caller below- * local reach gets the typed refusal instead of a partial answer - the- * same posture the `brain_receipts` compact half takes. A receipt the- * session fold withholds (`private` or `redacted`) is refused- * symmetrically: the fold never unfolds it, and verify never re-hashes- * it.- */-async function verifyReceipt(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const id = optionalStringArg("brain_context_receipts", args, "id");- if (id === undefined) {- throw new MCPError(INVALID_PARAMS, "brain_context_receipts: id is required for verify");- }- if (contextReach(ctx) !== TRANSPORT_REACH.local) {- // Returned as the literal, `satisfies`-checked against the refusal- // interface, mirroring the compact refusal's construction: the- // handler's wire type is Record<string, unknown>, and a value held- // in the interface's name would not carry the index signature.- return {- operation: RECEIPT_VERIFY_OPERATION,- measured: false,- reason: RECEIPT_VERIFY_REACH_REASON satisfies ReceiptVerifyRefusalReason,- detail:- "context receipt verification re-reads the vault pages the receipt names; " +- "page content is host-local, so it answers at local reach only",- } satisfies ReceiptVerifyRefusal;- }- const stored = getContextReceipt(ctx.vault, id);- if (stored === null) {- throw new MCPError(INVALID_PARAMS, `brain_context_receipts: receipt not found: ${id}`);- }- if (stored.private || stored.redacted) {- return {- operation: RECEIPT_VERIFY_OPERATION,- measured: false,- reason: RECEIPT_VERIFY_WITHHELD_REASON satisfies ReceiptVerifyRefusalReason,- detail:- "the receipt is flagged private or redacted and is refused symmetrically " +- "with the session fold, which withholds it whole",- } satisfies ReceiptVerifyRefusal;- }- // Spread, not returned in its own name: the kernel's frozen interface- // carries no index signature, and the handler's wire type is- // Record<string, unknown> (the members are unchanged by the spread).- return { ...verifyContextReceipt(ctx.vault, stored) };-}--/** Predicate: a receipt item whose `id` is one of `ids`. */-const itemIdIn =- (ids: ReadonlySet<string>) =>- (item: unknown): boolean => {- const id = (item as { id?: unknown } | null)?.id;- return typeof id === "string" && ids.has(id);- };--/** Receipt items naming the operator-rule blocks the SessionStart hook injected. */-const OPERATOR_RULE_ITEM_IDS: ReadonlySet<string> = new Set([- RECEIPT_ITEM_STANDING_RULES,- RECEIPT_ITEM_SCOPED_RULES,-]);--/**- * One operator-rule receipt item. Exported beside- * {@link isRuleOnlyInjection} for the brain_truth provenance join, which- * strips these items from a mixed receipt below local reach - the same- * shaping `receiptAtReach` applies to the receipts this tool serves.- */-export const isOperatorRuleItem = itemIdIn(OPERATOR_RULE_ITEM_IDS);--/**- * A measured injection receipt whose every item was an operator-rule- * block: the hook recorded it only because rules applied (a session with- * no `active.md` body to inject). Below local reach it- * is withheld whole - left out of list and summary, refused by show -- * since even its empty remainder would say that rules applied.- *- * Exported for the surfaces that must answer the same question the- * receipts surface answers: the brain_truth provenance join excludes- * these receipts below local reach, so a claim's provenance confirms no- * more about the operator's rules than this tool does.- */-export function isRuleOnlyInjection(record: ContinuityRecord): boolean {- if (record.payload["trigger"] !== "session_inject") return false;- // A degraded injection that served a cached body beside the rules is- // recorded whether or not rules applied: it stays, emptied of them. One- // with no cached body (`loader_source: "empty"`) exists only because the- // rules were injected, so it is rule-only like a measured one.- const injection = record.payload["injection"] as- | { sources_measured?: unknown; loader_source?: unknown }- | undefined;- if (injection?.sources_measured === false && injection.loader_source !== "empty") return false;- const items = record.payload["items"];- return Array.isArray(items) && items.length > 0 && items.every(isOperatorRuleItem);-}--/** Receipt items charged against the injection budget besides the scoped rules. */-const BUDGETED_BODY_ITEM_IDS: ReadonlySet<string> = new Set([- RECEIPT_ITEM_ACTIVE_BODY,- RECEIPT_ITEM_LESSONS_BODY,-]);--const isBudgetedBodyItem = itemIdIn(BUDGETED_BODY_ITEM_IDS);--/** Payload fields of an injection receipt whose figures include the operator-rule blocks. */-const INJECTION_TOTAL_FIELDS = ["final_text_hash", "final_text_chars"] as const;-const INJECTION_EXTRA_TOTAL_FIELDS = ["total_bytes", "total_tokens"] as const;-const BUDGET_RULE_FIELDS = ["scoped_rules_chars", "budgeted_source_count"] as const;--/**- * A stored receipt as the caller may see it at its reach.- *- * At local reach the record is returned unchanged. Below it, an injection- * receipt says nothing about the operator's standing and scoped rules:- * their items and source references are dropped (the remaining items- * re-ranked), and every figure that counts or measures them - the item- * count, the whole-text hash and lengths, the scoped characters and the- * budgeted source count - is removed, so a session that injected rules- * answers like one that did not.- */-function receiptAtReach(record: ContinuityRecord, local: boolean): ContinuityRecord {- if (local || record.payload["trigger"] !== "session_inject") return record;- const payload: Record<string, unknown> = { ...record.payload };- if (Array.isArray(payload["items"])) {- const items = (payload["items"] as ReadonlyArray<unknown>).filter(- (item) => !isOperatorRuleItem(item),- );- payload["items"] = items.map((item, index) =>- typeof item === "object" && item !== null ? { ...item, original_rank: index + 1 } : item,- );- payload["item_count"] = items.length;- }- for (const field of INJECTION_TOTAL_FIELDS) delete payload[field];- const injection = payload["injection"];- if (typeof injection === "object" && injection !== null) {- const kept: Record<string, unknown> = { ...(injection as Record<string, unknown>) };- for (const field of INJECTION_EXTRA_TOTAL_FIELDS) delete kept[field];- payload["injection"] = kept;- }- const budget = payload["budget"];- const remaining = Array.isArray(payload["items"]) ? (payload["items"] as unknown[]) : [];- if (!remaining.some(isBudgetedBodyItem)) {- // The block exists only because the scoped rules were charged: with- // no budgeted body left, a receipt without the rules carries none.- delete payload["budget"];- } else if (typeof budget === "object" && budget !== null) {- const kept: Record<string, unknown> = { ...(budget as Record<string, unknown>) };- for (const field of BUDGET_RULE_FIELDS) delete kept[field];- payload["budget"] = kept;- }- return {- ...record,- sourceRefs: record.sourceRefs.filter((ref) => !isOperatorRuleItem(ref)),- payload,- };-}--/**- * Session-scoped retrieval report (context-integrity-gates, Unit I): a- * read-only fold over receipts that already exist, joined to the- * observed-use verdicts for the same window.- *- * A window with no receipts reports exactly that. Receipt emission is- * opt-in, so counters of zero would describe a mechanism nobody enabled- * rather than a retrieval finding.- */-async function summarizeReceipts(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const trigger = optionalStringArg("brain_context_receipts", args, "trigger");- if (trigger !== undefined && !isContextReceiptTrigger(trigger)) {- throw new MCPError(- INVALID_PARAMS,- `brain_context_receipts: trigger must be one of ${CONTEXT_RECEIPT_TRIGGERS.join(", ")}`,- );- }- const host = optionalStringArg("brain_context_receipts", args, "host");- const sessionId = optionalStringArg("brain_context_receipts", args, "session_id");- const since = optionalStringArg("brain_context_receipts", args, "since");- const until = optionalStringArg("brain_context_receipts", args, "until");- // Both bounds are compared LEXICALLY against stored `createdAt`- // strings. An uncomparable value (`"yesterday"`, a local-time stamp,- // `2026-13-01`) silently filters the window to empty and the fold- // reports "no receipts recorded for this filter" - "nothing happened"- // for what is really malformed input. Refuse it instead.- for (const [field, value] of [- ["since", since],- ["until", until],- ] as const) {- try {- assertContextReceiptWindowBound(field, value);- } catch (err) {- throw new MCPError(- INVALID_PARAMS,- `brain_context_receipts: ${err instanceof Error ? err.message : String(err)}`,- );- }- }- const maxReceipts = coercePositiveInteger(- "brain_context_receipts",- "max_receipts",- args["max_receipts"],- );- const limit = coercePositiveInteger("brain_context_receipts", "limit", args["limit"]);-- const window = {- ...(trigger !== undefined ? { trigger } : {}),- ...(host !== undefined ? { host } : {}),- ...(sessionId !== undefined ? { sessionId } : {}),- ...(since !== undefined ? { since } : {}),- ...(until !== undefined ? { until } : {}),- };- const local = contextReach(ctx) === TRANSPORT_REACH.local;- const fold = summarizeContextReceiptSession(ctx.vault, {- ...window,- ...(maxReceipts !== undefined ? { maxReceipts } : {}),- // Below local reach the operator-rule items leave the item figures,- // and a receipt that recorded nothing else is not folded at all.- ...(local ? {} : { exclude: isRuleOnlyInjection, excludeItem: isOperatorRuleItem }),- });- if (!fold.recorded) {- return {- vault_path: vaultPathField(ctx),- recorded: false,- max_receipts: fold.max_receipts,- note: "no receipts recorded for this filter; receipt emission is opt-in per call",- };- }-- // Observed use is folded over the SAME window, so a per-item verdict- // describes this session rather than the artifact's lifetime rate.- const reuse = observedReuseRates(ctx.vault, {- ...(sessionId !== undefined ? { sessionId } : {}),- ...(since !== undefined ? { since } : {}),- ...(until !== undefined ? { until } : {}),- });- const items = limit === undefined ? fold.items : fold.items.slice(0, limit);-- return {- vault_path: vaultPathField(ctx),- recorded: true,- receipt_count: fold.receipt_count,- item_total: fold.item_total,- distinct_items: fold.distinct_items,- withheld_receipts: fold.withheld_receipts,- // Receipts that inflate `receipt_count` and contribute no items: an- // injection that degraded to cache records `items: []` by design,- // and a receipt with no item array at all cannot be unfolded. Both- // used to vanish into the gap between `receipt_count` and- // `item_total`.- empty_receipts: fold.empty_receipts,- malformed_receipts: fold.malformed_receipts,- truncated: fold.truncated,- max_receipts: fold.max_receipts,- items: items.map((item) => {- const observed = reuse.get(item.path ?? item.id);- return {- id: item.id,- ...(item.path !== undefined ? { path: item.path } : {}),- injections: item.injections,- tokens: item.tokens,- ...(observed !== undefined- ? {- observed: {- used: observed.used,- ignored: observed.ignored,- contradicted: observed.contradicted,- total: observed.total,- score: observed.score,- },- }- : {}),- };- }),- };-}--// ----- brain_event_trace -----------------------------------------------------async function toolBrainEventTrace(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const kind = optionalStringArg("brain_event_trace", args, "kind");- if (kind !== undefined && !BRAIN_LOG_EVENT_KIND_SET.has(kind)) {- throw new MCPError(INVALID_PARAMS, `brain_event_trace: unknown event kind '${kind}'`);- }- const date = optionalStringArg("brain_event_trace", args, "date");- const at = optionalStringArg("brain_event_trace", args, "at");- const sessionId = optionalStringArg("brain_event_trace", args, "session_id");- const limit = coercePositiveInteger("brain_event_trace", "limit", args["limit"]);- const offset = cursorOffsetArg("brain_event_trace", args);- const keepPrivate = coerceBool(args, "keep_private");-- let events;- try {- // The scan early-exits one event past the page's reach- // (`offset + limit + 1`, evaluated by the core before the- // trace-attachment work): the lookahead proves whether a next page- // exists, so `next_cursor` never lies and the full day's matching- // set stays reachable by walking, while one page fetch never re-runs- // the attachment scan past its own reach. (The cursor rollout- // dropped the caller cap that bounded this scan, making every page- // fetch attach traces for the whole day - a quadratic walk under- // forged cursors; the bound restores the early exit without- // reintroducing silent truncation.) `total`/`trace_total` are exact- // once the walk exhausts; before that they report the bound the- // page reached. A limit-less call still reads the day whole: its- // page is the answer, not a step of a walk.- const scanBound = limit !== undefined ? offset + limit + 1 : undefined;- events = resolveLogEventTraces(ctx.vault, {- ...(date !== undefined ? { date } : {}),- ...(at !== undefined ? { at } : {}),- ...(kind !== undefined ? { kind: kind as BrainLogEventKind } : {}),- ...(sessionId !== undefined ? { sessionId } : {}),- ...(scanBound !== undefined ? { limit: scanBound } : {}),- ...(keepPrivate === true ? { keepPrivate: true } : {}),- // The event body is echoed verbatim and log payloads carry- // artifact paths (a-label-is-not-a-boundary, U3).- ownerScope: gatedOwnerScopeView(ctx.vault, ctx.agentName).scope,- // A note-write body carries the page's whole-file digest and byte- // size, so an event naming a page the caller may not read at its- // reach is dropped exactly as an event about an absent page is.- view: reachView(ctx.vault, contextReach(ctx)),- });- } catch (err) {- // A selector-validation error (bad date/at/kind, checked before any IO) is- // a caller error (INVALID_PARAMS). ANY OTHER throw is a runtime IO failure -- // e.g. an existing-but-unreadable log dir (EACCES/EIO/ENOTDIR) - and must be- // an internal error, not a parameter error.- if (err instanceof EventTraceSelectorError) {- throw new MCPError(INVALID_PARAMS, `brain_event_trace: ${err.message}`);- }- throw new MCPError(INTERNAL_ERROR, `brain_event_trace: ${(err as Error).message}`);- }-- const page = pageSlice(events, offset, limit ?? Math.max(events.length, 1));- return {- vault_path: vaultPathField(ctx),- total: page.total,- trace_total: events.reduce((sum, e) => sum + e.traceCount, 0),- events: page.items,- next_cursor: page.next_cursor,- };-}--function receiptOptionsFromArgs(- tool: string,- args: Record<string, unknown>,- trigger: "context_pack" | "pre_compress",- defaultHost: string,-): ContextReceiptOptions | undefined {- if (!coerceBool(args, "receipt")) return undefined;- return {- host: optionalStringArg(tool, args, "receipt_host") ?? defaultHost,- trigger,- ...(optionalStringArg(tool, args, "session_id") !== undefined- ? { sessionId: optionalStringArg(tool, args, "session_id") }- : {}),- ...(optionalStringArg(tool, args, "turn_id") !== undefined- ? { turnId: optionalStringArg(tool, args, "turn_id") }- : {}),- };-}--async function toolBrainContextPresets(- _ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const operation = optionalStringArg("brain_context_presets", args, "operation");- if (operation === "show") {- const presetId = optionalStringArg("brain_context_presets", args, "preset_id");- const result =- presetId === undefined ? { presets: listContextPresets() } : getContextPreset(presetId);- if (result === null) {- throw new MCPError(INVALID_PARAMS, `brain_context_presets: unknown preset ${presetId}`);- }- return Array.isArray(result) ? { presets: result } : { ...result };- }- if (operation === "suggest") {- const model = optionalStringArg("brain_context_presets", args, "model");- const window = coercePositiveInteger(- "brain_context_presets",- "context_window_tokens",- args["context_window_tokens"],- );- return {- ...suggestContextPreset({- ...(model !== undefined ? { model } : {}),- ...(window !== undefined ? { contextWindowTokens: window } : {}),- }),- };- }- if (operation === "diff") {- const presetId = optionalStringArg("brain_context_presets", args, "preset_id");- if (presetId === undefined) {- throw new MCPError(INVALID_PARAMS, "brain_context_presets: preset_id is required for diff");- }- return {- ...diffContextPreset(presetId, contextPresetCurrentConfig(args["current"])),- };- }- throw unknownOperationError("brain_context_presets: operation must be show, suggest, or diff");-}--function contextPresetCurrentConfig(raw: unknown): ContextPresetCurrentConfig {- if (raw === undefined || raw === null) return {};- if (typeof raw !== "object" || Array.isArray(raw)) {- throw new MCPError(INVALID_PARAMS, "brain_context_presets: current must be an object");- }- return raw as ContextPresetCurrentConfig;-}--// ----- brain_pre_compact_extract --------------------------------------------/**- * Read-only bundle of the highest-confidence confirmed preferences plus- * the head of active.md, rendered as a system-prompt addendum for a host- * runtime to inject just before a context-compression event.- */-async function toolBrainPreCompressPack(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const model = optionalModelArg("brain_pre_compress_pack", args);- const topK = coercePositiveInteger("brain_pre_compress_pack", "top_k", args["top_k"]) ?? 10;- const maxCharsPerMemory = coercePositiveInteger(- "brain_pre_compress_pack",- "max_chars_per_memory",- args["max_chars_per_memory"],- );- const maxTotalChars = coercePositiveInteger(- "brain_pre_compress_pack",- "max_total_chars",- args["max_total_chars"],- );- // Derived caps (t_a567cc12): an absent cap used to mean unbounded - the- // one injection surface with no ceiling at all. When a cap is absent- // and a window resolves, the matching preset's `pre_compress` block- // fills it; explicit caps stay first-class; with nothing resolvable the- // historical unbounded addendum stands, byte-identical. `top_k` keeps- // its own 10 default - the presets' top-k values are suggestion- // diagnostics, not this tool's default.- let resolvedCaps: ResolvedModelWindow | null = null;- // A malformed OPEN_SECOND_BRAIN_MODEL_CONTEXT_WINDOW used to rethrow- // here as INVALID_PARAMS - blaming the caller's parameters and losing- // the addendum over an operator typo the caller cannot see and this- // result never disclosed. On THIS path an unparseable env value means- // nothing resolvable: the historical unbounded caps stand and a named- // warning says which channel misread, never echoing the value itself.- let windowWarning: string | undefined;- if (maxCharsPerMemory === undefined || maxTotalChars === undefined) {- try {- resolvedCaps = resolveSurfaceModelWindow(ctx.vault, model ?? undefined);- } catch {- resolvedCaps = null;- windowWarning =- `${MODEL_CONTEXT_WINDOW_ENV_KEY} is not a well-formed positive integer; ` +- "pre-compress caps stay unbounded and nothing was derived from it";- }- }- // The hint fallback rides along here exactly as it does in the- // context-pack budget above: when the resolver's answer is the- // default-sourced assumption, a hint-only model's caps come from its- // hint preset, the same mapping the pack and `brain_context_presets`- // suggest name - one model, one mapping on every surface.- const derivedCaps =- resolvedCaps !== null ? presetForResolvedWindow(model, resolvedCaps).pre_compress : null;- const effMaxCharsPerMemory = maxCharsPerMemory ?? derivedCaps?.max_chars_per_memory;- const effMaxTotalChars = maxTotalChars ?? derivedCaps?.max_total_chars;- const receipt = receiptOptionsFromArgs("brain_pre_compress_pack", args, "pre_compress", "mcp");- const telemetry = telemetryOptionsFromArgs("brain_pre_compress_pack", args, "mcp");- const agentScope = coerceAgentScope(ctx, args, true);- const readable = readableAtContextReachOrUndefined(ctx);- const pack = buildPreCompressPack(ctx.vault, {- topK,- // A preference the caller cannot read at its reach is absent from the- // head and from the top-K walk alike; a caller from whom nothing can- // be withheld is handed no filter.- ...(readable !== undefined ? { readable } : {}),- restricted: contextReach(ctx) !== TRANSPORT_REACH.local,- ...(agentScope !== undefined ? { agentScope } : {}),- ...(effMaxCharsPerMemory !== undefined ? { maxCharsPerMemory: effMaxCharsPerMemory } : {}),- ...(effMaxTotalChars !== undefined ? { maxTotalChars: effMaxTotalChars } : {}),- ...(configuredDegradation(ctx.vault) !== undefined- ? { degradation: configuredDegradation(ctx.vault)! }- : {}),- ...(receipt !== undefined ? { receipt } : {}),- ...(telemetry !== undefined ? { telemetry } : {}),- });- return {- vault_path: vaultPathField(ctx),- text: pack.text,- active_head_included: pack.activeHeadIncluded,- ...(pack.activeHeadSafety ? { active_head_safety: pack.activeHeadSafety } : {}),- total_chars: pack.totalChars,- // The pack's one degradation channel. This is the only surface the- // builder has, so a warning dropped here is a broken `_brain.yaml`- // nothing tells the caller about.- ...(pack.warnings ? { warnings: pack.warnings } : {}),- // The window channel's own warning: present only when the derivation- // was skipped over an unparseable operator env value (M4), so a- // normal answer stays byte-identical.- ...(windowWarning !== undefined ? { window_warning: windowWarning } : {}),- ...(pack.receiptId ? { receipt_id: pack.receiptId } : {}),- ...(pack.telemetryId ? { telemetry_id: pack.telemetryId } : {}),- items: pack.items.map((i) => ({- id: i.id,- principle: i.principle,- trimmed: i.trimmed,- ...(i.safety ? { safety: i.safety } : {}),- })),- };-}--async function toolBrainPreCompactExtract(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const sessionId = requiredStringArg("brain_pre_compact_extract", args, "session_id");- const turnStart = requiredStringArg("brain_pre_compact_extract", args, "turn_start");- const turnEnd = requiredStringArg("brain_pre_compact_extract", args, "turn_end");- const text = requiredStringArg("brain_pre_compact_extract", args, "text");- const maxChars = coercePositiveInteger(- "brain_pre_compact_extract",- "max_chars",- args["max_chars"],- );- const result = extractPreCompactRecords(ctx.vault, {- sessionId,- turnStart,- turnEnd,- text,- ...(optionalStringArg("brain_pre_compact_extract", args, "host") !== undefined- ? { host: optionalStringArg("brain_pre_compact_extract", args, "host") }- : {}),- ...(maxChars !== undefined ? { maxChars } : {}),- ...(coerceBool(args, "interrupted") === true ? { interrupted: true } : {}),- ...(coerceBool(args, "dry_run") === true ? { dryRun: true } : {}),- });- return { count: result.records.length, dry_run: coerceBool(args, "dry_run") === true, ...result };-}--// ----- session recall DAG ----------------------------------------------------/** Operator-configured trim strategy (`recall.degradation` in `_brain.yaml`). */-function configuredDegradation(vault: string): "staged" | undefined {- try {- return loadBrainConfig(vault).recall?.degradation === "staged" ? "staged" : undefined;- } catch {- return undefined;- }-}--async function toolBrainAnticipatoryContext(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const sessionId = coerceStr(args, "session_id");- if (sessionId === null || sessionId === undefined || sessionId.trim() === "") {- throw new MCPError(INVALID_PARAMS, "'session_id' is required");- }- let ttlSeconds: number | undefined;- let maxTokens: number | undefined;- try {- const anticipatory = loadBrainConfig(ctx.vault).anticipatory;- ttlSeconds = anticipatory?.ttl_seconds;- maxTokens = anticipatory?.max_tokens;- } catch {- // defaults apply; a broken config never blocks a read- }- const anticipatoryScope = coerceAgentScope(ctx, args, true);- const now = new Date();- // Below local reach the bundle is built for this caller with the same- // candidate filter `brain_context_pack` applies, and the shared cache is- // neither read nor written: a cached bundle may hold pages this caller- // cannot read, and a filtered bundle must not replace the operator's.- const view = reachView(ctx.vault, contextReach(ctx));- const remote = view.reach !== TRANSPORT_REACH.local;- if (remote) {- // A refresh takes the caller's signal exactly as the cached path does;- // a plain read has no cached signal to reuse here.- const signal = coerceBool(args, "refresh") === true ? coerceStr(args, "signal_text") : null;- const result = buildReaderAnticipatoryContext(ctx.vault, {- sessionId,- now,- visible: (abs: string) => view.visible(vaultRelative(ctx.vault, abs)),- ...(anticipatoryScope !== undefined ? { agentScope: anticipatoryScope } : {}),- ...(maxTokens !== undefined ? { maxTokens } : {}),- ...(typeof signal === "string" ? { signalText: signal } : {}),- });- return anticipatoryAnswer(result);- }- if (coerceBool(args, "refresh") === true) {- const signal = coerceStr(args, "signal_text");- refreshAnticipatoryCache(ctx.vault, {- sessionId,- ...(anticipatoryScope !== undefined ? { agentScope: anticipatoryScope } : {}),- ...(typeof signal === "string" && signal.trim() !== "" ? { signalText: signal } : {}),- now,- ...(ttlSeconds !== undefined ? { ttlSeconds } : {}),- ...(maxTokens !== undefined ? { maxTokens } : {}),- });- }- const result = readAnticipatoryContext(ctx.vault, {- sessionId,- now,- ...(anticipatoryScope !== undefined ? { agentScope: anticipatoryScope } : {}),- ...(ttlSeconds !== undefined ? { ttlSeconds } : {}),- ...(maxTokens !== undefined ? { maxTokens } : {}),- });- return anticipatoryAnswer(result);-}--function anticipatoryAnswer(result: ReadAnticipatoryContextResult): Record<string, unknown> {- return {- cache_state: result.cache_state,- root_session_id: result.root_session_id,- ...(result.generated_at !== undefined ? { generated_at: result.generated_at } : {}),- // Present only when a fresh-by-the-clock entry was refused on its- // provenance stamp or validity window, so an ordinary miss stays- // byte-identical (context-integrity-gates, Unit B).- ...(result.cache_refusal !== undefined ? { cache_refusal: result.cache_refusal } : {}),- items: result.context.items.map((item) => ({- id: item.id,- tier: item.tier,- tokens: item.tokens,- principle: item.principle,- body: item.body,- })),- session_hits: result.context.session_hits,- };-}+ toolBrainAnticipatoryContext,+ toolBrainContextPresets,+ toolBrainPreCompactExtract,+ toolBrainPreCompressPack,+} from "./pack-preset-tools.ts";++export type { ReceiptVerifyRefusalReason, ReceiptVerifyRefusal } from "./pack-receipt-tools.ts";+export {+ RECEIPT_VERIFY_OPERATION,+ RECEIPT_VERIFY_REACH_REASON,+ RECEIPT_VERIFY_WITHHELD_REASON,+ isOperatorRuleItem,+ isRuleOnlyInjection,+} from "./pack-receipt-tools.ts";export const PACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{diff --git a/src/mcp/brain/query-agent-tools.ts b/src/mcp/brain/query-agent-tools.tsnew file mode 100644index 00000000..32903400--- /dev/null+++ b/src/mcp/brain/query-agent-tools.ts@@ -0,0 +1,220 @@+/**+ * The agent-attribution and provenance tools of the query family (task+ * 3.19): `brain_agent_diff`, `brain_backlinks`, `brain_audit` and+ * `brain_sources`, with the contribution-kind and diff-mode coercion+ * they share. Split from `query-tools.ts`; registration happens through+ * that module's registry, which preserves the public QUERY_TOOLS+ * surface.+ */++import { buildBacklinkIndex } from "../../core/brain/backlinks.ts";+import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";+import { readPrefAudit } from "../../core/brain/pref-audit.ts";+import { aggregateSources } from "../../core/brain/portability/sources.ts";+import { brainArtifactSlug, normaliseWikilinkTarget } from "../../core/brain/wikilink.ts";+import { diffAgentSources, type AgentSourceDiffMode } from "../../core/brain/agent-source/diff.ts";+import {+ AGENT_SOURCE_CONTRIBUTION_KINDS,+ isAgentSourceContributionKind,+ type AgentSourceContributionKind,+} from "../../core/brain/agent-source/types.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import { contextReach } from "../tool-contract.ts";+import type { ServerContext } from "../tool-contract.ts";+import { coerceStr, coerceStrList, coerceInt } from "../coerce.ts";+import { reachView } from "../../core/brain/reach-view.ts";+import { recordRefs } from "../../core/brain/log-events-at-reach.ts";+import { pageSlice } from "../../core/brain/offset-cursor.ts";+import { deliveryView, recordReadable, requestRefView } from "./reach-events.ts";+import { TRANSPORT_REACH } from "../../core/graph/transport-reach.ts";+import { cursorOffsetArg } from "./pagination.ts";+import { shapeContribution } from "./query-serialize.ts";++export async function toolBrainAgentDiff(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const mode = coerceAgentDiffMode(args, "mode");+ const topic = coerceStr(args, "topic", false);+ const query = coerceStr(args, "query", false);+ const kind = coerceAgentContributionKind(args, "kind");+ // The twin of `brain_agent_query` over the same provenance fold, and+ // it returns the same contribution rows - ids, topics and the record+ // text. `brain_agent_query` honours an explicit `agent_scope`; this+ // tool declares no such argument, so it takes the GATED server+ // identity, which is `null` unless the operator set+ // `integrity.owner_scope_delivery: fail` (a-label-is-not-a-boundary, U3).+ const ownerScope = gatedOwnerScopeView(ctx.vault, ctx.agentName).scope;+ const limit = coerceInt(args, "limit", 50, 1, 500);+ const offset = cursorOffsetArg("brain_agent_diff", args);+ // Like `brain_agent_query`, the page is cut at this layer: the core+ // fold slices from the first match, so the full matched set is fetched+ // and one offset window is taken. The aggregates (per-agent rollup,+ // topic map, shared/unique topics) are computed over the whole matched+ // set, so they do not move between pages: the limit bounds the+ // returned contributions and the paging, never the comparison.+ const result = diffAgentSources(ctx.vault, {+ ...(mode !== null ? { mode } : {}),+ ...(ownerScope !== null ? { ownerScope } : {}),+ view: reachView(ctx.vault, contextReach(ctx)),+ agents: coerceStrList(args, "agents"),+ ...(topic !== null ? { topic } : {}),+ ...(query !== null ? { query } : {}),+ ...(kind !== null ? { kind } : {}),+ limit: Number.MAX_SAFE_INTEGER,+ });+ const page = pageSlice(result.contributions, offset, limit);+ // Delivery shaping (delivery-trust, lane A): the same rule the twin+ // query tool applies, through the request's one binding.+ const delivery = deliveryView(ctx);+ return {+ mode: result.mode,+ diff_mode: result.diff_mode,+ agents: result.agents,+ unknown_agents: result.unknown_agents,+ per_agent: result.per_agent,+ shared_topics: result.shared_topics,+ unique_topics: result.unique_topics,+ topic_map: result.topic_map,+ total_matched: result.total_matched,+ returned: page.items.length,+ contributions: page.items.map((c) => shapeContribution(delivery, ctx.vault, c)),+ summary: result.summary,+ next_cursor: page.next_cursor,+ };+}++export function coerceAgentContributionKind(+ args: Record<string, unknown>,+ key: string,+): AgentSourceContributionKind | null {+ const raw = coerceStr(args, key, false);+ if (raw === null) return null;+ if (!isAgentSourceContributionKind(raw)) {+ throw new MCPError(+ INVALID_PARAMS,+ `argument '${key}' must be one of ${AGENT_SOURCE_CONTRIBUTION_KINDS.join(", ")}`,+ );+ }+ return raw;+}++export function coerceAgentDiffMode(+ args: Record<string, unknown>,+ key: string,+): AgentSourceDiffMode | null {+ const raw = coerceStr(args, key, false);+ if (raw === null) return null;+ if (raw !== "browse" && raw !== "search" && raw !== "diff" && raw !== "map") {+ throw new MCPError(+ INVALID_PARAMS,+ `argument '${key}' must be 'browse', 'search', 'diff', or 'map'`,+ );+ }+ return raw;+}++// ----- brain_backlinks -----------------------------------------------------++export async function toolBrainBacklinks(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const id = coerceStr(args, "id", true)!;+ // The index is keyed by normalised wikilink targets. Run callers'+ // input through the same normaliser so `pref-foo`, `[[pref-foo]]`,+ // `[[pref-foo|Alias]]`, and `Brain/preferences/pref-foo.md` all+ // resolve to the same lookup.+ const target = normaliseWikilinkTarget(id);+ // The refs name the artifacts that WROTE them, so an unscoped index+ // published another owner's preference and retired ids to any caller+ // (a-label-is-not-a-boundary, U3). The scope is the gated one: no+ // argument exists on this tool, and under `off` the view hides nothing.+ const index = buildBacklinkIndex(ctx.vault, gatedOwnerScopeView(ctx.vault, ctx.agentName).scope, {+ withholdsPrivate: contextReach(ctx) !== TRANSPORT_REACH.local,+ });+ // The same reasoning one rule over: a ref names the artifact that WROTE+ // it, so an index unfiltered by reach publishes the id of a page+ // reserved against remote reads. A withheld TARGET answers as an absent+ // one - the empty backlink document - rather than refusing, because an+ // unknown target is a legitimate zero here and a refusal would be the+ // one response shape that proves the page exists.+ //+ // The target is asked under every spelling its record answers to, so a+ // retired record (on disk only as `ret-x`) asked for as `pref-x` is the+ // reserved page it is, not an absent one whose log backlinks are listed.+ const view = reachView(ctx.vault, contextReach(ctx));+ const refs = view.row(...recordRefs(target))+ ? (index.get(target) ?? []).filter((r) => view.visible(r.source))+ : [];+ const unparsed = index.unparsed+ .filter((u) => view.visible(u.source))+ .map((u) => ({ source: u.source, source_kind: u.sourceKind, reason: u.reason }));+ return {+ id: target,+ count: refs.length,+ refs: refs.map((r) => ({+ source: r.source,+ source_kind: r.sourceKind,+ field: r.field,+ ...(r.timestamp !== undefined ? { timestamp: r.timestamp } : {}),+ })),+ // A `count` beside a non-empty `unparsed` is not a measurement: the+ // walk skipped artifacts whose references it could not read, and a+ // caller told only the count would read a legacy vault's zero as a+ // genuine zero. Omitted entirely when the walk is clean, so a healthy+ // vault's payload is byte-identical.+ //+ // Filtered by the same rule the refs are. Each entry NAMES its source+ // artifact by id, so an unfiltered list disclosed a reserved page's id+ // through a call that never mentioned it - and the honesty this field+ // exists for does not extend to being honest about pages the caller+ // may not know exist.+ ...(unparsed.length > 0 ? { unparsed } : {}),+ };+}++export async function toolBrainAudit(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const raw = coerceStr(args, "pref_id", true)!;+ // The trail is keyed by the original `pref-<slug>` id, and the shared+ // fold in `wikilink.ts` is what reduces every spelling of a reference+ // (`[[id]]`, `[[id|Alias]]`, `Brain/.../id.md`, and the pre- or+ // post-retirement prefix) onto that one key.+ const slug = brainArtifactSlug(raw);+ if (slug.length === 0) {+ throw new Error(`brain_audit: empty preference slug after normalising '${raw}'`);+ }+ const prefId = `pref-${slug}`;+ // The mutation history is the trail of a private page and is private+ // with it, so it is read only when the preference's page is one this+ // caller may see: the same view every sibling reader asks, over every+ // spelling the record answers to. A withheld trail answers as an absent+ // one - the empty history - never as a refusal that would prove the id.+ if (!recordReadable(requestRefView(ctx), prefId)) {+ return { pref_id: prefId, count: 0, records: [], warnings: [] };+ }+ const { records, warnings } = readPrefAudit(ctx.vault, prefId);+ return {+ pref_id: prefId,+ count: records.length,+ records,+ warnings: warnings.map((w) => w.message),+ };+}++export async function toolBrainSources(+ ctx: ServerContext,+ _args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ void _args;+ const report = aggregateSources(ctx.vault);+ return {+ sources: report.sources,+ total_active: report.total_active,+ total_processed: report.total_processed,+ total_archived: report.total_archived,+ };+}diff --git a/src/mcp/brain/query-serialize.ts b/src/mcp/brain/query-serialize.tsnew file mode 100644index 00000000..f9403cec--- /dev/null+++ b/src/mcp/brain/query-serialize.ts@@ -0,0 +1,198 @@+/**+ * The payload shaping of the query family (task 3.19): the delivery+ * wrappers that fence a preference, signal and contribution payload at+ * the caller's reach, the record serializers beneath them, and the+ * source-page resolution a mention names. Split from `query-tools.ts`.+ */++import {+ type BrainPreference,+ type BrainRetired,+ type BrainSignal,+} from "../../core/brain/types.ts";+import type { BrainLogEntry } from "../../core/brain/log.ts";+import { BRAIN_PREFERENCES_REL, BRAIN_RETIRED_REL } from "../../core/brain/path-constants.ts";+import type { AgentSourceContribution } from "../../core/brain/agent-source/types.ts";+import { deliveryView, signalDeliveryRel, UNPROBED_DELIVERY_REL } from "./reach-events.ts";+import { TRANSPORT_REACH } from "../../core/graph/transport-reach.ts";++/** The page a preference or retired payload was parsed from. */+export function preferenceDeliveryRel(p: BrainPreference | BrainRetired): string {+ return p.kind === "brain-retired"+ ? `${BRAIN_RETIRED_REL}/${p.id}.md`+ : `${BRAIN_PREFERENCES_REL}/${p.id}.md`;+}++/**+ * The page an agent contribution's provenance is probed from, or null+ * when there is none to ask: a `log` row is a log event's own text,+ * which the delivery-shaping boundary deliberately leaves untouched.+ * The signal walk is {@link signalDeliveryRel}, shared with the+ * artifact-id mapping in reach-events.ts so the two faces cannot drift.+ * A note with no page of its own probes the guaranteed-absent page -+ * null means "leave untouched" for log rows only, because a fenced+ * delivery is the fail-closed answer for note text whose provenance+ * nothing can name.+ */+export function contributionDeliveryRel(vault: string, c: AgentSourceContribution): string | null {+ switch (c.kind) {+ case "note":+ return c.path ?? UNPROBED_DELIVERY_REL;+ case "preference":+ return c.id.startsWith("ret-")+ ? `${BRAIN_RETIRED_REL}/${c.id}.md`+ : `${BRAIN_PREFERENCES_REL}/${c.id}.md`;+ case "signal":+ return signalDeliveryRel(vault, c.id);+ default:+ return null;+ }+}++/**+ * Serialize one preference payload with its principle shaped.+ *+ * Delivery boundary (delivery-trust, lane A): `principle` is the payload's+ * stored-record body and fences; a retired payload's `retired_reason` does+ * NOT, because it is not free text - `parseRetired` refuses any value+ * outside the closed `BRAIN_RETIRED_REASON` vocabulary (and every writer+ * passes an enum member), so the field is a machine-readable token, not+ * stored prose, and fencing it would break the closed-vocabulary reading+ * remote consumers do. The free text the retire path actually collects+ * lands in `user_rejected_reason`, which no MCP surface delivers.+ */+export function shapePreferencePayload(+ delivery: ReturnType<typeof deliveryView>,+ p: BrainPreference | BrainRetired,+): Record<string, unknown> {+ const payload = serializePreference(p);+ if (delivery.reach === TRANSPORT_REACH.local) return payload;+ return {+ ...payload,+ principle: delivery.shape(payload.principle as string, preferenceDeliveryRel(p)),+ };+}++/** Serialize one signal payload with its principle and raw body shaped. */+export function shapeSignalPayload(+ delivery: ReturnType<typeof deliveryView>,+ vault: string,+ s: BrainSignal,+): Record<string, unknown> {+ const payload = serializeSignal(s);+ if (delivery.reach === TRANSPORT_REACH.local) return payload;+ const rel = signalDeliveryRel(vault, s.id);+ const shaped: Record<string, unknown> = {+ ...payload,+ principle: delivery.shape(payload.principle as string, rel),+ };+ if (typeof payload.raw === "string") shaped.raw = delivery.shape(payload.raw, rel);+ return shaped;+}++/**+ * Shape one contribution row: its `text` body, and the principle the+ * structured `data` block echoes beside it - the same stored text, so a+ * fenced body with an unfenced copy in `data` would not be a fence.+ * Log rows pass through untouched.+ */+export function shapeContribution(+ delivery: ReturnType<typeof deliveryView>,+ vault: string,+ c: AgentSourceContribution,+): AgentSourceContribution {+ if (delivery.reach === TRANSPORT_REACH.local) return c;+ const rel = contributionDeliveryRel(vault, c);+ if (rel === null) return c;+ const data = { ...c.data };+ if (typeof data["principle"] === "string") {+ data["principle"] = delivery.shape(data["principle"] as string, rel);+ }+ return { ...c, text: delivery.shape(c.text, rel), data };+}++export function serializeSignal(s: BrainSignal): Record<string, unknown> {+ return {+ kind: s.kind,+ id: s.id,+ created_at: s.created_at,+ topic: s.topic,+ signal: s.signal,+ agent: s.agent,+ principle: s.principle,+ tags: [...s.tags],+ ...(s.scope !== undefined ? { scope: s.scope } : {}),+ ...(s.source !== undefined ? { source: [...s.source] } : {}),+ ...(s.raw !== undefined ? { raw: s.raw } : {}),+ ...(s.expiration_date !== undefined ? { expiration_date: s.expiration_date } : {}),+ };+}++export function serializePreference(p: BrainPreference | BrainRetired): Record<string, unknown> {+ if (p.kind === "brain-retired") {+ return {+ kind: p.kind,+ id: p.id,+ status: p.status,+ retired_at: p.retired_at,+ retired_reason: p.retired_reason,+ retired_by: p.retired_by,+ ...(p.superseded_by !== undefined ? { superseded_by: p.superseded_by } : {}),+ created_at: p.created_at,+ topic: p.topic,+ ...(p.scope !== undefined ? { scope: p.scope } : {}),+ principle: p.principle,+ evidenced_by: [...p.evidenced_by],+ applied_count: p.applied_count,+ violated_count: p.violated_count,+ last_evidence_at: p.last_evidence_at,+ confidence: p.confidence,+ confidence_value: p.confidence_value,+ pinned: p.pinned,+ tags: [...p.tags],+ ...(p.aliases !== undefined ? { aliases: [...p.aliases] } : {}),+ };+ }+ return {+ kind: p.kind,+ id: p.id,+ created_at: p.created_at,+ confirmed_at: p.confirmed_at,+ unconfirmed_until: p.unconfirmed_until,+ topic: p.topic,+ ...(p.scope !== undefined ? { scope: p.scope } : {}),+ status: p.status,+ principle: p.principle,+ evidenced_by: [...p.evidenced_by],+ applied_count: p.applied_count,+ violated_count: p.violated_count,+ last_evidence_at: p.last_evidence_at,+ confidence: p.confidence,+ confidence_value: p.confidence_value,+ pinned: p.pinned,+ tags: [...p.tags],+ ...(p.supersedes !== undefined ? { supersedes: p.supersedes } : {}),+ ...(p.aliases !== undefined ? { aliases: [...p.aliases] } : {}),+ ...(p.expiration_date !== undefined ? { expiration_date: p.expiration_date } : {}),+ };+}++export function serializeLogEntry(e: BrainLogEntry): Record<string, unknown> {+ // Preserve the structured payload verbatim (array values stay arrays).+ // JSON.stringify handles `ReadonlyArray<string>` and string values+ // identically. `Object.entries` widens the value type to `unknown` for+ // generic-keyed records under `verbatimModuleSyntax`; narrow explicitly.+ const body: Record<string, string | ReadonlyArray<string>> = {};+ for (const [k, v] of Object.entries(e.body) as ReadonlyArray<+ readonly [string, string | ReadonlyArray<string>]+ >) {+ body[k] = Array.isArray(v) ? [...v] : v;+ }+ return {+ timestamp: e.timestamp,+ event_type: e.eventType,+ body,+ };+}++// ----- Misc ----------------------------------------------------------------diff --git a/src/mcp/brain/query-tools.ts b/src/mcp/brain/query-tools.tsindex 9169c3c5..50b9924e 100644--- a/src/mcp/brain/query-tools.ts+++ b/src/mcp/brain/query-tools.ts@@ -6,12 +6,6 @@* BRAIN_TOOLS surface.*/-import { buildBacklinkIndex } from "../../core/brain/backlinks.ts";-import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";-import { readPrefAudit } from "../../core/brain/pref-audit.ts";-import { aggregateSources } from "../../core/brain/portability/sources.ts";-import { findUnlinkedMentions } from "../../core/brain/link-graph/unlinked-mentions.ts";-import { brainArtifactSlug, normaliseWikilinkTarget } from "../../core/brain/wikilink.ts";import {BrainNotFoundError,queryByLogSince,@@ -19,37 +13,12 @@ import {queryByTopic,} from "../../core/brain/query.ts";import { parseIsoUtc } from "../../core/brain/health/iso-time.ts";-import { diffAgentSources, type AgentSourceDiffMode } from "../../core/brain/agent-source/diff.ts";import { queryAgentSources } from "../../core/brain/agent-source/query.ts";-import {- NoteRevertError,- noteRevertDigest,- planNoteRevert,- type NoteRevertSelector,-} from "../../core/brain/notes/revert.ts";-import { listNoteWrites, isLegacyPairDevice } from "../../core/brain/notes/write-log.ts";-import { listWriteDestinations } from "../../core/brain/notes/write-destinations.ts";-import { LogWindowBoundError } from "../../core/brain/notes/log-window.ts";-import {- NOTE_WRITE_OP,- NOTE_WRITE_OPS,- isNoteWriteOp,-} from "../../core/brain/notes/write-record.ts";-import {- AGENT_SOURCE_CONTRIBUTION_KINDS,- isAgentSourceContributionKind,- type AgentSourceContributionKind,-} from "../../core/brain/agent-source/types.ts";-import {- type BrainPreference,- type BrainRetired,- type BrainSignal,-} from "../../core/brain/types.ts";-import type { BrainLogEntry } from "../../core/brain/log.ts";+import { NOTE_WRITE_OPS } from "../../core/brain/notes/write-record.ts";+import { AGENT_SOURCE_CONTRIBUTION_KINDS } from "../../core/brain/agent-source/types.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";import { contextReach } from "../tool-contract.ts";import type { ServerContext, ToolDefinition } from "../tool-contract.ts";-import { vaultPathField } from "../vault-path-field.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import {coerceAgentScope,@@ -60,7 +29,6 @@ import {coerceFormat,coerceInt,coerceStringOptional,- unknownOperationError,} from "../coerce.ts";import { emitGatedTelemetry } from "../../core/brain/continuity/emit.ts";import {@@ -74,16 +42,27 @@ import { isPreferenceVisible } from "../../core/brain/owner-scoped-facts.ts";import { reachView } from "../../core/brain/reach-view.ts";import { logEntriesAtReach, recordRefs } from "../../core/brain/log-events-at-reach.ts";import { pageSlice } from "../../core/brain/offset-cursor.ts";-import { BRAIN_PREFERENCES_REL, BRAIN_RETIRED_REL } from "../../core/brain/path-constants.ts";-import type { AgentSourceContribution } from "../../core/brain/agent-source/types.ts";-import {- deliveryView,- memoryPageRelIn,- signalDeliveryRel,- UNPROBED_DELIVERY_REL,-} from "./reach-events.ts";-import { TRANSPORT_REACH } from "../../core/graph/transport-reach.ts";+import { deliveryView } from "./reach-events.ts";import { cursorOffsetArg, CURSOR_SCHEMA } from "./pagination.ts";+import {+ serializeLogEntry,+ shapeContribution,+ shapePreferencePayload,+ shapeSignalPayload,+} from "./query-serialize.ts";+import {+ coerceAgentContributionKind,+ toolBrainAgentDiff,+ toolBrainAudit,+ toolBrainBacklinks,+ toolBrainSources,+} from "./query-agent-tools.ts";+import {+ BRAIN_WRITES_ACTIONS,+ toolBrainWriteDestinations,+ toolBrainWrites,+} from "./query-writes-tools.ts";+import { toolBrainUnlinkedMentions } from "./query-unlinked-tools.ts";// ----- delivery shaping (delivery-trust, lane A) ----------------------------//@@ -94,101 +73,6 @@ import { cursorOffsetArg, CURSOR_SCHEMA } from "./pagination.ts";// K1 shaper. These helpers only decide WHICH vault-relative page a// payload's provenance is probed from.-/** The page a preference or retired payload was parsed from. */-function preferenceDeliveryRel(p: BrainPreference | BrainRetired): string {- return p.kind === "brain-retired"- ? `${BRAIN_RETIRED_REL}/${p.id}.md`- : `${BRAIN_PREFERENCES_REL}/${p.id}.md`;-}--/**- * The page an agent contribution's provenance is probed from, or null- * when there is none to ask: a `log` row is a log event's own text,- * which the delivery-shaping boundary deliberately leaves untouched.- * The signal walk is {@link signalDeliveryRel}, shared with the- * artifact-id mapping in reach-events.ts so the two faces cannot drift.- * A note with no page of its own probes the guaranteed-absent page -- * null means "leave untouched" for log rows only, because a fenced- * delivery is the fail-closed answer for note text whose provenance- * nothing can name.- */-function contributionDeliveryRel(vault: string, c: AgentSourceContribution): string | null {- switch (c.kind) {- case "note":- return c.path ?? UNPROBED_DELIVERY_REL;- case "preference":- return c.id.startsWith("ret-")- ? `${BRAIN_RETIRED_REL}/${c.id}.md`- : `${BRAIN_PREFERENCES_REL}/${c.id}.md`;- case "signal":- return signalDeliveryRel(vault, c.id);- default:- return null;- }-}--/**- * Serialize one preference payload with its principle shaped.- *- * Delivery boundary (delivery-trust, lane A): `principle` is the payload's- * stored-record body and fences; a retired payload's `retired_reason` does- * NOT, because it is not free text - `parseRetired` refuses any value- * outside the closed `BRAIN_RETIRED_REASON` vocabulary (and every writer- * passes an enum member), so the field is a machine-readable token, not- * stored prose, and fencing it would break the closed-vocabulary reading- * remote consumers do. The free text the retire path actually collects- * lands in `user_rejected_reason`, which no MCP surface delivers.- */-function shapePreferencePayload(- delivery: ReturnType<typeof deliveryView>,- p: BrainPreference | BrainRetired,-): Record<string, unknown> {- const payload = serializePreference(p);- if (delivery.reach === TRANSPORT_REACH.local) return payload;- return {- ...payload,- principle: delivery.shape(payload.principle as string, preferenceDeliveryRel(p)),- };-}--/** Serialize one signal payload with its principle and raw body shaped. */-function shapeSignalPayload(- delivery: ReturnType<typeof deliveryView>,- vault: string,- s: BrainSignal,-): Record<string, unknown> {- const payload = serializeSignal(s);- if (delivery.reach === TRANSPORT_REACH.local) return payload;- const rel = signalDeliveryRel(vault, s.id);- const shaped: Record<string, unknown> = {- ...payload,- principle: delivery.shape(payload.principle as string, rel),- };- if (typeof payload.raw === "string") shaped.raw = delivery.shape(payload.raw, rel);- return shaped;-}--/**- * Shape one contribution row: its `text` body, and the principle the- * structured `data` block echoes beside it - the same stored text, so a- * fenced body with an unfenced copy in `data` would not be a fence.- * Log rows pass through untouched.- */-function shapeContribution(- delivery: ReturnType<typeof deliveryView>,- vault: string,- c: AgentSourceContribution,-): AgentSourceContribution {- if (delivery.reach === TRANSPORT_REACH.local) return c;- const rel = contributionDeliveryRel(vault, c);- if (rel === null) return c;- const data = { ...c.data };- if (typeof data["principle"] === "string") {- data["principle"] = delivery.shape(data["principle"] as string, rel);- }- return { ...c, text: delivery.shape(c.text, rel), data };-}-/** Accepted `at` forms, named in every refusal so the exit is actionable. */const AS_OF_FORMS = "an ISO-8601 instant or YYYY-MM-DD date";@@ -456,664 +340,6 @@ async function toolBrainAgentQuery(};}-/**- * The two actions `brain_writes` offers.- *- * `plan_revert` READS: it returns the plan an operator would apply and- * carries no apply path of its own. Applying a revert moves bytes an- * agent did not ask for on targets it may not have written, and the- * design puts that decision at the CLI where a human types the digest- * (`docs/brainstorm/who-wrote-what/design.md`, "No new MCP tool for- * freeze"). The plan is the half an agent can act on: it names, per- * target, what would happen and why not.- */-const BRAIN_WRITES_ACTION = Object.freeze({- list: "list",- planRevert: "plan_revert",-} as const);--const BRAIN_WRITES_ACTIONS: ReadonlyArray<string> = Object.freeze(- Object.values(BRAIN_WRITES_ACTION),-);--/** Default and maximum rows one `brain_writes` list returns. */-const BRAIN_WRITES_DEFAULT_LIMIT = 50;-const BRAIN_WRITES_MAX_LIMIT = 500;--/**- * Run one write-ledger read, mapping the shared window parser's named- * error to `INVALID_PARAMS` blaming the mistyped argument. The readers- * throw `LogWindowBoundError` for a `since`/`until` in neither accepted- * spelling; that is client-resolvable input, and an uncaught throw here- * would surface as a server fault instead of the caller's mistake.- */-function ledgerRead<T>(tool: string, read: () => T): T {- try {- return read();- } catch (err) {- if (err instanceof LogWindowBoundError) {- throw new MCPError(INVALID_PARAMS, `${tool}: ${err.message}`);- }- throw err;- }-}--/**- * One device selector from an argument, shared by `brain_writes`,- * `brain_write_destinations` and the `plan_revert` selector. The empty- * (or whitespace-only) string is the legacy un-sharded pair and IS a- * filter value, so it is read through the shared- * {@link isLegacyPairDevice} before `coerceStr`, which treats emptiness- * as absence - both schemas promise `device: ""` selects the un-sharded- * log, and a coercion-first reading made that unreachable.- */-function deviceArg(args: Record<string, unknown>): string | null {- if (isLegacyPairDevice(args["device"])) return "";- return coerceStr(args, "device", false);-}--async function toolBrainWrites(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const action = coerceStr(args, "action", false) ?? BRAIN_WRITES_ACTION.list;- if (action === BRAIN_WRITES_ACTION.planRevert) {- return planRevert(ctx, args);- }- if (action !== BRAIN_WRITES_ACTION.list) {- throw unknownOperationError(- `brain_writes: 'action' must be one of ${BRAIN_WRITES_ACTIONS.join(", ")}`,- );- }- const rawOp = coerceStr(args, "op", false);- if (rawOp !== null && !isNoteWriteOp(rawOp)) {- throw new MCPError(- INVALID_PARAMS,- `brain_writes: 'op' must be one of ${Object.values(NOTE_WRITE_OP).join(", ")}`,- );- }- const agent = coerceStr(args, "agent", false);- const device = deviceArg(args);- const path = coerceStr(args, "path", false);- const since = coerceStr(args, "since", false);- const until = coerceStr(args, "until", false);- const limit = coerceInt(args, "limit", BRAIN_WRITES_DEFAULT_LIMIT, 1, BRAIN_WRITES_MAX_LIMIT);- const offset = cursorOffsetArg("brain_writes", args);-- // The log never opens the notes it names, so the reach rule is asked- // per target here: at remote reach a write to a page reserved against- // remote reads (or one whose file is gone - an unreadable claim fails- // closed) is dropped before counting, so neither its path nor the- // total betrays it. At local reach the view is the shared no-op.- const view = reachView(ctx.vault, contextReach(ctx));- const result = ledgerRead("brain_writes", () =>- listNoteWrites(ctx.vault, {- ...(agent !== null ? { agent } : {}),- ...(device !== null ? { device } : {}),- ...(path !== null ? { path } : {}),- ...(since !== null ? { since } : {}),- ...(until !== null ? { until } : {}),- ...(rawOp !== null ? { op: rawOp } : {}),- withholdsPrivate: view.withholdsPrivate === true,- }),- );- const writes = view.filtersNothing- ? result.writes- : result.writes.filter((w) => view.visible(w.target));- // `total_matched` beside `returned` so a truncated answer is legible as- // one: a list capped at the limit and a list that IS the whole history- // are otherwise the same shape. `next_cursor` continues the walk.- const page = pageSlice(writes, offset, limit);- return {- action: BRAIN_WRITES_ACTION.list,- total_matched: page.total,- returned: page.items.length,- writes: page.items.map((w) => ({ ...w })),- warnings: result.warnings.map((w) => ({- path: w.path,- line: w.lineNumber,- message: w.message,- })),- next_cursor: page.next_cursor,- };-}--/**- * The read-only half of the per-agent revert: what undoing the selected- * writes WOULD do, sealed by the digest `o2b brain writes revert --apply`- * takes.- *- * Every refusal the planner raises for the whole call - the unbounded- * selector, today the only one - comes back as `INVALID_PARAMS` carrying- * the CODE, so an agent narrows on a token rather than on a sentence.- * Nothing here writes; the digest is the only thing that crosses to the- * operator's terminal.- */-function planRevert(ctx: ServerContext, args: Record<string, unknown>): Record<string, unknown> {- // The device rides the same empty-aware selector as the list action:- // `device: ""` names the legacy un-sharded pair, and a selector that- // dropped the empty string beside a path would revert that path's- // writes from EVERY device while looking device-scoped.- const device = deviceArg(args);- const selector: NoteRevertSelector = {- ...selectorArg(args, "agent"),- ...(device !== null ? { device } : {}),- ...selectorArg(args, "path"),- ...selectorArg(args, "since"),- ...selectorArg(args, "until"),- };- const view = reachView(ctx.vault, contextReach(ctx));- let plan;- try {- plan = planNoteRevert(ctx.vault, selector, {- withholdsPrivate: view.withholdsPrivate === true,- });- } catch (err) {- if (err instanceof NoteRevertError) {- throw new MCPError(INVALID_PARAMS, `brain_writes: ${err.code}: ${err.message}`);- }- // The planner reads the same window bounds as the list surface, so a- // malformed since / until is the same client-resolvable mistake here.- if (err instanceof LogWindowBoundError) {- throw new MCPError(INVALID_PARAMS, `brain_writes: ${err.message}`);- }- throw err;- }- // Same reach rule as `list`. When an entry is withheld, the digest- // seals only the entries shown: the full plan's digest covers each- // hidden entry's current-bytes hash, so it would differ between a- // withheld page, a deleted one and a path never written, and change- // whenever the withheld page did. The CLI apply re-plans in full and- // refuses this digest with `digest_mismatch`, the safe outcome for a- // plan the caller could not fully see.- const entries = view.filtersNothing- ? plan.entries- : plan.entries.filter((entry) => view.visible(entry.target));- const digest =- entries.length === plan.entries.length ? plan.digest : noteRevertDigest(plan.selector, entries);- return {- action: BRAIN_WRITES_ACTION.planRevert,- selector: { ...plan.selector },- entries: entries.map((entry) => ({ ...entry })),- digest,- planned_at: plan.planned_at,- next_command: `o2b brain writes revert --apply ${digest}`,- warnings: plan.warnings.map((w) => ({- path: w.path,- line: w.lineNumber,- message: w.message,- })),- };-}--/**- * Default and maximum rows one `brain_write_destinations` call returns.- */-const BRAIN_WRITE_DESTINATIONS_DEFAULT_LIMIT = 50;-const BRAIN_WRITE_DESTINATIONS_MAX_LIMIT = 500;--/**- * The destination-keyed aggregate over the write ledger (actionable-now- * batch, A4): one row per vault-relative target the recorded write- * events name, across BOTH the note-write and the write-session kinds,- * with the kinds coverage field stating honestly which kinds spoke. The- * log never opens the pages it names, so the reach rule is asked per row- * here exactly as `brain_writes` asks it: at remote reach a destination- * whose page is reserved against remote reads - or unreadable, which- * fails closed - is dropped from the rows AND from `total_matched`, so a- * withheld page moves no count. Read-only.- */-async function toolBrainWriteDestinations(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const agent = coerceStr(args, "agent", false);- const device = deviceArg(args);- const path = coerceStr(args, "path", false);- const since = coerceStr(args, "since", false);- const until = coerceStr(args, "until", false);- const limit = coerceInt(- args,- "limit",- BRAIN_WRITE_DESTINATIONS_DEFAULT_LIMIT,- 1,- BRAIN_WRITE_DESTINATIONS_MAX_LIMIT,- );- const offset = cursorOffsetArg("brain_write_destinations", args);-- const view = reachView(ctx.vault, contextReach(ctx));- const result = ledgerRead("brain_write_destinations", () =>- listWriteDestinations(ctx.vault, {- ...(agent !== null ? { agent } : {}),- ...(device !== null ? { device } : {}),- ...(path !== null ? { path } : {}),- ...(since !== null ? { since } : {}),- ...(until !== null ? { until } : {}),- withholdsPrivate: view.withholdsPrivate === true,- }),- );- const rows = view.filtersNothing- ? result.destinations- : result.destinations.filter((d) => view.visible(d.target));- // `total_matched` beside `returned`, and `next_cursor` continuing the- // walk, so a truncated answer is legible as one.- const page = pageSlice(rows, offset, limit);- return {- total_matched: page.total,- returned: page.items.length,- destinations: page.items.map((d) => ({- ...d,- kinds: [...d.kinds],- agents: [...d.agents],- devices: [...d.devices],- })),- coverage_note: result.coverage_note,- // The window the walk actually covered, both ends completed to- // timestamps: the default lower bound is computed, not sent, so a- // caller reading only its own arguments would misread the coverage.- window: { since: result.window.since, until: result.window.until },- warnings: result.warnings.map((w) => ({- path: w.path,- line: w.lineNumber,- message: w.message,- })),- next_cursor: page.next_cursor,- };-}--/** One selector field, present only when the caller supplied it. The- * device is NOT read here: it goes through {@link deviceArg}, whose- * empty string is the legacy un-sharded pair, not absence. */-function selectorArg(- args: Record<string, unknown>,- key: "agent" | "path" | "since" | "until",-): Partial<Record<typeof key, string>> {- const value = coerceStr(args, key, false);- return value === null ? {} : { [key]: value };-}--async function toolBrainAgentDiff(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const mode = coerceAgentDiffMode(args, "mode");- const topic = coerceStr(args, "topic", false);- const query = coerceStr(args, "query", false);- const kind = coerceAgentContributionKind(args, "kind");- // The twin of `brain_agent_query` over the same provenance fold, and- // it returns the same contribution rows - ids, topics and the record- // text. `brain_agent_query` honours an explicit `agent_scope`; this- // tool declares no such argument, so it takes the GATED server- // identity, which is `null` unless the operator set- // `integrity.owner_scope_delivery: fail` (a-label-is-not-a-boundary, U3).- const ownerScope = gatedOwnerScopeView(ctx.vault, ctx.agentName).scope;- const limit = coerceInt(args, "limit", 50, 1, 500);- const offset = cursorOffsetArg("brain_agent_diff", args);- // Like `brain_agent_query`, the page is cut at this layer: the core- // fold slices from the first match, so the full matched set is fetched- // and one offset window is taken. The aggregates (per-agent rollup,- // topic map, shared/unique topics) are computed over the whole matched- // set, so they do not move between pages: the limit bounds the- // returned contributions and the paging, never the comparison.- const result = diffAgentSources(ctx.vault, {- ...(mode !== null ? { mode } : {}),- ...(ownerScope !== null ? { ownerScope } : {}),- view: reachView(ctx.vault, contextReach(ctx)),- agents: coerceStrList(args, "agents"),- ...(topic !== null ? { topic } : {}),- ...(query !== null ? { query } : {}),- ...(kind !== null ? { kind } : {}),- limit: Number.MAX_SAFE_INTEGER,- });- const page = pageSlice(result.contributions, offset, limit);- // Delivery shaping (delivery-trust, lane A): the same rule the twin- // query tool applies, through the request's one binding.- const delivery = deliveryView(ctx);- return {- mode: result.mode,- diff_mode: result.diff_mode,- agents: result.agents,- unknown_agents: result.unknown_agents,- per_agent: result.per_agent,- shared_topics: result.shared_topics,- unique_topics: result.unique_topics,- topic_map: result.topic_map,- total_matched: result.total_matched,- returned: page.items.length,- contributions: page.items.map((c) => shapeContribution(delivery, ctx.vault, c)),- summary: result.summary,- next_cursor: page.next_cursor,- };-}--function coerceAgentContributionKind(- args: Record<string, unknown>,- key: string,-): AgentSourceContributionKind | null {- const raw = coerceStr(args, key, false);- if (raw === null) return null;- if (!isAgentSourceContributionKind(raw)) {- throw new MCPError(- INVALID_PARAMS,- `argument '${key}' must be one of ${AGENT_SOURCE_CONTRIBUTION_KINDS.join(", ")}`,- );- }- return raw;-}--function coerceAgentDiffMode(- args: Record<string, unknown>,- key: string,-): AgentSourceDiffMode | null {- const raw = coerceStr(args, key, false);- if (raw === null) return null;- if (raw !== "browse" && raw !== "search" && raw !== "diff" && raw !== "map") {- throw new MCPError(- INVALID_PARAMS,- `argument '${key}' must be 'browse', 'search', 'diff', or 'map'`,- );- }- return raw;-}--// ----- brain_backlinks -------------------------------------------------------async function toolBrainBacklinks(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const id = coerceStr(args, "id", true)!;- // The index is keyed by normalised wikilink targets. Run callers'- // input through the same normaliser so `pref-foo`, `[[pref-foo]]`,- // `[[pref-foo|Alias]]`, and `Brain/preferences/pref-foo.md` all- // resolve to the same lookup.- const target = normaliseWikilinkTarget(id);- // The refs name the artifacts that WROTE them, so an unscoped index- // published another owner's preference and retired ids to any caller- // (a-label-is-not-a-boundary, U3). The scope is the gated one: no- // argument exists on this tool, and under `off` the view hides nothing.- const index = buildBacklinkIndex(ctx.vault, gatedOwnerScopeView(ctx.vault, ctx.agentName).scope, {- withholdsPrivate: contextReach(ctx) !== TRANSPORT_REACH.local,- });- // The same reasoning one rule over: a ref names the artifact that WROTE- // it, so an index unfiltered by reach publishes the id of a page- // reserved against remote reads. A withheld TARGET answers as an absent- // one - the empty backlink document - rather than refusing, because an- // unknown target is a legitimate zero here and a refusal would be the- // one response shape that proves the page exists.- //- // The target is asked under every spelling its record answers to, so a- // retired record (on disk only as `ret-x`) asked for as `pref-x` is the- // reserved page it is, not an absent one whose log backlinks are listed.- const view = reachView(ctx.vault, contextReach(ctx));- const refs = view.row(...recordRefs(target))- ? (index.get(target) ?? []).filter((r) => view.visible(r.source))- : [];- const unparsed = index.unparsed- .filter((u) => view.visible(u.source))- .map((u) => ({ source: u.source, source_kind: u.sourceKind, reason: u.reason }));- return {- id: target,- count: refs.length,- refs: refs.map((r) => ({- source: r.source,- source_kind: r.sourceKind,- field: r.field,- ...(r.timestamp !== undefined ? { timestamp: r.timestamp } : {}),- })),- // A `count` beside a non-empty `unparsed` is not a measurement: the- // walk skipped artifacts whose references it could not read, and a- // caller told only the count would read a legacy vault's zero as a- // genuine zero. Omitted entirely when the walk is clean, so a healthy- // vault's payload is byte-identical.- //- // Filtered by the same rule the refs are. Each entry NAMES its source- // artifact by id, so an unfiltered list disclosed a reserved page's id- // through a call that never mentioned it - and the honesty this field- // exists for does not extend to being honest about pages the caller- // may not know exist.- ...(unparsed.length > 0 ? { unparsed } : {}),- };-}--async function toolBrainAudit(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const raw = coerceStr(args, "pref_id", true)!;- // The trail is keyed by the original `pref-<slug>` id, and the shared- // fold in `wikilink.ts` is what reduces every spelling of a reference- // (`[[id]]`, `[[id|Alias]]`, `Brain/.../id.md`, and the pre- or- // post-retirement prefix) onto that one key.- const slug = brainArtifactSlug(raw);- if (slug.length === 0) {- throw new Error(`brain_audit: empty preference slug after normalising '${raw}'`);- }- const prefId = `pref-${slug}`;- const { records, warnings } = readPrefAudit(ctx.vault, prefId);- return {- pref_id: prefId,- count: records.length,- records,- warnings: warnings.map((w) => w.message),- };-}--async function toolBrainSources(- ctx: ServerContext,- _args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- void _args;- const report = aggregateSources(ctx.vault);- return {- sources: report.sources,- total_active: report.total_active,- total_processed: report.total_processed,- total_archived: report.total_archived,- };-}--// ----- brain_unlinked_mentions --------------------------------------------------/** Page size when no `limit` is sent: the core scanner's own default. */-const UNLINKED_MENTIONS_DEFAULT_LIMIT = 100;--/**- * Raw-text mentions of a target's title / aliases that are NOT- * already inside `[[...]]` wikilinks. Read-only walker over- * `Brain/preferences/` and `Brain/retired/`. Match boundary is- * Unicode-aware (`\p{L}`, `\p{N}`), language-agnostic.- */-async function toolBrainUnlinkedMentions(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const idRaw = args["id"];- if (typeof idRaw !== "string" || idRaw.trim().length === 0) {- throw new MCPError(INVALID_PARAMS, "brain_unlinked_mentions: id must be a non-empty string");- }- const targetId = normaliseWikilinkTarget(idRaw);- const offset = cursorOffsetArg("brain_unlinked_mentions", args);- // Limit coercion mirrors the v0.10.16 `brain_operator_summary`- // precedent: accept either a number or a strict integer-literal- // string (`"5"` ok; `"abc"`, `"3abc"`, `"2.5"` rejected). This- // keeps the MCP boundary uniform across new tools.- const limitRaw = args["limit"];- let limit: number | undefined;- if (limitRaw !== undefined && limitRaw !== null) {- if (typeof limitRaw === "number") {- if (!Number.isInteger(limitRaw) || limitRaw < 1) {- throw new MCPError(- INVALID_PARAMS,- "brain_unlinked_mentions: limit must be a positive integer",- );- }- limit = limitRaw;- } else if (typeof limitRaw === "string") {- const trimmed = limitRaw.trim();- if (trimmed === "" || !/^[0-9]+$/.test(trimmed)) {- throw new MCPError(- INVALID_PARAMS,- "brain_unlinked_mentions: limit must be a positive integer",- );- }- const parsed = Number.parseInt(trimmed, 10);- if (parsed < 1) {- throw new MCPError(- INVALID_PARAMS,- "brain_unlinked_mentions: limit must be a positive integer",- );- }- limit = parsed;- } else {- throw new MCPError(- INVALID_PARAMS,- "brain_unlinked_mentions: limit must be a positive integer",- );- }- }- // `context` is the source artifact's own line of prose, so an- // unscoped scan republished an owner-private body (U3, recon C3).- // The scanner early-exits one mention past the page's reach- // (`offset + limit + 1`): the lookahead proves whether a next page- // exists, so `next_cursor` never lies and the full visible set stays- // reachable by walking, while one page fetch never rescans the- // directory walk past its own reach. (The cursor rollout replaced the- // scanner's caller cap with `MAX_SAFE_INTEGER`, which made every page- // fetch re-walk every preference and retired file - a quadratic walk- // under forged cursors; the bound restores the early exit without- // reintroducing silent truncation.) `total` is exact once the walk- // exhausts; before that it reports the bound the page reached.- const pageSize = limit ?? UNLINKED_MENTIONS_DEFAULT_LIMIT;- const mentions = findUnlinkedMentions(ctx.vault, targetId, {- limit: offset + pageSize + 1,- ownerScope: gatedOwnerScopeView(ctx.vault, ctx.agentName).scope,- reachView: reachView(ctx.vault, contextReach(ctx)),- });- const page = pageSlice(mentions, offset, pageSize);- // Each mention's `context` is one line of the source page's own prose- // (delivery-trust, lane A): shaped through the request's delivery- // binding at the page the source id was parsed from - asked in the- // scanner's own walk order (preferences, then retired), so the probe- // reads the exact page the line came from. An id whose file sits in- // neither folder probes the guaranteed-absent page: fail closed,- // never a guessed root page whose stamps could vouch for prose it- // does not carry. Local reach keeps the bytes.- const delivery = deliveryView(ctx);- return {- vault_path: vaultPathField(ctx),- target_id: targetId,- total: page.total,- mentions: page.items.map((m) => ({- source: m.source,- line: m.line,- term: m.term,- context: delivery.shape(m.contextSnippet, mentionSourceRel(ctx.vault, m.source)),- })),- next_cursor: page.next_cursor,- };-}--/**- * The page a mention's source id was parsed from: the scanner walks the- * preferences folder then the retired one, so the same walk order- * answers which of the two holds the file, and an id whose file is in- * neither probes the guaranteed-absent page.- */-function mentionSourceRel(vault: string, id: string): string {- return (- memoryPageRelIn(vault, id, [BRAIN_PREFERENCES_REL, BRAIN_RETIRED_REL]) ?? UNPROBED_DELIVERY_REL- );-}--// ----- brain_foresight (t_08a79c81) -------------------------------------------function serializeSignal(s: BrainSignal): Record<string, unknown> {- return {- kind: s.kind,- id: s.id,- created_at: s.created_at,- topic: s.topic,- signal: s.signal,- agent: s.agent,- principle: s.principle,- tags: [...s.tags],- ...(s.scope !== undefined ? { scope: s.scope } : {}),- ...(s.source !== undefined ? { source: [...s.source] } : {}),- ...(s.raw !== undefined ? { raw: s.raw } : {}),- ...(s.expiration_date !== undefined ? { expiration_date: s.expiration_date } : {}),- };-}--function serializePreference(p: BrainPreference | BrainRetired): Record<string, unknown> {- if (p.kind === "brain-retired") {- return {- kind: p.kind,- id: p.id,- status: p.status,- retired_at: p.retired_at,- retired_reason: p.retired_reason,- retired_by: p.retired_by,- ...(p.superseded_by !== undefined ? { superseded_by: p.superseded_by } : {}),- created_at: p.created_at,- topic: p.topic,- ...(p.scope !== undefined ? { scope: p.scope } : {}),- principle: p.principle,- evidenced_by: [...p.evidenced_by],- applied_count: p.applied_count,- violated_count: p.violated_count,- last_evidence_at: p.last_evidence_at,- confidence: p.confidence,- confidence_value: p.confidence_value,- pinned: p.pinned,- tags: [...p.tags],- ...(p.aliases !== undefined ? { aliases: [...p.aliases] } : {}),- };- }- return {- kind: p.kind,- id: p.id,- created_at: p.created_at,- confirmed_at: p.confirmed_at,- unconfirmed_until: p.unconfirmed_until,- topic: p.topic,- ...(p.scope !== undefined ? { scope: p.scope } : {}),- status: p.status,- principle: p.principle,- evidenced_by: [...p.evidenced_by],- applied_count: p.applied_count,- violated_count: p.violated_count,- last_evidence_at: p.last_evidence_at,- confidence: p.confidence,- confidence_value: p.confidence_value,- pinned: p.pinned,- tags: [...p.tags],- ...(p.supersedes !== undefined ? { supersedes: p.supersedes } : {}),- ...(p.aliases !== undefined ? { aliases: [...p.aliases] } : {}),- ...(p.expiration_date !== undefined ? { expiration_date: p.expiration_date } : {}),- };-}--function serializeLogEntry(e: BrainLogEntry): Record<string, unknown> {- // Preserve the structured payload verbatim (array values stay arrays).- // JSON.stringify handles `ReadonlyArray<string>` and string values- // identically. `Object.entries` widens the value type to `unknown` for- // generic-keyed records under `verbatimModuleSyntax`; narrow explicitly.- const body: Record<string, string | ReadonlyArray<string>> = {};- for (const [k, v] of Object.entries(e.body) as ReadonlyArray<- readonly [string, string | ReadonlyArray<string>]- >) {- body[k] = Array.isArray(v) ? [...v] : v;- }- return {- timestamp: e.timestamp,- event_type: e.eventType,- body,- };-}--// ----- Misc -----------------------------------------------------------------const BRAIN_QUERY_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {type: "object",required: ["mode"],diff --git a/src/mcp/brain/query-unlinked-tools.ts b/src/mcp/brain/query-unlinked-tools.tsnew file mode 100644index 00000000..f3f41402--- /dev/null+++ b/src/mcp/brain/query-unlinked-tools.ts@@ -0,0 +1,135 @@+/**+ * `brain_unlinked_mentions` (task 3.19): the scanner that names vault+ * pages a record's text touches without a link, with the source-page+ * resolution its payload names. Split from `query-tools.ts`;+ * registration happens through that module's registry, which preserves+ * the public QUERY_TOOLS surface.+ */++import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";+import { findUnlinkedMentions } from "../../core/brain/link-graph/unlinked-mentions.ts";+import { normaliseWikilinkTarget } from "../../core/brain/wikilink.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import { contextReach } from "../tool-contract.ts";+import type { ServerContext } from "../tool-contract.ts";+import { vaultPathField } from "../vault-path-field.ts";+import { reachView } from "../../core/brain/reach-view.ts";+import { pageSlice } from "../../core/brain/offset-cursor.ts";+import { BRAIN_PREFERENCES_REL, BRAIN_RETIRED_REL } from "../../core/brain/path-constants.ts";+import { deliveryView, memoryPageRelIn, UNPROBED_DELIVERY_REL } from "./reach-events.ts";+import { cursorOffsetArg } from "./pagination.ts";++// ----- brain_unlinked_mentions ------------------------------------------------++/** Page size when no `limit` is sent: the core scanner's own default. */+export const UNLINKED_MENTIONS_DEFAULT_LIMIT = 100;++/**+ * Raw-text mentions of a target's title / aliases that are NOT+ * already inside `[[...]]` wikilinks. Read-only walker over+ * `Brain/preferences/` and `Brain/retired/`. Match boundary is+ * Unicode-aware (`\p{L}`, `\p{N}`), language-agnostic.+ */+export async function toolBrainUnlinkedMentions(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const idRaw = args["id"];+ if (typeof idRaw !== "string" || idRaw.trim().length === 0) {+ throw new MCPError(INVALID_PARAMS, "brain_unlinked_mentions: id must be a non-empty string");+ }+ const targetId = normaliseWikilinkTarget(idRaw);+ const offset = cursorOffsetArg("brain_unlinked_mentions", args);+ // Limit coercion mirrors the v0.10.16 `brain_operator_summary`+ // precedent: accept either a number or a strict integer-literal+ // string (`"5"` ok; `"abc"`, `"3abc"`, `"2.5"` rejected). This+ // keeps the MCP boundary uniform across new tools.+ const limitRaw = args["limit"];+ let limit: number | undefined;+ if (limitRaw !== undefined && limitRaw !== null) {+ if (typeof limitRaw === "number") {+ if (!Number.isInteger(limitRaw) || limitRaw < 1) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_unlinked_mentions: limit must be a positive integer",+ );+ }+ limit = limitRaw;+ } else if (typeof limitRaw === "string") {+ const trimmed = limitRaw.trim();+ if (trimmed === "" || !/^[0-9]+$/.test(trimmed)) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_unlinked_mentions: limit must be a positive integer",+ );+ }+ const parsed = Number.parseInt(trimmed, 10);+ if (parsed < 1) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_unlinked_mentions: limit must be a positive integer",+ );+ }+ limit = parsed;+ } else {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_unlinked_mentions: limit must be a positive integer",+ );+ }+ }+ // `context` is the source artifact's own line of prose, so an+ // unscoped scan republished an owner-private body (U3, recon C3).+ // The scanner early-exits one mention past the page's reach+ // (`offset + limit + 1`): the lookahead proves whether a next page+ // exists, so `next_cursor` never lies and the full visible set stays+ // reachable by walking, while one page fetch never rescans the+ // directory walk past its own reach. (The cursor rollout replaced the+ // scanner's caller cap with `MAX_SAFE_INTEGER`, which made every page+ // fetch re-walk every preference and retired file - a quadratic walk+ // under forged cursors; the bound restores the early exit without+ // reintroducing silent truncation.) `total` is exact once the walk+ // exhausts; before that it reports the bound the page reached.+ const pageSize = limit ?? UNLINKED_MENTIONS_DEFAULT_LIMIT;+ const mentions = findUnlinkedMentions(ctx.vault, targetId, {+ limit: offset + pageSize + 1,+ ownerScope: gatedOwnerScopeView(ctx.vault, ctx.agentName).scope,+ reachView: reachView(ctx.vault, contextReach(ctx)),+ });+ const page = pageSlice(mentions, offset, pageSize);+ // Each mention's `context` is one line of the source page's own prose+ // (delivery-trust, lane A): shaped through the request's delivery+ // binding at the page the source id was parsed from - asked in the+ // scanner's own walk order (preferences, then retired), so the probe+ // reads the exact page the line came from. An id whose file sits in+ // neither folder probes the guaranteed-absent page: fail closed,+ // never a guessed root page whose stamps could vouch for prose it+ // does not carry. Local reach keeps the bytes.+ const delivery = deliveryView(ctx);+ return {+ vault_path: vaultPathField(ctx),+ target_id: targetId,+ total: page.total,+ mentions: page.items.map((m) => ({+ source: m.source,+ line: m.line,+ term: m.term,+ context: delivery.shape(m.contextSnippet, mentionSourceRel(ctx.vault, m.source)),+ })),+ next_cursor: page.next_cursor,+ };+}++/**+ * The page a mention's source id was parsed from: the scanner walks the+ * preferences folder then the retired one, so the same walk order+ * answers which of the two holds the file, and an id whose file is in+ * neither probes the guaranteed-absent page.+ */+export function mentionSourceRel(vault: string, id: string): string {+ return (+ memoryPageRelIn(vault, id, [BRAIN_PREFERENCES_REL, BRAIN_RETIRED_REL]) ?? UNPROBED_DELIVERY_REL+ );+}++// ----- brain_foresight (t_08a79c81) -----------------------------------------diff --git a/src/mcp/brain/query-writes-tools.ts b/src/mcp/brain/query-writes-tools.tsnew file mode 100644index 00000000..c4c349b5--- /dev/null+++ b/src/mcp/brain/query-writes-tools.ts@@ -0,0 +1,304 @@+/**+ * The write-ledger tools of the query family (task 3.19):+ * `brain_writes` and `brain_write_destinations`, with the plan-revert+ * preview and the ledger-read wrapper they answer through. Split from+ * `query-tools.ts`; registration happens through that module's registry,+ * which preserves the public QUERY_TOOLS surface.+ */++import {+ NoteRevertError,+ noteRevertDigest,+ planNoteRevert,+ type NoteRevertSelector,+} from "../../core/brain/notes/revert.ts";+import { listNoteWrites, isLegacyPairDevice } from "../../core/brain/notes/write-log.ts";+import { listWriteDestinations } from "../../core/brain/notes/write-destinations.ts";+import { LogWindowBoundError } from "../../core/brain/notes/log-window.ts";+import { NOTE_WRITE_OP, isNoteWriteOp } from "../../core/brain/notes/write-record.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import { contextReach } from "../tool-contract.ts";+import type { ServerContext } from "../tool-contract.ts";+import { coerceStr, coerceInt, unknownOperationError } from "../coerce.ts";+import { reachView } from "../../core/brain/reach-view.ts";+import { pageSlice } from "../../core/brain/offset-cursor.ts";+import { cursorOffsetArg } from "./pagination.ts";++/**+ * The two actions `brain_writes` offers.+ *+ * `plan_revert` READS: it returns the plan an operator would apply and+ * carries no apply path of its own. Applying a revert moves bytes an+ * agent did not ask for on targets it may not have written, and the+ * design puts that decision at the CLI where a human types the digest+ * (`docs/brainstorm/who-wrote-what/design.md`, "No new MCP tool for+ * freeze"). The plan is the half an agent can act on: it names, per+ * target, what would happen and why not.+ */+export const BRAIN_WRITES_ACTION = Object.freeze({+ list: "list",+ planRevert: "plan_revert",+} as const);++export const BRAIN_WRITES_ACTIONS: ReadonlyArray<string> = Object.freeze(+ Object.values(BRAIN_WRITES_ACTION),+);++/** Default and maximum rows one `brain_writes` list returns. */+export const BRAIN_WRITES_DEFAULT_LIMIT = 50;+export const BRAIN_WRITES_MAX_LIMIT = 500;++/**+ * Run one write-ledger read, mapping the shared window parser's named+ * error to `INVALID_PARAMS` blaming the mistyped argument. The readers+ * throw `LogWindowBoundError` for a `since`/`until` in neither accepted+ * spelling; that is client-resolvable input, and an uncaught throw here+ * would surface as a server fault instead of the caller's mistake.+ */+export function ledgerRead<T>(tool: string, read: () => T): T {+ try {+ return read();+ } catch (err) {+ if (err instanceof LogWindowBoundError) {+ throw new MCPError(INVALID_PARAMS, `${tool}: ${err.message}`);+ }+ throw err;+ }+}++/**+ * One device selector from an argument, shared by `brain_writes`,+ * `brain_write_destinations` and the `plan_revert` selector. The empty+ * (or whitespace-only) string is the legacy un-sharded pair and IS a+ * filter value, so it is read through the shared+ * {@link isLegacyPairDevice} before `coerceStr`, which treats emptiness+ * as absence - both schemas promise `device: ""` selects the un-sharded+ * log, and a coercion-first reading made that unreachable.+ */+export function deviceArg(args: Record<string, unknown>): string | null {+ if (isLegacyPairDevice(args["device"])) return "";+ return coerceStr(args, "device", false);+}++export async function toolBrainWrites(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const action = coerceStr(args, "action", false) ?? BRAIN_WRITES_ACTION.list;+ if (action === BRAIN_WRITES_ACTION.planRevert) {+ return planRevert(ctx, args);+ }+ if (action !== BRAIN_WRITES_ACTION.list) {+ throw unknownOperationError(+ `brain_writes: 'action' must be one of ${BRAIN_WRITES_ACTIONS.join(", ")}`,+ );+ }+ const rawOp = coerceStr(args, "op", false);+ if (rawOp !== null && !isNoteWriteOp(rawOp)) {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_writes: 'op' must be one of ${Object.values(NOTE_WRITE_OP).join(", ")}`,+ );+ }+ const agent = coerceStr(args, "agent", false);+ const device = deviceArg(args);+ const path = coerceStr(args, "path", false);+ const since = coerceStr(args, "since", false);+ const until = coerceStr(args, "until", false);+ const limit = coerceInt(args, "limit", BRAIN_WRITES_DEFAULT_LIMIT, 1, BRAIN_WRITES_MAX_LIMIT);+ const offset = cursorOffsetArg("brain_writes", args);++ // The log never opens the notes it names, so the reach rule is asked+ // per target here: at remote reach a write to a page reserved against+ // remote reads (or one whose file is gone - an unreadable claim fails+ // closed) is dropped before counting, so neither its path nor the+ // total betrays it. At local reach the view is the shared no-op.+ const view = reachView(ctx.vault, contextReach(ctx));+ const result = ledgerRead("brain_writes", () =>+ listNoteWrites(ctx.vault, {+ ...(agent !== null ? { agent } : {}),+ ...(device !== null ? { device } : {}),+ ...(path !== null ? { path } : {}),+ ...(since !== null ? { since } : {}),+ ...(until !== null ? { until } : {}),+ ...(rawOp !== null ? { op: rawOp } : {}),+ withholdsPrivate: view.withholdsPrivate === true,+ }),+ );+ const writes = view.filtersNothing+ ? result.writes+ : result.writes.filter((w) => view.visible(w.target));+ // `total_matched` beside `returned` so a truncated answer is legible as+ // one: a list capped at the limit and a list that IS the whole history+ // are otherwise the same shape. `next_cursor` continues the walk.+ const page = pageSlice(writes, offset, limit);+ return {+ action: BRAIN_WRITES_ACTION.list,+ total_matched: page.total,+ returned: page.items.length,+ writes: page.items.map((w) => ({ ...w })),+ warnings: result.warnings.map((w) => ({+ path: w.path,+ line: w.lineNumber,+ message: w.message,+ })),+ next_cursor: page.next_cursor,+ };+}++/**+ * The read-only half of the per-agent revert: what undoing the selected+ * writes WOULD do, sealed by the digest `o2b brain writes revert --apply`+ * takes.+ *+ * Every refusal the planner raises for the whole call - the unbounded+ * selector, today the only one - comes back as `INVALID_PARAMS` carrying+ * the CODE, so an agent narrows on a token rather than on a sentence.+ * Nothing here writes; the digest is the only thing that crosses to the+ * operator's terminal.+ */+export function planRevert(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Record<string, unknown> {+ // The device rides the same empty-aware selector as the list action:+ // `device: ""` names the legacy un-sharded pair, and a selector that+ // dropped the empty string beside a path would revert that path's+ // writes from EVERY device while looking device-scoped.+ const device = deviceArg(args);+ const selector: NoteRevertSelector = {+ ...selectorArg(args, "agent"),+ ...(device !== null ? { device } : {}),+ ...selectorArg(args, "path"),+ ...selectorArg(args, "since"),+ ...selectorArg(args, "until"),+ };+ const view = reachView(ctx.vault, contextReach(ctx));+ let plan;+ try {+ plan = planNoteRevert(ctx.vault, selector, {+ withholdsPrivate: view.withholdsPrivate === true,+ });+ } catch (err) {+ if (err instanceof NoteRevertError) {+ throw new MCPError(INVALID_PARAMS, `brain_writes: ${err.code}: ${err.message}`);+ }+ // The planner reads the same window bounds as the list surface, so a+ // malformed since / until is the same client-resolvable mistake here.+ if (err instanceof LogWindowBoundError) {+ throw new MCPError(INVALID_PARAMS, `brain_writes: ${err.message}`);+ }+ throw err;+ }+ // Same reach rule as `list`. When an entry is withheld, the digest+ // seals only the entries shown: the full plan's digest covers each+ // hidden entry's current-bytes hash, so it would differ between a+ // withheld page, a deleted one and a path never written, and change+ // whenever the withheld page did. The CLI apply re-plans in full and+ // refuses this digest with `digest_mismatch`, the safe outcome for a+ // plan the caller could not fully see.+ const entries = view.filtersNothing+ ? plan.entries+ : plan.entries.filter((entry) => view.visible(entry.target));+ const digest =+ entries.length === plan.entries.length ? plan.digest : noteRevertDigest(plan.selector, entries);+ return {+ action: BRAIN_WRITES_ACTION.planRevert,+ selector: { ...plan.selector },+ entries: entries.map((entry) => ({ ...entry })),+ digest,+ planned_at: plan.planned_at,+ next_command: `o2b brain writes revert --apply ${digest}`,+ warnings: plan.warnings.map((w) => ({+ path: w.path,+ line: w.lineNumber,+ message: w.message,+ })),+ };+}++/**+ * Default and maximum rows one `brain_write_destinations` call returns.+ */+export const BRAIN_WRITE_DESTINATIONS_DEFAULT_LIMIT = 50;+export const BRAIN_WRITE_DESTINATIONS_MAX_LIMIT = 500;++/**+ * The destination-keyed aggregate over the write ledger (actionable-now+ * batch, A4): one row per vault-relative target the recorded write+ * events name, across BOTH the note-write and the write-session kinds,+ * with the kinds coverage field stating honestly which kinds spoke. The+ * log never opens the pages it names, so the reach rule is asked per row+ * here exactly as `brain_writes` asks it: at remote reach a destination+ * whose page is reserved against remote reads - or unreadable, which+ * fails closed - is dropped from the rows AND from `total_matched`, so a+ * withheld page moves no count. Read-only.+ */+export async function toolBrainWriteDestinations(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const agent = coerceStr(args, "agent", false);+ const device = deviceArg(args);+ const path = coerceStr(args, "path", false);+ const since = coerceStr(args, "since", false);+ const until = coerceStr(args, "until", false);+ const limit = coerceInt(+ args,+ "limit",+ BRAIN_WRITE_DESTINATIONS_DEFAULT_LIMIT,+ 1,+ BRAIN_WRITE_DESTINATIONS_MAX_LIMIT,+ );+ const offset = cursorOffsetArg("brain_write_destinations", args);++ const view = reachView(ctx.vault, contextReach(ctx));+ const result = ledgerRead("brain_write_destinations", () =>+ listWriteDestinations(ctx.vault, {+ ...(agent !== null ? { agent } : {}),+ ...(device !== null ? { device } : {}),+ ...(path !== null ? { path } : {}),+ ...(since !== null ? { since } : {}),+ ...(until !== null ? { until } : {}),+ withholdsPrivate: view.withholdsPrivate === true,+ }),+ );+ const rows = view.filtersNothing+ ? result.destinations+ : result.destinations.filter((d) => view.visible(d.target));+ // `total_matched` beside `returned`, and `next_cursor` continuing the+ // walk, so a truncated answer is legible as one.+ const page = pageSlice(rows, offset, limit);+ return {+ total_matched: page.total,+ returned: page.items.length,+ destinations: page.items.map((d) => ({+ ...d,+ kinds: [...d.kinds],+ agents: [...d.agents],+ devices: [...d.devices],+ })),+ coverage_note: result.coverage_note,+ // The window the walk actually covered, both ends completed to+ // timestamps: the default lower bound is computed, not sent, so a+ // caller reading only its own arguments would misread the coverage.+ window: { since: result.window.since, until: result.window.until },+ warnings: result.warnings.map((w) => ({+ path: w.path,+ line: w.lineNumber,+ message: w.message,+ })),+ next_cursor: page.next_cursor,+ };+}++/** One selector field, present only when the caller supplied it. The+ * device is NOT read here: it goes through {@link deviceArg}, whose+ * empty string is the legacy un-sharded pair, not absence. */+export function selectorArg(+ args: Record<string, unknown>,+ key: "agent" | "path" | "since" | "until",+): Partial<Record<typeof key, string>> {+ const value = coerceStr(args, key, false);+ return value === null ? {} : { [key]: value };+}diff --git a/src/mcp/brain/recall-bench-tools.ts b/src/mcp/brain/recall-bench-tools.tsnew file mode 100644index 00000000..06b30da3--- /dev/null+++ b/src/mcp/brain/recall-bench-tools.ts@@ -0,0 +1,388 @@+/**+ * The recall-quality tools (task 3.19): `brain_benchmark`, `brain_tune`+ * and `brain_recall_telemetry`, answered through the telemetry filters+ * and coercers the economics tools share. Split from `recall-tools.ts`;+ * registration happens through that module's registry, which preserves+ * the public RECALL_TOOLS surface.+ */++import { resolveSearchConfig } from "../../core/search/index.ts";+import { appendMetric } from "../../core/brain/metrics.ts";+import { parseRecallBenchmarkDataset, runRecallBenchmark } from "../../core/search/benchmark.ts";+import { tuneRecall } from "../../core/search/tuning.ts";+import { loadTunedParameters, resetTuning } from "../../core/search/tuning-store.ts";+import {+ listGateTelemetry,+ summarizeGateTelemetryRecords,+} from "../../core/brain/gate-telemetry.ts";+import { computeMemoryCostMeter } from "../../core/brain/memory-cost-meter.ts";+import { observedReuseRates } from "../../core/brain/observed-use.ts";+import { computeDeadWeight, DEAD_WEIGHT_MAX_LIMIT } from "../../core/brain/dead-weight.ts";+import { everyArtifactRefView } from "../../core/brain/artifact-ref-view.ts";+import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";+import {+ listRecallTelemetry,+ summarizeRecallTelemetryRecords,+} from "../../core/brain/recall-telemetry.ts";+import { isoSecond } from "../../core/brain/time.ts";+import { TRANSPORT_REACH } from "../../core/graph/transport-reach.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import { contextReach } from "../tool-contract.ts";+import { requestRefView } from "./reach-events.ts";+import type { ServerContext } from "../tool-contract.ts";+import { vaultPathField } from "../vault-path-field.ts";+import { optionalStringArg } from "./shared.ts";+import { unknownOperationError } from "../coerce.ts";+import { coerceNonNegativeNumber, recallTelemetryFilter } from "./recall-coerce-tools.ts";+import type { ContinuityRecord } from "../../core/brain/continuity/types.ts";++/**+ * The telemetry records this caller may see. A LOCAL caller keeps every+ * record whose artifact refs name something it may see - the ownership+ * gate applies at every reach - and with the gate off it still filters+ * nothing, by construction. Below local reach the records drop BEFORE any+ * total or summary count is taken (the analytics rule - a count that+ * still included a withheld record leaks its number):+ * - a `private` record is dropped whole (a REMOTE-only withholding: a+ * local caller owns the partition it sits in);+ * - a record whose artifact refs (its `sourceRefs`, or the+ * `top_artifacts` in its payload) name anything the composed+ * request's reach and ownership view withholds is dropped whole -+ * the same view the `observed_reuse` and `dead_weight` operations+ * apply to the same keys, and the same drop-whole rule the cluster+ * batches follow for a subject that cannot be resolved. A ref names+ * something through its `path` when the emitter had one and through+ * its bare `id` otherwise, so both spellings are asked.+ * Gate telemetry carries no artifact refs, so only the private half+ * applies to it below local reach.+ */+function callerVisibleTelemetry(+ ctx: ServerContext,+ records: ReadonlyArray<ContinuityRecord>,+): ReadonlyArray<ContinuityRecord> {+ const local = contextReach(ctx) === TRANSPORT_REACH.local;+ const refs = everyArtifactRefView(+ requestRefView(ctx),+ gatedOwnerScopeView(ctx.vault, ctx.agentName),+ );+ if (local && refs.filtersNothing) return records;+ const hiddenRef = (ref: unknown): boolean =>+ typeof ref === "string" && ref !== "" && !refs.filtersNothing && !refs.visible(ref);+ return records.filter((record) => {+ if (!local && record.private) return false;+ if (refs.filtersNothing) return true;+ // An emitter that had no path for an artifact still carries its id+ // (`pref-…` of a withheld preference, say), so both spellings are+ // asked of the view - the same keys the `observed_reuse` branch+ // filters, which arrive as bare ids just as often.+ if (+ record.sourceRefs.some((ref) => hiddenRef(ref.path) || hiddenRef(ref.id)) ||+ (Array.isArray(record.payload["top_artifacts"]) &&+ (+ record.payload["top_artifacts"] as ReadonlyArray<{ id?: unknown; path?: unknown } | null>+ ).some((artifact) => hiddenRef(artifact?.path) || hiddenRef(artifact?.id)))+ )+ return false;+ return true;+ });+}++/**+ * The caller's `limit` page, applied AFTER the visibility filter: the+ * `list` family asks the underlying readers for the full (filtered by+ * kind/time/host) set, drops the withheld records, and only then cuts+ * the page. A limit inside the reader would let a withheld newest+ * record consume the page and hide an older visible one.+ */+function pageRecords(+ records: ReadonlyArray<ContinuityRecord>,+ limit: number | undefined,+): ReadonlyArray<ContinuityRecord> {+ return limit === undefined ? records : records.slice(0, Math.max(0, Math.floor(limit)));+}++/** Recall-quality benchmark over an inline dataset. */+export async function toolBrainBenchmark(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const op = args["operation"];+ if (op !== "run") {+ throw unknownOperationError("brain_benchmark: operation must be run");+ }+ const k = args["k"];+ if (k !== undefined && (!Number.isInteger(k) || (k as number) < 1)) {+ throw new MCPError(INVALID_PARAMS, "brain_benchmark run: k must be a positive integer");+ }+ let dataset;+ try {+ dataset = parseRecallBenchmarkDataset(args["dataset"]);+ } catch (exc) {+ throw new MCPError(INVALID_PARAMS, `brain_benchmark run: ${(exc as Error).message}`);+ }+ const searchConfig = resolveSearchConfig({+ vault: ctx.vault,+ configPath: ctx.configPath ?? undefined,+ });+ const now = new Date();+ const report = await runRecallBenchmark(searchConfig, dataset, {+ ...(k !== undefined ? { k: k as number } : {}),+ expand: args["expand"] === true,+ // The dataset is the caller's, and so is the reach it is scored at:+ // `hit` / `rank` / `expectedFound` for caller-named paths is an+ // existence oracle over any corpus the caller did not earn.+ transportReach: contextReach(ctx),+ });+ try {+ appendMetric(ctx.vault, {+ surface: "recall_benchmark",+ runAt: isoSecond(now),+ payload: {+ total: report.total,+ k: report.k,+ expand: report.expand,+ hit_at_k: report.hitAtK,+ mrr: report.mrr,+ misses: report.perQuery.filter((q) => !q.hit).map((q) => q.id),+ },+ });+ } catch {+ // Metrics are observability, not correctness.+ }+ return {+ total: report.total,+ k: report.k,+ expand: report.expand,+ hit_at_k: report.hitAtK,+ mrr: report.mrr,+ // A degraded run measured a smaller system than the configured one.+ ...(report.degraded.length > 0 ? { degraded: report.degraded } : {}),+ per_query: report.perQuery,+ };+}++// ----- brain_tune (t_ae973491) -------------------------------------------------++/** Opt-in self-tuning recall: run the grid, inspect, or reset. */+export async function toolBrainTune(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const op = args["operation"];+ if (op !== "run" && op !== "status" && op !== "reset") {+ throw unknownOperationError("brain_tune: operation must be run|status|reset");+ }+ const searchConfig = resolveSearchConfig({+ vault: ctx.vault,+ configPath: ctx.configPath ?? undefined,+ });+ if (op === "status") {+ return {+ enabled: searchConfig.recall.selfTuningEnabled,+ tuned: loadTunedParameters(ctx.vault),+ };+ }+ if (op === "reset") {+ return { removed: resetTuning(ctx.vault) };+ }+ const k = args["k"];+ if (k !== undefined && (!Number.isInteger(k) || (k as number) < 1)) {+ throw new MCPError(INVALID_PARAMS, "brain_tune run: k must be a positive integer");+ }+ let dataset;+ try {+ dataset = parseRecallBenchmarkDataset(args["dataset"]);+ } catch (exc) {+ throw new MCPError(INVALID_PARAMS, `brain_tune run: ${(exc as Error).message}`);+ }+ const now = new Date();+ const report = await tuneRecall(searchConfig, dataset, {+ ...(k !== undefined ? { k: k as number } : {}),+ now,+ // Same reasoning as `brain_benchmark`: the grid is scored with the+ // benchmark, so every cell inherits whatever reach is passed here.+ transportReach: contextReach(ctx),+ });+ try {+ appendMetric(ctx.vault, {+ surface: "self_tuning",+ runAt: isoSecond(now),+ payload: {+ chosen: report.chosen,+ evaluated: report.evaluated.length,+ best_mrr: Math.max(...report.evaluated.map((e) => e.mrr)),+ dataset_hash: report.datasetHash,+ },+ });+ } catch {+ // Metrics are observability, not correctness.+ }+ return {+ chosen: report.chosen,+ evaluated: report.evaluated.map((e) => ({+ params: e.params,+ mrr: e.mrr,+ hit_at_k: e.hitAtK,+ ...(e.degraded.length > 0 ? { degraded: e.degraded } : {}),+ })),+ dataset_hash: report.datasetHash,+ ...(report.degraded.length > 0 ? { degraded: report.degraded } : {}),+ };+}++// ----- brain_dead_ends (t_be62c62d) -----------------------------------------++export async function toolBrainRecallTelemetry(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const operation = optionalStringArg("brain_recall_telemetry", args, "operation");+ const filter = recallTelemetryFilter(args);++ if (operation === "list") {+ const { limit, ...visibleFilter } = filter;+ const records = pageRecords(+ callerVisibleTelemetry(ctx, listRecallTelemetry(ctx.vault, visibleFilter)),+ limit,+ );+ return { vault_path: vaultPathField(ctx), total: records.length, records };+ }+ if (operation === "summary") {+ // The summary counts the VISIBLE records: the filter drops withheld+ // ones before the fold, so no count answers for a record the caller+ // may not see.+ // The limit, like the list's, is cut after the visibility filter.+ const { limit, ...visibleFilter } = filter;+ const summary = summarizeRecallTelemetryRecords(+ pageRecords(+ callerVisibleTelemetry(ctx, listRecallTelemetry(ctx.vault, visibleFilter)),+ limit,+ ),+ );+ return { ...summary };+ }+ // Gate-decision telemetry (Workspace Insight Suite, t_65036e02):+ // records emitted by brain_recall_gate when recall_gate_telemetry is on.+ if (operation === "gate_list") {+ const { limit, ...visibleFilter } = filter;+ const records = pageRecords(+ callerVisibleTelemetry(+ ctx,+ listGateTelemetry(ctx.vault, {+ ...(visibleFilter.host !== undefined ? { host: visibleFilter.host } : {}),+ ...(visibleFilter.since !== undefined ? { since: visibleFilter.since } : {}),+ ...(visibleFilter.until !== undefined ? { until: visibleFilter.until } : {}),+ }),+ ),+ limit,+ );+ return { vault_path: vaultPathField(ctx), total: records.length, records };+ }+ if (operation === "gate_summary") {+ const summary = summarizeGateTelemetryRecords(+ callerVisibleTelemetry(+ ctx,+ listGateTelemetry(ctx.vault, {+ ...(filter.host !== undefined ? { host: filter.host } : {}),+ ...(filter.since !== undefined ? { since: filter.since } : {}),+ ...(filter.until !== undefined ? { until: filter.until } : {}),+ }),+ ),+ );+ return { ...summary };+ }+ // Observed-use blend (t_65588d8b): the folded per-artifact+ // USED/IGNORED/CONTRADICTED reuse signal that recall ranking prefers over+ // predicted importance. Exposed here so the blend is inspectable.+ if (operation === "observed_reuse") {+ // The keys are artifact references - a vault-relative path or a bare+ // Brain id - so the request's reach/ownership view filters them, the+ // same view the dead_weight branch applies. A key the caller cannot+ // see is dropped BEFORE `total`, per the views' identical-to-absent+ // rule: a total that still counted it would leak its number.+ const refs = everyArtifactRefView(+ requestRefView(ctx),+ gatedOwnerScopeView(ctx.vault, ctx.agentName),+ );+ const rates = [...observedReuseRates(ctx.vault).entries()];+ const artifacts = (refs.filtersNothing ? rates : rates.filter(([key]) => refs.visible(key)))+ .map(([key, r]) => ({ key, ...r }))+ .toSorted((a, b) => (a.score !== b.score ? b.score - a.score : a.key < b.key ? -1 : 1));+ return { vault_path: vaultPathField(ctx), total: artifacts.length, artifacts };+ }+ // Write-vs-read cost meter (memory cost meter): folds write volume+ // against the read telemetry above. Period-based; mode/status/host/limit+ // do not apply to the write side, so reject them to mirror the CLI's+ // fail-closed behavior (recall-telemetry.ts costMeter) rather than+ // silently ignoring and looking like a valid filtered result.+ if (operation === "cost") {+ for (const name of ["mode", "status", "host", "limit"] as const) {+ if (args[name] !== undefined) {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_recall_telemetry: ${name} is not supported for the cost meter`,+ );+ }+ }+ const writeCost = coerceNonNegativeNumber("write_cost", args["write_cost"]);+ const readCost = coerceNonNegativeNumber("read_cost", args["read_cost"]);+ const writeHeavyRatio = coerceNonNegativeNumber("write_heavy_ratio", args["write_heavy_ratio"]);+ const meter = computeMemoryCostMeter(ctx.vault, {+ withholdsPrivate: contextReach(ctx) !== TRANSPORT_REACH.local,+ ...(filter.since !== undefined ? { since: filter.since } : {}),+ ...(filter.until !== undefined ? { until: filter.until } : {}),+ ...(writeCost !== undefined || readCost !== undefined+ ? {+ weights: {+ ...(writeCost !== undefined ? { write: writeCost } : {}),+ ...(readCost !== undefined ? { read: readCost } : {}),+ },+ }+ : {}),+ ...(writeHeavyRatio !== undefined ? { writeHeavyRatio } : {}),+ });+ return { vault_path: vaultPathField(ctx), ...meter };+ }+ // Dead weight (recall-quality, t_1ee67e5b): the complement fold over+ // the vault's live in-scope pages and every path recorded recall ever+ // surfaced (telemetry top artifacts + observed-use source refs). The+ // seventh operation on this tool - an operation, never a new tool, so+ // the tool-count pin does not move.+ if (operation === "dead_weight") {+ // Record-only filters (mode/status/channel/host) have no meaning for+ // the complement; reject them rather than silently ignore, mirroring+ // the cost op and the CLI's fail-closed verb. `limit` is the one+ // exception (PR #248 review L10): it bounds the dead preview, which+ // is otherwise pinned at the fold's 50-row default, clamped to the+ // shared maximum so the full list is reachable in bounded pages.+ for (const name of ["mode", "status", "channel", "host"] as const) {+ if (args[name] !== undefined) {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_recall_telemetry: ${name} is not supported for dead_weight`,+ );+ }+ }+ // Hidden rows are dropped BEFORE total: the request's reach/ownership+ // boundary is applied to the FULL SET, so `pages_total`, `dead` and+ // every count answer only what this caller may see - a total that+ // still included the hidden rows would leak their number (the+ // analytics rule). A local caller filters nothing, by construction.+ const refs = everyArtifactRefView(+ requestRefView(ctx),+ gatedOwnerScopeView(ctx.vault, ctx.agentName),+ );+ const report = computeDeadWeight(ctx.vault, {+ ...(filter.since !== undefined ? { since: filter.since } : {}),+ ...(filter.until !== undefined ? { until: filter.until } : {}),+ ...(filter.limit !== undefined+ ? { deadLimit: Math.min(filter.limit, DEAD_WEIGHT_MAX_LIMIT) }+ : {}),+ ...(refs.filtersNothing ? {} : { includePath: (rel: string) => refs.visible(rel) }),+ });+ return { vault_path: vaultPathField(ctx), ...report };+ }+ throw unknownOperationError(+ "brain_recall_telemetry: operation must be list, summary, gate_list, gate_summary, observed_reuse, cost, or dead_weight",+ );+}diff --git a/src/mcp/brain/recall-coerce-tools.ts b/src/mcp/brain/recall-coerce-tools.tsnew file mode 100644index 00000000..996b3b60--- /dev/null+++ b/src/mcp/brain/recall-coerce-tools.ts@@ -0,0 +1,404 @@+/**+ * The telemetry and economics tools of the recall family (task 3.19):+ * the argument coercers they share, `brain_route_metrics`,+ * `brain_retrieval_plan` and `brain_token_impact`. Split from+ * `recall-tools.ts`; registration happens through that module's+ * registry, which preserves the public RECALL_TOOLS surface.+ */++import {+ isRecallChannel,+ isRecallTelemetryMode,+ isRecallTelemetryStatus,+ RECALL_CHANNELS,+ RECALL_TELEMETRY_MODES,+ RECALL_TELEMETRY_STATUSES,+ type RecallChannel,+ type RecallTelemetryFilter,+ type RecallTelemetryMode,+ type RecallTelemetryStatus,+} from "../../core/brain/recall-telemetry.ts";+import {+ isMcpRouteStatus,+ listMcpRouteLatency,+ summarizeMcpRouteLatency,+ type McpRouteLatencyFilter,+ type McpRouteStatus,+} from "../../core/brain/mcp-route-metrics.ts";+import {+ emitTokenImpact,+ normalizeTokenCountMethod,+ TOKEN_COUNT_METHOD,+ TOKEN_COUNT_METHODS,+ isTokenImpactOutcome,+ listTokenImpact,+ recordTokenImpactOutcome,+ summarizeTokenImpact,+ type TokenCountMethod,+ type TokenImpactFilter,+ type TokenImpactOutcome,+} from "../../core/brain/token-impact.ts";+import { resolveTokenImpactLedgerEnabled } from "../../core/config.ts";+import { buildRetrievalPlan, serializeRetrievalPlan } from "../../core/brain/retrieval-plan.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import type { ServerContext } from "../tool-contract.ts";+import { vaultPathField } from "../vault-path-field.ts";+import { coercePositiveInteger, optionalStringArg, requiredStringArg } from "./shared.ts";+import { coerceAgentScope, unknownOperationError } from "../coerce.ts";++export function coerceNonNegativeNumber(name: string, raw: unknown): number | undefined {+ if (raw === undefined || raw === null) return undefined;+ if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 0) {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_recall_telemetry: ${name} must be a non-negative number`,+ );+ }+ return raw;+}++export function recallTelemetryFilter(args: Record<string, unknown>): RecallTelemetryFilter {+ const mode = coerceRecallTelemetryMode(args["mode"]);+ const status = coerceRecallTelemetryStatus(args["status"]);+ const channel = coerceRecallChannel(args["channel"]);+ const host = optionalStringArg("brain_recall_telemetry", args, "host");+ const since = optionalStringArg("brain_recall_telemetry", args, "since");+ const until = optionalStringArg("brain_recall_telemetry", args, "until");+ const limit = coercePositiveInteger("brain_recall_telemetry", "limit", args["limit"]);+ return {+ ...(mode !== undefined ? { mode } : {}),+ ...(status !== undefined ? { status } : {}),+ ...(channel !== undefined ? { channel } : {}),+ ...(host !== undefined ? { host } : {}),+ ...(since !== undefined ? { since } : {}),+ ...(until !== undefined ? { until } : {}),+ ...(limit !== undefined ? { limit } : {}),+ };+}++export function coerceRecallTelemetryMode(raw: unknown): RecallTelemetryMode | undefined {+ if (raw === undefined || raw === null) return undefined;+ const trimmed = typeof raw === "string" ? raw.trim() : raw;+ // Rendered from the frozen member list. The prose copy this replaces+ // omitted `query`, and so did the schema enum below it, so a mode the+ // server records was refused at its own boundary.+ if (!isRecallTelemetryMode(trimmed)) {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_recall_telemetry: mode must be one of ${RECALL_TELEMETRY_MODES.join(", ")}`,+ );+ }+ return trimmed;+}++export function coerceRecallTelemetryStatus(raw: unknown): RecallTelemetryStatus | undefined {+ if (raw === undefined || raw === null) return undefined;+ const trimmed = typeof raw === "string" ? raw.trim() : raw;+ if (!isRecallTelemetryStatus(trimmed)) {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_recall_telemetry: status must be one of ${RECALL_TELEMETRY_STATUSES.join(", ")}`,+ );+ }+ return trimmed;+}++export function coerceRecallChannel(raw: unknown): RecallChannel | undefined {+ if (raw === undefined || raw === null) return undefined;+ const trimmed = typeof raw === "string" ? raw.trim() : raw;+ if (!isRecallChannel(trimmed)) {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_recall_telemetry: channel must be one of ${RECALL_CHANNELS.join(", ")}`,+ );+ }+ return trimmed;+}++// ----- brain_route_metrics (context-pack-economics-observability) -----------++export async function toolBrainRouteMetrics(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const operation = optionalStringArg("brain_route_metrics", args, "operation");+ const filter = routeMetricsFilter(args);++ if (operation === "list") {+ const records = listMcpRouteLatency(ctx.vault, filter);+ return { vault_path: vaultPathField(ctx), total: records.length, records };+ }+ if (operation === "summary") {+ const summary = summarizeMcpRouteLatency(ctx.vault, filter);+ return { vault_path: vaultPathField(ctx), ...summary };+ }+ throw unknownOperationError("brain_route_metrics: operation must be list or summary");+}++// ----- brain_retrieval_plan (shadow-only retrieval advisor, t_3ffb021c) -----++export async function toolBrainRetrievalPlan(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const question = requiredStringArg("brain_retrieval_plan", args, "question");+ const tokenBudget = coercePositiveInteger(+ "brain_retrieval_plan",+ "token_budget",+ args["token_budget"],+ );+ const agentScope = coerceAgentScope(ctx, args, true);+ const plan = buildRetrievalPlan(ctx.vault, question, {+ ...(tokenBudget !== undefined ? { tokenBudget } : {}),+ ...(agentScope !== undefined ? { agentScope } : {}),+ });+ return { vault_path: vaultPathField(ctx), ...serializeRetrievalPlan(plan) };+}++export function routeMetricsFilter(args: Record<string, unknown>): McpRouteLatencyFilter {+ const tool = optionalStringArg("brain_route_metrics", args, "tool");+ const status = coerceRouteMetricsStatus(args["status"]);+ const since = optionalStringArg("brain_route_metrics", args, "since");+ const until = optionalStringArg("brain_route_metrics", args, "until");+ const limit = coercePositiveInteger("brain_route_metrics", "limit", args["limit"]);+ return {+ ...(tool !== undefined ? { tool } : {}),+ ...(status !== undefined ? { status } : {}),+ ...(since !== undefined ? { since } : {}),+ ...(until !== undefined ? { until } : {}),+ ...(limit !== undefined ? { limit } : {}),+ };+}++export function coerceRouteMetricsStatus(raw: unknown): McpRouteStatus | undefined {+ if (raw === undefined || raw === null) return undefined;+ const trimmed = typeof raw === "string" ? raw.trim() : raw;+ if (!isMcpRouteStatus(trimmed)) {+ throw new MCPError(INVALID_PARAMS, "brain_route_metrics: status must be ok or error");+ }+ return trimmed;+}++// ----- brain_token_impact (context-pack-economics-observability) ------------++/**+ * Durable token-impact + context-pack-quality ledger. `record`/`outcome`+ * write opt-in samples (gated on `token_impact_ledger_enabled`, payload-safe:+ * counts + opaque pack id only); `list`/`summary` read the ledger regardless+ * of the gate so historical aggregates stay inspectable.+ */+export async function toolBrainTokenImpact(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const operation = optionalStringArg("brain_token_impact", args, "operation");++ if (operation === "record") {+ const baselineTokens = coerceNonNegativeInteger(+ "brain_token_impact",+ "baseline_tokens",+ args["baseline_tokens"],+ );+ const packedTokens = coerceNonNegativeInteger(+ "brain_token_impact",+ "packed_tokens",+ args["packed_tokens"],+ );+ if (baselineTokens === undefined || packedTokens === undefined) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_token_impact: record requires baseline_tokens and packed_tokens (non-negative integers)",+ );+ }+ const method = coerceTokenCountMethod(args["method"]) ?? TOKEN_COUNT_METHOD.heuristic;+ const modeledAvoided = coerceNonNegativeTokenValue(+ "brain_token_impact",+ "modeled_avoided_inferences",+ args["modeled_avoided_inferences"],+ );+ const modeledPerInference = coerceNonNegativeTokenValue(+ "brain_token_impact",+ "modeled_tokens_per_inference",+ args["modeled_tokens_per_inference"],+ );+ const enabled = resolveTokenImpactLedgerEnabled(ctx.configPath ?? undefined);+ const record = emitTokenImpact(+ ctx.vault,+ {+ baselineTokens,+ packedTokens,+ method,+ ...tokenImpactCorrelation(args),+ ...(modeledAvoided !== undefined ? { modeledAvoidedInferences: modeledAvoided } : {}),+ ...(modeledPerInference !== undefined+ ? { modeledTokensPerInference: modeledPerInference }+ : {}),+ },+ enabled || undefined,+ );+ if (record === null) {+ return { vault_path: vaultPathField(ctx), recorded: false, enabled };+ }+ return {+ vault_path: vaultPathField(ctx),+ recorded: true,+ enabled,+ id: record.id,+ method,+ baseline_tokens: baselineTokens,+ packed_tokens: packedTokens,+ delta_tokens: baselineTokens - packedTokens,+ };+ }++ if (operation === "outcome") {+ const outcome = coerceTokenImpactOutcome(args["outcome"]);+ if (outcome === undefined) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_token_impact: outcome requires outcome (first_pass | repair | retry)",+ );+ }+ const tokensPerInference = coerceNonNegativeTokenValue(+ "brain_token_impact",+ "tokens_per_inference",+ args["tokens_per_inference"],+ );+ const enabled = resolveTokenImpactLedgerEnabled(ctx.configPath ?? undefined);+ const record = recordTokenImpactOutcome(+ ctx.vault,+ {+ outcome,+ ...tokenImpactCorrelation(args),+ ...(tokensPerInference !== undefined ? { tokensPerInference } : {}),+ },+ enabled || undefined,+ );+ if (record === null) {+ return { vault_path: vaultPathField(ctx), recorded: false, enabled };+ }+ return { vault_path: vaultPathField(ctx), recorded: true, enabled, id: record.id, outcome };+ }++ const filter = tokenImpactFilter(args);+ if (operation === "list") {+ const records = listTokenImpact(ctx.vault, filter);+ return { vault_path: vaultPathField(ctx), total: records.length, records };+ }+ if (operation === "summary") {+ return { vault_path: vaultPathField(ctx), ...summarizeTokenImpact(ctx.vault, filter) };+ }+ throw unknownOperationError(+ "brain_token_impact: operation must be record, outcome, list, or summary",+ );+}++export function tokenImpactCorrelation(args: Record<string, unknown>): {+ host?: string;+ sessionId?: string;+ turnId?: string;+ packId?: string;+} {+ const host = optionalStringArg("brain_token_impact", args, "host");+ const sessionId = optionalStringArg("brain_token_impact", args, "session_id");+ const turnId = optionalStringArg("brain_token_impact", args, "turn_id");+ const packId = optionalStringArg("brain_token_impact", args, "pack_id");+ return {+ ...(host !== undefined ? { host } : {}),+ ...(sessionId !== undefined ? { sessionId } : {}),+ ...(turnId !== undefined ? { turnId } : {}),+ ...(packId !== undefined ? { packId } : {}),+ };+}++export function tokenImpactFilter(args: Record<string, unknown>): TokenImpactFilter {+ const host = optionalStringArg("brain_token_impact", args, "host");+ const packId = optionalStringArg("brain_token_impact", args, "pack_id");+ const method = coerceTokenCountMethod(args["method"]);+ const since = optionalStringArg("brain_token_impact", args, "since");+ const until = optionalStringArg("brain_token_impact", args, "until");+ const limit = coercePositiveInteger("brain_token_impact", "limit", args["limit"]);+ const maxSamples = coercePositiveInteger(+ "brain_token_impact",+ "max_samples",+ args["max_samples"],+ );+ return {+ ...(host !== undefined ? { host } : {}),+ ...(packId !== undefined ? { packId } : {}),+ ...(method !== undefined ? { method } : {}),+ ...(since !== undefined ? { since } : {}),+ ...(until !== undefined ? { until } : {}),+ ...(limit !== undefined ? { limit } : {}),+ ...(maxSamples !== undefined ? { maxSamples } : {}),+ };+}++export function coerceTokenCountMethod(raw: unknown): TokenCountMethod | undefined {+ if (raw === undefined || raw === null) return undefined;+ const trimmed = typeof raw === "string" ? raw.trim() : raw;+ // Legacy-aware: an adapter still posting the pre-rename `exact` /+ // `fallback` labels is translated rather than rejected, so upgrading the+ // server does not silently stop recording an existing caller's samples.+ const method = normalizeTokenCountMethod(trimmed);+ if (method === null) {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_token_impact: method must be one of ${TOKEN_COUNT_METHODS.join(", ")}`,+ );+ }+ return method;+}++export function coerceTokenImpactOutcome(raw: unknown): TokenImpactOutcome | undefined {+ if (raw === undefined || raw === null) return undefined;+ const trimmed = typeof raw === "string" ? raw.trim() : raw;+ if (!isTokenImpactOutcome(trimmed)) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_token_impact: outcome must be first_pass, repair, or retry",+ );+ }+ return trimmed;+}++export function coerceNonNegativeInteger(+ tool: string,+ field: string,+ raw: unknown,+): number | undefined {+ if (raw === undefined || raw === null) return undefined;+ if (typeof raw === "number") {+ if (!Number.isInteger(raw) || raw < 0) {+ throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a non-negative integer`);+ }+ return raw;+ }+ if (typeof raw === "string") {+ const trimmed = raw.trim();+ if (trimmed === "" || !/^[0-9]+$/.test(trimmed)) {+ throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a non-negative integer`);+ }+ return Number.parseInt(trimmed, 10);+ }+ throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a non-negative integer`);+}++export function coerceNonNegativeTokenValue(+ tool: string,+ field: string,+ raw: unknown,+): number | undefined {+ if (raw === undefined || raw === null) return undefined;+ // Reject empty/whitespace-only strings explicitly: Number("") and+ // Number(" ".trim()) both coerce to 0 and would otherwise be written to the+ // durable ledger as a fabricated zero. Mirrors coerceNonNegativeInteger above.+ if (typeof raw === "string" && raw.trim() === "") {+ throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a non-negative number`);+ }+ const value = typeof raw === "string" ? Number(raw.trim()) : raw;+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {+ throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a non-negative number`);+ }+ return value;+}diff --git a/src/mcp/brain/recall-outcome-tools.ts b/src/mcp/brain/recall-outcome-tools.tsnew file mode 100644index 00000000..8d93a40a--- /dev/null+++ b/src/mcp/brain/recall-outcome-tools.ts@@ -0,0 +1,268 @@+/**+ * The context-pack economics tools (task 3.19): `brain_context_pack_outcome`+ * and `brain_knowledge_gaps`, with the correlation, evidence-claim and+ * filter helpers their answers render. Split from `recall-tools.ts`;+ * registration happens through that module's registry, which preserves+ * the public RECALL_TOOLS surface.+ */++import {+ listContextPackOutcomes,+ postContextPackOutcome,+ summarizeContextPackOutcomes,+ type ContextPackOutcomeFilter,+} from "../../core/brain/context-pack-outcome.ts";+import {+ CONTEXT_PACK_EVIDENCE_FIELD,+ type ContextPackEvidenceClaim,+} from "../../core/brain/context-pack-evidence.ts";+import { resolveContextPackOutcomeEnabled } from "../../core/config.ts";+import { aggregateQueryDemand, serializeQueryDemandReport } from "../../core/brain/query-demand.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import type { ServerContext } from "../tool-contract.ts";+import { vaultPathField } from "../vault-path-field.ts";+import { coercePositiveInteger, optionalStringArg, requiredStringArg } from "./shared.ts";+import { unknownOperationError } from "../coerce.ts";+import { coerceNonNegativeInteger, coerceNonNegativeTokenValue } from "./recall-coerce-tools.ts";++// ----- brain_context_pack_outcome (context-pack-economics-observability) ----++/**+ * Agent-operable context-pack outcome loop. `post` writes one compact+ * outcome row (gated on `context_pack_outcome_enabled`, payload-safe:+ * counters + an opaque sample id only), composes the C3 ledger by posting+ * a matching first-pass/repair/retry calibration record, and composes the+ * evidence half by posting the kernel's own reading of the sample beside+ * the agent's claim. All three rows join on the one sample id and carry+ * the same acting agent. `list`/`summary` read the rows regardless of the+ * gate so historical aggregates stay inspectable. The three token signals+ * (exact/modeled/observed) stay strictly separate; a field the caller omits+ * is never invented.+ */+export async function toolBrainContextPackOutcome(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const operation = optionalStringArg("brain_context_pack_outcome", args, "operation");++ if (operation === "post") {+ const sampleId = requiredStringArg("brain_context_pack_outcome", args, "sample_id");+ const firstPassSuccess = coerceBoolean(args["first_pass_success"]);+ if (firstPassSuccess === undefined) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_context_pack_outcome: post requires first_pass_success (boolean)",+ );+ }+ const repairRequired = coerceBoolean(args["repair_required"]);+ const retryCount = coerceNonNegativeInteger(+ "brain_context_pack_outcome",+ "retry_count",+ args["retry_count"],+ );+ const followUpTokens = coerceNonNegativeInteger(+ "brain_context_pack_outcome",+ "follow_up_tokens",+ args["follow_up_tokens"],+ );+ const exact = coerceNonNegativeTokenValue(+ "brain_context_pack_outcome",+ "exact_prompt_token_savings",+ args["exact_prompt_token_savings"],+ );+ const modeled = coerceNonNegativeTokenValue(+ "brain_context_pack_outcome",+ "modeled_inference_avoidance",+ args["modeled_inference_avoidance"],+ );+ const observed = coerceNonNegativeTokenValue(+ "brain_context_pack_outcome",+ "observed_provider_tokens",+ args["observed_provider_tokens"],+ );+ const evidenceClaim = contextPackEvidenceClaim(args["evidence_claim"]);+ const enabled = resolveContextPackOutcomeEnabled(ctx.configPath ?? undefined);+ const post = postContextPackOutcome(+ ctx.vault,+ {+ sampleId,+ firstPassSuccess,+ ...contextPackOutcomeCorrelation(args),+ // Omit-don't-invent: only forward fields the caller actually supplied.+ ...(repairRequired !== undefined ? { repairRequired } : {}),+ ...(retryCount !== undefined ? { retryCount } : {}),+ ...(followUpTokens !== undefined ? { followUpTokens } : {}),+ ...(exact !== undefined ? { exactPromptTokenSavings: exact } : {}),+ ...(modeled !== undefined ? { modeledInferenceAvoidance: modeled } : {}),+ ...(observed !== undefined ? { observedProviderTokens: observed } : {}),+ ...(evidenceClaim !== undefined ? { evidenceClaim } : {}),+ },+ enabled || undefined,+ );+ if (post === null) {+ return { vault_path: vaultPathField(ctx), recorded: false, enabled };+ }+ return {+ vault_path: vaultPathField(ctx),+ recorded: true,+ enabled,+ id: post.outcome.id,+ sample_id: sampleId,+ first_pass_success: firstPassSuccess,+ // The kernel's reading of this sample, surfaced so a contradicted+ // claim is visible to the poster and not only to a later reader.+ // Absent when the evidence half fail-opened - reporting a verdict+ // that was never written would be the fallback this project bans.+ ...(post.evidence !== null ? { evidence: post.evidence.payload } : {}),+ };+ }++ const filter = contextPackOutcomeFilter(args);+ if (operation === "list") {+ const records = listContextPackOutcomes(ctx.vault, filter);+ return { vault_path: vaultPathField(ctx), total: records.length, records };+ }+ if (operation === "summary") {+ return { vault_path: vaultPathField(ctx), ...summarizeContextPackOutcomes(ctx.vault, filter) };+ }+ throw unknownOperationError(+ "brain_context_pack_outcome: operation must be post, list, or summary",+ );+}++/**+ * The correlation keys a `post` records, read from the caller's arguments.+ *+ * `agent_id` is the ACTING agent, and it is an ARGUMENT rather than+ * `ServerContext.agentName` deliberately. That getter resolves the plugin+ * config on every access and RAISES on a config that is present but+ * unreadable - correctly, since the alternative is writing under a guessed+ * identity - so consulting it here would let one broken line in an+ * unrelated file turn a working telemetry post into a tool error. The+ * identity a client asserts is exactly as self-asserted as the one the+ * config holds and costs nothing when the config is broken, so it is the+ * one this row carries. Omitted stays omitted: no identity is invented.+ */+export function contextPackOutcomeCorrelation(args: Record<string, unknown>): {+ host?: string;+ sessionId?: string;+ turnId?: string;+ agentId?: string;+} {+ const host = optionalStringArg("brain_context_pack_outcome", args, "host");+ const sessionId = optionalStringArg("brain_context_pack_outcome", args, "session_id");+ const turnId = optionalStringArg("brain_context_pack_outcome", args, "turn_id");+ const agentId = optionalStringArg("brain_context_pack_outcome", args, "agent_id");+ return {+ ...(host !== undefined ? { host } : {}),+ ...(sessionId !== undefined ? { sessionId } : {}),+ ...(turnId !== undefined ? { turnId } : {}),+ ...(agentId !== undefined ? { agentId } : {}),+ };+}++/**+ * The acting agent's assertion about the sample, coerced at the tool+ * boundary. A malformed member is REFUSED here rather than dropped: a+ * claim silently discarded would land an evidence record reading+ * `unclaimed`, which asserts the agent said nothing when in fact it said+ * something unusable.+ */+export function contextPackEvidenceClaim(raw: unknown): ContextPackEvidenceClaim | undefined {+ if (raw === undefined || raw === null) return undefined;+ if (typeof raw !== "object" || Array.isArray(raw)) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_context_pack_outcome: evidence_claim must be an object",+ );+ }+ const claim = raw as Record<string, unknown>;+ const finalTextHash = optionalStringArg(+ "brain_context_pack_outcome",+ claim,+ CONTEXT_PACK_EVIDENCE_FIELD.finalTextHash,+ );+ const itemCount = coerceNonNegativeInteger(+ "brain_context_pack_outcome",+ CONTEXT_PACK_EVIDENCE_FIELD.itemCount,+ claim[CONTEXT_PACK_EVIDENCE_FIELD.itemCount],+ );+ const finalTextChars = coerceNonNegativeInteger(+ "brain_context_pack_outcome",+ CONTEXT_PACK_EVIDENCE_FIELD.finalTextChars,+ claim[CONTEXT_PACK_EVIDENCE_FIELD.finalTextChars],+ );+ if (finalTextHash === undefined && itemCount === undefined && finalTextChars === undefined) {+ return undefined;+ }+ return {+ ...(finalTextHash !== undefined ? { finalTextHash } : {}),+ ...(itemCount !== undefined ? { itemCount } : {}),+ ...(finalTextChars !== undefined ? { finalTextChars } : {}),+ };+}++export function contextPackOutcomeFilter(args: Record<string, unknown>): ContextPackOutcomeFilter {+ const host = optionalStringArg("brain_context_pack_outcome", args, "host");+ const sampleId = optionalStringArg("brain_context_pack_outcome", args, "sample_id");+ const since = optionalStringArg("brain_context_pack_outcome", args, "since");+ const until = optionalStringArg("brain_context_pack_outcome", args, "until");+ const limit = coercePositiveInteger("brain_context_pack_outcome", "limit", args["limit"]);+ const maxSamples = coercePositiveInteger(+ "brain_context_pack_outcome",+ "max_samples",+ args["max_samples"],+ );+ return {+ ...(host !== undefined ? { host } : {}),+ ...(sampleId !== undefined ? { sampleId } : {}),+ ...(since !== undefined ? { since } : {}),+ ...(until !== undefined ? { until } : {}),+ ...(limit !== undefined ? { limit } : {}),+ ...(maxSamples !== undefined ? { maxSamples } : {}),+ };+}++export function coerceBoolean(raw: unknown): boolean | undefined {+ if (raw === undefined || raw === null) return undefined;+ if (typeof raw === "boolean") return raw;+ if (raw === "true") return true;+ if (raw === "false") return false;+ throw new MCPError(+ INVALID_PARAMS,+ "brain_context_pack_outcome: boolean fields must be true or false",+ );+}++// ----- brain_knowledge_gaps (t_97091fff) -----------------------------------++export async function toolBrainKnowledgeGaps(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const since = optionalStringArg("brain_knowledge_gaps", args, "since");+ const until = optionalStringArg("brain_knowledge_gaps", args, "until");+ const minOccurrences = coercePositiveInteger(+ "brain_knowledge_gaps",+ "min_occurrences",+ args["min_occurrences"],+ );+ const limit = coercePositiveInteger("brain_knowledge_gaps", "limit", args["limit"]);+ const maxSatisfaction = coerceUnitInterval("max_satisfaction", args["max_satisfaction"]);+ const report = aggregateQueryDemand(ctx.vault, {+ ...(since !== undefined ? { since } : {}),+ ...(until !== undefined ? { until } : {}),+ ...(minOccurrences !== undefined ? { minOccurrences } : {}),+ ...(maxSatisfaction !== undefined ? { maxSatisfaction } : {}),+ ...(limit !== undefined ? { limit } : {}),+ });+ return { vault_path: vaultPathField(ctx), ...serializeQueryDemandReport(report) };+}++export function coerceUnitInterval(name: string, raw: unknown): number | undefined {+ if (raw === undefined || raw === null) return undefined;+ if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 0 || raw > 1) {+ throw new MCPError(INVALID_PARAMS, `brain_knowledge_gaps: ${name} must be a number in [0, 1]`);+ }+ return raw;+}diff --git a/src/mcp/brain/recall-session-tools.ts b/src/mcp/brain/recall-session-tools.tsnew file mode 100644index 00000000..6210c649--- /dev/null+++ b/src/mcp/brain/recall-session-tools.ts@@ -0,0 +1,321 @@+/**+ * The session tools of the recall family (task 3.19):+ * `brain_session_grep`, its coverage view, `brain_session_describe` and+ * `brain_session_expand`, each answering at the caller's reach. Split+ * from `recall-tools.ts`; registration happens through that module's+ * registry, which preserves the public RECALL_TOOLS surface.+ */++import {+ coverageSessionRecall,+ DEFAULT_LIMIT as SESSION_RECALL_DEFAULT_LIMIT,+ decorateSessionRecallHits,+ describeSessionRecall,+ expandSessionRecall,+ searchSessionRecall,+ SessionCoverageEntityUnknownError,+ SessionCoverageInfeasibleError,+} from "../../core/brain/session-recall.ts";+import { MINED_KEY_MAX_LENGTH } from "../../core/brain/link-graph/session-mining.ts";+import { resolveTimeBounds } from "./time-bounds.ts";+import { isPayloadRemotelyReadable } from "../../core/brain/payload-inventory.ts";+import { pageSlice } from "../../core/brain/offset-cursor.ts";+import {+ DEFAULT_PAYLOAD_PAGE_CHARS,+ PayloadNotFoundError,+ PayloadRefError,+ PayloadRegistry,+ payloadIdFromRef,+} from "../../core/brain/payload-registry.ts";+import { TRANSPORT_REACH } from "../../core/graph/transport-reach.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import { contextReach } from "../tool-contract.ts";+import type { ServerContext } from "../tool-contract.ts";+import { coercePositiveInteger, optionalStringArg, requiredStringArg } from "./shared.ts";+import { cursorOffsetArg } from "./pagination.ts";+import { unknownOperationError } from "../coerce.ts";++// ----- brain_context_presets ----------------------------------------------++export async function toolBrainSessionGrep(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ // Coverage-first selection (t_2c2a883c) rides this tool as an explicit+ // operation; omitted (the default) is the historical grep, byte-identical.+ const operation = args["operation"] ?? "match";+ if (operation === "coverage") return toolBrainSessionGrepCoverage(ctx, args);+ if (operation !== "match") {+ // The dispatch contract (surface-error-codes census): every tool whose+ // schema declares a dispatch enum answers an unknown value with the+ // shared `unknown_operation` code, message unchanged.+ throw unknownOperationError("brain_session_grep: operation must be 'match' or 'coverage'");+ }+ if (args["char_budget"] !== undefined) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_session_grep: char_budget is not applicable to operation 'match'; it sizes the coverage selection",+ );+ }+ if (args["entity_key"] !== undefined) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_session_grep: entity_key is not applicable to operation 'match'; it seeds the coverage fan-out",+ );+ }+ const limit = coercePositiveInteger("brain_session_grep", "limit", args["limit"]);+ const snippetChars = coercePositiveInteger(+ "brain_session_grep",+ "snippet_chars",+ args["snippet_chars"],+ );+ // Conversation-chronology bounds (S1): `since` / `before` parse through+ // the shared time-range grammar (ISO date/datetime, today/yesterday,+ // <n>h/<n>d/<n>w) via the shared time-bounds wrapper. `before` maps+ // onto the range's inclusive upper edge.+ const since = optionalStringArg("brain_session_grep", args, "since");+ const before = optionalStringArg("brain_session_grep", args, "before");+ const bounds = resolveTimeBounds(since, before);+ // Inline-raw disclosure (C2): opt-in flag inlines the raw captures beside+ // each derived record and stamps an extracted discriminator. Omitted, the+ // response stays byte-identical.+ const includeRaw = args["include_raw"] === true;+ const rawBudgetChars = coercePositiveInteger(+ "brain_session_grep",+ "raw_budget_chars",+ args["raw_budget_chars"],+ );+ // The matches are a deterministic ranked walk (score, then id), so the+ // page is cut here over the full hit set: `total` counts every match+ // across pages and `next_cursor` continues the walk (null when+ // exhausted). Absent `limit`, the page is the historical bounded+ // default (DEFAULT_LIMIT in session-recall.ts) - an unpaginated call+ // used to answer 10 hits, not every hit in the vault.+ //+ // The search below NEVER runs with includeRaw: decoration reads the+ // record set once per hit decorated, so decorating the full match set+ // on every page made a cursor walk O(N^2). The page is cut first and+ // only its items are decorated.+ const offset = cursorOffsetArg("brain_session_grep", args);+ const sessionIdArg = optionalStringArg("brain_session_grep", args, "session_id");+ const hits = searchSessionRecall(ctx.vault, {+ query: requiredStringArg("brain_session_grep", args, "query"),+ ...withheldAtRemoteReach(ctx),+ ...(sessionIdArg !== undefined ? { sessionId: sessionIdArg } : {}),+ limit: Number.MAX_SAFE_INTEGER,+ ...(snippetChars !== undefined ? { snippetChars } : {}),+ ...(bounds.sinceMs !== null ? { sinceMs: bounds.sinceMs } : {}),+ ...(bounds.untilMs !== null ? { untilMs: bounds.untilMs } : {}),+ ...(rawBudgetChars !== undefined ? { rawBudgetChars } : {}),+ });+ const page = pageSlice(hits.hits, offset, limit ?? SESSION_RECALL_DEFAULT_LIMIT);+ if (!includeRaw) {+ return { hits: page.items, total: page.total, next_cursor: page.next_cursor };+ }+ return {+ hits: decorateSessionRecallHits(ctx.vault, page.items, {+ ...withheldAtRemoteReach(ctx),+ ...(sessionIdArg !== undefined ? { sessionId: sessionIdArg } : {}),+ ...(rawBudgetChars !== undefined ? { rawBudgetChars } : {}),+ }),+ total: page.total,+ next_cursor: page.next_cursor,+ };+}++/**+ * The coverage operation of `brain_session_grep` (t_2c2a883c): the+ * coverage-first thread selection over the lineage-scoped record set,+ * fanning out under the adaptive topic budget and the caller's+ * `char_budget`, returning the selected turns chronologically beside the+ * selection diagnostics. The typed floor-violation infeasibility maps to+ * INVALID_PARAMS - a budget that cannot hold the floor-weighted+ * selection is a caller error, named so it can be retried, never a+ * silent truncation.+ */+export function toolBrainSessionGrepCoverage(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Record<string, unknown> {+ if (args["query"] !== undefined) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_session_grep: operation 'coverage' selects whole topics; it takes no `query`",+ );+ }+ for (const inapplicable of [+ "since",+ "before",+ "limit",+ "snippet_chars",+ "include_raw",+ "raw_budget_chars",+ "cursor",+ ] as const) {+ if (args[inapplicable] !== undefined) {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_session_grep: ${inapplicable} is not applicable to operation 'coverage'; it pages, sizes or filters the match operation`,+ );+ }+ }+ const charBudget = coercePositiveInteger(+ "brain_session_grep",+ "char_budget",+ args["char_budget"],+ );+ if (charBudget === undefined) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_session_grep: char_budget is required for the coverage operation",+ );+ }+ const sessionId = optionalStringArg("brain_session_grep", args, "session_id");+ // The miner's own cap: mined keys run to MINED_KEY_MAX_LENGTH, so a+ // 129-200 character URL or path key must be able to seed coverage here.+ const entityKey = optionalStringArg(+ "brain_session_grep",+ args,+ "entity_key",+ MINED_KEY_MAX_LENGTH,+ );+ let result;+ try {+ result = coverageSessionRecall(ctx.vault, {+ ...withheldAtRemoteReach(ctx),+ ...(sessionId !== undefined ? { sessionId } : {}),+ ...(entityKey !== undefined ? { entityKey } : {}),+ charBudget,+ });+ } catch (err) {+ if (err instanceof SessionCoverageInfeasibleError) {+ throw new MCPError(INVALID_PARAMS, err.message);+ }+ if (err instanceof SessionCoverageEntityUnknownError) {+ throw new MCPError(INVALID_PARAMS, err.message);+ }+ throw err;+ }+ return { ...result };+}++/**+ * Private continuity rows are session data a remote caller does not get:+ * the recall tools answer about them exactly as about a row that does not+ * exist. A local caller keeps every row.+ */+export function withheldAtRemoteReach(ctx: ServerContext): { withholdPrivate?: true } {+ return contextReach(ctx) === TRANSPORT_REACH.local ? {} : { withholdPrivate: true };+}++export async function toolBrainSessionDescribe(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ return {+ ...describeSessionRecall(ctx.vault, {+ sessionId: requiredStringArg("brain_session_describe", args, "session_id"),+ ...withheldAtRemoteReach(ctx),+ ...(args["topics"] === true ? { topics: true } : {}),+ }),+ };+}++export async function toolBrainSessionExpand(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const payloadRef = optionalStringArg("brain_session_expand", args, "payload");+ if (payloadRef !== undefined) return expandPayload(ctx, args, payloadRef);+ const rawLimit = coercePositiveInteger("brain_session_expand", "raw_limit", args["raw_limit"]);+ return {+ ...expandSessionRecall(ctx.vault, {+ id: requiredStringArg("brain_session_expand", args, "id"),+ ...withheldAtRemoteReach(ctx),+ ...(rawLimit !== undefined ? { rawLimit } : {}),+ ...(optionalStringArg("brain_session_expand", args, "cursor") !== undefined+ ? { cursor: optionalStringArg("brain_session_expand", args, "cursor") }+ : {}),+ }),+ };+}++/**+ * Page one externalized payload (t_35440e83) - the `payload` mode of+ * `brain_session_expand`.+ *+ * Payloads only ever come out of session import, so expanding a+ * placeholder found in a recalled turn is the same act as expanding the+ * turn: one more level of "give me the exact source". Riding this tool+ * rather than adding one keeps the tool budget and every profile that+ * already carries the session tools unchanged.+ *+ * Reach: a local caller reads any stored payload. A REMOTE caller reads+ * one only when a non-private session turn references it, directly or+ * through another remotely readable payload (`payload-inventory.ts`).+ * Pages grant nothing: a page can be written by tools a session turn+ * cannot. A payload referenced only from a private row or a page, and an+ * orphan nobody references, answer the same refusal, so a remote caller+ * cannot use the difference to probe what exists.+ */+export function expandPayload(+ ctx: ServerContext,+ args: Record<string, unknown>,+ ref: string,+): Record<string, unknown> {+ if (args["id"] !== undefined || args["raw_limit"] !== undefined) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_session_expand: `payload` pages one payload ref; it cannot be combined with `id` or `raw_limit`",+ );+ }+ let sha256: string;+ try {+ sha256 = payloadIdFromRef(ref);+ } catch (err) {+ if (err instanceof PayloadRefError) throw new MCPError(INVALID_PARAMS, err.message);+ throw err;+ }+ if (+ contextReach(ctx) !== TRANSPORT_REACH.local &&+ !isPayloadRemotelyReadable(ctx.vault, sha256)+ ) {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_session_expand: payload ${ref} is not readable at remote reach - no non-private ` ++ "session turn references it",+ );+ }+ const cursor = optionalStringArg("brain_session_expand", args, "cursor");+ const offset = cursor === undefined ? 0 : Number.parseInt(cursor, 10);+ if (cursor !== undefined && (!/^[0-9]+$/.test(cursor) || !Number.isFinite(offset))) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_session_expand: a payload cursor is the next_cursor of a previous page",+ );+ }+ const limit =+ coercePositiveInteger("brain_session_expand", "payload_chars", args["payload_chars"]) ??+ DEFAULT_PAYLOAD_PAGE_CHARS;+ try {+ const page = new PayloadRegistry({ vault: ctx.vault, maxInlineChars: 1 }).get(ref, {+ offset,+ limit,+ });+ return {+ payload: {+ ref: page.ref,+ offset: page.offset,+ limit: page.limit,+ total_chars: page.totalChars,+ content: page.content,+ },+ next_cursor: page.nextOffset === null ? null : String(page.nextOffset),+ };+ } catch (err) {+ if (err instanceof PayloadNotFoundError) throw new MCPError(INVALID_PARAMS, err.message);+ throw err;+ }+}++// ----- brain_pre_compress_pack (v0.20.0) -----------------------------------diff --git a/src/mcp/brain/recall-tools.ts b/src/mcp/brain/recall-tools.tsindex 61ba8d0f..97b747af 100644--- a/src/mcp/brain/recall-tools.ts+++ b/src/mcp/brain/recall-tools.ts@@ -6,1230 +6,32 @@* BRAIN_TOOLS surface.*/-import { resolveSearchConfig } from "../../core/search/index.ts";-import { appendMetric } from "../../core/brain/metrics.ts";-import { parseRecallBenchmarkDataset, runRecallBenchmark } from "../../core/search/benchmark.ts";-import { tuneRecall } from "../../core/search/tuning.ts";-import { loadTunedParameters, resetTuning } from "../../core/search/tuning-store.ts";-import { listGateTelemetry, summarizeGateTelemetry } from "../../core/brain/gate-telemetry.ts";-import { computeMemoryCostMeter } from "../../core/brain/memory-cost-meter.ts";-import { observedReuseRates } from "../../core/brain/observed-use.ts";-import { computeDeadWeight, DEAD_WEIGHT_MAX_LIMIT } from "../../core/brain/dead-weight.ts";-import { everyArtifactRefView } from "../../core/brain/artifact-ref-view.ts";-import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";import {- isRecallChannel,- isRecallTelemetryMode,- isRecallTelemetryStatus,- listRecallTelemetry,RECALL_CHANNELS,RECALL_TELEMETRY_MODES,RECALL_TELEMETRY_STATUSES,- summarizeRecallTelemetry,- type RecallChannel,- type RecallTelemetryFilter,- type RecallTelemetryMode,- type RecallTelemetryStatus,} from "../../core/brain/recall-telemetry.ts";+import { TOKEN_COUNT_METHODS } from "../../core/brain/token-impact.ts";+import type { ToolDefinition } from "../tool-contract.ts";+import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";+import { CURSOR_SCHEMA } from "./pagination.ts";+import { AGENT_SCOPE_SCHEMA } from "../coerce.ts";import {- isMcpRouteStatus,- listMcpRouteLatency,- summarizeMcpRouteLatency,- type McpRouteLatencyFilter,- type McpRouteStatus,-} from "../../core/brain/mcp-route-metrics.ts";-import {- emitTokenImpact,- normalizeTokenCountMethod,- TOKEN_COUNT_METHOD,- TOKEN_COUNT_METHODS,- isTokenImpactOutcome,- listTokenImpact,- recordTokenImpactOutcome,- summarizeTokenImpact,- type TokenCountMethod,- type TokenImpactFilter,- type TokenImpactOutcome,-} from "../../core/brain/token-impact.ts";-import {- listContextPackOutcomes,- postContextPackOutcome,- summarizeContextPackOutcomes,- type ContextPackOutcomeFilter,-} from "../../core/brain/context-pack-outcome.ts";-import {- CONTEXT_PACK_EVIDENCE_FIELD,- type ContextPackEvidenceClaim,-} from "../../core/brain/context-pack-evidence.ts";-import {- resolveContextPackOutcomeEnabled,- resolveTokenImpactLedgerEnabled,-} from "../../core/config.ts";+ toolBrainBenchmark,+ toolBrainRecallTelemetry,+ toolBrainTune,+} from "./recall-bench-tools.ts";import {- coverageSessionRecall,- DEFAULT_LIMIT as SESSION_RECALL_DEFAULT_LIMIT,- decorateSessionRecallHits,- describeSessionRecall,- expandSessionRecall,- searchSessionRecall,- SessionCoverageEntityUnknownError,- SessionCoverageInfeasibleError,-} from "../../core/brain/session-recall.ts";-import { MINED_KEY_MAX_LENGTH } from "../../core/brain/link-graph/session-mining.ts";-import { resolveTimeBounds } from "./time-bounds.ts";-import { aggregateQueryDemand, serializeQueryDemandReport } from "../../core/brain/query-demand.ts";-import { buildRetrievalPlan, serializeRetrievalPlan } from "../../core/brain/retrieval-plan.ts";-import { isoSecond } from "../../core/brain/time.ts";-import { isPayloadRemotelyReadable } from "../../core/brain/payload-inventory.ts";-import { pageSlice } from "../../core/brain/offset-cursor.ts";+ toolBrainRetrievalPlan,+ toolBrainRouteMetrics,+ toolBrainTokenImpact,+} from "./recall-coerce-tools.ts";+import { toolBrainContextPackOutcome, toolBrainKnowledgeGaps } from "./recall-outcome-tools.ts";import {- DEFAULT_PAYLOAD_PAGE_CHARS,- PayloadNotFoundError,- PayloadRefError,- PayloadRegistry,- payloadIdFromRef,-} from "../../core/brain/payload-registry.ts";-import { TRANSPORT_REACH } from "../../core/graph/transport-reach.ts";-import { INVALID_PARAMS, MCPError } from "../protocol.ts";-import { contextReach } from "../tool-contract.ts";-import { requestRefView } from "./reach-events.ts";-import type { ServerContext, ToolDefinition } from "../tool-contract.ts";-import { vaultPathField } from "../vault-path-field.ts";-import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";-import { coercePositiveInteger, optionalStringArg, requiredStringArg } from "./shared.ts";-import { cursorOffsetArg, CURSOR_SCHEMA } from "./pagination.ts";-import { AGENT_SCOPE_SCHEMA, coerceAgentScope, unknownOperationError } from "../coerce.ts";--/** Recall-quality benchmark over an inline dataset. */-async function toolBrainBenchmark(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const op = args["operation"];- if (op !== "run") {- throw unknownOperationError("brain_benchmark: operation must be run");- }- const k = args["k"];- if (k !== undefined && (!Number.isInteger(k) || (k as number) < 1)) {- throw new MCPError(INVALID_PARAMS, "brain_benchmark run: k must be a positive integer");- }- let dataset;- try {- dataset = parseRecallBenchmarkDataset(args["dataset"]);- } catch (exc) {- throw new MCPError(INVALID_PARAMS, `brain_benchmark run: ${(exc as Error).message}`);- }- const searchConfig = resolveSearchConfig({- vault: ctx.vault,- configPath: ctx.configPath ?? undefined,- });- const now = new Date();- const report = await runRecallBenchmark(searchConfig, dataset, {- ...(k !== undefined ? { k: k as number } : {}),- expand: args["expand"] === true,- // The dataset is the caller's, and so is the reach it is scored at:- // `hit` / `rank` / `expectedFound` for caller-named paths is an- // existence oracle over any corpus the caller did not earn.- transportReach: contextReach(ctx),- });- try {- appendMetric(ctx.vault, {- surface: "recall_benchmark",- runAt: isoSecond(now),- payload: {- total: report.total,- k: report.k,- expand: report.expand,- hit_at_k: report.hitAtK,- mrr: report.mrr,- misses: report.perQuery.filter((q) => !q.hit).map((q) => q.id),- },- });- } catch {- // Metrics are observability, not correctness.- }- return {- total: report.total,- k: report.k,- expand: report.expand,- hit_at_k: report.hitAtK,- mrr: report.mrr,- // A degraded run measured a smaller system than the configured one.- ...(report.degraded.length > 0 ? { degraded: report.degraded } : {}),- per_query: report.perQuery,- };-}--// ----- brain_tune (t_ae973491) ---------------------------------------------------/** Opt-in self-tuning recall: run the grid, inspect, or reset. */-async function toolBrainTune(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const op = args["operation"];- if (op !== "run" && op !== "status" && op !== "reset") {- throw unknownOperationError("brain_tune: operation must be run|status|reset");- }- const searchConfig = resolveSearchConfig({- vault: ctx.vault,- configPath: ctx.configPath ?? undefined,- });- if (op === "status") {- return {- enabled: searchConfig.recall.selfTuningEnabled,- tuned: loadTunedParameters(ctx.vault),- };- }- if (op === "reset") {- return { removed: resetTuning(ctx.vault) };- }- const k = args["k"];- if (k !== undefined && (!Number.isInteger(k) || (k as number) < 1)) {- throw new MCPError(INVALID_PARAMS, "brain_tune run: k must be a positive integer");- }- let dataset;- try {- dataset = parseRecallBenchmarkDataset(args["dataset"]);- } catch (exc) {- throw new MCPError(INVALID_PARAMS, `brain_tune run: ${(exc as Error).message}`);- }- const now = new Date();- const report = await tuneRecall(searchConfig, dataset, {- ...(k !== undefined ? { k: k as number } : {}),- now,- // Same reasoning as `brain_benchmark`: the grid is scored with the- // benchmark, so every cell inherits whatever reach is passed here.- transportReach: contextReach(ctx),- });- try {- appendMetric(ctx.vault, {- surface: "self_tuning",- runAt: isoSecond(now),- payload: {- chosen: report.chosen,- evaluated: report.evaluated.length,- best_mrr: Math.max(...report.evaluated.map((e) => e.mrr)),- dataset_hash: report.datasetHash,- },- });- } catch {- // Metrics are observability, not correctness.- }- return {- chosen: report.chosen,- evaluated: report.evaluated.map((e) => ({- params: e.params,- mrr: e.mrr,- hit_at_k: e.hitAtK,- ...(e.degraded.length > 0 ? { degraded: e.degraded } : {}),- })),- dataset_hash: report.datasetHash,- ...(report.degraded.length > 0 ? { degraded: report.degraded } : {}),- };-}--// ----- brain_dead_ends (t_be62c62d) -------------------------------------------async function toolBrainRecallTelemetry(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const operation = optionalStringArg("brain_recall_telemetry", args, "operation");- const filter = recallTelemetryFilter(args);-- if (operation === "list") {- const records = listRecallTelemetry(ctx.vault, filter);- return { vault_path: vaultPathField(ctx), total: records.length, records };- }- if (operation === "summary") {- const summary = summarizeRecallTelemetry(ctx.vault, filter);- return { ...summary };- }- // Gate-decision telemetry (Workspace Insight Suite, t_65036e02):- // records emitted by brain_recall_gate when recall_gate_telemetry is on.- if (operation === "gate_list") {- const records = listGateTelemetry(ctx.vault, {- ...(filter.host !== undefined ? { host: filter.host } : {}),- ...(filter.since !== undefined ? { since: filter.since } : {}),- ...(filter.until !== undefined ? { until: filter.until } : {}),- ...(filter.limit !== undefined ? { limit: filter.limit } : {}),- });- return { vault_path: vaultPathField(ctx), total: records.length, records };- }- if (operation === "gate_summary") {- const summary = summarizeGateTelemetry(ctx.vault, {- ...(filter.host !== undefined ? { host: filter.host } : {}),- ...(filter.since !== undefined ? { since: filter.since } : {}),- ...(filter.until !== undefined ? { until: filter.until } : {}),- });- return { ...summary };- }- // Observed-use blend (t_65588d8b): the folded per-artifact- // USED/IGNORED/CONTRADICTED reuse signal that recall ranking prefers over- // predicted importance. Exposed here so the blend is inspectable.- if (operation === "observed_reuse") {- const artifacts = [...observedReuseRates(ctx.vault).entries()]- .map(([key, r]) => ({ key, ...r }))- .toSorted((a, b) => (a.score !== b.score ? b.score - a.score : a.key < b.key ? -1 : 1));- return { vault_path: vaultPathField(ctx), total: artifacts.length, artifacts };- }- // Write-vs-read cost meter (memory cost meter): folds write volume- // against the read telemetry above. Period-based; mode/status/host/limit- // do not apply to the write side, so reject them to mirror the CLI's- // fail-closed behavior (recall-telemetry.ts costMeter) rather than- // silently ignoring and looking like a valid filtered result.- if (operation === "cost") {- for (const name of ["mode", "status", "host", "limit"] as const) {- if (args[name] !== undefined) {- throw new MCPError(- INVALID_PARAMS,- `brain_recall_telemetry: ${name} is not supported for the cost meter`,- );- }- }- const writeCost = coerceNonNegativeNumber("write_cost", args["write_cost"]);- const readCost = coerceNonNegativeNumber("read_cost", args["read_cost"]);- const writeHeavyRatio = coerceNonNegativeNumber("write_heavy_ratio", args["write_heavy_ratio"]);- const meter = computeMemoryCostMeter(ctx.vault, {- withholdsPrivate: contextReach(ctx) !== TRANSPORT_REACH.local,- ...(filter.since !== undefined ? { since: filter.since } : {}),- ...(filter.until !== undefined ? { until: filter.until } : {}),- ...(writeCost !== undefined || readCost !== undefined- ? {- weights: {- ...(writeCost !== undefined ? { write: writeCost } : {}),- ...(readCost !== undefined ? { read: readCost } : {}),- },- }- : {}),- ...(writeHeavyRatio !== undefined ? { writeHeavyRatio } : {}),- });- return { vault_path: vaultPathField(ctx), ...meter };- }- // Dead weight (recall-quality, t_1ee67e5b): the complement fold over- // the vault's live in-scope pages and every path recorded recall ever- // surfaced (telemetry top artifacts + observed-use source refs). The- // seventh operation on this tool - an operation, never a new tool, so- // the tool-count pin does not move.- if (operation === "dead_weight") {- // Record-only filters (mode/status/channel/host) have no meaning for- // the complement; reject them rather than silently ignore, mirroring- // the cost op and the CLI's fail-closed verb. `limit` is the one- // exception (PR #248 review L10): it bounds the dead preview, which- // is otherwise pinned at the fold's 50-row default, clamped to the- // shared maximum so the full list is reachable in bounded pages.- for (const name of ["mode", "status", "channel", "host"] as const) {- if (args[name] !== undefined) {- throw new MCPError(- INVALID_PARAMS,- `brain_recall_telemetry: ${name} is not supported for dead_weight`,- );- }- }- // Hidden rows are dropped BEFORE total: the request's reach/ownership- // boundary is applied to the FULL SET, so `pages_total`, `dead` and- // every count answer only what this caller may see - a total that- // still included the hidden rows would leak their number (the- // analytics rule). A local caller filters nothing, by construction.- const refs = everyArtifactRefView(- requestRefView(ctx),- gatedOwnerScopeView(ctx.vault, ctx.agentName),- );- const report = computeDeadWeight(ctx.vault, {- ...(filter.since !== undefined ? { since: filter.since } : {}),- ...(filter.until !== undefined ? { until: filter.until } : {}),- ...(filter.limit !== undefined- ? { deadLimit: Math.min(filter.limit, DEAD_WEIGHT_MAX_LIMIT) }- : {}),- ...(refs.filtersNothing ? {} : { includePath: (rel: string) => refs.visible(rel) }),- });- return { vault_path: vaultPathField(ctx), ...report };- }- throw unknownOperationError(- "brain_recall_telemetry: operation must be list, summary, gate_list, gate_summary, observed_reuse, cost, or dead_weight",- );-}--function coerceNonNegativeNumber(name: string, raw: unknown): number | undefined {- if (raw === undefined || raw === null) return undefined;- if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 0) {- throw new MCPError(- INVALID_PARAMS,- `brain_recall_telemetry: ${name} must be a non-negative number`,- );- }- return raw;-}--function recallTelemetryFilter(args: Record<string, unknown>): RecallTelemetryFilter {- const mode = coerceRecallTelemetryMode(args["mode"]);- const status = coerceRecallTelemetryStatus(args["status"]);- const channel = coerceRecallChannel(args["channel"]);- const host = optionalStringArg("brain_recall_telemetry", args, "host");- const since = optionalStringArg("brain_recall_telemetry", args, "since");- const until = optionalStringArg("brain_recall_telemetry", args, "until");- const limit = coercePositiveInteger("brain_recall_telemetry", "limit", args["limit"]);- return {- ...(mode !== undefined ? { mode } : {}),- ...(status !== undefined ? { status } : {}),- ...(channel !== undefined ? { channel } : {}),- ...(host !== undefined ? { host } : {}),- ...(since !== undefined ? { since } : {}),- ...(until !== undefined ? { until } : {}),- ...(limit !== undefined ? { limit } : {}),- };-}--function coerceRecallTelemetryMode(raw: unknown): RecallTelemetryMode | undefined {- if (raw === undefined || raw === null) return undefined;- const trimmed = typeof raw === "string" ? raw.trim() : raw;- // Rendered from the frozen member list. The prose copy this replaces- // omitted `query`, and so did the schema enum below it, so a mode the- // server records was refused at its own boundary.- if (!isRecallTelemetryMode(trimmed)) {- throw new MCPError(- INVALID_PARAMS,- `brain_recall_telemetry: mode must be one of ${RECALL_TELEMETRY_MODES.join(", ")}`,- );- }- return trimmed;-}--function coerceRecallTelemetryStatus(raw: unknown): RecallTelemetryStatus | undefined {- if (raw === undefined || raw === null) return undefined;- const trimmed = typeof raw === "string" ? raw.trim() : raw;- if (!isRecallTelemetryStatus(trimmed)) {- throw new MCPError(- INVALID_PARAMS,- `brain_recall_telemetry: status must be one of ${RECALL_TELEMETRY_STATUSES.join(", ")}`,- );- }- return trimmed;-}--function coerceRecallChannel(raw: unknown): RecallChannel | undefined {- if (raw === undefined || raw === null) return undefined;- const trimmed = typeof raw === "string" ? raw.trim() : raw;- if (!isRecallChannel(trimmed)) {- throw new MCPError(- INVALID_PARAMS,- `brain_recall_telemetry: channel must be one of ${RECALL_CHANNELS.join(", ")}`,- );- }- return trimmed;-}--// ----- brain_route_metrics (context-pack-economics-observability) -------------async function toolBrainRouteMetrics(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const operation = optionalStringArg("brain_route_metrics", args, "operation");- const filter = routeMetricsFilter(args);-- if (operation === "list") {- const records = listMcpRouteLatency(ctx.vault, filter);- return { vault_path: vaultPathField(ctx), total: records.length, records };- }- if (operation === "summary") {- const summary = summarizeMcpRouteLatency(ctx.vault, filter);- return { vault_path: vaultPathField(ctx), ...summary };- }- throw unknownOperationError("brain_route_metrics: operation must be list or summary");-}--// ----- brain_retrieval_plan (shadow-only retrieval advisor, t_3ffb021c) -------async function toolBrainRetrievalPlan(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const question = requiredStringArg("brain_retrieval_plan", args, "question");- const tokenBudget = coercePositiveInteger(- "brain_retrieval_plan",- "token_budget",- args["token_budget"],- );- const agentScope = coerceAgentScope(ctx, args, true);- const plan = buildRetrievalPlan(ctx.vault, question, {- ...(tokenBudget !== undefined ? { tokenBudget } : {}),- ...(agentScope !== undefined ? { agentScope } : {}),- });- return { vault_path: vaultPathField(ctx), ...serializeRetrievalPlan(plan) };-}--function routeMetricsFilter(args: Record<string, unknown>): McpRouteLatencyFilter {- const tool = optionalStringArg("brain_route_metrics", args, "tool");- const status = coerceRouteMetricsStatus(args["status"]);- const since = optionalStringArg("brain_route_metrics", args, "since");- const until = optionalStringArg("brain_route_metrics", args, "until");- const limit = coercePositiveInteger("brain_route_metrics", "limit", args["limit"]);- return {- ...(tool !== undefined ? { tool } : {}),- ...(status !== undefined ? { status } : {}),- ...(since !== undefined ? { since } : {}),- ...(until !== undefined ? { until } : {}),- ...(limit !== undefined ? { limit } : {}),- };-}--function coerceRouteMetricsStatus(raw: unknown): McpRouteStatus | undefined {- if (raw === undefined || raw === null) return undefined;- const trimmed = typeof raw === "string" ? raw.trim() : raw;- if (!isMcpRouteStatus(trimmed)) {- throw new MCPError(INVALID_PARAMS, "brain_route_metrics: status must be ok or error");- }- return trimmed;-}--// ----- brain_token_impact (context-pack-economics-observability) --------------/**- * Durable token-impact + context-pack-quality ledger. `record`/`outcome`- * write opt-in samples (gated on `token_impact_ledger_enabled`, payload-safe:- * counts + opaque pack id only); `list`/`summary` read the ledger regardless- * of the gate so historical aggregates stay inspectable.- */-async function toolBrainTokenImpact(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const operation = optionalStringArg("brain_token_impact", args, "operation");-- if (operation === "record") {- const baselineTokens = coerceNonNegativeInteger(- "brain_token_impact",- "baseline_tokens",- args["baseline_tokens"],- );- const packedTokens = coerceNonNegativeInteger(- "brain_token_impact",- "packed_tokens",- args["packed_tokens"],- );- if (baselineTokens === undefined || packedTokens === undefined) {- throw new MCPError(- INVALID_PARAMS,- "brain_token_impact: record requires baseline_tokens and packed_tokens (non-negative integers)",- );- }- const method = coerceTokenCountMethod(args["method"]) ?? TOKEN_COUNT_METHOD.heuristic;- const modeledAvoided = coerceNonNegativeTokenValue(- "brain_token_impact",- "modeled_avoided_inferences",- args["modeled_avoided_inferences"],- );- const modeledPerInference = coerceNonNegativeTokenValue(- "brain_token_impact",- "modeled_tokens_per_inference",- args["modeled_tokens_per_inference"],- );- const enabled = resolveTokenImpactLedgerEnabled(ctx.configPath ?? undefined);- const record = emitTokenImpact(- ctx.vault,- {- baselineTokens,- packedTokens,- method,- ...tokenImpactCorrelation(args),- ...(modeledAvoided !== undefined ? { modeledAvoidedInferences: modeledAvoided } : {}),- ...(modeledPerInference !== undefined- ? { modeledTokensPerInference: modeledPerInference }- : {}),- },- enabled || undefined,- );- if (record === null) {- return { vault_path: vaultPathField(ctx), recorded: false, enabled };- }- return {- vault_path: vaultPathField(ctx),- recorded: true,- enabled,- id: record.id,- method,- baseline_tokens: baselineTokens,- packed_tokens: packedTokens,- delta_tokens: baselineTokens - packedTokens,- };- }-- if (operation === "outcome") {- const outcome = coerceTokenImpactOutcome(args["outcome"]);- if (outcome === undefined) {- throw new MCPError(- INVALID_PARAMS,- "brain_token_impact: outcome requires outcome (first_pass | repair | retry)",- );- }- const tokensPerInference = coerceNonNegativeTokenValue(- "brain_token_impact",- "tokens_per_inference",- args["tokens_per_inference"],- );- const enabled = resolveTokenImpactLedgerEnabled(ctx.configPath ?? undefined);- const record = recordTokenImpactOutcome(- ctx.vault,- {- outcome,- ...tokenImpactCorrelation(args),- ...(tokensPerInference !== undefined ? { tokensPerInference } : {}),- },- enabled || undefined,- );- if (record === null) {- return { vault_path: vaultPathField(ctx), recorded: false, enabled };- }- return { vault_path: vaultPathField(ctx), recorded: true, enabled, id: record.id, outcome };- }-- const filter = tokenImpactFilter(args);- if (operation === "list") {- const records = listTokenImpact(ctx.vault, filter);- return { vault_path: vaultPathField(ctx), total: records.length, records };- }- if (operation === "summary") {- return { vault_path: vaultPathField(ctx), ...summarizeTokenImpact(ctx.vault, filter) };- }- throw unknownOperationError(- "brain_token_impact: operation must be record, outcome, list, or summary",- );-}--function tokenImpactCorrelation(args: Record<string, unknown>): {- host?: string;- sessionId?: string;- turnId?: string;- packId?: string;-} {- const host = optionalStringArg("brain_token_impact", args, "host");- const sessionId = optionalStringArg("brain_token_impact", args, "session_id");- const turnId = optionalStringArg("brain_token_impact", args, "turn_id");- const packId = optionalStringArg("brain_token_impact", args, "pack_id");- return {- ...(host !== undefined ? { host } : {}),- ...(sessionId !== undefined ? { sessionId } : {}),- ...(turnId !== undefined ? { turnId } : {}),- ...(packId !== undefined ? { packId } : {}),- };-}--function tokenImpactFilter(args: Record<string, unknown>): TokenImpactFilter {- const host = optionalStringArg("brain_token_impact", args, "host");- const packId = optionalStringArg("brain_token_impact", args, "pack_id");- const method = coerceTokenCountMethod(args["method"]);- const since = optionalStringArg("brain_token_impact", args, "since");- const until = optionalStringArg("brain_token_impact", args, "until");- const limit = coercePositiveInteger("brain_token_impact", "limit", args["limit"]);- const maxSamples = coercePositiveInteger(- "brain_token_impact",- "max_samples",- args["max_samples"],- );- return {- ...(host !== undefined ? { host } : {}),- ...(packId !== undefined ? { packId } : {}),- ...(method !== undefined ? { method } : {}),- ...(since !== undefined ? { since } : {}),- ...(until !== undefined ? { until } : {}),- ...(limit !== undefined ? { limit } : {}),- ...(maxSamples !== undefined ? { maxSamples } : {}),- };-}--function coerceTokenCountMethod(raw: unknown): TokenCountMethod | undefined {- if (raw === undefined || raw === null) return undefined;- const trimmed = typeof raw === "string" ? raw.trim() : raw;- // Legacy-aware: an adapter still posting the pre-rename `exact` /- // `fallback` labels is translated rather than rejected, so upgrading the- // server does not silently stop recording an existing caller's samples.- const method = normalizeTokenCountMethod(trimmed);- if (method === null) {- throw new MCPError(- INVALID_PARAMS,- `brain_token_impact: method must be one of ${TOKEN_COUNT_METHODS.join(", ")}`,- );- }- return method;-}--function coerceTokenImpactOutcome(raw: unknown): TokenImpactOutcome | undefined {- if (raw === undefined || raw === null) return undefined;- const trimmed = typeof raw === "string" ? raw.trim() : raw;- if (!isTokenImpactOutcome(trimmed)) {- throw new MCPError(- INVALID_PARAMS,- "brain_token_impact: outcome must be first_pass, repair, or retry",- );- }- return trimmed;-}--function coerceNonNegativeInteger(tool: string, field: string, raw: unknown): number | undefined {- if (raw === undefined || raw === null) return undefined;- if (typeof raw === "number") {- if (!Number.isInteger(raw) || raw < 0) {- throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a non-negative integer`);- }- return raw;- }- if (typeof raw === "string") {- const trimmed = raw.trim();- if (trimmed === "" || !/^[0-9]+$/.test(trimmed)) {- throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a non-negative integer`);- }- return Number.parseInt(trimmed, 10);- }- throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a non-negative integer`);-}--function coerceNonNegativeTokenValue(- tool: string,- field: string,- raw: unknown,-): number | undefined {- if (raw === undefined || raw === null) return undefined;- // Reject empty/whitespace-only strings explicitly: Number("") and- // Number(" ".trim()) both coerce to 0 and would otherwise be written to the- // durable ledger as a fabricated zero. Mirrors coerceNonNegativeInteger above.- if (typeof raw === "string" && raw.trim() === "") {- throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a non-negative number`);- }- const value = typeof raw === "string" ? Number(raw.trim()) : raw;- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {- throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a non-negative number`);- }- return value;-}--// ----- brain_context_pack_outcome (context-pack-economics-observability) ------/**- * Agent-operable context-pack outcome loop. `post` writes one compact- * outcome row (gated on `context_pack_outcome_enabled`, payload-safe:- * counters + an opaque sample id only), composes the C3 ledger by posting- * a matching first-pass/repair/retry calibration record, and composes the- * evidence half by posting the kernel's own reading of the sample beside- * the agent's claim. All three rows join on the one sample id and carry- * the same acting agent. `list`/`summary` read the rows regardless of the- * gate so historical aggregates stay inspectable. The three token signals- * (exact/modeled/observed) stay strictly separate; a field the caller omits- * is never invented.- */-async function toolBrainContextPackOutcome(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const operation = optionalStringArg("brain_context_pack_outcome", args, "operation");-- if (operation === "post") {- const sampleId = requiredStringArg("brain_context_pack_outcome", args, "sample_id");- const firstPassSuccess = coerceBoolean(args["first_pass_success"]);- if (firstPassSuccess === undefined) {- throw new MCPError(- INVALID_PARAMS,- "brain_context_pack_outcome: post requires first_pass_success (boolean)",- );- }- const repairRequired = coerceBoolean(args["repair_required"]);- const retryCount = coerceNonNegativeInteger(- "brain_context_pack_outcome",- "retry_count",- args["retry_count"],- );- const followUpTokens = coerceNonNegativeInteger(- "brain_context_pack_outcome",- "follow_up_tokens",- args["follow_up_tokens"],- );- const exact = coerceNonNegativeTokenValue(- "brain_context_pack_outcome",- "exact_prompt_token_savings",- args["exact_prompt_token_savings"],- );- const modeled = coerceNonNegativeTokenValue(- "brain_context_pack_outcome",- "modeled_inference_avoidance",- args["modeled_inference_avoidance"],- );- const observed = coerceNonNegativeTokenValue(- "brain_context_pack_outcome",- "observed_provider_tokens",- args["observed_provider_tokens"],- );- const evidenceClaim = contextPackEvidenceClaim(args["evidence_claim"]);- const enabled = resolveContextPackOutcomeEnabled(ctx.configPath ?? undefined);- const post = postContextPackOutcome(- ctx.vault,- {- sampleId,- firstPassSuccess,- ...contextPackOutcomeCorrelation(args),- // Omit-don't-invent: only forward fields the caller actually supplied.- ...(repairRequired !== undefined ? { repairRequired } : {}),- ...(retryCount !== undefined ? { retryCount } : {}),- ...(followUpTokens !== undefined ? { followUpTokens } : {}),- ...(exact !== undefined ? { exactPromptTokenSavings: exact } : {}),- ...(modeled !== undefined ? { modeledInferenceAvoidance: modeled } : {}),- ...(observed !== undefined ? { observedProviderTokens: observed } : {}),- ...(evidenceClaim !== undefined ? { evidenceClaim } : {}),- },- enabled || undefined,- );- if (post === null) {- return { vault_path: vaultPathField(ctx), recorded: false, enabled };- }- return {- vault_path: vaultPathField(ctx),- recorded: true,- enabled,- id: post.outcome.id,- sample_id: sampleId,- first_pass_success: firstPassSuccess,- // The kernel's reading of this sample, surfaced so a contradicted- // claim is visible to the poster and not only to a later reader.- // Absent when the evidence half fail-opened - reporting a verdict- // that was never written would be the fallback this project bans.- ...(post.evidence !== null ? { evidence: post.evidence.payload } : {}),- };- }-- const filter = contextPackOutcomeFilter(args);- if (operation === "list") {- const records = listContextPackOutcomes(ctx.vault, filter);- return { vault_path: vaultPathField(ctx), total: records.length, records };- }- if (operation === "summary") {- return { vault_path: vaultPathField(ctx), ...summarizeContextPackOutcomes(ctx.vault, filter) };- }- throw unknownOperationError(- "brain_context_pack_outcome: operation must be post, list, or summary",- );-}--/**- * The correlation keys a `post` records, read from the caller's arguments.- *- * `agent_id` is the ACTING agent, and it is an ARGUMENT rather than- * `ServerContext.agentName` deliberately. That getter resolves the plugin- * config on every access and RAISES on a config that is present but- * unreadable - correctly, since the alternative is writing under a guessed- * identity - so consulting it here would let one broken line in an- * unrelated file turn a working telemetry post into a tool error. The- * identity a client asserts is exactly as self-asserted as the one the- * config holds and costs nothing when the config is broken, so it is the- * one this row carries. Omitted stays omitted: no identity is invented.- */-function contextPackOutcomeCorrelation(args: Record<string, unknown>): {- host?: string;- sessionId?: string;- turnId?: string;- agentId?: string;-} {- const host = optionalStringArg("brain_context_pack_outcome", args, "host");- const sessionId = optionalStringArg("brain_context_pack_outcome", args, "session_id");- const turnId = optionalStringArg("brain_context_pack_outcome", args, "turn_id");- const agentId = optionalStringArg("brain_context_pack_outcome", args, "agent_id");- return {- ...(host !== undefined ? { host } : {}),- ...(sessionId !== undefined ? { sessionId } : {}),- ...(turnId !== undefined ? { turnId } : {}),- ...(agentId !== undefined ? { agentId } : {}),- };-}--/**- * The acting agent's assertion about the sample, coerced at the tool- * boundary. A malformed member is REFUSED here rather than dropped: a- * claim silently discarded would land an evidence record reading- * `unclaimed`, which asserts the agent said nothing when in fact it said- * something unusable.- */-function contextPackEvidenceClaim(raw: unknown): ContextPackEvidenceClaim | undefined {- if (raw === undefined || raw === null) return undefined;- if (typeof raw !== "object" || Array.isArray(raw)) {- throw new MCPError(- INVALID_PARAMS,- "brain_context_pack_outcome: evidence_claim must be an object",- );- }- const claim = raw as Record<string, unknown>;- const finalTextHash = optionalStringArg(- "brain_context_pack_outcome",- claim,- CONTEXT_PACK_EVIDENCE_FIELD.finalTextHash,- );- const itemCount = coerceNonNegativeInteger(- "brain_context_pack_outcome",- CONTEXT_PACK_EVIDENCE_FIELD.itemCount,- claim[CONTEXT_PACK_EVIDENCE_FIELD.itemCount],- );- const finalTextChars = coerceNonNegativeInteger(- "brain_context_pack_outcome",- CONTEXT_PACK_EVIDENCE_FIELD.finalTextChars,- claim[CONTEXT_PACK_EVIDENCE_FIELD.finalTextChars],- );- if (finalTextHash === undefined && itemCount === undefined && finalTextChars === undefined) {- return undefined;- }- return {- ...(finalTextHash !== undefined ? { finalTextHash } : {}),- ...(itemCount !== undefined ? { itemCount } : {}),- ...(finalTextChars !== undefined ? { finalTextChars } : {}),- };-}--function contextPackOutcomeFilter(args: Record<string, unknown>): ContextPackOutcomeFilter {- const host = optionalStringArg("brain_context_pack_outcome", args, "host");- const sampleId = optionalStringArg("brain_context_pack_outcome", args, "sample_id");- const since = optionalStringArg("brain_context_pack_outcome", args, "since");- const until = optionalStringArg("brain_context_pack_outcome", args, "until");- const limit = coercePositiveInteger("brain_context_pack_outcome", "limit", args["limit"]);- const maxSamples = coercePositiveInteger(- "brain_context_pack_outcome",- "max_samples",- args["max_samples"],- );- return {- ...(host !== undefined ? { host } : {}),- ...(sampleId !== undefined ? { sampleId } : {}),- ...(since !== undefined ? { since } : {}),- ...(until !== undefined ? { until } : {}),- ...(limit !== undefined ? { limit } : {}),- ...(maxSamples !== undefined ? { maxSamples } : {}),- };-}--function coerceBoolean(raw: unknown): boolean | undefined {- if (raw === undefined || raw === null) return undefined;- if (typeof raw === "boolean") return raw;- if (raw === "true") return true;- if (raw === "false") return false;- throw new MCPError(- INVALID_PARAMS,- "brain_context_pack_outcome: boolean fields must be true or false",- );-}--// ----- brain_knowledge_gaps (t_97091fff) -------------------------------------async function toolBrainKnowledgeGaps(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const since = optionalStringArg("brain_knowledge_gaps", args, "since");- const until = optionalStringArg("brain_knowledge_gaps", args, "until");- const minOccurrences = coercePositiveInteger(- "brain_knowledge_gaps",- "min_occurrences",- args["min_occurrences"],- );- const limit = coercePositiveInteger("brain_knowledge_gaps", "limit", args["limit"]);- const maxSatisfaction = coerceUnitInterval("max_satisfaction", args["max_satisfaction"]);- const report = aggregateQueryDemand(ctx.vault, {- ...(since !== undefined ? { since } : {}),- ...(until !== undefined ? { until } : {}),- ...(minOccurrences !== undefined ? { minOccurrences } : {}),- ...(maxSatisfaction !== undefined ? { maxSatisfaction } : {}),- ...(limit !== undefined ? { limit } : {}),- });- return { vault_path: vaultPathField(ctx), ...serializeQueryDemandReport(report) };-}--function coerceUnitInterval(name: string, raw: unknown): number | undefined {- if (raw === undefined || raw === null) return undefined;- if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 0 || raw > 1) {- throw new MCPError(INVALID_PARAMS, `brain_knowledge_gaps: ${name} must be a number in [0, 1]`);- }- return raw;-}--// ----- brain_context_presets ------------------------------------------------async function toolBrainSessionGrep(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- // Coverage-first selection (t_2c2a883c) rides this tool as an explicit- // operation; omitted (the default) is the historical grep, byte-identical.- const operation = args["operation"] ?? "match";- if (operation === "coverage") return toolBrainSessionGrepCoverage(ctx, args);- if (operation !== "match") {- // The dispatch contract (surface-error-codes census): every tool whose- // schema declares a dispatch enum answers an unknown value with the- // shared `unknown_operation` code, message unchanged.- throw unknownOperationError("brain_session_grep: operation must be 'match' or 'coverage'");- }- if (args["char_budget"] !== undefined) {- throw new MCPError(- INVALID_PARAMS,- "brain_session_grep: char_budget is not applicable to operation 'match'; it sizes the coverage selection",- );- }- if (args["entity_key"] !== undefined) {- throw new MCPError(- INVALID_PARAMS,- "brain_session_grep: entity_key is not applicable to operation 'match'; it seeds the coverage fan-out",- );- }- const limit = coercePositiveInteger("brain_session_grep", "limit", args["limit"]);- const snippetChars = coercePositiveInteger(- "brain_session_grep",- "snippet_chars",- args["snippet_chars"],- );- // Conversation-chronology bounds (S1): `since` / `before` parse through- // the shared time-range grammar (ISO date/datetime, today/yesterday,- // <n>h/<n>d/<n>w) via the shared time-bounds wrapper. `before` maps- // onto the range's inclusive upper edge.- const since = optionalStringArg("brain_session_grep", args, "since");- const before = optionalStringArg("brain_session_grep", args, "before");- const bounds = resolveTimeBounds(since, before);- // Inline-raw disclosure (C2): opt-in flag inlines the raw captures beside- // each derived record and stamps an extracted discriminator. Omitted, the- // response stays byte-identical.- const includeRaw = args["include_raw"] === true;- const rawBudgetChars = coercePositiveInteger(- "brain_session_grep",- "raw_budget_chars",- args["raw_budget_chars"],- );- // The matches are a deterministic ranked walk (score, then id), so the- // page is cut here over the full hit set: `total` counts every match- // across pages and `next_cursor` continues the walk (null when- // exhausted). Absent `limit`, the page is the historical bounded- // default (DEFAULT_LIMIT in session-recall.ts) - an unpaginated call- // used to answer 10 hits, not every hit in the vault.- //- // The search below NEVER runs with includeRaw: decoration reads the- // record set once per hit decorated, so decorating the full match set- // on every page made a cursor walk O(N^2). The page is cut first and- // only its items are decorated.- const offset = cursorOffsetArg("brain_session_grep", args);- const sessionIdArg = optionalStringArg("brain_session_grep", args, "session_id");- const hits = searchSessionRecall(ctx.vault, {- query: requiredStringArg("brain_session_grep", args, "query"),- ...withheldAtRemoteReach(ctx),- ...(sessionIdArg !== undefined ? { sessionId: sessionIdArg } : {}),- limit: Number.MAX_SAFE_INTEGER,- ...(snippetChars !== undefined ? { snippetChars } : {}),- ...(bounds.sinceMs !== null ? { sinceMs: bounds.sinceMs } : {}),- ...(bounds.untilMs !== null ? { untilMs: bounds.untilMs } : {}),- ...(rawBudgetChars !== undefined ? { rawBudgetChars } : {}),- });- const page = pageSlice(hits.hits, offset, limit ?? SESSION_RECALL_DEFAULT_LIMIT);- if (!includeRaw) {- return { hits: page.items, total: page.total, next_cursor: page.next_cursor };- }- return {- hits: decorateSessionRecallHits(ctx.vault, page.items, {- ...withheldAtRemoteReach(ctx),- ...(sessionIdArg !== undefined ? { sessionId: sessionIdArg } : {}),- ...(rawBudgetChars !== undefined ? { rawBudgetChars } : {}),- }),- total: page.total,- next_cursor: page.next_cursor,- };-}--/**- * The coverage operation of `brain_session_grep` (t_2c2a883c): the- * coverage-first thread selection over the lineage-scoped record set,- * fanning out under the adaptive topic budget and the caller's- * `char_budget`, returning the selected turns chronologically beside the- * selection diagnostics. The typed floor-violation infeasibility maps to- * INVALID_PARAMS - a budget that cannot hold the floor-weighted- * selection is a caller error, named so it can be retried, never a- * silent truncation.- */-function toolBrainSessionGrepCoverage(- ctx: ServerContext,- args: Record<string, unknown>,-): Record<string, unknown> {- if (args["query"] !== undefined) {- throw new MCPError(- INVALID_PARAMS,- "brain_session_grep: operation 'coverage' selects whole topics; it takes no `query`",- );- }- for (const inapplicable of [- "since",- "before",- "limit",- "snippet_chars",- "include_raw",- "raw_budget_chars",- "cursor",- ] as const) {- if (args[inapplicable] !== undefined) {- throw new MCPError(- INVALID_PARAMS,- `brain_session_grep: ${inapplicable} is not applicable to operation 'coverage'; it pages, sizes or filters the match operation`,- );- }- }- const charBudget = coercePositiveInteger(- "brain_session_grep",- "char_budget",- args["char_budget"],- );- if (charBudget === undefined) {- throw new MCPError(- INVALID_PARAMS,- "brain_session_grep: char_budget is required for the coverage operation",- );- }- const sessionId = optionalStringArg("brain_session_grep", args, "session_id");- // The miner's own cap: mined keys run to MINED_KEY_MAX_LENGTH, so a- // 129-200 character URL or path key must be able to seed coverage here.- const entityKey = optionalStringArg(- "brain_session_grep",- args,- "entity_key",- MINED_KEY_MAX_LENGTH,- );- let result;- try {- result = coverageSessionRecall(ctx.vault, {- ...withheldAtRemoteReach(ctx),- ...(sessionId !== undefined ? { sessionId } : {}),- ...(entityKey !== undefined ? { entityKey } : {}),- charBudget,- });- } catch (err) {- if (err instanceof SessionCoverageInfeasibleError) {- throw new MCPError(INVALID_PARAMS, err.message);- }- if (err instanceof SessionCoverageEntityUnknownError) {- throw new MCPError(INVALID_PARAMS, err.message);- }- throw err;- }- return { ...result };-}--/**- * Private continuity rows are session data a remote caller does not get:- * the recall tools answer about them exactly as about a row that does not- * exist. A local caller keeps every row.- */-function withheldAtRemoteReach(ctx: ServerContext): { withholdPrivate?: true } {- return contextReach(ctx) === TRANSPORT_REACH.local ? {} : { withholdPrivate: true };-}--async function toolBrainSessionDescribe(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- return {- ...describeSessionRecall(ctx.vault, {- sessionId: requiredStringArg("brain_session_describe", args, "session_id"),- ...withheldAtRemoteReach(ctx),- ...(args["topics"] === true ? { topics: true } : {}),- }),- };-}--async function toolBrainSessionExpand(- ctx: ServerContext,- args: Record<string, unknown>,-): Promise<Record<string, unknown>> {- const payloadRef = optionalStringArg("brain_session_expand", args, "payload");- if (payloadRef !== undefined) return expandPayload(ctx, args, payloadRef);- const rawLimit = coercePositiveInteger("brain_session_expand", "raw_limit", args["raw_limit"]);- return {- ...expandSessionRecall(ctx.vault, {- id: requiredStringArg("brain_session_expand", args, "id"),- ...withheldAtRemoteReach(ctx),- ...(rawLimit !== undefined ? { rawLimit } : {}),- ...(optionalStringArg("brain_session_expand", args, "cursor") !== undefined- ? { cursor: optionalStringArg("brain_session_expand", args, "cursor") }- : {}),- }),- };-}--/**- * Page one externalized payload (t_35440e83) - the `payload` mode of- * `brain_session_expand`.- *- * Payloads only ever come out of session import, so expanding a- * placeholder found in a recalled turn is the same act as expanding the- * turn: one more level of "give me the exact source". Riding this tool- * rather than adding one keeps the tool budget and every profile that- * already carries the session tools unchanged.- *- * Reach: a local caller reads any stored payload. A REMOTE caller reads- * one only when a non-private session turn references it, directly or- * through another remotely readable payload (`payload-inventory.ts`).- * Pages grant nothing: a page can be written by tools a session turn- * cannot. A payload referenced only from a private row or a page, and an- * orphan nobody references, answer the same refusal, so a remote caller- * cannot use the difference to probe what exists.- */-function expandPayload(- ctx: ServerContext,- args: Record<string, unknown>,- ref: string,-): Record<string, unknown> {- if (args["id"] !== undefined || args["raw_limit"] !== undefined) {- throw new MCPError(- INVALID_PARAMS,- "brain_session_expand: `payload` pages one payload ref; it cannot be combined with `id` or `raw_limit`",- );- }- let sha256: string;- try {- sha256 = payloadIdFromRef(ref);- } catch (err) {- if (err instanceof PayloadRefError) throw new MCPError(INVALID_PARAMS, err.message);- throw err;- }- if (- contextReach(ctx) !== TRANSPORT_REACH.local &&- !isPayloadRemotelyReadable(ctx.vault, sha256)- ) {- throw new MCPError(- INVALID_PARAMS,- `brain_session_expand: payload ${ref} is not readable at remote reach - no non-private ` +- "session turn references it",- );- }- const cursor = optionalStringArg("brain_session_expand", args, "cursor");- const offset = cursor === undefined ? 0 : Number.parseInt(cursor, 10);- if (cursor !== undefined && (!/^[0-9]+$/.test(cursor) || !Number.isFinite(offset))) {- throw new MCPError(- INVALID_PARAMS,- "brain_session_expand: a payload cursor is the next_cursor of a previous page",- );- }- const limit =- coercePositiveInteger("brain_session_expand", "payload_chars", args["payload_chars"]) ??- DEFAULT_PAYLOAD_PAGE_CHARS;- try {- const page = new PayloadRegistry({ vault: ctx.vault, maxInlineChars: 1 }).get(ref, {- offset,- limit,- });- return {- payload: {- ref: page.ref,- offset: page.offset,- limit: page.limit,- total_chars: page.totalChars,- content: page.content,- },- next_cursor: page.nextOffset === null ? null : String(page.nextOffset),- };- } catch (err) {- if (err instanceof PayloadNotFoundError) throw new MCPError(INVALID_PARAMS, err.message);- throw err;- }-}--// ----- brain_pre_compress_pack (v0.20.0) -----------------------------------+ toolBrainSessionDescribe,+ toolBrainSessionExpand,+ toolBrainSessionGrep,+} from "./recall-session-tools.ts";export const RECALL_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{diff --git a/src/mcp/resources-backlink-readers.ts b/src/mcp/resources-backlink-readers.tsnew file mode 100644index 00000000..a3e868a4--- /dev/null+++ b/src/mcp/resources-backlink-readers.ts@@ -0,0 +1,95 @@+/**+ * The backlinks reader of the `osb://` surface (task 3.19), with the+ * markdown renderer it answers through. Split from `resources.ts`;+ * dispatch happens through that module's `readResource`.+ */++import { buildBacklinkIndex } from "../core/brain/backlinks.ts";+import type { BacklinkRef } from "../core/brain/backlinks.ts";+import { normaliseWikilinkTarget } from "../core/brain/wikilink.ts";+import { recordRefs } from "../core/brain/log-events-at-reach.ts";+import { deliveryRelForBrainArtifact, UNPROBED_DELIVERY_REL } from "./brain/reach-events.ts";+import { INVALID_PARAMS, MCPError } from "./protocol.ts";+import type { RequestView, ResourceContent, ResourceContext } from "./resources-shared.ts";+import { MIME_MARKDOWN, deliveryFor } from "./resources-shared.ts";++export function readBacklinks(+ ctx: ResourceContext,+ uri: string,+ rawId: string,+ view: RequestView,+): ResourceContent {+ if (!rawId.trim()) {+ throw new MCPError(INVALID_PARAMS, `backlinks target must not be empty: ${uri}`);+ }+ // Normalise to the same form the index keys use so `[[pref-foo]]`,+ // `pref-foo`, and `Brain/preferences/pref-foo.md` all resolve.+ const target = normaliseWikilinkTarget(rawId);+ // The last unscoped `buildBacklinkIndex` call in the product. Every+ // ref it yields names its SOURCE artifact by id, so an unscoped index+ // here published the same list `brain_backlinks` had already learned+ // to withhold.+ //+ // A hidden TARGET answers exactly as an ABSENT one does - the empty+ // backlink document - rather than refusing: this reader has no+ // not-found path at all (an unknown target is a legitimate zero), so a+ // refusal here would be the one response shape that proves the page+ // exists. The echoed target is the caller's own argument.+ const index = buildBacklinkIndex(ctx.vault, view.ownerScope, {+ withholdsPrivate: view.refs.withholdsPrivate === true,+ });+ // Every spelling the target answers to across its retirement: a+ // retired reserved record is otherwise asked as `pref-x`, which names+ // no page once `ret-x` is the one on disk.+ const targetVisible = view.refs.row(...recordRefs(target));+ const refs = targetVisible+ ? (index.get(target) ?? []).filter((ref) => view.refs.visible(ref.source))+ : [];+ return {+ uri,+ mimeType: MIME_MARKDOWN,+ // The rendered document is derived from stored pages (delivery-trust,+ // lane A): fenced at remote reach, named for the TARGET page's own+ // derived provenance; local keeps the bytes. A withheld target probes+ // the guaranteed-absent page instead: reading a hidden target's real+ // stamps would name its existence and its channel through the fence's+ // origin label, while an absent one reads as unverified - the two+ // answers must stay identical.+ text: deliveryFor(ctx, view).shape(+ renderBacklinksMarkdown(target, refs),+ targetVisible ? deliveryRelForBrainArtifact(ctx.vault, target) : UNPROBED_DELIVERY_REL,+ ),+ };+}++export function renderBacklinksMarkdown(target: string, refs: ReadonlyArray<BacklinkRef>): string {+ const lines: string[] = [];+ lines.push(`# Backlinks to \`${target}\``);+ lines.push("");+ lines.push(`Total inbound references: ${refs.length}`);+ lines.push("");+ if (refs.length === 0) {+ lines.push("_No inbound references found._");+ return lines.join("\n") + "\n";+ }+ // Group by source-kind so the reader sees structure rather than a+ // flat list — the same source kind (e.g. multiple log apply-evidence+ // events) clusters together.+ const byKind = new Map<string, BacklinkRef[]>();+ for (const r of refs) {+ const arr = byKind.get(r.sourceKind) ?? [];+ arr.push(r);+ byKind.set(r.sourceKind, arr);+ }+ for (const [kind, group] of byKind) {+ lines.push(`## ${kind} (${group.length})`);+ lines.push("");+ for (const r of group) {+ const suffix = r.timestamp ? ` — ${r.timestamp}` : "";+ lines.push(`- \`${r.source}\` (field: \`${r.field}\`)${suffix}`);+ }+ lines.push("");+ }+ while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();+ return lines.join("\n") + "\n";+}diff --git a/src/mcp/resources-digest-readers.ts b/src/mcp/resources-digest-readers.tsnew file mode 100644index 00000000..63ba77d9--- /dev/null+++ b/src/mcp/resources-digest-readers.ts@@ -0,0 +1,224 @@+/**+ * The compiled-digest readers of the `osb://` surface (task 3.19): the+ * active preferences, the lessons, the latest digest and the status+ * projection, with the status renderer and the vault-relative paths of+ * the two generated files the delivery binding names. Split from+ * `resources.ts`; dispatch happens through that module's `readResource`.+ */++import { existsSync } from "node:fs";+import {+ activeDigestPathForRead,+ readActiveForReader,+ regenerateActive,+} from "../core/brain/active.ts";+import {+ lessonsDigestPathForRead,+ regenerateLessons,+ renderLessonsForReader,+} from "../core/brain/lessons.ts";+import { renderDigest } from "../core/brain/digest.ts";+import {+ computeBrainStatus,+ MAINTENANCE_DEBT_STATUS,+ type BrainStatusSnapshot,+} from "../core/brain/status.ts";+import { BRAIN_ACTIVE_FILE, BRAIN_LESSONS_FILE, BRAIN_ROOT_REL } from "../core/brain/paths.ts";+import { TRANSPORT_REACH, resolvedTransportReach } from "../core/graph/transport-reach.ts";+import { INTERNAL_ERROR, MCPError } from "./protocol.ts";+import type { RequestView, ResourceContent, ResourceContext } from "./resources-shared.ts";+import { MIME_MARKDOWN, deliveryFor, readMarkdown } from "./resources-shared.ts";++/**+ * Vault-relative paths of the two generated digest files, the probes the+ * delivery binding names when one of them is what a reader delivers+ * (delivery-trust, lane A). The files are the system's own render, so+ * the derivation reads THEIR absence of stamps rather than guessing.+ */+export const ACTIVE_REL = `${BRAIN_ROOT_REL}/${BRAIN_ACTIVE_FILE}`;+export const LESSONS_REL = `${BRAIN_ROOT_REL}/${BRAIN_LESSONS_FILE}`;++export function readActive(ctx: ResourceContext, uri: string, view: RequestView): ResourceContent {+ // On a store-only machine the digest is rendered on demand into the+ // device-local cache (D14 item 7); a render failure is reported below.+ let path: string;+ try {+ path = activeDigestPathForRead(ctx.vault);+ } catch (err) {+ throw new MCPError(INTERNAL_ERROR, `active digest render failed: ${(err as Error).message}`);+ }+ // First read attempt: the file usually exists because dream+ // regenerates it. On a fresh vault that has never been dreamed, the+ // file may not exist yet — generate it on demand so the resource is+ // always meaningful. We do NOT auto-generate on every read (that+ // would shift expensive work onto a hot path); only on the first+ // read of a missing file.+ if (!existsSync(path)) {+ try {+ regenerateActive(ctx.vault);+ } catch (err) {+ throw new MCPError(+ INTERNAL_ERROR,+ `active-preferences digest not present and on-demand regeneration failed: ${(err as Error).message}`,+ );+ }+ }+ // The shared file is served as it is to a local reader with no owner+ // scope; any other reader gets the in-memory render, stamped with the+ // generation on disk (see `readActiveForReader`).+ const text = readActiveForReader(ctx.vault, {+ ...(view.refs.filtersNothing ? {} : { readable: view.refs.visible }),+ ...(view.ownerScope !== null ? { agentScope: view.ownerScope } : {}),+ restricted: view.reach !== TRANSPORT_REACH.local,+ });+ return {+ uri,+ mimeType: MIME_MARKDOWN,+ // The digest quotes stored principles (delivery-trust, lane A): the+ // delivery is fenced at remote reach, named for the generated file's+ // own absence of stamps - the system's render is not operator prose,+ // and the derivation says so rather than guessing authorship.+ text: deliveryFor(ctx, view).shape(text, ACTIVE_REL),+ };+}++export function readLessons(ctx: ResourceContext, uri: string, view: RequestView): ResourceContent {+ let path: string;+ try {+ path = lessonsDigestPathForRead(ctx.vault);+ } catch (err) {+ throw new MCPError(INTERNAL_ERROR, `lessons digest render failed: ${(err as Error).message}`);+ }+ // Same on-demand-on-first-miss policy as readActive: a fresh vault+ // that has never been dreamed has no lessons.md yet — generate it+ // once so the resource is always meaningful, but never on every read.+ if (!existsSync(path)) {+ try {+ regenerateLessons(ctx.vault);+ } catch (err) {+ throw new MCPError(+ INTERNAL_ERROR,+ `lessons digest not present and on-demand regeneration failed: ${(err as Error).message}`,+ );+ }+ }+ // A local reader with no owner scope is served the shared file as it+ // is; any other reader gets the digest rendered without the records it+ // cannot see, scored and stamped at the generation on disk. Either way+ // the delivered markdown is the lessons corpus quoting stored+ // principles (delivery-trust, lane A): fenced at remote reach, named+ // for the generated file's own absence of stamps.+ const delivery = deliveryFor(ctx, view);+ const text = view.refs.filtersNothing+ ? readMarkdown(uri, path).text+ : renderLessonsForReader(ctx.vault, {+ readable: view.refs.visible,+ ...(view.refs.withholdsPrivate === true ? { withholdsPrivate: true } : {}),+ }).document;+ return { uri, mimeType: MIME_MARKDOWN, text: delivery.shape(text, LESSONS_REL) };+}++export function readDigestLatest(+ ctx: ResourceContext,+ uri: string,+ view: RequestView,+): ResourceContent {+ const rendered = renderDigest(ctx.vault, {+ format: "markdown",+ ...(view.refs.filtersNothing ? {} : { readable: view.refs.visible }),+ ...(view.refs.withholdsPrivate === true ? { withholdsPrivate: true } : {}),+ // Ownership is pushed into the render's SELECTION as well as its+ // row filter, the way `readActive` does: `view.refs` already+ // carries the rule on the filter side, and the digest's+ // vault-wide sections (the maintenance actions) are scoped by the+ // render itself rather than by which rows an id happens to name.+ ...(view.ownerScope !== null ? { agentScope: view.ownerScope } : {}),+ });+ return {+ uri,+ mimeType: MIME_MARKDOWN,+ // The digest quotes stored principles (delivery-trust, lane A) in the+ // same render family as the active and lessons digests, so it shapes+ // through the same binding: fenced at remote reach, named for the+ // compiled-digest render's own absence of stamps - the system's voice+ // is not operator prose, and the derivation says so rather than+ // guessing authorship. The probe rel names that family's on-disk+ // member (BRAIN_COMPILED_DIGEST_RELS), whose generated page carries+ // no stamps, the exact probe readActive's render makes.+ text: deliveryFor(ctx, view).shape(rendered.content, ACTIVE_REL),+ };+}++export function readStatus(ctx: ResourceContext, uri: string): ResourceContent {+ const snapshot = computeBrainStatus(ctx.vault, {+ withholdsPrivate: resolvedTransportReach(ctx.reach) !== TRANSPORT_REACH.local,+ });+ return {+ uri,+ mimeType: MIME_MARKDOWN,+ text: renderStatusMarkdown(snapshot),+ };+}++/**+ * Render the topic-query result as a compact markdown document. Kept+ * here (not in `query.ts`) because the markdown shape is a+ * resource-surface concern; callers that want the structured form can+ * still invoke `queryByTopic` directly.+ */+export function renderStatusMarkdown(s: BrainStatusSnapshot): string {+ const lines: string[] = [];+ lines.push("# Brain status");+ lines.push("");+ if (!s.present) {+ lines.push("_Brain layer not present in this vault. Run `o2b brain init` first._");+ return lines.join("\n") + "\n";+ }+ lines.push("## Counts");+ lines.push("");+ lines.push(+ `- inbox: ${s.counts.inbox} (processed: ${s.counts.inbox_processed}, ` ++ `archived: ${s.counts.inbox_archived})`,+ );+ lines.push(`- preferences: ${s.counts.preferences}`);+ for (const [status, n] of Object.entries(s.counts.preferences_by_status).toSorted()) {+ lines.push(` - ${status}: ${n}`);+ }+ lines.push(`- retired: ${s.counts.retired}`);+ lines.push(`- log days: ${s.counts.log_days}`);+ lines.push(`- snapshots: ${s.counts.snapshots}`);+ lines.push("");+ lines.push("## Activity");+ lines.push("");+ lines.push(`- last dream: ${s.last_dream_at ?? "_(never)_"}`);+ lines.push(`- last apply-evidence: ${s.last_apply_evidence_at ?? "_(never)_"}`);+ lines.push("");+ lines.push("## Maintenance debt");+ lines.push("");+ const debtCount = s.maintenance_debt.log_events_since_dream;+ const debtNoun = debtCount === 1 ? "log event" : "log events";+ if (s.maintenance_debt.status === MAINTENANCE_DEBT_STATUS.neverDreamed) {+ lines.push(`- never dreamed — ${debtCount} ${debtNoun} recorded since inception`);+ } else if (s.maintenance_debt.status === MAINTENANCE_DEBT_STATUS.undercounted) {+ // The figure is a floor: at least one shard in the window would not+ // read or would not parse. Printing it as a count would be the+ // partial walk presented as a total.+ lines.push(+ `- at least ${debtCount} ${debtNoun} since the last dream — a log shard could not be ` ++ "read in full, so this is a lower bound",+ );+ } else {+ lines.push(`- ${debtCount} ${debtNoun} since the last dream`);+ }+ lines.push("");+ if (s.sanity.signals_awaiting_dream > 0) {+ lines.push("## Sanity");+ lines.push("");+ lines.push(+ `- **${s.sanity.signals_awaiting_dream}** signal(s) in inbox/ predate the unconfirmed_window — run \`o2b brain dream\`.`,+ );+ lines.push("");+ }+ while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();+ return lines.join("\n") + "\n";+}diff --git a/src/mcp/resources-record-readers.ts b/src/mcp/resources-record-readers.tsnew file mode 100644index 00000000..ef389826--- /dev/null+++ b/src/mcp/resources-record-readers.ts@@ -0,0 +1,376 @@+/**+ * The record readers of the `osb://` surface (task 3.19): one+ * preference, one topic, one log day, each answered at the caller's+ * reach, with the topic and status markdown renderers and the topic+ * objection section. Split from `resources.ts`; dispatch happens+ * through that module's `readResource`.+ */++import { storeMemoryPageAt } from "../core/brain/memory-pages.ts";+import { logDayReader } from "../core/brain/log-days.ts";+import { vaultRelative } from "../core/path-safety.ts";+import { formatFrontmatter } from "../core/vault.ts";+import { readFileSync } from "node:fs";+import { listLogMarkdownFiles } from "../core/brain/log-jsonl.ts";+import {+ preferencePath,+ retiredPath,+ validateIsoDate,+ validateSlug,+ BRAIN_PREFERENCES_REL,+} from "../core/brain/paths.ts";+import { BrainNotFoundError, queryByPreference, queryByTopic } from "../core/brain/query.ts";+import { type ArtifactRefView } from "../core/brain/artifact-ref-view.ts";+import { logEntriesAtReach, recordRefs } from "../core/brain/log-events-at-reach.ts";+import {+ parseLogDayFile,+ renderLogDayHeader,+ renderLogEntryBlock,+ type ParseLogDayResult,+} from "../core/brain/log.ts";+import type { BrainPreference, BrainRetired } from "../core/brain/types.ts";+import { deliveryRelForBrainArtifact, signalDeliveryRel } from "./brain/reach-events.ts";+import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "./protocol.ts";+import type { RequestView, ResourceContent, ResourceContext } from "./resources-shared.ts";+import { MIME_MARKDOWN, deliveryFor, notFound, readMarkdown } from "./resources-shared.ts";++export function readPreference(+ ctx: ResourceContext,+ uri: string,+ rawId: string,+ view: RequestView,+): ResourceContent {+ if (!rawId.trim()) {+ throw new MCPError(INVALID_PARAMS, `resource id must not be empty: ${uri}`);+ }+ // Accept `pref-foo`, `ret-foo`, or the bare slug. Strip the prefix+ // (if any) for `validateSlug` — that helper rejects `..` traversal+ // and other shape problems with a clear INVALID_PARAMS-shaped+ // message, which is a better diagnosis than a downstream+ // "not found" error. The prefixed form is then handed to+ // queryByPreference, which handles the active → retired fallback.+ const slug = rawId.startsWith("pref-")+ ? rawId.slice("pref-".length)+ : rawId.startsWith("ret-")+ ? rawId.slice("ret-".length)+ : rawId;+ try {+ validateSlug(slug);+ } catch (err) {+ throw new MCPError(INVALID_PARAMS, (err as Error).message);+ }+ const normalized =+ rawId.startsWith("pref-") || rawId.startsWith("ret-") ? rawId : `pref-${rawId}`;+ // Asked before the page is parsed: a withheld page that fails to parse+ // would otherwise answer with the parser's error, which names the page+ // an absent id never could.+ if (!view.refs.row(...recordRefs(normalized))) throw notFound(normalized);+ let result;+ try {+ result = queryByPreference(ctx.vault, normalized);+ } catch (err) {+ if (err instanceof BrainNotFoundError) {+ throw new MCPError(INTERNAL_ERROR, err.message);+ }+ throw err;+ }+ // queryByPreference returns the parsed object but not its path; we+ // re-derive the path from the resolved id so we can hand back the+ // raw markdown body (the resource contract is "give me the file",+ // not "give me a structured projection").+ const resolvedId = result.preference.id;+ const resolvedSlug = resolvedId.startsWith("pref-")+ ? resolvedId.slice("pref-".length)+ : resolvedId.slice("ret-".length);+ const filePath = resolvedId.startsWith("pref-")+ ? preferencePath(ctx.vault, resolvedSlug)+ : retiredPath(ctx.vault, resolvedSlug);+ // The whole file, `owner:` line and body prose included, is what this+ // reader hands back - so the ownership question is asked before the+ // read, not filtered out of the bytes afterwards.+ //+ // `normalized`, not `rawId`: the absent branch above rethrows what+ // `queryByPreference` threw, and that names the NORMALISED id. This+ // reader accepts the bare slug too, so echoing the raw one here made+ // `osb://preference/acme` answer "...for id 'acme'" when the page+ // existed and was withheld, against "...for id 'pref-acme'" when it did+ // not - the presence of the prefix a one-bit existence oracle over the+ // whole reserved population.+ if (!view.refs.visible(resolvedId)) throw notFound(normalized);+ // On a store-only machine the page is the one the fold rebuilds (task 2.10).+ const stored = storeMemoryPageAt(ctx.vault, vaultRelative(filePath, ctx.vault));+ const file =+ stored === null+ ? readMarkdown(uri, filePath)+ : { uri, mimeType: MIME_MARKDOWN, text: formatFrontmatter(...stored.read()) };+ return {+ ...file,+ // The whole file - frontmatter and body - is the delivery+ // (delivery-trust, lane A): fenced at remote reach through the+ // binding, named for the page's own derived provenance; local keeps+ // the bytes. The probe asks the RESOLVED page - the id the+ // active-to-retired fallback answered - never the caller's spelling.+ text: deliveryFor(ctx, view).shape(+ file.text,+ deliveryRelForBrainArtifact(ctx.vault, resolvedId),+ ),+ };+}++export function readTopic(+ ctx: ResourceContext,+ uri: string,+ rawSlug: string,+ view: RequestView,+): ResourceContent {+ if (!rawSlug.trim()) {+ throw new MCPError(INVALID_PARAMS, `topic slug must not be empty: ${uri}`);+ }+ validateSlug(rawSlug);+ let result;+ try {+ // The scope reaches the SELECTION, not the result: a topic resolves+ // to one preference and several may carry it, so filtering afterwards+ // would report the topic as having no rule whenever another owner's+ // preference happened to sort first.+ result = queryByTopic(ctx.vault, rawSlug, {+ ownerScope: view.ownerScope,+ transportReach: view.reach,+ });+ } catch (err) {+ if (err instanceof BrainNotFoundError) {+ throw new MCPError(INTERNAL_ERROR, err.message);+ }+ throw err;+ }+ // The two remaining owner-bearing streams, filtered before the+ // renderer sees them: each signal row names its id and its author, and+ // the log rows are the same events `brain_event_trace` filters. A+ // topic whose ONLY rule is one this caller may not see is reported as+ // a topic with no rule, not as a topic that refused - the renderer+ // already has that shape for a topic that never reached promotion.+ const scoped = Object.freeze({+ ...result,+ signals: view.refs.keep(result.signals, (s) => [s.id]),+ all_log_events: logEntriesAtReach(view.refs, result.all_log_events),+ });+ // The synthesis is composed from spans shaped at the page each span+ // quotes (delivery-trust, lane A): the body under the governing+ // preference page's provenance - a topic with no current rule probes+ // the page that would hold it, the absent-page fail-closed answer -+ // and the objection block under the page ITS text quotes, because the+ // strongest objection may quote an agent-authored counter-signal+ // whose page is not the page that decided the body's treatment.+ const delivery = deliveryFor(ctx, view);+ const preferenceRel = result.preference+ ? deliveryRelForBrainArtifact(ctx.vault, result.preference.id)+ : `${BRAIN_PREFERENCES_REL}/pref-${rawSlug}.md`;+ const objection = topicObjectionSection(ctx.vault, scoped);+ let text: string;+ if (objection.rel === null) {+ // The block quotes the governing preference itself (or no page at+ // all): one document, one probe. The trailing newline keeps the+ // unfenced bytes identical to the pre-shaping document.+ text = delivery.shape(+ `${renderTopicMarkdown(rawSlug, scoped)}\n${objection.text}\n`,+ preferenceRel,+ );+ } else {+ text =+ `${delivery.shape(renderTopicMarkdown(rawSlug, scoped), preferenceRel)}\n` ++ `${delivery.shape(objection.text, objection.rel)}\n`;+ }+ return { uri, mimeType: MIME_MARKDOWN, text };+}++export function readLog(+ ctx: ResourceContext,+ uri: string,+ rawDate: string,+ view: RequestView,+): ResourceContent {+ validateIsoDate(rawDate);+ // Per-device shards (Memory Integrity Suite): a day's human view can+ // span several markdown files. The legacy single file is returned+ // verbatim (byte-identical to pre-shard behaviour); multiple shards+ // are concatenated in shard order.+ // A store-only machine has no day pages (task 2.10): the day is+ // rendered from its `log-event` records, in the shape a page has.+ const log = logDayReader(ctx.vault);+ if (log.stored) {+ // Filtered first: a day whose every event the caller may not see reads+ // as a day with none, never as an empty page (no existence oracle).+ const entries = logEntriesAtReach(view.refs, log.day(rawDate).entries);+ if (entries.length === 0) {+ throw new MCPError(INTERNAL_ERROR, `no log events for date '${rawDate}'`);+ }+ const blocks = entries.map((e) => renderLogEntryBlock(e).trimEnd());+ const text = [renderLogDayHeader(rawDate).trimEnd(), ...blocks].join(LOG_BLOCK_SEPARATOR);+ return { uri, mimeType: MIME_MARKDOWN, text: `${text}\n` };+ }+ const files = listLogMarkdownFiles(ctx.vault).filter((f) => f.date === rawDate);+ if (files.length === 0) {+ throw new MCPError(INTERNAL_ERROR, `no log file for date '${rawDate}'`);+ }+ const shard = (f: { path: string }): string =>+ shardAtReach(readFileSync(f.path, "utf8"), view.refs, () =>+ parseLogDayFile(ctx.vault, rawDate, f.path),+ );+ // The single-shard read stays verbatim (trailing newline included), so+ // a vault with the gate off is byte-identical to the pre-filter shape.+ if (files.length === 1) return { uri, mimeType: MIME_MARKDOWN, text: shard(files[0]!) };+ return { uri, mimeType: MIME_MARKDOWN, text: files.map((f) => shard(f).trimEnd()).join("\n\n") };+}++/** Start of one rendered log event: `## <time> — <kind>`. */+export const LOG_EVENT_HEADING = "\n## ";++/** The blank line {@link appendLogEvent} keeps between a shard's blocks. */+export const LOG_BLOCK_SEPARATOR = "\n\n";++/**+ * One shard as a caller behind `view` may read it: the frontmatter and+ * day heading verbatim, then the entries the Brain log event rule keeps+ * ({@link logEntriesAtReach}), each rendered as the appender writes it.+ * A shared dream keeps its readable transitions, and a retired record is+ * judged under each of its spellings, so the shard reads as it would in a+ * vault that never logged the withheld record.+ *+ * A shard is shared by construction - it is named by date and carries no+ * `owner:` - but its CONTENTS name preferences by id and by path, which+ * is why the events are filtered rather than the page.+ *+ * A block the parser cannot read is not served below local reach: what+ * it names cannot be judged, so it fails closed.+ */+export function shardAtReach(+ markdown: string,+ view: ArtifactRefView,+ parse: () => ParseLogDayResult,+): string {+ if (view.filtersNothing) return markdown;+ const firstEvent = markdown.indexOf(LOG_EVENT_HEADING);+ const head = firstEvent < 0 ? markdown : markdown.slice(0, firstEvent);+ const blocks = logEntriesAtReach(view, parse().entries).map((e) =>+ renderLogEntryBlock(e).trimEnd(),+ );+ return [head.trimEnd(), ...blocks].join(LOG_BLOCK_SEPARATOR) + "\n";+}++export function renderTopicMarkdown(slug: string, result: ReturnType<typeof queryByTopic>): string {+ const lines: string[] = [];+ lines.push(`# Brain topic: ${slug}`);+ lines.push("");+ const pref = result.preference;+ if (pref) {+ if (pref.id.startsWith("ret-")) {+ const r = pref as BrainRetired;+ const date = r.retired_at.slice(0, 10);+ lines.push("## Retired preference (no current active)");+ lines.push("");+ lines.push(`- \`${r.id}\` — retired_reason: \`${r.retired_reason}\` on ${date}`);+ lines.push(` - ${r.principle}`);+ } else {+ const p = pref as BrainPreference;+ lines.push("## Current preference");+ lines.push("");+ lines.push(`- \`${p.id}\` — status: \`${p.status}\`, confidence: \`${p.confidence}\``);+ lines.push(` - ${p.principle}`);+ }+ lines.push("");+ }+ const sigs = result.signals;+ if (sigs.length > 0) {+ lines.push(`## Signals (${sigs.length})`);+ lines.push("");+ for (const s of sigs) {+ lines.push(`- \`${s.id}\` — ${s.signal} signal by ${s.agent} at ${s.created_at}`);+ }+ lines.push("");+ }+ const log = result.all_log_events;+ if (log.length > 0) {+ lines.push(`## Recent log entries (${log.length})`);+ lines.push("");+ for (const e of log) {+ lines.push(`- ${e.timestamp} — \`${e.eventType}\``);+ }+ lines.push("");+ }+ while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();+ return lines.join("\n") + "\n";+}++/**+ * The rendered "Strongest objection" section, and the page whose+ * provenance governs it: null rel when the block quotes the governing+ * preference itself (retired, quarantined, unconfirmed) or no page at+ * all, so the document's own probe covers it; the counter-signal's own+ * page when the block quotes a negative signal's principle - agent-+ * authored text from a DIFFERENT page than the preference that decided+ * the document's treatment, which brain_query's signal payloads shape+ * at the same page.+ */+export function topicObjectionSection(+ vault: string,+ result: ReturnType<typeof queryByTopic>,+): { readonly text: string; readonly rel: string | null } {+ const sentence = buildTopicObjection(vault, result);+ const text = `## Strongest objection\n\n- ${sentence.sentence}`;+ return { text, rel: sentence.rel };+}++/**+ * The single best-formed reason to distrust the topic's current+ * preference, by fixed priority: an already-retired rule > a+ * quarantined rule > a recorded negative counter-signal > an+ * unconfirmed rule still in its trial window, and a "no standing+ * objection" sentence when none applies. The rel names the page the+ * sentence quotes, for the section renderer to probe.+ */+export function buildTopicObjection(+ vault: string,+ result: ReturnType<typeof queryByTopic>,+): { readonly sentence: string; readonly rel: string | null } {+ const pref = result.preference;+ if (pref && pref.id.startsWith("ret-")) {+ const r = pref as BrainRetired;+ return {+ sentence: `This rule was already retired (\`${r.retired_reason}\`); adopting "${r.principle}" again would repeat a judgment the Brain has discarded.`,+ rel: null,+ };+ }+ if (pref) {+ const p = pref as BrainPreference;+ if (p.status === "quarantine") {+ return {+ sentence: `The rule "${p.principle}" is on probation — recent evidence has been dominantly negative, and a single further violation retires it.`,+ rel: null,+ };+ }+ }+ const negatives = result.signals+ .filter((s) => s.signal === "negative")+ .toSorted((a, b) => (a.created_at < b.created_at ? 1 : a.created_at > b.created_at ? -1 : 0));+ if (negatives.length > 0) {+ const n = negatives[0]!;+ return {+ sentence: `A recorded counter-signal (\`${n.id}\`) argues against this: "${n.principle}". Treat the preference as contested.`,+ rel: signalDeliveryRel(vault, n.id),+ };+ }+ if (pref) {+ const p = pref as BrainPreference;+ if (p.status === "unconfirmed") {+ return {+ sentence: `The rule "${p.principle}" is unconfirmed — it has not yet earned applied evidence and may not survive its trial window (until ${p.unconfirmed_until.slice(0, 10)}).`,+ rel: null,+ };+ }+ }+ return {+ sentence:+ "No standing objection: the current preference is confirmed and faces no recorded counter-signal.",+ rel: null,+ };+}diff --git a/src/mcp/resources-shared.ts b/src/mcp/resources-shared.tsnew file mode 100644index 00000000..9fbe1321--- /dev/null+++ b/src/mcp/resources-shared.ts@@ -0,0 +1,179 @@+/**+ * The request plumbing every `osb://` resource reader shares (task+ * 3.19): the visibility view and the delivery binding built once per+ * read, the URI parser and the not-found error, the markdown reader and+ * the markdown MIME type. Split from `resources.ts`.+ */++import { readFileSync } from "node:fs";+import { BrainNotFoundError } from "../core/brain/query.ts";+import { gatedOwnerScopeView } from "../core/brain/owner-scope-view.ts";+import { everyArtifactRefView, type ArtifactRefView } from "../core/brain/artifact-ref-view.ts";+import { reachView } from "../core/brain/reach-view.ts";+import { resolvedTransportReach, type TransportReach } from "../core/graph/transport-reach.ts";+import { deliveryView } from "./brain/reach-events.ts";+import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "./protocol.ts";++export interface ResourceContext {+ readonly vault: string;+ /**+ * The identity this server resolved for the caller, threaded from+ * `MCPServer.agentName` exactly as `ServerContext.agentName` is+ * threaded into every tool.+ *+ * `resources/read` carries no arguments beyond the URI, so - like+ * `brain_context` - this surface cannot be TOLD which owner is asking+ * and the server identity is the only scope available. Absent means+ * exactly what it means for a tool: `resolveOwnerScopeDelivery` reads+ * no requested scope, `enforcedScope` is `null`, and nothing is+ * filtered - the same behaviour, from the same resolver, so the two+ * surfaces cannot disagree about what an unidentified caller sees.+ */+ readonly agentName?: string | undefined;+ /**+ * How far the caller of this read reached, minted by the transport+ * (`src/core/graph/transport-reach.ts`) and threaded from+ * `MCPServer.reach` exactly as {@link ResourceContext.agentName} is+ * threaded from `MCPServer.agentName`.+ *+ * Optional on the TYPE and mandatory in EFFECT, on the same terms+ * `ServerContext.reach` is: absent means no transport established+ * anything, which resolves to the narrowest rather than the widest.+ */+ readonly reach?: TransportReach;+}++export interface ResourceDescriptor {+ readonly uri: string;+ readonly name: string;+ readonly description: string;+ readonly mimeType: string;+}++export interface ResourceTemplateDescriptor {+ readonly uriTemplate: string;+ readonly name: string;+ readonly description: string;+ readonly mimeType: string;+}++export interface ResourceContent {+ readonly uri: string;+ readonly mimeType: string;+ readonly text: string;+}++export const MIME_MARKDOWN = "text/markdown";++export function requestView(ctx: ResourceContext): RequestView {+ const owner = gatedOwnerScopeView(ctx.vault, ctx.agentName);+ const reach = reachView(ctx.vault, resolvedTransportReach(ctx.reach));+ return Object.freeze({+ ownerScope: owner.scope,+ reach: reach.reach,+ refs: everyArtifactRefView(owner, reach),+ });+}++/**+ * The two rules this request is answered under.+ *+ * `refs` is the ANDed decision every reference-shaped filter asks.+ * `ownerScope` is separate because two readers push ownership into their+ * SELECTION rather than filtering afterwards - `queryByTopic` and+ * `buildBacklinkIndex` both take a scope - and that argument is the owner+ * rule's alone. The reserved-token rule has no selection-side form; it is+ * asked over the rows those selections return.+ */+export interface RequestView {+ readonly ownerScope: string | null;+ readonly reach: TransportReach;+ readonly refs: ArtifactRefView;+}++/**+ * The error a resource raises for something the caller may not see.+ *+ * Byte-identical to the one a genuinely ABSENT artifact produces+ * (`BrainNotFoundError`, rendered as `INTERNAL_ERROR` above), because a+ * distinguishable refusal is an existence oracle over exactly the+ * population the gate exists to hide - the same convention+ * `preferences-collect.ts` states for counts and `brain_search_expand`+ * already follows for a chunk id.+ */+export function notFound(id: string): MCPError {+ return new MCPError(INTERNAL_ERROR, new BrainNotFoundError(id).message);+}++/**+ * The delivery binding for one resource read (delivery-trust, lane A):+ * the same binding every report-shaped tool shares, bound to the request+ * the resource view already resolved. At local reach `shape` is the+ * identity and no probe runs - the operator's own readers keep the+ * pre-wave bytes; at remote reach the markdown of the readers that+ * deliver stored-record text is fenced through the K1 shaper, the+ * fence's origin naming the governing page's derived provenance. One+ * binding per read: `readResource` dispatches to exactly one reader, so+ * one frontmatter cache serves the whole request.+ */+export function deliveryFor(+ ctx: ResourceContext,+ view: RequestView,+): ReturnType<typeof deliveryView> {+ return deliveryView({ vault: ctx.vault, configPath: null, repoRoot: null, reach: view.reach });+}++// ----- URI parsing ---------------------------------------------------------++export type Parsed =+ | { readonly kind: "active" }+ | { readonly kind: "lessons" }+ | { readonly kind: "digestLatest" }+ | { readonly kind: "status" }+ | { readonly kind: "preference"; readonly id: string }+ | { readonly kind: "topic"; readonly slug: string }+ | { readonly kind: "log"; readonly date: string }+ | { readonly kind: "backlinks"; readonly id: string };++export function parseUri(uri: string): Parsed {+ if (typeof uri !== "string" || !uri.startsWith("osb://")) {+ throw new MCPError(INVALID_PARAMS, `unsupported resource uri: ${uri}`);+ }+ const remainder = uri.slice("osb://".length);+ // Resources have at most one slash for the templated variants+ // (`preference/foo`). We don't accept deeper paths.+ const parts = remainder.split("/");+ const head = parts[0] ?? "";+ if (head === "preferences" && parts[1] === "active" && parts.length === 2) {+ return { kind: "active" };+ }+ if (head === "lessons" && parts.length === 1) {+ return { kind: "lessons" };+ }+ if (head === "digest" && parts[1] === "latest" && parts.length === 2) {+ return { kind: "digestLatest" };+ }+ if (head === "status" && parts.length === 1) {+ return { kind: "status" };+ }+ if (head === "preference" && parts.length === 2) {+ return { kind: "preference", id: parts[1]! };+ }+ if (head === "topic" && parts.length === 2) {+ return { kind: "topic", slug: parts[1]! };+ }+ if (head === "log" && parts.length === 2) {+ return { kind: "log", date: parts[1]! };+ }+ if (head === "backlinks" && parts.length === 2) {+ return { kind: "backlinks", id: parts[1]! };+ }+ throw new MCPError(INVALID_PARAMS, `unsupported resource uri: ${uri}`);+}++// ----- Readers -------------------------------------------------------------++export function readMarkdown(uri: string, path: string): ResourceContent {+ const text = readFileSync(path, "utf8");+ return { uri, mimeType: MIME_MARKDOWN, text };+}diff --git a/src/mcp/resources.ts b/src/mcp/resources.tsindex 56c4c31a..f30e249a 100644--- a/src/mcp/resources.ts+++ b/src/mcp/resources.ts@@ -58,126 +58,28 @@* Brain layer and is not filtered here.*/-import { storeMemoryPageAt } from "../core/brain/memory-pages.ts";-import { logDayReader } from "../core/brain/log-days.ts";-import { vaultRelative } from "../core/path-safety.ts";-import { formatFrontmatter } from "../core/vault.ts";-import { existsSync, readFileSync } from "node:fs";-import { listLogMarkdownFiles } from "../core/brain/log-jsonl.ts";--import {- activeDigestPathForRead,- readActiveForReader,- regenerateActive,-} from "../core/brain/active.ts";-import {- lessonsDigestPathForRead,- regenerateLessons,- renderLessonsForReader,-} from "../core/brain/lessons.ts";-import { buildBacklinkIndex } from "../core/brain/backlinks.ts";-import type { BacklinkRef } from "../core/brain/backlinks.ts";-import { renderDigest } from "../core/brain/digest.ts";-import {- computeBrainStatus,- MAINTENANCE_DEBT_STATUS,- type BrainStatusSnapshot,-} from "../core/brain/status.ts";+import type {+ ResourceContent,+ ResourceContext,+ ResourceDescriptor,+ ResourceTemplateDescriptor,+} from "./resources-shared.ts";+import { MIME_MARKDOWN, parseUri, requestView } from "./resources-shared.ts";import {- preferencePath,- retiredPath,- validateIsoDate,- validateSlug,- BRAIN_ACTIVE_FILE,- BRAIN_LESSONS_FILE,- BRAIN_PREFERENCES_REL,- BRAIN_ROOT_REL,-} from "../core/brain/paths.ts";-import { BrainNotFoundError, queryByPreference, queryByTopic } from "../core/brain/query.ts";-import { gatedOwnerScopeView } from "../core/brain/owner-scope-view.ts";-import { everyArtifactRefView, type ArtifactRefView } from "../core/brain/artifact-ref-view.ts";-import { reachView } from "../core/brain/reach-view.ts";-import {- TRANSPORT_REACH,- resolvedTransportReach,- type TransportReach,-} from "../core/graph/transport-reach.ts";-import { normaliseWikilinkTarget } from "../core/brain/wikilink.ts";-import { logEntriesAtReach, recordRefs } from "../core/brain/log-events-at-reach.ts";-import {- parseLogDayFile,- renderLogDayHeader,- renderLogEntryBlock,- type ParseLogDayResult,-} from "../core/brain/log.ts";-import type { BrainPreference, BrainRetired } from "../core/brain/types.ts";-import {- deliveryRelForBrainArtifact,- deliveryView,- signalDeliveryRel,- UNPROBED_DELIVERY_REL,-} from "./brain/reach-events.ts";-import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "./protocol.ts";--export interface ResourceContext {- readonly vault: string;- /**- * The identity this server resolved for the caller, threaded from- * `MCPServer.agentName` exactly as `ServerContext.agentName` is- * threaded into every tool.- *- * `resources/read` carries no arguments beyond the URI, so - like- * `brain_context` - this surface cannot be TOLD which owner is asking- * and the server identity is the only scope available. Absent means- * exactly what it means for a tool: `resolveOwnerScopeDelivery` reads- * no requested scope, `enforcedScope` is `null`, and nothing is- * filtered - the same behaviour, from the same resolver, so the two- * surfaces cannot disagree about what an unidentified caller sees.- */- readonly agentName?: string | undefined;- /**- * How far the caller of this read reached, minted by the transport- * (`src/core/graph/transport-reach.ts`) and threaded from- * `MCPServer.reach` exactly as {@link ResourceContext.agentName} is- * threaded from `MCPServer.agentName`.- *- * Optional on the TYPE and mandatory in EFFECT, on the same terms- * `ServerContext.reach` is: absent means no transport established- * anything, which resolves to the narrowest rather than the widest.- */- readonly reach?: TransportReach;-}--export interface ResourceDescriptor {- readonly uri: string;- readonly name: string;- readonly description: string;- readonly mimeType: string;-}--export interface ResourceTemplateDescriptor {- readonly uriTemplate: string;- readonly name: string;- readonly description: string;- readonly mimeType: string;-}--export interface ResourceContent {- readonly uri: string;- readonly mimeType: string;- readonly text: string;-}--const MIME_MARKDOWN = "text/markdown";--/**- * Vault-relative paths of the two generated digest files, the probes the- * delivery binding names when one of them is what a reader delivers- * (delivery-trust, lane A). The files are the system's own render, so- * the derivation reads THEIR absence of stamps rather than guessing.- */-const ACTIVE_REL = `${BRAIN_ROOT_REL}/${BRAIN_ACTIVE_FILE}`;-const LESSONS_REL = `${BRAIN_ROOT_REL}/${BRAIN_LESSONS_FILE}`;+ readActive,+ readDigestLatest,+ readLessons,+ readStatus,+} from "./resources-digest-readers.ts";+import { readLog, readPreference, readTopic } from "./resources-record-readers.ts";+import { readBacklinks } from "./resources-backlink-readers.ts";++export type {+ ResourceContext,+ ResourceDescriptor,+ ResourceTemplateDescriptor,+ ResourceContent,+} from "./resources-shared.ts";const CONCRETE: ReadonlyArray<ResourceDescriptor> = [{@@ -282,717 +184,5 @@ export function readResource(ctx: ResourceContext, uri: string): ResourceContent* observable, because neither reports a count - see* `src/core/brain/artifact-ref-view.ts`.*/-function requestView(ctx: ResourceContext): RequestView {- const owner = gatedOwnerScopeView(ctx.vault, ctx.agentName);- const reach = reachView(ctx.vault, resolvedTransportReach(ctx.reach));- return Object.freeze({- ownerScope: owner.scope,- reach: reach.reach,- refs: everyArtifactRefView(owner, reach),- });-}--/**- * The two rules this request is answered under.- *- * `refs` is the ANDed decision every reference-shaped filter asks.- * `ownerScope` is separate because two readers push ownership into their- * SELECTION rather than filtering afterwards - `queryByTopic` and- * `buildBacklinkIndex` both take a scope - and that argument is the owner- * rule's alone. The reserved-token rule has no selection-side form; it is- * asked over the rows those selections return.- */-interface RequestView {- readonly ownerScope: string | null;- readonly reach: TransportReach;- readonly refs: ArtifactRefView;-}--/**- * The error a resource raises for something the caller may not see.- *- * Byte-identical to the one a genuinely ABSENT artifact produces- * (`BrainNotFoundError`, rendered as `INTERNAL_ERROR` above), because a- * distinguishable refusal is an existence oracle over exactly the- * population the gate exists to hide - the same convention- * `preferences-collect.ts` states for counts and `brain_search_expand`- * already follows for a chunk id.- */-function notFound(id: string): MCPError {- return new MCPError(INTERNAL_ERROR, new BrainNotFoundError(id).message);-}--/**- * The delivery binding for one resource read (delivery-trust, lane A):- * the same binding every report-shaped tool shares, bound to the request- * the resource view already resolved. At local reach `shape` is the- * identity and no probe runs - the operator's own readers keep the- * pre-wave bytes; at remote reach the markdown of the readers that- * deliver stored-record text is fenced through the K1 shaper, the- * fence's origin naming the governing page's derived provenance. One- * binding per read: `readResource` dispatches to exactly one reader, so- * one frontmatter cache serves the whole request.- */-function deliveryFor(ctx: ResourceContext, view: RequestView): ReturnType<typeof deliveryView> {- return deliveryView({ vault: ctx.vault, configPath: null, repoRoot: null, reach: view.reach });-}--// ----- URI parsing -----------------------------------------------------------type Parsed =- | { readonly kind: "active" }- | { readonly kind: "lessons" }- | { readonly kind: "digestLatest" }- | { readonly kind: "status" }- | { readonly kind: "preference"; readonly id: string }- | { readonly kind: "topic"; readonly slug: string }- | { readonly kind: "log"; readonly date: string }- | { readonly kind: "backlinks"; readonly id: string };--function parseUri(uri: string): Parsed {- if (typeof uri !== "string" || !uri.startsWith("osb://")) {- throw new MCPError(INVALID_PARAMS, `unsupported resource uri: ${uri}`);- }- const remainder = uri.slice("osb://".length);- // Resources have at most one slash for the templated variants- // (`preference/foo`). We don't accept deeper paths.- const parts = remainder.split("/");- const head = parts[0] ?? "";- if (head === "preferences" && parts[1] === "active" && parts.length === 2) {- return { kind: "active" };- }- if (head === "lessons" && parts.length === 1) {- return { kind: "lessons" };- }- if (head === "digest" && parts[1] === "latest" && parts.length === 2) {- return { kind: "digestLatest" };- }- if (head === "status" && parts.length === 1) {- return { kind: "status" };- }- if (head === "preference" && parts.length === 2) {- return { kind: "preference", id: parts[1]! };- }- if (head === "topic" && parts.length === 2) {- return { kind: "topic", slug: parts[1]! };- }- if (head === "log" && parts.length === 2) {- return { kind: "log", date: parts[1]! };- }- if (head === "backlinks" && parts.length === 2) {- return { kind: "backlinks", id: parts[1]! };- }- throw new MCPError(INVALID_PARAMS, `unsupported resource uri: ${uri}`);-}--// ----- Readers ---------------------------------------------------------------function readActive(ctx: ResourceContext, uri: string, view: RequestView): ResourceContent {- // On a store-only machine the digest is rendered on demand into the- // device-local cache (D14 item 7); a render failure is reported below.- let path: string;- try {- path = activeDigestPathForRead(ctx.vault);- } catch (err) {- throw new MCPError(INTERNAL_ERROR, `active digest render failed: ${(err as Error).message}`);- }- // First read attempt: the file usually exists because dream- // regenerates it. On a fresh vault that has never been dreamed, the- // file may not exist yet — generate it on demand so the resource is- // always meaningful. We do NOT auto-generate on every read (that- // would shift expensive work onto a hot path); only on the first- // read of a missing file.- if (!existsSync(path)) {- try {- regenerateActive(ctx.vault);- } catch (err) {- throw new MCPError(- INTERNAL_ERROR,- `active-preferences digest not present and on-demand regeneration failed: ${(err as Error).message}`,- );- }- }- // The shared file is served as it is to a local reader with no owner- // scope; any other reader gets the in-memory render, stamped with the- // generation on disk (see `readActiveForReader`).- const text = readActiveForReader(ctx.vault, {- ...(view.refs.filtersNothing ? {} : { readable: view.refs.visible }),- ...(view.ownerScope !== null ? { agentScope: view.ownerScope } : {}),- restricted: view.reach !== TRANSPORT_REACH.local,- });- return {- uri,- mimeType: MIME_MARKDOWN,- // The digest quotes stored principles (delivery-trust, lane A): the- // delivery is fenced at remote reach, named for the generated file's- // own absence of stamps - the system's render is not operator prose,- // and the derivation says so rather than guessing authorship.- text: deliveryFor(ctx, view).shape(text, ACTIVE_REL),- };-}--function readLessons(ctx: ResourceContext, uri: string, view: RequestView): ResourceContent {- let path: string;- try {- path = lessonsDigestPathForRead(ctx.vault);- } catch (err) {- throw new MCPError(INTERNAL_ERROR, `lessons digest render failed: ${(err as Error).message}`);- }- // Same on-demand-on-first-miss policy as readActive: a fresh vault- // that has never been dreamed has no lessons.md yet — generate it- // once so the resource is always meaningful, but never on every read.- if (!existsSync(path)) {- try {- regenerateLessons(ctx.vault);- } catch (err) {- throw new MCPError(- INTERNAL_ERROR,- `lessons digest not present and on-demand regeneration failed: ${(err as Error).message}`,- );- }- }- // A local reader with no owner scope is served the shared file as it- // is; any other reader gets the digest rendered without the records it- // cannot see, scored and stamped at the generation on disk. Either way- // the delivered markdown is the lessons corpus quoting stored- // principles (delivery-trust, lane A): fenced at remote reach, named- // for the generated file's own absence of stamps.- const delivery = deliveryFor(ctx, view);- const text = view.refs.filtersNothing- ? readMarkdown(uri, path).text- : renderLessonsForReader(ctx.vault, {- readable: view.refs.visible,- ...(view.refs.withholdsPrivate === true ? { withholdsPrivate: true } : {}),- }).document;- return { uri, mimeType: MIME_MARKDOWN, text: delivery.shape(text, LESSONS_REL) };-}--function readDigestLatest(ctx: ResourceContext, uri: string, view: RequestView): ResourceContent {- const rendered = renderDigest(ctx.vault, {- format: "markdown",- ...(view.refs.filtersNothing ? {} : { readable: view.refs.visible }),- ...(view.refs.withholdsPrivate === true ? { withholdsPrivate: true } : {}),- // Ownership is pushed into the render's SELECTION as well as its- // row filter, the way `readActive` does: `view.refs` already- // carries the rule on the filter side, and the digest's- // vault-wide sections (the maintenance actions) are scoped by the- // render itself rather than by which rows an id happens to name.- ...(view.ownerScope !== null ? { agentScope: view.ownerScope } : {}),- });- return {- uri,- mimeType: MIME_MARKDOWN,- // The digest quotes stored principles (delivery-trust, lane A) in the- // same render family as the active and lessons digests, so it shapes- // through the same binding: fenced at remote reach, named for the- // compiled-digest render's own absence of stamps - the system's voice- // is not operator prose, and the derivation says so rather than- // guessing authorship. The probe rel names that family's on-disk- // member (BRAIN_COMPILED_DIGEST_RELS), whose generated page carries- // no stamps, the exact probe readActive's render makes.- text: deliveryFor(ctx, view).shape(rendered.content, ACTIVE_REL),- };-}--function readStatus(ctx: ResourceContext, uri: string): ResourceContent {- const snapshot = computeBrainStatus(ctx.vault, {- withholdsPrivate: resolvedTransportReach(ctx.reach) !== TRANSPORT_REACH.local,- });- return {- uri,- mimeType: MIME_MARKDOWN,- text: renderStatusMarkdown(snapshot),- };-}--function readPreference(- ctx: ResourceContext,- uri: string,- rawId: string,- view: RequestView,-): ResourceContent {- if (!rawId.trim()) {- throw new MCPError(INVALID_PARAMS, `resource id must not be empty: ${uri}`);- }- // Accept `pref-foo`, `ret-foo`, or the bare slug. Strip the prefix- // (if any) for `validateSlug` — that helper rejects `..` traversal- // and other shape problems with a clear INVALID_PARAMS-shaped- // message, which is a better diagnosis than a downstream- // "not found" error. The prefixed form is then handed to- // queryByPreference, which handles the active → retired fallback.- const slug = rawId.startsWith("pref-")- ? rawId.slice("pref-".length)- : rawId.startsWith("ret-")- ? rawId.slice("ret-".length)- : rawId;- try {- validateSlug(slug);- } catch (err) {- throw new MCPError(INVALID_PARAMS, (err as Error).message);- }- const normalized =- rawId.startsWith("pref-") || rawId.startsWith("ret-") ? rawId : `pref-${rawId}`;- // Asked before the page is parsed: a withheld page that fails to parse- // would otherwise answer with the parser's error, which names the page- // an absent id never could.- if (!view.refs.row(...recordRefs(normalized))) throw notFound(normalized);- let result;- try {- result = queryByPreference(ctx.vault, normalized);- } catch (err) {- if (err instanceof BrainNotFoundError) {- throw new MCPError(INTERNAL_ERROR, err.message);- }- throw err;- }- // queryByPreference returns the parsed object but not its path; we- // re-derive the path from the resolved id so we can hand back the- // raw markdown body (the resource contract is "give me the file",- // not "give me a structured projection").- const resolvedId = result.preference.id;- const resolvedSlug = resolvedId.startsWith("pref-")- ? resolvedId.slice("pref-".length)- : resolvedId.slice("ret-".length);- const filePath = resolvedId.startsWith("pref-")- ? preferencePath(ctx.vault, resolvedSlug)- : retiredPath(ctx.vault, resolvedSlug);- // The whole file, `owner:` line and body prose included, is what this- // reader hands back - so the ownership question is asked before the- // read, not filtered out of the bytes afterwards.- //- // `normalized`, not `rawId`: the absent branch above rethrows what- // `queryByPreference` threw, and that names the NORMALISED id. This- // reader accepts the bare slug too, so echoing the raw one here made- // `osb://preference/acme` answer "...for id 'acme'" when the page- // existed and was withheld, against "...for id 'pref-acme'" when it did- // not - the presence of the prefix a one-bit existence oracle over the- // whole reserved population.- if (!view.refs.visible(resolvedId)) throw notFound(normalized);- // On a store-only machine the page is the one the fold rebuilds (task 2.10).- const stored = storeMemoryPageAt(ctx.vault, vaultRelative(filePath, ctx.vault));- const file =- stored === null- ? readMarkdown(uri, filePath)- : { uri, mimeType: MIME_MARKDOWN, text: formatFrontmatter(...stored.read()) };- return {- ...file,- // The whole file - frontmatter and body - is the delivery- // (delivery-trust, lane A): fenced at remote reach through the- // binding, named for the page's own derived provenance; local keeps- // the bytes. The probe asks the RESOLVED page - the id the- // active-to-retired fallback answered - never the caller's spelling.- text: deliveryFor(ctx, view).shape(- file.text,- deliveryRelForBrainArtifact(ctx.vault, resolvedId),- ),- };-}--function readTopic(- ctx: ResourceContext,- uri: string,- rawSlug: string,- view: RequestView,-): ResourceContent {- if (!rawSlug.trim()) {- throw new MCPError(INVALID_PARAMS, `topic slug must not be empty: ${uri}`);- }- validateSlug(rawSlug);- let result;- try {- // The scope reaches the SELECTION, not the result: a topic resolves- // to one preference and several may carry it, so filtering afterwards- // would report the topic as having no rule whenever another owner's- // preference happened to sort first.- result = queryByTopic(ctx.vault, rawSlug, {- ownerScope: view.ownerScope,- transportReach: view.reach,- });- } catch (err) {- if (err instanceof BrainNotFoundError) {- throw new MCPError(INTERNAL_ERROR, err.message);- }- throw err;- }- // The two remaining owner-bearing streams, filtered before the- // renderer sees them: each signal row names its id and its author, and- // the log rows are the same events `brain_event_trace` filters. A- // topic whose ONLY rule is one this caller may not see is reported as- // a topic with no rule, not as a topic that refused - the renderer- // already has that shape for a topic that never reached promotion.- const scoped = Object.freeze({- ...result,- signals: view.refs.keep(result.signals, (s) => [s.id]),- all_log_events: logEntriesAtReach(view.refs, result.all_log_events),- });- // The synthesis is composed from spans shaped at the page each span- // quotes (delivery-trust, lane A): the body under the governing- // preference page's provenance - a topic with no current rule probes- // the page that would hold it, the absent-page fail-closed answer -- // and the objection block under the page ITS text quotes, because the- // strongest objection may quote an agent-authored counter-signal- // whose page is not the page that decided the body's treatment.- const delivery = deliveryFor(ctx, view);- const preferenceRel = result.preference- ? deliveryRelForBrainArtifact(ctx.vault, result.preference.id)- : `${BRAIN_PREFERENCES_REL}/pref-${rawSlug}.md`;- const objection = topicObjectionSection(ctx.vault, scoped);- let text: string;- if (objection.rel === null) {- // The block quotes the governing preference itself (or no page at- // all): one document, one probe. The trailing newline keeps the- // unfenced bytes identical to the pre-shaping document.- text = delivery.shape(- `${renderTopicMarkdown(rawSlug, scoped)}\n${objection.text}\n`,- preferenceRel,- );- } else {- text =- `${delivery.shape(renderTopicMarkdown(rawSlug, scoped), preferenceRel)}\n` +- `${delivery.shape(objection.text, objection.rel)}\n`;- }- return { uri, mimeType: MIME_MARKDOWN, text };-}--function readLog(- ctx: ResourceContext,- uri: string,- rawDate: string,- view: RequestView,-): ResourceContent {- validateIsoDate(rawDate);- // Per-device shards (Memory Integrity Suite): a day's human view can- // span several markdown files. The legacy single file is returned- // verbatim (byte-identical to pre-shard behaviour); multiple shards- // are concatenated in shard order.- // A store-only machine has no day pages (task 2.10): the day is- // rendered from its `log-event` records, in the shape a page has.- const log = logDayReader(ctx.vault);- if (log.stored) {- // Filtered first: a day whose every event the caller may not see reads- // as a day with none, never as an empty page (no existence oracle).- const entries = logEntriesAtReach(view.refs, log.day(rawDate).entries);- if (entries.length === 0) {- throw new MCPError(INTERNAL_ERROR, `no log events for date '${rawDate}'`);- }- const blocks = entries.map((e) => renderLogEntryBlock(e).trimEnd());- const text = [renderLogDayHeader(rawDate).trimEnd(), ...blocks].join(LOG_BLOCK_SEPARATOR);- return { uri, mimeType: MIME_MARKDOWN, text: `${text}\n` };- }- const files = listLogMarkdownFiles(ctx.vault).filter((f) => f.date === rawDate);- if (files.length === 0) {- throw new MCPError(INTERNAL_ERROR, `no log file for date '${rawDate}'`);- }- const shard = (f: { path: string }): string =>- shardAtReach(readFileSync(f.path, "utf8"), view.refs, () =>- parseLogDayFile(ctx.vault, rawDate, f.path),- );- // The single-shard read stays verbatim (trailing newline included), so- // a vault with the gate off is byte-identical to the pre-filter shape.- if (files.length === 1) return { uri, mimeType: MIME_MARKDOWN, text: shard(files[0]!) };- return { uri, mimeType: MIME_MARKDOWN, text: files.map((f) => shard(f).trimEnd()).join("\n\n") };-}--/** Start of one rendered log event: `## <time> — <kind>`. */-const LOG_EVENT_HEADING = "\n## ";--/** The blank line {@link appendLogEvent} keeps between a shard's blocks. */-const LOG_BLOCK_SEPARATOR = "\n\n";--/**- * One shard as a caller behind `view` may read it: the frontmatter and- * day heading verbatim, then the entries the Brain log event rule keeps- * ({@link logEntriesAtReach}), each rendered as the appender writes it.- * A shared dream keeps its readable transitions, and a retired record is- * judged under each of its spellings, so the shard reads as it would in a- * vault that never logged the withheld record.- *- * A shard is shared by construction - it is named by date and carries no- * `owner:` - but its CONTENTS name preferences by id and by path, which- * is why the events are filtered rather than the page.- *- * A block the parser cannot read is not served below local reach: what- * it names cannot be judged, so it fails closed.- */-function shardAtReach(- markdown: string,- view: ArtifactRefView,- parse: () => ParseLogDayResult,-): string {- if (view.filtersNothing) return markdown;- const firstEvent = markdown.indexOf(LOG_EVENT_HEADING);- const head = firstEvent < 0 ? markdown : markdown.slice(0, firstEvent);- const blocks = logEntriesAtReach(view, parse().entries).map((e) =>- renderLogEntryBlock(e).trimEnd(),- );- return [head.trimEnd(), ...blocks].join(LOG_BLOCK_SEPARATOR) + "\n";-}--function readBacklinks(- ctx: ResourceContext,- uri: string,- rawId: string,- view: RequestView,-): ResourceContent {- if (!rawId.trim()) {- throw new MCPError(INVALID_PARAMS, `backlinks target must not be empty: ${uri}`);- }- // Normalise to the same form the index keys use so `[[pref-foo]]`,- // `pref-foo`, and `Brain/preferences/pref-foo.md` all resolve.- const target = normaliseWikilinkTarget(rawId);- // The last unscoped `buildBacklinkIndex` call in the product. Every- // ref it yields names its SOURCE artifact by id, so an unscoped index- // here published the same list `brain_backlinks` had already learned- // to withhold.- //- // A hidden TARGET answers exactly as an ABSENT one does - the empty- // backlink document - rather than refusing: this reader has no- // not-found path at all (an unknown target is a legitimate zero), so a- // refusal here would be the one response shape that proves the page- // exists. The echoed target is the caller's own argument.- const index = buildBacklinkIndex(ctx.vault, view.ownerScope, {- withholdsPrivate: view.refs.withholdsPrivate === true,- });- // Every spelling the target answers to across its retirement: a- // retired reserved record is otherwise asked as `pref-x`, which names- // no page once `ret-x` is the one on disk.- const targetVisible = view.refs.row(...recordRefs(target));- const refs = targetVisible- ? (index.get(target) ?? []).filter((ref) => view.refs.visible(ref.source))- : [];- return {- uri,- mimeType: MIME_MARKDOWN,- // The rendered document is derived from stored pages (delivery-trust,- // lane A): fenced at remote reach, named for the TARGET page's own- // derived provenance; local keeps the bytes. A withheld target probes- // the guaranteed-absent page instead: reading a hidden target's real- // stamps would name its existence and its channel through the fence's- // origin label, while an absent one reads as unverified - the two- // answers must stay identical.- text: deliveryFor(ctx, view).shape(- renderBacklinksMarkdown(target, refs),- targetVisible ? deliveryRelForBrainArtifact(ctx.vault, target) : UNPROBED_DELIVERY_REL,- ),- };-}// ----- Helpers ---------------------------------------------------------------function readMarkdown(uri: string, path: string): ResourceContent {- const text = readFileSync(path, "utf8");- return { uri, mimeType: MIME_MARKDOWN, text };-}--/**- * Render the topic-query result as a compact markdown document. Kept- * here (not in `query.ts`) because the markdown shape is a- * resource-surface concern; callers that want the structured form can- * still invoke `queryByTopic` directly.- */-function renderStatusMarkdown(s: BrainStatusSnapshot): string {- const lines: string[] = [];- lines.push("# Brain status");- lines.push("");- if (!s.present) {- lines.push("_Brain layer not present in this vault. Run `o2b brain init` first._");- return lines.join("\n") + "\n";- }- lines.push("## Counts");- lines.push("");- lines.push(- `- inbox: ${s.counts.inbox} (processed: ${s.counts.inbox_processed}, ` +- `archived: ${s.counts.inbox_archived})`,- );- lines.push(`- preferences: ${s.counts.preferences}`);- for (const [status, n] of Object.entries(s.counts.preferences_by_status).toSorted()) {- lines.push(` - ${status}: ${n}`);- }- lines.push(`- retired: ${s.counts.retired}`);- lines.push(`- log days: ${s.counts.log_days}`);- lines.push(`- snapshots: ${s.counts.snapshots}`);- lines.push("");- lines.push("## Activity");- lines.push("");- lines.push(`- last dream: ${s.last_dream_at ?? "_(never)_"}`);- lines.push(`- last apply-evidence: ${s.last_apply_evidence_at ?? "_(never)_"}`);- lines.push("");- lines.push("## Maintenance debt");- lines.push("");- const debtCount = s.maintenance_debt.log_events_since_dream;- const debtNoun = debtCount === 1 ? "log event" : "log events";- if (s.maintenance_debt.status === MAINTENANCE_DEBT_STATUS.neverDreamed) {- lines.push(`- never dreamed — ${debtCount} ${debtNoun} recorded since inception`);- } else if (s.maintenance_debt.status === MAINTENANCE_DEBT_STATUS.undercounted) {- // The figure is a floor: at least one shard in the window would not- // read or would not parse. Printing it as a count would be the- // partial walk presented as a total.- lines.push(- `- at least ${debtCount} ${debtNoun} since the last dream — a log shard could not be ` +- "read in full, so this is a lower bound",- );- } else {- lines.push(`- ${debtCount} ${debtNoun} since the last dream`);- }- lines.push("");- if (s.sanity.signals_awaiting_dream > 0) {- lines.push("## Sanity");- lines.push("");- lines.push(- `- **${s.sanity.signals_awaiting_dream}** signal(s) in inbox/ predate the unconfirmed_window — run \`o2b brain dream\`.`,- );- lines.push("");- }- while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();- return lines.join("\n") + "\n";-}--function renderBacklinksMarkdown(target: string, refs: ReadonlyArray<BacklinkRef>): string {- const lines: string[] = [];- lines.push(`# Backlinks to \`${target}\``);- lines.push("");- lines.push(`Total inbound references: ${refs.length}`);- lines.push("");- if (refs.length === 0) {- lines.push("_No inbound references found._");- return lines.join("\n") + "\n";- }- // Group by source-kind so the reader sees structure rather than a- // flat list — the same source kind (e.g. multiple log apply-evidence- // events) clusters together.- const byKind = new Map<string, BacklinkRef[]>();- for (const r of refs) {- const arr = byKind.get(r.sourceKind) ?? [];- arr.push(r);- byKind.set(r.sourceKind, arr);- }- for (const [kind, group] of byKind) {- lines.push(`## ${kind} (${group.length})`);- lines.push("");- for (const r of group) {- const suffix = r.timestamp ? ` — ${r.timestamp}` : "";- lines.push(`- \`${r.source}\` (field: \`${r.field}\`)${suffix}`);- }- lines.push("");- }- while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();- return lines.join("\n") + "\n";-}--function renderTopicMarkdown(slug: string, result: ReturnType<typeof queryByTopic>): string {- const lines: string[] = [];- lines.push(`# Brain topic: ${slug}`);- lines.push("");- const pref = result.preference;- if (pref) {- if (pref.id.startsWith("ret-")) {- const r = pref as BrainRetired;- const date = r.retired_at.slice(0, 10);- lines.push("## Retired preference (no current active)");- lines.push("");- lines.push(`- \`${r.id}\` — retired_reason: \`${r.retired_reason}\` on ${date}`);- lines.push(` - ${r.principle}`);- } else {- const p = pref as BrainPreference;- lines.push("## Current preference");- lines.push("");- lines.push(`- \`${p.id}\` — status: \`${p.status}\`, confidence: \`${p.confidence}\``);- lines.push(` - ${p.principle}`);- }- lines.push("");- }- const sigs = result.signals;- if (sigs.length > 0) {- lines.push(`## Signals (${sigs.length})`);- lines.push("");- for (const s of sigs) {- lines.push(`- \`${s.id}\` — ${s.signal} signal by ${s.agent} at ${s.created_at}`);- }- lines.push("");- }- const log = result.all_log_events;- if (log.length > 0) {- lines.push(`## Recent log entries (${log.length})`);- lines.push("");- for (const e of log) {- lines.push(`- ${e.timestamp} — \`${e.eventType}\``);- }- lines.push("");- }- while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();- return lines.join("\n") + "\n";-}--/**- * The rendered "Strongest objection" section, and the page whose- * provenance governs it: null rel when the block quotes the governing- * preference itself (retired, quarantined, unconfirmed) or no page at- * all, so the document's own probe covers it; the counter-signal's own- * page when the block quotes a negative signal's principle - agent-- * authored text from a DIFFERENT page than the preference that decided- * the document's treatment, which brain_query's signal payloads shape- * at the same page.- */-function topicObjectionSection(- vault: string,- result: ReturnType<typeof queryByTopic>,-): { readonly text: string; readonly rel: string | null } {- const sentence = buildTopicObjection(vault, result);- const text = `## Strongest objection\n\n- ${sentence.sentence}`;- return { text, rel: sentence.rel };-}--/**- * The single best-formed reason to distrust the topic's current- * preference, by fixed priority: an already-retired rule > a- * quarantined rule > a recorded negative counter-signal > an- * unconfirmed rule still in its trial window, and a "no standing- * objection" sentence when none applies. The rel names the page the- * sentence quotes, for the section renderer to probe.- */-function buildTopicObjection(- vault: string,- result: ReturnType<typeof queryByTopic>,-): { readonly sentence: string; readonly rel: string | null } {- const pref = result.preference;- if (pref && pref.id.startsWith("ret-")) {- const r = pref as BrainRetired;- return {- sentence: `This rule was already retired (\`${r.retired_reason}\`); adopting "${r.principle}" again would repeat a judgment the Brain has discarded.`,- rel: null,- };- }- if (pref) {- const p = pref as BrainPreference;- if (p.status === "quarantine") {- return {- sentence: `The rule "${p.principle}" is on probation — recent evidence has been dominantly negative, and a single further violation retires it.`,- rel: null,- };- }- }- const negatives = result.signals- .filter((s) => s.signal === "negative")- .toSorted((a, b) => (a.created_at < b.created_at ? 1 : a.created_at > b.created_at ? -1 : 0));- if (negatives.length > 0) {- const n = negatives[0]!;- return {- sentence: `A recorded counter-signal (\`${n.id}\`) argues against this: "${n.principle}". Treat the preference as contested.`,- rel: signalDeliveryRel(vault, n.id),- };- }- if (pref) {- const p = pref as BrainPreference;- if (p.status === "unconfirmed") {- return {- sentence: `The rule "${p.principle}" is unconfirmed — it has not yet earned applied evidence and may not survive its trial window (until ${p.unconfirmed_until.slice(0, 10)}).`,- rel: null,- };- }- }- return {- sentence:- "No standing objection: the current preference is confirmed and faces no recorded counter-signal.",- rel: null,- };-}diff --git a/tests/core/architecture/brain-literal-census.test.ts b/tests/core/architecture/brain-literal-census.test.tsindex 4026d4b8..3c46eb88 100644--- a/tests/core/architecture/brain-literal-census.test.ts+++ b/tests/core/architecture/brain-literal-census.test.ts@@ -170,8 +170,10 @@ const ALLOWLIST: Readonly<Record<string, string>> = Object.freeze({"src/core/state/surfaces.ts": TEXT,"src/core/write-binding/index.ts": TEXT,"src/mcp/brain/context-tools.ts": NOTE_WALL,- "src/mcp/brain/feedback-tools.ts": TEXT,- "src/mcp/brain/knowledge-tools.ts": LANE,+ // Task 3.19 moved the handlers with the literals into sibling modules;+ // the entries follow the code they excuse.+ "src/mcp/brain/dream-tools.ts": TEXT,+ "src/mcp/brain/knowledge-lane-tools.ts": LANE,"src/mcp/brain/procedure-tools.ts": LANE,"src/mcp/skill-tools.ts": TEXT,});diff --git a/tests/core/architecture/log-reader-census.test.ts b/tests/core/architecture/log-reader-census.test.tsindex bf121775..63c3117e 100644--- a/tests/core/architecture/log-reader-census.test.ts+++ b/tests/core/architecture/log-reader-census.test.ts@@ -120,15 +120,15 @@ const LOG_READERS: Readonly<Record<string, LogReaderRow>> = Object.freeze(...rows(["core/brain/agent-source/vault-provider.ts"], "at-reach", "D2 row 4"),...rows(["core/brain/backlinks.ts"], "at-reach", "D2 row 5"),...rows(- [- "core/brain/digest-agent-summary.ts",- "core/brain/digest.ts",- "core/brain/lessons.ts",- "core/brain/event-trace.ts",- ],+ ["core/brain/digest-agent-summary.ts", "core/brain/lessons.ts", "core/brain/event-trace.ts"],"at-reach","`logEntryAtReach` with the caller's view",),+ ...rows(+ ["core/brain/digest-collect.ts"],+ "at-reach",+ "`logEntryAtReach` with the caller's view; the digest's log window moved out of `digest.ts` in the 700-line split (task 3.19)",+ ),...rows(["core/brain/doctor/orphan-session-check.ts", "core/brain/doctor/records.ts"],"computation",@@ -179,12 +179,16 @@ const LOG_READERS: Readonly<Record<string, LogReaderRow>> = Object.freeze(),...rows(["core/brain/query.ts"], "at-reach", "`brain_query` filters every mode (D2 row 1)"),...rows(- ["mcp/brain/analytics-tools.ts", "mcp/brain/brief-tools.ts"],+ ["mcp/brain/analytics-tools.ts", "mcp/brain/brief-view-tools.ts"],"at-reach",- "`requestRefView` (D1); derived rows: an index built withholding (D2 row 9)",+ "`requestRefView` (D1); derived rows: an index built withholding (D2 row 9); the brief views moved out of `brief-tools.ts` in the 700-line split (task 3.19)",),...rows(["mcp/brain/review-tools.ts"], "at-reach", "D2 row 9"),- ...rows(["mcp/resources.ts"], "at-reach", "`osb://log` filters (D3 of `lane-pages-split`)"),+ ...rows(+ ["mcp/resources-record-readers.ts"],+ "at-reach",+ "`osb://log` filters (D3 of `lane-pages-split`); the log reader moved out of `resources.ts` in the 700-line split (task 3.19)",+ ),...rows(["core/brain/log-days.ts",diff --git a/tests/core/architecture/source-archive-stamp-census.test.ts b/tests/core/architecture/source-archive-stamp-census.test.tsindex 5c0038c5..1482f62a 100644--- a/tests/core/architecture/source-archive-stamp-census.test.ts+++ b/tests/core/architecture/source-archive-stamp-census.test.ts@@ -65,7 +65,9 @@ const STAMP_KEY_FILES: ReadonlyArray<string> = Object.freeze([posix.join("core", "brain", "ingest", "ingest.ts"),posix.join("core", "brain", "provenance", "source-archive.ts"),posix.join("mcp", "brain", "hygiene-tools.ts"),- posix.join("mcp", "brain", "ingest-tools.ts"),+ // The ingest cleanup moved out of `ingest-tools.ts` in the 700-line+ // split (task 3.19); the entry follows the code that names the key.+ posix.join("mcp", "brain", "ingest-source-tools.ts"),]);/** The one writer among them - the ingest lane's stamp site. */diff --git a/tests/core/architecture/visibility-surface-census.test.ts b/tests/core/architecture/visibility-surface-census.test.tsindex 4f8ea776..81ebcbe1 100644--- a/tests/core/architecture/visibility-surface-census.test.ts+++ b/tests/core/architecture/visibility-surface-census.test.ts@@ -483,10 +483,26 @@ function discoverMcpToolPopulation(for (const file of files) {constantsByFile.set(file.path, stringConstantsIn(lexedViews(file).withoutComments));}+ // A file qualifies when it imports a note-content primitive itself, or+ // when it imports ANY identifier from a file that does. The second+ // reading exists because the registration site and the handlers it+ // registers are different files since the 700-line split (task 3.19):+ // the registry holds the `name:` literals while the handler module it+ // imports holds the primitive, so the file-level rule needs the one+ // step across that import to keep finding the same surfaces. One step,+ // not a transitive closure: the aggregator that spreads every registry+ // (brain-tools.ts, tools.ts) must not qualify through it.+ const direct = new Set<string>();+ for (const file of files) {+ if (importsNoteContentPrimitive(lexedViews(file).withoutComments)) direct.add(file.path);+ }const found = new Set<string>();for (const file of files) {const text = lexedViews(file).withoutComments;- if (!importsNoteContentPrimitive(text)) continue;+ const qualifies =+ direct.has(file.path) ||+ [...importSources(file, text).values()].some((source) => direct.has(source));+ if (!qualifies) continue;for (const literal of toolNameLiteralsIn(text)) {if (realToolNames.has(literal)) found.add(literal);}diff --git a/tests/core/brain/doctor-store.test.ts b/tests/core/brain/doctor-store.test.tsindex dee03ee5..dfbd1cc6 100644--- a/tests/core/brain/doctor-store.test.ts+++ b/tests/core/brain/doctor-store.test.ts@@ -20,6 +20,7 @@ import { tmpdir } from "node:os";import { dirname, join } from "node:path";import { runDoctor } from "../../../src/core/brain/doctor.ts";+import { PERMISSIONS_UNREADABLE_CODE } from "../../../src/core/brain/doctor/permissions-check.ts";import { nextCommandField } from "../../../src/core/brain/next-step.ts";import {STORE_CLOCK_AHEAD_CODE,@@ -53,6 +54,7 @@ import { publishStateDigest } from "../../../src/core/store/state-digest.ts";import { inspectStore, openStore, type StoreHandle } from "../../../src/core/store/store-open.ts";import { initStore } from "../../../src/core/store/store-init.ts";import { ensureStore } from "../store/fixtures/temp-store.ts";+import { switchDevice } from "./store-only/fixtures.ts";import {STORE_SHARD_BLOB_PENDING_CODE,STORE_SHARD_CORRUPT_LINE_CODE,@@ -276,6 +278,43 @@ describe("store in use", () => {}});+ test("below local reach the permissions-unreadable finding keeps its code without the lost partition's name", () => {+ process.env[STORE_ROOT_ENV] = storeRoot;+ process.env["O2B_DEVICE_ID"] = "dev-a";+ ensureStore(storeRoot);+ switchDevice(storeRoot);+ rmSync(join(storeRoot, "private", "store.json"));+ const unreadableOf = (opts: { withholdsPrivate?: true; reach?: "remote" }) =>+ runDoctor(vault, { now: new Date(NOW), ...opts }).errors.filter(+ (i) => i.code === PERMISSIONS_UNREADABLE_CODE,+ );+ const local = unreadableOf({});+ expect(local).toHaveLength(1);+ // Local reach names the cause: the held partition's lost identity file.+ expect(local[0]!.message).toContain("private/store.json");+ for (const opts of [{ withholdsPrivate: true } as const, { reach: "remote" } as const]) {+ const remote = unreadableOf(opts);+ expect(remote).toHaveLength(1);+ // The finding keeps its code and its source label; the cause is the+ // store check's own redacted detail.+ expect(remote[0]!.message).toContain("could not be opened");+ expect(remote[0]!.message).not.toContain("private");+ // The whole serialized answer names no partition and no remedy+ // (`private/`, not the bare word: on macOS the temp root itself+ // resolves under `/private/var`, and the redacted finding keeps the+ // store root).+ const whole = JSON.stringify(runDoctor(vault, { now: new Date(NOW), ...opts }));+ // The redacted finding keeps the store root, and the temporary store+ // root itself may resolve under a private partition on some hosts+ // (macOS `/private/var`): the allowed root is cut out before the+ // check, so only a `private/` spelling OUTSIDE the permitted root+ // still fails.+ const outsideRoot = whole.split(storeRoot).join("");+ expect(outsideRoot).not.toContain("private/");+ expect(whole).not.toContain("partition leave private");+ }+ });+test("a store that never held private on this machine is no finding", () => {process.env[STORE_ROOT_ENV] = storeRoot;initStore({ root: storeRoot, partitions: ["shared"] });diff --git a/tests/core/brain/permissions/document-source.test.ts b/tests/core/brain/permissions/document-source.test.tsindex 51886d73..c757406b 100644--- a/tests/core/brain/permissions/document-source.test.ts+++ b/tests/core/brain/permissions/document-source.test.ts@@ -119,6 +119,27 @@ describe("permissions.document setting", () => {expect(refusal(() => resolveWriteDisposition(env!.vault, "notes"))).toBe("WriteRefusedError");});+ test("a lost private partition stays out of the write gate's refusal text", () => {+ env = makeStoreEnv("osb-perm-src-lost-private-");+ switchDevice(env.storeRoot);+ // A read on the switched machine records the partitions it holds.+ expect(loadPermissionsDocumentFor(env.vault).document).toBeNull();+ rmSync(join(env.storeRoot, "private", "store.json"));+ let caught: unknown = null;+ try {+ resolveWriteDisposition(env.vault, "notes");+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(PermissionsDocumentError);+ const err = caught as PermissionsDocumentError;+ expect(err.message).toContain(PERMISSIONS_SETTING_LABEL);+ expect(err.message).not.toContain("private/");+ expect(err.message).not.toContain("partition leave");+ // The raw cause rides along for the operator's own doctor.+ expect((err.cause as Error).message).toContain("private/store.json");+ });+test("with no vault the deny still holds", () => {env = makeStoreEnv("osb-perm-src-novault-", { legacyTree: false, configureVault: false });expect(refusal(() => resolveWriteDisposition(null, "signals"))).toBe("none");diff --git a/tests/core/brain/store-signal-forget.test.ts b/tests/core/brain/store-signal-forget.test.tsindex 0ec94299..45b8cbda 100644--- a/tests/core/brain/store-signal-forget.test.ts+++ b/tests/core/brain/store-signal-forget.test.ts@@ -100,6 +100,20 @@ test("a removal while a shard of the signal is gone since this machine read it rexpect(() => removeStoreSignal(env!.vault, id)).toThrow(StoreWriteError);expect(tombstonesIn("shared")).toBe(0);expect(tombstonesIn("private")).toBe(0);+ // The refusal carries no caller reach, so it never names the private+ // shard's path (which names the device that wrote it): it counts it.+ let refused: unknown;+ try {+ removeStoreSignal(env!.vault, id);+ } catch (err) {+ refused = err;+ }+ expect(refused).toBeInstanceOf(StoreWriteError);+ const message = (refused as Error).message;+ expect(message).toContain("1 private events shard");+ expect(message).not.toContain("private/");+ expect(message).not.toContain(".jsonl");+ expect(message).not.toContain("dev-b");});test("a removal whose shared tombstone failed is finished by a retry", () => {diff --git a/tests/core/brain/temporal/foresight.test.ts b/tests/core/brain/temporal/foresight.test.tsindex 15b83b94..e85d64cc 100644--- a/tests/core/brain/temporal/foresight.test.ts+++ b/tests/core/brain/temporal/foresight.test.ts@@ -7,7 +7,7 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -114,4 +114,67 @@ describe("buildForesight", () => {expect(a.upcoming.length).toBeLessThanOrEqual(FORESIGHT_MAX_ITEMS);expect(a).toEqual(b);});++ test("withholdsPrivate drops private extracts and keeps the readable ones", () => {+ seedExtract("commitment", "A private promise nobody may see", "2026-06-01T10:00:00Z");+ appendContinuityRecord(vault, {+ kind: "pre_compact_extract",+ createdAt: "2026-06-02T10:00:00Z",+ sourceRefs: [{ id: "sess-private", kind: "session" }],+ payload: { extract_type: "commitment", text: "An open commitment marked private" },+ private: true,+ });++ // Local reach: the fold is unfiltered and carries both.+ const local = buildForesight(vault, { now: NOW });+ expect(local.upcoming.find((u) => u.title.includes("marked private"))).toBeDefined();++ // Below local reach: the private record is dropped whole - its text+ // and its source refs with it - and the readable extract stays.+ const remote = buildForesight(vault, { now: NOW, withholdsPrivate: true });+ expect(remote.upcoming.find((u) => u.title.includes("marked private"))).toBeUndefined();+ expect(remote.upcoming.find((u) => u.title.includes("private promise"))).toBeDefined();+ });++ test("withholdsPrivate drops recurrence support from private-classified events; local keeps it", () => {+ // A recurrence event whose scope names a private page is classified+ // private by the writer's own checks, and that scope is what the+ // projected item title carries - so below local reach the private+ // event's support is dropped before the cadences are built, and the+ // routine does not surface (nor does a residual support count or+ // commitment). Local reach keeps the unfiltered projection.+ mkdirSync(join(vault, "Notes"), { recursive: true });+ writeFileSync(+ join(vault, "Notes", "secret.md"),+ "---\nvisibility: [private]\n---\n\n# secret\n",+ );+ applyRecurrenceEvidence(vault, {+ contentHash: "privcd",+ scope: "[[Notes/secret]]",+ sourceId: "session-priv-a",+ action: "learn",+ at: "2026-05-28T09:00:00Z",+ });+ applyRecurrenceEvidence(vault, {+ contentHash: "privcd",+ scope: "[[Notes/secret]]",+ sourceId: "session-priv-b",+ action: "learn",+ at: "2026-06-03T09:00:00Z",+ });++ // Local reach: the routine projects, named by its (here readable)+ // scope.+ const local = buildForesight(vault, { now: NOW });+ const localRecurring = local.upcoming.filter((u) => u.kind === "recurring");+ expect(localRecurring).toHaveLength(1);+ expect(localRecurring[0]!.title).toContain("Notes/secret");+ expect(localRecurring[0]!.sources).toContain("recurrence:privcd");++ // Below local reach: the whole routine is withheld - no title, no+ // due date, no support count, no commitment.+ const remote = buildForesight(vault, { now: NOW, withholdsPrivate: true });+ expect(remote.upcoming.filter((u) => u.kind === "recurring")).toHaveLength(0);+ expect(JSON.stringify(remote)).not.toContain("secret");+ });});diff --git a/tests/core/store/shard-quarantine.test.ts b/tests/core/store/shard-quarantine.test.tsindex 257a5ae1..294176cb 100644--- a/tests/core/store/shard-quarantine.test.ts+++ b/tests/core/store/shard-quarantine.test.ts@@ -7,19 +7,27 @@* record is still left out until the blob arrives, and the migration's* refusals still see it.*/-import { afterEach, describe, expect, test } from "bun:test";+import { afterEach, describe, expect, spyOn, test } from "bun:test";+import * as fs from "node:fs";import {+ chmodSync,existsSync,mkdirSync,readFileSync,+ readdirSync,renameSync,rmSync,statSync,symlinkSync,+ utimesSync,writeFileSync,} from "node:fs";import { dirname, join, relative } from "node:path";+import {+ buildEntityIndex,+ __clearEntityIndexCache,+} from "../../../src/core/brain/entities/index-builder.ts";import { buildCaptureBoundary } from "../../../src/core/brain/capture-boundary.ts";import { BrainSettingsUnreadableError } from "../../../src/core/brain/policy/errors.ts";import { readBrainSettingsFromStore } from "../../../src/core/brain/policy/settings-source.ts";@@ -27,12 +35,14 @@ import { brainSettingKey } from "../../../src/core/store-migration/brain-settingimport { readHeldRecords } from "../../../src/core/store-migration/journal.ts";import { appendRecord } from "../../../src/core/store/appender.ts";import { laneStoreFold } from "../../../src/core/store/lane-fold-cache.ts";+import { laneStoreStamp } from "../../../src/core/store/lane-pages.ts";import {PINNED_SET_KIND,SETTING_SET_KIND,STORE_LINE_CAP_BYTES,} from "../../../src/core/store/constants.ts";import { LANE_ENTRY_KIND } from "../../../src/core/store/lane-records.ts";+import { BRAIN_ENTITY_KIND } from "../../../src/core/brain/entities/types.ts";import { readEntitiesOf } from "../../../src/core/store/read/store-entities.ts";import { readStreamRecords } from "../../../src/core/store/read/stream-read.ts";import { readShard, shardReadGap } from "../../../src/core/store/reader.ts";@@ -52,6 +62,7 @@ import {import { inspectStore, openStore } from "../../../src/core/store/store-open.ts";import { partitionDir } from "../../../src/core/store/store-paths.ts";import { switchDevice } from "../brain/store-only/fixtures.ts";+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";import { makeStoreEnv, type StoreEnv } from "./fixtures/store-env.ts";let env: StoreEnv | null = null;@@ -676,7 +687,7 @@ function quarantinedPending(e: StoreEnv, kind: string, body: Record<string, unknconst BIG = "x".repeat(20_000);describe("a cached read that skipped a quarantined pending record", () => {- test("the entity read shows the record once its blob arrives, in the same process", () => {+ test("the entity read is served from the cache while the blob is absent, and shows the record once it arrives", () => {env = makeStoreEnv("osb-quarantine-entities-blob-", { legacyTree: false });const deliver = quarantinedPending(env, PINNED_SET_KIND, {authority: "human",@@ -684,14 +695,32 @@ describe("a cached read that skipped a quarantined pending record", () => {});const pinned = () =>readEntitiesOf(inspectStore(env!.storeRoot)!).pinned.get("shared")?.content ?? null;+ // The first read builds and stores its fingerprint with the skipped+ // blob's absence stamp, so the next read is already a cache hit.expect(pinned()).toBeNull();- // Read twice before the blob arrives, so a cache would be warm.- expect(pinned()).toBeNull();- deliver();- expect(pinned()).toBe(BIG);+ const open = spyOn(fs, "openSync");+ const readFile = spyOn(fs, "readFileSync");+ const shardReads = (): string[] =>+ [...open.mock.calls, ...readFile.mock.calls]+ .map((call) => String(call[0]))+ .filter((p) => p.startsWith(env!.storeRoot) && p.endsWith(".jsonl"));+ try {+ expect(pinned()).toBeNull();+ expect(shardReads()).toEqual([]);+ deliver();+ // The blob's arrival moves the fingerprint's blob stamp, so the+ // next read rebuilds - and a rebuild is seen by the same spies,+ // which proves the empty list above is the cache and not a blind+ // spy.+ expect(pinned()).toBe(BIG);+ expect(shardReads().length).toBeGreaterThan(0);+ } finally {+ open.mockRestore();+ readFile.mockRestore();+ }});- test("the lane fold shows the entry once its blob arrives, in the same process", () => {+ test("the lane fold is served from the cache while the blob is absent, and folds the entry once it arrives", () => {env = makeStoreEnv("osb-quarantine-lane-blob-", { legacyTree: false });switchDevice(env.storeRoot);const deliver = quarantinedPending(env, LANE_ENTRY_KIND, {@@ -705,8 +734,235 @@ describe("a cached read that skipped a quarantined pending record", () => {[...laneStoreFold().entries.values()].find((v) => v.text === BIG)?.text ?? null;expect(laneStoreFold().unreadable).toEqual([]);expect(text()).toBeNull();- expect(text()).toBeNull();+ // The fold is stored with the skipped blob's absence stamp, so the+ // next fold is already a cache hit.+ const open = spyOn(fs, "openSync");+ const readFile = spyOn(fs, "readFileSync");+ const shardReads = (): string[] =>+ [...open.mock.calls, ...readFile.mock.calls]+ .map((call) => String(call[0]))+ .filter((p) => p.startsWith(env!.storeRoot) && p.endsWith(".jsonl"));+ try {+ expect(text()).toBeNull();+ expect(shardReads()).toEqual([]);+ deliver();+ // The blob's arrival moves the fingerprint's blob stamp, so the+ // next fold rebuilds - seen by the same spies, which proves the+ // empty list above is the cache and not a blind spy.+ expect(text()).toBe(BIG);+ expect(shardReads().length).toBeGreaterThan(0);+ } finally {+ open.mockRestore();+ readFile.mockRestore();+ }+ });++ test("a same-size blob repaired in place with its mtime kept is picked up", () => {+ env = makeStoreEnv("osb-quarantine-entities-repair-", { legacyTree: false });+ const deliver = quarantinedPending(env, PINNED_SET_KIND, {+ authority: "human",+ content: BIG,+ });deliver();- expect(text()).toBe(BIG);+ const blobsDir = join(shared(env), "blobs");+ const [ab] = readdirSync(blobsDir);+ const [name] = readdirSync(join(blobsDir, ab!));+ const blobFile = join(blobsDir, ab!, name!);+ const good = readFileSync(blobFile);+ const stat = statSync(blobFile);+ const pinned = () =>+ readEntitiesOf(inspectStore(env!.storeRoot)!).pinned.get("shared")?.content ?? null;+ // Corrupt the blob in place at the same size and put the mtime back:+ // only the reader's own hash check refuses it now.+ writeFileSync(+ blobFile,+ Buffer.concat([good.subarray(0, -1), Buffer.from([good[good.length - 1]! ^ 0xff])]),+ );+ utimesSync(blobFile, stat.atime, stat.mtime);+ expect(pinned()).toBeNull();+ // The repair also keeps size and mtime; only the content and the+ // blob's ctime move, so the refused-blob state was never cached and+ // the next read picks the repaired blob up.+ writeFileSync(blobFile, good);+ utimesSync(blobFile, stat.atime, stat.mtime);+ expect(pinned()).toBe(BIG);});});++describe("the entity index on a store-only machine", () => {+ const ENTITY_FIELDS = {+ kind: BRAIN_ENTITY_KIND,+ entity_id: "e1",+ category: "org",+ name: "Acme",+ status: "active",+ created_at: "2026-11-06T09:00:00Z",+ };++ function laneEntry(e: StoreEnv, entry: string, text: string): string {+ return appendRecord(+ openStore({ root: e.storeRoot, device: "dev-b" }),+ {+ partition: "shared",+ stream: "events",+ kind: LANE_ENTRY_KIND,+ agent: "t",+ body: {+ authority: "agent",+ lane: "entities",+ entry,+ fields: ENTITY_FIELDS,+ text,+ },+ },+ // An October shard: the quarantined update below lands alone in its+ // own November shard, at the line offset the helper expects.+ { now: () => Date.UTC(2026, 9, 6, 9) },+ ).path;+ }++ /** A lane entry whose record lands in the month `ms` falls in. */+ function laneEntryIn(e: StoreEnv, entry: string, text: string, ms: number): string {+ return appendRecord(+ openStore({ root: e.storeRoot, device: "dev-b" }),+ {+ partition: "shared",+ stream: "events",+ kind: LANE_ENTRY_KIND,+ agent: "t",+ body: {+ authority: "agent",+ lane: "entities",+ entry,+ fields: { ...ENTITY_FIELDS, entity_id: entry.split("/")[1] },+ text,+ },+ },+ { now: () => ms },+ ).path;+ }++ test("a lane update's pending blob arriving moves the index stamp", () => {+ env = makeStoreEnv("osb-quarantine-index-blob-", { legacyTree: false });+ switchDevice(env.storeRoot);+ laneEntry(env, "org/e1", "v1 body");+ __clearEntityIndexCache();+ const body = (): string =>+ buildEntityIndex(env!.vault).entities.find((entity) => entity.id === "e1")?.body ?? "missing";+ // The first build warms the index memo on the page as it is.+ expect(body()).toBe("v1 body");+ // An update of the same page lands with its body as a quarantined+ // pending blob: the page list and every shard stamp stay the same.+ const deliver = quarantinedPending(env, LANE_ENTRY_KIND, {+ authority: "agent",+ lane: "entities",+ entry: "org/e1",+ fields: ENTITY_FIELDS,+ text: BIG,+ });+ expect(body()).toBe("v1 body");+ deliver();+ // The blob's arrival moves the lane stamp, so the memo no longer+ // serves the old build.+ expect(body()).toBe(BIG);+ });++ test("an unreadable shard leaves a deterministic stamp, so the index memo keeps hitting", () => {+ env = makeStoreEnv("osb-quarantine-index-incomplete-", { legacyTree: false });+ switchDevice(env.storeRoot);+ const october = laneEntry(env, "org/e1", "v1 body");+ // A second entity whose winning record survives on the November+ // shard, so the degraded index still has a page to serve.+ laneEntryIn(env, "org/e2", "e2 body", NOV);+ __clearEntityIndexCache();+ const body = (): string =>+ buildEntityIndex(env!.vault).entities.find((entity) => entity.id === "e2")?.body ?? "missing";+ // The first build warms the memo and the seen-shard tracking.+ expect(body()).toBe("e2 body");+ // A shard this machine read and that is gone now leaves the fold+ // uncached - but its stamp is deterministic and carries the+ // `incomplete` prefix: no healthy stamp can match it.+ const octoberBytes = readFileSync(october);+ rmSync(october);+ const degraded = laneStoreStamp(env!.vault);+ expect(degraded).toContain("incomplete");+ const open = spyOn(fs, "openSync");+ const readFile = spyOn(fs, "readFileSync");+ const shardReads = (): string[] =>+ [...open.mock.calls, ...readFile.mock.calls]+ .map((call) => String(call[0]))+ .filter((p) => p.startsWith(env!.storeRoot) && p.endsWith(".jsonl"));+ try {+ // The degraded build is stable: the same stamp, the same answer.+ // The signature's stamp still costs one fold rebuild (the fold+ // itself stays uncached), but the memo absorbs the rest: a cold+ // build parses every entity page, one fold per page, a warm one+ // pays only the signature. Before the deterministic stamp the+ // memo never hit, so every build paid the cold price.+ expect(laneStoreStamp(env!.vault)).toBe(degraded);+ __clearEntityIndexCache();+ expect(body()).toBe("e2 body");+ const cold = shardReads().length;+ expect(cold).toBeGreaterThan(0);+ expect(body()).toBe("e2 body");+ const warm = shardReads().length - cold;+ expect(warm).toBeGreaterThan(0);+ expect(warm).toBeLessThan(cold);+ // Once the shard reads again (sync delivers it back), the stamp+ // moves, the incomplete prefix is gone, and the next build is a+ // fresh, healthy one.+ writeFileSync(october, octoberBytes);+ expect(laneStoreStamp(env!.vault)).not.toBe(degraded);+ expect(laneStoreStamp(env!.vault)).not.toContain("incomplete");+ expect(body()).toBe("e2 body");+ expect(shardReads().length).toBeGreaterThan(cold + warm);+ } finally {+ open.mockRestore();+ readFile.mockRestore();+ }+ });++ // The transient-unreadable state is a permission denial, which chmod+ // cannot produce everywhere (root reads through any mode, Windows maps+ // it to read-only), so the pair-of-states fixture skips there.+ test.skipIf(CHMOD_CANNOT_DENY)(+ "an unreadable shard's stamp moves when the records the fold saw change",+ () => {+ env = makeStoreEnv("osb-quarantine-stamp-records-", { legacyTree: false });+ switchDevice(env.storeRoot);+ // Three lane entries in ONE shard: the two degraded states below share+ // that shard's stamp, its `unreadable` name and its pending blobs -+ // only the records the fold managed to read differ.+ const shard = laneEntry(env, "org/e1", "v1 body");+ laneEntry(env, "org/e2", "v2 body");+ laneEntry(env, "org/e3", "v3 body");+ // A corrupt middle line, rewritten at an equal length and stamped back+ // to the shard's original mtime, so the shard's size and mtime are+ // frozen across both states.+ const identity = statSync(shard);+ editLine(shard, 1, (line) => "x".repeat(line.length));+ utimesSync(shard, identity.atime, identity.mtime);++ // State A: a transient open failure - the shard is unreadable and the+ // fold saw NONE of its records.+ chmodSync(shard, 0o000);+ let unseen: string;+ try {+ unseen = laneStoreStamp(env!.vault);+ expect(unseen).toContain("incomplete");+ // The same degraded state stamps the same way twice.+ expect(laneStoreStamp(env!.vault)).toBe(unseen);+ } finally {+ chmodSync(shard, 0o644);+ }+ // State B: the same bytes, now read in part - the corrupt line is a+ // read gap and the fold carries the two records around it. Without the+ // contributing records in the fingerprint this stamp equals state A's,+ // and a memo keyed by it would serve the record-less build.+ const gapped = laneStoreStamp(env!.vault);+ expect(gapped).toContain("incomplete");+ expect(gapped).not.toBe(unseen);+ expect(laneStoreStamp(env!.vault)).toBe(gapped);+ },+ );+});diff --git a/tests/core/store/store-paths.test.ts b/tests/core/store/store-paths.test.tsindex 9f16d672..2c73734a 100644--- a/tests/core/store/store-paths.test.ts+++ b/tests/core/store/store-paths.test.ts@@ -1,11 +1,21 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { mkdirSync, mkdtempSync, rmSync, symlinkSync } from "node:fs";+import {+ mkdirSync,+ mkdtempSync,+ renameSync,+ rmSync,+ statSync,+ symlinkSync,+ utimesSync,+ writeFileSync,+} from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { STORE_ROOT_CONFIG_KEY, STORE_ROOT_ENV } from "../../../src/core/store/constants.ts";import {blobPath,+ blobStamp,deviceStateDirFor,isPathInside,partitionDir,@@ -200,3 +210,59 @@ describe("store layout paths", () => {).toThrow();});});++describe("the blob availability stamp", () => {+ const SHA = "ab".padEnd(64, "0");+ const BLOB = "hello";++ let root = "";+ let partitionRoot = "";+ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), "o2b-blobstamp-"));+ partitionRoot = partitionDir(root, "shared");+ mkdirSync(join(partitionRoot, "blobs", "ab"), { recursive: true });+ });+ afterEach(() => rmSync(root, { recursive: true, force: true }));++ test("an absent blob reads as absent, a present one by its identity", () => {+ expect(blobStamp(partitionRoot, SHA)).toBe("absent");+ writeFileSync(blobPath(partitionRoot, SHA), BLOB);+ expect(blobStamp(partitionRoot, SHA)).not.toBe("absent");+ expect(blobStamp(partitionRoot, "zz")).toBe("absent");+ });++ test("a link swapped for the real file moves the stamp at a standstill of size and mtime", () => {+ writeFileSync(blobPath(partitionRoot, SHA), BLOB);+ const blobFile = blobPath(partitionRoot, SHA);+ const before = blobStamp(partitionRoot, SHA);+ // A twin of the same size, its mtime set back to the original's, with+ // the blob path turned into a link to it: the reader refuses the link,+ // and a size:mtime stamp would not notice the swap.+ const twin = join(root, "twin");+ writeFileSync(twin, BLOB);+ const stat = statSync(blobFile);+ utimesSync(twin, stat.atime, stat.mtime);+ rmSync(blobFile);+ symlinkSync(twin, blobFile, "file");+ expect(blobStamp(partitionRoot, SHA)).not.toBe(before);+ // The operator repairs the link in place (`mv`, `cp -p`): the size and+ // the mtime stay, only ctime moves.+ rmSync(blobFile);+ writeFileSync(blobFile, BLOB);+ utimesSync(blobFile, stat.atime, stat.mtime);+ expect(blobStamp(partitionRoot, SHA)).not.toBe(before);+ });++ test("the blobs/<ab> folder's identity is stamped too", () => {+ writeFileSync(blobPath(partitionRoot, SHA), BLOB);+ const abDir = join(partitionRoot, "blobs", "ab");+ const before = blobStamp(partitionRoot, SHA);+ // The blob's own folder arrives as a link (a synced move): the blob+ // file keeps its identity, the folder's does not, and the reader+ // refuses a blob whose fan-out folder is a link.+ const kept = join(root, "ab-real");+ renameSync(abDir, kept);+ symlinkSync(kept, abDir, "dir");+ expect(blobStamp(partitionRoot, SHA)).not.toBe(before);+ });+});diff --git a/tests/mcp/brain-audit-reach.test.ts b/tests/mcp/brain-audit-reach.test.tsnew file mode 100644index 00000000..dbb4ce10--- /dev/null+++ b/tests/mcp/brain-audit-reach.test.ts@@ -0,0 +1,201 @@+/**+ * `brain_audit` answers at the caller's reach. The mutation history of a+ * preference is the trail of that preference's page and is private with+ * it: each record names the agent, the reason and the revision hashes of+ * a page the caller may not be able to read at all. The handler therefore+ * asks the same view every sibling reader asks before reading the trail,+ * and a withheld trail answers as an absent one - the empty history -+ * never as a refusal that would prove the id exists.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { brainConfigPath } from "../../src/core/brain/paths.ts";+import { writePreference } from "../../src/core/brain/preference.ts";+import { appendPrefAudit } from "../../src/core/brain/pref-audit.ts";+import { BRAIN_PREFERENCE_STATUS, PREF_AUDIT_OP } from "../../src/core/brain/types.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";+import { buildToolTable } from "../../src/mcp/tools.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";++const WITHHELD_MARKER = "zzwithheldreasonzz";+const RESERVE_LINE = `visibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]`;++let tmp: string;+let vault: string;+let configHome: string;+let configPath: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-brain-audit-reach-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ configHome = mkdtempSync(join(tmpdir(), "o2b-brain-audit-reach-cfg-"));+ configPath = join(configHome, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);+ bootstrapBrain(vault, { configPath });+ confirmed("shared", "Prefer short sentences.");+ confirmed("withheld", "A rule reserved against remote reads.");+ reserve(join(vault, "Brain", "preferences", "pref-withheld.md"));+ audit("pref-shared", "readable trail");+ audit("pref-withheld", WITHHELD_MARKER);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+});++function confirmed(slug: string, principle: string): void {+ writePreference(vault, {+ slug,+ topic: slug,+ principle,+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by: [],+ confirmed_at: "2026-05-02T00:00:00Z",+ });+}++/** Insert frontmatter lines into a preference page already on disk. */+function reserve(abs: string): void {+ const text = readFileSync(abs, "utf8");+ const close = text.indexOf("\n---\n", "---\n".length);+ writeFileSync(abs, `${text.slice(0, close)}\n${RESERVE_LINE}${text.slice(close)}`);+}++function audit(prefId: string, reason: string): void {+ appendPrefAudit(+ vault,+ {+ pref_id: prefId,+ op: PREF_AUDIT_OP.create,+ agent: "dream",+ reason,+ revision_before: null,+ revision_after: 1,+ hash_before: null,+ hash_after: "abc123",+ },+ { now: new Date("2026-05-29T12:00:00Z") },+ );+}++async function auditCall(reach: TransportReach, prefId: string): Promise<Record<string, unknown>> {+ const server = new MCPServer({ vault, configPath }, { reach });+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: "audit-reach-test", version: "0" },+ },+ });+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });+ const response = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 9,+ method: "tools/call",+ params: { name: "brain_audit", arguments: { pref_id: prefId } },+ })) as { result: { content: ReadonlyArray<{ type: string; text: string }> } };+ return JSON.parse(response.result.content[0]!.text) as Record<string, unknown>;+}++describe("brain_audit at remote reach", () => {+ test("the trail of a withheld preference answers as an absent one", async () => {+ const remote = await auditCall(TRANSPORT_REACH.remote, "pref-withheld");+ expect(remote["count"]).toBe(0);+ expect(remote["records"]).toEqual([]);+ expect(JSON.stringify(remote)).not.toContain(WITHHELD_MARKER);+ // Identical to absent: the same answer an unknown id gives, so the+ // empty history proves nothing about the preference's existence.+ const absent = await auditCall(TRANSPORT_REACH.remote, "pref-never-was");+ const { pref_id: _echoed, ...withheldShape } = remote as Record<string, unknown>;+ const { pref_id: _absentId, ...absentShape } = absent as Record<string, unknown>;+ expect(withheldShape).toEqual(absentShape);+ });++ test("a readable preference keeps its trail at remote reach", async () => {+ const remote = await auditCall(TRANSPORT_REACH.remote, "pref-shared");+ expect(remote["count"]).toBe(1);+ expect((remote["records"] as Array<Record<string, unknown>>)[0]!["reason"]).toBe(+ "readable trail",+ );+ });++ test("local reach keeps the withheld trail", async () => {+ const local = await auditCall(TRANSPORT_REACH.local, "pref-withheld");+ expect(local["count"]).toBe(1);+ expect(JSON.stringify(local)).toContain(WITHHELD_MARKER);+ });+});++/**+ * The ownership half of the same rule, under+ * `integrity.owner_scope_delivery: fail`: the trail is private with the+ * preference's OWNER too. `requestRefView` asks+ * `readableAtContextReachOrUndefined`, which binds the ownership rule to+ * the same request, so the trail of another owner's preference answers as+ * an absent one even at local reach - and the owner's own trail is kept.+ */+describe("brain_audit under integrity.owner_scope_delivery: fail", () => {+ const OWNER_A = "agent-a";+ const CALLER = "agent-b";+ const FOREIGN = "foreign-slug";+ const OWN = "own-slug";++ beforeEach(() => {+ confirmed(FOREIGN, "A rule owned by another scope.");+ confirmed(OWN, "A rule owned by the caller.");+ stampOwner(join(vault, "Brain", "preferences", `pref-${FOREIGN}.md`), OWNER_A);+ stampOwner(join(vault, "Brain", "preferences", `pref-${OWN}.md`), CALLER);+ audit(`pref-${FOREIGN}`, "foreign trail");+ audit(`pref-${OWN}`, "own trail");+ // The gate reads the brain config, so it is set AFTER the seeding+ // writes, which must not be owner-stamped by the gate itself.+ writeFileSync(+ brainConfigPath(vault),+ "schema_version: 1\nintegrity:\n owner_scope_delivery: fail\n",+ );+ });++ function stampOwner(abs: string, owner: string): void {+ const text = readFileSync(abs, "utf8");+ writeFileSync(abs, text.replace("---\n", `---\nowner: ${owner}\n`));+ }++ async function auditAs(prefId: string, agentName: string): Promise<Record<string, unknown>> {+ const tool = buildToolTable("full").find((t) => t.name === "brain_audit")!;+ const ctx: ServerContext = {+ vault,+ configPath,+ repoRoot: null,+ agentName,+ reach: TRANSPORT_REACH.local,+ };+ return (await tool.handler(ctx, { pref_id: prefId })) as Record<string, unknown>;+ }++ test("another owner's trail answers as an absent one at local reach", async () => {+ const foreign = await auditAs(`pref-${FOREIGN}`, CALLER);+ expect(foreign["count"]).toBe(0);+ expect(foreign["records"]).toEqual([]);+ expect(JSON.stringify(foreign)).not.toContain("foreign trail");++ // The caller's own trail is kept: the absence is the ownership rule.+ const own = await auditAs(`pref-${OWN}`, CALLER);+ expect(own["count"]).toBe(1);+ expect(JSON.stringify(own)).toContain("own trail");+ });+});diff --git a/tests/mcp/brain-bridges-visibility.test.ts b/tests/mcp/brain-bridges-visibility.test.tsindex af7d8f5d..9e304b41 100644--- a/tests/mcp/brain-bridges-visibility.test.ts+++ b/tests/mcp/brain-bridges-visibility.test.ts@@ -19,11 +19,13 @@*/import { test, expect, beforeEach, afterEach, describe } from "bun:test";-import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs";+import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { indexVault, resolveSearchConfig } from "../../src/core/search/index.ts";+import { writeBridgeProposals } from "../../src/core/brain/link-graph/bridge-discovery.ts";+import { brainConfigPath } from "../../src/core/brain/paths.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";@@ -98,3 +100,214 @@ describe("brain_bridges operation=discover", () => {expect(remote.scanned_candidates).toBe(local.scanned_candidates);});});++describe("brain_bridges list reads the artifact discover wrote", () => {+ test("a proposal path containing parentheses round-trips writer to parser", async () => {+ // `writeBridgeProposals` emits the path unchanged inside the source+ // cell - `[[Design (v2)]] (Notes/Design (v2).md)` - so the parser+ // must take the path up to the cell's final parenthesis, not the+ // first one. A parser that stops early cannot read the row back,+ // and the whole artifact then answers as absent even at local reach.+ const source = "Notes/Design (v2).md";+ const target = "Notes/Spec (v2).md";+ mkdirSync(join(vault, "Notes"), { recursive: true });+ writeFileSync(join(vault, source), "# Design\n\nSee [[Spec (v2)]].\n");+ writeFileSync(join(vault, target), "# Spec\n\nSee [[Design (v2)]].\n");+ writeBridgeProposals(+ vault,+ {+ proposals: [{ source, target, similarity: 0.8, sourceInbound: 1, targetInbound: 1 }],+ scannedCandidates: 2,+ vecAvailable: true,+ },+ { now: new Date("2026-06-04T12:00:00Z") },+ );+ const tool = BRAIN_TOOLS.find((t) => t.name === "brain_bridges")!;+ const ctx: ServerContext = { vault, reach: TRANSPORT_REACH.local, configPath, repoRoot: null };+ const out = (await tool.handler(ctx, { operation: "list" })) as Record<string, unknown>;+ expect(out["exists"]).toBe(true);+ expect(out["proposals"]).toBe(1);+ });+});++describe("brain_clusters operation=run", () => {+ /** Four mutually linked pages, one of them the reserved one. */+ async function writeCommunity(): Promise<void> {+ const group = ["team-a", "team-b", "team-c", RESERVED];+ for (const name of group) {+ const others = group+ .filter((g) => g !== name)+ .map((g) => `[[${g}]]`)+ .join(" ");+ const frontmatter =+ name === RESERVED ? `---\nvisibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]\n---\n\n` : "";+ writeFileSync(join(vault, `${name}.md`), `${frontmatter}# ${name}\n\nSee ${others}.\n`);+ }+ await indexVault(resolveSearchConfig({ vault, configPath }));+ }++ async function clusters(reach: TransportReach): Promise<Record<string, unknown>> {+ const tool = BRAIN_TOOLS.find((t) => t.name === "brain_clusters")!;+ const ctx: ServerContext = { vault, reach, configPath, repoRoot: null };+ return (await tool.handler(ctx, { operation: "run", batch_size: 1 })) as Record<+ string,+ unknown+ >;+ }++ test("each batch is filtered by the same visibility rules as the top-level result", async () => {+ await writeCommunity();+ const remote = await clusters(TRANSPORT_REACH.remote);+ const body = JSON.stringify(remote);+ // Every detected community names the reserved page, so a remote+ // caller sees no community and therefore NO batch: the offsets and+ // index count detected communities, and a `{start: 0, end: 1}` beside+ // an empty `communities` would show that a withheld community exists+ // and how many there are. No batch may name the cluster note its+ // seed produced (or any stale removal, or a raw write error's seed+ // path) either - `batch_size` must not be the side door back in.+ expect(remote["batches"]).toEqual([]);+ expect(remote["communities"]).toEqual([]);+ expect(body).not.toContain("Brain/clusters/");+ expect(body).not.toContain(RESERVED);++ // The unrestricted view keeps the batches verbatim: the note this run+ // materialised is reported.+ const local = await clusters(TRANSPORT_REACH.local);+ const localBatches = local["batches"] as Array<Record<string, unknown>> | undefined;+ expect(localBatches).toHaveLength(1);+ expect((localBatches as Array<{ written: string[] }>)[0]!.written.length).toBeGreaterThan(0);+ expect(JSON.stringify(local)).toContain("Brain/clusters/");+ });+});++/**+ * The ownership half of the same root closure: a proposal names two pages+ * by path, so under `integrity.owner_scope_delivery: fail` a proposal+ * naming another owner's page is dropped whole, and a lane page carrying+ * an owner is answered only to that owner - the same composed view every+ * sibling reader asks.+ */+describe("brain_bridges under integrity.owner_scope_delivery: fail", () => {+ const OWNER_A = "agent-a";+ const CALLER = "agent-b";+ const OWNED_A = "canary-alpha.md";+ const OWNED_B = "canary-beta.md";++ /** A near-identical pair owned by `OWNER_A`, indexed into the vec store. */+ async function writeOwnedPair(): Promise<void> {+ const body =+ "Release the candidate build to staging, watch error rates closely, expand gradually, roll back on regression.";+ for (const name of [OWNED_A, OWNED_B]) {+ writeFileSync(join(vault, name), `---\nowner: ${OWNER_A}\n---\n\n# ${name}\n\n${body}\n`);+ }+ await indexVault(resolveSearchConfig({ vault, configPath }), { embeddings: true });+ }++ function setGateFail(): void {+ writeFileSync(+ brainConfigPath(vault),+ "schema_version: 1\nintegrity:\n owner_scope_delivery: fail\n",+ );+ }++ function ctxFor(reach: TransportReach, agentName?: string): ServerContext {+ return { vault, reach, configPath, repoRoot: null, agentName };+ }++ function bridgesTool() {+ return BRAIN_TOOLS.find((t) => t.name === "brain_bridges")!;+ }++ test("discover drops a pair that names another owner's pages, whole", async () => {+ await writeOwnedPair();+ setGateFail();++ // The owner sees its own pair.+ const asA = (+ (await bridgesTool().handler(ctxFor(TRANSPORT_REACH.local, OWNER_A), {+ operation: "discover",+ min_similarity: 0.5,+ })) as { proposals: ReadonlyArray<{ source: string; target: string }> }+ ).proposals;+ expect(+ asA.some((p) => p.source === OWNED_A || p.target === OWNED_A || p.source === OWNED_B),+ ).toBe(true);++ // Another scope sees neither end - the proposal is gone whole, not+ // reported with one end missing.+ const asB = (+ (await bridgesTool().handler(ctxFor(TRANSPORT_REACH.local, CALLER), {+ operation: "discover",+ min_similarity: 0.5,+ })) as { proposals: ReadonlyArray<{ source: string; target: string }> }+ ).proposals;+ expect(+ asB.some((p) => p.source === OWNED_A || p.target === OWNED_A || p.source === OWNED_B),+ ).toBe(false);+ });++ test("list answers an owner-stamped proposals artifact only to its owner", async () => {+ await writeOwnedPair();+ setGateFail();+ // Produce the shared artifact, then stamp the page with an owner - the+ // state a writer resolved under an enforced identity leaves.+ const bridges = bridgesTool();+ await bridges.handler(ctxFor(TRANSPORT_REACH.local, OWNER_A), {+ operation: "discover",+ min_similarity: 0.5,+ });+ const artifact = join(vault, "Brain", "proposals", "bridges.md");+ const text = readFileSync(artifact, "utf8");+ writeFileSync(artifact, text.replace("---\n", `---\nowner: ${OWNER_A}\n`));++ const asB = (await bridges.handler(ctxFor(TRANSPORT_REACH.local, CALLER), {+ operation: "list",+ })) as Record<string, unknown>;+ // A withheld lane page answers exactly as an absent one.+ expect(asB["exists"]).toBe(false);+ expect(asB["proposals"]).toBe(0);++ const asA = (await bridges.handler(ctxFor(TRANSPORT_REACH.local, OWNER_A), {+ operation: "list",+ })) as Record<string, unknown>;+ expect(asA["exists"]).toBe(true);+ });++ test("list counts only the rows the caller may see when the artifact is visible", async () => {+ // The artifact page itself carries no owner stamp, so the file-level+ // check passes for both callers - the count is what would leak.+ const bridges = bridgesTool();+ await writeOwnedPair();+ // A second, near-identical pair owned by the CALLER, so the shared+ // artifact holds rows of both ownerships.+ const sharedBody =+ "Roll out the candidate build to one staging host, watch the error rate, expand the rollout step by step, roll back if it regresses.";+ for (const name of ["canary-gamma.md", "canary-delta.md"]) {+ writeFileSync(+ join(vault, name),+ `---\nowner: ${CALLER}\n---\n\n# ${name}\n\n${sharedBody}\n`,+ );+ }+ await indexVault(resolveSearchConfig({ vault, configPath }), { embeddings: true });+ setGateFail();+ await bridges.handler(ctxFor(TRANSPORT_REACH.local, OWNER_A), {+ operation: "discover",+ min_similarity: 0.4,+ });++ const asA = (await bridges.handler(ctxFor(TRANSPORT_REACH.local, OWNER_A), {+ operation: "list",+ })) as Record<string, unknown>;+ const asB = (await bridges.handler(ctxFor(TRANSPORT_REACH.local, CALLER), {+ operation: "list",+ })) as Record<string, unknown>;+ // Both see the shared file; the owner counts every row, the other+ // scope counts only rows naming pages it may see.+ expect(asA["exists"]).toBe(true);+ expect(asB["exists"]).toBe(true);+ expect(Number(asA["proposals"])).toBeGreaterThan(0);+ expect(Number(asB["proposals"])).toBeGreaterThan(0);+ expect(Number(asB["proposals"])).toBeLessThan(Number(asA["proposals"]));+ });+});diff --git a/tests/mcp/brain-feedback-staged.test.ts b/tests/mcp/brain-feedback-staged.test.tsindex 70bc6760..1390a9d6 100644--- a/tests/mcp/brain-feedback-staged.test.ts+++ b/tests/mcp/brain-feedback-staged.test.ts@@ -9,13 +9,27 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { mkdtempSync, readdirSync, rmSync } from "node:fs";+import {+ appendFileSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ renameSync,+ rmSync,+ writeFileSync,+} from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { bootstrapBrain } from "../../src/core/brain/init.ts";import { brainDirs } from "../../src/core/brain/paths.ts";+import { moveToRetired } from "../../src/core/brain/preference.ts";+import { deleteBySource } from "../../src/core/brain/source-cleanup.ts";+import { sha256Hex } from "../../src/core/integrity/digest.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { PREFERENCE_MARKER_NAMESPACE } from "../../src/mcp/brain/feedback-tool.ts";import { FEEDBACK_TOOLS } from "../../src/mcp/brain/feedback-tools.ts";import type { ServerContext } from "../../src/mcp/tool-contract.ts";@@ -100,4 +114,435 @@ describe("brain_feedback staged receipt", () => {// The retry consumed nothing: the queue still holds exactly the original.expect(pendingFiles()).toEqual([`${String(first["signal_id"])}.md`]);});++ test("a retry after a failed force-confirmed write resumes the preference", async () => {+ // Block the preferences lane so the first call's force-confirmed write+ // throws AFTER the signal (and its idempotency receipt) landed.+ const prefsDir = join(vault, "Brain", "preferences");+ rmSync(prefsDir, { recursive: true, force: true });+ writeFileSync(prefsDir, "not a directory");+ const args = {+ ...ARGS,+ force_confirmed: true,+ idempotency_key: "resume-key-1",+ };+ await expect(handler(ctx, args)).rejects.toThrow();++ // Unblock the lane and retry with the same key and payload: the+ // receipt dedupes the signal, but the confirmed rule is still absent,+ // so the retry must complete the capture instead of answering deduped.+ rmSync(prefsDir);+ mkdirSync(prefsDir, { recursive: true });+ const retry = (await handler(ctx, args)) as Record<string, unknown>;+ expect(retry["kind"]).toBe("preference");+ expect(retry["deduped"]).toBe(true);+ const prefId = String(retry["preference_id"]);+ expect(prefId).toMatch(/^pref-/);+ expect(existsSync(join(prefsDir, `${prefId}.md`))).toBe(true);+ // The signal was not duplicated by the resume: exactly one capture.+ expect(+ readdirSync(brainDirs(vault).inbox).filter((f) => f.includes("staged-feedback")),+ ).toHaveLength(1);++ // A further retry against the COMPLETED capture stays a true no-op:+ // deduped, and the preference is not rewritten.+ const again = (await handler(ctx, args)) as Record<string, unknown>;+ expect(again["deduped"]).toBe(true);+ expect(again["kind"]).toBe("signal");+ expect(existsSync(join(prefsDir, `${prefId}.md`))).toBe(true);+ // Two sequential retries do not write the preference twice: the DONE+ // marker of the completed capture makes every later replay a no-op.+ const third = (await handler(ctx, args)) as Record<string, unknown>;+ expect(third["kind"]).toBe("signal");+ expect(readdirSync(prefsDir).filter((f) => f.startsWith("pref-"))).toEqual([`${prefId}.md`]);+ });++ test("a replay after delete-by-source stays deduped and writes no preference", async () => {+ // The capture cites a source page, so `deleteBySource` has something+ // to forget: the original, the signal and the folded preference.+ writeFileSync(join(vault, "runbook.md"), "# runbook\n");+ const args = {+ ...ARGS,+ force_confirmed: true,+ idempotency_key: "forgotten-capture-1",+ source: ["runbook.md"],+ };+ const first = (await handler(ctx, args)) as Record<string, unknown>;+ expect(first["kind"]).toBe("preference");+ const prefId = String(first["preference_id"]);+ expect(existsSync(join(vault, "Brain", "preferences", `${prefId}.md`))).toBe(true);++ // The operator forgets the source: the folded preference goes with it+ // (the signal's evidence trail names the forgotten source), but the+ // idempotency receipts never expire.+ appendFileSync(join(vault, String(first["signal_path"])), "\n\nSee [[runbook]].\n");+ deleteBySource(vault, "runbook", { confirm: true, includeOriginals: true });+ expect(existsSync(join(vault, "Brain", "preferences", `${prefId}.md`))).toBe(false);++ // A replay of the same call must NOT resurrect the forgotten rule:+ // the capture completed, so its DONE marker makes the replay a true+ // no-op.+ const replay = (await handler(ctx, args)) as Record<string, unknown>;+ expect(replay["deduped"]).toBe(true);+ expect(replay["kind"]).toBe("signal");+ expect(replay["preference_id"]).toBeUndefined();+ expect(existsSync(join(vault, "Brain", "preferences", `${prefId}.md`))).toBe(false);+ expect(+ readdirSync(join(vault, "Brain", "preferences")).filter((f) => f.startsWith("pref-")),+ ).toEqual([]);+ });++ test("a forced retry of a capture whose first call was not forced writes no preference", async () => {+ const key = "unforced-then-forced-1";+ const base = { ...ARGS, idempotency_key: key };+ // Call 1: no force. By design it writes the inbox signal only.+ const first = (await handler(ctx, base)) as Record<string, unknown>;+ expect(first["kind"]).toBe("signal");+ expect(+ readdirSync(join(vault, "Brain", "preferences")).filter((f) => f.startsWith("pref-")),+ ).toEqual([]);++ // Call 2: same key and payload, plus force_confirmed. The unforced+ // original never asked for a rule, the payload hash that guards the+ // capture names the force flag, so the retry must not confirm one.+ const retry = (await handler(ctx, { ...base, force_confirmed: true })) as Record<+ string,+ unknown+ >;+ expect(retry["deduped"]).toBe(true);+ expect(retry["kind"]).toBe("signal");+ expect(retry["preference_id"]).toBeUndefined();+ expect(+ readdirSync(join(vault, "Brain", "preferences")).filter((f) => f.startsWith("pref-")),+ ).toEqual([]);+ });++ test("a forced retry with a different expiration does not resume the original capture", async () => {+ const args = { ...ARGS, force_confirmed: true, idempotency_key: "expiry-mismatch-1" };+ const first = (await handler(ctx, args)) as Record<string, unknown>;+ expect(first["kind"]).toBe("preference");+ const prefId = String(first["preference_id"]);+ const originalExpiration = readFileSync(+ join(vault, "Brain", "preferences", `${prefId}.md`),+ "utf8",+ );++ // Same key and topic, a different lifetime: a different payload. The+ // retry must not land the original's rule again under a new stamp.+ const retry = (await handler(ctx, { ...args, expires: "2031-01-01" })) as Record<+ string,+ unknown+ >;+ expect(retry["kind"]).toBe("signal");+ expect(+ readdirSync(join(vault, "Brain", "preferences")).filter((f) => f.startsWith("pref-")),+ ).toEqual([`${prefId}.md`]);+ expect(readFileSync(join(vault, "Brain", "preferences", `${prefId}.md`), "utf8")).toBe(+ originalExpiration,+ );+ });++ test("a retry whose pending capture lost its signal stays a no-op", async () => {+ // A first forced call whose preference write fails leaves the PENDING+ // capture marker without DONE - the retry-resume state.+ const prefsDir = join(vault, "Brain", "preferences");+ rmSync(prefsDir, { recursive: true, force: true });+ writeFileSync(prefsDir, "not a directory");+ const args = {+ ...ARGS,+ force_confirmed: true,+ idempotency_key: "forgotten-pending-1",+ };+ await expect(handler(ctx, args)).rejects.toThrow();++ // Before the retry runs, the signal page is forgotten - the state+ // `delete-by-source` and a hand removal both leave: receipts never+ // expire, the signal does.+ const signalFile = readdirSync(brainDirs(vault).inbox).find((f) =>+ f.includes("staged-feedback"),+ );+ expect(signalFile).toBeDefined();+ rmSync(join(brainDirs(vault).inbox, signalFile!));++ // Unblock the lane and replay: the pending marker is there, but the+ // signal it stands for is gone, so the replay stays a true no-op and+ // writes no preference.+ rmSync(prefsDir);+ mkdirSync(prefsDir, { recursive: true });+ const replay = (await handler(ctx, args)) as Record<string, unknown>;+ expect(replay["deduped"]).toBe(true);+ expect(replay["kind"]).toBe("signal");+ expect(replay["preference_id"]).toBeUndefined();+ expect(readdirSync(prefsDir).filter((f) => f.startsWith("pref-"))).toEqual([]);+ });++ test("a capture with a 250-character key replays deduped without an error", async () => {+ // The ledger accepts client keys up to 256 characters. The marker+ // keys are digests of the key, never the key plus a suffix, so a+ // near-limit key must still capture fresh and replay deduped: with a+ // suffix appended the PENDING/DONE appends fail soft and every+ // replay's marker lookup throws instead.+ const key = "k".repeat(250);+ const args = { ...ARGS, force_confirmed: true, idempotency_key: key };+ const first = (await handler(ctx, args)) as Record<string, unknown>;+ expect(first["kind"]).toBe("preference");+ const prefId = String(first["preference_id"]);+ expect(existsSync(join(vault, "Brain", "preferences", `${prefId}.md`))).toBe(true);++ // The forced replay of the completed capture: a deduped no-op that+ // answers normally, with no preference written twice.+ const replay = (await handler(ctx, args)) as Record<string, unknown>;+ expect(replay["deduped"]).toBe(true);+ expect(replay["kind"]).toBe("signal");+ expect(replay["preference_id"]).toBeUndefined();+ expect(+ readdirSync(join(vault, "Brain", "preferences")).filter((f) => f.startsWith("pref-")),+ ).toEqual([`${prefId}.md`]);+ });++ test("a crash-window resume still fires after the dream pass moved the signal", async () => {+ // The same blocked-lane first call as above, but before the retry the+ // signal page MOVES: the dream pass files inbox pages under+ // `Brain/inbox/processed/`. The signal is still alive, so the resume+ // must find it by id in the processed folder and complete the+ // capture instead of answering a dead no-op.+ const prefsDir = join(vault, "Brain", "preferences");+ rmSync(prefsDir, { recursive: true, force: true });+ writeFileSync(prefsDir, "not a directory");+ const args = {+ ...ARGS,+ force_confirmed: true,+ idempotency_key: "moved-signal-resume-1",+ };+ await expect(handler(ctx, args)).rejects.toThrow();++ const signalFile = readdirSync(brainDirs(vault).inbox).find((f) =>+ f.includes("staged-feedback"),+ );+ expect(signalFile).toBeDefined();+ mkdirSync(join(vault, "Brain", "inbox", "processed"), { recursive: true });+ renameSync(+ join(brainDirs(vault).inbox, signalFile!),+ join(vault, "Brain", "inbox", "processed", signalFile!),+ );++ rmSync(prefsDir);+ mkdirSync(prefsDir, { recursive: true });+ const retry = (await handler(ctx, args)) as Record<string, unknown>;+ expect(retry["kind"]).toBe("preference");+ expect(retry["deduped"]).toBe(true);+ expect(existsSync(join(prefsDir, `${String(retry["preference_id"])}.md`))).toBe(true);+ });++ test("a crash-window resume still fires after the staged signal was applied into the inbox", async () => {+ // The apply pass files a staged signal out of `Brain/pending/` into+ // `Brain/inbox/` - the destination an unswitched machine lands on.+ // The signal is still alive there, so the resume must find it by id+ // in the inbox folder and complete the capture instead of answering+ // a dead no-op.+ setGate(true);+ const prefsDir = join(vault, "Brain", "preferences");+ rmSync(prefsDir, { recursive: true, force: true });+ writeFileSync(prefsDir, "not a directory");+ const args = {+ ...ARGS,+ force_confirmed: true,+ idempotency_key: "applied-signal-resume-1",+ };+ await expect(handler(ctx, args)).rejects.toThrow();++ // Apply the staged signal: out of the pending queue, into the inbox.+ const signalFile = pendingFiles().find((f) => f.includes("staged-feedback"));+ expect(signalFile).toBeDefined();+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });+ renameSync(+ join(brainDirs(vault).pending, signalFile!),+ join(vault, "Brain", "inbox", signalFile!),+ );++ rmSync(prefsDir);+ mkdirSync(prefsDir, { recursive: true });+ const retry = (await handler(ctx, args)) as Record<string, unknown>;+ expect(retry["kind"]).toBe("preference");+ expect(retry["deduped"]).toBe(true);+ expect(existsSync(join(prefsDir, `${String(retry["preference_id"])}.md`))).toBe(true);+ });++ test("a crash-window resume matches a retry key spelled with surrounding whitespace", async () => {+ // The ledger normalises the client key (trim) on every receipt, so+ // the PENDING/DONE marker digests must be taken over the trimmed key+ // too: a retry whose key only differs in surrounding whitespace+ // dedupes the signal and must find the original capture's marker,+ // not strand it behind a hash no retry can match.+ const prefsDir = join(vault, "Brain", "preferences");+ rmSync(prefsDir, { recursive: true, force: true });+ writeFileSync(prefsDir, "not a directory");+ const first = {+ ...ARGS,+ force_confirmed: true,+ idempotency_key: " trim-key-1 ",+ };+ await expect(handler(ctx, first)).rejects.toThrow();++ rmSync(prefsDir);+ mkdirSync(prefsDir, { recursive: true });+ const retry = (await handler(ctx, {+ ...ARGS,+ force_confirmed: true,+ idempotency_key: "trim-key-1",+ })) as Record<string, unknown>;+ expect(retry["deduped"]).toBe(true);+ expect(retry["kind"]).toBe("preference");+ expect(existsSync(join(prefsDir, `${String(retry["preference_id"])}.md`))).toBe(true);+ });++ test("a crash-window replay after the rule was retired writes nothing", async () => {+ // A completed forced capture whose DONE marker is then lost (the+ // crash window: PENDING without DONE) leaves a replay resumable - so+ // a rule the user retired in that window must not be re-confirmed+ // beside its own retirement.+ const args = {+ ...ARGS,+ force_confirmed: true,+ idempotency_key: "retired-in-crash-window-1",+ };+ const first = (await handler(ctx, args)) as Record<string, unknown>;+ expect(first["kind"]).toBe("preference");+ const prefId = String(first["preference_id"]);++ // Lose the DONE marker: rewrite the ledger shards without it, which+ // is exactly the on-disk state a crash between the preference write+ // and the DONE append leaves.+ const doneKey = `pref-capture-done:${sha256Hex(args.idempotency_key)}`;+ const ledgerDir = join(vault, "Brain", "logs", "idempotency");+ let dropped = 0;+ for (const shard of readdirSync(ledgerDir)) {+ const path = join(ledgerDir, shard);+ const kept = readFileSync(path, "utf8")+ .split("\n")+ .filter((line) => {+ if (line.trim() === "") return true;+ const record = JSON.parse(line) as { key?: string; namespace?: string };+ const isDone = record.key === doneKey && record.namespace === PREFERENCE_MARKER_NAMESPACE;+ if (isDone) dropped += 1;+ return !isDone;+ })+ .join("\n");+ writeFileSync(path, kept);+ }+ expect(dropped).toBe(1);++ // The user retires the rule in the crash window.+ moveToRetired(vault, join(vault, "Brain", "preferences", `${prefId}.md`), "user-rejected", {+ now: new Date(),+ retired_by: "[[2026-01-01]]",+ user_rejected_reason: "superseded",+ });++ // The replay: PENDING without DONE and a live signal, but the rule+ // is retired, so the guard keeps the replay a true no-op.+ const replay = (await handler(ctx, args)) as Record<string, unknown>;+ expect(replay["deduped"]).toBe(true);+ expect(replay["kind"]).toBe("signal");+ expect(replay["preference_id"]).toBeUndefined();+ expect(+ readdirSync(join(vault, "Brain", "preferences")).filter((f) => f.startsWith("pref-")),+ ).toEqual([]);+ });++ test("a crash-window replay of a completed capture answers deduped without writing again", async () => {+ // A completed forced capture whose DONE marker is then lost: PENDING+ // without DONE, the signal still alive, and the rule the original+ // call wrote still ACTIVE. The replay must recognise the rule as this+ // capture's own completed write, close the ledger, and answer deduped+ // - not attempt the preference write a second time and fail on the+ // existing rule.+ const args = {+ ...ARGS,+ force_confirmed: true,+ idempotency_key: "active-in-crash-window-1",+ };+ const first = (await handler(ctx, args)) as Record<string, unknown>;+ expect(first["kind"]).toBe("preference");+ const prefId = String(first["preference_id"]);+ const prefsDir = join(vault, "Brain", "preferences");+ expect(existsSync(join(prefsDir, `${prefId}.md`))).toBe(true);++ // Lose the DONE marker: exactly the on-disk state a crash between the+ // preference write and the DONE append leaves.+ dropDoneMarker(vault, args.idempotency_key);++ // The replay: no error, deduped, naming the rule that already exists,+ // and without a second preference page.+ const replay = (await handler(ctx, args)) as Record<string, unknown>;+ expect(replay["deduped"]).toBe(true);+ expect(replay["kind"]).toBe("preference");+ expect(replay["preference_id"]).toBe(prefId);+ expect(readdirSync(prefsDir).filter((f) => f.startsWith("pref-"))).toEqual([`${prefId}.md`]);++ // The ledger is closed again: a further replay is the ordinary+ // completed-capture no-op.+ const again = (await handler(ctx, args)) as Record<string, unknown>;+ expect(again["deduped"]).toBe(true);+ expect(again["kind"]).toBe("signal");+ expect(readdirSync(prefsDir).filter((f) => f.startsWith("pref-"))).toEqual([`${prefId}.md`]);+ });++ test("a crash-window replay does not adopt a pre-existing rule this capture did not write", async () => {+ // Same crash window, but the active rule under the capture's slug was+ // written by something else: same payload, confirmed, yet its+ // evidenced_by names another signal. The replay must not close the+ // ledger on a rule this capture cannot prove it wrote - it falls+ // through, and the conflicting rule surfaces instead of being+ // silently adopted.+ const args = {+ ...ARGS,+ force_confirmed: true,+ idempotency_key: "foreign-rule-in-crash-window-1",+ };+ const first = (await handler(ctx, args)) as Record<string, unknown>;+ expect(first["kind"]).toBe("preference");+ const prefId = String(first["preference_id"]);+ const prefPath = join(vault, "Brain", "preferences", `${prefId}.md`);++ // Lose the DONE marker, then detach the rule from this capture's+ // signal: the on-disk state of a same-slug same-payload rule whose+ // evidence is somebody else's.+ dropDoneMarker(vault, args.idempotency_key);+ const before = readFileSync(prefPath, "utf8");+ const after = before.replace(/_evidenced_by:.*\n/, '_evidenced_by: ["[[sig-elsewhere]]"]\n');+ expect(after).not.toBe(before);+ writeFileSync(prefPath, after);++ // The replay falls through instead of adopting the rule, and the+ // resume write refuses on the rule that is already there.+ await expect(handler(ctx, args)).rejects.toThrow();+ // The foreign rule is untouched and unclaimed by the replay.+ expect(readFileSync(prefPath, "utf8")).toContain('_evidenced_by: ["[[sig-elsewhere]]"]');+ expect(+ readdirSync(join(vault, "Brain", "preferences")).filter((f) => f.startsWith("pref-")),+ ).toEqual([`${prefId}.md`]);+ });});++/** Rewrite the idempotency ledger shards without this key's DONE marker. */+function dropDoneMarker(vault: string, key: string): void {+ const doneKey = `pref-capture-done:${sha256Hex(key)}`;+ const ledgerDir = join(vault, "Brain", "logs", "idempotency");+ let dropped = 0;+ for (const shard of readdirSync(ledgerDir)) {+ const path = join(ledgerDir, shard);+ const kept = readFileSync(path, "utf8")+ .split("\n")+ .filter((line) => {+ if (line.trim() === "") return true;+ const record = JSON.parse(line) as { key?: string; namespace?: string };+ const isDone = record.key === doneKey && record.namespace === PREFERENCE_MARKER_NAMESPACE;+ if (isDone) dropped += 1;+ return !isDone;+ })+ .join("\n");+ writeFileSync(path, kept);+ }+ expect(dropped).toBe(1);+}diff --git a/tests/mcp/brain-settings-tool.test.ts b/tests/mcp/brain-settings-tool.test.tsindex b86efc73..2c6655bd 100644--- a/tests/mcp/brain-settings-tool.test.ts+++ b/tests/mcp/brain-settings-tool.test.ts@@ -5,10 +5,12 @@* key, the settings file edited on an unswitched machine.*/import { afterEach, describe, expect, test } from "bun:test";-import { readFileSync } from "node:fs";+import { existsSync, readFileSync, rmSync } from "node:fs";+import { join } from "node:path";import { brainConfigPath } from "../../src/core/brain/paths.ts";import { setBrainSetting } from "../../src/core/brain/policy/settings-write.ts";+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";import { SETTING_SET_KIND } from "../../src/core/store/constants.ts";import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";import {@@ -45,8 +47,16 @@ async function call(server: MCPServer, args: Record<string, unknown>): Promise<Areturn { result: JSON.parse(text) as Record<string, unknown> };}-async function serverFor(vault: string | null, configPath: string): Promise<MCPServer> {- const server = new MCPServer({ vault, configPath });+async function serverFor(+ vault: string | null,+ configPath: string,+ reach?: TransportReach,+): Promise<MCPServer> {+ const server = new MCPServer({+ vault,+ configPath,+ ...(reach !== undefined ? { reach } : {}),+ });await server.handleRequest({jsonrpc: JSONRPC_VERSION,id: 1,@@ -209,3 +219,71 @@ describe("brain_settings on an unswitched machine", () => {expect(readFileSync(brainConfigPath(env.vault), "utf8")).toBe(before);});});++describe("brain_settings on a switched machine whose store cannot be opened", () => {+ test("a remote agent's refusal names neither the lost partition nor the leave remedy", async () => {+ env = makeStoreEnv("osb-settool-remote-redact-");+ switchDevice(env.storeRoot);+ setBrainSetting(+ { vault: env.vault, authority: "human", agent: "u" },+ "dream.heal_enrich_enabled",+ true,+ );+ // A switched machine that lost the identity file of the private+ // partition it holds: the store-open error names `private/store.json`+ // and the leave verb, but none of that may reach the remote caller.+ // Only `private/store.json` is removed: the raw text keeps the leave+ // remedy here, so the assertions below have something to catch.+ rmSync(join(env.storeRoot, "private", "store.json"));+ const before = sets(env).length;+ const server = await serverFor(env.vault, env.configPath, TRANSPORT_REACH.remote);+ const reply = await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 4,+ method: "tools/call",+ params: {+ name: "brain_settings",+ arguments: { action: "set", name: "dream.heal_enrich_enabled", value: false },+ },+ });+ // The write fails closed; the whole answer - prose, codes, data -+ // names neither the partition's identity file nor the remedy.+ expect(JSON.stringify(reply)).not.toContain("private/");+ expect(JSON.stringify(reply)).not.toContain("partition leave private");+ const err = (reply as { error?: { message: string; data?: Record<string, unknown> } }).error;+ expect(err?.data?.["code"]).toBe("settings_unreadable");+ expect(err?.message).toContain("dream.heal_enrich_enabled cannot be changed by an agent");+ expect(sets(env)).toHaveLength(before);+ });++ test("a refused remote note write names neither the lost partition nor the remedy", async () => {+ env = makeStoreEnv("osb-settool-remote-permissions-");+ switchDevice(env.storeRoot);+ setBrainSetting(+ { vault: env.vault, authority: "human", agent: "u" },+ "dream.heal_enrich_enabled",+ true,+ );+ // The same state as above, reached through a note write:+ // `brain_create_note` is refused before any write (the settings read+ // refuses first), and the refusal must not carry the store-open+ // cause's raw text. The permissions gate's own text is pinned in+ // `tests/core/brain/permissions/document-source.test.ts`.+ rmSync(join(env.storeRoot, "private", "store.json"));+ const server = await serverFor(env.vault, env.configPath, TRANSPORT_REACH.remote);+ const reply = await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 5,+ method: "tools/call",+ params: {+ name: "brain_create_note",+ arguments: { path: "Notes/Blocked.md", content: "never written" },+ },+ });+ const text = JSON.stringify(reply);+ expect(text).toContain("could not be opened");+ expect(text).not.toContain("private/");+ expect(text).not.toContain("partition leave");+ expect(existsSync(join(env.vault, "Notes", "Blocked.md"))).toBe(false);+ });+});diff --git a/tests/mcp/brain-truth.test.ts b/tests/mcp/brain-truth.test.tsindex 73a8755d..0b324a90 100644--- a/tests/mcp/brain-truth.test.ts+++ b/tests/mcp/brain-truth.test.ts@@ -113,6 +113,9 @@ async function callRaw(test("ingest then slots round-trips one claim through the fold", async () => {const server = new MCPServer({ vault, configPath });await initialize(server);+ // The source page exists: a claim whose source the caller cannot read+ // is withheld from the fold, exactly as it is from `events`.+ writeSourcePage("standup.md");const ingested = await call(server, {operation: "ingest",entity: "Alice Mason",@@ -131,6 +134,8 @@ test("ingest then slots round-trips one claim through the fold", async () => {});test("conflicts and aggregate read the same ledger", async () => {+ // Every claim's source page exists, so the fold sees all three.+ for (const name of ["a.md", "b.md", "c.md"]) writeSourcePage(name);appendClaimEvent(vault, {ts: "2026-06-01T10:00:00Z",agent: "claude",@@ -384,6 +389,85 @@ test("events answers a caller denied a source page exactly as if the row were ab}});+test("slots, conflicts, aggregate and collisions fold only the claims the caller may read", async () => {+ writeSourcePage("public.md");+ writeSourcePage("private.md", `\nvisibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]`);+ appendClaimEvent(vault, {+ ts: "2026-06-01T10:00:00Z",+ agent: "claude",+ entity: "Alice Mason",+ aspect: "employer",+ value: "Google",+ source: "[[Brain/notes/public.md]]",+ });+ appendClaimEvent(vault, {+ ts: "2026-06-02T10:00:00Z",+ agent: "other-agent",+ entity: "Alice Mason",+ aspect: "employer",+ value: "Meta",+ quantity: { value: 5, unit: "k", action: null },+ // A real quantity, so the private contribution is eligible for the+ // aggregate fold at all: without `valueKind` the aggregate skips+ // the claim and the remote assertions below pass even unfiltered.+ valueKind: "quantity",+ source: "[[Brain/notes/private.md]]",+ });+ const remote = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.remote });+ await initialize(remote);+ // Every fold operation answers only the readable claim: no withheld+ // value, quantity, agent or source path, directly or derived.+ const slots = (await call(remote, { operation: "slots" })) as unknown as Record<string, unknown>;+ expect(JSON.stringify(slots)).not.toContain("Meta");+ expect(JSON.stringify(slots)).not.toContain("other-agent");+ expect(JSON.stringify(slots)).not.toContain("private");+ const conflicts = (await call(remote, {+ operation: "conflicts",+ })) as unknown as Record<string, unknown>;+ expect(JSON.stringify(conflicts)).not.toContain("Meta");+ expect(JSON.stringify(conflicts)).not.toContain("private");+ const aggregate = (await call(remote, {+ operation: "aggregate",+ entity: "alice mason",+ unit: "k",+ })) as unknown as Record<string, unknown>;+ expect(JSON.stringify(aggregate)).not.toContain("Meta");+ expect(JSON.stringify(aggregate)).not.toContain("private");+ // The withheld quantity must be aggregate-eligible: if the visibility+ // filter were removed, the private contribution (5k) would show up+ // here. Remote folds neither the contribution nor its total.+ expect(aggregate["total"]).not.toBe(5);+ expect(aggregate["contributions"]).toHaveLength(0);+ const collisions = (await call(remote, {+ operation: "collisions",+ })) as unknown as Record<string, unknown>;+ expect(JSON.stringify(collisions)).not.toContain("other-agent");+ expect(JSON.stringify(collisions)).not.toContain("Meta");+ expect(JSON.stringify(collisions)).not.toContain("private");+ // The visible claim still folds: one slot for the readable value.+ const slotRows = slots["slots"] as Array<Record<string, unknown>>;+ expect(slotRows).toHaveLength(1);+ expect(JSON.stringify(slotRows)).toContain("Google");+ // Local reach keeps the whole ledger in every fold.+ const local = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.local });+ await initialize(local);+ const localSlots = (await call(local, { operation: "slots" })) as unknown as Record<+ string,+ unknown+ >;+ expect(JSON.stringify(localSlots)).toContain("Meta");+ expect(JSON.stringify(localSlots)).toContain("Google");+ // Local reach keeps the whole ledger in every fold: the private 5k+ // contribution lands in the aggregate and is the total.+ const localAggregate = (await call(local, {+ operation: "aggregate",+ entity: "alice mason",+ unit: "k",+ })) as unknown as Record<string, unknown>;+ expect(localAggregate["total"]).toBe(5);+ expect(localAggregate["contributions"]).toHaveLength(1);+});+test("events refuses unparseable bounds and invalid limits as invalid params", async () => {const server = new MCPServer({ vault, configPath });await initialize(server);diff --git a/tests/mcp/foresight-reach.test.ts b/tests/mcp/foresight-reach.test.tsnew file mode 100644index 00000000..eacf2b20--- /dev/null+++ b/tests/mcp/foresight-reach.test.ts@@ -0,0 +1,81 @@+/**+ * `brain_foresight` answers at the caller's reach (private-is-not-a-+ * suggestion). The extract fold reads the raw continuity store, which+ * carries private records the read model would drop, and a record's text+ * becomes the item title with its refs as sources - so below local reach+ * the fold must withhold the private partition, while a local caller+ * still sees it.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { appendContinuityRecord } from "../../src/core/brain/continuity/store.ts";+import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";+import { BRAIN_TOOLS } from "../../src/mcp/brain-tools.ts";++let tmp: string;+let vault: string;+let configHome: string;+let configPath: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-foresight-reach-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ configHome = mkdtempSync(join(tmpdir(), "o2b-foresight-reach-cfg-"));+ configPath = join(configHome, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);+ bootstrapBrain(vault, { configPath });+ // One readable extract and one private one, both inside the lookback+ // window (the fold looks back thirty days); the private flag is the+ // store's own judgment (write time).+ const dayMs = 24 * 60 * 60 * 1000;+ const at = (daysAgo: number): string => new Date(Date.now() - daysAgo * dayMs).toISOString();+ appendContinuityRecord(vault, {+ kind: "pre_compact_extract",+ createdAt: at(3),+ sourceRefs: [{ id: "sess-open", kind: "session" }],+ payload: { extract_type: "commitment", text: "Ship the readable commitment" },+ });+ appendContinuityRecord(vault, {+ kind: "pre_compact_extract",+ createdAt: at(2),+ sourceRefs: [{ id: "sess-private", kind: "session" }],+ payload: { extract_type: "commitment", text: "ZZPrivate commitment text" },+ private: true,+ });+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+});++async function foresight(reach: TransportReach): Promise<Record<string, unknown>> {+ const tool = BRAIN_TOOLS.find((t) => t.name === "brain_foresight")!;+ const ctx: ServerContext = { vault, reach, configPath, repoRoot: null };+ return (await tool.handler(ctx, {})) as Record<string, unknown>;+}++describe("brain_foresight at remote reach", () => {+ test("a private extract is absent from the report, its text and refs with it", async () => {+ const remote = await foresight(TRANSPORT_REACH.remote);+ const body = JSON.stringify(remote);+ expect(body).not.toContain("ZZPrivate commitment text");+ expect(body).not.toContain("sess-private");+ // The readable extract keeps its place.+ expect(body).toContain("Ship the readable commitment");+ });++ test("local reach keeps the private extract in the report", async () => {+ const local = await foresight(TRANSPORT_REACH.local);+ expect(JSON.stringify(local)).toContain("ZZPrivate commitment text");+ });+});diff --git a/tests/mcp/http-write-identity.test.ts b/tests/mcp/http-write-identity.test.tsindex 5cfafdad..21dd9a9f 100644--- a/tests/mcp/http-write-identity.test.ts+++ b/tests/mcp/http-write-identity.test.ts@@ -12,13 +12,25 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { startHttp, type HttpServerHandle } from "../../src/mcp/index.ts";+import { FEEDBACK_TOOLS } from "../../src/mcp/brain/feedback-tools.ts";+import { EXPIRE_TOOL } from "../../src/mcp/brain/expire-tools.ts";import { bootstrapBrain } from "../../src/core/brain/init.ts";import { brainConfigPath } from "../../src/core/brain/paths.ts";+import { writePreference } from "../../src/core/brain/preference.ts";+import { BRAIN_PREFERENCE_STATUS } from "../../src/core/brain/types.ts";import { queryDecisionLedger } from "../../src/core/brain/permissions/ledger.ts";import { mintAgentToken } from "../../src/core/brain/secrets/token-store.ts";import { GATE_MODE } from "../../src/core/integrity/stamp.ts";@@ -92,6 +104,22 @@ function inboxEntries(): string[] {return existsSync(dir) ? readdirSync(dir).filter((n) => n.includes("prefer-tests")) : [];}+/** Every parsed JSONL row of the audit log, newest file last. */+function logRows(): Array<Record<string, unknown>> {+ const dir = join(vault, "Brain", "log");+ const rows: Array<Record<string, unknown>> = [];+ if (!existsSync(dir)) return rows;+ for (const name of readdirSync(dir)+ .filter((n) => n.endsWith(".jsonl"))+ .toSorted()) {+ for (const line of readFileSync(join(dir, name), "utf8").split("\n")) {+ if (!line.trim()) continue;+ rows.push(JSON.parse(line) as Record<string, unknown>);+ }+ }+ return rows;+}+describe("write-side decisions answer for the token's agent", () => {test("a document deny for the token's agent refuses its create, naming the rule", async () => {const { tokenMaterial } = mintAgentToken(vault, "mcp_token_bob", "bob");@@ -199,4 +227,127 @@ describe("write-side decisions answer for the token's agent", () => {source: "default",});});++ test("a token caller's brain_note without agent is attributed to the token's agent", async () => {+ const { tokenMaterial } = mintAgentToken(vault, "mcp_token_bob", "bob");+ await start();+ const body = await postJson(+ rpc("tools/call", 1, {+ name: "brain_note",+ arguments: { text: "shipped the thing" },+ }),+ tokenMaterial,+ );+ const result = (body.result as Record<string, any>).structuredContent as Record<string, any>;+ expect(body.error).toBeUndefined();+ // The receipt and the log line name the credential's agent: the+ // process config identity (operator) must never appear there.+ expect(result["agent"]).toBe("bob");+ const noteRows = logRows().filter((row) => row["kind"] === "note");+ expect(noteRows.length).toBeGreaterThan(0);+ expect(JSON.stringify(noteRows)).toContain("bob");+ expect(JSON.stringify(noteRows)).not.toContain("operator");+ });++ test("a token caller's brain_expire without agent stamps the token's agent in the audit log", async () => {+ const { tokenMaterial } = mintAgentToken(vault, "mcp_token_bob", "bob");+ writePreference(vault, {+ slug: "expire-me",+ topic: "expire me",+ principle: "prefer expiring rules",+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by: [],+ confirmed_at: "2026-05-02T00:00:00Z",+ });+ await start();+ const body = await postJson(+ rpc("tools/call", 1, {+ name: "brain_expire",+ arguments: { id: "pref-expire-me", expires: "2030-01-01" },+ }),+ tokenMaterial,+ );+ expect(body.error).toBeUndefined();+ // The expiration's audit event names who set it - the token's agent,+ // never the writer's default stamp nor the config identity.+ const setRows = logRows().filter((row) => row["kind"] === "expiration-set");+ expect(setRows).toHaveLength(1);+ expect((setRows[0]!["payload"] as Record<string, unknown>)["agent"]).toBe("bob");+ });+});++describe("the identity fallback answers for tokens only", () => {+ let configHome: string;++ afterEach(() => {+ if (configHome !== undefined) {+ rmSync(configHome, { recursive: true, force: true });+ configHome = undefined as unknown as string;+ }+ });++ test("a shared-key identity never stamps its own name over the config resolution", async () => {+ // A non-default config identity: this is the name the config path+ // resolves, and the name a shared-key write must keep carrying.+ setEnv("VAULT_AGENT_NAME", "cfgagent");+ configHome = mkdtempSync(join(tmpdir(), "o2b-identity-cfg-"));+ const configPath = join(configHome, "config.yaml");+ writeFileSync(configPath, `vault: ${vault}\nagent_name: cfgagent\n`);+ const noteTool = FEEDBACK_TOOLS.find((t) => t.name === "brain_note")!;+ const ctx = {+ vault,+ configPath,+ repoRoot: null,+ // A shared-key caller's minted identity is the operator's, but the+ // rule must not TRUST it for stamping: whatever it carries, the+ // config-path resolution decides, as it did before the token+ // fallback existed.+ requestIdentity: { agent: "infiltrator", via: "shared-key" as const },+ };+ const res = (await noteTool.handler(ctx, { text: "shared key note" })) as Record<+ string,+ unknown+ >;+ expect(res["agent"]).toBe("cfgagent");+ expect(logRows().filter((row) => row["kind"] === "note").length).toBeGreaterThan(0);+ expect(JSON.stringify(logRows())).not.toContain("infiltrator");+ });++ test("a token identity still stamps the token's agent on a note and an expiration", async () => {+ setEnv("VAULT_AGENT_NAME", "cfgagent");+ configHome = mkdtempSync(join(tmpdir(), "o2b-identity-cfg-"));+ const configPath = join(configHome, "config.yaml");+ writeFileSync(configPath, `vault: ${vault}\nagent_name: cfgagent\n`);+ writePreference(vault, {+ slug: "expire-token",+ topic: "expire token",+ principle: "prefer token expirations",+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by: [],+ confirmed_at: "2026-05-02T00:00:00Z",+ });+ const tools = FEEDBACK_TOOLS;+ const noteTool = tools.find((t) => t.name === "brain_note")!;+ const expireTool = tools.find((t) => t.name === EXPIRE_TOOL)!;+ const ctx = {+ vault,+ configPath,+ repoRoot: null,+ requestIdentity: { agent: "bob", via: "token" as const },+ };+ const note = (await noteTool.handler(ctx, { text: "token note" })) as Record<string, unknown>;+ expect(note["agent"]).toBe("bob");+ const res = (await expireTool.handler(ctx, {+ id: "pref-expire-token",+ expires: "2030-01-01",+ })) as Record<string, unknown>;+ expect(res["id"]).toBe("pref-expire-token");+ const setRows = logRows().filter((row) => row["kind"] === "expiration-set");+ expect(setRows).toHaveLength(1);+ expect((setRows[0]!["payload"] as Record<string, unknown>)["agent"]).toBe("bob");+ });});diff --git a/tests/mcp/link-recall-tools.test.ts b/tests/mcp/link-recall-tools.test.tsindex a84b75c3..f68db4b7 100644--- a/tests/mcp/link-recall-tools.test.ts+++ b/tests/mcp/link-recall-tools.test.ts@@ -12,6 +12,7 @@ import { join } from "node:path";import { bootstrapBrain } from "../../src/core/brain/init.ts";import { listMetrics } from "../../src/core/brain/metrics.ts";+import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";import { indexVault } from "../../src/core/search/indexer.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";import { makeConfig } from "../helpers/search-fixtures.ts";@@ -203,9 +204,29 @@ test("brain_clusters run with batch_size returns per-batch results", async () =>await initialize(server);const run = await call(server, "brain_clusters", { operation: "run", batch_size: 1 });- const batches = run["batches"] as Array<{ index: number; start: number; end: number }>;- expect(batches).toHaveLength(1);- expect(batches[0]).toMatchObject({ index: 0, start: 0, end: 1 });+ // The default server reach is below local, so the batches are+ // withheld whole - the same rule the top-level `removed` follows: a+ // batch's very existence counts detected communities, and a raw+ // `error` names a `cluster-<community id>.md` note, so no filtered+ // form of the list can be shown without disclosing one.+ expect(run["batches"]).toEqual([]);++ // Local reach filters nothing, so the batches stay verbatim: raw+ // `index`/`start`/`end` offsets and all.+ const localServer = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.local });+ await initialize(localServer);+ const localRun = await call(localServer, "brain_clusters", { operation: "run", batch_size: 1 });+ const localBatches = localRun["batches"] as Array<{+ index: number;+ start?: number;+ end?: number;+ written: string[];+ }>;+ expect(localBatches).toHaveLength(1);+ expect(localBatches[0]!.index).toBe(0);+ expect(localBatches[0]!.written.length).toBeGreaterThan(0);+ expect(localBatches[0]!.start).toBe(0);+ expect(localBatches[0]!.end).toBeGreaterThan(0);const badZero = await callError(server, "brain_clusters", { operation: "run", batch_size: 0 });expect(badZero.code).toBe(-32602);diff --git a/tests/mcp/recall-telemetry-tool.test.ts b/tests/mcp/recall-telemetry-tool.test.tsindex 93f56336..deeb773f 100644--- a/tests/mcp/recall-telemetry-tool.test.ts+++ b/tests/mcp/recall-telemetry-tool.test.ts@@ -1,8 +1,10 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";+import { appendContinuityRecord } from "../../src/core/brain/continuity/store.ts";+import { brainConfigPath } from "../../src/core/brain/paths.ts";import {emitRecallTelemetry,RECALL_CHANNEL,@@ -14,6 +16,7 @@ import { recordHostMemoryWrite } from "../../src/core/brain/host-memory-write.tsimport { writePreference } from "../../src/core/brain/preference.ts";import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../src/core/brain/types.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";import { INVALID_PARAMS } from "../../src/mcp/protocol.ts";import { buildToolTable } from "../../src/mcp/tools.ts";@@ -292,13 +295,19 @@ describe("brain_recall_telemetry tool", () => {describe("brain_observed_use tool (t_65588d8b)", () => {test("records verdicts and surfaces them via observed_reuse", async () => {+ // The keys are page references, so both pages exist: a key whose page+ // the caller cannot read is withheld from the fold (see the reach+ // test below).+ mkdirSync(join(vault, "notes"), { recursive: true });+ writeFileSync(join(vault, "notes", "a.md"), "---\nkind: note\n---\n\na\n");+ writeFileSync(join(vault, "notes", "b.md"), "---\nkind: note\n---\n\nb\n");const server = new MCPServer({ vault, configPath });await initialize(server);const rec = await callTool(server, "brain_observed_use", {entries: [- { id: "1", path: "a.md", verdict: "USED" },- { id: "2", path: "b.md", verdict: "CONTRADICTED" },+ { id: "1", path: "notes/a.md", verdict: "USED" },+ { id: "2", path: "notes/b.md", verdict: "CONTRADICTED" },],});expect(rec.recorded).toBe(2);@@ -306,9 +315,9 @@ describe("brain_observed_use tool (t_65588d8b)", () => {const reuse = await callTelemetry(server, { operation: "observed_reuse" });expect(reuse.total).toBe(2);const artifacts = reuse.artifacts as Array<Record<string, unknown>>;- const a = artifacts.find((x) => x.key === "a.md");+ const a = artifacts.find((x) => x.key === "notes/a.md");expect(a?.score).toBe(1);- const b = artifacts.find((x) => x.key === "b.md");+ const b = artifacts.find((x) => x.key === "notes/b.md");expect(b?.score).toBe(0);});@@ -326,6 +335,38 @@ describe("brain_observed_use tool (t_65588d8b)", () => {})) as { error?: { code: number } };expect(response.error?.code).toBe(INVALID_PARAMS);});++ test("observed_reuse answers at the caller's reach", async () => {+ // One key the caller can read and one whose page is reserved against+ // remote reads; the write path accepts any path unchecked, so the log+ // holds both.+ mkdirSync(join(vault, "notes"), { recursive: true });+ writeFileSync(join(vault, "notes", "visible.md"), "---\nkind: note\n---\n\nvisible\n");+ writeFileSync(+ join(vault, "notes", "hidden.md"),+ "---\nkind: note\nvisibility: [private]\n---\n\nhidden\n",+ );+ await callTool(new MCPServer({ vault, configPath }), "brain_observed_use", {+ entries: [+ { id: "1", path: "notes/visible.md", verdict: "USED" },+ { id: "2", path: "notes/hidden.md", verdict: "USED" },+ ],+ });++ const remote = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.remote });+ await initialize(remote);+ const seen = await callTelemetry(remote, { operation: "observed_reuse" });+ const keys = (seen["artifacts"] as Array<{ key: string }>).map((a) => a.key);+ expect(keys).toEqual(["notes/visible.md"]);+ // Dropped BEFORE total, so the withheld key's number is not leaked.+ expect(seen["total"]).toBe(1);++ // Local reach keeps both keys.+ const local = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.local });+ await initialize(local);+ const all = await callTelemetry(local, { operation: "observed_reuse" });+ expect(all["total"]).toBe(2);+ });});describe("brain_recall_telemetry channel dimension", () => {@@ -389,3 +430,302 @@ describe("brain_recall_telemetry channel dimension", () => {expect(response.error?.message).toContain("mcp, cli, hook");});});++describe("brain_recall_telemetry reach boundary on list, summary and gate ops", () => {+ test("list, summary, gate_list and gate_summary drop withheld records at remote reach", async () => {+ // Two pages: one the remote caller may read, one reserved.+ mkdirSync(join(vault, "notes"), { recursive: true });+ writeFileSync(join(vault, "notes", "open.md"), "---\nkind: note\n---\n\nopen\n");+ writeFileSync(+ join(vault, "notes", "closed.md"),+ "---\nkind: note\nvisibility: [private]\n---\n\nclosed\n",+ );++ // Three recall records: one naming the open page, one naming the+ // reserved page (both in its source refs and its top_artifacts), and+ // one naming nothing.+ emitRecallTelemetry(vault, {+ createdAt: "2026-05-20T18:00:00.000Z",+ host: "mcp-test",+ channel: RECALL_CHANNEL.mcp,+ mode: "search",+ status: "ok",+ durationMs: 2,+ resultCount: 1,+ topArtifacts: [{ id: "notes-open", path: "notes/open.md" }],+ });+ emitRecallTelemetry(vault, {+ createdAt: "2026-05-20T18:01:00.000Z",+ host: "mcp-test",+ channel: RECALL_CHANNEL.mcp,+ mode: "query",+ status: "ok",+ durationMs: 2,+ resultCount: 0,+ topArtifacts: [{ id: "notes-closed", path: "notes/closed.md" }],+ });+ emitRecallTelemetry(vault, {+ createdAt: "2026-05-20T18:02:00.000Z",+ host: "mcp-test",+ channel: RECALL_CHANNEL.hook,+ mode: "query",+ status: "ok",+ durationMs: 1,+ resultCount: 0,+ });+ // One gate record flagged private and one ordinary one. Gate records+ // carry no artifact refs, so only the private flag can withhold them.+ appendContinuityRecord(vault, {+ kind: "gate_telemetry",+ createdAt: "2026-05-20T18:03:00.000Z",+ sourceRefs: [],+ private: true,+ payload: { host: "mcp-test", decision: "skip", reason: "private" },+ });+ appendContinuityRecord(vault, {+ kind: "gate_telemetry",+ createdAt: "2026-05-20T18:04:00.000Z",+ sourceRefs: [],+ payload: { host: "mcp-test", decision: "retrieve", reason: "threshold" },+ });++ // Local reach keeps everything, exactly as before this boundary.+ const local = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.local });+ await initialize(local);+ expect((await callTelemetry(local, { operation: "summary" }))["total"]).toBe(3);+ expect((await callTelemetry(local, { operation: "gate_summary" }))["total"]).toBe(2);++ // Remote reach: the reserved page's record is dropped whole BEFORE+ // total and before the summary counts, and the private gate record+ // with it. No path of the reserved page appears anywhere.+ const remote = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.remote });+ await initialize(remote);+ const seen = await callTelemetry(remote, { operation: "list", mode: "search" });+ expect(seen["total"]).toBe(1);+ expect(JSON.stringify(seen)).not.toContain("notes/closed.md");++ const summary = await callTelemetry(remote, { operation: "summary" });+ expect(summary).toMatchObject({+ total: 2,+ by_mode: { search: 1, query: 1 },+ by_channel: { hook: 1, mcp: 1 },+ total_results: 1,+ });++ const gateList = await callTelemetry(remote, { operation: "gate_list" });+ expect(gateList["total"]).toBe(1);+ expect(JSON.stringify(gateList)).not.toContain('"reason":"private"');++ const gateSummary = await callTelemetry(remote, { operation: "gate_summary" });+ expect(gateSummary).toMatchObject({+ total: 1,+ retrieved: 1,+ skipped: 0,+ by_reason: { threshold: 1 },+ });+ });++ test("an id-only artifact of a withheld preference drops the record at remote reach", async () => {+ // The emitter had no path for the artifact, only its bare Brain id -+ // the shape `emitRecallTelemetry` records whenever the ranked search+ // never surfaced a path. The preference's page is reserved against+ // remote reads, so the record that names it only by id must drop+ // whole below local reach.+ writePreference(vault, {+ slug: "withheld",+ topic: "withheld",+ principle: "A rule nobody else may read",+ created_at: "2026-05-20T19:00:00.000Z",+ unconfirmed_until: "2026-05-21T00:00:00.000Z",+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by: ["[[sig-2026-05-20-withheld]]"],+ confirmed_at: "2026-05-20T19:00:00.000Z",+ });+ const prefPath = join(vault, "Brain", "preferences", "pref-withheld.md");+ const page = readFileSync(prefPath, "utf8");+ const frontmatterEnd = page.indexOf("\n---", 1);+ atomicWriteFileSync(+ prefPath,+ `${page.slice(0, frontmatterEnd)}\nvisibility: [private]${page.slice(frontmatterEnd)}`,+ );++ emitRecallTelemetry(vault, {+ createdAt: "2026-05-20T19:01:00.000Z",+ host: "mcp-test",+ channel: RECALL_CHANNEL.mcp,+ mode: "search",+ status: "ok",+ durationMs: 1,+ resultCount: 1,+ topArtifacts: [{ id: "pref-withheld" }],+ });++ const local = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.local });+ await initialize(local);+ expect((await callTelemetry(local, { operation: "list" }))["total"]).toBe(1);++ const remote = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.remote });+ await initialize(remote);+ const seen = await callTelemetry(remote, { operation: "list" });+ expect(seen["total"]).toBe(0);+ expect(JSON.stringify(seen)).not.toContain("pref-withheld");++ const summary = await callTelemetry(remote, { operation: "summary" });+ expect(summary["total"]).toBe(0);+ });+});++/**+ * The ownership half of the same filter, under+ * `integrity.owner_scope_delivery: fail`: a record whose artifact refs+ * name another owner's page is withheld at LOCAL reach too - the private+ * partition stays a remote-only withholding, but the owner reference+ * filter is not reach-bound. With the gate off, a local caller still sees+ * everything.+ */+describe("brain_recall_telemetry under integrity.owner_scope_delivery: fail", () => {+ const OWNER_A = "agent-a";+ const CALLER = "agent-b";++ /** The caller's tool handler call, resolved under one enforced identity. */+ function callAs(args: Record<string, unknown>, agentName?: string) {+ const tool = buildToolTable("full").find((t) => t.name === "brain_recall_telemetry")!;+ return tool.handler(+ { vault, configPath, repoRoot: null, agentName, reach: TRANSPORT_REACH.local },+ args,+ );+ }++ function setGate(mode: "fail" | null): void {+ writeFileSync(+ brainConfigPath(vault),+ mode === null+ ? "schema_version: 1\n"+ : "schema_version: 1\nintegrity:\n owner_scope_delivery: fail\n",+ );+ }++ function seedForeignPref(): void {+ writePreference(vault, {+ slug: "foreign-rule",+ topic: "foreign-rule",+ principle: "A rule owned by another scope.",+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by: [],+ confirmed_at: "2026-05-02T00:00:00Z",+ owner: OWNER_A,+ });+ }++ function emitForeignRecord(): void {+ emitRecallTelemetry(vault, {+ createdAt: "2026-05-20T16:00:00.000Z",+ host: "owner-scope-test",+ channel: RECALL_CHANNEL.mcp,+ mode: "context_pack",+ status: "ok",+ durationMs: 3,+ resultCount: 1,+ topArtifacts: [{ id: "pref-foreign-rule" }],+ });+ }++ test("a record naming another owner's artifact is withheld at local reach", async () => {+ seedForeignPref();+ emitForeignRecord();+ setGate("fail");++ const list = (await callAs({ operation: "list" }, CALLER)) as Record<string, unknown>;+ expect(list["total"]).toBe(0);+ expect(JSON.stringify(list)).not.toContain("pref-foreign-rule");++ const summary = (await callAs({ operation: "summary" }, CALLER)) as Record<string, unknown>;+ expect(summary["total"]).toBe(0);++ // Not over-filtering: the record travels whole to its own owner.+ const asOwner = (await callAs({ operation: "list" }, OWNER_A)) as Record<string, unknown>;+ expect(asOwner["total"]).toBe(1);+ });++ test("with the gate off, a local caller keeps every record", async () => {+ seedForeignPref();+ emitForeignRecord();+ setGate(null);++ const list = (await callAs({ operation: "list" }, CALLER)) as Record<string, unknown>;+ expect(list["total"]).toBe(1);+ });+});++/**+ * The limit is the caller's page over what it may SEE, not over what the+ * log holds: the visibility filter runs first, then the page is cut. A+ * limit inside the reader would let the newest withheld record consume+ * the page and hide an older visible one behind it.+ */+describe("brain_recall_telemetry limit applies after the visibility filter", () => {+ test("list limit 1 with the newest record withheld returns the older visible one", async () => {+ mkdirSync(join(vault, "notes"), { recursive: true });+ writeFileSync(join(vault, "notes", "open.md"), "---\nkind: note\n---\n\nopen\n");+ writeFileSync(+ join(vault, "notes", "closed.md"),+ "---\nkind: note\nvisibility: [private]\n---\n\nclosed\n",+ );+ // The OLDER record is visible, the NEWER one names a reserved page.+ emitRecallTelemetry(vault, {+ createdAt: "2026-05-20T18:00:00.000Z",+ host: "mcp-test",+ channel: RECALL_CHANNEL.mcp,+ mode: "search",+ status: "ok",+ durationMs: 2,+ resultCount: 1,+ topArtifacts: [{ id: "notes-open", path: "notes/open.md" }],+ });+ emitRecallTelemetry(vault, {+ createdAt: "2026-05-20T18:01:00.000Z",+ host: "mcp-test",+ channel: RECALL_CHANNEL.mcp,+ mode: "search",+ status: "ok",+ durationMs: 2,+ resultCount: 0,+ topArtifacts: [{ id: "notes-closed", path: "notes/closed.md" }],+ });++ const remote = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.remote });+ await initialize(remote);+ const page = await callTelemetry(remote, { operation: "list", limit: 1 });+ expect(page["total"]).toBe(1);+ expect(JSON.stringify(page)).toContain("notes/open.md");+ expect(JSON.stringify(page)).not.toContain("notes/closed.md");+ // The summary cuts its limit after the same filter.+ const summary = await callTelemetry(remote, { operation: "summary", limit: 1 });+ expect(summary["total"]).toBe(1);+ });++ test("gate_list limit 1 with the newest record private returns the older visible one", async () => {+ appendContinuityRecord(vault, {+ kind: "gate_telemetry",+ createdAt: "2026-05-20T18:00:00.000Z",+ sourceRefs: [],+ payload: { host: "mcp-test", decision: "retrieve", reason: "threshold" },+ });+ appendContinuityRecord(vault, {+ kind: "gate_telemetry",+ createdAt: "2026-05-20T18:01:00.000Z",+ sourceRefs: [],+ private: true,+ payload: { host: "mcp-test", decision: "skip", reason: "private" },+ });++ const remote = new MCPServer({ vault, configPath }, { reach: TRANSPORT_REACH.remote });+ await initialize(remote);+ const page = await callTelemetry(remote, { operation: "gate_list", limit: 1 });+ expect(page["total"]).toBe(1);+ expect(JSON.stringify(page)).toContain('"reason":"threshold"');+ expect(JSON.stringify(page)).not.toContain('"reason":"private"');+ });+});