Skip to content

A self-organizing Obsidian vault that gives AI coding agents persistent memory.

feat: reach the vault from any repo — MCP server and scoped cross-repo memory (#161)

Brenno Ferrari2be0e092aa28
diff --git a/.claude/scripts/generate-memory-index.ts b/.claude/scripts/generate-memory-index.ts
index 4772158..17ac5d7 100644
--- a/.claude/scripts/generate-memory-index.ts
+++ b/.claude/scripts/generate-memory-index.ts
@@ -18,7 +18,7 @@ import {
extractFrontmatterField,
isMarkdownFilename,
} from "./lib/session-start.ts";
-import { generateMemoryIndex, type BrainNote } from "./lib/memory-index.ts";
+import { generateMemoryIndex, type BrainNote } from "./lib/automemory-index.ts";
/**
* Collect brain/ notes (name + description) for index generation. Exported
diff --git a/.claude/scripts/lib/atomic-write.ts b/.claude/scripts/lib/atomic-write.ts
new file mode 100644
index 0000000..f0642ad
--- /dev/null
+++ b/.claude/scripts/lib/atomic-write.ts
@@ -0,0 +1,81 @@
+/**
+ * Claiming a filename without losing a write.
+ *
+ * Extracted because both write paths — memories and work records — need it, and
+ * a correctness-critical pattern implemented twice is a fix applied once.
+ *
+ * WHY NOT check-then-write
+ *
+ * The obvious version is `while (existsSync(x)) bump(x); writeFileSync(x)`. It
+ * is a TOCTOU race, and not a theoretical one: the deployment shape is one
+ * server process PER CONSUMING REPO, all writing into one vault. Six processes
+ * recording the same title produced FOUR files and SIX success messages — two
+ * writes lost silently, reported as recorded, which is the worst outcome
+ * available to a layer whose whole job is not losing them.
+ *
+ * `COPYFILE_EXCL` fails instead of clobbering, so the loser simply takes the
+ * next suffix. The temp file also means a crash mid-write cannot leave a
+ * half-written note for the indexer to pick up.
+ */
+
+import { writeFileSync, copyFileSync, unlinkSync, constants } from "node:fs";
+import { join } from "node:path";
+
+/** Per-process counter, so two in-flight writes cannot share a temp name. */
+let tmpSeq = 0;
+
+export interface ClaimResult {
+ /** The filename that was successfully claimed. */
+ readonly name: string;
+ /** Its absolute path. */
+ readonly full: string;
+}
+
+export interface ClaimOptions {
+ /** How many suffixed names to try before giving up. */
+ readonly maxAttempts?: number;
+ /**
+ * Called with each candidate before it is claimed. Throw to refuse it —
+ * used by the capture path to verify containment rather than trust that a
+ * slug stripped every separator.
+ */
+ readonly verify?: (full: string) => void;
+ /** Message when every attempt collided. */
+ readonly exhaustedMessage?: string;
+}
+
+/**
+ * Write `body` into `dir` under the first free name `nameFor` produces.
+ *
+ * `nameFor(1)` is the preferred name; higher `n` are the collision fallbacks,
+ * so the caller decides whether that looks like `note (2).md` or `note-2.md`.
+ */
+export function claimFile(
+ dir: string,
+ body: string,
+ nameFor: (n: number) => string,
+ { maxAttempts = 50, verify, exhaustedMessage = "too many colliding files for that name" }: ClaimOptions = {},
+): ClaimResult {
+ const tmp = join(dir, `.om-${process.pid}-${++tmpSeq}.tmp`);
+ writeFileSync(tmp, body, "utf8");
+ try {
+ for (let n = 1; n <= maxAttempts; n++) {
+ const name = nameFor(n);
+ const full = join(dir, name);
+ verify?.(full);
+ try {
+ copyFileSync(tmp, full, constants.COPYFILE_EXCL);
+ return { name, full };
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException)?.code !== "EEXIST") throw e;
+ }
+ }
+ throw new Error(exhaustedMessage);
+ } finally {
+ try {
+ unlinkSync(tmp);
+ } catch {
+ /* temp cleanup is best-effort */
+ }
+ }
+}
diff --git a/.claude/scripts/lib/memory-index.ts b/.claude/scripts/lib/automemory-index.ts
similarity index 81%
rename from .claude/scripts/lib/memory-index.ts
rename to .claude/scripts/lib/automemory-index.ts
index 7aeaf4a..688cf5b 100644
--- a/.claude/scripts/lib/memory-index.ts
+++ b/.claude/scripts/lib/automemory-index.ts
@@ -1,6 +1,13 @@
/**
* MEMORY.md generation (#125) — the auto-memory index as a DERIVED view.
*
+ * NOT the vault memory layer. This module builds Claude Code's local
+ * `MEMORY.md` pointer index; `memory-write.ts` / `memory-recall.ts` are the
+ * cross-repo vault memory reached over MCP. Two unrelated things were both
+ * called "memory" until this file was renamed — the entry script keeps its
+ * original name because it is quoted verbatim in `om-wrap-up.md` and pinned in
+ * `vault-manifest.json`, and a rename there would break a documented command.
+ *
* CLAUDE.md doctrine: `~/.claude/.../memory/MEMORY.md` is an auto-loaded
* index ONLY — pointers to brain/ topic notes, never content. The doctrine
* only holds if the index is derivable: the moment authored knowledge
diff --git a/.claude/scripts/lib/mcp-caller.ts b/.claude/scripts/lib/mcp-caller.ts
new file mode 100644
index 0000000..fb87652
--- /dev/null
+++ b/.claude/scripts/lib/mcp-caller.ts
@@ -0,0 +1,186 @@
+/**
+ * Caller identity, and sanitising what crosses back to it.
+ *
+ * Identity comes from the MCP `roots/list` handshake — never from a tool
+ * argument, so a session cannot claim to be a project it is not. A client that
+ * does not complete the handshake is anonymous and sees only `general`-scoped
+ * memories; `health` reports that explicitly, since it otherwise looks like an
+ * empty vault.
+ */
+
+import { appendFileSync, mkdirSync, readFileSync, renameSync, statSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+export interface Root {
+ readonly uri?: string;
+ readonly name?: string;
+}
+
+/**
+ * Normalise a path for comparison: separators, trailing slash, case, and the
+ * leading slash a drive-letter path carries on platforms without drives
+ * (`fileURLToPath("file:///C:/x")` is `C:\x` on Windows, `/C:/x` elsewhere).
+ */
+export function normalizePath(x: unknown): string {
+ return String(x ?? "")
+ .split("\\")
+ .join("/")
+ .replace(/^\/(?=[A-Za-z]:)/, "")
+ .replace(/\/+$/, "")
+ .toLowerCase();
+}
+
+/** Turn a `file://` root URI into a plain path. */
+export function rootToPath(uri: unknown): string {
+ const raw = String(uri ?? "");
+
+ if (/^file:\/\//i.test(raw)) {
+ try {
+ return fileURLToPath(raw);
+ } catch {
+ // Fall through: clients also send the two-slash `file://C:/x` form,
+ // which is not a legal file URL. Parsing it tolerantly beats treating
+ // the caller as anonymous.
+ }
+ }
+
+ const stripped = raw.replace(/^file:\/\//i, "");
+ const path = /^\/[A-Za-z]:/.test(stripped) ? stripped.slice(1) : stripped;
+ try {
+ return decodeURIComponent(path);
+ } catch {
+ return path;
+ }
+}
+
+/** Where a repo may declare its own project name, overriding the folder name. */
+export const PROJECT_MARKER = ".om-project";
+
+/**
+ * The calling repo's project identity.
+ *
+ * The folder name by default. A repo can override that by writing a single
+ * line into `.om-project`, which is what resolves the one real failure here:
+ * two repos both called `api` otherwise share an identity, so each receives
+ * the other's memories. Declaring a distinct name in either repo separates
+ * them, and nothing changes for anyone who does not hit the collision.
+ */
+export function callerProject(roots: readonly Root[]): string | null {
+ const first = roots[0];
+ if (!first) return null;
+ const root = rootToPath(first.uri).replace(/\/+$/, "");
+
+ const declared = readProjectMarker(root);
+ if (declared) return declared;
+
+ const seg = root.split(/[\\/]/).filter(Boolean).pop();
+ return seg ? seg.toLowerCase() : null;
+}
+
+/** How the identity was decided, so `health` can explain itself. */
+export function callerProjectSource(roots: readonly Root[]): "declared" | "folder" | "none" {
+ const first = roots[0];
+ if (!first) return "none";
+ const root = rootToPath(first.uri).replace(/\/+$/, "");
+ if (readProjectMarker(root)) return "declared";
+ return root.split(/[\\/]/).filter(Boolean).length ? "folder" : "none";
+}
+
+function readProjectMarker(root: string): string | null {
+ try {
+ const raw = readFileSync(join(root, PROJECT_MARKER), "utf8")
+ .split("\n")
+ .map((l) => l.trim())
+ .find((l) => l && !l.startsWith("#"));
+ if (!raw) return null;
+ // Same shape as a folder name, so a declared identity cannot smuggle in a
+ // path segment or anything the scope rule would compare oddly.
+ const name = raw.toLowerCase();
+ return /^[\w.-]+$/.test(name) ? name : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Is the caller the vault itself? Checked across all roots, since a session can
+ * open the vault as a secondary directory. Used to refuse memory writes from
+ * inside the vault, which would reach only sessions that already read it.
+ */
+export function isVaultItself(vaultRoot: string, roots: readonly Root[]): boolean {
+ if (!roots.length) return false;
+ const vault = normalizePath(vaultRoot);
+ return roots.some((r) => normalizePath(rootToPath(r.uri)) === vault);
+}
+
+/**
+ * Replace local absolute paths with `<path>`.
+ *
+ * Error text reaches the calling session and may be pasted into a commit or an
+ * issue; raw filesystem errors carry full local paths. Applied at this single
+ * boundary rather than per throw site. Vault-relative paths are left alone —
+ * those are citations.
+ */
+export function sanitize(message: unknown): string {
+ return String(message)
+ // The lookbehind keeps a drive letter to ONE letter, so `vault://note/x`
+ // is not read as a `t:` drive path.
+ .replace(/(?<![A-Za-z])[A-Za-z]:[\\/][^\s'"`)]+/g, "<path>")
+ .replace(/\/(?:home|Users|users|root)\/[^\s'"`)]+/g, "<path>")
+ .replace(/\\\\[^\s'"`)]+/g, "<path>");
+}
+
+export interface AuditEntry {
+ readonly action: string;
+ readonly caller: string;
+ readonly at: string;
+ readonly [key: string]: unknown;
+}
+
+/**
+ * Append-only log of what each caller read. Write failures are swallowed: the
+ * log must never be able to break the server.
+ */
+/** Rotate at 5MB — roughly a year of ordinary use, kept for one generation. */
+export const AUDIT_MAX_BYTES = 5 * 1024 * 1024;
+
+export function createAuditor(
+ logPath: string,
+ getCaller: () => string | null,
+ now: () => string = () => new Date().toISOString(),
+ maxBytes: number = AUDIT_MAX_BYTES,
+): (action: string, detail?: Record<string, unknown>) => void {
+ let ensured = false;
+ return (action, detail = {}) => {
+ try {
+ if (!ensured) {
+ mkdirSync(dirname(logPath), { recursive: true });
+ ensured = true;
+ }
+ // One generation kept, then dropped. An append-only log with no bound
+ // grows for the life of the vault, and this one records a line per read.
+ try {
+ if (statSync(logPath).size >= maxBytes) renameSync(logPath, `${logPath}.1`);
+ } catch {
+ /* absent, or a rotation that lost a race — either way, keep writing */
+ }
+ // Detail spreads first so the authoritative fields win: a tool argument
+ // named `caller` must not be able to forge the recorded identity.
+ const entry: AuditEntry = {
+ ...detail,
+ action,
+ caller: getCaller() ?? "unknown",
+ at: now(),
+ };
+ appendFileSync(logPath, JSON.stringify(entry) + "\n");
+ } catch {
+ /* auditing must never break the server */
+ }
+ };
+}
+
+/** Where the audit log lives for a given vault. */
+export function auditPath(vaultRoot: string): string {
+ return join(vaultRoot, ".claude", "om-mcp-audit.jsonl");
+}
diff --git a/.claude/scripts/lib/mcp-capture.ts b/.claude/scripts/lib/mcp-capture.ts
new file mode 100644
index 0000000..455a481
--- /dev/null
+++ b/.claude/scripts/lib/mcp-capture.ts
@@ -0,0 +1,308 @@
+/**
+ * `record_work` — filing what happened in a repo back into the vault.
+ *
+ * The sibling of `remember`, and constantly confused with it. The distinction
+ * is single-valued vs multi-valued: a WORK RECORD is about one project at one
+ * moment, so it has a correct folder and gets filed into it. A MEMORY may touch
+ * several projects and a cross-cutting theme, so it has no correct folder and
+ * lives under a date with its reach declared in frontmatter.
+ *
+ * ROUTING IS DELEGATED, NOT INFERRED
+ *
+ * The calling session already carries the vault's conventions (through the
+ * injected contract) and can search the vault to see where similar notes live.
+ * It is an agent the user is already paying for, so asking it to choose costs
+ * nothing extra and beats anything this server could infer from a repo name.
+ *
+ * The server's job is therefore to VALIDATE, never to guess: a caller-supplied
+ * folder must resolve inside an exposed root, so a destination string cannot
+ * turn this tool into an arbitrary write anywhere on disk.
+ */
+
+import { existsSync, readdirSync, mkdirSync, realpathSync } from "node:fs";
+import { join, resolve, sep } from "node:path";
+
+import type { ExposurePolicy } from "./mcp-exposure.ts";
+import { claimFile } from "./atomic-write.ts";
+
+const SLUG_MAX = 60;
+const MAX_COLLISIONS = 500;
+const DESCRIPTION_MAX = 150;
+
+export interface Destination {
+ readonly dir: string;
+ readonly rel: string;
+ readonly project: string | null;
+ readonly routed: "caller" | "caller-identity" | "fallback";
+}
+
+export interface CaptureInput {
+ readonly title?: unknown;
+ readonly summary?: unknown;
+ readonly changes?: unknown;
+ readonly decisions?: unknown;
+ readonly learned?: unknown;
+ readonly verification?: unknown;
+ readonly open?: unknown;
+ readonly informed_by?: unknown;
+ readonly folder?: unknown;
+ readonly kind?: unknown;
+ readonly dry_run?: unknown;
+}
+
+export interface CaptureResult {
+ readonly path: string;
+ readonly bytes: number;
+ readonly written: boolean;
+ readonly routed: Destination["routed"];
+ readonly preview?: string;
+ readonly indexed?: boolean;
+}
+
+/** Filesystem-safe stem from a title. Separators are stripped, not escaped. */
+export function slugifyTitle(title: unknown): string {
+ return String(title)
+ .normalize("NFKD")
+ .replace(/[^\w\s-]/g, "")
+ .trim()
+ .replace(/\s+/g, "-")
+ .slice(0, SLUG_MAX)
+ .replace(/^-+|-+$/g, "")
+ .toLowerCase();
+}
+
+/**
+ * The project folder matching a calling repo, if this vault has one.
+ *
+ * Exact match, then case-insensitive, then a prefix match in either direction —
+ * a repo and its project folder usually agree but not always ("poc" vs
+ * "pocket"). Returns null when the vault has no `projects/` folder at all,
+ * which a clean install of this template does not.
+ */
+export function projectDirFor(vaultRoot: string, caller: string | null): { name: string; dir: string } | null {
+ if (!caller) return null;
+ const root = join(vaultRoot, "projects");
+ if (!existsSync(root)) return null;
+
+ let entries: string[];
+ try {
+ entries = readdirSync(root);
+ } catch {
+ return null;
+ }
+ // Matched against the directory listing rather than with existsSync, so the
+ // name returned is the folder's REAL casing. On a case-insensitive
+ // filesystem existsSync(join(root, "Pocket")) succeeds for a folder actually
+ // called "pocket", and the caller's casing would then be written into every
+ // capture's `project:` frontmatter — splitting one project into two groups in
+ // any Base that filters on it.
+ const want = caller.toLowerCase();
+ const hit =
+ entries.find((e) => e === caller) ??
+ entries.find((e) => e.toLowerCase() === want) ??
+ entries.find((e) => {
+ const a = e.toLowerCase();
+ return a.startsWith(want) || want.startsWith(a);
+ });
+ return hit ? { name: hit, dir: join(root, hit) } : null;
+}
+
+/**
+ * Where the note goes, cheapest-and-most-informed first:
+ *
+ * 1. a `folder` the caller chose — validated, never trusted
+ * 2. derived from caller identity, when the repo maps to a project folder
+ * 3. the configured inbox, for the genuinely unknown case only
+ */
+export function resolveDestination(
+ vaultRoot: string,
+ policy: ExposurePolicy,
+ manifest: Record<string, unknown> | null | undefined,
+ caller: string | null,
+ folder: unknown,
+ kind: unknown,
+): Destination {
+ if (typeof folder === "string" && folder.trim()) {
+ const rel = folder.trim().replace(/^[\\/]+|[\\/]+$/g, "");
+ const root = rel.split(/[\\/]/)[0] ?? "";
+ if (!policy.roots.some((r) => r.toLowerCase() === root.toLowerCase())) {
+ throw new Error(`refused: "${root}" is not an exposed root (allowed: ${policy.roots.join(", ")})`);
+ }
+ // No traversal segments at all. Checking containment against the VAULT is
+ // not enough: `brain/../work` passes the root check on its first segment
+ // and still resolves inside the vault, so it landed in `work/` — a folder
+ // the caller never named and the policy may not even serve.
+ if (rel.split(/[\\/]/).some((seg) => seg === "..")) {
+ throw new Error(`refused: "${folder}" contains a traversal segment`);
+ }
+ const dir = resolve(join(vaultRoot, rel));
+ // Containment against the DECLARED ROOT, not merely the vault: roots are
+ // per-folder, so "inside the vault" is the wrong question.
+ const rootDir = resolve(join(vaultRoot, root));
+ if (dir !== rootDir && !dir.startsWith(rootDir + sep)) {
+ throw new Error(`refused: "${folder}" escapes the "${root}" root`);
+ }
+ return { dir, rel, project: null, routed: "caller" };
+ }
+
+ const proj = projectDirFor(vaultRoot, caller);
+ if (proj) {
+ const sub = kind === "decision" ? "decisions" : "notes";
+ return {
+ dir: join(proj.dir, sub),
+ rel: `projects/${proj.name}/${sub}`,
+ project: proj.name,
+ routed: "caller-identity",
+ };
+ }
+
+ const declared = manifest?.mcp_inbox;
+ const fallback = typeof declared === "string" && /^[\w.-]+$/.test(declared) ? declared : "inbox";
+ return { dir: join(vaultRoot, fallback), rel: fallback, project: null, routed: "fallback" };
+}
+
+/** Render the note body. Pure, so the shape can be asserted without writing. */
+export function renderCapture(
+ input: CaptureInput,
+ dest: Destination,
+ caller: string,
+ resolvable: ReadonlySet<string>,
+ now: Date,
+): string {
+ const day = now.toISOString().slice(0, 10);
+
+ const list = (arr: unknown): string | null =>
+ Array.isArray(arr) && arr.length ? arr.map((x) => `- ${String(x).trim()}`).join("\n") : null;
+
+ const section = (heading: string, content: string | null): string =>
+ content ? `\n## ${heading}\n\n${content}\n` : "";
+
+ // Only emit links that actually resolve. A capture that manufactures broken
+ // links is worse than one that omits them: it degrades the graph silently and
+ // trips the vault's own wikilink gate.
+ const linkOrPlain = (raw: unknown): string => {
+ const name = String(raw).replace(/^\[\[|\]\]$/g, "").trim();
+ return resolvable.has(name.toLowerCase()) ? `- [[${name}]]` : `- ${name} _(no note yet)_`;
+ };
+
+ // `informed_by` becomes wikilinks, which is the point of asking for it: the
+ // notes that shaped this work gain a backlink proving they were applied. A
+ // decision with no backlinks is either unused or undiscoverable, and this is
+ // how you tell the difference.
+ const informed =
+ Array.isArray(input.informed_by) && input.informed_by.length
+ ? input.informed_by.map(linkOrPlain).join("\n")
+ : null;
+
+ // Orphans are bugs, but so are broken links. Link home only if the project is
+ // genuinely reachable by name (a README alias, usually).
+ const home = dest.project && resolvable.has(dest.project.toLowerCase()) ? `- [[${dest.project}]]` : null;
+ const related = [home, informed].filter(Boolean).join("\n");
+
+ const summary = String(input.summary ?? "").trim();
+
+ return [
+ "---",
+ `date: ${day}`,
+ `description: "${summary.replace(/"/g, "'").replace(/\s+/g, " ").slice(0, DESCRIPTION_MAX)}"`,
+ "tags:",
+ input.kind === "decision" ? " - decision" : " - project-note",
+ ...(dest.project ? [`project: ${dest.project}`] : []),
+ `source_repo: ${caller}`,
+ "---",
+ "",
+ `# ${String(input.title ?? "").trim()}`,
+ "",
+ summary,
+ section("What changed", list(input.changes)),
+ section("Decisions", list(input.decisions)),
+ section("Learned", list(input.learned)),
+ section("Verification", input.verification ? String(input.verification).trim() : null),
+ section("Open", list(input.open)),
+ section("Related", related || null),
+ "",
+ `_Recorded ${now.toISOString()} from \`${caller}\` via the om MCP server (routing: ${dest.routed})._`,
+ "",
+ ].join("\n");
+}
+
+/**
+ * File the note.
+ *
+ * Written to a temp file first, so a crash mid-write cannot leave a half-note
+ * for the indexer to pick up, then the final name is claimed with an ATOMIC
+ * exclusive create.
+ *
+ * The obvious version — `while (existsSync(x)) bump(x); rename(tmp, x)` — is a
+ * TOCTOU race: two processes can both see a name free, and `rename` silently
+ * OVERWRITES, so one capture vanishes with no error. It did not reproduce
+ * across 8 concurrent writers because process startup staggers them, but "did
+ * not fire" is not "cannot fire". `COPYFILE_EXCL` fails instead of clobbering,
+ * so the loser simply takes the next suffix.
+ */
+export function captureNote(
+ vaultRoot: string,
+ policy: ExposurePolicy,
+ manifest: Record<string, unknown> | null | undefined,
+ caller: string | null,
+ input: CaptureInput,
+ resolvable: ReadonlySet<string>,
+ opts: { now?: Date; reindex?: () => boolean } = {},
+): CaptureResult {
+ const now = opts.now ?? new Date();
+ const who = caller ?? "unknown";
+
+ const stemBase = slugifyTitle(input.title);
+ if (!stemBase) throw new Error("title produces an empty filename");
+
+ const dest = resolveDestination(vaultRoot, policy, manifest, caller, input.folder, input.kind);
+
+ // A capture is a RECORD OF WHAT HAPPENED — point-in-time, so it takes the
+ // vault's `YYYY-MM-DD ` naming law. A decision is a living document and does
+ // not, because a creation-date prefix inverts the recency signal on a note
+ // that keeps being edited.
+ const day = now.toISOString().slice(0, 10);
+ const stem = input.kind === "decision" ? stemBase : `${day}-${stemBase}`;
+
+ const body = renderCapture(input, dest, who, resolvable, now);
+
+ // Returned BEFORE the destination is created. An earlier version made the
+ // folder first, so previewing a capture left an empty `inbox/` in the user's
+ // vault — a "dry run" that changes the vault is not one, and the whole point
+ // of the preview is that it can be trusted.
+ if (input.dry_run === true) {
+ return {
+ path: `${dest.rel}/${stem}.md`,
+ bytes: body.length,
+ written: false,
+ routed: dest.routed,
+ preview: body.slice(0, 600),
+ };
+ }
+
+ if (!existsSync(dest.dir)) mkdirSync(dest.dir, { recursive: true });
+ const base = realpathSync(dest.dir);
+
+ // Claimed atomically rather than checked-then-written; see `atomic-write.ts`
+ // for why, and for what the naive version cost.
+ const claimed = claimFile(base, body, (n) => (n === 1 ? `${stem}.md` : `${stem}-${n}.md`), {
+ maxAttempts: MAX_COLLISIONS,
+ // Containment: slugify strips separators, but verify rather than trust.
+ verify: (full) => {
+ if (!resolve(full).startsWith(base + sep)) throw new Error("refused: path escapes the destination");
+ },
+ exhaustedMessage: "too many colliding captures for that title",
+ });
+
+ // Index it NOW. An MCP write bypasses the PostToolUse hook that normally
+ // triggers re-indexing, so without this the note is on disk but invisible to
+ // search — written and unfindable.
+ const indexed = opts.reindex ? opts.reindex() : undefined;
+ return {
+ path: `${dest.rel}/${claimed.name}`,
+ bytes: body.length,
+ written: true,
+ routed: dest.routed,
+ ...(indexed === undefined ? {} : { indexed }),
+ };
+}
diff --git a/.claude/scripts/lib/mcp-context.ts b/.claude/scripts/lib/mcp-context.ts
new file mode 100644
index 0000000..714a36f
--- /dev/null
+++ b/.claude/scripts/lib/mcp-context.ts
@@ -0,0 +1,214 @@
+/**
+ * Everything the MCP server needs to know about the vault it is serving,
+ * resolved once at startup.
+ *
+ * Split out of the server for one reason: this is the layer where a wrong
+ * answer is INVISIBLE. A vault root pointing one directory too high, an index
+ * name belonging to a different vault, a memory root that no longer exists —
+ * none of them error. They all present as "the vault knows nothing", and three
+ * separate defects of exactly that shape were found only by installing the
+ * prototype against a vault other than the author's.
+ *
+ * So every value here is either derived from the vault itself, validated before
+ * use, or reported by `health()`. Nothing is assumed, and nothing that fails
+ * validation is trusted just because it was written down.
+ */
+
+import { readFileSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import { resolveQmdIndex } from "./session-start.ts";
+import { MEMORY_ROOT } from "./memory-write.ts";
+import { discoverMemoryRoot, discoverQmdLauncher, type MemoryRootInfo } from "./memory-discover.ts";
+
+export interface VaultContext {
+ /** Absolute path to the vault this server serves. */
+ readonly vaultRoot: string;
+ /** Parsed `vault-manifest.json`, or `{}` when absent or malformed. */
+ readonly manifest: Record<string, unknown>;
+ /** The qmd named index this vault owns, or null for qmd's global default. */
+ readonly qmdIndex: string | null;
+ /** Where memories actually live, and whether that disagreed with config. */
+ readonly memory: MemoryRootInfo;
+ /** Convenience: `memory.root`. */
+ readonly memoryRoot: string;
+ /** Path to this install's qmd MCP launcher, or null when qmd is absent. */
+ readonly qmdLauncher: string | null;
+ /** Set when OM_VAULT_PATH pointed somewhere other than the launcher location. */
+ readonly overriddenFrom: string | null;
+}
+
+/**
+ * Resolve the vault root.
+ *
+ * Layout assumption, identical to `qmd-mcp.mjs`: the server lives at
+ * `<vault>/.claude/scripts/`, so the vault is two levels up. The env override
+ * exists because one binary should be able to serve any vault — "which vault?"
+ * is a config answer, never a guess — and because a consuming repo registering
+ * this server may point at a vault that is nowhere near it on disk.
+ */
+export function resolveVaultRoot(metaUrl: string, env: NodeJS.ProcessEnv = process.env): string {
+ // `OM_VAULT_PATH` only. A bare `VAULT_PATH` was also honoured, and that name
+ // is too generic to claim: it is set for unrelated reasons on real machines,
+ // and the result was a server silently serving a DIFFERENT vault than the
+ // launcher it was started from — reporting that vault's config as if correct.
+ const override = env.OM_VAULT_PATH;
+ if (override && override.trim()) return resolve(override.trim());
+ return resolve(dirname(fileURLToPath(metaUrl)), "..", "..");
+}
+
+/**
+ * The vault the launcher's own location implies, ignoring any override. Used by
+ * `health` to say when the two disagree.
+ */
+export function derivedVaultRoot(metaUrl: string): string {
+ return resolve(dirname(fileURLToPath(metaUrl)), "..", "..");
+}
+
+/** Read and parse the manifest. A malformed manifest is `{}`, never a throw. */
+export function readManifest(vaultRoot: string): Record<string, unknown> {
+ try {
+ const parsed: unknown = JSON.parse(readFileSync(join(vaultRoot, "vault-manifest.json"), "utf8"));
+ // `typeof [] === "object"`, so the array case needs its own guard or a
+ // manifest of `[1,2,3]` is handed back as if it were a record.
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)
+ ? (parsed as Record<string, unknown>)
+ : {};
+ } catch {
+ return {};
+ }
+}
+
+/**
+ * Validate a declared `memory_root` before anything writes through it.
+ *
+ * A memory root carrying a separator or a traversal would turn every capture
+ * into an arbitrary write anywhere on disk. The rule is deliberately stricter
+ * than "does it resolve inside the vault": a single path segment of ordinary
+ * filename characters, or the default. Anything else is not repaired or
+ * rejected loudly — it falls back, because a capture landing in the default
+ * folder is recoverable and a capture landing outside the vault is not.
+ */
+export function safeMemoryRoot(declared: unknown, fallback: string = MEMORY_ROOT): string {
+ if (typeof declared !== "string") return fallback;
+ const value = declared.trim();
+ if (!value || value === "." || value === "..") return fallback;
+ if (!/^[\w.-]+$/.test(value)) return fallback;
+ return value;
+}
+
+/**
+ * Build the context. Every discovery is individually guarded: a failure in one
+ * must degrade that one capability, never take down startup. A server that
+ * refuses to boot because `health` could not be computed is strictly worse than
+ * one that boots and reports the problem.
+ */
+export function createContext(vaultRoot: string, derivedFrom?: string): VaultContext {
+ const manifest = readManifest(vaultRoot);
+
+ // Route through the canonical resolver. Four other callers already share it
+ // (SessionStart, the refresh worker, the MCP wrapper, the bootstrap script)
+ // and they fail SILENTLY when they disagree — one writes to a store another
+ // never reads, which surfaces only as "0 documents". This server is the fifth.
+ let qmdIndex: string | null = null;
+ try {
+ const raw = readFileSync(join(vaultRoot, "vault-manifest.json"), "utf8");
+ qmdIndex = resolveQmdIndex(raw, vaultRoot);
+ } catch {
+ qmdIndex = resolveQmdIndex(null, vaultRoot);
+ }
+
+ const configured = safeMemoryRoot(manifest.memory_root);
+ let memory: MemoryRootInfo;
+ try {
+ memory = discoverMemoryRoot(vaultRoot, configured);
+ } catch {
+ memory = {
+ root: configured,
+ source: "configured",
+ memories: 0,
+ healed: false,
+ configured,
+ split: null,
+ };
+ }
+
+ let qmdLauncher: string | null = null;
+ try {
+ qmdLauncher = discoverQmdLauncher(vaultRoot).path;
+ } catch {
+ qmdLauncher = null;
+ }
+
+ const overriddenFrom =
+ derivedFrom && resolve(derivedFrom) !== resolve(vaultRoot) ? resolve(derivedFrom) : null;
+ return { vaultRoot, manifest, qmdIndex, memory, memoryRoot: memory.root, qmdLauncher, overriddenFrom };
+}
+
+/**
+ * The contract. This is the payload that makes tier 0 worth building: it lands
+ * in the system prompt of every session that connects, in any repository.
+ *
+ * Kept deliberately short. Every token here is paid by every session, so it
+ * carries only rules that change behaviour OUTSIDE the vault — not the vault's
+ * own filing conventions, which are useless to a session in another repo.
+ *
+ * Note what this does and does not attempt. The PROHIBITION at the end holds
+ * reliably: measured, a session refused a direct request and an authority
+ * override rather than break it. The "when to use it" section is ADVISORY and
+ * gets skipped whenever a nearer source exists — which is why the install also
+ * requires a pointer in the consuming repo's own CLAUDE.md. A server can stop a
+ * session doing something; it cannot make one go looking.
+ */
+export const INSTRUCTIONS: string = [
+ "You have access to the user's personal knowledge vault through this server.",
+ "",
+ "WHEN TO USE IT: before answering questions about past decisions, prior art, why",
+ "something is the way it is, or what the user already concluded, call search.",
+ "The vault is the record; your memory of this conversation is not.",
+ "",
+ "The vault also exposes notes as MCP RESOURCES. List them when you want to see what",
+ "knowledge exists before searching blindly, and read one directly when its title",
+ "already answers the question — that is cheaper and more exact than a search.",
+ "Once you know a specific note, call expand to see what it links to and what",
+ "links back, rather than searching again.",
+ "",
+ "HOW TO TREAT WHAT YOU FIND: cite the note path you used. Vault notes carry",
+ "'as of YYYY-MM-DD' markers on volatile facts and (TBC)/(inferred) markers on",
+ "unverified ones. Preserve those qualifiers when you repeat a claim; never",
+ "promote an inferred fact to a stated one. If a note is months old and the claim",
+ "is volatile, say so rather than asserting it.",
+ "",
+ "NEVER put agent-session artifacts into anything that lands in a repository:",
+ "no claude.ai session URLs, no 'Claude-Session:' trailers, no local absolute",
+ "paths. Not in commit messages, PR or issue bodies, review comments, or files.",
+ "'Co-Authored-By:' is fine and wanted; the session URL is not.",
+].join("\n");
+
+export interface PromptDef {
+ readonly name: string;
+ readonly description: string;
+ readonly arguments: { name: string; description: string; required: boolean }[];
+}
+
+/**
+ * Vault workflows as slash commands in the calling session.
+ *
+ * These exist because they are USER-invoked. Everything else on this server
+ * depends on the model deciding to call it, and the measured finding is that it
+ * often does not when a nearer source is available. A prompt bypasses that
+ * entirely: the human chooses, so the vault is consulted with certainty.
+ */
+export const PROMPTS: readonly PromptDef[] = [
+ {
+ name: "recall_topic",
+ description: "Search the vault and summarise what is already known about a topic, with citations.",
+ arguments: [{ name: "topic", description: "What to recall", required: true }],
+ },
+ {
+ name: "prior_art",
+ description: "Check the vault for prior decisions on a question before deciding it again.",
+ arguments: [{ name: "question", description: "The decision being faced", required: true }],
+ },
+];
diff --git a/.claude/scripts/lib/mcp-exposure.ts b/.claude/scripts/lib/mcp-exposure.ts
new file mode 100644
index 0000000..d1f561c
--- /dev/null
+++ b/.claude/scripts/lib/mcp-exposure.ts
@@ -0,0 +1,396 @@
+/**
+ * Which notes this vault serves, on every surface.
+ *
+ * The default is the vault's own `user_content_roots` — the user's notes, read
+ * by the user's own session. `mcp_exposed_roots` narrows that, and exists for a
+ * vault holding material that is not the user's to share.
+ *
+ * A note is served when all three hold:
+ *
+ * 1. its path is inside an exposed root
+ * 2. its filename is not in the never-expose list
+ * 3. it is not tagged `private` in frontmatter
+ *
+ * Every read surface resolves through this module rather than walking the vault
+ * itself, so `search`, `expand` and the resource enumerators cannot disagree
+ * about which notes exist. A surface that reads the filesystem directly is the
+ * defect this module is shaped to prevent.
+ */
+
+import { readFileSync, readdirSync, statSync, lstatSync, existsSync, realpathSync } from "node:fs";
+import { join, basename, resolve, sep } from "node:path";
+
+
+import { vaultRelKey } from "./mcp-qmd-client.ts";
+
+/** How deep to walk inside an exposed root. */
+const MAX_DEPTH = 4;
+/** How much of a file to read when probing its frontmatter. */
+const HEAD_BYTES = 1200;
+
+export interface ExposurePolicy {
+ /** Path prefixes whose notes are served. */
+ readonly roots: readonly string[];
+ /** Filenames withheld regardless of folder. */
+ readonly neverExpose: ReadonlySet<string>;
+ /** Where the root list came from, for `health` to report. */
+ readonly source: "manifest" | "derived" | "fallback";
+ /** The memory root, excluded from every read surface unconditionally. */
+ readonly memoryRoot: string;
+}
+
+export interface VisibleFile {
+ readonly full: string;
+ readonly label: string;
+ /** The exposed root this file was reached through. */
+ readonly scope: string;
+}
+
+export interface ResourceDef {
+ readonly uri: string;
+ readonly name: string;
+ readonly description: string;
+ readonly mimeType: string;
+}
+
+/** Used only when the manifest declares neither exposure key. */
+const FALLBACK_ROOTS: readonly string[] = ["brain", "reference"];
+
+/**
+ * Normalise a declared root. Path PREFIXES are allowed, not just top-level
+ * names, because that is the granularity the vault already speaks in:
+ * `user_content_roots` says `work/active/`, not `work/`. Collapsing to the top
+ * segment would expose `work/1-1/` because `work/active/` was declared, which
+ * is both wrong and not what the user wrote down.
+ *
+ * Traversal is refused; a trailing slash and a leading `./` are tolerated
+ * because the manifest is written by humans.
+ */
+function cleanRoots(value: unknown): string[] {
+ if (!Array.isArray(value)) return [];
+ const out: string[] = [];
+ for (const raw of value) {
+ if (typeof raw !== "string") continue;
+ const trimmed = raw.trim().replace(/^\.\//, "");
+ // A trailing slash marks the last segment as a FOLDER; without one it is a
+ // file pattern. That distinction decides how a glob is handled.
+ const endsInFolder = /[\\/]$/.test(trimmed);
+ const s = trimmed.replace(/^[\\/]+|[\\/]+$/g, "");
+ if (!s) continue;
+ const parts = s.split(/[\\/]/);
+ if (parts.some((p) => p === "." || p === "..")) continue;
+
+ const globAt = parts.findIndex((p) => p.includes("*"));
+ if (globAt < 0) {
+ out.push(parts.join("/"));
+ continue;
+ }
+ // `brain/*.md` — a file pattern, so the parent folder is what was meant.
+ // `perf/h*-*/` — a set of FOLDERS under perf. Truncating that to `perf`
+ // would serve every folder under it, which is more than the vault
+ // declared, so the entry is dropped instead.
+ if (!endsInFolder && globAt === parts.length - 1 && globAt > 0) {
+ out.push(parts.slice(0, globAt).join("/"));
+ }
+ }
+ return [...new Set(out)];
+}
+
+/**
+ * Memories are never served as ordinary notes, whatever the config says. They
+ * carry their own declared scope, evaluated per caller; reaching them through
+ * the note surface would bypass it.
+ */
+function withoutMemoryRoot(roots: readonly string[], memoryRoot: string): string[] {
+ const mem = memoryRoot.toLowerCase();
+ return roots.filter((r) => r.toLowerCase() !== mem && !r.toLowerCase().startsWith(`${mem}/`));
+}
+
+/** Keep only roots that exist on disk, so the listing reflects the vault. */
+function present(vaultRoot: string, roots: readonly string[]): string[] {
+ return roots.filter((r) => {
+ try {
+ return statSync(join(vaultRoot, r)).isDirectory();
+ } catch {
+ return false;
+ }
+ });
+}
+
+/**
+ * Which folders this vault serves.
+ *
+ * `mcp_exposed_roots` when declared, otherwise the vault's own
+ * `user_content_roots` — the user's notes, read by the user's own session. A
+ * vault holding material that is not the user's to share (employer-confidential
+ * notes, client data) narrows it explicitly.
+ */
+export function resolveExposure(
+ vaultRoot: string,
+ manifest: Record<string, unknown> | null | undefined,
+ memoryRoot = "memories",
+): ExposurePolicy {
+ // Filenames, not folder names — spaces and dots are legitimate here.
+ const never = new Set(
+ Array.isArray(manifest?.mcp_never_expose)
+ ? manifest.mcp_never_expose.filter((s): s is string => typeof s === "string")
+ : [],
+ );
+
+ const declared = cleanRoots(manifest?.mcp_exposed_roots);
+ if (declared.length) {
+ return { roots: withoutMemoryRoot(declared, memoryRoot), neverExpose: never, source: "manifest", memoryRoot };
+ }
+
+ const derived = present(vaultRoot, cleanRoots(manifest?.user_content_roots));
+ if (derived.length) {
+ return { roots: withoutMemoryRoot(derived, memoryRoot), neverExpose: never, source: "derived", memoryRoot };
+ }
+
+ const fallback = present(vaultRoot, FALLBACK_ROOTS);
+ return {
+ roots: withoutMemoryRoot(fallback.length ? fallback : [...FALLBACK_ROOTS], memoryRoot),
+ neverExpose: never,
+ source: "fallback",
+ memoryRoot,
+ };
+}
+
+/**
+ * Is this note marked private?
+ *
+ * An UNREADABLE file returns true, so a file whose frontmatter cannot be
+ * inspected is not served — a permissions error must not resolve to "not
+ * private".
+ */
+export function isPrivate(path: string): boolean {
+ try {
+ const head = readFileSync(path, "utf8").slice(0, HEAD_BYTES);
+ return /^\s*-?\s*private\s*$/m.test(head) || /^private:\s*true/m.test(head);
+ } catch {
+ return true;
+ }
+}
+
+/** Pull the frontmatter `description:` so a resource list is self-describing. */
+export function firstDescription(path: string, fallback = "Vault note"): string {
+ try {
+ const head = readFileSync(path, "utf8").slice(0, HEAD_BYTES);
+ const m = head.match(/^description:\s*"?(.+?)"?\s*$/m);
+ return m?.[1] ? m[1].slice(0, 200) : fallback;
+ } catch {
+ return fallback;
+ }
+}
+
+/**
+ * Does `path` resolve to something inside `rootReal`?
+ *
+ * `realpath` follows symlinks all the way, so this is the check that decides
+ * whether a link stays inside the root it was reached through. A broken link
+ * throws and is refused: a path that cannot be resolved is not served.
+ */
+function containedIn(rootReal: string, path: string): boolean {
+ try {
+ const real = realpathSync(resolve(path));
+ return real === rootReal || real.startsWith(rootReal + sep);
+ } catch {
+ return false;
+ }
+}
+
+/** The declared root that admits `rel`, at the granularity the manifest wrote it. */
+function matchedRoot(policy: ExposurePolicy, rel: string): string | null {
+ const lower = rel.replace(/\\/g, "/").toLowerCase();
+ return (
+ policy.roots.find((r) => {
+ const root = r.toLowerCase();
+ return lower === root || lower.startsWith(`${root}/`);
+ }) ?? null
+ );
+}
+
+/** Is `rel` inside one of the policy's exposed roots? */
+export function isExposedPath(policy: ExposurePolicy, relPath: string): boolean {
+ const rel = relPath.replace(/\\/g, "/").toLowerCase();
+ if (!rel) return false;
+ const mem = policy.memoryRoot?.toLowerCase();
+ if (mem && (rel === mem || rel.startsWith(`${mem}/`))) return false;
+ // Prefix match on whole segments, so `work/active` does not admit
+ // `work/active-secrets` and `brain` admits `brain/sub/note.md`.
+ return policy.roots.some((r) => {
+ const root = r.toLowerCase();
+ return rel === root || rel.startsWith(`${root}/`);
+ });
+}
+
+/**
+ * Every note this vault will expose, on any surface.
+ *
+ * This is the single source of truth. `search` filters its hits against it,
+ * `expand` computes backlinks only over it, and the resource enumerators build
+ * from it — so a note cannot be absent from one surface and present on another.
+ *
+ * Symlinks are resolved and contained DURING the walk, not only when a URI is
+ * read back. `statSync` follows a link silently, so enumerating with it meant a
+ * `.md` link inside an exposed root pulled in a file from anywhere on disk:
+ * `listResources` published its description, `allowedSearchPaths` accepted it,
+ * and `expand` read its body — while `resolveResourceUri` refused the very same
+ * path. Two read paths disagreeing is the one thing this module exists to stop.
+ */
+export function visibleFiles(vaultRoot: string, policy: ExposurePolicy): VisibleFile[] {
+ const files: VisibleFile[] = [];
+
+ const walk = (dir: string, scope: string, rootReal: string, depth: number): void => {
+ if (depth > MAX_DEPTH || !existsSync(dir)) return;
+ let entries: string[];
+ try {
+ entries = readdirSync(dir);
+ } catch {
+ return;
+ }
+ for (const f of entries) {
+ if (f.startsWith(".")) continue;
+ const full = join(dir, f);
+ let isDir: boolean;
+ try {
+ // lstat describes the ENTRY; stat describes what it points at. The
+ // difference is the whole check: a link is contained before it is
+ // followed, and an ordinary entry costs no extra syscall.
+ const entry = lstatSync(full);
+ if (entry.isSymbolicLink()) {
+ if (!containedIn(rootReal, full)) continue;
+ isDir = statSync(full).isDirectory();
+ } else {
+ isDir = entry.isDirectory();
+ }
+ } catch {
+ continue;
+ }
+ if (isDir) {
+ walk(full, scope, rootReal, depth + 1);
+ continue;
+ }
+ if (!f.endsWith(".md")) continue;
+ if (policy.neverExpose.has(f)) continue;
+ if (isPrivate(full)) continue;
+ files.push({ full, label: basename(f, ".md"), scope });
+ }
+ };
+
+ for (const root of policy.roots) {
+ // Belt and braces: resolveExposure already strips it, but a hand-built
+ // policy must not be able to walk the memory store into the read surface.
+ if (policy.memoryRoot && root.toLowerCase() === policy.memoryRoot.toLowerCase()) continue;
+ const dir = join(vaultRoot, root);
+ let rootReal: string;
+ try {
+ rootReal = realpathSync(resolve(dir));
+ } catch {
+ continue; // the root does not exist, or is itself a broken link
+ }
+ walk(dir, root, rootReal, 0);
+ }
+ return files;
+}
+
+/**
+ * The set `search` filters against — vault-relative keys of every visible file.
+ *
+ * Derived from `visibleFiles` rather than computed separately, because two
+ * independent implementations of "what may this caller see" is how the surfaces
+ * drifted apart in the first place.
+ */
+export function allowedSearchPaths(vaultRoot: string, policy: ExposurePolicy): Set<string> {
+ return new Set(visibleFiles(vaultRoot, policy).map((f) => vaultRelKey(vaultRoot, f.full)));
+}
+
+/**
+ * Notes offered as MCP resources, so a session can list what knowledge exists
+ * and read one directly when its title already answers the question — cheaper
+ * and more exact than a search.
+ *
+ * Built from `visibleFiles` rather than from a walk of its own, so a vault that
+ * narrows `mcp_exposed_roots` gets that narrowing here too. An enumerator that
+ * reads known folders directly ignores the setting entirely.
+ */
+export function listResources(vaultRoot: string, policy: ExposurePolicy): ResourceDef[] {
+ return visibleFiles(vaultRoot, policy).map((f) => {
+ const rel = vaultRelKeyRaw(vaultRoot, f.full);
+ return {
+ uri: `vault://note/${rel.split("/").map(encodeURIComponent).join("/")}`,
+ name: f.scope === f.label ? f.label : `${f.scope}: ${f.label}`,
+ description: firstDescription(f.full),
+ mimeType: "text/markdown",
+ };
+ });
+}
+
+/**
+ * Vault-relative path with case and spacing PRESERVED.
+ *
+ * `vaultRelKey` deliberately normalises for comparison; a URI must round-trip to
+ * a real file, so it needs the original.
+ */
+export function vaultRelKeyRaw(vaultRoot: string, full: string): string {
+ const v = vaultRoot.replace(/\\/g, "/").replace(/\/+$/, "");
+ const p = full.replace(/\\/g, "/");
+ return p.toLowerCase().startsWith(v.toLowerCase()) ? p.slice(v.length).replace(/^\/+/, "") : p;
+}
+
+/**
+ * Resolve a `vault://note/<rel>` URI back to a file, re-applying the policy.
+ *
+ * Re-checked rather than trusted: a URI is caller-supplied input, and the fact
+ * that this server minted one earlier is not evidence that THIS one resolves
+ * inside the policy. Anything outside it returns null, which the caller reports
+ * as not-found — to this server a URI it does not serve is simply not a
+ * resource.
+ */
+export function resolveResourceUri(
+ vaultRoot: string,
+ policy: ExposurePolicy,
+ uri: string,
+): string | null {
+ const m = String(uri).match(/^vault:\/\/note\/(.+)$/);
+ if (!m?.[1]) return null;
+
+ let rel: string;
+ try {
+ rel = m[1]
+ .split("/")
+ .map((s) => decodeURIComponent(s))
+ .join("/");
+ } catch {
+ return null;
+ }
+
+ // Traversal and absolute paths are refused before touching the filesystem.
+ if (rel.includes("..") || rel.startsWith("/") || /^[A-Za-z]:/.test(rel)) return null;
+ if (!rel.toLowerCase().endsWith(".md")) return null;
+ if (!isExposedPath(policy, rel)) return null;
+ if (policy.neverExpose.has(basename(rel))) return null;
+
+ // Containment must survive SYMLINKS, not just `..`. `resolve` collapses dot
+ // segments but happily returns a path whose real target is outside the vault,
+ // so a symlink inside an exposed folder would read anything this process can
+ // read. Both ends are resolved through `realpath` and compared.
+ //
+ // Against the DECLARED root, not the first path segment: roots are prefixes,
+ // so a vault serving `work/active/` and not `work/1-1/` must not accept a link
+ // under the former resolving into the latter — both share the segment `work`.
+ const root = matchedRoot(policy, rel);
+ if (!root) return null;
+ let rootReal: string;
+ let full: string;
+ try {
+ rootReal = realpathSync(resolve(join(vaultRoot, root)));
+ full = realpathSync(resolve(join(vaultRoot, rel)));
+ } catch {
+ return null; // missing, or a broken link
+ }
+ if (full !== rootReal && !full.startsWith(rootReal + sep)) return null;
+ if (policy.neverExpose.has(basename(full))) return null;
+ if (isPrivate(full)) return null;
+ return full;
+}
diff --git a/.claude/scripts/lib/mcp-graph.ts b/.claude/scripts/lib/mcp-graph.ts
new file mode 100644
index 0000000..6d1a022
--- /dev/null
+++ b/.claude/scripts/lib/mcp-graph.ts
@@ -0,0 +1,190 @@
+/**
+ * Graph traversal — `expand`.
+ *
+ * WHY THIS IS NOT JUST ANOTHER SEARCH
+ *
+ * Searching and expanding from a known node are different operations, and
+ * conflating them wastes turns: a session that already has the relevant note
+ * should not have to re-describe it as a query and hope the index agrees. The
+ * vault is already a wikilink graph, so following it is nearly free — no model
+ * call, no embedding, just reading what is already written down.
+ *
+ * SCOPING APPLIES ON BOTH DIRECTIONS OF THE EDGE
+ *
+ * Backlinks are computed only over served notes, so `expand` and `search` agree
+ * on which notes exist rather than reaching them by different routes. Outbound
+ * links get the same treatment from the other side: a link pointing outside the
+ * served set is COUNTED but not NAMED, which is honest about the graph being
+ * larger than the view without listing the rest of it.
+ */
+
+import { readFileSync } from "node:fs";
+
+import { firstDescription, type VisibleFile } from "./mcp-exposure.ts";
+
+/** `[[Target]]`, `[[Target|alias]]`, `[[Target#heading]]` — capture the target. */
+const WIKILINK = /\[\[([^\]|#]+)(?:[#|][^\]]*)?\]\]/g;
+
+/** How many suggestions to offer when a seed matches nothing. */
+const NEAR_MISS_LIMIT = 5;
+
+export interface ExpandResult {
+ readonly text: string;
+ /** Null when the seed matched no visible note. */
+ readonly note: VisibleFile | null;
+ readonly outbound: string[];
+ readonly inbound: string[];
+ /** Outbound links that exist but point outside the caller's scope. */
+ readonly hiddenOutbound: number;
+}
+
+/**
+ * Normalise any way a caller might refer to a note into one comparable key.
+ *
+ * OBSERVED FAILURE, and the reason this is not just `toLowerCase()`: `search`
+ * returns the index's paths, which flatten spaces to dashes, and the model fed
+ * those straight into a resource read that only accepted its own URI form. Both
+ * reads failed. Two namespaces for the same notes means a search hit cannot be
+ * followed into a read, which defeats the point of exposing both surfaces.
+ *
+ * So: accept a URI, an index path, a repo-relative path or a bare title, and
+ * compare with separators, case, and word punctuation normalised away.
+ */
+export function normalizeKey(s: unknown): string {
+ let decoded = String(s ?? "");
+ try {
+ decoded = decodeURIComponent(decoded);
+ } catch {
+ /* a stray % is not a reason to fail the lookup */
+ }
+ const tail = decoded
+ .replace(/^vault:\/\/(?:note\/)?/, "")
+ .replace(/\.md$/i, "")
+ .split(/[\\/]/)
+ .pop();
+ return (tail ?? "").toLowerCase().replace(/[\s_-]+/g, "");
+}
+
+/**
+ * Resolve a caller-supplied reference to exactly one visible note.
+ *
+ * Ambiguity returns null rather than guessing. Two notes that normalise to the
+ * same key are a real possibility across folders, and picking one silently
+ * would hand back the wrong note's content with no signal that it happened.
+ */
+export function resolveVisible(files: readonly VisibleFile[], uriOrPath: unknown): VisibleFile | null {
+ const key = normalizeKey(uriOrPath);
+ if (!key) return null;
+ const matches = files.filter((f) => normalizeKey(f.label) === key);
+ return matches.length === 1 ? (matches[0] ?? null) : null;
+}
+
+/** Every wikilink target in a body, de-duplicated, in first-seen order. */
+export function outboundLinks(body: string): string[] {
+ const seen = new Set<string>();
+ const out: string[] = [];
+ for (const m of String(body).matchAll(WIKILINK)) {
+ const target = (m[1] ?? "").trim();
+ if (!target) continue;
+ const key = target.toLowerCase();
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push(target);
+ }
+ return out;
+}
+
+function read(path: string): string {
+ try {
+ return readFileSync(path, "utf8");
+ } catch {
+ return "";
+ }
+}
+
+/**
+ * Expand a note into its neighbourhood.
+ *
+ * Cost note: computing backlinks reads every visible file, so this is O(n) in
+ * vault size per call. Measured fine at present scale and tracked for an index
+ * (#159) before it is not — but the read is deliberately not cached here,
+ * because a stale graph that looks fresh is worse than a slow one.
+ */
+export function expandNote(files: readonly VisibleFile[], seed: string): ExpandResult {
+ const want = String(seed ?? "")
+ .replace(/\.md$/i, "")
+ .toLowerCase();
+
+ // Candidates are COLLECTED before one is chosen. Using `find` here took the
+ // first match, which silently returned the wrong note whenever two visible
+ // notes shared a basename — exactly what resolveVisible refuses to do, so
+ // the module's own rule was broken by its primary path.
+ const byLabel = files.filter((f) => f.label.toLowerCase() === want);
+ const byPath = files.filter((f) => f.full.toLowerCase().replace(/\\/g, "/").endsWith(`/${want}.md`));
+ const candidates = byLabel.length ? byLabel : byPath;
+
+ if (candidates.length > 1) {
+ // Naming the folders is safe — every candidate is already visible to this
+ // caller — and it is the only way they can disambiguate, since the seed
+ // they have is by definition not specific enough.
+ const where = candidates.map((f) => `${f.scope}/${f.label}`).join("; ");
+ return {
+ text: `"${seed}" matches ${candidates.length} visible notes: ${where}. Pass a path rather than a title to choose one.`,
+ note: null,
+ outbound: [],
+ inbound: [],
+ hiddenOutbound: 0,
+ };
+ }
+
+ const hit = candidates[0] ?? resolveVisible(files, seed);
+
+ if (!hit) {
+ // The near-miss list is built from served notes only, so a suggestion
+ // always points at something the caller can actually open.
+ const near = files
+ .filter((f) => f.label.toLowerCase().includes(want) && want.length > 0)
+ .slice(0, NEAR_MISS_LIMIT)
+ .map((f) => f.label);
+ return {
+ text: `No visible note matches "${seed}".${near.length ? ` Did you mean: ${near.join("; ")}?` : ""}`,
+ note: null,
+ outbound: [],
+ inbound: [],
+ hiddenOutbound: 0,
+ };
+ }
+
+ const outbound = outboundLinks(read(hit.full));
+ const visibleLabels = new Set(files.map((f) => f.label.toLowerCase()));
+
+ const inbound: string[] = [];
+ for (const f of files) {
+ if (f.full === hit.full) continue;
+ for (const m of read(f.full).matchAll(WIKILINK)) {
+ if ((m[1] ?? "").trim().toLowerCase() === hit.label.toLowerCase()) {
+ inbound.push(f.label);
+ break;
+ }
+ }
+ }
+
+ // Split outbound into what can actually be served and what the note links to
+ // but sits outside the served set. Counting the latter tells the caller the
+ // graph continues; naming it would offer a target `expand` cannot follow.
+ const servable = outbound.filter((o) => visibleLabels.has(o.toLowerCase()));
+ const hiddenOutbound = outbound.length - servable.length;
+
+ const text = [
+ `# ${hit.label} (${hit.scope})`,
+ firstDescription(hit.full),
+ "",
+ `## Links out (${servable.length} visible${hiddenOutbound ? `, ${hiddenOutbound} outside your scope` : ""})`,
+ servable.length ? servable.map((s) => `- ${s}`).join("\n") : "- (none visible)",
+ "",
+ `## Linked from (${inbound.length})`,
+ inbound.length ? inbound.map((s) => `- ${s}`).join("\n") : "- (none visible)",
+ ].join("\n");
+
+ return { text, note: hit, outbound: servable, inbound, hiddenOutbound };
+}
diff --git a/.claude/scripts/lib/mcp-memory-bridge.ts b/.claude/scripts/lib/mcp-memory-bridge.ts
new file mode 100644
index 0000000..7916a6b
--- /dev/null
+++ b/.claude/scripts/lib/mcp-memory-bridge.ts
@@ -0,0 +1,240 @@
+/**
+ * The seam between the memory core and the server.
+ *
+ * The core modules (`memory-write`, `memory-recall`, `memory-similarity`,
+ * `memory-supersede`) are pure decisions about content. This file is where those
+ * decisions meet a real vault: which names a link may resolve to, which
+ * platforms the caller belongs to, and how the index reorders what the
+ * visibility rule already allowed.
+ *
+ * Everything here was the site of at least one real defect, and each is called
+ * out where it lives. They share a shape worth stating once: **a lookup scoped
+ * to the wrong thing returns an empty answer, and an empty answer is the one
+ * result this system cannot distinguish from a correct one.**
+ */
+
+import { readFileSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+
+import { listMemoryFiles, parseFrontmatter, facetsOf, type Facets } from "./memory-recall.ts";
+import { qmdRelKey, vaultRelKey, subQueries, type QmdClient } from "./mcp-qmd-client.ts";
+import type { VisibleFile } from "./mcp-exposure.ts";
+
+const HEAD_BYTES = 1200;
+
+export interface MemoryDigest extends Facets {
+ readonly rel: string;
+ readonly full: string;
+ readonly title: string;
+ readonly body: string;
+}
+
+/**
+ * Every name a wikilink could legitimately resolve to.
+ *
+ * An MCP write bypasses the PostToolUse validation hook, so a guarantee the
+ * vault normally enforces has to be re-implemented here: never emit a broken
+ * link. The naive version breaks immediately — a project's note is
+ * `projects/pocket/README.md`, so `[[pocket]]` resolves to nothing unless that
+ * README declares `aliases: [pocket]`. Some vaults' do; a fresh vault's do not,
+ * and the capture would manufacture a broken link every single time.
+ *
+ * Resolvable = a file basename, or any name in a file's frontmatter `aliases:`,
+ * in either the block or the inline form. Same rule the vault's own wikilink
+ * checker applies.
+ */
+export function resolvableNames(files: readonly VisibleFile[]): Set<string> {
+ const names = new Set<string>();
+ for (const f of files) {
+ names.add(f.label.toLowerCase());
+ let head: string;
+ try {
+ head = readFileSync(f.full, "utf8").slice(0, HEAD_BYTES);
+ } catch {
+ continue; // an unreadable file still contributes its basename
+ }
+ const block = head.match(/^aliases:\s*$([\s\S]*?)^(?=\S|---)/m);
+ if (block?.[1]) {
+ for (const line of block[1].split("\n")) {
+ const m = line.match(/^\s*-\s*(.+?)\s*$/);
+ if (m?.[1]) names.add(m[1].replace(/^["']|["']$/g, "").toLowerCase());
+ }
+ }
+ const inline = head.match(/^aliases:\s*\[(.*)\]\s*$/m);
+ if (inline?.[1]) {
+ for (const part of inline[1].split(",")) {
+ const name = part.trim().replace(/^["']|["']$/g, "").toLowerCase();
+ if (name) names.add(name);
+ }
+ }
+ }
+ return names;
+}
+
+/** Load every agent-written memory with its facets, title and body. */
+export function loadMemoryDigests(vaultRoot: string, memoryRoot: string): MemoryDigest[] {
+ const out: MemoryDigest[] = [];
+ for (const f of listMemoryFiles(vaultRoot, memoryRoot)) {
+ let md: string;
+ try {
+ md = readFileSync(f.full, "utf8");
+ } catch {
+ continue;
+ }
+ const fm = parseFrontmatter(md);
+ // Only agent-written memories participate. A human note that wandered in
+ // here is left alone rather than silently governed by these rules.
+ if (fm.source !== "mcp-capture") continue;
+ const title = (md.match(/^#\s+(.+)$/m)?.[1] ?? "").trim();
+ const body = md
+ .replace(/^---[\s\S]*?\r?\n---\r?\n/, "")
+ .replace(/^#\s+.*$/m, "")
+ .trim();
+ out.push({ rel: f.rel, full: f.full, title, body, ...facetsOf(fm) });
+ }
+ return out;
+}
+
+/**
+ * First markdown file in the vault whose basename matches `name`.
+ *
+ * Skips dot-directories, `node_modules` and the memory tree — a memory is never
+ * a project note, and walking it would grow the cost with the store for no
+ * benefit.
+ */
+export function findNoteNamed(vaultRoot: string, name: string, memoryRoot: string): string | null {
+ const want = `${String(name).toLowerCase()}.md`;
+ const stack: string[] = [vaultRoot];
+ while (stack.length) {
+ const dir = stack.pop();
+ if (!dir) break;
+ let entries;
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const e of entries) {
+ if (e.name.startsWith(".")) continue;
+ const full = join(dir, e.name);
+ if (e.isDirectory()) {
+ if (e.name === memoryRoot || e.name === "node_modules") continue;
+ stack.push(full);
+ } else if (e.isFile() && e.name.toLowerCase() === want) {
+ return full;
+ }
+ }
+ }
+ return null;
+}
+
+/**
+ * Which platforms the calling repo belongs to.
+ *
+ * Read from the project's own note rather than from server config, so the answer
+ * lives where a human would naturally maintain it and no vault has to learn a
+ * second place to declare things. A project with no note, or no `platforms:`
+ * key, simply has no platform, and platform-scoped memories will not reach it —
+ * the correct default for "unknown".
+ *
+ * TWO WRONG VERSIONS PRECEDED THIS, both failing the same silent way.
+ *
+ * The first looked in `projects/<caller>/README.md`. That is one vault's shape;
+ * a clean install of this template has no `projects/` folder at all. Config
+ * would not have saved it either — a key that must be set correctly per vault
+ * is the same assumption with extra steps.
+ *
+ * The second matched on note identity but walked the EXPOSED files only. A
+ * vault that keeps its projects in a folder outside `mcp_exposed_roots` (the
+ * default does exactly that) silently returned no platform, so every
+ * platform-scoped memory was withheld. It was caught only because `explain`
+ * printed `platforms=[]`.
+ *
+ * The fix is a boundary correction rather than a wider allowlist: what platform
+ * the CALLER belongs to is a property of the caller, not of what the vault
+ * chooses to expose as readable content. So the search is vault-wide by
+ * FILENAME, exactly one frontmatter key is read from the single matching file,
+ * no note body is opened, and nothing is returned to the caller except its own
+ * platform list.
+ */
+export function callerPlatforms(vaultRoot: string, caller: string | null, memoryRoot: string): string[] {
+ if (!caller) return [];
+ const match = findNoteNamed(vaultRoot, caller.toLowerCase(), memoryRoot);
+ if (!match) return [];
+ try {
+ const v = parseFrontmatter(readFileSync(match, "utf8")).platforms;
+ if (Array.isArray(v)) return v.map(String).filter(Boolean);
+ if (typeof v === "string" && v) return [v];
+ } catch {
+ /* unreadable — treat as no platform */
+ }
+ return [];
+}
+
+/**
+ * Reorder already-visible memories by semantic relevance, through the index.
+ *
+ * RETRIEVE SEMANTICALLY, THEN FILTER BY VISIBILITY — never the reverse.
+ *
+ * The index sees every memory in the vault, including ones scoped to other
+ * projects. Ranking by relevance first and applying the scope rule to the RESULT
+ * keeps one implementation of that rule, so semantic recall returns exactly the
+ * set plain recall would. Handing the index a pre-narrowed corpus would put a
+ * second, subtly different rule in the query layer, and the two would drift.
+ *
+ * Returns null when the index cannot answer, so the caller falls back to lexical
+ * matching. That fallback is the point: qmd is OPTIONAL in this template, and an
+ * unavailable index must degrade recall to "worse ordering", never to "the vault
+ * knows nothing", which is indistinguishable from having no memories at all.
+ */
+export async function semanticMemoryOrder<T extends { full: string }>(
+ client: QmdClient,
+ vaultRoot: string,
+ query: string,
+ visible: readonly T[],
+ limit: number,
+): Promise<T[] | null> {
+ const byKey = new Map(visible.map((m) => [vaultRelKey(vaultRoot, m.full), m]));
+ try {
+ const out = (await client.call("tools/call", {
+ name: "query",
+ arguments: {
+ searches: subQueries(query),
+ intent: `durable lessons relevant to: ${query}`,
+ limit: Math.max(limit * 3, 15),
+ minScore: 0.3,
+ },
+ })) as { structuredContent?: { results?: unknown } } | null;
+
+ const hits = out?.structuredContent?.results;
+ if (!Array.isArray(hits) || hits.length === 0) return null;
+
+ const ordered: T[] = [];
+ const seen = new Set<string>();
+ const placed = new Set<T>();
+ for (const h of hits as { file?: string }[]) {
+ const key = qmdRelKey(h.file);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ const m = byKey.get(key);
+ // Absent from `byKey` means the scope rule already excluded it — it was
+ // written for a different project. Skipped silently, because it is not
+ // a result this caller asked about.
+ if (m) {
+ ordered.push(m);
+ placed.add(m);
+ }
+ }
+ if (!ordered.length) return null;
+
+ // REORDER, never filter. The index ranks what it matched; everything else
+ // the visibility rule allowed follows in its declared order. Returning only
+ // the matches would DROP a visible memory from recall entirely — which is
+ // what happens to one written moments ago, since a fresh note carries no
+ // embedding until the index next embeds. A memory that exists, is in
+ // scope, and cannot be recalled is the false negative this layer is for.
+ return [...ordered, ...visible.filter((m) => !placed.has(m))];
+ } catch {
+ return null;
+ }
+}
diff --git a/.claude/scripts/lib/mcp-protocol.ts b/.claude/scripts/lib/mcp-protocol.ts
new file mode 100644
index 0000000..4828f0b
--- /dev/null
+++ b/.claude/scripts/lib/mcp-protocol.ts
@@ -0,0 +1,232 @@
+/**
+ * JSON-RPC framing and the caller-identity handshake.
+ *
+ * Hand-rolled, newline-delimited, zero dependencies — matching this template's
+ * no-dependency script convention. The protocol surface used here is small
+ * enough that a dependency would be more risk than the code it replaces.
+ *
+ * THE PART THAT IS NOT BOILERPLATE
+ *
+ * A server can ask the CLIENT which directories the calling session is working
+ * in (`roots/list`). That is what turns "any repo can read the vault" into "this
+ * repo sees what belongs to it", and it is derived from the client rather than
+ * declared by the caller, which is what makes it a boundary at all.
+ *
+ * But it is ASYNCHRONOUS, and `resources/list` arrives before it resolves — in
+ * practice, not in theory. Announcing `notifications/resources/list_changed`
+ * afterwards was tried first and the client did not re-fetch, so the listing
+ * stayed unscoped. The deterministic fix is to make scope-dependent requests
+ * WAIT for identity, capped so a client that never answers cannot hang the
+ * server: **something that scopes by caller must not answer before it knows the
+ * caller.**
+ */
+
+import { sanitize, callerProject, type Root } from "./mcp-caller.ts";
+
+/** How long a scope-dependent request waits for identity before proceeding. */
+export const IDENTITY_TIMEOUT_MS = 2_000;
+
+/** Server-initiated request ids start high, so they cannot collide with the client's. */
+const SERVER_ID_BASE = 10_000;
+
+export type Send = (msg: unknown) => void;
+export type Handler = (id: number | string, params: unknown) => unknown | Promise<unknown>;
+export type Handlers = Record<string, Handler>;
+
+export interface JsonRpcMessage {
+ jsonrpc?: string;
+ id?: number | string;
+ method?: string;
+ params?: unknown;
+ result?: unknown;
+ error?: { code?: number; message?: string };
+}
+
+export interface SessionOptions {
+ readonly send: Send;
+ readonly handlers: Handlers;
+ /** Called when identity is established or changes. */
+ readonly onIdentified?: (roots: readonly Root[]) => void;
+ readonly identityTimeoutMs?: number;
+}
+
+/**
+ * One MCP session over one stdio pair.
+ *
+ * A class rather than module state so a test can drive several independently —
+ * the prototype's module-level `callerRoots` made the identity race untestable,
+ * which is precisely why it took a live client to find.
+ */
+export class McpSession {
+ readonly #send: Send;
+ readonly #handlers: Handlers;
+ readonly #onIdentified: ((roots: readonly Root[]) => void) | undefined;
+ readonly #identityTimeoutMs: number;
+
+ #roots: Root[] = [];
+ #rootsRequestId: number | null = null;
+ #nextServerId = SERVER_ID_BASE;
+ #identified = false;
+ #refresh: Promise<void> | null = null;
+ #resolveRefresh: (() => void) | null = null;
+ #resolveIdentity!: () => void;
+ readonly #identityKnown: Promise<void>;
+
+ constructor({ send, handlers, onIdentified, identityTimeoutMs = IDENTITY_TIMEOUT_MS }: SessionOptions) {
+ this.#send = send;
+ this.#handlers = handlers;
+ this.#onIdentified = onIdentified;
+ this.#identityTimeoutMs = identityTimeoutMs;
+ this.#identityKnown = new Promise<void>((res) => {
+ this.#resolveIdentity = res;
+ });
+ }
+
+ get roots(): readonly Root[] {
+ return this.#roots;
+ }
+
+ get identified(): boolean {
+ return this.#identified;
+ }
+
+ get project(): string | null {
+ return callerProject(this.#roots);
+ }
+
+ /**
+ * Await identity, or give up after the cap.
+ *
+ * Resolving on timeout rather than rejecting is deliberate: a client that
+ * never answers `roots/list` gets an anonymous, general-only view, which is
+ * the safe degradation. Hanging would be worse than being unhelpful.
+ */
+ identityReady(): Promise<void> {
+ // A refresh in flight is awaited even though identity is already known:
+ // answering now would answer for whoever the caller USED to be.
+ if (this.#refresh) return this.#bounded(this.#refresh);
+ if (this.#identified) return Promise.resolve();
+ return this.#bounded(this.#identityKnown);
+ }
+
+ /** Await `p`, or give up after the cap. Resolves either way. */
+ #bounded(p: Promise<void>): Promise<void> {
+ return new Promise<void>((res) => {
+ // The timer is deliberately NOT unref'd: it is the only thing keeping
+ // this wait alive, and an unref'd one lets the loop drain with the
+ // promise still pending — the wait never resolves at all. It is cleared
+ // the moment identity arrives, so the normal path costs nothing.
+ const timer = setTimeout(res, this.#identityTimeoutMs);
+ const settle = (): void => {
+ clearTimeout(timer);
+ res();
+ };
+ p.then(settle, settle);
+ });
+ }
+
+ /**
+ * Ask the client who it is.
+ *
+ * A REFRESH (triggered by `notifications/roots/list_changed`) opens a pending
+ * gate. Without it, `identityReady()` returned immediately because identity
+ * was already established, so a tool call arriving between the notification
+ * and the reply was served under the STALE identity — the wrong project, and
+ * therefore the wrong scope. Same class as the original first-listing race,
+ * one step later in the lifecycle.
+ */
+ requestRoots(): void {
+ this.#rootsRequestId = ++this.#nextServerId;
+ if (this.#identified && !this.#refresh) {
+ this.#refresh = new Promise<void>((res) => {
+ this.#resolveRefresh = res;
+ });
+ }
+ this.#send({ jsonrpc: "2.0", id: this.#rootsRequestId, method: "roots/list" });
+ }
+
+ ok(id: number | string, result: unknown): void {
+ this.#send({ jsonrpc: "2.0", id, result });
+ }
+
+ /**
+ * Error text crosses into the CALLING session, which may paste it into a
+ * commit or an issue, so local paths are stripped at this single boundary.
+ */
+ fail(id: number | string, message: unknown, code = -32603): void {
+ this.#send({ jsonrpc: "2.0", id, error: { code, message: sanitize(message) } });
+ }
+
+ /**
+ * Handle one line of input.
+ *
+ * Malformed input is IGNORED rather than answered with an error: a line that
+ * does not parse has no id to reply to, and inventing one would put a message
+ * on the wire the client never asked for.
+ */
+ async handleLine(line: string): Promise<void> {
+ const t = String(line ?? "").trim();
+ if (!t) return;
+
+ let msg: JsonRpcMessage;
+ try {
+ msg = JSON.parse(t) as JsonRpcMessage;
+ } catch {
+ return;
+ }
+ if (msg === null || typeof msg !== "object") return;
+
+ // Handshake complete → ask who is calling. This is a server→client
+ // request, so its reply arrives back through this same loop.
+ if (msg.method === "notifications/initialized") {
+ this.requestRoots();
+ return;
+ }
+
+ // A response to something WE asked: no method, and an id we issued.
+ if (msg.id !== undefined && msg.method === undefined) {
+ if (msg.id === this.#rootsRequestId) this.#acceptRoots(msg);
+ return;
+ }
+
+ // The client may tell us the roots changed mid-session; re-ask.
+ if (msg.method === "notifications/roots/list_changed") {
+ this.requestRoots();
+ return;
+ }
+
+ if (msg.id === undefined) return; // any other notification
+
+ const handler = msg.method ? this.#handlers[msg.method] : undefined;
+ if (!handler) {
+ this.fail(msg.id, `no method ${msg.method}`, -32601);
+ return;
+ }
+ try {
+ await handler(msg.id, msg.params);
+ } catch (e) {
+ this.fail(msg.id, e instanceof Error ? e.message : String(e));
+ }
+ }
+
+ #acceptRoots(msg: JsonRpcMessage): void {
+ const before = this.project;
+ const result = msg.result as { roots?: unknown } | undefined;
+ this.#roots = Array.isArray(result?.roots) ? (result.roots as Root[]) : [];
+ this.#identified = true;
+ this.#resolveIdentity();
+ // Close the refresh gate: the new roots are in hand.
+ this.#resolveRefresh?.();
+ this.#refresh = null;
+ this.#resolveRefresh = null;
+ this.#onIdentified?.(this.#roots);
+
+ // Belt-and-braces for clients that DO re-fetch on this notification.
+ // Claude Code did not in testing, which is why the identity WAIT above is
+ // the actual mechanism and this is only a courtesy.
+ const after = this.project;
+ if (after && after !== before) {
+ this.#send({ jsonrpc: "2.0", method: "notifications/resources/list_changed" });
+ }
+ }
+}
diff --git a/.claude/scripts/lib/mcp-qmd-client.ts b/.claude/scripts/lib/mcp-qmd-client.ts
new file mode 100644
index 0000000..f7f1db5
--- /dev/null
+++ b/.claude/scripts/lib/mcp-qmd-client.ts
@@ -0,0 +1,330 @@
+/**
+ * Tier 1 — search, served by acting as an MCP CLIENT of the vault's own qmd
+ * server.
+ *
+ * The index covers the whole vault, including memories and any folder outside
+ * the exposed roots. Results are matched against the served set AFTER
+ * retrieval, so one place decides what comes back.
+ *
+ * That ordering is load-bearing. Filtering the QUERY would require every caller
+ * to construct a scoped query correctly; filtering the RESULT means no query a
+ * caller can write returns more than the policy serves.
+ *
+ * The spawn and the filter are deliberately separated: the filter is pure, so
+ * its behaviour is provable without starting a process.
+ */
+
+import { spawn, type ChildProcess } from "node:child_process";
+import { join } from "node:path";
+
+/** One hit as qmd reports it in `structuredContent.results`. */
+export interface QmdHit {
+ readonly file?: string;
+ readonly line?: number;
+ readonly score?: number;
+ readonly title?: string;
+ readonly snippet?: string;
+}
+
+export interface ScopedResult {
+ readonly text: string;
+ /** How many hits the policy removed. Surfaced for the audit log. */
+ readonly withheld: number;
+ /** How many qmd returned before filtering. */
+ readonly total: number;
+}
+
+// ---------------------------------------------------------------------------
+// Path identity — the comparison the filter depends on
+// ---------------------------------------------------------------------------
+
+/**
+ * Normalise a path for comparison.
+ *
+ * Spaces collapse to hyphens because qmd does the same when it indexes, so
+ * `brain/Key Decisions.md` and `brain/Key-Decisions.md` are the same document
+ * and must compare equal. Case folds because Windows.
+ */
+export function pathKey(s: unknown): string {
+ return String(s ?? "")
+ .replace(/\\/g, "/")
+ .replace(/\s+/g, "-")
+ .toLowerCase();
+}
+
+/**
+ * A file's identity relative to the vault root.
+ *
+ * Matching is on the FULL relative path, never the basename: two notes sharing
+ * a filename in different folders would otherwise alias, and one of them being
+ * in scope would admit the other.
+ */
+export function vaultRelKey(vaultRoot: string, fullPath: string): string {
+ const v = pathKey(vaultRoot).replace(/\/+$/, "");
+ const p = pathKey(fullPath);
+ return p.startsWith(v) ? p.slice(v.length).replace(/^\/+/, "") : p;
+}
+
+/** A word that marks a query as a question rather than a set of keywords. */
+const QUESTION_SHAPED = /\b(why|how|what|when|where|which|who|should|can|does|did|is|are|was)\b|\?/i;
+
+export interface SubQuery {
+ readonly type: "lex" | "vec" | "hyde";
+ readonly query: string;
+}
+
+/**
+ * Build the typed sub-queries for one search.
+ *
+ * `lex` and `vec` always go out together: keywords find the exact term, vectors
+ * find the note that answers the question without using the word.
+ *
+ * `hyde` is added only for question-shaped queries. It writes a hypothetical
+ * answer and matches against that, which is what helps when someone asks "why
+ * did we decide X" and the note is titled something else entirely. It is not
+ * free — it runs a local generation model — so a two-word keyword lookup, where
+ * lexical matching is already the right tool, does not pay for it.
+ */
+export function subQueries(query: string): SubQuery[] {
+ const q = String(query).trim();
+ const subs: SubQuery[] = [
+ { type: "lex", query: q },
+ { type: "vec", query: q },
+ ];
+ if (q.split(/\s+/).length >= 4 && QUESTION_SHAPED.test(q)) subs.push({ type: "hyde", query: q });
+ return subs;
+}
+
+/** qmd paths are collection-prefixed: `myvault/brain/Foo.md` → `brain/foo.md`. */
+export function qmdRelKey(qmdPath: unknown): string {
+ const p = pathKey(qmdPath);
+ const i = p.indexOf("/");
+ return i >= 0 ? p.slice(i + 1) : p;
+}
+
+// ---------------------------------------------------------------------------
+// The filter — pure, and the reason this file is split
+// ---------------------------------------------------------------------------
+
+const SNIPPET_MAX = 700;
+const RESPONSE_MAX = 6000;
+
+/**
+ * Filter and render qmd's results against the set of paths this vault serves.
+ *
+ * `allowed` is a set of vault-relative keys produced by `vaultRelKey`. A hit
+ * whose key is not in it is dropped and counted — counted, because a silent
+ * drop is indistinguishable from an empty index, and the caller needs to tell
+ * "nothing matched" apart from "nothing in scope".
+ */
+export function scopeResults(
+ structured: unknown,
+ allowed: ReadonlySet<string>,
+ limit = 5,
+): ScopedResult {
+ // No structured results means no per-hit paths to filter on. qmd's
+ // human-readable summary carries note paths too, so returning that instead
+ // would hand back results nothing ever matched against the policy.
+ if (!Array.isArray(structured)) {
+ return { text: "(search unavailable: results could not be scope-checked)", withheld: 0, total: 0 };
+ }
+
+ const hitsAll = structured as QmdHit[];
+ const permitted = hitsAll.filter((h) => allowed.has(qmdRelKey(h.file)));
+ const withheld = hitsAll.length - permitted.length;
+ const hits = permitted.slice(0, Math.max(0, limit));
+
+ if (!hits.length) {
+ return {
+ text: withheld
+ ? `(no results visible to this repo; ${withheld} match(es) withheld as out of scope)`
+ : "(no results)",
+ withheld,
+ total: hitsAll.length,
+ };
+ }
+
+ // `context` is dropped: qmd repeats an identical vault-level blurb on every
+ // hit, and it was the single biggest consumer of the response budget.
+ const body = hits
+ .map((h, i) => {
+ const snippet = String(h.snippet ?? "")
+ .replace(/\s+/g, " ")
+ .trim()
+ .slice(0, SNIPPET_MAX);
+ const where = `${h.file}${h.line ? `:${h.line}` : ""}`;
+ const score = Math.round((h.score ?? 0) * 100);
+ return `[${i + 1}] ${where} (score ${score}%)\n ${h.title ?? ""}\n ${snippet}`;
+ })
+ .join("\n\n")
+ .slice(0, RESPONSE_MAX);
+
+ const tail = withheld ? `\n\n(${withheld} further match(es) withheld: outside this repo's scope)` : "";
+ return { text: body + tail, withheld, total: hitsAll.length };
+}
+
+// ---------------------------------------------------------------------------
+// The client — impure
+// ---------------------------------------------------------------------------
+
+const CALL_TIMEOUT_MS = 45_000;
+
+interface Pending {
+ resolve: (v: unknown) => void;
+ reject: (e: Error) => void;
+ timer: NodeJS.Timeout;
+}
+
+export interface QmdClient {
+ call(method: string, params?: unknown): Promise<unknown>;
+ readonly ready: Promise<void>;
+ dispose(): void;
+ /**
+ * False once the child has exited or failed to start. The caller must not
+ * keep using a dead client: a memoised one would make a single qmd crash
+ * disable search for the whole life of the server.
+ */
+ readonly alive: boolean;
+}
+
+/**
+ * Spawn the vault's own qmd launcher and speak MCP to it.
+ *
+ * Reusing the launcher rather than invoking qmd directly inherits two fixes for
+ * free: the Windows `.cmd` shim workaround, and the named-index pin. Locating it
+ * rather than hardcoding the path matters because #71 is actively moving hook
+ * scripts, and a stale path here kills search silently.
+ */
+export function createQmdClient(vaultRoot: string, launcherPath: string | null): QmdClient {
+ const launcher = launcherPath ?? join(vaultRoot, ".claude", "scripts", "qmd-mcp.mjs");
+ const child: ChildProcess = spawn(process.execPath, [launcher], {
+ stdio: ["pipe", "pipe", "ignore"],
+ env: { ...process.env, CLAUDE_PROJECT_DIR: vaultRoot },
+ });
+
+ const pending = new Map<number, Pending>();
+ let alive = true;
+ let rpcId = 0;
+ let buf = "";
+
+ child.stdout?.on("data", (d: Buffer | string) => {
+ buf += String(d);
+ let nl: number;
+ while ((nl = buf.indexOf("\n")) >= 0) {
+ const line = buf.slice(0, nl).trim();
+ buf = buf.slice(nl + 1);
+ if (!line) continue;
+ let msg: { id?: number; error?: { message?: string }; result?: unknown };
+ try {
+ msg = JSON.parse(line) as typeof msg;
+ } catch {
+ continue;
+ }
+ if (typeof msg.id !== "number") continue;
+ const p = pending.get(msg.id);
+ if (!p) continue;
+ pending.delete(msg.id);
+ clearTimeout(p.timer);
+ if (msg.error) p.reject(new Error(msg.error.message ?? "qmd error"));
+ else p.resolve(msg.result);
+ }
+ });
+
+ // A launcher that dies (qmd not installed, bad path) must fail every waiting
+ // call rather than leaving them to time out one by one 45 seconds apart.
+ const failAll = (reason: string): void => {
+ alive = false;
+ for (const [id, p] of pending) {
+ pending.delete(id);
+ clearTimeout(p.timer);
+ p.reject(new Error(reason));
+ }
+ };
+ child.on("error", (e) => failAll(`qmd launcher failed: ${e.message}`));
+ child.on("exit", () => failAll("qmd launcher exited"));
+
+ const call = (method: string, params?: unknown): Promise<unknown> =>
+ new Promise((resolve, reject) => {
+ // A call made AFTER the child died would otherwise sit in `pending`
+ // forever: failAll has already run, so nothing will ever reject it, and
+ // the timeout timer is unref'd. Callers that skip `await ready` — the
+ // semantic-ordering path does — would block until the 45s timeout.
+ if (!alive) {
+ reject(new Error(`qmd unavailable (${method})`));
+ return;
+ }
+ const id = ++rpcId;
+ const timer = setTimeout(() => {
+ if (pending.delete(id)) reject(new Error(`qmd timeout on ${method}`));
+ }, CALL_TIMEOUT_MS);
+ // Node keeps the process alive for a pending timer; this one must not
+ // hold the server open on its own.
+ timer.unref?.();
+ pending.set(id, { resolve, reject, timer });
+ child.stdin?.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
+ });
+
+ const ready = call("initialize", {
+ protocolVersion: "2025-11-25",
+ capabilities: {},
+ clientInfo: { name: "om", version: "0.1.0" },
+ }).then(() => {
+ child.stdin?.write(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }) + "\n");
+ });
+
+ // `ready` rejects if the child dies during the handshake. Attaching a handler
+ // here keeps that from surfacing as an UNHANDLED rejection, which Node treats
+ // as fatal — so a qmd that failed to start would take the whole MCP server
+ // down with it, when the correct behaviour is search degrading on its own.
+ // Anyone who awaits `ready` still sees the rejection.
+ ready.catch(() => {});
+
+ return {
+ call,
+ ready,
+ get alive() {
+ return alive;
+ },
+ dispose: () => {
+ failAll("qmd client disposed");
+ child.kill();
+ },
+ };
+}
+
+/**
+ * Run a hybrid search and return only what this caller may see.
+ *
+ * Both a lexical and a vector sub-query go out: keyword matching finds the exact
+ * term, embeddings find the note that answers the question without using the
+ * word. Sending one and not the other is how a search that "works" still misses
+ * the note the user was thinking of.
+ */
+export async function qmdSearch(
+ client: QmdClient,
+ allowed: ReadonlySet<string>,
+ query: string,
+ limit = 5,
+): Promise<ScopedResult> {
+ try {
+ await client.ready;
+ const out = (await client.call("tools/call", {
+ name: "query",
+ arguments: {
+ searches: subQueries(query),
+ intent: query,
+ // Over-fetch: the filter is applied to the RESULT, so asking for
+ // exactly `limit` means a vault with much unexposed content returns
+ // far fewer than requested with no sign that more existed.
+ limit: Math.max(limit * 4, 20),
+ minScore: 0.4,
+ },
+ })) as { structuredContent?: { results?: unknown } } | null;
+ return scopeResults(out?.structuredContent?.results, allowed, limit);
+ } catch (e) {
+ // qmd is optional in this template. A failure degrades this ONE call and
+ // says so; it must never present as "the vault is empty".
+ const message = e instanceof Error ? e.message : String(e);
+ return { text: `search failed: ${message}`, withheld: 0, total: 0 };
+ }
+}
diff --git a/.claude/scripts/lib/mcp-server.ts b/.claude/scripts/lib/mcp-server.ts
new file mode 100644
index 0000000..3fb6392
--- /dev/null
+++ b/.claude/scripts/lib/mcp-server.ts
@@ -0,0 +1,456 @@
+/**
+ * The wiring: MCP methods to vault behaviour.
+ *
+ * Kept out of the entry script so the whole surface can be driven in-process by
+ * a test — the prototype's handlers were bound to module state and stdio, which
+ * meant every behavioural claim needed a live client to check, and two bugs
+ * survived precisely because checking was expensive.
+ *
+ * The consistent rule here: a tool that depends on WHO is calling waits for
+ * identity first. Anything that answers before the roots handshake completes is
+ * answering for an anonymous caller, and quietly returns the wrong scope rather
+ * than an error.
+ */
+
+import { readFileSync } from "node:fs";
+import { spawn, spawnSync } from "node:child_process";
+
+import type { VaultContext } from "./mcp-context.ts";
+import { INSTRUCTIONS, PROMPTS } from "./mcp-context.ts";
+import type { McpSession, Handlers } from "./mcp-protocol.ts";
+import {
+ type ExposurePolicy,
+ visibleFiles,
+ allowedSearchPaths,
+ listResources,
+ resolveResourceUri,
+} from "./mcp-exposure.ts";
+import { expandNote } from "./mcp-graph.ts";
+import { qmdSearch, type QmdClient } from "./mcp-qmd-client.ts";
+import { callerProject, callerProjectSource, isVaultItself, PROJECT_MARKER } from "./mcp-caller.ts";
+import { callerPlatforms, loadMemoryDigests, resolvableNames } from "./mcp-memory-bridge.ts";
+import { captureNote } from "./mcp-capture.ts";
+import { semanticMemoryOrder } from "./mcp-memory-bridge.ts";
+import { TOOLS } from "./mcp-tools.ts";
+import { recall, type MemoryEntry } from "./memory-recall.ts";
+import { validateMemory, writeMemory, renderMemory, resolveLinks, neutralizeWikilinks } from "./memory-write.ts";
+import { findSimilar } from "./memory-similarity.ts";
+import { markSuperseded, resolveSupersedes } from "./memory-supersede.ts";
+import { health } from "./memory-discover.ts";
+import { resolveQmdEntry, buildQmdCommand } from "./qmd.ts";
+
+const PROTOCOL_VERSION = "2025-11-25";
+const SERVER_NAME = "om";
+const SERVER_VERSION = "0.1.0";
+const DEFAULT_RECALL_LIMIT = 20;
+const REINDEX_TIMEOUT_MS = 20_000;
+
+export interface ServerDeps {
+ readonly ctx: VaultContext;
+ readonly policy: ExposurePolicy;
+ readonly session: McpSession;
+ /** Lazily created, because a vault with no qmd must still serve everything else. */
+ readonly qmd: () => QmdClient;
+ readonly audit: (action: string, detail?: Record<string, unknown>) => void;
+ readonly reindex?: () => boolean;
+ readonly now?: () => Date;
+}
+
+const text = (s: string): { content: { type: "text"; text: string }[] } => ({
+ content: [{ type: "text", text: s }],
+});
+
+/**
+ * Re-index after a write.
+ *
+ * The vault normally re-indexes from a PostToolUse hook, but an MCP write is not
+ * a Claude Code tool call, so no hook fires — without this a note sits on disk
+ * and cannot be found, which is worse than no note because it looks like the
+ * system worked.
+ *
+ * Split by what each step guarantees: `update` decides whether the note is
+ * retrievable at all and is synchronous and bounded; `embed` only decides where
+ * it ranks and is detached, because it runs a local model.
+ */
+export function reindexSync(indexName: string | null): boolean {
+ const run = (sub: string): boolean => {
+ try {
+ const entry = resolveQmdEntry();
+ const args = indexName ? ["--index", indexName, sub] : [sub];
+ const { cmd, args: argv, shell } = buildQmdCommand(entry, args);
+ const r = spawnSync(cmd, [...argv], { shell, timeout: REINDEX_TIMEOUT_MS, stdio: "ignore" });
+ return r.status === 0;
+ } catch {
+ return false;
+ }
+ };
+
+ // `update` indexes the text and is what makes the note retrievable at all, so
+ // it is synchronous: reporting "recorded" before that is a lie the caller
+ // cannot detect.
+ const indexed = run("update");
+ if (!indexed) return false;
+
+ // `embed` builds the vector and is DETACHED, because it affects only where a
+ // memory RANKS, never whether it is found — recall appends everything the
+ // index did not match in declared order, and a new memory sorts to the front
+ // of that group. Waiting on a local model run for ordering that corrects
+ // itself moments later buys nothing: measured, it was most of the write.
+ try {
+ const entry = resolveQmdEntry();
+ const args = indexName ? ["--index", indexName, "embed"] : ["embed"];
+ const { cmd, args: argv, shell } = buildQmdCommand(entry, args);
+ spawn(cmd, [...argv], { shell, detached: true, stdio: "ignore" }).unref();
+ } catch {
+ /* ranking quality is best-effort; retrieval already works without it */
+ }
+ return true;
+}
+
+export function createHandlers(deps: ServerDeps): Handlers {
+ const { ctx, policy, session, qmd, audit } = deps;
+ const now = deps.now ?? (() => new Date());
+ const reindex = deps.reindex ?? (() => reindexSync(ctx.qmdIndex));
+
+ /** Who is asking, as the memory layer understands it. */
+ const caller = () => ({
+ project: callerProject(session.roots),
+ platforms: callerPlatforms(ctx.vaultRoot, callerProject(session.roots), ctx.memoryRoot),
+ });
+
+ // -----------------------------------------------------------------------
+ // Tools
+ // -----------------------------------------------------------------------
+
+ async function callSearch(args: Record<string, unknown>): Promise<string> {
+ const query = String(args.query ?? "");
+ if (!query.trim()) return "(search needs a query)";
+ const limit = Number(args.limit ?? 5);
+ const allowed = allowedSearchPaths(ctx.vaultRoot, policy);
+ const r = await qmdSearch(qmd(), allowed, query, limit);
+ audit("search", { query, withheld: r.withheld, total: r.total, bytes: r.text.length });
+ return r.text;
+ }
+
+ function callExpand(args: Record<string, unknown>): string {
+ const seed = String(args.note ?? "");
+ const r = expandNote(visibleFiles(ctx.vaultRoot, policy), seed);
+ audit("expand", { note: seed, found: r.note !== null, hidden: r.hiddenOutbound });
+ return r.text;
+ }
+
+ async function callRecall(args: Record<string, unknown>): Promise<string> {
+ const who = caller();
+ const limit = Number(args.limit ?? DEFAULT_RECALL_LIMIT);
+ const explain = args.explain === true;
+ const query = String(args.query ?? "").trim();
+
+ const result = explain
+ ? recall(ctx.vaultRoot, who, { root: ctx.memoryRoot, explain: true })
+ : { visible: recall(ctx.vaultRoot, who, { root: ctx.memoryRoot }), withheld: [] as MemoryEntry[] };
+
+ let visible = result.visible;
+
+ // Semantic ordering, applied to what visibility ALREADY allowed. A null
+ // result means the index could not help, so the declared order stands —
+ // worse ordering, never "the vault knows nothing".
+ if (query && visible.length > 1) {
+ const ordered = await semanticMemoryOrder(qmd(), ctx.vaultRoot, query, visible, limit);
+ if (ordered) visible = ordered;
+ else {
+ // Lexical fallback: match against title AND body, per token. An
+ // earlier version tested the whole query as one substring, which
+ // found nothing whenever the caller phrased it as a question.
+ const terms = query.toLowerCase().split(/\W+/).filter(Boolean);
+ const scored = visible
+ .map((m) => {
+ const hay = `${m.title ?? ""} ${m.body}`.toLowerCase();
+ return { m, hits: terms.filter((t) => hay.includes(t)).length };
+ })
+ .filter((x) => x.hits > 0)
+ .sort((a, b) => b.hits - a.hits);
+ if (scored.length) visible = scored.map((x) => x.m);
+ }
+
+ // Relevance decides the order WITHIN each group, but a superseded
+ // memory never outranks a live one. Reordering by relevance alone puts
+ // a corrected-away fact above the correction that replaced it, which is
+ // the one thing supersession exists to prevent.
+ const live = visible.filter((m) => m.facets.superseded_by.length === 0);
+ const retired = visible.filter((m) => m.facets.superseded_by.length > 0);
+ visible = [...live, ...retired];
+ }
+
+ const shown = visible.slice(0, Math.max(0, limit));
+ audit("recall", { query: query || null, returned: shown.length, project: who.project });
+
+ if (!shown.length) {
+ const why = who.project
+ ? `No memories are scoped to reach "${who.project}".`
+ : "This session has no identity (no MCP roots), so only general-scope memories are visible — and there are none.";
+ return `${why} Call health if you expected something here.`;
+ }
+
+ const lines = shown.map((m) => {
+ const facets = [
+ m.facets.confidence,
+ m.facets.projects.length ? `projects: ${m.facets.projects.join(", ")}` : null,
+ m.facets.platforms.length ? `platforms: ${m.facets.platforms.join(", ")}` : null,
+ m.facets.date ? `as of ${m.facets.date}` : null,
+ m.facets.superseded_by.length ? `SUPERSEDED by ${m.facets.superseded_by.join("; ")}` : null,
+ m.why ? `why: ${m.why}` : null,
+ ].filter(Boolean);
+ // Body headings are demoted so the only `##` lines in the response are
+ // entry titles. A memory body legitimately contains its own `## How
+ // this is known`, and rendered at the same level it reads as a separate
+ // memory titled that — the reader cannot tell where one entry ends.
+ const body = m.body.replace(/^(#{1,4})\s/gm, (_, h: string) => `${"#".repeat(Math.min(h.length + 3, 6))} `);
+ return `## ${m.title ?? "(untitled)"}\n${m.rel}\n(${facets.join(" · ")})\n\n${body}`;
+ });
+
+ if (explain && result.withheld.length) {
+ // Counts and reasons only. Naming a withheld memory would put another
+ // project's material into this caller's context — the noise the scope
+ // rule exists to remove.
+ lines.push(
+ `\n---\n${result.withheld.length} memor${result.withheld.length === 1 ? "y" : "ies"} withheld. ` +
+ `Reasons: ${[...new Set(result.withheld.map((w) => w.why ?? "out of scope"))].join("; ")}`,
+ );
+ }
+ return lines.join("\n\n---\n\n");
+ }
+
+ function callRemember(args: Record<string, unknown>): string {
+ // The vault does not write to its own memory layer. A session inside the
+ // vault already reads every note directly, and a memory written there
+ // would be scoped to the vault-as-a-project — reaching only sessions that
+ // by definition did not need it. Write-only by construction.
+ if (isVaultItself(ctx.vaultRoot, session.roots)) {
+ return [
+ "Refused: this session is running inside the vault itself.",
+ "",
+ "Memories exist so a session that CANNOT see the vault can reach its knowledge.",
+ "A memory recorded from here would be scoped to the vault as a project and would",
+ "reach only sessions that already read every note directly. Write the note into",
+ "the vault normally instead — the vault's own hooks will file and link it.",
+ ].join("\n");
+ }
+
+ const who = caller();
+ const resolvable = resolvableNames(visibleFiles(ctx.vaultRoot, policy));
+
+ // Neutralise dangling wikilinks in the TITLE and BODY before validation, so
+ // what is checked is what will be written. An agent in another repo writing
+ // `[[Some Note]]` would otherwise turn the vault's own wikilink gate red.
+ // The title matters as much as the body and was missed first time round:
+ // it becomes the H1 *and* the filename, so a dangling link there is both a
+ // broken edge and a file called `... [[Ghost Link]].md`.
+ const titleLinks = neutralizeWikilinks((args as { title?: unknown }).title, resolvable);
+ const bodyLinks = neutralizeWikilinks((args as { body?: unknown }).body, resolvable);
+ const unlinked = [...new Set([...titleLinks.dropped, ...bodyLinks.dropped])];
+ const v = validateMemory(
+ { ...args, title: titleLinks.text, body: bodyLinks.text },
+ { now: now(), origin: who.project },
+ );
+ if (!v.ok || !v.value) {
+ return `Refused:\n${v.errors.map((e) => `- ${e}`).join("\n")}`;
+ }
+
+ const digests = loadMemoryDigests(ctx.vaultRoot, ctx.memoryRoot);
+
+ // Near-duplicate suppression, facet-gated so two projects can each hold
+ // their own copy of the same lesson.
+ if (args.force !== true) {
+ const { duplicates } = findSimilar(v.value, digests);
+ if (duplicates.length) {
+ const d = duplicates[0]!;
+ return [
+ `Not recorded: a near-identical memory already exists (${Math.round(d.score * 100)}% similar).`,
+ ` ${d.entry.title}`,
+ ` ${d.entry.rel}`,
+ "",
+ "If this genuinely differs, pass force: true. If it CORRECTS that memory,",
+ "pass supersedes: [\"<its exact title>\"] instead — the old one is kept and back-linked.",
+ ].join("\n");
+ }
+ }
+
+ const { resolved, dropped } = resolveLinks(args.links, resolvable);
+ const supers = resolveSupersedes(args.supersedes, digests);
+
+ if (args.dry_run === true) {
+ return [
+ "Preview (nothing written):",
+ "",
+ renderMemory(v.value, resolved),
+ ...(dropped.length ? ["", `Links dropped as unresolvable: ${dropped.join(", ")}`] : []),
+ ...(unlinked.length ? [`Dangling wikilinks were unlinked: ${unlinked.join(", ")}`] : []),
+ ...(supers.unmatched.length ? [`Supersedes not matched: ${supers.unmatched.join(", ")}`] : []),
+ ...(v.warnings.length ? ["", "Warnings:", ...v.warnings.map((w) => `- ${w}`)] : []),
+ ].join("\n");
+ }
+
+ const written = writeMemory(ctx.vaultRoot, v.value, resolved, { root: ctx.memoryRoot });
+
+ const retired: string[] = [];
+ for (const m of supers.matched) {
+ if (markSuperseded(ctx.vaultRoot, m.rel, v.value.title).ok) retired.push(m.title);
+ }
+
+ const indexed = reindex();
+ audit("remember", { rel: written.rel, scope: v.value.scope, projects: v.value.projects, indexed });
+
+ return [
+ `Recorded: ${written.rel}`,
+ `Scope: ${v.value.scope}${v.value.projects.length ? ` → ${v.value.projects.join(", ")}` : ""}`,
+ ...(retired.length ? [`Superseded: ${retired.join("; ")} (kept and back-linked)`] : []),
+ ...(supers.unmatched.length ? [`Supersedes NOT matched: ${supers.unmatched.join(", ")}`] : []),
+ ...(dropped.length ? [`Links dropped as unresolvable: ${dropped.join(", ")}`] : []),
+ ...(unlinked.length ? [`Dangling wikilinks were unlinked: ${unlinked.join(", ")}`] : []),
+ ...(v.warnings.length ? ["", "Warnings:", ...v.warnings.map((w) => `- ${w}`)] : []),
+ ...(indexed ? [] : ["", "NOTE: the search index could not be refreshed, so this memory may not be findable by query yet."]),
+ ].join("\n");
+ }
+
+ function callRecordWork(args: Record<string, unknown>): string {
+ const who = callerProject(session.roots);
+ const resolvable = resolvableNames(visibleFiles(ctx.vaultRoot, policy));
+ let r;
+ try {
+ r = captureNote(ctx.vaultRoot, policy, ctx.manifest, who, args, resolvable, {
+ now: now(),
+ reindex,
+ });
+ } catch (e) {
+ // A refusal is the expected outcome for a bad folder, so it is reported
+ // as a message rather than thrown — the caller can correct and retry,
+ // which a protocol-level error makes harder.
+ return `Not recorded: ${e instanceof Error ? e.message : String(e)}`;
+ }
+
+ if (!r.written) {
+ return [`Preview (nothing written) → ${r.path}`, `Routing: ${r.routed}`, "", r.preview ?? ""].join("\n");
+ }
+ audit("record_work", { path: r.path, routed: r.routed, indexed: r.indexed });
+ return [
+ `Recorded: ${r.path}`,
+ `Routing: ${r.routed}`,
+ ...(r.indexed === false
+ ? ["", "NOTE: the search index could not be refreshed, so this note may not be findable by query yet."]
+ : []),
+ ].join("\n");
+ }
+
+ function callHealth(): string {
+ const who = caller();
+ const names = new Set(visibleFiles(ctx.vaultRoot, policy).map((f) => f.label));
+ if (who.project) names.add(who.project);
+ const h = health(ctx.vaultRoot, ctx.manifest, {
+ knownNames: names,
+ indexName: ctx.qmdIndex,
+ home: process.env.HOME ?? process.env.USERPROFILE ?? null,
+ });
+
+ return [
+ `Vault: ${ctx.vaultRoot}`,
+ ...(ctx.overriddenFrom
+ ? [
+ ` ⚠ OM_VAULT_PATH points here instead of ${ctx.overriddenFrom}, where this server's launcher lives.`,
+ " If that is not deliberate, unset it — everything below describes the OTHER vault.",
+ ]
+ : []),
+ `Caller: ${who.project ?? "ANONYMOUS (no MCP roots — only general-scope memories are visible)"}${who.project ? ` (from the ${callerProjectSource(session.roots) === "declared" ? PROJECT_MARKER + " file" : "folder name"})` : ""}`,
+ ...(who.project && callerProjectSource(session.roots) === "folder"
+ ? [` Another repo with this folder name would share this identity. Write a distinct name into ${PROJECT_MARKER} to separate them.`]
+ : []),
+ `Platforms: ${who.platforms.length ? who.platforms.join(", ") : "(none declared)"}`,
+ `Memory root: ${h.memory.root}/ (${h.memory.memories} memor${h.memory.memories === 1 ? "y" : "ies"}, ${h.memory.source})`,
+ `Exposed roots: ${policy.roots.join(", ") || "(none)"} [${policy.source}]`,
+ `Search index: ${ctx.qmdIndex ?? "(qmd default)"} · launcher ${ctx.qmdLauncher ? "found" : "NOT FOUND"}`,
+ "",
+ h.warnings.length ? `Warnings:\n${h.warnings.map((w) => `- ${w}`).join("\n")}` : "No warnings.",
+ ...(h.notes.length ? ["", `Notes:\n${h.notes.map((n) => `- ${n}`).join("\n")}`] : []),
+ ].join("\n");
+ }
+
+ // -----------------------------------------------------------------------
+ // Dispatch
+ // -----------------------------------------------------------------------
+
+ return {
+ initialize: (id, params) =>
+ session.ok(id, {
+ protocolVersion: (params as { protocolVersion?: string } | undefined)?.protocolVersion ?? PROTOCOL_VERSION,
+ // listChanged on resources is load-bearing: the scoped list cannot be
+ // computed until roots/list comes back, which is after the client's
+ // first resources/list.
+ capabilities: { tools: {}, resources: { listChanged: true }, prompts: {} },
+ serverInfo: { name: SERVER_NAME, version: SERVER_VERSION },
+ instructions: INSTRUCTIONS,
+ }),
+
+ ping: (id) => session.ok(id, {}),
+
+ "tools/list": (id) => session.ok(id, { tools: TOOLS }),
+
+ "tools/call": async (id, params) => {
+ // Every tool below is scope-dependent. Answering before identity
+ // resolves silently serves the anonymous view.
+ await session.identityReady();
+ const p = (params ?? {}) as { name?: string; arguments?: Record<string, unknown> };
+ const args = p.arguments ?? {};
+ switch (p.name) {
+ case "search":
+ return session.ok(id, text(await callSearch(args)));
+ case "expand":
+ return session.ok(id, text(callExpand(args)));
+ case "recall":
+ return session.ok(id, text(await callRecall(args)));
+ case "remember":
+ return session.ok(id, text(callRemember(args)));
+ case "record_work":
+ return session.ok(id, text(callRecordWork(args)));
+ case "health":
+ return session.ok(id, text(callHealth()));
+ default:
+ return session.fail(id, `unknown tool ${p.name}`, -32602);
+ }
+ },
+
+ "resources/list": async (id) => {
+ await session.identityReady();
+ session.ok(id, { resources: listResources(ctx.vaultRoot, policy) });
+ },
+
+ "resources/read": async (id, params) => {
+ await session.identityReady();
+ const uri = String((params as { uri?: unknown } | undefined)?.uri ?? "");
+ const full = resolveResourceUri(ctx.vaultRoot, policy, uri);
+ if (!full) {
+ // Not-found rather than forbidden: to this server, a URI outside
+ // the served set is simply not a resource it has.
+ audit("resource_denied", { uri });
+ return session.fail(id, `no such resource: ${uri}`, -32602);
+ }
+ audit("resource_read", { uri });
+ session.ok(id, { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(full, "utf8") }] });
+ },
+
+ "prompts/list": (id) => session.ok(id, { prompts: PROMPTS }),
+
+ "prompts/get": (id, params) => {
+ const p = (params ?? {}) as { name?: string; arguments?: Record<string, unknown> };
+ const prompt = PROMPTS.find((x) => x.name === p.name);
+ if (!prompt) return session.fail(id, `no prompt ${p.name}`, -32602);
+ const arg = String(p.arguments?.[prompt.arguments[0]!.name] ?? "");
+ const instruction =
+ prompt.name === "prior_art"
+ ? `Search the vault for prior decisions bearing on: "${arg}". Use the search tool, then recall. Report what was already decided, cite note paths, and say plainly if nothing was found rather than inferring an answer.`
+ : `Search the vault for what is already known about: "${arg}". Use the search tool, then expand from the most relevant note. Summarise with citations, preserving any (TBC)/(inferred) markers and "as of" dates you find.`;
+ session.ok(id, {
+ description: prompt.description,
+ messages: [{ role: "user", content: { type: "text", text: instruction } }],
+ });
+ },
+ };
+}
diff --git a/.claude/scripts/lib/mcp-tools.ts b/.claude/scripts/lib/mcp-tools.ts
new file mode 100644
index 0000000..33f7b8f
--- /dev/null
+++ b/.claude/scripts/lib/mcp-tools.ts
@@ -0,0 +1,244 @@
+/**
+ * Tool declarations.
+ *
+ * These descriptions are not documentation — they are the ONLY thing the model
+ * reads when deciding whether to call a tool, so they are written as
+ * instructions to that decision rather than as summaries of behaviour. Two
+ * measured lessons shape them:
+ *
+ * 1. A tool is skipped whenever a nearer source of the answer exists. So each
+ * description says WHEN to reach for it, not merely what it does.
+ * 2. `remember` and `record_work` are constantly confused, and a store filling
+ * with "what I did today" is worse than an empty one. The distinction is
+ * stated as a TEST the model can apply ("would this help someone on a
+ * different project?") rather than as a definition.
+ *
+ * `annotations` let a client pick a tool without trial-and-error and let a
+ * permission layer auto-approve the read-only ones. Omitting them was an
+ * oversight in the first prototype.
+ */
+
+export interface ToolDef {
+ readonly name: string;
+ readonly description: string;
+ readonly inputSchema: Record<string, unknown>;
+ readonly annotations: {
+ readonly title: string;
+ readonly readOnlyHint: boolean;
+ readonly destructiveHint: boolean;
+ readonly idempotentHint: boolean;
+ readonly openWorldHint: boolean;
+ };
+}
+
+const READ_ONLY = {
+ readOnlyHint: true,
+ destructiveHint: false,
+ idempotentHint: true,
+ openWorldHint: false,
+} as const;
+
+export const TOOLS: readonly ToolDef[] = [
+ {
+ name: "search",
+ description:
+ "Semantic + keyword search over the user's personal knowledge vault. Returns ranked passages with note paths. Fast and free — prefer this over asking the user to recall something.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ query: { type: "string", description: "What to look for" },
+ limit: { type: "number", description: "Max results (default 5)" },
+ },
+ required: ["query"],
+ },
+ annotations: { title: "Search the personal vault", ...READ_ONLY },
+ },
+ {
+ name: "expand",
+ description:
+ "Given a note you already know, show what it links to and what links back to it. Use this instead of searching again when you have a specific note and want its neighbourhood.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ note: { type: "string", description: "Note title, path or vault:// URI" },
+ },
+ required: ["note"],
+ },
+ annotations: { title: "Expand a note's graph neighbourhood", ...READ_ONLY },
+ },
+ {
+ name: "recall",
+ description:
+ "Retrieve the durable lessons this repo is allowed to see, most specific first. Call this BEFORE making a decision you might already have made once — the vault is where the last session left its reasoning. Returns only memories scoped to reach you; another project's memories are withheld by design.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ query: {
+ type: "string",
+ description:
+ "Optional filter. Omit to see everything in scope, which is usually what you want at the start of a task.",
+ },
+ limit: { type: "number", description: "Max memories to return (default 20)." },
+ explain: {
+ type: "boolean",
+ description:
+ "Also report what was withheld and why. Use when a memory you expected is missing — it will tell you whether it was scoped away or never existed.",
+ },
+ },
+ },
+ annotations: { title: "Recall durable lessons", ...READ_ONLY },
+ },
+ {
+ name: "record_work",
+ description:
+ "Record work that happened in this repo into the vault, filed where it belongs. This is a durable record, not a scratch note — write it for a future session that will NOT have your context and cannot re-read your diff. Fill every field you can; sparse records are near-worthless six weeks later. Use dry_run to preview the filed note first.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ title: { type: "string", description: "Short, specific. 'Add archive command' not 'update'." },
+ summary: {
+ type: "string",
+ description:
+ "2-4 sentences: what happened and why it was done. Enough for someone to decide whether to read on.",
+ },
+ changes: {
+ type: "array",
+ items: { type: "string" },
+ description:
+ "One line per file or component touched, saying what changed and why. e.g. 'src/store.mjs - added pure archive(db,id); marks a flag rather than removing, so seq is untouched'.",
+ },
+ decisions: {
+ type: "array",
+ items: { type: "string" },
+ description:
+ "Choices made and the reasoning, especially where you rejected an alternative. These are the entries most likely to matter later.",
+ },
+ learned: {
+ type: "array",
+ items: { type: "string" },
+ description:
+ "Surprises, gotchas, things that cost time or nearly went wrong. What you wish you had known starting out.",
+ },
+ verification: {
+ type: "string",
+ description:
+ "How you know it works: tests run and their result, manual checks performed. State failures honestly.",
+ },
+ open: {
+ type: "array",
+ items: { type: "string" },
+ description:
+ "Unresolved threads, deferred work, known limits. Anything a reader should not assume is handled.",
+ },
+ informed_by: {
+ type: "array",
+ items: { type: "string" },
+ description:
+ "Vault notes you read that shaped this work, by title. Rendered as links, so those notes accumulate evidence they were actually used.",
+ },
+ folder: {
+ type: "string",
+ description:
+ "Vault-relative destination, e.g. 'projects/pocket/notes'. Omit to file it under the calling repo's project automatically. Search the vault first if unsure where similar notes live.",
+ },
+ kind: {
+ type: "string",
+ enum: ["note", "decision"],
+ description:
+ "'decision' files it as a decision record with an undated title; 'note' is a dated point-in-time record. Default 'note'.",
+ },
+ dry_run: { type: "boolean", description: "Preview without writing (default false)" },
+ },
+ required: ["title", "summary"],
+ },
+ annotations: {
+ title: "Record work into the vault",
+ readOnlyHint: false,
+ // Creates a new note; never edits or deletes an existing one.
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: false,
+ },
+ },
+ {
+ name: "remember",
+ description:
+ "Record a DURABLE LESSON into the vault's memory — something that will still be true, and still useful, in a repo that is not this one. The test: would this help someone working on a different project? If yes, remember it. If it is a log of what you did here today, use record_work instead. Good memories: a constraint you discovered, a gotcha that cost you time, a rule that generalises. Bad memories: status updates, task summaries, anything you would not want to be told again in six weeks.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ title: {
+ type: "string",
+ description:
+ "The lesson itself, stated as a claim. 'tsup externals decide what a patch can fix', not 'patch notes'. This is what a future session will match against.",
+ },
+ body: {
+ type: "string",
+ description:
+ "The lesson in full, written for someone with none of your context: what is true, why, and what it means for what they are about to do. State mechanisms, not narrative.",
+ },
+ confidence: {
+ type: "string",
+ enum: ["verified", "inferred", "unverified"],
+ description:
+ "'verified' = you checked it against the code, a doc, or a run. 'inferred' = you reasoned to it. 'unverified' = you were told or assumed it. Be honest; this is what a reader trusts.",
+ },
+ verification: {
+ type: "string",
+ description: "How you know. Required in spirit whenever confidence is 'verified'.",
+ },
+ scope: {
+ type: "string",
+ enum: ["general", "platform", "project"],
+ description:
+ "How far this reaches. 'project' = only projects you name. 'platform' = anything on the same platform. 'general' = everywhere, and it will be narrowed if you name projects.",
+ },
+ projects: {
+ type: "array",
+ items: { type: "string" },
+ description:
+ "Every project this applies to — a LIST, so a lesson spanning two projects reaches both. Omit for a platform or general lesson.",
+ },
+ platforms: {
+ type: "array",
+ items: { type: "string" },
+ description: "Platforms this applies to, e.g. ['ios']. Used with scope 'platform'.",
+ },
+ links: {
+ type: "array",
+ items: { type: "string" },
+ description:
+ "Vault notes this relates to, by title. Unresolvable ones are dropped and reported rather than written as broken links.",
+ },
+ supersedes: {
+ type: "array",
+ items: { type: "string" },
+ description:
+ "Exact titles of memories this CORRECTS. They are kept and back-linked, not deleted, and this one will outrank them. Use when you have learned that something recorded earlier is wrong.",
+ },
+ force: {
+ type: "boolean",
+ description:
+ "Write even if a near-identical memory already exists. Default false — you will be told what it collided with.",
+ },
+ dry_run: { type: "boolean", description: "Preview without writing (default false)." },
+ },
+ required: ["title", "body", "confidence"],
+ },
+ annotations: {
+ title: "Remember a durable lesson",
+ readOnlyHint: false,
+ destructiveHint: false,
+ idempotentHint: false,
+ openWorldHint: false,
+ },
+ },
+ {
+ name: "health",
+ description:
+ "Check that this vault's wiring is intact: where memories actually live, which roots are exposed, whether the search index is reachable, and whether any memories reference a project that no longer resolves. Call this when something that should be in the vault cannot be found — every failure in this layer presents identically as 'no results', and this is what tells them apart.",
+ inputSchema: { type: "object", properties: {} },
+ annotations: { title: "Check vault wiring", ...READ_ONLY },
+ },
+];
+
diff --git a/.claude/scripts/lib/memory-discover.ts b/.claude/scripts/lib/memory-discover.ts
new file mode 100644
index 0000000..69470a4
--- /dev/null
+++ b/.claude/scripts/lib/memory-discover.ts
@@ -0,0 +1,446 @@
+/**
+ * Discovery and self-healing for the vault memory layer.
+ *
+ * THE PROBLEM THIS SOLVES
+ *
+ * Every hardcoded path and every config key in this layer is a promise the user
+ * can break without knowing. They rename `memories/` in Obsidian; they
+ * reorganise `brain/`; they move the vault folder; the template moves its own
+ * scripts. Nothing errors — the server simply stops finding things, and
+ * "returns nothing" is indistinguishable from "there is nothing", which is the
+ * failure mode that cost the most time building this layer.
+ *
+ * So: DERIVE, don't declare. Config becomes an override for the rare case where
+ * derivation is wrong, not the mechanism everything depends on. Where a value
+ * genuinely cannot be derived, it gets reported by `health()` rather than
+ * failing quietly.
+ *
+ * Modelled on this template's qmd bootstrap: detect current state, repair what
+ * can be repaired, migrate from a legacy shape, stay idempotent, and say out
+ * loud when it healed something.
+ */
+
+import { readFileSync, readdirSync, statSync, existsSync } from "node:fs";
+import { normalizePath } from "./mcp-caller.ts";
+import { join, relative, sep } from "node:path";
+
+/** Directories never worth walking, in any vault. */
+const SKIP = new Set([".git", ".obsidian", ".shardmind", "node_modules", ".claude", ".codex", ".gemini"]);
+
+/** How deep a memory tree can nest before we stop believing it is one. */
+const MAX_DEPTH = 4;
+
+export interface SplitRoot {
+ readonly root: string;
+ readonly memories: number;
+}
+
+export interface MemoryRootInfo {
+ readonly root: string;
+ readonly source: "configured" | "discovered";
+ readonly memories: number;
+ /** True when the notes disagree with config — the rename case. */
+ readonly healed: boolean;
+ readonly configured: string;
+ /** Non-null when captures are spread across more than one folder. */
+ readonly split: SplitRoot[] | null;
+}
+
+export interface ExposedRootsInfo {
+ readonly roots: string[];
+ readonly source: "manifest" | "fallback";
+}
+
+export interface QmdLauncherInfo {
+ readonly path: string | null;
+ readonly source: "expected" | "discovered" | "absent";
+}
+
+export interface OrphanedProject {
+ readonly project: string;
+ readonly memories: number;
+}
+
+export interface IndexPathInfo {
+ readonly state: "unknown" | "registered" | "malformed" | "unregistered";
+ readonly path: string | null;
+}
+
+export interface HealthReport {
+ readonly memory: MemoryRootInfo;
+ readonly exposed: ExposedRootsInfo;
+ readonly qmd: QmdLauncherInfo;
+ readonly orphans: OrphanedProject[];
+ readonly warnings: string[];
+ readonly notes: string[];
+ readonly ok: boolean;
+}
+
+type Manifest = Record<string, unknown> | null | undefined;
+
+/**
+ * Walk markdown files, bounded. Shared by every discovery below so a vault is
+ * traversed at most once per concern rather than once per question.
+ */
+export function walkMarkdown(root: string, { maxDepth = MAX_DEPTH }: { maxDepth?: number } = {}): string[] {
+ const out: string[] = [];
+ const stack: { dir: string; depth: number }[] = [{ dir: root, depth: 0 }];
+ while (stack.length) {
+ const item = stack.pop();
+ if (!item) break;
+ const { dir, depth } = item;
+ let entries;
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const e of entries) {
+ if (e.name.startsWith(".") || SKIP.has(e.name)) continue;
+ const full = join(dir, e.name);
+ if (e.isDirectory()) {
+ if (depth < maxDepth) stack.push({ dir: full, depth: depth + 1 });
+ } else if (e.isFile() && e.name.toLowerCase().endsWith(".md")) {
+ out.push(full);
+ }
+ }
+ }
+ return out;
+}
+
+/** Cheap frontmatter probe — reads only the head of a file. */
+export function probeFrontmatter(full: string, bytes = 800): string | null {
+ try {
+ const head = readFileSync(full, "utf8").slice(0, bytes);
+ const m = head.match(/^---\r?\n([\s\S]*?)\r?\n---/);
+ return m ? (m[1] ?? null) : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Where do memories actually live?
+ *
+ * Config is consulted first, but is NOT trusted blindly: a `memory_root`
+ * pointing at a folder the user has since renamed would send new captures to a
+ * fresh empty directory while the real ones sit unreachable — the store
+ * silently forking in two.
+ *
+ * The authority is the notes themselves. `source: mcp-capture` is written by
+ * this layer on every memory, so the folder containing the most of them IS the
+ * memory root, whatever it has been renamed to. Only when none exist anywhere
+ * does the configured (or default) value stand — the empty-vault case, where
+ * there is nothing to be wrong about yet.
+ */
+export function discoverMemoryRoot(vaultRoot: string, configured = "memories"): MemoryRootInfo {
+ const counts = new Map<string, number>();
+ for (const full of walkMarkdown(vaultRoot)) {
+ const fm = probeFrontmatter(full);
+ if (!fm || !/^source:\s*["']?mcp-capture["']?\s*$/m.test(fm)) continue;
+ const rel = relative(vaultRoot, full).split(sep);
+ if (rel.length < 2) continue;
+ const top = rel[0];
+ if (!top) continue;
+ counts.set(top, (counts.get(top) ?? 0) + 1);
+ }
+
+ if (counts.size === 0) {
+ return {
+ root: configured,
+ source: "configured",
+ memories: 0,
+ healed: false,
+ configured,
+ split: null,
+ };
+ }
+
+ let bestRoot = "";
+ let bestCount = -1;
+ for (const [root, n] of counts) {
+ if (n > bestCount) {
+ bestRoot = root;
+ bestCount = n;
+ }
+ }
+
+ return {
+ root: bestRoot,
+ source: bestRoot === configured ? "configured" : "discovered",
+ memories: bestCount,
+ // A discovered root that disagrees with config is the rename case. The
+ // layer follows the notes, and says so — silently following either one is
+ // how a store forks.
+ healed: bestRoot !== configured,
+ configured,
+ // More than one folder holding captures means an incomplete move. Worth
+ // naming, because retrieval will only ever see the larger half.
+ split: counts.size > 1 ? [...counts.entries()].map(([r, c]) => ({ root: r, memories: c })) : null,
+ };
+}
+
+/**
+ * Which top-level folders hold user content?
+ *
+ * Derived from the manifest's own `user_content_roots`, which this template and
+ * its derivatives already maintain for other purposes — so there is no new key
+ * to keep correct, and a vault that reorganises updates one list it was already
+ * updating.
+ *
+ * An earlier default of `["brain", "projects", "strategy", "reference"]` was one
+ * specific vault's shape: a clean install has no `projects/` and no `strategy/`
+ * at all, so resources came back empty and nothing said why.
+ */
+export function discoverExposedRoots(
+ vaultRoot: string,
+ manifest: Manifest,
+ fallback: string[] = ["brain", "reference"],
+): ExposedRootsInfo {
+ const declared = Array.isArray(manifest?.user_content_roots) ? manifest.user_content_roots : [];
+ const tops = new Set<string>();
+ for (const entry of declared) {
+ const top = String(entry)
+ .replace(/^[./]+/, "")
+ .split(/[/\\]/)[0];
+ // Globs like `perf/h*-*/` contribute their literal first segment; a
+ // leading-glob entry contributes nothing rather than everything.
+ if (top && !top.includes("*")) tops.add(top);
+ }
+ const existing = [...tops].filter((t) => {
+ try {
+ return statSync(join(vaultRoot, t)).isDirectory();
+ } catch {
+ return false;
+ }
+ });
+ if (existing.length) return { roots: existing, source: "manifest" };
+
+ const present = fallback.filter((t) => existsSync(join(vaultRoot, t)));
+ return { roots: present.length ? present : fallback, source: "fallback" };
+}
+
+/**
+ * Locate the vault's qmd MCP launcher.
+ *
+ * Hardcoding `.claude/scripts/qmd-mcp.mjs` bets on a layout the template itself
+ * is actively trying to change (#71 moves hook scripts). Searching for it by
+ * name costs one bounded walk at startup and survives the move.
+ *
+ * Returns null when absent, which is a legitimate state — qmd is optional, and
+ * the caller degrades to lexical rather than failing.
+ */
+export function discoverQmdLauncher(vaultRoot: string): QmdLauncherInfo {
+ const preferred = join(vaultRoot, ".claude", "scripts", "qmd-mcp.mjs");
+ if (existsSync(preferred)) return { path: preferred, source: "expected" };
+
+ const stack: { dir: string; depth: number }[] = [{ dir: vaultRoot, depth: 0 }];
+ while (stack.length) {
+ const item = stack.pop();
+ if (!item) break;
+ const { dir, depth } = item;
+ let entries;
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const e of entries) {
+ const full = join(dir, e.name);
+ if (e.isFile() && e.name === "qmd-mcp.mjs") return { path: full, source: "discovered" };
+ // Dotfolders ARE walked here: the launcher legitimately lives inside
+ // one. Only the known-irrelevant ones are skipped.
+ if (e.isDirectory() && depth < 3 && !SKIP.has(e.name) && e.name !== ".git") {
+ stack.push({ dir: full, depth: depth + 1 });
+ }
+ }
+ }
+ return { path: null, source: "absent" };
+}
+
+/**
+ * Memories naming a project that has no note in this vault.
+ *
+ * Deliberately NOT called "orphaned" to the user, and deliberately not an error.
+ * Visibility matches a memory's `projects` against the CALLING REPO's name,
+ * which does not require a note to exist — so a memory scoped to a repo you have
+ * never written a note about still reaches that repo's sessions perfectly well.
+ *
+ * The first version of this reported such memories as reaching nobody. That was
+ * simply false, and a diagnostic that lies is worse than no diagnostic: it sends
+ * you looking for a fault that isn't there. What it is genuinely useful for is
+ * spotting a REPO RENAME — memories still scoped to the old name — which shows
+ * up here as a name nothing else in the vault refers to.
+ *
+ * Reported as information, never auto-fixed: rewriting a user's records on a
+ * guess about their intent is not this layer's call.
+ */
+export function findOrphanedProjects(
+ vaultRoot: string,
+ memoryRoot: string,
+ knownNames: Iterable<string>,
+): OrphanedProject[] {
+ const known = new Set([...knownNames].map((n) => String(n).toLowerCase()));
+ const orphans = new Map<string, number>();
+ const base = join(vaultRoot, memoryRoot);
+ if (!existsSync(base)) return [];
+ for (const full of walkMarkdown(base)) {
+ const fm = probeFrontmatter(full, 1200);
+ if (!fm) continue;
+ const m = fm.match(/^projects:\s*\[(.*)\]\s*$/m);
+ if (!m) continue;
+ for (const raw of (m[1] ?? "").split(",")) {
+ const name = raw.trim().replace(/^["']|["']$/g, "");
+ if (!name) continue;
+ if (known.has(name.toLowerCase())) continue;
+ orphans.set(name, (orphans.get(name) ?? 0) + 1);
+ }
+ }
+ return [...orphans.entries()].map(([project, memories]) => ({ project, memories }));
+}
+
+/**
+ * Does this vault's search index actually belong to this vault?
+ *
+ * The failure this catches cost real time to diagnose by hand. A vault whose
+ * `qmd_index` collides with another vault's — a shared literal, or two vaults
+ * that happen to share a folder name — gets a collection registered against
+ * SOMEONE ELSE'S directory. Re-indexing then faithfully updates the wrong tree,
+ * search returns nothing from this vault, and every layer above it reports "no
+ * results".
+ *
+ * Nothing errors anywhere in that chain. It is the same silent shape as every
+ * other defect in this layer, and it is the last one left.
+ *
+ * qmd keeps one YAML per index under the user's config dir, of the shape:
+ *
+ * collections:
+ * <name>:
+ * path: /path/to/some-vault
+ *
+ * Parsed with a line scan rather than a YAML dependency: we read exactly one
+ * key, the file is machine-written, and a malformed read degrades to "unknown"
+ * rather than to a wrong answer.
+ *
+ * `readFile` and `joinPath` are injected so this stays testable without touching
+ * the real user config dir.
+ */
+export function readIndexPath(
+ indexName: string | null | undefined,
+ home: string,
+ readFile: (path: string) => string,
+ joinPath: (...parts: string[]) => string,
+): IndexPathInfo {
+ if (!indexName) return { state: "unknown", path: null };
+ const candidates = [
+ joinPath(home, ".config", "qmd", `${indexName}.yml`),
+ joinPath(home, ".config", "qmd", `${indexName}.yaml`),
+ ];
+ for (const file of candidates) {
+ let text: string;
+ try {
+ text = readFile(file);
+ } catch {
+ continue;
+ }
+ // First `path:` under the collections block. One key, one scan.
+ const m = text.match(/^\s*path:\s*(.+?)\s*$/m);
+ if (m?.[1]) return { state: "registered", path: m[1].replace(/^["']|["']$/g, "") };
+ return { state: "malformed", path: null };
+ }
+ return { state: "unregistered", path: null };
+}
+
+/** Case- and separator-insensitive path comparison, for Windows and POSIX alike. */
+export function samePath(a: unknown, b: unknown): boolean {
+ return normalizePath(a) === normalizePath(b);
+}
+
+/**
+ * Verdict on the index wiring. Returns a warning string, or null when fine.
+ *
+ * `unregistered` is deliberately NOT a warning: a vault that has never run the
+ * bootstrap is in a normal starting state, and the missing-launcher check
+ * already covers the case where qmd is absent entirely.
+ */
+export function indexOwnershipWarning(
+ indexName: string,
+ vaultRoot: string,
+ info: IndexPathInfo | null | undefined,
+): string | null {
+ if (!info || info.state === "unregistered") return null;
+ if (info.state === "malformed") {
+ return `Search index "${indexName}" has an unreadable config; index health cannot be confirmed.`;
+ }
+ if (info.state !== "registered" || !info.path) return null;
+ if (samePath(info.path, vaultRoot)) return null;
+ return (
+ `Search index "${indexName}" is registered to a DIFFERENT vault (${info.path}). ` +
+ "Re-indexing updates that tree, not this one, so memories and notes here will not be found. " +
+ "Give this vault its own qmd_index in vault-manifest.json, then re-run the qmd bootstrap."
+ );
+}
+
+/**
+ * One call that answers "is this wiring actually intact?".
+ *
+ * Exists because every failure in this layer is silent by nature: a renamed
+ * folder, a moved script, a stale index and an orphaned project all present
+ * identically as "no results". Health turns each of them into a sentence.
+ */
+export function health(
+ vaultRoot: string,
+ manifest: Manifest,
+ {
+ knownNames = [],
+ indexName = null,
+ home = null,
+ }: { knownNames?: Iterable<string>; indexName?: string | null; home?: string | null } = {},
+): HealthReport {
+ const configured = typeof manifest?.memory_root === "string" ? manifest.memory_root : "memories";
+ const mem = discoverMemoryRoot(vaultRoot, configured);
+ const exposed = discoverExposedRoots(vaultRoot, manifest);
+ const qmd = discoverQmdLauncher(vaultRoot);
+ const orphans = findOrphanedProjects(vaultRoot, mem.root, knownNames);
+
+ const warnings: string[] = [];
+ if (mem.healed) {
+ warnings.push(
+ `Memories are in "${mem.root}/" but the manifest says "${mem.configured}". Following the notes; set memory_root to "${mem.root}" to make it explicit.`,
+ );
+ }
+ if (mem.split) {
+ warnings.push(
+ `Captures are split across ${mem.split.map((s) => `${s.root}/ (${s.memories})`).join(" and ")} — retrieval only sees "${mem.root}/". Move the rest.`,
+ );
+ }
+ // An undeclared `mcp_exposed_roots` is not a warning: it means the server
+ // serves the vault's own `user_content_roots`, which is the default and the
+ // state most vaults should be in. Declaring the key narrows that.
+ if (qmd.source === "absent") {
+ warnings.push("qmd launcher not found — search and recall degrade to lexical matching.");
+ }
+ if (qmd.source === "discovered") {
+ warnings.push(`qmd launcher found at an unexpected path (${qmd.path}); the layout moved.`);
+ }
+ // Does the index this vault writes to actually belong to this vault?
+ if (indexName && home) {
+ const info = readIndexPath(
+ indexName,
+ home,
+ (f) => readFileSync(f, "utf8"),
+ (...p) => join(...p),
+ );
+ const w = indexOwnershipWarning(indexName, vaultRoot, info);
+ if (w) warnings.push(w);
+ }
+ // Kept out of `warnings` on purpose: this is not a fault. A repo needs no note
+ // in the vault for its memories to reach it, so surfacing this as a problem
+ // sends the reader hunting for a break that does not exist.
+ const notes = orphans.map(
+ (o) =>
+ `${o.memories} memor${o.memories === 1 ? "y" : "ies"} scoped to "${o.project}", which has no note here. Normal if that repo simply has no note; worth checking if it was renamed.`,
+ );
+
+ return { memory: mem, exposed, qmd, orphans, warnings, notes, ok: warnings.length === 0 };
+}
diff --git a/.claude/scripts/lib/memory-recall.ts b/.claude/scripts/lib/memory-recall.ts
new file mode 100644
index 0000000..e7b714c
--- /dev/null
+++ b/.claude/scripts/lib/memory-recall.ts
@@ -0,0 +1,330 @@
+/**
+ * The vault memory layer — retrieval.
+ *
+ * Deliberately a separate module from the write path. They have different
+ * failure modes: a bad write costs one note, while a bad read puts another
+ * project's context into this session and is acted on as if it applied. Keeping
+ * them apart means the visibility rule can be reasoned about — and hammered —
+ * alone.
+ *
+ * THE PRECISION PROBLEM
+ *
+ * Retrieval has two failure modes pulling in opposite directions:
+ *
+ * false positive — a memory from an unrelated project surfaces. The expensive
+ * one: it is how a session gets "reminded" of a constraint
+ * that does not apply, and how one client's context reaches
+ * another's.
+ * false negative — a memory that would have helped stays hidden. Cheap in
+ * isolation, but it is the entire value proposition; a memory
+ * layer nobody's session ever sees is an expensive no-op.
+ *
+ * The resolution: reach is DECLARED at write time (`scope`) rather than guessed
+ * at read time. A reader never widens what a writer declared.
+ */
+
+import { readFileSync, readdirSync, statSync, existsSync } from "node:fs";
+import { join } from "node:path";
+import { MEMORY_ROOT } from "./memory-write.ts";
+
+export interface Facets {
+ readonly scope: string;
+ readonly projects: string[];
+ readonly platforms: string[];
+ readonly confidence: string;
+ readonly flags: string[];
+ readonly origin: string | null;
+ readonly date: string | null;
+ /** ISO timestamp of the write; breaks ties within a day. */
+ readonly session: string | null;
+ readonly superseded_by: string[];
+ readonly source: string | null;
+}
+
+export interface Caller {
+ readonly project?: string | null;
+ readonly platforms?: readonly string[];
+}
+
+export interface MemoryEntry {
+ readonly rel: string;
+ readonly full: string;
+ readonly facets: Facets;
+ readonly title: string | null;
+ readonly body: string;
+ readonly why?: string;
+}
+
+// ---------------------------------------------------------------------------
+// Frontmatter
+// ---------------------------------------------------------------------------
+
+/**
+ * Parse the subset of YAML this layer writes. Not a general parser on purpose:
+ * we own the writer, so supporting arbitrary YAML would be surface area with no
+ * caller. Anything unrecognised is ignored rather than guessed at.
+ *
+ * Returns `{}` for a file with no frontmatter — such a file is simply not a
+ * memory, and must not throw its way into a retrieval path.
+ */
+export function parseFrontmatter(md: unknown): Record<string, string | string[]> {
+ const m = String(md ?? "").match(/^---\r?\n([\s\S]*?)\r?\n---/);
+ if (!m) return {};
+ const out: Record<string, string | string[]> = {};
+ for (const line of (m[1] ?? "").split(/\r?\n/)) {
+ const kv = line.match(/^([A-Za-z_][\w-]*):\s*(.*)$/);
+ if (!kv) continue;
+ const key = kv[1]!;
+ const raw = (kv[2] ?? "").trim();
+ if (raw === "") continue;
+ if (raw.startsWith("[") && raw.endsWith("]")) {
+ const inner = raw.slice(1, -1).trim();
+ out[key] = inner ? inner.split(",").map((p) => unquote(p.trim())).filter(Boolean) : [];
+ } else {
+ out[key] = unquote(raw);
+ }
+ }
+ return out;
+}
+
+function unquote(s: string): string {
+ const t = String(s).trim();
+ if (t.length >= 2 && t.startsWith('"') && t.endsWith('"')) {
+ try {
+ return JSON.parse(t) as string;
+ } catch {
+ return t.slice(1, -1);
+ }
+ }
+ if (t.length >= 2 && t.startsWith("'") && t.endsWith("'")) return t.slice(1, -1);
+ return t;
+}
+
+/** Normalize a parsed memory's facets so the visibility rule sees one shape. */
+export function facetsOf(fm: Record<string, unknown> | null | undefined): Facets {
+ const list = (v: unknown): string[] =>
+ Array.isArray(v) ? v.filter(Boolean).map(String) : v ? [String(v)] : [];
+ const str = (v: unknown): string | null => (typeof v === "string" ? v : null);
+ return {
+ scope: typeof fm?.scope === "string" ? fm.scope : "project",
+ projects: list(fm?.projects),
+ platforms: list(fm?.platforms),
+ confidence: typeof fm?.confidence === "string" ? fm.confidence : "unverified",
+ flags: list(fm?.flags),
+ origin: str(fm?.origin),
+ date: str(fm?.date),
+ session: str(fm?.session),
+ superseded_by: list(fm?.superseded_by),
+ source: str(fm?.source),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Visibility — the precision rule
+// ---------------------------------------------------------------------------
+
+const eq = (a: unknown, b: unknown): boolean => String(a).toLowerCase() === String(b).toLowerCase();
+const overlaps = (a: readonly string[], b: readonly string[]): boolean =>
+ a.some((x) => b.some((y) => eq(x, y)));
+
+/**
+ * Is this memory visible to this caller? Evaluated in order, and the ORDER is
+ * the design:
+ *
+ * 1. `general` reaches everyone. The only scope that does, which is why
+ * write-side narrowing polices it so hard.
+ * 2. An explicit project listing always wins. If a memory names your project
+ * you see it, regardless of its declared scope — this is what makes the
+ * multi-project case work: `projects: [a, b]` reaches both, and neither has
+ * to know the other exists.
+ * 3. `platform` scope reaches any caller sharing a platform. The "same
+ * platform, different project" case: an iOS lesson learned in one app
+ * should reach the next iOS app and must NOT reach the web one.
+ * 4. Otherwise: not visible. Default deny — a memory with no matching facet
+ * stays put rather than surfacing on a near-miss.
+ *
+ * A caller with no identity (no MCP roots) sees only `general`. That is the
+ * safest reading of "I don't know who you are", and it degrades to useless
+ * rather than to wide-open.
+ */
+export function isVisibleTo(facets: Facets | null | undefined, caller: Caller | null | undefined): boolean {
+ const f = facets;
+ const project = caller?.project ?? null;
+ const platforms = Array.isArray(caller?.platforms) ? caller.platforms : [];
+
+ if (f?.scope === "general") return true;
+ if (project && (f?.projects ?? []).some((p) => eq(p, project))) return true;
+ if (f?.scope === "platform" && overlaps(f?.platforms ?? [], platforms)) return true;
+ return false;
+}
+
+/**
+ * Why a memory was or was not shown.
+ *
+ * Retrieval that cannot explain itself is impossible to debug and impossible to
+ * trust — and every failure in this layer presents identically as "no results".
+ * This string is what tells a renamed folder apart from an empty vault.
+ */
+export function visibilityReason(facets: Facets | null | undefined, caller: Caller | null | undefined): string {
+ const f = facets;
+ const project = caller?.project ?? null;
+ const platforms = Array.isArray(caller?.platforms) ? caller.platforms : [];
+
+ if (f?.scope === "general") return "general scope reaches every caller";
+ if (project && (f?.projects ?? []).some((p) => eq(p, project))) {
+ return `explicitly lists project "${project}"`;
+ }
+ if (f?.scope === "platform" && overlaps(f?.platforms ?? [], platforms)) {
+ return `platform scope overlaps caller platforms [${platforms.join(", ")}]`;
+ }
+ if (!project && platforms.length === 0) {
+ return "caller has no identity; only general memories are visible";
+ }
+ return `no facet matches caller (project="${project}", platforms=[${platforms.join(", ")}])`;
+}
+
+// ---------------------------------------------------------------------------
+// Ranking
+// ---------------------------------------------------------------------------
+
+/**
+ * Specificity first, then recency.
+ *
+ * A memory naming your project is more likely to matter than one that happens to
+ * share a platform, which in turn beats a general one. Ranking by relevance
+ * alone would bury the precise hit under the broad ones exactly when the caller
+ * needs it most.
+ */
+export function specificity(facets: Facets | null | undefined, caller: Caller | null | undefined): number {
+ const project = caller?.project ?? null;
+ if (project && (facets?.projects ?? []).some((p) => eq(p, project))) {
+ // A memory naming ONLY your project is more specific than one naming five.
+ return 100 - Math.min(20, (facets?.projects ?? []).length);
+ }
+ if (facets?.scope === "platform") return 50;
+ if (facets?.scope === "general") return 10;
+ return 0;
+}
+
+/**
+ * Superseded memories sink rather than disappear: the correction is what you
+ * want, but the history is occasionally what you need.
+ */
+export function rankMemories<T extends { facets: Facets }>(entries: readonly T[], caller: Caller): T[] {
+ return [...entries].sort((a, b) => {
+ const supA = a.facets.superseded_by.length > 0 ? 1 : 0;
+ const supB = b.facets.superseded_by.length > 0 ? 1 : 0;
+ if (supA !== supB) return supA - supB;
+ const s = specificity(b.facets, caller) - specificity(a.facets, caller);
+ if (s !== 0) return s;
+ const byDate = String(b.facets.date ?? "").localeCompare(String(a.facets.date ?? ""));
+ if (byDate !== 0) return byDate;
+ // `date` is day-granular, so same-day memories would otherwise sort
+ // arbitrarily and a just-written one could fall outside the caller's limit
+ // entirely. `session` is the ISO timestamp of the write.
+ return String(b.facets.session ?? "").localeCompare(String(a.facets.session ?? ""));
+ });
+}
+
+// ---------------------------------------------------------------------------
+// IO shell
+// ---------------------------------------------------------------------------
+
+/** Walk the memory tree. Shallow by design: `root/YYYY/MM/*.md`, nothing deeper. */
+export function listMemoryFiles(vaultRoot: string, root: string = MEMORY_ROOT): { rel: string; full: string }[] {
+ const base = join(vaultRoot, root);
+ if (!existsSync(base)) return [];
+ const out: { rel: string; full: string }[] = [];
+ for (const year of safeDirs(base)) {
+ for (const month of safeDirs(join(base, year))) {
+ const dir = join(base, year, month);
+ let names: string[];
+ try {
+ names = readdirSync(dir);
+ } catch {
+ continue;
+ }
+ for (const name of names) {
+ if (name.endsWith(".md")) out.push({ rel: `${root}/${year}/${month}/${name}`, full: join(dir, name) });
+ }
+ }
+ }
+ return out;
+}
+
+function safeDirs(dir: string): string[] {
+ try {
+ return readdirSync(dir).filter((n) => {
+ try {
+ return statSync(join(dir, n)).isDirectory();
+ } catch {
+ return false;
+ }
+ });
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * Load every memory visible to this caller, ranked.
+ *
+ * `explain` attaches the visibility reason to each entry AND returns the
+ * withheld ones with theirs — used to prove a memory was excluded deliberately
+ * rather than missed by accident.
+ */
+export function recall(
+ vaultRoot: string,
+ caller: Caller,
+ opts?: { root?: string; explain?: false },
+): MemoryEntry[];
+export function recall(
+ vaultRoot: string,
+ caller: Caller,
+ opts: { root?: string; explain: true },
+): { visible: MemoryEntry[]; withheld: MemoryEntry[] };
+export function recall(
+ vaultRoot: string,
+ caller: Caller,
+ { root = MEMORY_ROOT, explain = false }: { root?: string; explain?: boolean } = {},
+): MemoryEntry[] | { visible: MemoryEntry[]; withheld: MemoryEntry[] } {
+ const visible: MemoryEntry[] = [];
+ const withheld: MemoryEntry[] = [];
+ for (const file of listMemoryFiles(vaultRoot, root)) {
+ let md: string;
+ try {
+ md = readFileSync(file.full, "utf8");
+ } catch {
+ continue; // an unreadable file must not take down retrieval
+ }
+ const fm = parseFrontmatter(md);
+ // Only agent-written memories participate; a human note that wandered in
+ // here is left alone rather than silently governed by these rules.
+ if (fm.source !== "mcp-capture") continue;
+ const facets = facetsOf(fm);
+ // The body travels with the entry. A caller past the visibility rule has
+ // earned the content, and the memory root is not in the resource-exposure
+ // list anyway — so a pointer-only result hands back a path it cannot open.
+ const entry: MemoryEntry = { ...file, facets, title: titleOf(md), body: bodyOf(md) };
+ if (isVisibleTo(facets, caller)) {
+ visible.push(explain ? { ...entry, why: visibilityReason(facets, caller) } : entry);
+ } else if (explain) {
+ withheld.push({ ...entry, why: visibilityReason(facets, caller) });
+ }
+ }
+ const ranked = rankMemories(visible, caller);
+ return explain ? { visible: ranked, withheld } : ranked;
+}
+
+function titleOf(md: string): string | null {
+ const m = md.match(/^#\s+(.+)$/m);
+ return m ? (m[1] ?? "").trim() : null;
+}
+
+/** The note minus its frontmatter and H1 — the part worth carrying. */
+function bodyOf(md: string): string {
+ return md
+ .replace(/^---[\s\S]*?\r?\n---\r?\n/, "")
+ .replace(/^#\s+.*$/m, "")
+ .trim();
+}
diff --git a/.claude/scripts/lib/memory-similarity.ts b/.claude/scripts/lib/memory-similarity.ts
new file mode 100644
index 0000000..d3f8bbf
--- /dev/null
+++ b/.claude/scripts/lib/memory-similarity.ts
@@ -0,0 +1,186 @@
+/**
+ * Near-duplicate detection for the vault memory layer.
+ *
+ * WHY THIS EXISTS
+ *
+ * A memory store without a duplicate guard degrades as it grows, and it degrades
+ * in the worst possible way: silently, and fastest for the lessons that matter
+ * most. The same constraint gets rediscovered every few weeks by a session that
+ * could not find the earlier note, and each rediscovery writes another copy — so
+ * the most important lessons end up the most duplicated, retrieval returns five
+ * near-identical hits, and the reader trusts the store less exactly where it
+ * should trust it more.
+ *
+ * Deliberately lexical, not semantic. An embedding call on every write would
+ * cost latency and money on the hot path, and the failure it prevents is the
+ * *literal* re-record — a session restating a lesson in near-identical words,
+ * not two genuinely different phrasings of one idea. The semantic case is what
+ * retrieval is for; this is a write-time guard against obvious repetition.
+ *
+ * All pure. No IO, no index, no network.
+ */
+
+/** The facets that decide whether two memories can even be compared. */
+export interface Comparable {
+ readonly title: string;
+ readonly body: string;
+ readonly scope?: string;
+ readonly projects?: readonly string[];
+ readonly platforms?: readonly string[];
+}
+
+export interface SimilarHit<T> {
+ readonly entry: T;
+ readonly score: number;
+}
+
+/** Words carrying no discriminating signal in a technical note. */
+const STOP = new Set([
+ "a","an","the","and","or","but","if","then","else","when","while","for","to","of","in","on","at","by","from","with",
+ "is","are","was","were","be","been","being","it","its","this","that","these","those","as","so","not","no","do","does",
+ "did","can","could","will","would","should","may","might","must","have","has","had","you","your","we","our","they",
+ "their","he","she","i","me","my","us","them","there","here","what","which","who","whom","how","why","because","into",
+ "than","too","very","just","also","only","own","same","up","down","out","over","under","again","more","most","some",
+]);
+
+/**
+ * Plural folding, and nothing more.
+ *
+ * Without it "patch" and "patches" are different tokens, which alone drags a
+ * near-verbatim restatement below the duplicate threshold — measured at 0.800
+ * before this was added, where the same pair scores 1.000 after. A full stemmer
+ * would be worse than useless: it collapses distinct technical terms and costs
+ * precision on exactly the identifiers that carry the signal.
+ */
+export function stem(token: string): string {
+ if (token.length > 4 && token.endsWith("ies")) return `${token.slice(0, -3)}y`;
+ if (token.length > 4 && /(?:s|x|z|ch|sh)es$/.test(token)) return token.slice(0, -2);
+ if (token.length > 3 && token.endsWith("s") && !token.endsWith("ss")) {
+ const candidate = token.slice(0, -1);
+ // A stem with no vowel is not a word, it is an acronym or a scheme —
+ // `https` must not fold into `http`, because that is a distinction a
+ // technical note is often written specifically to make.
+ if (/[aeiou]/.test(candidate)) return candidate;
+ }
+ return token;
+}
+
+/**
+ * Normalize text to a comparable token bag.
+ *
+ * Numbers are preserved: two memories differing only in a version number are
+ * NOT duplicates, and that difference is usually the entire point of the second
+ * one. `_` survives the markdown pass because it is part of an identifier far
+ * more often than it is emphasis — splitting `node_modules` into two tokens
+ * throws away the most discriminating word in a technical note.
+ */
+export function tokenize(text: unknown): string[] {
+ return String(text ?? "")
+ .toLowerCase()
+ .replace(/[`*~>#[\]()]/g, " ")
+ .replace(/[^a-z0-9._/-]+/g, " ")
+ .split(/\s+/)
+ .map((t) => t.replace(/^[._/-]+|[._/-]+$/g, ""))
+ .filter((t) => t.length > 1 && !STOP.has(t))
+ .map(stem);
+}
+
+/** Jaccard: shared tokens over total distinct tokens. 0 → disjoint, 1 → identical. */
+export function jaccard(aTokens: readonly string[], bTokens: readonly string[]): number {
+ const a = new Set(aTokens);
+ const b = new Set(bTokens);
+ if (a.size === 0 && b.size === 0) return 1;
+ if (a.size === 0 || b.size === 0) return 0;
+ let shared = 0;
+ for (const t of a) if (b.has(t)) shared++;
+ return shared / (a.size + b.size - shared);
+}
+
+/**
+ * Similarity between two memories, title-weighted.
+ *
+ * The title is where a session states the lesson in its most compressed form, so
+ * two memories with near-identical titles are near-identical memories almost
+ * regardless of how differently the bodies ramble. Body agreement alone is a
+ * weaker signal — two notes about the same subsystem share a lot of vocabulary
+ * without being the same lesson.
+ */
+export function similarity(a: Comparable, b: Comparable): number {
+ const titleScore = jaccard(tokenize(a.title), tokenize(b.title));
+ const bodyScore = jaccard(tokenize(a.body), tokenize(b.body));
+ return 0.6 * titleScore + 0.4 * bodyScore;
+}
+
+/**
+ * Thresholds, chosen from measurement rather than feel.
+ *
+ * Measured against a real memory and five comparison texts:
+ *
+ * near-verbatim restatement 1.000
+ * same lesson, reworded 0.497
+ * adjacent note, same subsystem 0.071
+ * different lesson, same subsystem 0.060
+ * unrelated 0.000
+ *
+ * The gap between a reworded restatement and a merely adjacent note is where
+ * the useful signal lives, so the bands sit either side of it. An earlier guess
+ * put these at 0.82 / 0.45 — the first missed verbatim restatements and the
+ * second could never fire on real text. Both were fixed by measuring.
+ *
+ * `DUPLICATE` stays deliberately high: a false positive here suppresses a real
+ * memory, which is the expensive error.
+ */
+export const DUPLICATE = 0.75;
+
+/**
+ * Possible restatement in different words. Advisory only: the write proceeds,
+ * the caller is told, and a link is proposed. A false positive costs one
+ * suggested link.
+ */
+export const RELATED = 0.35;
+
+/**
+ * Do these two memories reach any of the same readers?
+ *
+ * If they do not they cannot be duplicates in any sense that matters — nobody
+ * will ever see both. This is what stops the guard suppressing a legitimate
+ * per-project copy of the same lesson.
+ */
+export function sharesFacet(a: Comparable, b: Comparable): boolean {
+ const scopeA = a.scope ?? "project";
+ const scopeB = b.scope ?? "project";
+ if (scopeA === "general" || scopeB === "general") return true;
+ const lower = (xs?: readonly string[]): string[] => (xs ?? []).map((x) => String(x).toLowerCase());
+ const pa = lower(a.projects);
+ const pb = lower(b.projects);
+ if (pa.some((p) => pb.includes(p))) return true;
+ const la = lower(a.platforms);
+ const lb = lower(b.platforms);
+ if (scopeA === "platform" && scopeB === "platform" && la.some((p) => lb.includes(p))) return true;
+ return false;
+}
+
+/**
+ * Compare a candidate against existing memories.
+ *
+ * Only memories the candidate could actually collide with are compared. Two
+ * identically-worded notes scoped to different projects are not duplicates:
+ * each project's session needs its own copy, because neither can see the other's.
+ */
+export function findSimilar<T extends Comparable>(
+ candidate: Comparable,
+ existing: readonly T[],
+ { duplicate = DUPLICATE, related = RELATED }: { duplicate?: number; related?: number } = {},
+): { duplicates: SimilarHit<T>[]; related: SimilarHit<T>[] } {
+ const duplicates: SimilarHit<T>[] = [];
+ const relatedTo: SimilarHit<T>[] = [];
+ for (const entry of existing) {
+ if (!sharesFacet(candidate, entry)) continue;
+ const score = similarity(candidate, entry);
+ if (score >= duplicate) duplicates.push({ entry, score });
+ else if (score >= related) relatedTo.push({ entry, score });
+ }
+ duplicates.sort((x, y) => y.score - x.score);
+ relatedTo.sort((x, y) => y.score - x.score);
+ return { duplicates, related: relatedTo };
+}
diff --git a/.claude/scripts/lib/memory-supersede.ts b/.claude/scripts/lib/memory-supersede.ts
new file mode 100644
index 0000000..9d7d43e
--- /dev/null
+++ b/.claude/scripts/lib/memory-supersede.ts
@@ -0,0 +1,154 @@
+/**
+ * Supersession — knowledge that corrects itself.
+ *
+ * WHY THIS MATTERS MORE THAN IT LOOKS
+ *
+ * A flat memory store accumulates contradictions. It learns "X is true", later
+ * learns "X is false", and then holds both with equal authority forever. Every
+ * subsequent retrieval is a coin flip, and the store gets *less* trustworthy the
+ * longer it runs — the opposite of what memory is for.
+ *
+ * Supersession makes a correction first-class: the new memory declares what it
+ * replaces, the old one records that it was replaced, and retrieval ranks the
+ * correction above the thing it corrected. Nothing is deleted, because the
+ * history is occasionally the point ("we used to think X, here is why we
+ * stopped") and because removing a note the user may have linked is not the
+ * server's call.
+ *
+ * THIS MODULE IS THE ONLY PLACE THE SERVER EDITS AN EXISTING FILE.
+ *
+ * Isolated deliberately so that stays auditable. Two rules, enforced here rather
+ * than documented and hoped for:
+ *
+ * 1. It may only touch a note it wrote (`source: mcp-capture`). A human's note
+ * is never modified, whatever it happens to be linked to.
+ * 2. It only ADDS a frontmatter key. Never rewrites a body, removes a key, or
+ * reorders. The blast radius of a bug here is one extra line.
+ */
+
+import { readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+/** The only `source` value this module is permitted to modify. */
+const OWNED_BY_SERVER = "mcp-capture";
+
+export interface FrontmatterEdit {
+ readonly changed: boolean;
+ readonly text: string;
+ readonly reason: string;
+}
+
+export interface SupersedeResult {
+ readonly ok: boolean;
+ readonly changed?: boolean;
+ readonly reason: string;
+}
+
+/** Anything with a title, which is all supersession matching needs. */
+export interface Titled {
+ readonly title?: string | null;
+ readonly rel?: string;
+}
+
+/**
+ * Add or extend a list-valued frontmatter key. Pure.
+ *
+ * Returns the text unchanged when the value is already present, so a repeated
+ * supersession is a no-op rather than a growing list of duplicates.
+ */
+export function addToFrontmatterList(md: string, key: string, value: string): FrontmatterEdit {
+ const m = String(md).match(/^(---\r?\n)([\s\S]*?)(\r?\n---)/);
+ if (!m) return { changed: false, text: md, reason: "no frontmatter block" };
+
+ const open = m[1]!;
+ const block = m[2]!;
+ const close = m[3]!;
+ const lineRe = new RegExp(`^${key}:\\s*(.*)$`, "m");
+ const existing = block.match(lineRe);
+ const quoted = JSON.stringify(String(value));
+
+ let nextBlock: string;
+ if (existing) {
+ const raw = (existing[1] ?? "").trim();
+ if (raw.includes(quoted)) return { changed: false, text: md, reason: "already present" };
+ const inner = raw.startsWith("[") && raw.endsWith("]") ? raw.slice(1, -1).trim() : "";
+ nextBlock = block.replace(lineRe, `${key}: ${inner ? `[${inner}, ${quoted}]` : `[${quoted}]`}`);
+ } else {
+ nextBlock = `${block}\n${key}: [${quoted}]`;
+ }
+
+ return {
+ changed: true,
+ text: md.replace(open + block + close, open + nextBlock + close),
+ reason: existing ? "extended" : "added",
+ };
+}
+
+/** Read a single frontmatter scalar without pulling in the whole parser. */
+function frontmatterScalar(md: string, key: string): string | null {
+ const m = String(md).match(/^---\r?\n([\s\S]*?)\r?\n---/);
+ if (!m) return null;
+ const line = (m[1] ?? "").match(new RegExp(`^${key}:\\s*(.*)$`, "m"));
+ if (!line) return null;
+ const raw = (line[1] ?? "").trim();
+ try {
+ return raw.startsWith('"') ? (JSON.parse(raw) as string) : raw;
+ } catch {
+ return raw;
+ }
+}
+
+/**
+ * Mark an existing memory as superseded by a newer one.
+ *
+ * Refuses — loudly, without writing — on anything it does not own. A refusal is
+ * returned rather than thrown so a capture is never lost because its
+ * housekeeping half failed: the memory still lands, and the caller is told the
+ * back-link could not be written.
+ */
+export function markSuperseded(vaultRoot: string, rel: string, supersedingTitle: string): SupersedeResult {
+ const full = join(vaultRoot, rel);
+ let md: string;
+ try {
+ md = readFileSync(full, "utf8");
+ } catch {
+ return { ok: false, reason: `cannot read ${rel}` };
+ }
+
+ if (frontmatterScalar(md, "source") !== OWNED_BY_SERVER) {
+ return {
+ ok: false,
+ reason: `refusing to modify ${rel}: not an agent-written memory (source is not ${OWNED_BY_SERVER})`,
+ };
+ }
+
+ const result = addToFrontmatterList(md, "superseded_by", supersedingTitle);
+ if (!result.changed) return { ok: true, changed: false, reason: result.reason };
+
+ writeFileSync(full, result.text, "utf8");
+ return { ok: true, changed: true, reason: result.reason };
+}
+
+/**
+ * Resolve the memories a capture claims to supersede.
+ *
+ * Matching is on title, because that is what a calling session actually has —
+ * it saw the title in a recall result. Exact (case-insensitive) only: a fuzzy
+ * match here would let a session retire the wrong memory, which is the one
+ * irreversible-feeling action in this whole layer.
+ */
+export function resolveSupersedes<T extends Titled>(
+ claims: unknown,
+ existing: readonly T[],
+): { matched: T[]; unmatched: string[] } {
+ const matched: T[] = [];
+ const unmatched: string[] = [];
+ for (const claim of Array.isArray(claims) ? claims : []) {
+ const needle = String(claim ?? "").trim().toLowerCase();
+ if (!needle) continue;
+ const hit = existing.find((e) => String(e.title ?? "").trim().toLowerCase() === needle);
+ if (hit) matched.push(hit);
+ else unmatched.push(String(claim));
+ }
+ return { matched, unmatched };
+}
diff --git a/.claude/scripts/lib/memory-write.ts b/.claude/scripts/lib/memory-write.ts
new file mode 100644
index 0000000..b6db3d6
--- /dev/null
+++ b/.claude/scripts/lib/memory-write.ts
@@ -0,0 +1,579 @@
+/**
+ * The vault memory layer — write path.
+ *
+ * Pure functions over plain data, plus one thin IO shell (`writeMemory`), so the
+ * epistemic contract can be hammered by tests without an MCP client, a vault on
+ * disk, or a search index.
+ *
+ * WHY THIS IS SEPARATE FROM A WORK RECORD
+ *
+ * A *work record* ("what I did in this repo today") is single-valued by nature:
+ * it belongs to the project it happened in, and it is a log entry. A *memory*
+ * ("a tsup-external dependency can't be fixed by a local patch") is multi-valued
+ * by nature: it transfers, and its whole worth is that a session in a DIFFERENT
+ * repo can find it. One tool for both would force a single shape on two
+ * artifacts and lose the facets that make the second findable.
+ *
+ * The routing test, stated for the model in the tool description: *would this
+ * help someone working in a different repo?*
+ */
+
+import { mkdirSync, writeFileSync, readFileSync } from "node:fs";
+import { join, dirname, basename } from "node:path";
+import { claimFile } from "./atomic-write.ts";
+
+/** Vault-relative root for every memory. Writes are confined to this prefix. */
+export const MEMORY_ROOT = "memories";
+
+export const SCOPES = ["general", "platform", "project"] as const;
+export const CONFIDENCE = ["verified", "inferred", "unverified"] as const;
+
+export type Scope = (typeof SCOPES)[number];
+export type Confidence = (typeof CONFIDENCE)[number];
+
+/** Filenames truncate here; long titles are still fine as the H1. */
+const SLUG_MAX = 60;
+
+/** A memory shorter than this is not a memory, it is a shrug. */
+const MIN_BODY = 40;
+
+/**
+ * Windows refuses these as filename stems, with or without an extension. A vault
+ * syncing across machines gets a corrupt file rather than an error, so they are
+ * rewritten rather than rejected.
+ */
+const WINDOWS_RESERVED = /^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i;
+
+export interface MemoryInput {
+ readonly title?: unknown;
+ readonly body?: unknown;
+ readonly confidence?: unknown;
+ readonly verification?: unknown;
+ readonly scope?: unknown;
+ readonly projects?: unknown;
+ readonly platforms?: unknown;
+}
+
+export interface MemoryValue {
+ readonly title: string;
+ readonly body: string;
+ readonly confidence: Confidence;
+ readonly claimed_confidence: Confidence | null;
+ readonly flags: string[];
+ readonly verification: string | null;
+ readonly scope: Scope;
+ readonly projects: string[];
+ readonly platforms: string[];
+ readonly downgraded_from: Scope | null;
+ readonly origin: string | null;
+ readonly date: Date;
+}
+
+export interface ValidationResult {
+ readonly ok: boolean;
+ readonly errors: string[];
+ readonly warnings: string[];
+ readonly value: MemoryValue | null;
+}
+
+// ---------------------------------------------------------------------------
+// Slug and path
+// ---------------------------------------------------------------------------
+
+/**
+ * Filename-safe slug. Deliberately strict: the result is concatenated into a
+ * path, so anything that could traverse (`..`), escape (`/`, `\`) or break a
+ * filesystem (control chars, trailing dots) must not survive.
+ */
+export function slugify(title: unknown): string {
+ let out = String(title ?? "")
+ .normalize("NFKD")
+ .replace(/[\u0300-\u036f]/g, "")
+ .replace(/[<>:"|?*\u0000-\u001f]/g, " ")
+ .replace(/[/\\]/g, " ")
+ // Square brackets go too. A title carrying `[[Something]]` otherwise
+ // produces a file literally named `... [[Something]].md`, which reads as a
+ // wikilink embedded in a filename and confuses every surface showing it.
+ .replace(/[[\]]/g, " ")
+ .replace(/\.{2,}/g, " ")
+ .replace(/\s+/g, " ")
+ .trim();
+
+ if (out.length > SLUG_MAX) {
+ out = out.slice(0, SLUG_MAX);
+ const lastSpace = out.lastIndexOf(" ");
+ if (lastSpace > SLUG_MAX * 0.6) out = out.slice(0, lastSpace);
+ out = out.trim();
+ }
+
+ // NTFS silently strips trailing dots and spaces, producing a different file
+ // than the one planned — fold them so path and reality agree.
+ out = out.replace(/[. ]+$/, "");
+ if (WINDOWS_RESERVED.test(out)) out = `_${out}`;
+ return out;
+}
+
+/** `2026-07-26` from a Date, in the vault's local-date convention. */
+export function isoDate(d: Date): string {
+ const pad = (n: number): string => String(n).padStart(2, "0");
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
+}
+
+/**
+ * `memories/2026/07/2026-07-26 <slug>.md`
+ *
+ * Time is the ONLY thing in the path, because time is the only single-valued
+ * fact about a memory. Two levels keeps any folder to a month's worth and the
+ * tree at depth 3 — inside Obsidian's guidance, and matching the daily-note
+ * convention users already recognise.
+ */
+export function memoryPath(date: Date, title: unknown, root: string = MEMORY_ROOT): string {
+ const iso = isoDate(date);
+ const [y, m] = iso.split("-");
+ return `${root}/${y}/${m}/${iso} ${slugify(title)}.md`;
+}
+
+// ---------------------------------------------------------------------------
+// Scope narrowing
+// ---------------------------------------------------------------------------
+
+/**
+ * The caller proposes a scope; the server narrows it. Never widens.
+ *
+ * `general` is the only claim worth policing: widest blast radius, and the
+ * cheapest thing for a session to over-claim. Because `projects` is a LIST, a
+ * caller with a genuinely cross-project lesson can name them all honestly — so
+ * an unjustified `general` is the one remaining way to over-reach, and the
+ * origin repo is the evidence against it.
+ *
+ * The original claim is preserved: a downgrade that hides what was asked for is
+ * a downgrade nobody can audit.
+ */
+export function narrowScope(input: {
+ scope?: unknown;
+ projects?: unknown;
+ origin?: string | null;
+}): { scope: Scope; projects: string[]; downgraded_from: Scope | null } {
+ const claimed: Scope = (SCOPES as readonly string[]).includes(String(input.scope))
+ ? (input.scope as Scope)
+ : "project";
+ const named = Array.isArray(input.projects) ? (input.projects as unknown[]).filter(Boolean).map(String) : [];
+ const origin = input.origin ?? null;
+
+ // `general` is honest only when the memory names no project. If the caller
+ // named projects, it is scoped to them by its own admission.
+ if (claimed === "general" && named.length > 0) {
+ return { scope: "project", projects: named, downgraded_from: "general" };
+ }
+ // `general` naming nothing STANDS.
+ //
+ // An earlier revision narrowed this to the origin repo, reasoning that one
+ // session should not speak for the whole vault. The effect was that `general`
+ // became UNREACHABLE through the server — every caller has an origin, so
+ // every general memory silently became project-scoped to whoever wrote it.
+ // The tier stayed in the reader, the tool schema, the Base view and the docs,
+ // and nothing could ever produce it.
+ //
+ // It also contradicted the rule immediately above: general is honest exactly
+ // WHEN no project is named, and this narrowed precisely that case. Declared
+ // reach is the design; silently overriding an explicit declaration is not a
+ // narrowing, it is a different memory. Over-claiming is answered by the
+ // contract's warnings and by `origin` being recorded as evidence, not by
+ // rewriting what the caller said.
+ if (claimed === "project" && named.length === 0 && origin) {
+ return { scope: "project", projects: [origin], downgraded_from: null };
+ }
+ return { scope: claimed, projects: named, downgraded_from: null };
+}
+
+// ---------------------------------------------------------------------------
+// Link resolution
+// ---------------------------------------------------------------------------
+
+/**
+ * Neutralise wikilinks in free text that point at notes which do not exist.
+ *
+ * `resolveLinks` below governs the `links:` ARRAY. This governs the BODY, and it
+ * is needed for the same reason with a sharper consequence: a broken wikilink
+ * anywhere in a note trips the vault's own wikilink gate, so an agent writing
+ * `[[Some Note]]` from another repo can turn the user's test suite red in a
+ * repository it has never seen.
+ *
+ * Neutralised rather than refused, and reported rather than silent. The text
+ * survives as plain words — `[[Ghost]]` becomes `Ghost`, `[[Ghost|shown]]`
+ * becomes `shown` — so the meaning is kept while the dangling edge is not
+ * created. Refusing the whole write would throw away a good memory over a
+ * formatting detail; writing it unchanged degrades the graph silently.
+ */
+export function neutralizeWikilinks(
+ text: unknown,
+ resolvableSet: ReadonlySet<string>,
+): { text: string; dropped: string[] } {
+ const dropped: string[] = [];
+ const out = String(text ?? "").replace(
+ /\[\[([^\]|#]+)((?:[#|][^\]]*)?)\]\]/g,
+ (whole, rawTarget: string, suffix: string) => {
+ const target = rawTarget.trim();
+ if (resolvableSet.has(target.toLowerCase())) return whole;
+ if (!dropped.includes(target)) dropped.push(target);
+ // Prefer the alias, which is what a human was meant to read.
+ const alias = suffix.startsWith("|") ? suffix.slice(1).trim() : "";
+ return alias || target;
+ },
+ );
+ return { text: out, dropped };
+}
+
+/**
+ * Resolve proposed wikilink targets against names that actually exist.
+ *
+ * An MCP write bypasses the vault's own write-validation hook, so "never emit a
+ * broken link" is re-implemented here. Unresolvable targets are dropped AND
+ * reported — silently dropping would let a session believe it made a connection
+ * it did not make.
+ */
+export function resolveLinks(
+ proposed: unknown,
+ resolvableSet: ReadonlySet<string>,
+): { resolved: string[]; dropped: string[] } {
+ const resolved: string[] = [];
+ const dropped: string[] = [];
+ const seen = new Set<string>();
+ for (const raw of Array.isArray(proposed) ? proposed : []) {
+ const name = String(raw ?? "").trim();
+ if (!name) continue;
+ const key = name.toLowerCase();
+ if (seen.has(key)) continue;
+ seen.add(key);
+ if (resolvableSet.has(key)) resolved.push(name);
+ else dropped.push(name);
+ }
+ return { resolved, dropped };
+}
+
+// ---------------------------------------------------------------------------
+// The epistemic contract, as data
+// ---------------------------------------------------------------------------
+
+const HAPPENING =
+ "break|breaks|broke|fail|fails|failed|crash|crashes|crashed|hang|hangs|error|errors|happen|happens|recover|recovers|work|works|worked";
+
+// String.raw, NOT a plain template literal: in a template literal `\b` is the
+// BACKSPACE character, so `new RegExp` would be handed a control char instead of
+// a word boundary and the rule could never fire — silently. This bit once
+// already, which is why every pattern here has a known-NEGATIVE test as well as
+// a positive one.
+const RECURRENCE = new RegExp(
+ String.raw`\b(?:always|never)\b[^.!?]{0,40}\b(?:${HAPPENING})\b` +
+ String.raw`|\bevery\s+time\b` +
+ String.raw`|\bkeeps?\s+(?:on\s+)?(?:happening|breaking|failing|crashing)\b` +
+ String.raw`|\brecurring\b` +
+ String.raw`|\bconsistently\s+(?:${HAPPENING})\b`,
+ "i",
+);
+
+const VOLATILE = /\b\d[\d,._]*\s*(stars?|forks?|downloads?|users?|subscribers?|followers?|commits?)\b/i;
+const DATE_ANCHOR = /\bas of\b|\d{4}-\d{2}-\d{2}/i;
+const SPEAKER = /^\s*(user|assistant|human|ai|system)\s*:/gim;
+
+export interface ContractRule {
+ readonly id: string;
+ readonly severity: "reject" | "flag";
+ readonly marker?: string;
+ readonly test: (body: string) => boolean;
+ readonly message: string;
+}
+
+/**
+ * Rules as a list so a vault can extend, disable or reorder them without forking
+ * the validator. Each declares its own severity, and that choice is the design:
+ *
+ * reject — the artifact is structurally wrong. Nothing is written.
+ * flag — the CLAIM is weak. The memory IS written, confidence is capped at
+ * `inferred`, and a marker lands in frontmatter for a review view.
+ *
+ * The first version rejected on prose judgements and immediately refused its own
+ * canonical example: "the patch NEVER reaches them" is a deterministic
+ * consequence, not a claim of recurrence. That is the argument against blocking
+ * on prose — a false reject destroys knowledge the session already had, while a
+ * false flag costs one line of frontmatter. Severity chosen accordingly, which
+ * also means these patterns do not need to be perfect.
+ */
+export const CONTRACT_RULES: readonly ContractRule[] = [
+ {
+ id: "transcript",
+ severity: "reject",
+ // Structural, not a judgement: a transcript is a different artifact. The
+ // threshold is high so a memory QUOTING one exchange is unaffected.
+ test: (body) => (body.match(SPEAKER) ?? []).length >= 4,
+ message:
+ "body looks like a transcript. A memory is a conclusion, not a log — record what was learned, not the conversation that produced it.",
+ },
+ {
+ id: "recurrence",
+ severity: "flag",
+ marker: "generalised",
+ test: (body) => RECURRENCE.test(body),
+ message:
+ "body generalises over occurrences (always / every time / keeps failing). One session sees one occurrence, so confidence is capped at `inferred` — state the occurrence with its date and let the vault decide it is a pattern.",
+ },
+ {
+ id: "undated-volatile",
+ severity: "flag",
+ marker: "volatile",
+ test: (body) => VOLATILE.test(body) && !DATE_ANCHOR.test(body),
+ message:
+ 'body states a figure that rots with no date anchor. Add "as of <date>" so staleness is visible instead of silent; the memory is flagged `volatile` until then.',
+ },
+];
+
+/** Run the contract. Pure: returns verdicts, changes nothing. */
+export function applyContract(
+ body: string,
+ rules: readonly ContractRule[] = CONTRACT_RULES,
+): { rejections: string[]; flags: { id: string; marker: string; message: string }[] } {
+ const rejections: string[] = [];
+ const flags: { id: string; marker: string; message: string }[] = [];
+ for (const rule of rules) {
+ let hit = false;
+ try {
+ hit = Boolean(rule.test(body));
+ } catch {
+ // A broken custom rule must not take the whole write down.
+ continue;
+ }
+ if (!hit) continue;
+ if (rule.severity === "reject") rejections.push(rule.message);
+ else flags.push({ id: rule.id, marker: rule.marker ?? rule.id, message: rule.message });
+ }
+ return { rejections, flags };
+}
+
+// ---------------------------------------------------------------------------
+// Validation
+// ---------------------------------------------------------------------------
+
+export function validateMemory(
+ input: MemoryInput | null | undefined,
+ ctx: { now?: Date; origin?: string | null; rules?: readonly ContractRule[] } = {},
+): ValidationResult {
+ const errors: string[] = [];
+ const warnings: string[] = [];
+
+ const title = String(input?.title ?? "").trim();
+ const body = String(input?.body ?? "").trim();
+ const now = ctx.now instanceof Date ? ctx.now : new Date();
+
+ if (!title) errors.push("title is required");
+ else if (title.length > 200) errors.push("title is too long (max 200 chars)");
+ else if (!slugify(title)) {
+ errors.push(
+ `title ${JSON.stringify(title)} contains no characters usable in a filename — give it a title with letters or digits`,
+ );
+ }
+
+ if (!body) errors.push("body is required");
+ else if (body.length < MIN_BODY) {
+ errors.push(
+ `body is ${body.length} chars; a memory needs at least ${MIN_BODY}. Write it for a session that will not have your context.`,
+ );
+ }
+
+ const confidence = String(input?.confidence ?? "").trim();
+ if (!(CONFIDENCE as readonly string[]).includes(confidence)) {
+ errors.push(`confidence must be one of ${CONFIDENCE.join(" | ")}`);
+ }
+
+ if (input?.scope !== undefined && !(SCOPES as readonly string[]).includes(String(input.scope))) {
+ errors.push(`scope must be one of ${SCOPES.join(" | ")}`);
+ }
+
+ for (const field of ["projects", "platforms"] as const) {
+ const v = input?.[field];
+ if (v === undefined || v === null) continue;
+ if (!Array.isArray(v)) {
+ errors.push(`${field} must be an array (it is the multi-valued axis)`);
+ continue;
+ }
+ for (const item of v as unknown[]) {
+ if (typeof item !== "string" || !/^[\w.-]+$/.test(item)) {
+ errors.push(`${field} entries must be simple slugs; got ${JSON.stringify(item)}`);
+ }
+ }
+ }
+
+ const { rejections, flags } = applyContract(body, ctx.rules ?? CONTRACT_RULES);
+ errors.push(...rejections);
+ for (const f of flags) warnings.push(f.message);
+
+ if (body.length > 8000) {
+ warnings.push(`body is ${body.length} chars. Memories are atomic; consider splitting into separate lessons.`);
+ }
+ if (confidence === "verified" && !input?.verification) {
+ warnings.push(
+ 'confidence is "verified" but no verification was given. Say how you know — otherwise "inferred" is the honest value.',
+ );
+ }
+
+ if (errors.length) return { ok: false, errors, warnings, value: null };
+
+ const narrowed = narrowScope({
+ scope: input?.scope ?? "project",
+ projects: input?.projects,
+ origin: ctx.origin ?? null,
+ });
+ const platformsGiven = Array.isArray(input?.platforms)
+ ? (input.platforms as unknown[]).filter(Boolean).map(String)
+ : [];
+
+ // REFUSE A MEMORY THAT WOULD REACH NOBODY.
+ //
+ // A project-scoped memory naming no projects is invisible to every caller:
+ // the visibility rule has nothing to match on. It would validate, write,
+ // index and report success — and be unreachable forever. The hole is a caller
+ // with neither identity nor named projects, i.e. a client that never answered
+ // `roots/list`, which is an observed state rather than a theoretical one.
+ //
+ // Refusing beats widening to `general`: scope IS reach, and granting the
+ // widest possible reach because the narrowest could not be determined is the
+ // exact opposite of what narrowing exists to do.
+ if (narrowed.scope === "project" && narrowed.projects.length === 0) {
+ return {
+ ok: false,
+ errors: [
+ 'This memory would reach nobody: it is project-scoped, names no projects, and the caller has no identity (no MCP roots). Name the projects it applies to, or pass scope: "general" if it genuinely applies everywhere.',
+ ],
+ warnings,
+ value: null,
+ };
+ }
+ if (narrowed.scope === "platform" && platformsGiven.length === 0) {
+ return {
+ ok: false,
+ errors: [
+ 'This memory would reach nobody: it is platform-scoped but names no platforms. List them, or use scope: "project" with the projects it applies to.',
+ ],
+ warnings,
+ value: null,
+ };
+ }
+
+ const capped = flags.length && confidence === "verified";
+ return {
+ ok: true,
+ errors,
+ warnings,
+ value: {
+ title,
+ body,
+ // A flagged claim cannot stay `verified` regardless of what the caller
+ // asserted: the flag exists precisely because the claim outruns what one
+ // session can know. Capping is the enforcement; the marker is the audit.
+ confidence: capped ? "inferred" : (confidence as Confidence),
+ claimed_confidence: capped ? "verified" : null,
+ flags: flags.map((f) => f.marker),
+ verification: input?.verification ? String(input.verification).trim() : null,
+ scope: narrowed.scope,
+ projects: narrowed.projects,
+ platforms: platformsGiven,
+ downgraded_from: narrowed.downgraded_from,
+ origin: ctx.origin ?? null,
+ date: now,
+ },
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Render
+// ---------------------------------------------------------------------------
+
+/** YAML-safe double-quoted scalar. Frontmatter that fails to parse is invisible. */
+function yamlString(s: unknown): string {
+ return JSON.stringify(String(s));
+}
+
+function yamlList(items: readonly string[]): string {
+ return `[${items.map((i) => yamlString(i)).join(", ")}]`;
+}
+
+/**
+ * ~150-char description, the vault-wide requirement. Derived from the body's
+ * first sentence so it is always present without asking the caller for it.
+ */
+export function deriveDescription(body: string): string {
+ const flat = body.replace(/\s+/g, " ").trim();
+ const firstStop = flat.search(/[.!?]\s/);
+ let out = firstStop > 40 ? flat.slice(0, firstStop + 1) : flat;
+ if (out.length > 150) {
+ out = out.slice(0, 150);
+ const lastSpace = out.lastIndexOf(" ");
+ if (lastSpace > 100) out = out.slice(0, lastSpace);
+ out = `${out.trim()}…`;
+ }
+ return out;
+}
+
+export function renderMemory(value: MemoryValue, links: readonly string[] = []): string {
+ const fm = [
+ "---",
+ `date: ${isoDate(value.date)}`,
+ `description: ${yamlString(deriveDescription(value.body))}`,
+ "tags: [memory]",
+ "source: mcp-capture",
+ `origin: ${yamlString(value.origin ?? "unknown")}`,
+ `session: ${yamlString(value.date.toISOString())}`,
+ `scope: ${value.scope}`,
+ `projects: ${yamlList(value.projects)}`,
+ ];
+ if (value.platforms.length) fm.push(`platforms: ${yamlList(value.platforms)}`);
+ fm.push(`confidence: ${value.confidence}`);
+ if (value.claimed_confidence) fm.push(`claimed_confidence: ${value.claimed_confidence}`);
+ // Markers make the contract operational: a Base can list every weak claim in
+ // the vault without re-reading a single body.
+ if (value.flags.length) fm.push(`flags: ${yamlList(value.flags)}`);
+ if (value.downgraded_from) fm.push(`claimed_scope: ${value.downgraded_from}`);
+ fm.push("---", "");
+
+ const parts = [fm.join("\n"), `# ${value.title}`, "", value.body, ""];
+ if (value.verification) parts.push("## How this is known", "", value.verification, "");
+ // A note without links is a bug — the vault's own doctrine. Links are the only
+ // way a memory reaches the project it is about, since it does not live inside
+ // that project's folder.
+ if (links.length) parts.push("## Related", "", ...links.map((l) => `- [[${l}]]`), "");
+ return parts.join("\n");
+}
+
+// ---------------------------------------------------------------------------
+// IO shell
+// ---------------------------------------------------------------------------
+
+/**
+ * Write the memory. The only impure function here.
+ *
+ * Collision handling matters more than it looks: two memories captured the same
+ * day with the same title would otherwise silently overwrite, and the loser is
+ * unrecoverable. Suffix rather than clobber.
+ */
+export function writeMemory(
+ vaultRoot: string,
+ value: MemoryValue,
+ links: readonly string[],
+ { root = MEMORY_ROOT }: { root?: string } = {},
+): { rel: string; full: string } {
+ const base = memoryPath(value.date, value.title, root).replace(/\.md$/, "");
+ const dir = dirname(join(vaultRoot, `${base}.md`));
+ mkdirSync(dir, { recursive: true });
+ const body = renderMemory(value, links);
+
+ // Claimed atomically rather than checked-then-written; see `atomic-write.ts`
+ // for why, and for what the naive version cost.
+ const claimed = claimFile(dir, body, (n) => `${basename(base)}${n === 1 ? "" : ` (${n})`}.md`, {
+ exhaustedMessage: "too many same-titled memories on one day",
+ });
+ return { rel: `${dirname(base)}/${claimed.name}`.replace(/\\/g, "/"), full: claimed.full };
+}
+
+/** Read back what was written — used by tests and the post-write self-check. */
+export function readMemory(vaultRoot: string, rel: string): string {
+ return readFileSync(join(vaultRoot, rel), "utf8");
+}
diff --git a/.claude/scripts/om-mcp.mjs b/.claude/scripts/om-mcp.mjs
new file mode 100644
index 0000000..71e31d9
--- /dev/null
+++ b/.claude/scripts/om-mcp.mjs
@@ -0,0 +1,48 @@
+#!/usr/bin/env node
+/**
+ * om-mcp.mjs — launcher for the `om` MCP server.
+ *
+ * Exists so a consuming project's `.mcp.json` can be one plain line:
+ *
+ * { "command": "node", "args": ["<vault>/.claude/scripts/om-mcp.mjs"] }
+ *
+ * The server itself is TypeScript, which needs `--experimental-strip-types`.
+ * Putting that flag in every consuming repo's config would mean every one of
+ * them has to be edited when the flag stops being needed — and a stale flag in
+ * someone else's repo is exactly the kind of breakage nobody attributes back
+ * here. Same reasoning as `qmd-mcp.mjs`, which this deliberately mirrors.
+ *
+ * Re-exec rather than dynamic import: the flags must be set at process start.
+ * stdio is inherited, so the child speaks MCP directly to the client and this
+ * process is a transparent shim on the wire.
+ */
+
+import { spawn } from "node:child_process";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const here = dirname(fileURLToPath(import.meta.url));
+const server = join(here, "om-mcp.ts");
+
+const child = spawn(
+ process.execPath,
+ ["--disable-warning=ExperimentalWarning", "--experimental-strip-types", server, ...process.argv.slice(2)],
+ { stdio: "inherit", env: process.env },
+);
+
+// Forward termination so the client's shutdown reaches the real server rather
+// than orphaning it.
+for (const sig of ["SIGTERM", "SIGINT"]) {
+ process.on(sig, () => child.kill(sig));
+}
+
+child.on("exit", (code, signal) => {
+ process.exit(signal ? 1 : (code ?? 0));
+});
+
+child.on("error", (err) => {
+ // stderr, never stdout: stdout is the MCP channel and any non-JSON byte on
+ // it corrupts the stream for the client.
+ process.stderr.write(`om-mcp: failed to start server: ${err.message}\n`);
+ process.exit(1);
+});
diff --git a/.claude/scripts/om-mcp.ts b/.claude/scripts/om-mcp.ts
new file mode 100644
index 0000000..4dd4af2
--- /dev/null
+++ b/.claude/scripts/om-mcp.ts
@@ -0,0 +1,94 @@
+/**
+ * The `om` MCP server — the vault, reachable from any repository.
+ *
+ * This file is deliberately thin. It owns exactly the things a test cannot
+ * usefully drive: resolving the vault, opening stdio, and holding the lazy qmd
+ * child. Every decision worth arguing about lives in `lib/mcp-*.ts`, where it
+ * can be driven in-process — the prototype bound its handlers to module state
+ * and stdio, and two bugs survived because checking anything needed a live
+ * client.
+ *
+ * Registered in a consuming project's `.mcp.json` through the `om-mcp.mjs`
+ * launcher, which adds the type-stripping flags this file needs.
+ *
+ * The server is only HALF the install. The other half is a short section in the
+ * consuming repo's own CLAUDE.md, and that is not documentation garnish: a
+ * prohibition in the MCP `instructions` field propagates into a calling session
+ * reliably, while a positive instruction to go and consult the vault is
+ * advisory and gets skipped whenever a nearer source exists. This server can
+ * stop a session doing something; only the project's own law makes one look.
+ */
+
+import { createInterface } from "node:readline";
+
+import { createContext, resolveVaultRoot, derivedVaultRoot } from "./lib/mcp-context.ts";
+import { resolveExposure } from "./lib/mcp-exposure.ts";
+import { McpSession, type Handlers } from "./lib/mcp-protocol.ts";
+import { createQmdClient, type QmdClient } from "./lib/mcp-qmd-client.ts";
+import { createAuditor, auditPath, callerProject } from "./lib/mcp-caller.ts";
+import { createHandlers } from "./lib/mcp-server.ts";
+
+const vaultRoot = resolveVaultRoot(import.meta.url);
+const ctx = createContext(vaultRoot, derivedVaultRoot(import.meta.url));
+const policy = resolveExposure(vaultRoot, ctx.manifest, ctx.memoryRoot);
+
+/**
+ * One long-lived qmd child, started on first use and REPLACED if it dies.
+ *
+ * Lazy because a vault with no qmd installed must still serve resources,
+ * `expand`, `recall` and `health` — search is the only surface that degrades,
+ * and it degrades to a message rather than to silence.
+ *
+ * Memoising it unconditionally was the bug: a single qmd crash left a dead
+ * client in place, whose pending map rejects every later call, so search stayed
+ * broken for the life of the server. The cooldown guards the opposite failure —
+ * when qmd is missing or permanently broken, respawning per call would fork a
+ * process for every search.
+ */
+let qmdClient: QmdClient | null = null;
+let lastSpawn = 0;
+const RESPAWN_COOLDOWN_MS = 5_000;
+
+const qmd = (): QmdClient => {
+ if (qmdClient?.alive) return qmdClient;
+ const now = Date.now();
+ if (qmdClient && now - lastSpawn < RESPAWN_COOLDOWN_MS) return qmdClient;
+ lastSpawn = now;
+ qmdClient = createQmdClient(vaultRoot, ctx.qmdLauncher);
+ return qmdClient;
+};
+
+const send = (msg: unknown): void => {
+ process.stdout.write(JSON.stringify(msg) + "\n");
+};
+
+// The session and its handlers are mutually referential: handlers reply through
+// session.ok/fail, and the session dispatches into handlers. Sharing one object
+// and filling it after construction keeps that honest without a proxy.
+const handlers: Handlers = {};
+const session = new McpSession({ send, handlers });
+Object.assign(
+ handlers,
+ createHandlers({
+ ctx,
+ policy,
+ session,
+ qmd,
+ audit: createAuditor(auditPath(vaultRoot), () => callerProject(session.roots)),
+ }),
+);
+
+createInterface({ input: process.stdin }).on("line", (line) => {
+ // Deliberately not awaited: MCP allows concurrent in-flight requests, and
+ // serialising them here would make one slow search block every other call.
+ void session.handleLine(line);
+});
+
+const shutdown = (): void => {
+ qmdClient?.dispose();
+ process.exit(0);
+};
+process.on("SIGTERM", shutdown);
+process.on("SIGINT", shutdown);
+// stdin closing is how an MCP client says goodbye.
+process.stdin.on("end", shutdown);
diff --git a/.claude/scripts/tests/memory-index.test.ts b/.claude/scripts/tests/automemory-index.test.ts
similarity index 98%
rename from .claude/scripts/tests/memory-index.test.ts
rename to .claude/scripts/tests/automemory-index.test.ts
index 460a5f2..db09c11 100644
--- a/.claude/scripts/tests/memory-index.test.ts
+++ b/.claude/scripts/tests/automemory-index.test.ts
@@ -10,7 +10,7 @@ import {
MEMORY_INDEX_HEADER,
generateMemoryIndex,
type BrainNote,
-} from "../lib/memory-index.ts";
+} from "../lib/automemory-index.ts";
const NOTES: readonly BrainNote[] = [
{ name: "Patterns", description: "Recurring patterns and conventions" },
diff --git a/.claude/scripts/tests/mcp-caller.test.ts b/.claude/scripts/tests/mcp-caller.test.ts
new file mode 100644
index 0000000..9c0e493
--- /dev/null
+++ b/.claude/scripts/tests/mcp-caller.test.ts
@@ -0,0 +1,351 @@
+/**
+ * Caller identity and the outbound boundary.
+ *
+ * Two independent properties.
+ *
+ * Identity is DERIVED from the roots handshake, so a session cannot claim to be
+ * a project it is not — which is what makes every scoping rule downstream mean
+ * anything. And the sanitiser replaces local absolute paths in anything crossing
+ * back, because error text lands in the calling session and may be pasted into a
+ * commit or an issue.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync, readFileSync, existsSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, dirname, basename } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+import {
+ normalizePath,
+ rootToPath,
+ callerProject,
+ callerProjectSource,
+ PROJECT_MARKER,
+ isVaultItself,
+ sanitize,
+ createAuditor,
+ auditPath,
+ type Root,
+} from "../lib/mcp-caller.ts";
+
+const root = (uri: string): Root => ({ uri });
+
+// ---------------------------------------------------------------------------
+// Identity
+// ---------------------------------------------------------------------------
+
+describe("reading the caller's identity from roots", () => {
+ test("handles the two- and three-slash file URI forms", () => {
+ // Asserted through normalizePath rather than as an exact string, because a
+ // drive-letter URI resolves to the NATIVE form: `C:\Dev\atlas` on Windows
+ // but `/C:/Dev/atlas` on POSIX, which has no drive concept. Pinning either
+ // passes on the machine it was written on and fails on the CI matrix — as
+ // this test did. normalizePath absorbs the difference, and comparison is
+ // what every caller actually does with the value.
+ assert.equal(normalizePath(rootToPath("file:///C:/Dev/atlas")), normalizePath("C:/Dev/atlas"));
+ assert.equal(normalizePath(rootToPath("file://C:/Dev/atlas")), normalizePath("C:/Dev/atlas"));
+ });
+
+ test("a drive path compares equal however the platform rendered it", () => {
+ // The regression itself: identical roots must not compare unequal because
+ // of which platform parsed the URI.
+ assert.equal(normalizePath("/C:/Dev/atlas"), normalizePath("C:\\Dev\\atlas"));
+ assert.equal(normalizePath("/c:/dev/atlas"), "c:/dev/atlas");
+ // A POSIX root must NOT have its leading slash stripped — that slash is
+ // the filesystem root, not a URI artifact.
+ assert.equal(normalizePath("/home/x/atlas"), "/home/x/atlas");
+ });
+
+ test("a POSIX root KEEPS its leading slash — that slash is the filesystem root", () => {
+ // Regression, and the test that previously encoded the bug as expected.
+ // The old pattern ate the third slash unconditionally, which is right for
+ // `file:///C:/x` and wrong for `file:///home/x`. Every POSIX root became a
+ // relative path, so isVaultItself() could never match and the guard against
+ // the vault writing to its own memory layer failed OPEN on Linux and macOS.
+ assert.equal(rootToPath("file:///home/x/atlas"), "/home/x/atlas");
+ assert.equal(rootToPath("file:///Users/x/vault"), "/Users/x/vault");
+ });
+
+ test("percent-encoding is decoded, and a malformed escape does not throw", () => {
+ assert.equal(normalizePath(rootToPath("file:///C:/Dev/my%20app")), normalizePath("C:/Dev/my app"));
+ assert.equal(normalizePath(rootToPath("file:///home/x/my%20app")), "/home/x/my app");
+ // A stray `%` is not a legal escape. It must degrade, not throw the
+ // caller's identity away — an exception here would make the session
+ // anonymous, which silently narrows its scope to `general`.
+ assert.equal(normalizePath(rootToPath("file:///C:/Dev/100%")), normalizePath("C:/Dev/100%"));
+ });
+
+ test("the project is the last segment, lowercased", () => {
+ assert.equal(callerProject([root("file:///C:/Dev/Atlas")]), "atlas");
+ assert.equal(callerProject([root("file:///C:/Dev/atlas/")]), "atlas");
+ assert.equal(callerProject([root("file:///home/x/pocket")]), "pocket");
+ });
+
+ test("no roots means NO identity — never a guess and never a default", () => {
+ // An anonymous caller must fall through to general-scoped material only.
+ // Inventing an identity here would hand it another project's memories.
+ assert.equal(callerProject([]), null);
+ assert.equal(callerProject([{}]), null);
+ assert.equal(callerProject([root("")]), null);
+ });
+
+ test("the first root wins when a session has several", () => {
+ assert.equal(callerProject([root("file:///C:/Dev/atlas"), root("file:///C:/Dev/other")]), "atlas");
+ });
+
+ test("a repo can declare its own identity, which separates same-named repos", () => {
+ // Two repos both called `api` otherwise share an identity, so each
+ // receives the other's memories — a relevance failure, not a security one.
+ const dir = mkdtempSync(join(tmpdir(), "marker-"));
+ try {
+ const uri = pathToFileURL(dir).href;
+ assert.equal(callerProject([root(uri)]), basename(dir).toLowerCase(), "folder name by default");
+ assert.equal(callerProjectSource([root(uri)]), "folder");
+
+ writeFileSync(join(dir, PROJECT_MARKER), "# which api is this\nbilling-api\n", "utf8");
+ assert.equal(callerProject([root(uri)]), "billing-api");
+ assert.equal(callerProjectSource([root(uri)]), "declared");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test("a declared identity cannot smuggle in a path or junk", () => {
+ const dir = mkdtempSync(join(tmpdir(), "marker2-"));
+ try {
+ const uri = pathToFileURL(dir).href;
+ for (const bad of ["../escape", "a/b", "with spaces", "", " "]) {
+ writeFileSync(join(dir, PROJECT_MARKER), bad, "utf8");
+ assert.equal(callerProject([root(uri)]), basename(dir).toLowerCase(), `refused: ${JSON.stringify(bad)}`);
+ }
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe("recognising the vault itself", () => {
+ test("a session whose root IS the vault is recognised", () => {
+ assert.equal(isVaultItself("C:/Dev/myvault", [root("file:///C:/Dev/myvault")]), true);
+ });
+
+ test("recognised on POSIX too — the guard must not fail open off Windows", () => {
+ // This is the whole point of the guard: a memory recorded from inside the
+ // vault is scoped to the vault-as-a-project and reaches only sessions that
+ // already read every note directly. It was returning false on Linux and
+ // macOS, so the refusal never fired there.
+ assert.equal(isVaultItself("/home/x/myvault", [root("file:///home/x/myvault")]), true);
+ assert.equal(isVaultItself("/Users/x/myvault", [root("file:///Users/x/myvault/")]), true);
+ assert.equal(isVaultItself("/home/x/myvault", [root("file:///home/x/other")]), false);
+ });
+
+ test("separator style, trailing slash and case do not matter", () => {
+ for (const uri of [
+ "file:///C:/Dev/MyVault",
+ "file:///C:/Dev/myvault/",
+ "file:///C:\\Dev\\myvault",
+ ]) {
+ assert.equal(isVaultItself("C:\\Dev\\myvault", [root(uri)]), true, uri);
+ }
+ });
+
+ test("the vault as a SECONDARY root still counts", () => {
+ // A session can legitimately open the vault as an extra directory, and it
+ // is still the vault writing to itself.
+ assert.equal(
+ isVaultItself("C:/Dev/myvault", [root("file:///C:/Dev/atlas"), root("file:///C:/Dev/myvault")]),
+ true,
+ );
+ });
+
+ test("an ordinary repo is not the vault", () => {
+ assert.equal(isVaultItself("C:/Dev/myvault", [root("file:///C:/Dev/atlas")]), false);
+ });
+
+ test("a repo NESTED inside the vault is not the vault", () => {
+ // It is a different project that happens to live there, and its memories
+ // are legitimately its own.
+ assert.equal(isVaultItself("C:/Dev/myvault", [root("file:///C:/Dev/myvault/sub")]), false);
+ });
+
+ test("an anonymous caller is not the vault", () => {
+ assert.equal(isVaultItself("C:/Dev/myvault", []), false);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// The outbound boundary
+// ---------------------------------------------------------------------------
+
+describe("sanitising text that crosses back to the caller", () => {
+ test("a Windows path in a real fs error is stripped", () => {
+ const msg = "ENOENT: no such file or directory, lstat 'C:\\Users\\someone\\vault\\CLAUDE.md'";
+ const out = sanitize(msg);
+ assert.ok(!out.includes("Users"), out);
+ assert.ok(!out.includes("someone"), out);
+ assert.match(out, /<path>/);
+ });
+
+ test("a POSIX home path is stripped", () => {
+ for (const p of ["/home/someone/vault/note.md", "/Users/someone/vault/note.md", "/root/secret"]) {
+ const out = sanitize(`failed reading ${p}`);
+ assert.ok(!out.includes("someone") && !out.includes("secret"), out);
+ assert.match(out, /<path>/);
+ }
+ });
+
+ test("a UNC path is stripped", () => {
+ assert.match(sanitize("cannot open \\\\server\\share\\vault\\a.md"), /<path>/);
+ assert.ok(!sanitize("cannot open \\\\server\\share\\vault\\a.md").includes("server"));
+ });
+
+ test("the message around the path survives — this is not redaction of everything", () => {
+ const out = sanitize("ENOENT: no such file or directory, lstat 'C:\\v\\a.md'");
+ assert.match(out, /ENOENT/);
+ assert.match(out, /no such file/);
+ });
+
+ test("a vault-relative path is NOT stripped, because that is what a citation is", () => {
+ const out = sanitize("see brain/Gotchas.md for the reasoning");
+ assert.equal(out, "see brain/Gotchas.md for the reasoning");
+ });
+
+ test("multiple paths in one message are all stripped", () => {
+ const out = sanitize("copy 'C:\\a\\b.md' to '/home/x/c.md'");
+ assert.equal((out.match(/<path>/g) ?? []).length, 2);
+ });
+
+ test("a URI survives — a drive letter is ONE letter, not any letter", () => {
+ // Regression: "vault://note/work/Secret.md" matched from its "t://note/..."
+ // and came back as "vaul<path>", destroying every URI in every error
+ // message. A wire probe caught it; none of the fs-error cases above could.
+ for (const uri of [
+ "vault://note/brain/Gotchas.md",
+ "file:///c/x",
+ "https://example.com/a/b",
+ "qmd://index/thing",
+ ]) {
+ assert.equal(sanitize(`no such resource: ${uri}`), `no such resource: ${uri}`, uri);
+ }
+ });
+
+ test("a real drive path at a word boundary is still stripped", () => {
+ assert.match(sanitize("open C:\\vault\\a.md"), /<path>/);
+ assert.match(sanitize("(C:/vault/a.md)"), /<path>/);
+ assert.match(sanitize("'D:\\other\\b.md'"), /<path>/);
+ });
+
+ test("a non-string is coerced rather than throwing", () => {
+ assert.equal(sanitize(undefined), "undefined");
+ assert.equal(sanitize(new Error("boom").message), "boom");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Audit
+// ---------------------------------------------------------------------------
+
+describe("the audit log", () => {
+ function withDir(fn: (dir: string) => void): void {
+ const dir = mkdtempSync(join(tmpdir(), "audit-"));
+ try {
+ fn(dir);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+
+ test("records the action, the caller and a timestamp as one JSON line each", () => {
+ withDir((dir) => {
+ const log = join(dir, "nested", "audit.jsonl");
+ const audit = createAuditor(log, () => "atlas", () => "2026-07-26T00:00:00Z");
+ audit("search", { query: "tokens", bytes: 42 });
+ audit("recall");
+ const lines = readFileSync(log, "utf8").trim().split("\n");
+ assert.equal(lines.length, 2);
+ const first = JSON.parse(lines[0]!);
+ assert.equal(first.action, "search");
+ assert.equal(first.caller, "atlas");
+ assert.equal(first.at, "2026-07-26T00:00:00Z");
+ assert.equal(first.query, "tokens");
+ });
+ });
+
+ test("an anonymous caller is logged as unknown, not omitted", () => {
+ withDir((dir) => {
+ const log = join(dir, "audit.jsonl");
+ createAuditor(log, () => null)("search");
+ assert.equal(JSON.parse(readFileSync(log, "utf8").trim()).caller, "unknown");
+ });
+ });
+
+ test("an unwritable log NEVER breaks the caller", () => {
+ // A control that can take the server down is a liability, not a control.
+ const audit = createAuditor(join("Z:", "definitely", "not", "here.jsonl"), () => "x");
+ assert.doesNotThrow(() => audit("search", { query: "q" }));
+ });
+
+ test("the log rotates instead of growing without bound", () => {
+ withDir((dir) => {
+ const log = join(dir, "audit.jsonl");
+ const audit = createAuditor(log, () => "atlas", () => "2026-07-26T00:00:00Z", 400);
+ for (let i = 0; i < 40; i++) audit("search", { query: `query number ${i} with some padding` });
+ assert.ok(existsSync(`${log}.1`), "a rotated generation must exist");
+ assert.ok(readFileSync(log, "utf8").length < 400 * 3, "the live log stays bounded");
+ // The most recent entry is still in the live file, not lost to rotation.
+ assert.match(readFileSync(log, "utf8"), /query number 39/);
+ });
+ });
+
+ test("rotation never breaks the write", () => {
+ withDir((dir) => {
+ const log = join(dir, "audit.jsonl");
+ const audit = createAuditor(log, () => "atlas", () => "t", 1);
+ assert.doesNotThrow(() => {
+ audit("a");
+ audit("b");
+ audit("c");
+ });
+ });
+ });
+
+ test("the log lands inside the vault, where the repo can ignore it", () => {
+ assert.equal(auditPath("C:/v"), join("C:/v", ".claude", "om-mcp-audit.jsonl"));
+ });
+
+ test("the log is actually gitignored, and the two places agree", () => {
+ // Two sources of truth for one path: auditPath() decides where the file
+ // goes, .gitignore decides whether it is tracked. Changing one silently
+ // stops the other from matching, and the symptom is a churning log file —
+ // full of the user's own query strings — appearing in every commit.
+ const repoRoot = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
+ const rel = auditPath("").replace(/^[\\/]+/, "").split(/[\\/]/).join("/");
+ const gitignore = readFileSync(join(repoRoot, ".gitignore"), "utf8");
+ assert.ok(
+ gitignore.split(/\r?\n/).some((line) => line.trim() === rel),
+ `.gitignore must contain "${rel}" — auditPath() and .gitignore have drifted`,
+ );
+ });
+
+ test("detail keys cannot overwrite the action or the caller", () => {
+ withDir((dir) => {
+ const log = join(dir, "audit.jsonl");
+ // Spread order matters: a tool argument named `caller` must not be able
+ // to forge the identity recorded against its own call.
+ createAuditor(log, () => "atlas")("search", { caller: "someone-else", action: "innocent" });
+ const entry = JSON.parse(readFileSync(log, "utf8").trim());
+ assert.equal(entry.caller, "atlas");
+ assert.equal(entry.action, "search");
+ });
+ });
+
+ test("nothing is created until something is logged", () => {
+ withDir((dir) => {
+ const log = join(dir, "sub", "audit.jsonl");
+ createAuditor(log, () => "x");
+ assert.equal(existsSync(log), false);
+ });
+ });
+});
diff --git a/.claude/scripts/tests/mcp-capture.test.ts b/.claude/scripts/tests/mcp-capture.test.ts
new file mode 100644
index 0000000..568020e
--- /dev/null
+++ b/.claude/scripts/tests/mcp-capture.test.ts
@@ -0,0 +1,312 @@
+/**
+ * Filing a work record.
+ *
+ * Three properties are load-bearing and each is asserted directly rather than
+ * inferred from a happy path:
+ *
+ * - a caller-supplied folder is VALIDATED against the exposed roots, so a
+ * destination string cannot become an arbitrary write;
+ * - the final name is claimed ATOMICALLY, because the obvious
+ * check-then-rename loses a whole capture to a race with no error; and
+ * - a link is emitted only when it resolves, because a note that
+ * manufactures broken links degrades the graph silently.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readdirSync, readFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ slugifyTitle,
+ projectDirFor,
+ resolveDestination,
+ renderCapture,
+ captureNote,
+ type Destination,
+} from "../lib/mcp-capture.ts";
+import type { ExposurePolicy } from "../lib/mcp-exposure.ts";
+
+const NOW = new Date("2026-07-26T10:00:00Z");
+const POLICY: ExposurePolicy = { roots: ["brain", "projects"], neverExpose: new Set(), source: "manifest", memoryRoot: "memories" };
+
+function withVault(fn: (dir: string) => void): void {
+ const dir = mkdtempSync(join(tmpdir(), "cap-"));
+ try {
+ fn(dir);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+const BASIC = {
+ title: "Add the archive command",
+ summary: "Shipped the archive command behind a flag.",
+ changes: ["added cmd", "wired flag"],
+ kind: "note",
+};
+
+// ---------------------------------------------------------------------------
+// Slug
+// ---------------------------------------------------------------------------
+
+describe("slugifying a title", () => {
+ test("produces a filesystem-safe stem", () => {
+ assert.equal(slugifyTitle("Add the archive command"), "add-the-archive-command");
+ });
+
+ test("strips separators rather than escaping them", () => {
+ // This is the containment property: a title cannot contribute a path.
+ for (const t of ["a/b", "a\\b", "../../etc/passwd", "a:b"]) {
+ const s = slugifyTitle(t);
+ assert.ok(!s.includes("/") && !s.includes("\\") && !s.includes(".."), `${t} → ${s}`);
+ }
+ });
+
+ test("a title of only punctuation produces an empty stem, which is refused upstream", () => {
+ assert.equal(slugifyTitle("!!!"), "");
+ assert.equal(slugifyTitle(""), "");
+ });
+
+ test("is bounded, so a pathological title cannot make an unusable filename", () => {
+ assert.ok(slugifyTitle("x".repeat(500)).length <= 60);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Routing
+// ---------------------------------------------------------------------------
+
+describe("finding a project folder", () => {
+ test("exact, case-insensitive and prefix matches all resolve", () => {
+ withVault((dir) => {
+ mkdirSync(join(dir, "projects", "pocket"), { recursive: true });
+ assert.equal(projectDirFor(dir, "pocket")?.name, "pocket");
+ assert.equal(projectDirFor(dir, "Pocket")?.name, "pocket");
+ assert.equal(projectDirFor(dir, "poc")?.name, "pocket", "repo and folder names do not always agree");
+ });
+ });
+
+ test("a vault with no projects/ folder is null, not a crash", () => {
+ // A clean install of this template has no projects/ at all.
+ withVault((dir) => assert.equal(projectDirFor(dir, "pocket"), null));
+ });
+
+ test("an anonymous caller has no project", () => {
+ withVault((dir) => assert.equal(projectDirFor(dir, null), null));
+ });
+});
+
+describe("resolving the destination", () => {
+ test("a caller-chosen folder inside an exposed root is honoured", () => {
+ withVault((dir) => {
+ const d = resolveDestination(dir, POLICY, {}, "atlas", "brain/notes", "note");
+ assert.equal(d.routed, "caller");
+ assert.equal(d.rel, "brain/notes");
+ });
+ });
+
+ test("a folder OUTSIDE the exposed roots is refused", () => {
+ // The exposed roots bound writing as well as reading: a note lands in a
+ // folder the vault declared, or the call is refused.
+ withVault((dir) => {
+ assert.throws(() => resolveDestination(dir, POLICY, {}, "atlas", "work/career", "note"), /not an exposed root/);
+ assert.throws(() => resolveDestination(dir, POLICY, {}, "atlas", "people", "note"), /not an exposed root/);
+ });
+ });
+
+ test("a traversal that starts inside an exposed root is refused", () => {
+ withVault((dir) => {
+ assert.throws(
+ () => resolveDestination(dir, POLICY, {}, "atlas", "brain/../../elsewhere", "note"),
+ /traversal segment/,
+ );
+ });
+ });
+
+ test("a traversal that lands back INSIDE the vault is still refused", () => {
+ // The one that got through. `brain/../work` passes the first-segment root
+ // check and resolves to a path still inside the vault, so a containment
+ // test against the vault accepted it — and the capture landed in work/,
+ // which nobody named. Containment has to be against the DECLARED ROOT.
+ withVault((dir) => {
+ for (const escape of ["brain/../work", "brain/../../vault/work", "brain/./../org", "projects/../perf"]) {
+ assert.throws(() => resolveDestination(dir, POLICY, {}, "atlas", escape, "note"), /refused/, escape);
+ }
+ });
+ });
+
+ test("caller identity routes into the matching project", () => {
+ withVault((dir) => {
+ mkdirSync(join(dir, "projects", "atlas"), { recursive: true });
+ const d = resolveDestination(dir, POLICY, {}, "atlas", undefined, "note");
+ assert.equal(d.routed, "caller-identity");
+ assert.equal(d.rel, "projects/atlas/notes");
+ assert.equal(d.project, "atlas");
+ });
+ });
+
+ test("a decision routes to decisions/ rather than notes/", () => {
+ withVault((dir) => {
+ mkdirSync(join(dir, "projects", "atlas"), { recursive: true });
+ assert.equal(resolveDestination(dir, POLICY, {}, "atlas", undefined, "decision").rel, "projects/atlas/decisions");
+ });
+ });
+
+ test("an unknown caller falls back to the inbox", () => {
+ withVault((dir) => {
+ assert.equal(resolveDestination(dir, POLICY, {}, "unknown-repo", undefined, "note").routed, "fallback");
+ assert.equal(resolveDestination(dir, POLICY, { mcp_inbox: "dump" }, null, undefined, "note").rel, "dump");
+ });
+ });
+
+ test("an unsafe configured inbox falls back to the default", () => {
+ withVault((dir) => {
+ assert.equal(resolveDestination(dir, POLICY, { mcp_inbox: "../escape" }, null, undefined, "note").rel, "inbox");
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Rendering
+// ---------------------------------------------------------------------------
+
+describe("rendering a capture", () => {
+ const dest: Destination = { dir: "/v/projects/atlas/notes", rel: "projects/atlas/notes", project: "atlas", routed: "caller-identity" };
+
+ test("carries frontmatter the vault's own validator would accept", () => {
+ const md = renderCapture(BASIC, dest, "atlas", new Set(["atlas"]), NOW);
+ assert.match(md, /^---\n/);
+ assert.match(md, /date: 2026-07-26/);
+ assert.match(md, /description: "Shipped the archive command behind a flag\."/);
+ assert.match(md, /project: atlas/);
+ assert.match(md, /source_repo: atlas/);
+ });
+
+ test("a resolvable informed_by becomes a wikilink; an unresolvable one does NOT", () => {
+ // A capture that manufactures broken links degrades the graph silently and
+ // trips the vault's own wikilink gate.
+ const md = renderCapture(
+ { ...BASIC, informed_by: ["Gotchas", "Note That Does Not Exist"] },
+ dest,
+ "atlas",
+ new Set(["atlas", "gotchas"]),
+ NOW,
+ );
+ assert.match(md, /- \[\[Gotchas\]\]/);
+ assert.match(md, /- Note That Does Not Exist _\(no note yet\)_/);
+ assert.ok(!md.includes("[[Note That Does Not Exist]]"));
+ });
+
+ test("the project home link is emitted only when the project resolves by name", () => {
+ assert.match(renderCapture(BASIC, dest, "atlas", new Set(["atlas"]), NOW), /- \[\[atlas\]\]/);
+ assert.ok(!renderCapture(BASIC, dest, "atlas", new Set(), NOW).includes("[[atlas]]"));
+ });
+
+ test("empty sections are omitted rather than left as empty headings", () => {
+ const md = renderCapture({ title: "t", summary: "s", kind: "note" }, dest, "atlas", new Set(), NOW);
+ assert.ok(!md.includes("## What changed"));
+ assert.ok(!md.includes("## Open"));
+ });
+
+ test("a quote in the summary cannot break the frontmatter", () => {
+ const md = renderCapture({ ...BASIC, summary: 'He said "hello" today' }, dest, "atlas", new Set(), NOW);
+ const front = md.slice(0, md.indexOf("\n---", 4));
+ assert.ok(!/description: ".*".*"/.test(front.split("\n").find((l) => l.startsWith("description:")) ?? ""));
+ });
+
+ test("the routing decision is recorded in the note itself", () => {
+ assert.match(renderCapture(BASIC, dest, "atlas", new Set(), NOW), /routing: caller-identity/);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Writing
+// ---------------------------------------------------------------------------
+
+describe("writing a capture", () => {
+ test("a dry run writes nothing and previews", () => {
+ withVault((dir) => {
+ const r = captureNote(dir, POLICY, {}, "atlas", { ...BASIC, dry_run: true }, new Set(), { now: NOW });
+ assert.equal(r.written, false);
+ assert.ok(r.preview);
+ assert.equal(readdirSync(dir).length, 0, "nothing may touch disk");
+ });
+ });
+
+ test("a note record takes the date prefix; a decision does not", () => {
+ withVault((dir) => {
+ const note = captureNote(dir, POLICY, {}, null, BASIC, new Set(), { now: NOW });
+ assert.match(note.path, /2026-07-26-add-the-archive-command\.md$/);
+ const dec = captureNote(dir, POLICY, {}, null, { ...BASIC, kind: "decision" }, new Set(), { now: NOW });
+ // A decision is a living document; a creation-date prefix would invert
+ // its recency signal.
+ assert.match(dec.path, /\/add-the-archive-command\.md$/);
+ });
+ });
+
+ test("the file lands where it was routed, with its content", () => {
+ withVault((dir) => {
+ const r = captureNote(dir, POLICY, {}, null, BASIC, new Set(), { now: NOW });
+ const md = readFileSync(join(dir, r.path), "utf8");
+ assert.match(md, /# Add the archive command/);
+ assert.match(md, /- added cmd/);
+ });
+ });
+
+ test("a colliding title takes the next suffix rather than overwriting", () => {
+ // The obvious check-then-rename loses one capture entirely, with no error.
+ withVault((dir) => {
+ const a = captureNote(dir, POLICY, {}, null, BASIC, new Set(), { now: NOW });
+ const b = captureNote(dir, POLICY, {}, null, BASIC, new Set(), { now: NOW });
+ assert.notEqual(a.path, b.path);
+ assert.match(b.path, /-2\.md$/);
+ assert.ok(readFileSync(join(dir, a.path), "utf8").length > 0, "the first must survive");
+ });
+ });
+
+ test("no temp file is left behind", () => {
+ withVault((dir) => {
+ const r = captureNote(dir, POLICY, {}, null, BASIC, new Set(), { now: NOW });
+ const leftovers = readdirSync(join(dir, "inbox")).filter((f) => f.endsWith(".tmp"));
+ assert.deepEqual(leftovers, [], "a half-written note must never be visible to the indexer");
+ assert.ok(r.written);
+ });
+ });
+
+ test("an empty title is refused before anything is written", () => {
+ withVault((dir) => {
+ assert.throws(() => captureNote(dir, POLICY, {}, null, { ...BASIC, title: "!!!" }, new Set()), /empty filename/);
+ assert.equal(readdirSync(dir).length, 0);
+ });
+ });
+
+ test("a refused folder writes nothing at all", () => {
+ withVault((dir) => {
+ assert.throws(
+ () => captureNote(dir, POLICY, {}, "atlas", { ...BASIC, folder: "work/secret" }, new Set()),
+ /not an exposed root/,
+ );
+ assert.equal(readdirSync(dir).length, 0, "a refusal must not create the folder either");
+ });
+ });
+
+ test("the reindex result is reported, so an unfindable note is not called a success", () => {
+ withVault((dir) => {
+ const ok = captureNote(dir, POLICY, {}, null, BASIC, new Set(), { now: NOW, reindex: () => true });
+ assert.equal(ok.indexed, true);
+ const bad = captureNote(dir, POLICY, {}, null, BASIC, new Set(), { now: NOW, reindex: () => false });
+ assert.equal(bad.indexed, false);
+ });
+ });
+
+ test("existing files in the destination are untouched", () => {
+ withVault((dir) => {
+ mkdirSync(join(dir, "inbox"), { recursive: true });
+ writeFileSync(join(dir, "inbox", "existing.md"), "keep me", "utf8");
+ captureNote(dir, POLICY, {}, null, BASIC, new Set(), { now: NOW });
+ assert.equal(readFileSync(join(dir, "inbox", "existing.md"), "utf8"), "keep me");
+ });
+ });
+});
diff --git a/.claude/scripts/tests/mcp-context.test.ts b/.claude/scripts/tests/mcp-context.test.ts
new file mode 100644
index 0000000..907f4c5
--- /dev/null
+++ b/.claude/scripts/tests/mcp-context.test.ts
@@ -0,0 +1,272 @@
+/**
+ * Startup context resolution.
+ *
+ * The theme of every test here is that a WRONG answer at this layer is
+ * invisible. A vault root one directory too high, an index belonging to another
+ * vault, a memory root that escapes the tree — none of them throw. They all
+ * present downstream as "the vault knows nothing", which is the single most
+ * expensive failure shape in this whole layer.
+ *
+ * So the assertions are about refusal and about degradation: what gets rejected
+ * despite being written down, and what still boots when a discovery fails.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, dirname, resolve, sep } from "node:path";
+import { pathToFileURL } from "node:url";
+
+import {
+ resolveVaultRoot,
+ readManifest,
+ safeMemoryRoot,
+ createContext,
+ INSTRUCTIONS,
+ PROMPTS,
+} from "../lib/mcp-context.ts";
+
+function tmpVault(): string {
+ return mkdtempSync(join(tmpdir(), "ctx-"));
+}
+
+function put(dir: string, rel: string, content: string): void {
+ const full = join(dir, rel);
+ mkdirSync(dirname(full), { recursive: true });
+ writeFileSync(full, content, "utf8");
+}
+
+const CAPTURE = "---\ndate: 2026-07-26\nsource: mcp-capture\nscope: general\n---\n\n# m\n\nbody\n";
+
+function withVault(fn: (dir: string) => void): void {
+ const dir = tmpVault();
+ try {
+ fn(dir);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Vault root
+// ---------------------------------------------------------------------------
+
+describe("resolving the vault root", () => {
+ test("derives two levels up from .claude/scripts/", () => {
+ const url = pathToFileURL(join("/some", "vault", ".claude", "scripts", "om-mcp.ts")).href;
+ assert.equal(resolveVaultRoot(url, {}), resolve("/some/vault"));
+ });
+
+ test("an explicit override wins — one binary must be able to serve any vault", () => {
+ const url = pathToFileURL(join("/some", "vault", ".claude", "scripts", "om-mcp.ts")).href;
+ assert.equal(resolveVaultRoot(url, { OM_VAULT_PATH: "/elsewhere/other" }), resolve("/elsewhere/other"));
+ });
+
+ test("a bare VAULT_PATH is IGNORED — the name is too generic to claim", () => {
+ // Regression, found by a real session: `VAULT_PATH` was set on the machine
+ // for an unrelated reason, and the server silently served that vault
+ // instead of the one its launcher lives in — reporting the wrong vault's
+ // config, index and memory count as though they were correct.
+ const url = pathToFileURL(join("/a", "b", ".claude", "scripts", "om-mcp.ts")).href;
+ assert.equal(resolveVaultRoot(url, { VAULT_PATH: "/somewhere-else" }), resolve("/a/b"));
+ assert.equal(resolveVaultRoot(url, { OM_VAULT_PATH: "/deliberate" }), resolve("/deliberate"));
+ });
+
+ test("health can tell when an override disagrees with the launcher location", () => {
+ withVault((dir) => {
+ const ctx = createContext(dir, "/somewhere/else");
+ assert.equal(ctx.overriddenFrom, resolve("/somewhere/else"));
+ // No disagreement means nothing to report.
+ assert.equal(createContext(dir, dir).overriddenFrom, null);
+ });
+ });
+
+ test("a blank override is ignored rather than resolving to the cwd", () => {
+ // `resolve("")` is the process cwd, which would silently serve whatever
+ // directory the client happened to launch from.
+ const url = pathToFileURL(join("/a", "b", ".claude", "scripts", "om-mcp.ts")).href;
+ assert.equal(resolveVaultRoot(url, { OM_VAULT_PATH: " " }), resolve("/a/b"));
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Manifest
+// ---------------------------------------------------------------------------
+
+describe("reading the manifest", () => {
+ test("parses a real manifest", () => {
+ withVault((dir) => {
+ put(dir, "vault-manifest.json", JSON.stringify({ template: "obsidian-mind", memory_root: "memories" }));
+ assert.equal(readManifest(dir).template, "obsidian-mind");
+ });
+ });
+
+ test("a missing manifest is an empty object, not a throw", () => {
+ withVault((dir) => {
+ assert.deepEqual(readManifest(dir), {});
+ });
+ });
+
+ test("a malformed manifest is an empty object, not a throw", () => {
+ withVault((dir) => {
+ put(dir, "vault-manifest.json", "{ not json");
+ assert.deepEqual(readManifest(dir), {});
+ });
+ });
+
+ test("a manifest that is valid JSON but not an object is still an empty object", () => {
+ withVault((dir) => {
+ put(dir, "vault-manifest.json", "[1,2,3]");
+ assert.deepEqual(readManifest(dir), {});
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Memory root validation — the one with a blast radius
+// ---------------------------------------------------------------------------
+
+describe("validating a declared memory root", () => {
+ test("an ordinary name is taken as declared", () => {
+ assert.equal(safeMemoryRoot("knowledge"), "knowledge");
+ assert.equal(safeMemoryRoot("my-memories"), "my-memories");
+ assert.equal(safeMemoryRoot("mem_2"), "mem_2");
+ });
+
+ test("a traversal is refused — this is the whole reason the check exists", () => {
+ // Every capture writes through this value. A root that escapes the vault
+ // turns the capture tool into an arbitrary file write.
+ assert.equal(safeMemoryRoot(".."), "memories");
+ assert.equal(safeMemoryRoot("../../etc"), "memories");
+ assert.equal(safeMemoryRoot("../outside"), "memories");
+ });
+
+ test("a separator is refused in either style", () => {
+ assert.equal(safeMemoryRoot("a/b"), "memories");
+ assert.equal(safeMemoryRoot("a\\b"), "memories");
+ assert.equal(safeMemoryRoot("/absolute"), "memories");
+ assert.equal(safeMemoryRoot("C:\\Windows"), "memories");
+ });
+
+ test("empty, blank and non-string values fall back", () => {
+ assert.equal(safeMemoryRoot(""), "memories");
+ assert.equal(safeMemoryRoot(" "), "memories");
+ assert.equal(safeMemoryRoot("."), "memories");
+ assert.equal(safeMemoryRoot(null), "memories");
+ assert.equal(safeMemoryRoot(undefined), "memories");
+ assert.equal(safeMemoryRoot(42), "memories");
+ assert.equal(safeMemoryRoot({ root: "x" }), "memories");
+ });
+
+ test("a shell metacharacter is refused", () => {
+ assert.equal(safeMemoryRoot("mem;rm -rf"), "memories");
+ assert.equal(safeMemoryRoot("mem$(x)"), "memories");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Context assembly
+// ---------------------------------------------------------------------------
+
+describe("building the context", () => {
+ test("an unconfigured vault still resolves everything it can", () => {
+ withVault((dir) => {
+ const ctx = createContext(dir);
+ assert.equal(ctx.vaultRoot, dir);
+ assert.deepEqual(ctx.manifest, {});
+ assert.equal(ctx.memoryRoot, "memories");
+ assert.equal(ctx.qmdLauncher, null, "qmd is optional");
+ // Derived from the folder name rather than left null: a template that
+ // ships one literal gives every install the same store (#137).
+ assert.ok(ctx.qmdIndex, "an index name must be derived, never shared by default");
+ });
+ });
+
+ test("an explicit index pin wins over derivation", () => {
+ withVault((dir) => {
+ put(dir, "vault-manifest.json", JSON.stringify({ qmd_index: "pinned-name" }));
+ assert.equal(createContext(dir).qmdIndex, "pinned-name");
+ });
+ });
+
+ test("the derived index is per-vault, not a shared literal", () => {
+ withVault((a) => {
+ withVault((b) => {
+ const one = createContext(a).qmdIndex;
+ const two = createContext(b).qmdIndex;
+ assert.notEqual(one, two, "two vaults sharing an index is exactly #137");
+ });
+ });
+ });
+
+ test("a renamed memory folder is discovered, and the disagreement is visible", () => {
+ withVault((dir) => {
+ put(dir, "vault-manifest.json", JSON.stringify({ memory_root: "memories" }));
+ put(dir, join("knowledge", "2026", "07", "a.md"), CAPTURE);
+ const ctx = createContext(dir);
+ assert.equal(ctx.memoryRoot, "knowledge");
+ assert.equal(ctx.memory.healed, true);
+ assert.equal(ctx.memory.configured, "memories");
+ });
+ });
+
+ test("an unsafe declared root never reaches discovery", () => {
+ withVault((dir) => {
+ put(dir, "vault-manifest.json", JSON.stringify({ memory_root: "../escape" }));
+ const ctx = createContext(dir);
+ assert.equal(ctx.memoryRoot, "memories");
+ assert.ok(!ctx.memoryRoot.includes(".."));
+ assert.ok(!ctx.memoryRoot.includes(sep));
+ });
+ });
+
+ test("a present qmd launcher is found", () => {
+ withVault((dir) => {
+ put(dir, join(".claude", "scripts", "qmd-mcp.mjs"), "//");
+ assert.ok(createContext(dir).qmdLauncher);
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// The contract
+// ---------------------------------------------------------------------------
+
+describe("the injected contract", () => {
+ test("carries the prohibition that was measured to hold", () => {
+ // A prohibition propagates into the calling session reliably; a positive
+ // routing instruction does not. This is the half that actually enforces.
+ assert.match(INSTRUCTIONS, /claude\.ai session URLs/);
+ assert.match(INSTRUCTIONS, /Claude-Session:/);
+ assert.match(INSTRUCTIONS, /Co-Authored-By:/);
+ });
+
+ test("tells the session to preserve epistemic qualifiers rather than flatten them", () => {
+ assert.match(INSTRUCTIONS, /never/i);
+ assert.match(INSTRUCTIONS, /promote an inferred fact/);
+ });
+
+ test("stays small — every token is paid by every connecting session", () => {
+ assert.ok(
+ INSTRUCTIONS.length < 2000,
+ `contract is ${INSTRUCTIONS.length} bytes; it is injected into every session in every repo`,
+ );
+ });
+
+ test("names the tools it tells the session to call", () => {
+ // A contract referring to a tool that does not exist is worse than silence.
+ for (const tool of ["search", "expand"]) {
+ assert.ok(INSTRUCTIONS.includes(tool), `contract references ${tool}`);
+ }
+ });
+
+ test("prompts are user-invoked and both declare a required argument", () => {
+ assert.equal(PROMPTS.length, 2);
+ for (const p of PROMPTS) {
+ assert.ok(p.name && p.description);
+ assert.ok(p.arguments.length >= 1);
+ assert.equal(p.arguments[0]!.required, true);
+ }
+ });
+});
diff --git a/.claude/scripts/tests/mcp-exposure.test.ts b/.claude/scripts/tests/mcp-exposure.test.ts
new file mode 100644
index 0000000..fa3a933
--- /dev/null
+++ b/.claude/scripts/tests/mcp-exposure.test.ts
@@ -0,0 +1,589 @@
+/**
+ * The exposure policy, across every surface.
+ *
+ * The failure this suite is shaped around is a SECOND read path that skips the
+ * check the first one applies — a surface that walks the vault itself instead of
+ * resolving through `visibleFiles`, and so ignores the configured roots.
+ *
+ * So the sharpest tests here assert that the surfaces AGREE: a note absent from
+ * one is absent from all of them. A per-surface suite passes even when they have
+ * drifted apart, which is exactly the state worth catching.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync, writeFileSync, mkdirSync, symlinkSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, dirname } from "node:path";
+
+import {
+ resolveExposure,
+ isPrivate,
+ firstDescription,
+ isExposedPath,
+ visibleFiles,
+ allowedSearchPaths,
+ listResources,
+ resolveResourceUri,
+ vaultRelKeyRaw,
+} from "../lib/mcp-exposure.ts";
+import { vaultRelKey } from "../lib/mcp-qmd-client.ts";
+
+const NOTE = (desc = "a note") => `---\ndate: 2026-07-26\ndescription: "${desc}"\n---\n\n# n\n\nbody\n`;
+const PRIVATE_TAG = "---\ndate: 2026-07-26\ntags:\n - private\n---\n\n# secret\n\nbody\n";
+const PRIVATE_FLAG = "---\ndate: 2026-07-26\nprivate: true\n---\n\n# secret\n\nbody\n";
+
+function put(dir: string, rel: string, content = NOTE()): string {
+ const full = join(dir, rel);
+ mkdirSync(dirname(full), { recursive: true });
+ writeFileSync(full, content, "utf8");
+ return full;
+}
+
+function withVault(fn: (dir: string) => void): void {
+ const dir = mkdtempSync(join(tmpdir(), "exp-"));
+ try {
+ fn(dir);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+/** A vault with a declared root, undeclared ones, and a note tagged private. */
+function stocked(dir: string): void {
+ put(dir, "brain/Gotchas.md", NOTE("things that bit us"));
+ put(dir, "brain/SOUL.md", NOTE("identity"));
+ put(dir, "brain/Private Thing.md", PRIVATE_TAG);
+ put(dir, "reference/Arch.md");
+ put(dir, "work/1-1/Sarah.md", NOTE("a 1:1 note"));
+ put(dir, "people/Someone.md");
+}
+
+// ---------------------------------------------------------------------------
+// Policy resolution
+// ---------------------------------------------------------------------------
+
+describe("resolving the policy", () => {
+ test("an explicit declaration wins", () => {
+ withVault((dir) => {
+ const p = resolveExposure(dir, { mcp_exposed_roots: ["brain", "strategy"] });
+ assert.deepEqual([...p.roots], ["brain", "strategy"]);
+ assert.equal(p.source, "manifest");
+ });
+ });
+
+ test("a traversal root is refused; a path prefix is kept", () => {
+ withVault((dir) => {
+ const p = resolveExposure(dir, { mcp_exposed_roots: ["..", "../escape", "work/active", "brain"] });
+ assert.ok(!p.roots.some((r) => r.includes("..")), `${p.roots}`);
+ // Path prefixes are the granularity the vault speaks in — the manifest
+ // declares `work/active/`, not `work/`.
+ assert.ok(p.roots.includes("work/active"));
+ assert.ok(p.roots.includes("brain"));
+ });
+ });
+
+ test("a FILE glob yields its parent folder; a FOLDER glob is dropped", () => {
+ withVault((dir) => {
+ const p = resolveExposure(dir, {
+ mcp_exposed_roots: ["brain/*.md", "perf/competencies/*.md", "perf/h*-*/", "*/anything", "reference"],
+ });
+ // `brain/*.md` means the notes in brain — the parent is exactly right.
+ assert.ok(p.roots.includes("brain"), `${p.roots}`);
+ assert.ok(p.roots.includes("perf/competencies"));
+ // `perf/h*-*/` names SOME folders under perf. Truncating it to `perf`
+ // would serve every folder under it, including ones never declared.
+ assert.ok(!p.roots.includes("perf"), `bare perf must not appear: ${p.roots}`);
+ assert.ok(!p.roots.some((r) => r.includes("*")));
+ assert.ok(!p.roots.includes(""), "a leading glob contributes nothing");
+ });
+ });
+
+ test("the shipped manifest resolves to exactly what it declares", () => {
+ // Guards the same over-widening on the real template shape.
+ withVault((dir) => {
+ for (const d of ["work/active", "perf/brag", "perf/secret-draft", "brain"]) {
+ mkdirSync(join(dir, d), { recursive: true });
+ }
+ const p = resolveExposure(dir, {
+ user_content_roots: ["work/active/", "perf/brag/", "perf/h*-*/", "brain/*.md"],
+ });
+ assert.ok(!p.roots.includes("perf"), `${p.roots}`);
+ assert.ok(p.roots.includes("perf/brag"));
+ assert.ok(!p.roots.includes("perf/secret-draft"), "an undeclared sibling must not ride along");
+ });
+ });
+
+ test("undeclared exposure derives from the vault's own user_content_roots", () => {
+ // The user's notes, read by the user's own session. Declared at the
+ // granularity the manifest uses, so work/active is served without
+ // dragging in work/1-1.
+ withVault((dir) => {
+ for (const d of ["brain", "reference", "work/active", "work/1-1", "perf/brag"]) {
+ mkdirSync(join(dir, d), { recursive: true });
+ }
+ const p = resolveExposure(dir, {
+ user_content_roots: ["work/active/", "perf/brag/", "brain/*.md", "reference/"],
+ });
+ assert.equal(p.source, "derived");
+ assert.ok(p.roots.includes("work/active"), `${p.roots}`);
+ assert.ok(p.roots.includes("brain"));
+ assert.ok(!p.roots.includes("work/1-1"), "only what the vault declared as user content");
+ });
+ });
+
+ test("a declared root that does not exist on disk is dropped", () => {
+ withVault((dir) => {
+ mkdirSync(join(dir, "brain"), { recursive: true });
+ const p = resolveExposure(dir, { user_content_roots: ["brain/", "nowhere/"] });
+ assert.deepEqual([...p.roots], ["brain"]);
+ });
+ });
+
+ test("a vault declaring neither key falls back", () => {
+ withVault((dir) => {
+ mkdirSync(join(dir, "brain"), { recursive: true });
+ const p = resolveExposure(dir, {});
+ assert.equal(p.source, "fallback");
+ assert.deepEqual([...p.roots], ["brain"]);
+ });
+ });
+
+ test("the default is NARROW — an unconfigured vault is not surprised", () => {
+ withVault((dir) => {
+ const p = resolveExposure(dir, {});
+ assert.ok(!p.roots.includes("work"));
+ assert.ok(!p.roots.includes("people"));
+ assert.ok(!p.roots.includes("journal"));
+ });
+ });
+
+ test("never-expose keeps filenames with spaces and dots, which the root rule would reject", () => {
+ withVault((dir) => {
+ const p = resolveExposure(dir, { mcp_never_expose: ["North Star.md", "SOUL.md"] });
+ assert.ok(p.neverExpose.has("North Star.md"));
+ assert.ok(p.neverExpose.has("SOUL.md"));
+ });
+ });
+
+ test("never-expose ships EMPTY — the template must not impose one vault's sensitivities", () => {
+ withVault((dir) => {
+ assert.equal(resolveExposure(dir, {}).neverExpose.size, 0);
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Private
+// ---------------------------------------------------------------------------
+
+describe("private notes", () => {
+ test("a private tag withholds", () => {
+ withVault((dir) => assert.equal(isPrivate(put(dir, "a.md", PRIVATE_TAG)), true));
+ });
+
+ test("an explicit private flag withholds", () => {
+ withVault((dir) => assert.equal(isPrivate(put(dir, "a.md", PRIVATE_FLAG)), true));
+ });
+
+ test("an ordinary note does not", () => {
+ withVault((dir) => assert.equal(isPrivate(put(dir, "a.md")), false));
+ });
+
+ test("an UNREADABLE note withholds — a read error must never become an exposure", () => {
+ assert.equal(isPrivate(join(tmpdir(), "definitely-not-here-xyz.md")), true);
+ });
+
+ test("a note merely CONTAINING the word private in its body is not withheld", () => {
+ withVault((dir) => {
+ const f = put(dir, "a.md", "---\ndate: 2026-07-26\n---\n\n# n\n\nthis is a private matter\n");
+ assert.equal(isPrivate(f), false, "the marker is frontmatter, not prose");
+ });
+ });
+});
+
+describe("descriptions", () => {
+ test("pulls the frontmatter description", () => {
+ withVault((dir) => assert.equal(firstDescription(put(dir, "a.md", NOTE("hello there"))), "hello there"));
+ });
+
+ test("a note without one gets the fallback", () => {
+ withVault((dir) => {
+ const f = put(dir, "a.md", "---\ndate: 2026-07-26\n---\n\n# n\n");
+ assert.equal(firstDescription(f), "Vault note");
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// The surfaces must agree
+// ---------------------------------------------------------------------------
+
+describe("every surface applies the same policy", () => {
+ test("an undeclared folder is absent from files, search paths AND resources", () => {
+ withVault((dir) => {
+ stocked(dir);
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["brain", "reference"] });
+
+ const files = visibleFiles(dir, policy).map((f) => f.full.replace(/\\/g, "/"));
+ const search = [...allowedSearchPaths(dir, policy)];
+ const resources = listResources(dir, policy).map((r) => r.uri);
+
+ for (const [surface, entries] of [
+ ["visibleFiles", files],
+ ["allowedSearchPaths", search],
+ ["listResources", resources],
+ ] as const) {
+ assert.ok(!entries.some((e) => e.toLowerCase().includes("work/")), `${surface} served work/`);
+ assert.ok(!entries.some((e) => e.toLowerCase().includes("people/")), `${surface} served people/`);
+ assert.ok(!entries.some((e) => e.toLowerCase().includes("private")), `${surface} served a private note`);
+ }
+ });
+ });
+
+ test("EXCLUDING brain from the roots actually excludes it from resources", () => {
+ // The real defect: the enumerator read brain/ off disk directly, so a vault
+ // that declared roots WITHOUT brain/ still listed brain notes.
+ withVault((dir) => {
+ stocked(dir);
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["reference"] });
+ const resources = listResources(dir, policy);
+ assert.ok(!resources.some((r) => r.uri.toLowerCase().includes("brain")), "brain/ must be gone");
+ assert.ok(resources.some((r) => r.uri.toLowerCase().includes("reference")), "reference/ must remain");
+ });
+ });
+
+ test("never-expose removes a file from every surface at once", () => {
+ withVault((dir) => {
+ stocked(dir);
+ const policy = resolveExposure(dir, {
+ mcp_exposed_roots: ["brain"],
+ mcp_never_expose: ["SOUL.md"],
+ });
+ assert.ok(!visibleFiles(dir, policy).some((f) => f.label === "SOUL"));
+ assert.ok(!listResources(dir, policy).some((r) => r.uri.includes("SOUL")));
+ assert.ok(![...allowedSearchPaths(dir, policy)].some((p) => p.includes("soul")));
+ });
+ });
+
+ test("the search allow-set uses the same normalisation the search filter does", () => {
+ // If these two disagreed, every note with a space in its name would be
+ // permanently unsearchable while remaining readable.
+ withVault((dir) => {
+ put(dir, "brain/Key Decisions.md");
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["brain"] });
+ const allowed = allowedSearchPaths(dir, policy);
+ assert.ok(allowed.has(vaultRelKey(dir, join(dir, "brain/Key Decisions.md"))));
+ assert.ok(allowed.has("brain/key-decisions.md"));
+ });
+ });
+
+ test("nested notes inside an exposed root are reached", () => {
+ withVault((dir) => {
+ put(dir, "reference/deep/deeper/Note.md");
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["reference"] });
+ assert.equal(visibleFiles(dir, policy).length, 1);
+ });
+ });
+
+ test("dotfolders inside an exposed root are skipped", () => {
+ withVault((dir) => {
+ put(dir, "reference/.hidden/Note.md");
+ put(dir, "reference/Real.md");
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["reference"] });
+ assert.deepEqual(visibleFiles(dir, policy).map((f) => f.label), ["Real"]);
+ });
+ });
+
+ test("a missing exposed root is empty, not a throw", () => {
+ withVault((dir) => {
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["nope"] });
+ assert.deepEqual(visibleFiles(dir, policy), []);
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Memories are never ordinary notes
+// ---------------------------------------------------------------------------
+
+describe("the memory store is never part of the read surface", () => {
+ /** A vault holding one memory scoped to a DIFFERENT project. */
+ function withMemories(fn: (dir: string) => void, root = "memories"): void {
+ withVault((dir) => {
+ put(dir, "brain/Gotchas.md");
+ put(
+ dir,
+ `${root}/2026/07/a.md`,
+ "---\ndate: 2026-07-26\nsource: mcp-capture\nscope: project\nprojects: [other-app]\n---\n\n# another project private lesson\n\nbody\n",
+ );
+ fn(dir);
+ });
+ }
+
+ test("memories/ in user_content_roots does NOT expose them", () => {
+ // This is the real configuration, not a contrived one. `memories/` belongs
+ // in user_content_roots because that key is what /om-vault-upgrade copies
+ // across versions — leaving it out silently drops the store on upgrade.
+ // Exposure derives from the same key, so doing the right thing for
+ // upgrades used to expose every memory in the vault to every caller.
+ withMemories((dir) => {
+ const policy = resolveExposure(dir, { user_content_roots: ["brain/", "memories/"] }, "memories");
+ assert.ok(!policy.roots.includes("memories"));
+ assert.deepEqual(visibleFiles(dir, policy).map((f) => f.label), ["Gotchas"]);
+ assert.equal(listResources(dir, policy).length, 1);
+ assert.equal([...allowedSearchPaths(dir, policy)].filter((p) => p.startsWith("memories/")).length, 0);
+ });
+ });
+
+ test("naming it explicitly in mcp_exposed_roots does NOT override the exclusion", () => {
+ // There is no version of "serve memories as plain notes" that is safe to
+ // honour: it bypasses the declared-scope rule the whole layer rests on.
+ withMemories((dir) => {
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["brain", "memories"] }, "memories");
+ assert.ok(!policy.roots.includes("memories"), "config must not be able to ask for this");
+ assert.ok(!visibleFiles(dir, policy).some((f) => f.full.includes("memories")));
+ });
+ });
+
+ test("a RENAMED memory root is excluded too", () => {
+ // The exclusion follows the DISCOVERED root, not the configured name —
+ // otherwise renaming memories/ in Obsidian silently exposes the store.
+ withMemories((dir) => {
+ const policy = resolveExposure(dir, { user_content_roots: ["brain/", "knowledge/"] }, "knowledge");
+ assert.ok(!policy.roots.includes("knowledge"));
+ assert.ok(!visibleFiles(dir, policy).some((f) => f.full.includes("knowledge")));
+ }, "knowledge");
+ });
+
+ test("a hand-built policy naming the memory root still cannot walk it", () => {
+ withMemories((dir) => {
+ const forced = {
+ roots: ["brain", "memories"],
+ neverExpose: new Set<string>(),
+ source: "manifest" as const,
+ memoryRoot: "memories",
+ };
+ assert.ok(!visibleFiles(dir, forced).some((f) => f.full.includes("memories")));
+ assert.equal(isExposedPath(forced, "memories/2026/07/a.md"), false);
+ });
+ });
+
+ test("a memory cannot be read by URI either", () => {
+ withMemories((dir) => {
+ const policy = resolveExposure(dir, { user_content_roots: ["brain/", "memories/"] }, "memories");
+ assert.equal(resolveResourceUri(dir, policy, "vault://note/memories/2026/07/a.md"), null);
+ });
+ });
+});
+
+describe("path exposure checks", () => {
+ test("matches the first segment only", () => {
+ const policy = { roots: ["brain"], neverExpose: new Set<string>(), source: "manifest" as const, memoryRoot: "memories" };
+ assert.equal(isExposedPath(policy, "brain/Gotchas.md"), true);
+ assert.equal(isExposedPath(policy, "work/brain/Secret.md"), false, "brain must not match mid-path");
+ assert.equal(isExposedPath(policy, ""), false);
+ });
+
+ test("raw relative keys preserve case and spaces so a URI round-trips", () => {
+ assert.equal(vaultRelKeyRaw("C:/v", "C:/v/brain/Key Decisions.md"), "brain/Key Decisions.md");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Resource URIs are caller input, and re-checked
+// ---------------------------------------------------------------------------
+
+describe("resolving a resource URI", () => {
+ test("a legal URI resolves to the file", () => {
+ withVault((dir) => {
+ stocked(dir);
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["brain"] });
+ const uri = listResources(dir, policy).find((r) => r.uri.includes("Gotchas"))!.uri;
+ assert.ok(resolveResourceUri(dir, policy, uri));
+ });
+ });
+
+ test("a URI naming an out-of-scope note is refused even though it is well-formed", () => {
+ withVault((dir) => {
+ stocked(dir);
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["brain"] });
+ assert.equal(resolveResourceUri(dir, policy, "vault://note/work/1-1/Sarah.md"), null);
+ });
+ });
+
+ test("traversal is refused, encoded or not", () => {
+ withVault((dir) => {
+ stocked(dir);
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["brain"] });
+ for (const bad of [
+ "vault://note/../../../etc/passwd",
+ "vault://note/brain/../../work/1-1/Sarah.md",
+ "vault://note/%2e%2e/%2e%2e/work/1-1/Sarah.md",
+ "vault://note//etc/passwd",
+ "vault://note/C:/Windows/system.ini",
+ ]) {
+ assert.equal(resolveResourceUri(dir, policy, bad), null, `refused: ${bad}`);
+ }
+ });
+ });
+
+ test("a private note is refused even when its folder is exposed", () => {
+ withVault((dir) => {
+ stocked(dir);
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["brain"] });
+ assert.equal(resolveResourceUri(dir, policy, "vault://note/brain/Private Thing.md"), null);
+ });
+ });
+
+ test("a never-expose filename is refused by URI too", () => {
+ withVault((dir) => {
+ stocked(dir);
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["brain"], mcp_never_expose: ["SOUL.md"] });
+ assert.equal(resolveResourceUri(dir, policy, "vault://note/brain/SOUL.md"), null);
+ });
+ });
+
+ test("a SYMLINK out of an exposed folder is refused", () => {
+ // `resolve` collapses `..` but happily returns a path whose real target is
+ // outside the vault. A link planted in an exposed folder would otherwise
+ // read anything this process can. MCPVault shipped this bug for real.
+ withVault((dir) => {
+ stocked(dir);
+ const outside = put(dir, "..-outside/secret.md", NOTE("should never be readable"));
+ const link = join(dir, "brain", "innocent.md");
+ try {
+ symlinkSync(outside, link, "file");
+ } catch {
+ // Windows without developer mode cannot create symlinks; the guard is
+ // still compiled and exercised by the traversal cases above.
+ return;
+ }
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["brain"] });
+ assert.equal(
+ resolveResourceUri(dir, policy, "vault://note/brain/innocent.md"),
+ null,
+ "a link whose target escapes the exposed root must not resolve",
+ );
+ });
+ });
+
+ test("containment is against the DECLARED ROOT, not the first path segment", () => {
+ // A vault serving `work/active/` and not `work/1-1/`. Both share the segment
+ // `work`, so containing against the segment accepts a link that escapes the
+ // root the caller actually reached the note through.
+ withVault((dir) => {
+ const target = put(dir, "work/1-1/Sarah.md", NOTE("not served"));
+ mkdirSync(join(dir, "work", "active"), { recursive: true });
+ const link = join(dir, "work", "active", "innocent.md");
+ try {
+ symlinkSync(target, link, "file");
+ } catch {
+ return;
+ }
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["work/active"] });
+ assert.equal(
+ resolveResourceUri(dir, policy, "vault://note/work/active/innocent.md"),
+ null,
+ "still inside work/, but outside work/active/ — must be refused",
+ );
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Symlinks during ENUMERATION, not only on read-back
+// ---------------------------------------------------------------------------
+
+describe("enumeration follows the same containment rule as read-back", () => {
+ /** Build a vault with `brain/innocent.md` linking wherever `target` points. */
+ function linked(dir: string, target: string): boolean {
+ stocked(dir);
+ try {
+ symlinkSync(target, join(dir, "brain", "innocent.md"), "file");
+ return true;
+ } catch {
+ return false; // Windows without developer mode
+ }
+ }
+
+ test("a .md symlink escaping the vault is not enumerated by ANY surface", () => {
+ // The gap this closes: `statSync` follows links, so the walk pulled in a
+ // file from anywhere on disk. `resolveResourceUri` refused that same path,
+ // which is precisely the two-read-paths-disagree failure — and the leak was
+ // real, since `listResources` publishes each note's description.
+ withVault((dir) => {
+ const outside = put(dir, "..-outside/secret.md", NOTE("OUT-OF-VAULT-MARKER"));
+ if (!linked(dir, outside)) return;
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["brain"] });
+
+ const files = visibleFiles(dir, policy);
+ assert.ok(!files.some((f) => f.label === "innocent"), "not enumerated");
+
+ const resources = listResources(dir, policy);
+ assert.ok(
+ !resources.some((r) => r.description.includes("OUT-OF-VAULT-MARKER")),
+ "the outside file's description must not reach the resource listing",
+ );
+
+ assert.ok(
+ ![...allowedSearchPaths(dir, policy)].some((p) => p.includes("innocent")),
+ "and search must not accept a hit on it",
+ );
+ });
+ });
+
+ test("a symlink that stays INSIDE the exposed root is still served", () => {
+ // The fix must not cost ordinary use: a link within the root is a legitimate
+ // way to file the same note twice, and refusing it would be over-correction.
+ withVault((dir) => {
+ const inside = join(dir, "brain", "Gotchas.md");
+ if (!linked(dir, inside)) return;
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["brain"] });
+ assert.ok(
+ visibleFiles(dir, policy).some((f) => f.label === "innocent"),
+ "a contained link is a normal note",
+ );
+ });
+ });
+
+ test("a symlinked DIRECTORY escaping the root is not walked into", () => {
+ // The same hole one level up: the walk recurses through directories, so a
+ // linked folder would hand back every note underneath it.
+ withVault((dir) => {
+ stocked(dir);
+ put(dir, "..-elsewhere/Buried.md", NOTE("DIR-ESCAPE-MARKER"));
+ try {
+ symlinkSync(join(dir, "..-elsewhere"), join(dir, "brain", "sub"), "junction");
+ } catch {
+ return;
+ }
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["brain"] });
+ const files = visibleFiles(dir, policy);
+ assert.ok(!files.some((f) => f.label === "Buried"), "the linked tree must not be walked");
+ assert.ok(
+ !listResources(dir, policy).some((r) => r.description.includes("DIR-ESCAPE-MARKER")),
+ "and nothing under it may reach the listing",
+ );
+ });
+ });
+
+ test("a broken symlink is skipped rather than throwing the whole walk away", () => {
+ withVault((dir) => {
+ if (!linked(dir, join(dir, "brain", "Nothing Here.md"))) return;
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["brain"] });
+ const files = visibleFiles(dir, policy);
+ assert.ok(!files.some((f) => f.label === "innocent"), "a dangling link is not a note");
+ assert.ok(files.some((f) => f.label === "Gotchas"), "and the real notes still enumerate");
+ });
+ });
+
+ test("a nonexistent note and a foreign scheme are both null", () => {
+ withVault((dir) => {
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["brain"] });
+ assert.equal(resolveResourceUri(dir, policy, "vault://note/brain/Ghost.md"), null);
+ assert.equal(resolveResourceUri(dir, policy, "file:///etc/passwd"), null);
+ assert.equal(resolveResourceUri(dir, policy, "vault://other/brain/Gotchas.md"), null);
+ });
+ });
+});
diff --git a/.claude/scripts/tests/mcp-graph.test.ts b/.claude/scripts/tests/mcp-graph.test.ts
new file mode 100644
index 0000000..50c809c
--- /dev/null
+++ b/.claude/scripts/tests/mcp-graph.test.ts
@@ -0,0 +1,253 @@
+/**
+ * Graph traversal.
+ *
+ * The tests that matter are the ones about what `expand` leaves OUT. A backlink
+ * query is a listing query wearing a different hat: "what links to X" reports
+ * the titles of the notes doing the linking, so a graph walk over every file on
+ * disk would answer with notes the other surfaces do not serve.
+ *
+ * The other half is the resolution key. It exists because of a measured
+ * failure — search returned index paths, the model fed them into a read that
+ * only accepted URIs, and both surfaces failed — so it is tested against every
+ * form a caller might realistically produce.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, dirname } from "node:path";
+
+import { normalizeKey, resolveVisible, outboundLinks, expandNote } from "../lib/mcp-graph.ts";
+import { resolveExposure, visibleFiles, type VisibleFile } from "../lib/mcp-exposure.ts";
+
+function put(dir: string, rel: string, body: string): void {
+ const full = join(dir, rel);
+ mkdirSync(dirname(full), { recursive: true });
+ writeFileSync(full, body, "utf8");
+}
+
+function note(desc: string, body = ""): string {
+ return `---\ndate: 2026-07-26\ndescription: "${desc}"\n---\n\n# n\n\n${body}\n`;
+}
+
+function withVault(fn: (dir: string, files: VisibleFile[]) => void, roots = ["brain", "reference"]): void {
+ const dir = mkdtempSync(join(tmpdir(), "graph-"));
+ try {
+ // A small graph: Gotchas <-> Patterns, both linking to a note in work/,
+ // which the default roots do NOT serve. work/ also links back to Gotchas.
+ put(dir, "brain/Gotchas.md", note("things that bit us", "See [[Patterns]] and [[Roadmap]]."));
+ put(dir, "brain/Patterns.md", note("how we do things", "Related: [[Gotchas]]."));
+ put(dir, "brain/Key Decisions.md", note("choices", "Nothing links here."));
+ put(dir, "reference/Arch.md", note("architecture", "Builds on [[Patterns]]."));
+ put(dir, "work/Roadmap.md", note("what is planned", "Contradicts [[Gotchas]]."));
+ const policy = resolveExposure(dir, { mcp_exposed_roots: roots });
+ fn(dir, visibleFiles(dir, policy));
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Reference resolution
+// ---------------------------------------------------------------------------
+
+describe("normalising a reference", () => {
+ test("every form a caller might produce collapses to one key", () => {
+ // This is the compose bug: search speaks index paths, resources speak
+ // URIs, and a human speaks the title. All three must land on one note.
+ const forms = [
+ "Key Decisions",
+ "key decisions",
+ "Key-Decisions",
+ "Key_Decisions",
+ "brain/Key Decisions.md",
+ "myvault/brain/Key-Decisions.md",
+ "vault://note/brain/Key%20Decisions.md",
+ "vault://brain/Key%20Decisions.md",
+ "C:\\Dev\\v\\brain\\Key Decisions.md",
+ ];
+ const keys = new Set(forms.map(normalizeKey));
+ assert.equal(keys.size, 1, `expected one key, got ${[...keys].join(" | ")}`);
+ assert.equal([...keys][0], "keydecisions");
+ });
+
+ test("a malformed percent escape does not throw the lookup away", () => {
+ assert.equal(normalizeKey("brain/100%.md"), "100%");
+ });
+
+ test("empty input is an empty key rather than a match-anything", () => {
+ assert.equal(normalizeKey(""), "");
+ assert.equal(normalizeKey(null), "");
+ });
+
+ test("resolves a visible note from any form", () => {
+ withVault((_dir, files) => {
+ for (const form of ["Gotchas", "brain/Gotchas.md", "vault://note/brain/Gotchas.md", "GOTCHAS"]) {
+ assert.equal(resolveVisible(files, form)?.label, "Gotchas", `resolved ${form}`);
+ }
+ });
+ });
+
+ test("an out-of-scope note does not resolve, however it is named", () => {
+ withVault((_dir, files) => {
+ for (const form of ["Roadmap", "work/Roadmap.md", "vault://note/work/Roadmap.md"]) {
+ assert.equal(resolveVisible(files, form), null, `refused ${form}`);
+ }
+ });
+ });
+
+ test("an ambiguous reference returns null rather than guessing", () => {
+ // Picking one silently hands back the wrong note's content with no signal.
+ const files: VisibleFile[] = [
+ { full: "/v/a/Notes.md", label: "Notes", scope: "a" },
+ { full: "/v/b/Notes.md", label: "Notes", scope: "b" },
+ ];
+ assert.equal(resolveVisible(files, "Notes"), null);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Link extraction
+// ---------------------------------------------------------------------------
+
+describe("extracting links", () => {
+ test("plain, aliased and heading links all yield the target", () => {
+ assert.deepEqual(outboundLinks("[[A]] [[B|shown as]] [[C#section]]"), ["A", "B", "C"]);
+ });
+
+ test("duplicates collapse, case-insensitively, keeping first-seen order", () => {
+ assert.deepEqual(outboundLinks("[[A]] [[b]] [[a]] [[B]]"), ["A", "b"]);
+ });
+
+ test("empty and malformed links are ignored", () => {
+ assert.deepEqual(outboundLinks("[[]] [[ ]] [not a link] [[ok]]"), ["ok"]);
+ });
+
+ test("no links is an empty list, not a throw", () => {
+ assert.deepEqual(outboundLinks("nothing here"), []);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Expansion, and what it refuses to disclose
+// ---------------------------------------------------------------------------
+
+describe("expanding a note", () => {
+ test("returns links out and links back", () => {
+ withVault((_dir, files) => {
+ const r = expandNote(files, "Patterns");
+ assert.equal(r.note?.label, "Patterns");
+ assert.deepEqual(r.outbound, ["Gotchas"]);
+ // Both Gotchas and Arch link to Patterns.
+ assert.deepEqual(r.inbound.sort(), ["Arch", "Gotchas"]);
+ });
+ });
+
+ test("an outbound link outside the served set is COUNTED but never NAMED", () => {
+ withVault((_dir, files) => {
+ const r = expandNote(files, "Gotchas");
+ assert.equal(r.hiddenOutbound, 1, "the link to work/ must be counted");
+ assert.ok(!r.text.includes("Roadmap"), "and must not be named");
+ assert.match(r.text, /1 outside your scope/);
+ });
+ });
+
+ test("a backlink from an unserved note is not reported at all", () => {
+ // work/Roadmap.md links to Gotchas, but `expand` cannot follow the edge
+ // back, so naming it would offer a neighbour the caller cannot open.
+ withVault((_dir, files) => {
+ const r = expandNote(files, "Gotchas");
+ assert.ok(!r.inbound.includes("Roadmap"));
+ assert.ok(!r.text.includes("Roadmap"));
+ });
+ });
+
+ test("an unknown seed suggests only visible notes", () => {
+ withVault((_dir, files) => {
+ const r = expandNote(files, "Gotch");
+ assert.equal(r.note, null);
+ assert.match(r.text, /No visible note matches/);
+ assert.match(r.text, /Gotchas/);
+ });
+ });
+
+ test("a seed naming an unserved note resolves to nothing", () => {
+ withVault((_dir, files) => {
+ const r = expandNote(files, "Roadmap");
+ assert.equal(r.note, null);
+ // The near-miss list is built from served files only, so it cannot
+ // suggest a title `expand` would then refuse to open.
+ assert.ok(!r.text.includes("Did you mean: Roadmap"));
+ });
+ });
+
+ test("a note with no neighbours reads as empty rather than broken", () => {
+ withVault((_dir, files) => {
+ const r = expandNote(files, "Key Decisions");
+ assert.deepEqual(r.inbound, []);
+ assert.match(r.text, /Links out \(0 visible\)/);
+ assert.match(r.text, /- \(none visible\)/);
+ });
+ });
+
+ test("the header carries the scope and the description", () => {
+ withVault((_dir, files) => {
+ const r = expandNote(files, "Arch");
+ assert.match(r.text, /# Arch {2}\(reference\)/);
+ assert.match(r.text, /architecture/);
+ });
+ });
+
+ test("a seed given as a path or a URI expands the same note", () => {
+ withVault((_dir, files) => {
+ const byTitle = expandNote(files, "Patterns");
+ for (const form of ["brain/Patterns.md", "vault://note/brain/Patterns.md", "myvault/brain/Patterns.md"]) {
+ assert.equal(expandNote(files, form).note?.full, byTitle.note?.full, `matched via ${form}`);
+ }
+ });
+ });
+
+ test("an ambiguous seed reports the collision instead of guessing", () => {
+ // Regression: expandNote used `find`, so it returned the FIRST match and
+ // handed back the wrong note's neighbourhood with no signal — the exact
+ // behaviour resolveVisible refuses, broken by the module's primary path.
+ const files: VisibleFile[] = [
+ { full: "/v/brain/Notes.md", label: "Notes", scope: "brain" },
+ { full: "/v/reference/Notes.md", label: "Notes", scope: "reference" },
+ ];
+ const r = expandNote(files, "Notes");
+ assert.equal(r.note, null, "must not pick one");
+ assert.match(r.text, /matches 2 visible notes/);
+ assert.match(r.text, /brain\/Notes/);
+ assert.match(r.text, /reference\/Notes/);
+ assert.match(r.text, /Pass a path/, "must say how to disambiguate");
+ });
+
+ test("a path disambiguates what a bare title cannot", () => {
+ const files: VisibleFile[] = [
+ { full: "/v/brain/Notes.md", label: "Notes", scope: "brain" },
+ { full: "/v/reference/Notes.md", label: "Notes", scope: "reference" },
+ ];
+ assert.equal(expandNote(files, "reference/Notes.md").note?.scope, "reference");
+ });
+
+ test("an empty seed does not match an arbitrary note", () => {
+ withVault((_dir, files) => {
+ assert.equal(expandNote(files, "").note, null);
+ });
+ });
+
+ test("widening the roots reveals what was previously only a count", () => {
+ // The same query, the same graph, a different policy: proof the omission
+ // is the policy's doing and not a parsing failure.
+ withVault(
+ (_dir, files) => {
+ const r = expandNote(files, "Gotchas");
+ assert.equal(r.hiddenOutbound, 0);
+ assert.ok(r.outbound.includes("Roadmap"));
+ },
+ ["brain", "reference", "work"],
+ );
+ });
+});
diff --git a/.claude/scripts/tests/mcp-memory-bridge.test.ts b/.claude/scripts/tests/mcp-memory-bridge.test.ts
new file mode 100644
index 0000000..bd8a2fa
--- /dev/null
+++ b/.claude/scripts/tests/mcp-memory-bridge.test.ts
@@ -0,0 +1,294 @@
+/**
+ * The seam between the memory core and a real vault.
+ *
+ * Every function here has already failed once in a way that produced an EMPTY
+ * result rather than an error, which is the one outcome this system cannot tell
+ * apart from a correct one. So each block includes the specific shape that
+ * broke: a project note outside the exposed roots, a README whose name is not
+ * its project's name, an index that answers with memories scoped elsewhere.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, dirname } from "node:path";
+
+import {
+ resolvableNames,
+ loadMemoryDigests,
+ findNoteNamed,
+ callerPlatforms,
+ semanticMemoryOrder,
+} from "../lib/mcp-memory-bridge.ts";
+import type { VisibleFile } from "../lib/mcp-exposure.ts";
+import type { QmdClient } from "../lib/mcp-qmd-client.ts";
+
+function put(dir: string, rel: string, body: string): string {
+ const full = join(dir, rel);
+ mkdirSync(dirname(full), { recursive: true });
+ writeFileSync(full, body, "utf8");
+ return full;
+}
+
+function withVault(fn: (dir: string) => void): void {
+ const dir = mkdtempSync(join(tmpdir(), "bridge-"));
+ try {
+ fn(dir);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+const memory = (title: string, extra = ""): string =>
+ `---\ndate: 2026-07-26\nsource: mcp-capture\nscope: general\n${extra}\n---\n\n# ${title}\n\nthe body.\n`;
+
+/** A fake index that returns whatever files it was told to. */
+function fakeQmd(files: string[] | null, fail = false): QmdClient {
+ return {
+ ready: Promise.resolve(),
+ dispose: () => {},
+ alive: true,
+ call: async () => {
+ if (fail) throw new Error("index down");
+ return files === null ? {} : { structuredContent: { results: files.map((f) => ({ file: f })) } };
+ },
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Link resolution
+// ---------------------------------------------------------------------------
+
+describe("names a wikilink may resolve to", () => {
+ test("a file basename resolves", () => {
+ withVault((dir) => {
+ const full = put(dir, "brain/Gotchas.md", "---\ndate: 2026-07-26\n---\n\n# G\n");
+ const files: VisibleFile[] = [{ full, label: "Gotchas", scope: "brain" }];
+ assert.ok(resolvableNames(files).has("gotchas"));
+ });
+ });
+
+ test("a block-form alias resolves — this is the README case", () => {
+ // projects/pocket/README.md is reachable as [[pocket]] ONLY via its alias.
+ // Without this, every capture linking to a project manufactured a broken
+ // link, every time.
+ withVault((dir) => {
+ const full = put(dir, "projects/pocket/README.md", "---\naliases:\n - pocket\n - Pocket App\n---\n\n# P\n");
+ const names = resolvableNames([{ full, label: "README", scope: "projects" }]);
+ assert.ok(names.has("pocket"));
+ assert.ok(names.has("pocket app"));
+ assert.ok(names.has("readme"), "the basename still resolves too");
+ });
+ });
+
+ test("an inline-form alias resolves", () => {
+ withVault((dir) => {
+ const full = put(dir, "a/README.md", '---\naliases: ["atlas", \'Atlas API\']\n---\n\n# A\n');
+ const names = resolvableNames([{ full, label: "README", scope: "a" }]);
+ assert.ok(names.has("atlas"));
+ assert.ok(names.has("atlas api"));
+ });
+ });
+
+ test("an unreadable file still contributes its basename", () => {
+ const names = resolvableNames([{ full: join(tmpdir(), "gone-xyz.md"), label: "Ghost", scope: "x" }]);
+ assert.ok(names.has("ghost"));
+ });
+
+ test("a note with no aliases contributes exactly one name", () => {
+ withVault((dir) => {
+ const full = put(dir, "a.md", "---\ndate: 2026-07-26\n---\n\n# A\n");
+ assert.equal(resolvableNames([{ full, label: "A", scope: "x" }]).size, 1);
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Digests
+// ---------------------------------------------------------------------------
+
+describe("loading memory digests", () => {
+ test("reads title, body and facets", () => {
+ withVault((dir) => {
+ put(dir, "memories/2026/07/a.md", memory("tokens expire fast", "projects: [atlas]\nconfidence: verified"));
+ const [d] = loadMemoryDigests(dir, "memories");
+ assert.equal(d!.title, "tokens expire fast");
+ assert.equal(d!.body, "the body.");
+ assert.deepEqual(d!.projects, ["atlas"]);
+ assert.equal(d!.confidence, "verified");
+ assert.ok(d!.full.endsWith("a.md"), "the full path travels, so the index can be joined on it");
+ });
+ });
+
+ test("a human note in the memory folder is ignored, not governed", () => {
+ withVault((dir) => {
+ put(dir, "memories/2026/07/mine.md", "---\ndate: 2026-07-26\ntags: [note]\n---\n\n# mine\n\nhand written\n");
+ put(dir, "memories/2026/07/a.md", memory("agent written"));
+ const digests = loadMemoryDigests(dir, "memories");
+ assert.equal(digests.length, 1);
+ assert.equal(digests[0]!.title, "agent written");
+ });
+ });
+
+ test("an empty store is an empty list", () => {
+ withVault((dir) => assert.deepEqual(loadMemoryDigests(dir, "memories"), []));
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Finding the caller's own note
+// ---------------------------------------------------------------------------
+
+describe("finding a note by name", () => {
+ test("finds it wherever the vault happens to keep it", () => {
+ withVault((dir) => {
+ put(dir, "work/active/atlas.md", "---\n---\n\n# A\n");
+ assert.ok(findNoteNamed(dir, "atlas", "memories"));
+ });
+ });
+
+ test("does not walk the memory tree", () => {
+ // A memory is never a project note, and walking the store makes this cost
+ // grow with the number of memories for no benefit.
+ withVault((dir) => {
+ put(dir, "memories/2026/07/atlas.md", memory("atlas"));
+ assert.equal(findNoteNamed(dir, "atlas", "memories"), null);
+ });
+ });
+
+ test("skips dot-directories and node_modules", () => {
+ withVault((dir) => {
+ put(dir, ".git/atlas.md", "x");
+ put(dir, "node_modules/pkg/atlas.md", "x");
+ assert.equal(findNoteNamed(dir, "atlas", "memories"), null);
+ });
+ });
+
+ test("matching is case-insensitive", () => {
+ withVault((dir) => {
+ put(dir, "work/Atlas.md", "---\n---\n\n# A\n");
+ assert.ok(findNoteNamed(dir, "atlas", "memories"));
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Platforms — the boundary that took two tries
+// ---------------------------------------------------------------------------
+
+describe("the caller's platforms", () => {
+ test("read from the project's own note", () => {
+ withVault((dir) => {
+ put(dir, "work/atlas.md", "---\nplatforms: [ios, watchos]\n---\n\n# A\n");
+ assert.deepEqual(callerPlatforms(dir, "atlas", "memories"), ["ios", "watchos"]);
+ });
+ });
+
+ test("a project note OUTSIDE the exposed roots is still found", () => {
+ // The second failed version walked the exposed files only. A vault whose
+ // projects live outside a narrowed `mcp_exposed_roots` silently returned
+ // no platform, and every platform-scoped memory was withheld with no
+ // error anywhere.
+ withVault((dir) => {
+ put(dir, "work/deeply/nested/atlas.md", "---\nplatforms: [ios]\n---\n\n# A\n");
+ assert.deepEqual(callerPlatforms(dir, "atlas", "memories"), ["ios"]);
+ });
+ });
+
+ test("a single string platform is accepted as a one-item list", () => {
+ withVault((dir) => {
+ put(dir, "a/atlas.md", "---\nplatforms: ios\n---\n\n# A\n");
+ assert.deepEqual(callerPlatforms(dir, "atlas", "memories"), ["ios"]);
+ });
+ });
+
+ test("no note, no platforms key, and no caller all yield no platform", () => {
+ withVault((dir) => {
+ put(dir, "a/other.md", "---\nplatforms: [ios]\n---\n\n# O\n");
+ assert.deepEqual(callerPlatforms(dir, "atlas", "memories"), [], "no note for this project");
+ put(dir, "a/atlas.md", "---\ndate: 2026-07-26\n---\n\n# A\n");
+ assert.deepEqual(callerPlatforms(dir, "atlas", "memories"), [], "note without the key");
+ assert.deepEqual(callerPlatforms(dir, null, "memories"), [], "anonymous caller");
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Semantic ordering
+// ---------------------------------------------------------------------------
+
+describe("semantic ordering", () => {
+ const VAULT = "C:/v";
+ const mem = (rel: string) => ({ full: `C:/v/${rel}` });
+
+ test("reorders the visible set to match the index", () => {
+ const visible = [mem("memories/2026/07/a.md"), mem("memories/2026/07/b.md")];
+ return semanticMemoryOrder(
+ fakeQmd(["myvault/memories/2026/07/b.md", "myvault/memories/2026/07/a.md"]),
+ VAULT,
+ "q",
+ visible,
+ 5,
+ ).then((r) => {
+ assert.deepEqual(r?.map((m) => m.full), [visible[1]!.full, visible[0]!.full]);
+ });
+ });
+
+ test("a hit the visibility rule excluded is dropped SILENTLY", async () => {
+ // Not even a count: a memory scoped to another project is not a result
+ // this caller asked about, so it does not enter the response at all.
+ const visible = [mem("memories/2026/07/a.md")];
+ const r = await semanticMemoryOrder(
+ fakeQmd(["myvault/memories/2026/07/secret.md", "myvault/memories/2026/07/a.md"]),
+ VAULT,
+ "q",
+ visible,
+ 5,
+ );
+ assert.equal(r?.length, 1);
+ assert.ok(!JSON.stringify(r).includes("secret"));
+ });
+
+ test("a duplicate hit does not duplicate the memory", async () => {
+ const visible = [mem("memories/2026/07/a.md")];
+ const r = await semanticMemoryOrder(
+ fakeQmd(["myvault/memories/2026/07/a.md", "myvault/memories/2026/07/a.md"]),
+ VAULT,
+ "q",
+ visible,
+ 5,
+ );
+ assert.equal(r?.length, 1);
+ });
+
+ test("an index that is DOWN returns null so the caller falls back to lexical", async () => {
+ // qmd is optional in this template. An unavailable index must degrade
+ // ordering, never become "the vault knows nothing".
+ const r = await semanticMemoryOrder(fakeQmd(null, true), VAULT, "q", [mem("memories/a.md")], 5);
+ assert.equal(r, null);
+ });
+
+ test("an index with no structured results returns null rather than an empty list", async () => {
+ // Returning [] would present as "no relevant memories", which is a
+ // different and wrong claim.
+ assert.equal(await semanticMemoryOrder(fakeQmd(null), VAULT, "q", [mem("memories/a.md")], 5), null);
+ });
+
+ test("hits that are ALL invisible return null, not an empty result", async () => {
+ const r = await semanticMemoryOrder(fakeQmd(["myvault/memories/other.md"]), VAULT, "q", [mem("memories/a.md")], 5);
+ assert.equal(r, null, "fall back to lexical rather than assert nothing is relevant");
+ });
+
+ test("paths with spaces join correctly against the index's dashed form", async () => {
+ const visible = [{ full: "C:/v/memories/2026/07/2026-07-26 a lesson.md" }];
+ const r = await semanticMemoryOrder(
+ fakeQmd(["myvault/memories/2026/07/2026-07-26-a-lesson.md"]),
+ VAULT,
+ "q",
+ visible,
+ 5,
+ );
+ assert.equal(r?.length, 1, "the index flattens spaces; the join must survive that");
+ });
+});
diff --git a/.claude/scripts/tests/mcp-protocol.test.ts b/.claude/scripts/tests/mcp-protocol.test.ts
new file mode 100644
index 0000000..a6d0a3f
--- /dev/null
+++ b/.claude/scripts/tests/mcp-protocol.test.ts
@@ -0,0 +1,283 @@
+/**
+ * Framing and the identity handshake.
+ *
+ * The handshake is the reason this file is a class rather than module state.
+ * The prototype kept the caller's roots in module scope, which made the
+ * identity race untestable — so it took a live client to find that
+ * `resources/list` arrives BEFORE the server knows who is asking, and that
+ * announcing a list-changed notification afterwards does not make the client
+ * re-fetch. A scoping layer that answers before it knows the caller is not a
+ * scoping layer.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+
+import { McpSession, type Handlers } from "../lib/mcp-protocol.ts";
+
+interface Sent {
+ jsonrpc?: string;
+ id?: number | string;
+ method?: string;
+ result?: unknown;
+ error?: { code?: number; message?: string };
+}
+
+function session(handlers: Handlers = {}, identityTimeoutMs = 50) {
+ const sent: Sent[] = [];
+ const s = new McpSession({ send: (m) => sent.push(m as Sent), handlers, identityTimeoutMs });
+ return { s, sent };
+}
+
+const ROOT = "file:///C:/Dev/atlas";
+
+/** Drive a full handshake and return the session. */
+async function handshaken(handlers: Handlers = {}, uri = ROOT) {
+ const { s, sent } = session(handlers);
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }));
+ const ask = sent.find((m) => m.method === "roots/list");
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", id: ask!.id, result: { roots: [{ uri }] } }));
+ return { s, sent };
+}
+
+// ---------------------------------------------------------------------------
+// Framing
+// ---------------------------------------------------------------------------
+
+describe("framing", () => {
+ test("dispatches a request to its handler and replies with the result", async () => {
+ const { s, sent } = session({ ping: (id) => s.ok(id, { pong: true }) });
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "ping" }));
+ assert.deepEqual(sent, [{ jsonrpc: "2.0", id: 1, result: { pong: true } }]);
+ });
+
+ test("blank and malformed lines are IGNORED, never answered", async () => {
+ // A line that does not parse has no id to reply to, so inventing one puts
+ // a message on the wire the client never asked for.
+ const { s, sent } = session();
+ for (const line of ["", " ", "\n", "not json", "{oops", "null", "[1,2]"]) {
+ await s.handleLine(line);
+ }
+ assert.deepEqual(sent, []);
+ });
+
+ test("an unknown method returns method-not-found", async () => {
+ const { s, sent } = session();
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", id: 7, method: "nope" }));
+ assert.equal(sent[0]!.error?.code, -32601);
+ assert.match(String(sent[0]!.error?.message), /no method nope/);
+ });
+
+ test("a notification with no id gets no reply", async () => {
+ const { s, sent } = session({ ping: () => assert.fail("must not run") });
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", method: "notifications/something" }));
+ assert.deepEqual(sent, []);
+ });
+
+ test("a throwing handler becomes an error response, not a crash", async () => {
+ const { s, sent } = session({
+ boom: () => {
+ throw new Error("kaboom");
+ },
+ });
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", id: 3, method: "boom" }));
+ assert.equal(sent[0]!.error?.code, -32603);
+ assert.match(String(sent[0]!.error?.message), /kaboom/);
+ });
+
+ test("a rejecting async handler is caught the same way", async () => {
+ const { s, sent } = session({ boom: async () => Promise.reject(new Error("async kaboom")) });
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", id: 4, method: "boom" }));
+ assert.match(String(sent[0]!.error?.message), /async kaboom/);
+ });
+
+ test("an error message carrying a local path is sanitised before it leaves", async () => {
+ // Error text lands in the calling session and may be pasted into a commit.
+ const { s, sent } = session({
+ boom: () => {
+ throw new Error("ENOENT, lstat 'C:\\Users\\someone\\vault\\a.md'");
+ },
+ });
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", id: 5, method: "boom" }));
+ const msg = String(sent[0]!.error?.message);
+ assert.ok(!msg.includes("someone"), msg);
+ assert.match(msg, /<path>/);
+ });
+
+ test("an id of 0 is a real id, not a missing one", async () => {
+ const { s, sent } = session({ ping: (id) => s.ok(id, "ok") });
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", id: 0, method: "ping" }));
+ assert.equal(sent.length, 1);
+ assert.equal(sent[0]!.id, 0);
+ });
+
+ test("a string id round-trips unchanged", async () => {
+ const { s, sent } = session({ ping: (id) => s.ok(id, "ok") });
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", id: "abc", method: "ping" }));
+ assert.equal(sent[0]!.id, "abc");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Identity
+// ---------------------------------------------------------------------------
+
+describe("the identity handshake", () => {
+ test("initialized triggers a roots request", async () => {
+ const { s, sent } = session();
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }));
+ const ask = sent.find((m) => m.method === "roots/list");
+ assert.ok(ask, "the server must ask who is calling");
+ assert.ok(typeof ask!.id === "number" && ask!.id >= 10_000, "server ids must not collide with the client's");
+ });
+
+ test("the roots reply establishes the caller", async () => {
+ const { s } = await handshaken();
+ assert.equal(s.identified, true);
+ assert.equal(s.project, "atlas");
+ });
+
+ test("a caller that never answers stays ANONYMOUS rather than hanging", async () => {
+ // The cap is the whole point: an unhelpful answer beats a hung server.
+ const { s } = session({}, 10);
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }));
+ await s.identityReady();
+ assert.equal(s.identified, false);
+ assert.equal(s.project, null, "anonymous — and downstream that means general-scope only");
+ });
+
+ test("identityReady resolves immediately once identity is known", async () => {
+ const { s } = await handshaken();
+ // A 50ms cap would make this measurably slow if it were still racing.
+ const before = process.hrtime.bigint();
+ await s.identityReady();
+ const ms = Number(process.hrtime.bigint() - before) / 1e6;
+ assert.ok(ms < 20, `resolved in ${ms}ms`);
+ });
+
+ test("a scope-dependent request waits for identity before it is served", async () => {
+ // This is the race: resources/list arrives before roots/list comes back.
+ const order: string[] = [];
+ const { s, sent } = session({
+ "resources/list": async (id) => {
+ await s.identityReady();
+ order.push(`served:${s.project}`);
+ s.ok(id, { resources: [] });
+ },
+ });
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }));
+ const pending = s.handleLine(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "resources/list" }));
+ const ask = sent.find((m) => m.method === "roots/list");
+ order.push("roots-answered");
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", id: ask!.id, result: { roots: [{ uri: ROOT }] } }));
+ await pending;
+ assert.deepEqual(order, ["roots-answered", "served:atlas"], "the listing must not be served unscoped");
+ });
+
+ test("an empty roots reply is identified-but-anonymous", async () => {
+ const { s, sent } = session();
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }));
+ const ask = sent.find((m) => m.method === "roots/list");
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", id: ask!.id, result: { roots: [] } }));
+ assert.equal(s.identified, true);
+ assert.equal(s.project, null);
+ });
+
+ test("a malformed roots reply does not poison the session", async () => {
+ const { s, sent } = session();
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }));
+ const ask = sent.find((m) => m.method === "roots/list");
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", id: ask!.id, result: { roots: "not an array" } }));
+ assert.deepEqual(s.roots, []);
+ assert.equal(s.project, null);
+ });
+
+ test("a response to an id we did NOT issue is ignored", async () => {
+ const { s, sent } = session();
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }));
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", id: 999, result: { roots: [{ uri: ROOT }] } }));
+ assert.equal(s.identified, false, "a stray response must not establish identity");
+ assert.equal(s.project, null);
+ });
+
+ test("establishing a caller announces list_changed", async () => {
+ const { sent } = await handshaken();
+ assert.ok(sent.some((m) => m.method === "notifications/resources/list_changed"));
+ });
+
+ test("roots changing mid-session re-asks and rescopes", async () => {
+ const { s, sent } = await handshaken();
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", method: "notifications/roots/list_changed" }));
+ const asks = sent.filter((m) => m.method === "roots/list");
+ assert.equal(asks.length, 2, "a changed root must be re-read, not assumed stable");
+ await s.handleLine(
+ JSON.stringify({ jsonrpc: "2.0", id: asks[1]!.id, result: { roots: [{ uri: "file:///C:/Dev/beacon" }] } }),
+ );
+ assert.equal(s.project, "beacon");
+ });
+
+ test("a request during a roots REFRESH waits for the new identity", async () => {
+ // The stale-identity race, one step later in the lifecycle than the first
+ // one. Identity was already established, so identityReady() returned
+ // immediately and a call arriving between the list_changed notification
+ // and the roots reply was served as the PREVIOUS project — the wrong
+ // scope, silently.
+ const served: string[] = [];
+ const { s, sent } = session({
+ "tools/call": async (id) => {
+ await s.identityReady();
+ served.push(String(s.project));
+ s.ok(id, {});
+ },
+ });
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }));
+ const first = sent.find((m) => m.method === "roots/list");
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", id: first!.id, result: { roots: [{ uri: ROOT }] } }));
+ assert.equal(s.project, "atlas");
+
+ // Client says the roots changed; a call races the re-fetch.
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", method: "notifications/roots/list_changed" }));
+ const pending = s.handleLine(JSON.stringify({ jsonrpc: "2.0", id: 42, method: "tools/call" }));
+ const second = sent.filter((m) => m.method === "roots/list")[1];
+ await s.handleLine(
+ JSON.stringify({ jsonrpc: "2.0", id: second!.id, result: { roots: [{ uri: "file:///C:/Dev/beacon" }] } }),
+ );
+ await pending;
+ assert.deepEqual(served, ["beacon"], "must be served as the NEW project, never the old one");
+ });
+
+ test("a refresh the client never answers still releases, as anonymous-ish", async () => {
+ // The cap has to apply to the refresh gate too, or a client that announces
+ // a change and never answers hangs every subsequent call.
+ const { s, sent } = session({}, 30);
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }));
+ const first = sent.find((m) => m.method === "roots/list");
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", id: first!.id, result: { roots: [{ uri: ROOT }] } }));
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", method: "notifications/roots/list_changed" }));
+ await s.identityReady(); // must not hang
+ assert.equal(s.project, "atlas", "the last known identity stands rather than going blank");
+ });
+
+ test("the onIdentified hook fires with the roots", async () => {
+ const seen: string[] = [];
+ const sent: Sent[] = [];
+ const s = new McpSession({
+ send: (m) => sent.push(m as Sent),
+ handlers: {},
+ onIdentified: (roots) => seen.push(...roots.map((r) => String(r.uri))),
+ });
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }));
+ const ask = sent.find((m) => m.method === "roots/list");
+ await s.handleLine(JSON.stringify({ jsonrpc: "2.0", id: ask!.id, result: { roots: [{ uri: ROOT }] } }));
+ assert.deepEqual(seen, [ROOT]);
+ });
+
+ test("two sessions do not share identity", async () => {
+ // The prototype kept this in module scope, which is what made the race
+ // impossible to test in the first place.
+ const a = await handshaken({}, "file:///C:/Dev/atlas");
+ const b = await handshaken({}, "file:///C:/Dev/beacon");
+ assert.equal(a.s.project, "atlas");
+ assert.equal(b.s.project, "beacon");
+ });
+});
diff --git a/.claude/scripts/tests/mcp-qmd-client.test.ts b/.claude/scripts/tests/mcp-qmd-client.test.ts
new file mode 100644
index 0000000..7b55f98
--- /dev/null
+++ b/.claude/scripts/tests/mcp-qmd-client.test.ts
@@ -0,0 +1,284 @@
+/**
+ * The search filter.
+ *
+ * qmd indexes the whole vault, so `scopeResults` is the only thing that keeps
+ * `search` agreeing with the other read surfaces about which notes exist.
+ *
+ * The tests are adversarial by design: most hand `scopeResults` a result set
+ * containing a hit outside the served set and assert on its ABSENCE. An
+ * assertion that the right hit came back passes just as well when the filter
+ * does nothing at all, which is why the absence cases carry the weight.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { join } from "node:path";
+
+import {
+ pathKey,
+ vaultRelKey,
+ qmdRelKey,
+ scopeResults,
+ subQueries,
+ createQmdClient,
+ type QmdHit,
+} from "../lib/mcp-qmd-client.ts";
+
+const VAULT = "C:/Dev/myvault";
+
+/** The set a caller scoped to `brain/` and `projects/` would get. */
+const ALLOWED = new Set(["brain/gotchas.md", "brain/key-decisions.md", "projects/pocket/readme.md"]);
+
+function hit(file: string, extra: Partial<QmdHit> = {}): QmdHit {
+ return { file, score: 0.9, title: "t", snippet: "s", ...extra };
+}
+
+// ---------------------------------------------------------------------------
+// Path identity
+// ---------------------------------------------------------------------------
+
+describe("path identity", () => {
+ test("separator style and case do not change identity", () => {
+ assert.equal(pathKey("Brain\\Gotchas.md"), "brain/gotchas.md");
+ });
+
+ test("spaces collapse to hyphens, because that is what the index does", () => {
+ // `brain/Key Decisions.md` and `brain/Key-Decisions.md` are one document.
+ // If these compared unequal, every note with a space in its name would be
+ // permanently invisible to search while remaining readable as a resource.
+ assert.equal(pathKey("brain/Key Decisions.md"), "brain/key-decisions.md");
+ });
+
+ test("a vault-relative key strips the root", () => {
+ assert.equal(vaultRelKey(VAULT, "C:/Dev/myvault/brain/Gotchas.md"), "brain/gotchas.md");
+ assert.equal(vaultRelKey(VAULT + "/", "C:\\Dev\\myvault\\brain\\Gotchas.md"), "brain/gotchas.md");
+ });
+
+ test("a path outside the vault keeps its full key rather than being mangled into one", () => {
+ const k = vaultRelKey(VAULT, "C:/Dev/other/secret.md");
+ assert.equal(k, "c:/dev/other/secret.md");
+ assert.ok(!ALLOWED.has(k), "an outside path must never accidentally match an allowed key");
+ });
+
+ test("a qmd path drops its collection prefix", () => {
+ assert.equal(qmdRelKey("myvault/brain/Gotchas.md"), "brain/gotchas.md");
+ });
+
+ test("a qmd path with no prefix is left alone", () => {
+ assert.equal(qmdRelKey("gotchas.md"), "gotchas.md");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Sub-query shaping
+// ---------------------------------------------------------------------------
+
+describe("building sub-queries", () => {
+ test("lexical and vector always go out together", () => {
+ const types = subQueries("caching").map((s) => s.type);
+ assert.ok(types.includes("lex"));
+ assert.ok(types.includes("vec"));
+ });
+
+ test("a question-shaped query also gets hyde", () => {
+ // hyde writes a hypothetical answer and matches against that, which is
+ // what finds the note whose title shares no words with the question.
+ for (const q of [
+ "why did we choose postgres over mysql",
+ "how does the retry envelope behave",
+ "what happens when the lease expires?",
+ ]) {
+ assert.ok(subQueries(q).some((s) => s.type === "hyde"), q);
+ }
+ });
+
+ test("a keyword lookup does NOT pay for hyde", () => {
+ // It runs a local generation model. Lexical matching is already the right
+ // tool for a two-word lookup, so the cost buys nothing.
+ for (const q of ["caching", "deploy runbook", "retry envelope", "postgres"]) {
+ assert.ok(!subQueries(q).some((s) => s.type === "hyde"), q);
+ }
+ });
+
+ test("a long non-question stays lex + vec", () => {
+ const q = "connection pool timeout during the nightly batch reconciliation job";
+ assert.deepEqual(subQueries(q).map((s) => s.type), ["lex", "vec"]);
+ });
+
+ test("every sub-query carries the trimmed text", () => {
+ for (const s of subQueries(" why did we do this ")) assert.equal(s.query, "why did we do this");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// The filter
+// ---------------------------------------------------------------------------
+
+describe("scoping results", () => {
+ test("an in-scope hit comes back", () => {
+ const r = scopeResults([hit("myvault/brain/Gotchas.md")], ALLOWED);
+ assert.match(r.text, /brain\/Gotchas\.md/);
+ assert.equal(r.withheld, 0);
+ });
+
+ test("an out-of-scope hit does NOT come back, and is counted", () => {
+ // A note the index matched, sitting in a folder this vault does not serve.
+ // The index knows nothing of the policy, so this filter is the only thing
+ // between the two.
+ const r = scopeResults([hit("myvault/work/1-1/2026-07-26 Sarah.md")], ALLOWED);
+ assert.ok(!r.text.includes("Sarah"), "the withheld note must not appear at all");
+ assert.ok(!r.text.includes("work/1-1"), "and neither must its path");
+ assert.equal(r.withheld, 1);
+ });
+
+ test("a mixed result set returns only the permitted half and reports the rest", () => {
+ const r = scopeResults(
+ [
+ hit("myvault/brain/Gotchas.md"),
+ hit("myvault/people/Someone.md"),
+ hit("myvault/projects/pocket/README.md"),
+ hit("myvault/journal/2026-07-26.md"),
+ ],
+ ALLOWED,
+ );
+ assert.match(r.text, /Gotchas/);
+ assert.match(r.text, /pocket/);
+ assert.ok(!r.text.includes("people/"), "people/ is not served");
+ assert.ok(!r.text.includes("journal/"), "journal/ is not served");
+ assert.equal(r.withheld, 2);
+ assert.equal(r.total, 4);
+ assert.match(r.text, /2 further match/);
+ });
+
+ test("everything withheld says so, rather than pretending the vault is empty", () => {
+ // "(no results)" here would be a lie that sends the user looking for a
+ // missing note instead of a scoping decision.
+ const r = scopeResults([hit("myvault/people/A.md"), hit("myvault/people/B.md")], ALLOWED);
+ assert.match(r.text, /withheld as out of scope/);
+ assert.ok(!/^\(no results\)$/.test(r.text));
+ assert.equal(r.withheld, 2);
+ });
+
+ test("a genuinely empty index is distinguishable from a fully withheld one", () => {
+ const r = scopeResults([], ALLOWED);
+ assert.equal(r.text, "(no results)");
+ assert.equal(r.withheld, 0);
+ });
+
+ test("missing structured results REFUSE rather than fall back to the text summary", () => {
+ // qmd also returns a human-readable summary that carries note paths. Using
+ // it when the structured field is absent is precisely the unfiltered path.
+ for (const bad of [undefined, null, "some summary text", { results: [] }, 42]) {
+ const r = scopeResults(bad, ALLOWED);
+ assert.match(r.text, /could not be scope-checked/, `refused for ${JSON.stringify(bad)}`);
+ }
+ });
+
+ test("an empty allow-set withholds everything — a caller with no scope sees nothing", () => {
+ const r = scopeResults([hit("myvault/brain/Gotchas.md")], new Set());
+ assert.equal(r.withheld, 1);
+ assert.ok(!r.text.includes("Gotchas"));
+ });
+
+ test("a hit with no file cannot slip through", () => {
+ const r = scopeResults([{ score: 1, snippet: "unmatchable" } as QmdHit], ALLOWED);
+ assert.equal(r.withheld, 1);
+ assert.ok(!r.text.includes("unmatchable"));
+ });
+
+ test("basename collision does not admit a note from an out-of-scope folder", () => {
+ // `projects/pocket/README.md` is allowed. A README elsewhere is not, and
+ // matching on basename rather than full path would have admitted it.
+ const r = scopeResults([hit("myvault/reference/runbooks/README.md")], ALLOWED);
+ assert.equal(r.withheld, 1);
+ assert.ok(!r.text.includes("runbooks"));
+ });
+
+ test("a note whose name contains spaces is matched, not silently dropped", () => {
+ const allowed = new Set(["brain/key-decisions.md"]);
+ const r = scopeResults([hit("myvault/brain/Key Decisions.md")], allowed);
+ assert.equal(r.withheld, 0);
+ assert.match(r.text, /Key Decisions/);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Liveness
+// ---------------------------------------------------------------------------
+
+describe("client liveness", () => {
+ test("a client whose child exits reports itself dead", async () => {
+ // The caller memoises this client. Without a liveness signal, one qmd
+ // crash leaves a dead client in place whose pending map rejects every
+ // later call — search stays broken for the life of the server.
+ const c = createQmdClient(process.cwd(), join(process.cwd(), "definitely-not-a-launcher.mjs"));
+ assert.equal(c.alive, true, "alive until proven otherwise");
+ // Spawning a missing script fails asynchronously; wait for the signal.
+ await new Promise((r) => setTimeout(r, 400));
+ assert.equal(c.alive, false, "a failed launcher must mark the client dead");
+ c.dispose();
+ });
+
+ test("dispose marks it dead too", () => {
+ const c = createQmdClient(process.cwd(), join(process.cwd(), "also-missing.mjs"));
+ c.dispose();
+ assert.equal(c.alive, false);
+ });
+
+ test("a call against a dead client rejects rather than hanging", async () => {
+ const c = createQmdClient(process.cwd(), join(process.cwd(), "still-missing.mjs"));
+ await new Promise((r) => setTimeout(r, 400));
+ await assert.rejects(() => c.call("tools/call", {}), /qmd/i);
+ c.dispose();
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Rendering
+// ---------------------------------------------------------------------------
+
+describe("rendering", () => {
+ test("limit caps the hits shown but the withheld count still reflects the policy", () => {
+ const hits = [hit("myvault/brain/Gotchas.md"), hit("myvault/brain/Key Decisions.md")];
+ const r = scopeResults([...hits, hit("myvault/people/X.md")], ALLOWED, 1);
+ assert.equal(r.withheld, 1, "withheld counts the POLICY, not the limit");
+ assert.equal((r.text.match(/^\[\d\]/gm) ?? []).length, 1);
+ });
+
+ test("a limit of zero returns no hits without throwing", () => {
+ const r = scopeResults([hit("myvault/brain/Gotchas.md")], ALLOWED, 0);
+ assert.match(r.text, /no results/);
+ });
+
+ test("a negative limit is treated as zero rather than slicing from the end", () => {
+ // `slice(-1)` would return the LAST hit — quietly returning something the
+ // caller did not ask for.
+ const r = scopeResults([hit("myvault/brain/Gotchas.md")], ALLOWED, -1);
+ assert.match(r.text, /no results/);
+ });
+
+ test("a long snippet is truncated and whitespace normalised", () => {
+ const r = scopeResults([hit("myvault/brain/Gotchas.md", { snippet: "x\n\n y".repeat(500) })], ALLOWED);
+ assert.ok(r.text.length < 2000);
+ assert.ok(!r.text.includes("\n\n y"), "internal whitespace is collapsed");
+ });
+
+ test("the whole response is bounded even with many large hits", () => {
+ const many = Array.from({ length: 50 }, () => hit("myvault/brain/Gotchas.md", { snippet: "z".repeat(700) }));
+ const r = scopeResults(many, ALLOWED, 50);
+ assert.ok(r.text.length <= 6200, `response was ${r.text.length} bytes`);
+ });
+
+ test("score renders as a percentage and a missing score does not print NaN", () => {
+ const r = scopeResults([hit("myvault/brain/Gotchas.md", { score: 0.93 })], ALLOWED);
+ assert.match(r.text, /score 93%/);
+ const noScore = scopeResults([{ file: "myvault/brain/Gotchas.md" }], ALLOWED);
+ assert.match(noScore.text, /score 0%/);
+ assert.ok(!noScore.text.includes("NaN"));
+ });
+
+ test("a line number is included when present and omitted when not", () => {
+ assert.match(scopeResults([hit("myvault/brain/Gotchas.md", { line: 42 })], ALLOWED).text, /Gotchas\.md:42/);
+ assert.ok(!scopeResults([hit("myvault/brain/Gotchas.md")], ALLOWED).text.includes(".md:"));
+ });
+});
diff --git a/.claude/scripts/tests/memory-discover.test.ts b/.claude/scripts/tests/memory-discover.test.ts
new file mode 100644
index 0000000..7d0e290
--- /dev/null
+++ b/.claude/scripts/tests/memory-discover.test.ts
@@ -0,0 +1,492 @@
+/**
+ * Discovery and self-healing.
+ *
+ * Every defect this module exists to catch is SILENT: a renamed folder, a moved
+ * launcher, an index registered against someone else's vault and a store that
+ * has forked in two all present identically as "no results". So the assertions
+ * here are mostly about the *diagnostic* — that the layer notices, says which
+ * state it is in, and names the fix — not merely that it returns a value.
+ *
+ * The known-negative cases are load-bearing: an unregistered index and a project
+ * with no note in the vault are both NORMAL, and a diagnostic that flags them as
+ * faults sends the reader hunting for a break that does not exist.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, dirname } from "node:path";
+
+import {
+ walkMarkdown,
+ probeFrontmatter,
+ discoverMemoryRoot,
+ discoverExposedRoots,
+ discoverQmdLauncher,
+ findOrphanedProjects,
+ readIndexPath,
+ samePath,
+ indexOwnershipWarning,
+ health,
+ type IndexPathInfo,
+} from "../lib/memory-discover.ts";
+
+// ---------------------------------------------------------------------------
+// Fixtures
+// ---------------------------------------------------------------------------
+
+function tmpVault(): string {
+ return mkdtempSync(join(tmpdir(), "disc-"));
+}
+
+/** Write a file, creating parents. Content defaults to a real capture. */
+function put(dir: string, rel: string, content?: string): string {
+ const full = join(dir, rel);
+ mkdirSync(dirname(full), { recursive: true });
+ writeFileSync(full, content ?? capture(), "utf8");
+ return full;
+}
+
+function capture(projects: string[] = ["atlas"]): string {
+ return [
+ "---",
+ "date: 2026-07-26",
+ "source: mcp-capture",
+ "scope: project",
+ `projects: [${projects.join(", ")}]`,
+ "---",
+ "",
+ "# a memory",
+ "",
+ "body",
+ "",
+ ].join("\n");
+}
+
+/** A note a human wrote. Must never be mistaken for a capture. */
+const HUMAN = "---\ndate: 2026-07-26\ntags:\n - project-note\n---\n\n# hand written\n\nbody\n";
+
+function withVault(fn: (dir: string) => void): void {
+ const dir = tmpVault();
+ try {
+ fn(dir);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Walking
+// ---------------------------------------------------------------------------
+
+describe("walking", () => {
+ test("finds markdown and ignores everything else", () => {
+ withVault((dir) => {
+ put(dir, "brain/a.md", HUMAN);
+ put(dir, "brain/b.txt", "not markdown");
+ put(dir, "brain/c.MD", HUMAN);
+ const found = walkMarkdown(dir).map((f) => f.toLowerCase());
+ assert.equal(found.length, 2);
+ assert.ok(found.some((f) => f.endsWith("a.md")));
+ assert.ok(found.some((f) => f.endsWith("c.md")), "extension match is case-insensitive");
+ });
+ });
+
+ test("never walks into infrastructure directories", () => {
+ withVault((dir) => {
+ put(dir, "node_modules/pkg/readme.md", HUMAN);
+ put(dir, ".git/x.md", HUMAN);
+ put(dir, ".obsidian/y.md", HUMAN);
+ // The bundled template copy is a whole second vault; walking it would
+ // double every count in this module.
+ put(dir, ".shardmind/template/brain/z.md", HUMAN);
+ put(dir, "brain/real.md", HUMAN);
+ const found = walkMarkdown(dir);
+ assert.equal(found.length, 1);
+ assert.ok(found[0]!.endsWith("real.md"));
+ });
+ });
+
+ test("depth is bounded, so a pathological tree cannot hang startup", () => {
+ withVault((dir) => {
+ put(dir, "a/b/c/d/e/f/g/deep.md", HUMAN);
+ assert.equal(walkMarkdown(dir, { maxDepth: 2 }).length, 0);
+ assert.equal(walkMarkdown(dir, { maxDepth: 8 }).length, 1);
+ });
+ });
+
+ test("a missing root is empty, not a throw", () => {
+ assert.deepEqual(walkMarkdown(join(tmpdir(), "does-not-exist-at-all")), []);
+ });
+});
+
+describe("frontmatter probe", () => {
+ test("returns the block for a note that has one", () => {
+ withVault((dir) => {
+ const f = put(dir, "m.md");
+ assert.match(String(probeFrontmatter(f)), /source: mcp-capture/);
+ });
+ });
+
+ test("a note with no frontmatter is null rather than an error", () => {
+ withVault((dir) => {
+ const f = put(dir, "plain.md", "# just a heading\n");
+ assert.equal(probeFrontmatter(f), null);
+ });
+ });
+
+ test("an unreadable path is null rather than an error", () => {
+ assert.equal(probeFrontmatter(join(tmpdir(), "nope-nope.md")), null);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Memory root — the rename case
+// ---------------------------------------------------------------------------
+
+describe("discovering the memory root", () => {
+ test("an empty vault trusts config, because there is nothing to be wrong about", () => {
+ withVault((dir) => {
+ const r = discoverMemoryRoot(dir, "memories");
+ assert.equal(r.root, "memories");
+ assert.equal(r.source, "configured");
+ assert.equal(r.memories, 0);
+ assert.equal(r.healed, false);
+ assert.equal(r.split, null);
+ });
+ });
+
+ test("config that matches reality is reported as configured, not discovered", () => {
+ withVault((dir) => {
+ put(dir, "memories/2026/07/a.md");
+ const r = discoverMemoryRoot(dir, "memories");
+ assert.equal(r.root, "memories");
+ assert.equal(r.source, "configured");
+ assert.equal(r.healed, false);
+ });
+ });
+
+ test("a user renaming the folder in Obsidian is followed, and said out loud", () => {
+ withVault((dir) => {
+ // The whole point: config still says `memories`, the notes say otherwise.
+ put(dir, "knowledge/2026/07/a.md");
+ put(dir, "knowledge/2026/07/b.md");
+ const r = discoverMemoryRoot(dir, "memories");
+ assert.equal(r.root, "knowledge", "follow the notes, not the config");
+ assert.equal(r.source, "discovered");
+ assert.equal(r.healed, true, "healing must be visible — silence is how a store forks");
+ assert.equal(r.configured, "memories");
+ assert.equal(r.memories, 2);
+ });
+ });
+
+ test("only agent captures count — a human note cannot move the root", () => {
+ withVault((dir) => {
+ put(dir, "memories/2026/07/a.md");
+ put(dir, "journal/x.md", HUMAN);
+ put(dir, "journal/y.md", HUMAN);
+ put(dir, "journal/z.md", HUMAN);
+ assert.equal(discoverMemoryRoot(dir, "memories").root, "memories");
+ });
+ });
+
+ test("an incomplete move is named, because retrieval only sees the larger half", () => {
+ withVault((dir) => {
+ put(dir, "memories/2026/07/a.md");
+ put(dir, "memories/2026/07/b.md");
+ put(dir, "knowledge/2026/07/c.md");
+ const r = discoverMemoryRoot(dir, "memories");
+ assert.equal(r.root, "memories");
+ assert.ok(r.split, "a split store must be reported");
+ assert.equal(r.split!.length, 2);
+ const knowledge = r.split!.find((s) => s.root === "knowledge");
+ assert.equal(knowledge?.memories, 1);
+ });
+ });
+
+ test("a capture at the vault root is ignored — the root is not a memory folder", () => {
+ withVault((dir) => {
+ put(dir, "loose.md");
+ const r = discoverMemoryRoot(dir, "memories");
+ assert.equal(r.memories, 0);
+ assert.equal(r.root, "memories");
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Exposed roots
+// ---------------------------------------------------------------------------
+
+describe("discovering exposed roots", () => {
+ test("derives from the manifest key the template already maintains", () => {
+ withVault((dir) => {
+ mkdirSync(join(dir, "brain"), { recursive: true });
+ mkdirSync(join(dir, "reference"), { recursive: true });
+ const r = discoverExposedRoots(dir, { user_content_roots: ["brain/", "reference/"] });
+ assert.deepEqual(r.roots.sort(), ["brain", "reference"]);
+ assert.equal(r.source, "manifest");
+ });
+ });
+
+ test("a declared root that does not exist is dropped, not exposed", () => {
+ withVault((dir) => {
+ mkdirSync(join(dir, "brain"), { recursive: true });
+ const r = discoverExposedRoots(dir, { user_content_roots: ["brain/", "strategy/"] });
+ assert.deepEqual(r.roots, ["brain"]);
+ });
+ });
+
+ test("a glob entry contributes its literal segment, never everything", () => {
+ withVault((dir) => {
+ mkdirSync(join(dir, "perf"), { recursive: true });
+ const r = discoverExposedRoots(dir, { user_content_roots: ["perf/h*-*/", "*/"] });
+ assert.deepEqual(r.roots, ["perf"], "a leading-glob entry must contribute nothing");
+ });
+ });
+
+ test("no usable manifest falls back, and says so, so health can warn", () => {
+ withVault((dir) => {
+ mkdirSync(join(dir, "brain"), { recursive: true });
+ const r = discoverExposedRoots(dir, {});
+ assert.equal(r.source, "fallback");
+ assert.deepEqual(r.roots, ["brain"]);
+ });
+ });
+
+ test("a null manifest is a fallback, not a crash", () => {
+ withVault((dir) => {
+ assert.equal(discoverExposedRoots(dir, null).source, "fallback");
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// qmd launcher
+// ---------------------------------------------------------------------------
+
+describe("locating the qmd launcher", () => {
+ test("the expected path is used without a walk", () => {
+ withVault((dir) => {
+ put(dir, ".claude/scripts/qmd-mcp.mjs", "//");
+ const r = discoverQmdLauncher(dir);
+ assert.equal(r.source, "expected");
+ assert.ok(r.path);
+ });
+ });
+
+ test("a moved launcher is still found — the layout is allowed to change", () => {
+ withVault((dir) => {
+ // #71 moves hook scripts out of .claude/; hardcoding the old path would
+ // silently disable search the day that lands.
+ put(dir, ".scripts/qmd-mcp.mjs", "//");
+ const r = discoverQmdLauncher(dir);
+ assert.equal(r.source, "discovered");
+ assert.ok(r.path!.endsWith("qmd-mcp.mjs"));
+ });
+ });
+
+ test("absent is a legitimate state — qmd is optional", () => {
+ withVault((dir) => {
+ const r = discoverQmdLauncher(dir);
+ assert.equal(r.source, "absent");
+ assert.equal(r.path, null);
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Project names — a diagnostic that must not lie
+// ---------------------------------------------------------------------------
+
+describe("projects with no note in the vault", () => {
+ test("reports a name nothing in the vault refers to", () => {
+ withVault((dir) => {
+ put(dir, "memories/2026/07/a.md", capture(["atlas-old"]));
+ const r = findOrphanedProjects(dir, "memories", ["atlas", "beacon"]);
+ assert.equal(r.length, 1);
+ assert.equal(r[0]!.project, "atlas-old");
+ assert.equal(r[0]!.memories, 1);
+ });
+ });
+
+ test("a known project is never reported", () => {
+ withVault((dir) => {
+ put(dir, "memories/2026/07/a.md", capture(["atlas"]));
+ assert.deepEqual(findOrphanedProjects(dir, "memories", ["Atlas"]), [], "match is case-insensitive");
+ });
+ });
+
+ test("counts accumulate per name", () => {
+ withVault((dir) => {
+ put(dir, "memories/2026/07/a.md", capture(["ghost"]));
+ put(dir, "memories/2026/07/b.md", capture(["ghost"]));
+ assert.equal(findOrphanedProjects(dir, "memories", [])[0]!.memories, 2);
+ });
+ });
+
+ test("a missing memory root is empty, not a throw", () => {
+ withVault((dir) => {
+ assert.deepEqual(findOrphanedProjects(dir, "memories", []), []);
+ });
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Index ownership — the last silent-loss path
+// ---------------------------------------------------------------------------
+
+describe("index ownership", () => {
+ const HOME = "/home/x";
+ const j = (...p: string[]): string => p.join("/");
+ const reader =
+ (map: Record<string, string>) =>
+ (f: string): string => {
+ const v = map[f];
+ if (v === undefined) throw new Error("ENOENT");
+ return v;
+ };
+
+ test("reads the registered path out of qmd's per-index config", () => {
+ const r = readIndexPath(
+ "myvault",
+ HOME,
+ reader({
+ "/home/x/.config/qmd/myvault.yml": "collections:\n myvault:\n path: C:\\Dev\\myvault\n",
+ }),
+ j,
+ );
+ assert.equal(r.state, "registered");
+ assert.equal(r.path, String.raw`C:\Dev\myvault`);
+ });
+
+ test("an unregistered index is NOT a warning — that is a fresh vault", () => {
+ const info = readIndexPath("fresh", HOME, reader({}), j);
+ assert.equal(info.state, "unregistered");
+ assert.equal(indexOwnershipWarning("fresh", "C:/Dev/fresh", info), null);
+ });
+
+ test("a collection pointing at THIS vault is silent", () => {
+ const info: IndexPathInfo = { state: "registered", path: String.raw`C:\Dev\myvault` };
+ assert.equal(indexOwnershipWarning("myvault", "C:/Dev/myvault", info), null);
+ });
+
+ test("a collection pointing at ANOTHER vault warns and names it", () => {
+ // Exactly the #137 collision: two vaults sharing one index name, so
+ // reindexing silently updates the wrong tree.
+ const info: IndexPathInfo = { state: "registered", path: String.raw`C:\Dev\obsidian-mind` };
+ const w = indexOwnershipWarning("obsidian-mind", "C:/Dev/sandbox/e2e-om", info);
+ assert.ok(w, "must warn");
+ assert.match(w!, /DIFFERENT vault/);
+ assert.ok(w!.includes(String.raw`C:\Dev\obsidian-mind`), "must name the vault it actually points at");
+ assert.match(w!, /qmd_index/, "must name the fix");
+ });
+
+ test("path comparison ignores separator style and case", () => {
+ assert.equal(samePath(String.raw`C:\Dev\Vault`, "c:/dev/vault"), true);
+ assert.equal(samePath("C:/Dev/vault/", "C:/Dev/vault"), true);
+ assert.equal(samePath("C:/Dev/vault", "C:/Dev/other"), false);
+ });
+
+ test("a malformed config degrades to a warning, not a wrong answer", () => {
+ const info = readIndexPath("bad", HOME, reader({ "/home/x/.config/qmd/bad.yml": "nonsense" }), j);
+ assert.equal(info.state, "malformed");
+ assert.match(String(indexOwnershipWarning("bad", "C:/Dev/x", info)), /cannot be confirmed/);
+ });
+
+ test("no index name at all is unknown, and never warns", () => {
+ const info = readIndexPath(null, HOME, reader({}), j);
+ assert.equal(info.state, "unknown");
+ assert.equal(indexOwnershipWarning("", "C:/Dev/x", info), null);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Health — every silent state becomes a sentence
+// ---------------------------------------------------------------------------
+
+describe("health", () => {
+ test("a correctly wired vault is ok and warns about nothing", () => {
+ withVault((dir) => {
+ mkdirSync(join(dir, "brain"), { recursive: true });
+ put(dir, ".claude/scripts/qmd-mcp.mjs", "//");
+ put(dir, "memories/2026/07/a.md", capture(["atlas"]));
+ const h = health(dir, { user_content_roots: ["brain/"], memory_root: "memories" }, {
+ knownNames: ["atlas"],
+ });
+ assert.deepEqual(h.warnings, []);
+ assert.equal(h.ok, true);
+ });
+ });
+
+ test("a renamed memory folder produces a warning that names the fix", () => {
+ withVault((dir) => {
+ mkdirSync(join(dir, "brain"), { recursive: true });
+ put(dir, ".claude/scripts/qmd-mcp.mjs", "//");
+ put(dir, "knowledge/2026/07/a.md");
+ const h = health(dir, { user_content_roots: ["brain/"], memory_root: "memories" });
+ assert.equal(h.ok, false);
+ const w = h.warnings.join(" ");
+ assert.match(w, /knowledge/);
+ assert.match(w, /memory_root/, "a warning without the remedy is half a diagnostic");
+ });
+ });
+
+ test("a missing qmd launcher warns but does not claim the vault is empty", () => {
+ withVault((dir) => {
+ mkdirSync(join(dir, "brain"), { recursive: true });
+ const h = health(dir, { user_content_roots: ["brain/"] });
+ assert.match(h.warnings.join(" "), /lexical/, "degradation must be described, not implied");
+ });
+ });
+
+ test("a project with no note is a NOTE, never a warning", () => {
+ withVault((dir) => {
+ mkdirSync(join(dir, "brain"), { recursive: true });
+ put(dir, ".claude/scripts/qmd-mcp.mjs", "//");
+ put(dir, "memories/2026/07/a.md", capture(["ghost"]));
+ const h = health(dir, { user_content_roots: ["brain/"], memory_root: "memories" }, {
+ knownNames: ["atlas"],
+ });
+ // A repo needs no note in the vault for its memories to reach it. Calling
+ // this a fault would send the reader hunting for a break that is not there.
+ assert.deepEqual(h.warnings, []);
+ assert.equal(h.ok, true);
+ assert.equal(h.notes.length, 1);
+ assert.match(h.notes[0]!, /ghost/);
+ assert.match(h.notes[0]!, /renamed/, "must point at the case where it IS a real signal");
+ });
+ });
+
+ test("singular and plural read correctly in the notes", () => {
+ withVault((dir) => {
+ put(dir, "memories/2026/07/a.md", capture(["ghost"]));
+ put(dir, "memories/2026/07/b.md", capture(["ghost"]));
+ const one = health(dir, { memory_root: "memories" }, { knownNames: [] });
+ assert.match(one.notes[0]!, /2 memories scoped/);
+ });
+ });
+
+ test("an unconfigured manifest still works — memory_root defaults", () => {
+ withVault((dir) => {
+ put(dir, "memories/2026/07/a.md");
+ const h = health(dir, null);
+ assert.equal(h.memory.root, "memories");
+ assert.equal(h.memory.healed, false);
+ });
+ });
+
+ test("index ownership is folded into the same report", () => {
+ withVault((dir) => {
+ mkdirSync(join(dir, "brain"), { recursive: true });
+ put(dir, ".claude/scripts/qmd-mcp.mjs", "//");
+ // A home with no qmd config at all: unregistered, which must stay quiet.
+ const h = health(dir, { user_content_roots: ["brain/"] }, {
+ indexName: "whatever",
+ home: join(dir, "fake-home"),
+ });
+ assert.deepEqual(h.warnings, []);
+ });
+ });
+});
diff --git a/.claude/scripts/tests/memory-recall.test.ts b/.claude/scripts/tests/memory-recall.test.ts
new file mode 100644
index 0000000..cb0c9f4
--- /dev/null
+++ b/.claude/scripts/tests/memory-recall.test.ts
@@ -0,0 +1,328 @@
+/**
+ * Precision harness for memory retrieval.
+ *
+ * Builds a synthetic vault covering the real shapes a person actually has:
+ *
+ * atlas iOS app
+ * beacon iOS app — same platform, different project
+ * harbor web app — different platform, different project
+ * atlas-api backend — different platform, SAME product context
+ * drifter unrelated — shares nothing
+ * (unknown) no identity — an agent with no MCP roots
+ *
+ * Memories are written through the real writer, so this is a write→read round
+ * trip rather than a test against hand-authored markdown: if the writer and the
+ * reader ever disagree about a facet, it fails here.
+ *
+ * Every case asserts BOTH directions — what surfaced and what was withheld —
+ * because a retrieval layer is only as good as the things it refuses to return.
+ * A false positive puts another project's context into this session, where it is
+ * acted on as if it applied; a false negative is a memory nobody benefits from.
+ */
+
+import { test, describe, before, after } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { readFileSync } from "node:fs";
+
+import { validateMemory, writeMemory } from "../lib/memory-write.ts";
+import {
+ recall,
+ isVisibleTo,
+ facetsOf,
+ parseFrontmatter,
+ specificity,
+ rankMemories,
+ type Caller,
+} from "../lib/memory-recall.ts";
+
+const DAY = new Date(2026, 6, 26);
+
+const CALLERS = {
+ atlas: { project: "atlas", platforms: ["ios"] },
+ beacon: { project: "beacon", platforms: ["ios"] },
+ harbor: { project: "harbor", platforms: ["web"] },
+ atlasApi: { project: "atlas-api", platforms: ["backend"] },
+ drifter: { project: "drifter", platforms: ["android"] },
+ unknown: { project: null, platforms: [] },
+};
+
+/**
+ * The fixture set. `id` is embedded in the title so assertions read as sets of
+ * ids rather than as brittle prose matching.
+ */
+const FIXTURES = [
+ {
+ id: "M1",
+ title: "M1 atlas keychain migration must run before first read",
+ scope: "project",
+ projects: ["atlas"],
+ },
+ {
+ id: "M2",
+ title: "M2 the atlas session token format is shared with the api",
+ scope: "project",
+ projects: ["atlas", "atlas-api"],
+ },
+ {
+ id: "M3",
+ title: "M3 ios background tasks are killed after thirty seconds",
+ scope: "platform",
+ platforms: ["ios"],
+ },
+ {
+ id: "M4",
+ title: "M4 web service workers cache opaque responses silently",
+ scope: "platform",
+ platforms: ["web"],
+ },
+ { id: "M5", title: "M5 semver patch releases still break lockfiles", scope: "general", projects: [] },
+ { id: "M6", title: "M6 beacon analytics batches on a five minute timer", scope: "project", projects: ["beacon"] },
+ {
+ id: "M7",
+ title: "M7 atlas ios build needs the legacy provisioning profile",
+ scope: "project",
+ projects: ["atlas"],
+ platforms: ["ios"],
+ },
+ {
+ id: "M8",
+ title: "M8 mobile deep links need an intent filter and an assoc file",
+ scope: "platform",
+ platforms: ["ios", "android"],
+ },
+];
+
+const BODY =
+ "Recorded by the precision harness. The body is long enough to satisfy the minimum length rule and says nothing that trips a contract flag.";
+
+let VAULT: string;
+
+before(() => {
+ VAULT = mkdtempSync(join(tmpdir(), "recall-"));
+ for (const f of FIXTURES) {
+ const v = validateMemory(
+ {
+ title: f.title,
+ body: BODY,
+ confidence: "inferred",
+ scope: f.scope,
+ projects: f.projects ?? [],
+ platforms: f.platforms ?? [],
+ },
+ // origin is deliberately null for general fixtures so write-side
+ // narrowing does not re-attribute them to a project.
+ { now: DAY, origin: null },
+ );
+ assert.equal(v.ok, true, `fixture ${f.id} failed validation: ${JSON.stringify(v.errors)}`);
+ writeMemory(VAULT, v.value!, []);
+ }
+});
+
+after(() => rmSync(VAULT, { recursive: true, force: true }));
+
+/** Ids visible to a caller, as a sorted array. */
+function seen(caller: Caller): string[] {
+ return recall(VAULT, caller)
+ .map((e) => (e.title ?? "").split(" ")[0]!)
+ .sort();
+}
+
+function withheldIds(caller: Caller): string[] {
+ return recall(VAULT, caller, { explain: true })
+ .withheld.map((e) => (e.title ?? "").split(" ")[0]!)
+ .sort();
+}
+
+// ---------------------------------------------------------------------------
+// The matrix
+// ---------------------------------------------------------------------------
+
+describe("retrieval precision matrix", () => {
+ test("atlas (ios): own project, shared-context, ios platform, general", () => {
+ assert.deepEqual(seen(CALLERS.atlas), ["M1", "M2", "M3", "M5", "M7", "M8"]);
+ });
+
+ test("beacon (ios): SAME platform, different project — gets ios lessons, not atlas's", () => {
+ assert.deepEqual(seen(CALLERS.beacon), ["M3", "M5", "M6", "M8"]);
+ // The headline precision claim: a sibling iOS app must not inherit
+ // another app's project-scoped memories, even platform-tagged ones.
+ assert.deepEqual(withheldIds(CALLERS.beacon), ["M1", "M2", "M4", "M7"]);
+ });
+
+ test("harbor (web): different platform — no ios memories at all", () => {
+ assert.deepEqual(seen(CALLERS.harbor), ["M4", "M5"]);
+ for (const id of ["M1", "M2", "M3", "M6", "M7", "M8"]) {
+ assert.ok(withheldIds(CALLERS.harbor).includes(id), `${id} must not reach a web project`);
+ }
+ });
+
+ test("atlas-api: SAME context, different platform — shared memory only", () => {
+ // M2 names it explicitly, so it crosses the platform boundary. M1 and M7
+ // are atlas-only and must not, and no ios memory may reach a backend.
+ assert.deepEqual(seen(CALLERS.atlasApi), ["M2", "M5"]);
+ });
+
+ test("drifter: shares ONLY a platform — gets that platform's lesson and nothing else", () => {
+ // No shared project, no shared product context, no shared codebase. The
+ // single android-tagged memory (M8) still reaches it, which is the point
+ // of platform scope; every atlas/beacon/harbor memory stays away.
+ assert.deepEqual(seen(CALLERS.drifter), ["M5", "M8"]);
+ assert.deepEqual(withheldIds(CALLERS.drifter), ["M1", "M2", "M3", "M4", "M6", "M7"]);
+ });
+
+ test("an agent with no identity sees general only, not everything", () => {
+ assert.deepEqual(seen(CALLERS.unknown), ["M5"]);
+ });
+
+ test("every memory reaches at least one caller (no write-only memories)", () => {
+ const reached = new Set();
+ for (const caller of Object.values(CALLERS)) for (const id of seen(caller)) reached.add(id);
+ assert.deepEqual([...reached].sort(), FIXTURES.map((f) => f.id).sort());
+ });
+
+ test("no caller sees the whole store", () => {
+ for (const [name, caller] of Object.entries(CALLERS)) {
+ assert.ok(
+ seen(caller).length < FIXTURES.length,
+ `${name} saw everything — the scoping rule is not doing anything`,
+ );
+ }
+ });
+});
+
+// ---------------------------------------------------------------------------
+// The rule itself
+// ---------------------------------------------------------------------------
+
+describe("visibility rule", () => {
+ const f = (o: Record<string, unknown>): ReturnType<typeof facetsOf> => facetsOf(o);
+
+ test("general reaches everyone including the anonymous caller", () => {
+ for (const caller of Object.values(CALLERS)) {
+ assert.equal(isVisibleTo(f({ scope: "general" }), caller), true);
+ }
+ });
+
+ test("an explicit project listing beats a scope mismatch", () => {
+ const m = f({ scope: "platform", projects: ["harbor"], platforms: ["ios"] });
+ assert.equal(isVisibleTo(m, CALLERS.harbor), true, "named project must win");
+ });
+
+ test("project scope never leaks on a platform near-miss", () => {
+ const m = f({ scope: "project", projects: ["atlas"], platforms: ["ios"] });
+ assert.equal(isVisibleTo(m, CALLERS.beacon), false);
+ });
+
+ test("platform matching is case-insensitive", () => {
+ const m = f({ scope: "platform", platforms: ["iOS"] });
+ assert.equal(isVisibleTo(m, { project: "x", platforms: ["ios"] }), true);
+ });
+
+ test("a memory with no facets at all reaches nobody but stays on disk", () => {
+ const m = f({ scope: "project", projects: [], platforms: [] });
+ for (const caller of Object.values(CALLERS)) {
+ assert.equal(isVisibleTo(m, caller), false);
+ }
+ });
+
+ test("malformed facets degrade to invisible rather than throwing", () => {
+ for (const junk of [null, undefined, {}, { scope: 42 }, { projects: "atlas" }]) {
+ assert.doesNotThrow(() => isVisibleTo(facetsOf(junk ?? {}), CALLERS.atlas));
+ }
+ });
+
+ test("a caller shaped wrongly does not crash retrieval", () => {
+ for (const junk of [null, undefined, {}, { project: 0 }, { platforms: "ios" }]) {
+ assert.doesNotThrow(() => isVisibleTo(facetsOf({ scope: "general" }), junk as Caller | null | undefined));
+ }
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Ranking
+// ---------------------------------------------------------------------------
+
+describe("ranking", () => {
+ test("the caller's own project outranks platform, which outranks general", () => {
+ const own = facetsOf({ scope: "project", projects: ["atlas"] });
+ const plat = facetsOf({ scope: "platform", platforms: ["ios"] });
+ const gen = facetsOf({ scope: "general" });
+ assert.ok(specificity(own, CALLERS.atlas) > specificity(plat, CALLERS.atlas));
+ assert.ok(specificity(plat, CALLERS.atlas) > specificity(gen, CALLERS.atlas));
+ });
+
+ test("a memory naming one project outranks one naming many", () => {
+ const narrow = facetsOf({ scope: "project", projects: ["atlas"] });
+ const broad = facetsOf({ scope: "project", projects: ["atlas", "b", "c", "d"] });
+ assert.ok(specificity(narrow, CALLERS.atlas) > specificity(broad, CALLERS.atlas));
+ });
+
+ test("superseded memories sink below live ones", () => {
+ const live = { facets: facetsOf({ scope: "general", date: "2026-01-01" }) };
+ const dead = { facets: facetsOf({ scope: "general", date: "2026-12-31", superseded_by: ["x"] }) };
+ assert.equal(rankMemories([dead, live], CALLERS.atlas)[0], live);
+ });
+
+ test("in a real recall, the project-specific memory comes first", () => {
+ assert.equal((recall(VAULT, CALLERS.atlas)[0]?.title ?? "").split(" ")[0], "M1");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Robustness of the reader
+// ---------------------------------------------------------------------------
+
+describe("reader robustness", () => {
+ test("frontmatter round-trips through the real writer", () => {
+ const v = validateMemory(
+ { title: "round trip", body: BODY, confidence: "verified", verification: "checked", projects: ["atlas"] },
+ { now: DAY, origin: "atlas" },
+ );
+ const dir = mkdtempSync(join(tmpdir(), "rt-"));
+ try {
+ const { full } = writeMemory(dir, v.value!, []);
+ const fm = parseFrontmatter(readFileSync(full, "utf8"));
+ assert.equal(fm.source, "mcp-capture");
+ assert.deepEqual(facetsOf(fm).projects, ["atlas"]);
+ assert.equal(facetsOf(fm).confidence, "verified");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test("notes without the mcp-capture source are ignored entirely", () => {
+ // A human note that lands in memories/ is not governed by these rules and
+ // must not be served as if it were a capture.
+ const fm = parseFrontmatter("---\ntitle: mine\n---\n# hand written\n");
+ assert.notEqual(fm.source, "mcp-capture");
+ });
+
+ test("a file with no frontmatter parses to an empty object rather than throwing", () => {
+ assert.deepEqual(parseFrontmatter("# just a heading\n"), {});
+ assert.deepEqual(parseFrontmatter(""), {});
+ assert.deepEqual(parseFrontmatter(null), {});
+ });
+
+ test("an empty list in frontmatter parses to an empty array", () => {
+ assert.deepEqual(parseFrontmatter("---\nprojects: []\n---\n").projects, []);
+ });
+
+ test("quoted values with commas survive list parsing", () => {
+ const fm = parseFrontmatter('---\nprojects: ["a", "b"]\ndescription: "one, two"\n---\n');
+ assert.deepEqual(fm.projects, ["a", "b"]);
+ assert.equal(fm.description, "one, two");
+ });
+
+ test("recall on a vault with no memories returns empty, not an error", () => {
+ const dir = mkdtempSync(join(tmpdir(), "empty-"));
+ try {
+ assert.deepEqual(recall(dir, CALLERS.atlas), []);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
+
diff --git a/.claude/scripts/tests/memory-similarity.test.ts b/.claude/scripts/tests/memory-similarity.test.ts
new file mode 100644
index 0000000..f61470a
--- /dev/null
+++ b/.claude/scripts/tests/memory-similarity.test.ts
@@ -0,0 +1,207 @@
+/**
+ * Near-duplicate detection for the vault memory layer.
+ *
+ * Thresholds here were set from measurement, so the tests pin the measured
+ * separation rather than the numbers: a verbatim restatement must be caught, a
+ * reworded one must be flagged but not suppressed, and a merely adjacent note
+ * must trigger nothing. If a tokenizer change moves any of those, one of these
+ * fails.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ tokenize,
+ stem,
+ jaccard,
+ similarity,
+ findSimilar,
+ sharesFacet,
+ DUPLICATE,
+} from "../lib/memory-similarity.ts";
+
+describe("tokenizing", () => {
+ test("stopwords are dropped, signal is kept", () => {
+ const t = tokenize("The patch is not applied to the user's node_modules");
+ assert.ok(!t.includes("the"));
+ assert.ok(!t.includes("is"));
+ assert.ok(t.includes("patch"));
+ // `_` survives the markdown pass, so the identifier stays one token;
+ // plural folding then trims the trailing s.
+ assert.ok(t.includes("node_module"), `identifier was split or lost: ${JSON.stringify(t)}`);
+ });
+
+ test("plural folding matches singular and plural without over-stemming", () => {
+ assert.equal(stem("patches"), "patch");
+ assert.equal(stem("externals"), "external");
+ assert.equal(stem("resolves"), "resolve");
+ assert.equal(stem("dependencies"), "dependency");
+ // Must NOT mangle these — over-stemming collapses distinct technical terms.
+ assert.equal(stem("class"), "class");
+ assert.equal(stem("https"), "https", "https must not fold into http");
+ assert.equal(stem("ios"), "ios");
+ assert.equal(stem("css"), "css");
+ });
+
+ test("numbers survive — a version difference is the point of a second memory", () => {
+ assert.ok(tokenize("breaks in 0.1.5").includes("0.1.5"));
+ });
+
+ test("markdown punctuation does not become tokens", () => {
+ const t = tokenize("**bold** `code` [link](x) > quote");
+ assert.ok(!t.some((x) => x.includes("*") || x.includes("`") || x.includes("[")));
+ });
+
+ test("empty and junk input yields no tokens", () => {
+ assert.deepEqual(tokenize(""), []);
+ assert.deepEqual(tokenize(null), []);
+ assert.deepEqual(tokenize("### *** ---"), []);
+ });
+});
+
+describe("similarity scoring", () => {
+ const A = {
+ title: "tsup externals decide what a patch can fix",
+ body: "patch-package only patches the local node_modules; an external dependency resolves on the user machine so the patch never ships.",
+ };
+
+ test("a memory is identical to itself", () => {
+ assert.equal(similarity(A, A), 1);
+ });
+
+ test("a near-verbatim restatement scores as a duplicate", () => {
+ const B = {
+ title: "tsup externals decide what patches can fix",
+ body: "patch-package patches only the local node_modules; an external dependency resolves on the user machine so a patch never ships.",
+ };
+ assert.ok(similarity(A, B) >= DUPLICATE, `scored ${similarity(A, B)}`);
+ });
+
+ test("a genuinely different lesson about the same subsystem is NOT a duplicate", () => {
+ const B = {
+ title: "tsup emits no shebang unless banner is set",
+ body: "The CLI entry needs a banner in tsup.config so npx can execute dist/cli.js directly.",
+ };
+ assert.ok(similarity(A, B) < DUPLICATE, `scored ${similarity(A, B)}`);
+ });
+
+ test("unrelated memories score near zero", () => {
+ const B = { title: "beacon analytics batches on a timer", body: "Events flush every five minutes." };
+ assert.ok(similarity(A, B) < 0.2);
+ });
+
+ test("title is weighted above body", () => {
+ const sameTitle = { title: A.title, body: "completely unrelated prose about kittens and weather." };
+ const sameBody = { title: "utterly different heading about kittens", body: A.body };
+ assert.ok(similarity(A, sameTitle) > similarity(A, sameBody));
+ });
+
+ test("jaccard handles empty bags without dividing by zero", () => {
+ assert.equal(jaccard([], []), 1);
+ assert.equal(jaccard([], ["a"]), 0);
+ });
+});
+
+describe("facet gating", () => {
+ test("identical text in two unrelated projects is not a duplicate", () => {
+ const a = { title: "t", body: "b", scope: "project", projects: ["atlas"] };
+ const b = { title: "t", body: "b", scope: "project", projects: ["harbor"] };
+ assert.equal(sharesFacet(a, b), false);
+ assert.equal(findSimilar(a, [b]).duplicates.length, 0);
+ });
+
+ test("a general memory can duplicate anything", () => {
+ assert.equal(
+ sharesFacet(
+ { title: "t", body: "b", scope: "general", projects: [] },
+ { title: "t", body: "b", scope: "project", projects: ["harbor"] },
+ ),
+ true,
+ );
+ });
+
+ test("two platform memories on the same platform can duplicate", () => {
+ assert.equal(
+ sharesFacet(
+ { title: "t", body: "b", scope: "platform", platforms: ["ios"] },
+ { title: "t", body: "b", scope: "platform", platforms: ["ios"] },
+ ),
+ true,
+ );
+ });
+
+ test("a shared project makes them comparable across scopes", () => {
+ assert.equal(
+ sharesFacet(
+ { title: "t", body: "b", scope: "project", projects: ["atlas"] },
+ { title: "t", body: "b", scope: "platform", projects: ["atlas"], platforms: ["ios"] },
+ ),
+ true,
+ );
+ });
+});
+
+describe("findSimilar", () => {
+ const existing = [
+ {
+ rel: "memories/2026/07/a.md",
+ title: "tsup externals decide what a patch can fix",
+ body: "patch-package only patches local node_modules; external deps resolve on the user machine.",
+ scope: "general",
+ },
+ {
+ rel: "memories/2026/07/b.md",
+ title: "beacon analytics batches on a five minute timer",
+ body: "Events are flushed on a timer rather than per event.",
+ scope: "general",
+ },
+ ];
+
+ test("a near-restatement is returned as a duplicate with its score", () => {
+ const r = findSimilar(
+ {
+ title: "tsup externals decide what patches can fix",
+ body: "patch-package patches only local node_modules; external deps resolve on the user machine.",
+ scope: "general",
+ },
+ existing,
+ );
+ assert.equal(r.duplicates.length, 1);
+ assert.equal(r.duplicates[0]!.entry.rel, "memories/2026/07/a.md");
+ assert.ok(r.duplicates[0]!.score >= DUPLICATE);
+ });
+
+ test("the same lesson in different words is flagged as a possible restatement", () => {
+ const r = findSimilar(
+ {
+ title: "a patch cannot fix an external dependency",
+ body: "Because tsup marks the dependency external it resolves on the user machine, so patching local node_modules never ships anything.",
+ scope: "general",
+ },
+ existing,
+ );
+ assert.equal(r.duplicates.length, 0, "a rewording is not a duplicate — it may say it better");
+ assert.ok(r.related.length >= 1, "but the caller should be told it already knows this");
+ });
+
+ test("a merely adjacent note about the same subsystem triggers nothing", () => {
+ const r = findSimilar(
+ {
+ title: "tsup emits no shebang unless banner is set",
+ body: "The CLI entry needs a banner in tsup.config so npx can execute dist/cli.js directly.",
+ scope: "general",
+ },
+ existing,
+ );
+ assert.equal(r.duplicates.length, 0);
+ assert.equal(r.related.length, 0);
+ });
+
+ test("results are ordered by score", () => {
+ const r = findSimilar({ ...existing[0]! }, [...existing, { ...existing[0]!, rel: "c.md" }]);
+ for (let i = 1; i < r.duplicates.length; i++) {
+ assert.ok(r.duplicates[i - 1]!.score >= r.duplicates[i]!.score);
+ }
+ });
+});
diff --git a/.claude/scripts/tests/memory-supersede.test.ts b/.claude/scripts/tests/memory-supersede.test.ts
new file mode 100644
index 0000000..92e2d3b
--- /dev/null
+++ b/.claude/scripts/tests/memory-supersede.test.ts
@@ -0,0 +1,211 @@
+/**
+ * Supersession — the only path where the server edits an existing file.
+ *
+ * The tests that matter most here are the refusals. A layer that can rewrite
+ * notes is only safe if it provably declines to touch anything it did not
+ * write, so that case asserts the file is byte-identical afterwards rather than
+ * merely that a flag came back false.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, dirname } from "node:path";
+
+import { addToFrontmatterList, markSuperseded, resolveSupersedes } from "../lib/memory-supersede.ts";
+import { validateMemory, writeMemory } from "../lib/memory-write.ts";
+import { recall, parseFrontmatter, facetsOf } from "../lib/memory-recall.ts";
+
+const MD = "---\ndate: 2026-07-26\nsource: mcp-capture\nscope: general\n---\n\n# t\n\nbody\n";
+
+function vaultWith(md: string): { dir: string; rel: string } {
+ const dir = mkdtempSync(join(tmpdir(), "sup-"));
+ const rel = "memories/2026/07/2026-07-26 old.md";
+ mkdirSync(dirname(join(dir, rel)), { recursive: true });
+ writeFileSync(join(dir, rel), md, "utf8");
+ return { dir, rel };
+}
+
+describe("frontmatter surgery", () => {
+ test("adds a new list key without touching anything else", () => {
+ const r = addToFrontmatterList(MD, "superseded_by", "New Title");
+ assert.equal(r.changed, true);
+ assert.ok(r.text.includes('superseded_by: ["New Title"]'));
+ assert.ok(r.text.includes("date: 2026-07-26"), "existing keys must survive");
+ assert.ok(r.text.endsWith("body\n"), "the body must be untouched");
+ });
+
+ test("extends an existing list rather than replacing it", () => {
+ const once = addToFrontmatterList(MD, "superseded_by", "First").text;
+ assert.ok(addToFrontmatterList(once, "superseded_by", "Second").text.includes('["First", "Second"]'));
+ });
+
+ test("re-adding the same value is a no-op", () => {
+ const once = addToFrontmatterList(MD, "superseded_by", "First").text;
+ const again = addToFrontmatterList(once, "superseded_by", "First");
+ assert.equal(again.changed, false);
+ assert.equal(again.text, once);
+ });
+
+ test("a file with no frontmatter is left alone", () => {
+ assert.equal(addToFrontmatterList("# just a body\n", "superseded_by", "x").changed, false);
+ });
+
+ test("values containing quotes cannot break the YAML", () => {
+ const r = addToFrontmatterList(MD, "superseded_by", 'a "quoted" title');
+ const inner = r.text.match(/superseded_by: \[(.*)\]/)?.[1];
+ assert.ok(inner);
+ assert.doesNotThrow(() => JSON.parse(inner));
+ });
+});
+
+describe("markSuperseded", () => {
+ test("marks an agent-written memory and reports the change", () => {
+ const { dir, rel } = vaultWith(MD);
+ try {
+ const r = markSuperseded(dir, rel, "The Correction");
+ assert.equal(r.ok, true);
+ assert.equal(r.changed, true);
+ assert.ok(readFileSync(join(dir, rel), "utf8").includes('superseded_by: ["The Correction"]'));
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test("REFUSES to modify a note it did not write, byte-for-byte", () => {
+ // The safety rule that matters most: a human's note is never edited,
+ // whatever it happens to be linked to.
+ const original = "---\ntitle: my own note\n---\n\n# mine\n\nhand written\n";
+ const { dir, rel } = vaultWith(original);
+ try {
+ const r = markSuperseded(dir, rel, "The Correction");
+ assert.equal(r.ok, false);
+ assert.match(r.reason, /refusing to modify/);
+ assert.equal(readFileSync(join(dir, rel), "utf8"), original);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test("a missing file returns a refusal rather than throwing", () => {
+ const dir = mkdtempSync(join(tmpdir(), "sup-"));
+ try {
+ assert.equal(markSuperseded(dir, "memories/nope.md", "x").ok, false);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe("resolveSupersedes", () => {
+ const existing = [
+ { rel: "a.md", title: "The Old Lesson" },
+ { rel: "b.md", title: "Another Memory" },
+ ];
+
+ test("matches on exact title, case-insensitively", () => {
+ const r = resolveSupersedes(["the old lesson"], existing);
+ assert.equal(r.matched.length, 1);
+ assert.equal(r.matched[0]!.rel, "a.md");
+ });
+
+ test("does NOT fuzzy match — retiring the wrong memory is the one bad outcome", () => {
+ const r = resolveSupersedes(["The Old"], existing);
+ assert.equal(r.matched.length, 0);
+ assert.deepEqual(r.unmatched, ["The Old"]);
+ });
+
+ test("unmatched claims are reported so the caller learns nothing was retired", () => {
+ assert.deepEqual(resolveSupersedes(["Ghost"], existing).unmatched, ["Ghost"]);
+ });
+
+ test("empty and malformed claims are ignored safely", () => {
+ assert.deepEqual(resolveSupersedes(null, existing).matched, []);
+ assert.deepEqual(resolveSupersedes(["", " "], existing).matched, []);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// End to end: a correction lands and outranks what it corrected
+// ---------------------------------------------------------------------------
+
+/**
+ * The unit tests above prove each half in isolation. This is the claim that
+ * actually matters to a user, and it can only be made by driving the real
+ * writer, the real supersession and the real reader in sequence: a flat store
+ * that learns "X" and later "not X" holds both with equal authority forever and
+ * gets LESS trustworthy the longer it runs. Here the correction wins and the
+ * history survives.
+ */
+describe("correction round trip", () => {
+ const DAY = new Date(2026, 6, 26);
+
+ test("the correction outranks the corrected memory in recall", () => {
+ const dir = mkdtempSync(join(tmpdir(), "corr-"));
+ try {
+ const caller = { project: "atlas", platforms: [] };
+
+ const oldV = validateMemory(
+ {
+ title: "atlas tokens expire after one hour",
+ body: "Observed the session token being rejected sixty minutes after issue during manual testing.",
+ confidence: "inferred",
+ projects: ["atlas"],
+ },
+ { now: new Date(2026, 5, 1), origin: "atlas" },
+ );
+ const oldWritten = writeMemory(dir, oldV.value!, []);
+
+ const newV = validateMemory(
+ {
+ title: "atlas tokens expire after fifteen minutes not one hour",
+ body: "The hour figure was wrong: the gateway shortened the TTL. Confirmed against the issuer config on 2026-07-26.",
+ confidence: "verified",
+ verification: "Read the issuer config directly.",
+ projects: ["atlas"],
+ },
+ { now: DAY, origin: "atlas" },
+ );
+ writeMemory(dir, newV.value!, []);
+
+ const marked = markSuperseded(dir, oldWritten.rel, newV.value!.title);
+ assert.equal(marked.ok, true);
+
+ const results = recall(dir, caller);
+ assert.equal(results.length, 2, "nothing is deleted — the history survives");
+ assert.ok(
+ String(results[0]!.title).includes("fifteen minutes"),
+ `the correction must rank first, got: ${results[0]!.title}`,
+ );
+ assert.ok(
+ results[1]!.facets.superseded_by.length > 0,
+ "the corrected memory carries its back-link",
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test("a superseded memory is still readable and still carries its facets", () => {
+ const dir = mkdtempSync(join(tmpdir(), "corr2-"));
+ try {
+ const v = validateMemory(
+ {
+ title: "a fact that later changed",
+ body: "Recorded before the correction arrived, in good faith.",
+ confidence: "inferred",
+ projects: ["atlas"],
+ },
+ { now: DAY, origin: "atlas" },
+ );
+ const w = writeMemory(dir, v.value!, []);
+ markSuperseded(dir, w.rel, "the newer one");
+ const fm = facetsOf(parseFrontmatter(readFileSync(join(dir, w.rel), "utf8")));
+ assert.deepEqual(fm.projects, ["atlas"]);
+ assert.deepEqual(fm.superseded_by, ["the newer one"]);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/.claude/scripts/tests/memory-write.concurrency.test.ts b/.claude/scripts/tests/memory-write.concurrency.test.ts
new file mode 100644
index 0000000..aedc713
--- /dev/null
+++ b/.claude/scripts/tests/memory-write.concurrency.test.ts
@@ -0,0 +1,95 @@
+/**
+ * Cross-process write safety.
+ *
+ * Separate from the other write tests because the defect it guards CANNOT
+ * reproduce in-process: Node runs the synchronous fs calls to completion, so a
+ * single-threaded test always serialises them and always passes.
+ *
+ * It matters because the deployment shape is one server process PER CONSUMING
+ * REPO, all writing into one vault. An adversarial run with six processes
+ * recording the same lesson title produced FOUR files and SIX success messages
+ * — two memories lost silently, which is the worst outcome available to a layer
+ * whose whole job is not losing them.
+ *
+ * The cause was `while (existsSync(x)) bump(x); writeFileSync(x)`: both
+ * processes see the name free, both write, one clobbers the other. The fix is
+ * an atomic exclusive create, which fails instead of overwriting so the loser
+ * takes the next suffix.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { execFile } from "node:child_process";
+import { mkdtempSync, rmSync, readdirSync, writeFileSync, mkdirSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, dirname } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const LIB = join(dirname(fileURLToPath(import.meta.url)), "..", "lib", "memory-write.ts");
+const WRITERS = 8;
+
+/**
+ * A tiny script that performs one write and prints the path it claimed.
+ *
+ * The import must be a `file://` URL: on Windows an absolute path starting with
+ * a drive letter is read by the ESM loader as an unsupported URL scheme.
+ */
+const WRITER_SRC = `
+import { validateMemory, writeMemory } from ${JSON.stringify(pathToFileURL(LIB).href)};
+const [vault, origin] = process.argv.slice(2);
+const v = validateMemory(
+ {
+ title: "the same lesson title from every process",
+ body: "Identical body from every writer, chosen so the filename collides and the atomic claim is the only thing separating them.",
+ confidence: "inferred",
+ scope: "project",
+ projects: [origin],
+ },
+ { now: new Date("2026-07-26"), origin },
+);
+if (!v.ok) { console.error("INVALID: " + v.errors.join("; ")); process.exit(2); }
+process.stdout.write(writeMemory(vault, v.value, [], { root: "memories" }).rel);
+`;
+
+describe("concurrent writes from separate processes", () => {
+ test("every process gets its own file — none is silently clobbered", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "conc-"));
+ try {
+ const script = join(dir, "writer.mjs");
+ mkdirSync(join(dir, "memories", "2026", "07"), { recursive: true });
+ writeFileSync(script, WRITER_SRC, "utf8");
+
+ // All started BEFORE any is awaited. A synchronous exec would serialise
+ // them and the race — which is the entire point — would never occur.
+ const procs = await Promise.all(
+ Array.from(
+ { length: WRITERS },
+ (_, i) =>
+ new Promise<string>((res, rej) => {
+ execFile(
+ process.execPath,
+ ["--disable-warning=ExperimentalWarning", "--experimental-strip-types", script, dir, `repo-${i}`],
+ { encoding: "utf8" },
+ (err, stdout, stderr) => (err ? rej(new Error(String(stderr || err.message))) : res(stdout.trim())),
+ );
+ }),
+ ),
+ );
+
+ assert.equal(procs.length, WRITERS, "every writer must report a path");
+ assert.equal(new Set(procs).size, WRITERS, `paths must be distinct, got ${new Set(procs).size}`);
+
+ const onDisk = readdirSync(join(dir, "memories", "2026", "07")).filter((f) => f.endsWith(".md"));
+ assert.equal(
+ onDisk.length,
+ WRITERS,
+ `every reported write must exist on disk — ${onDisk.length} files for ${WRITERS} successes means memories were lost`,
+ );
+
+ const leftovers = readdirSync(join(dir, "memories", "2026", "07")).filter((f) => f.endsWith(".tmp"));
+ assert.deepEqual(leftovers, [], "no half-written note may be left for the indexer");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/.claude/scripts/tests/memory-write.test.ts b/.claude/scripts/tests/memory-write.test.ts
new file mode 100644
index 0000000..3376e10
--- /dev/null
+++ b/.claude/scripts/tests/memory-write.test.ts
@@ -0,0 +1,618 @@
+/**
+ * Hardening suite for the vault memory layer.
+ *
+ * Ordered from real situations outward to the adversarial ones, because the
+ * cheap tests are the ones that fail first when something breaks. The last
+ * section is a containment property test: the path builder is handed hostile
+ * titles and must never produce a path that escapes the memory root.
+ *
+ * Zero dependencies, matching the harness.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync, existsSync, readFileSync, mkdirSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, sep, resolve } from "node:path";
+
+import {
+ slugify,
+ isoDate,
+ memoryPath,
+ narrowScope,
+ resolveLinks,
+ validateMemory,
+ renderMemory,
+ deriveDescription,
+ writeMemory,
+ readMemory,
+ MEMORY_ROOT,
+ type MemoryInput,
+} from "../lib/memory-write.ts";
+
+const DAY = new Date(2026, 6, 26, 14, 2, 11); // 2026-07-26, local
+const OK = {
+ title: "tsup externals decide what a patch can fix",
+ body:
+ "patch-package only patches this repo's node_modules. A dependency marked external in tsup is resolved on the user's machine at install time, so the patch never reaches them.",
+ confidence: "inferred",
+};
+
+function tmpVault(): string {
+ return mkdtempSync(join(tmpdir(), "memtest-"));
+}
+
+/** Split frontmatter off a rendered memory and return the raw lines. */
+function frontmatter(md: string): string[] {
+ const m = md.match(/^---\n([\s\S]*?)\n---\n/);
+ assert.ok(m, "rendered memory must open with a frontmatter block");
+ return (m[1] ?? "").split("\n");
+}
+
+function fmValue(md: string, key: string): string | undefined {
+ const line = frontmatter(md).find((l: string) => l.startsWith(`${key}:`));
+ return line === undefined ? undefined : line.slice(key.length + 1).trim();
+}
+
+/** fmValue where the caller has already established the key must be present. */
+function fmRequired(md: string, key: string): string {
+ const v = fmValue(md, key);
+ assert.ok(v !== undefined, `frontmatter key "${key}" is missing`);
+ return v;
+}
+
+// ---------------------------------------------------------------------------
+// 1. The real path
+// ---------------------------------------------------------------------------
+
+describe("real usage", () => {
+ test("a normal memory validates, renders and writes where the blueprint says", () => {
+ const v = validateMemory(OK, { now: DAY, origin: "pocket" });
+ assert.equal(v.ok, true, JSON.stringify(v.errors));
+
+ const dir = tmpVault();
+ try {
+ const { rel } = writeMemory(dir, v.value!, ["pocket"]);
+ assert.equal(rel, "memories/2026/07/2026-07-26 tsup externals decide what a patch can fix.md");
+ assert.ok(existsSync(join(dir, rel)));
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test("frontmatter carries every field the architecture doc promises", () => {
+ const v = validateMemory(
+ { ...OK, scope: "project", projects: ["pocket", "obsidian-mind"], platforms: ["ios"] },
+ { now: DAY, origin: "pocket" },
+ );
+ const md = renderMemory(v.value!, ["pocket"]);
+ assert.equal(fmValue(md, "date"), "2026-07-26");
+ assert.equal(fmValue(md, "source"), "mcp-capture");
+ assert.equal(fmValue(md, "origin"), '"pocket"');
+ assert.equal(fmValue(md, "scope"), "project");
+ assert.equal(fmValue(md, "projects"), '["pocket", "obsidian-mind"]');
+ assert.equal(fmValue(md, "platforms"), '["ios"]');
+ assert.equal(fmValue(md, "confidence"), "inferred");
+ assert.equal(fmValue(md, "tags"), "[memory]");
+ assert.ok(fmRequired(md, "session").includes("T"));
+ });
+
+ test("projects is a list, which is the whole point", () => {
+ const v = validateMemory({ ...OK, projects: ["a", "b", "c"] }, { now: DAY, origin: "a" });
+ assert.deepEqual(v.value!.projects, ["a", "b", "c"]);
+ });
+
+ test("body and title survive into the note verbatim", () => {
+ const v = validateMemory(OK, { now: DAY, origin: "pocket" });
+ const md = renderMemory(v.value!, []);
+ assert.ok(md.includes(`# ${OK.title}`));
+ assert.ok(md.includes(OK.body));
+ });
+
+ test("verification renders its own section", () => {
+ const v = validateMemory({ ...OK, verification: "Ran npm pack; patches/ absent." }, { now: DAY, origin: "p" });
+ const md = renderMemory(v.value!, []);
+ assert.ok(md.includes("## How this is known"));
+ assert.ok(md.includes("Ran npm pack"));
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 2. Scope narrowing — never widens
+// ---------------------------------------------------------------------------
+
+describe("scope narrowing", () => {
+ test("general + named projects downgrades to project", () => {
+ const r = narrowScope({ scope: "general", projects: ["pocket"], origin: "pocket" });
+ assert.equal(r.scope, "project");
+ assert.equal(r.downgraded_from, "general");
+ });
+
+ test("general naming nothing STANDS, with or without an origin", () => {
+ // Regression. An earlier version attributed this case to the origin repo,
+ // so every general memory silently became project-scoped to whoever wrote
+ // it and the general tier was UNREACHABLE through the server — while the
+ // reader, the tool schema, the Base view and the docs all still described
+ // it. Found by an adversarial run in which five of six callers could not
+ // see a memory explicitly written as general.
+ for (const origin of ["pocket", null]) {
+ const r = narrowScope({ scope: "general", projects: [], origin });
+ assert.equal(r.scope, "general", `origin=${origin}`);
+ assert.deepEqual(r.projects, []);
+ assert.equal(r.downgraded_from, null);
+ }
+ });
+
+ test("a downgrade is recorded in the note, not hidden", () => {
+ // The surviving downgrade: general WITH named projects is scoped to them
+ // by the caller's own admission.
+ const v = validateMemory({ ...OK, scope: "general", projects: ["pocket"] }, { now: DAY, origin: "pocket" });
+ const md = renderMemory(v.value!, []);
+ assert.equal(fmValue(md, "claimed_scope"), "general");
+ });
+
+ test("scope is never widened", () => {
+ for (const origin of ["pocket", null]) {
+ for (const projects of [[], ["a"], ["a", "b"]]) {
+ const r = narrowScope({ scope: "project", projects, origin });
+ assert.notEqual(r.scope, "general", "project must never become general");
+ }
+ }
+ });
+
+ test("platform scope passes through untouched", () => {
+ const r = narrowScope({ scope: "platform", projects: [], origin: "pocket" });
+ assert.equal(r.scope, "platform");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 3. Link resolution — never emit a broken edge
+// ---------------------------------------------------------------------------
+
+describe("link resolution", () => {
+ const known = new Set(["pocket", "obsidian-mind"]);
+
+ test("resolvable links survive, unresolvable are dropped and reported", () => {
+ const r = resolveLinks(["pocket", "Ghost Note"], known);
+ assert.deepEqual(r.resolved, ["pocket"]);
+ assert.deepEqual(r.dropped, ["Ghost Note"]);
+ });
+
+ test("matching is case-insensitive but preserves the caller's casing", () => {
+ const r = resolveLinks(["POCKET"], known);
+ assert.deepEqual(r.resolved, ["POCKET"]);
+ });
+
+ test("duplicates collapse", () => {
+ const r = resolveLinks(["pocket", "Pocket", "pocket"], known);
+ assert.equal(r.resolved.length, 1);
+ });
+
+ test("empty and non-array input is survivable", () => {
+ assert.deepEqual(resolveLinks(undefined, known).resolved, []);
+ assert.deepEqual(resolveLinks(null, known).dropped, []);
+ assert.deepEqual(resolveLinks(["", " "], known).resolved, []);
+ });
+
+ test("no resolvable links means no Related section rather than an empty one", () => {
+ const v = validateMemory(OK, { now: DAY, origin: "p" });
+ assert.ok(!renderMemory(v.value!, []).includes("## Related"));
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 4. The epistemic contract
+// ---------------------------------------------------------------------------
+
+describe("epistemic contract", () => {
+ const ctx = { now: DAY, origin: "pocket" };
+
+ test("recurrence claims are flagged and capped, not rejected", () => {
+ // v1 REJECTED these. That was wrong: a false reject destroys knowledge the
+ // session already had, while a false flag costs one frontmatter line.
+ for (const claim of [
+ "This always breaks on Windows when the path has a space in it somewhere.",
+ "The installer never recovers from a partial write, so state is lost.",
+ "Every time the cache is cold the build fails with a null exit code.",
+ "This keeps happening whenever two vaults share one index name.",
+ ]) {
+ const r = validateMemory({ ...OK, body: claim, confidence: "verified" }, ctx);
+ assert.equal(r.ok, true, `should accept but flag: ${claim}`);
+ assert.ok(r.value!.flags.includes("generalised"), `no flag for: ${claim}`);
+ assert.equal(r.value!.confidence, "inferred", "a generalised claim cannot stay verified");
+ assert.equal(r.value!.claimed_confidence, "verified", "the original claim stays auditable");
+ }
+ });
+
+ test("a deterministic consequence using the word 'never' is NOT flagged", () => {
+ // The regression that killed v1: "the patch never reaches them" describes a
+ // mechanism, not a frequency. This is the canonical example from the docs.
+ const r = validateMemory(OK, ctx);
+ assert.equal(r.ok, true, JSON.stringify(r.errors));
+ assert.deepEqual(r.value!.flags, [], "benign prose must not be flagged");
+ });
+
+ test("a single dated occurrence is accepted", () => {
+ const r = validateMemory(
+ {
+ ...OK,
+ body: "On 2026-07-26 the build failed with a null exit code because the guard had no timeout.",
+ },
+ ctx,
+ );
+ assert.equal(r.ok, true, JSON.stringify(r.errors));
+ });
+
+ test("volatile figures without a date anchor are flagged, not rejected", () => {
+ const r = validateMemory(
+ {
+ ...OK,
+ body: "The template repo has 3974 stars and 480 forks right now, which is worth recording.",
+ confidence: "verified",
+ },
+ ctx,
+ );
+ assert.equal(r.ok, true);
+ assert.ok(r.value!.flags.includes("volatile"));
+ assert.equal(r.value!.confidence, "inferred", "an undated figure cannot be verified");
+ });
+
+ test("the same figure with an anchor is accepted", () => {
+ const r = validateMemory(
+ { ...OK, body: "The template repo has 3974 stars as of 2026-07-26, which is up from launch." },
+ ctx,
+ );
+ assert.equal(r.ok, true, JSON.stringify(r.errors));
+ assert.deepEqual(r.value!.flags, [], "an anchored figure carries no volatile flag");
+ });
+
+ test("transcripts are rejected, short dialogue quotes are not", () => {
+ const transcript = ["User: why did it fail", "Assistant: because of X", "User: fix it", "Assistant: done"].join("\n");
+ assert.equal(validateMemory({ ...OK, body: transcript }, ctx).ok, false);
+
+ const quoted = "The maintainer said:\nUser: it fails on Windows\nThat was the only report we had, so it stays unverified for now.";
+ assert.equal(validateMemory({ ...OK, body: quoted }, ctx).ok, true);
+ });
+
+ test("verified without verification warns but does not block", () => {
+ const r = validateMemory({ ...OK, confidence: "verified" }, ctx);
+ assert.equal(r.ok, true);
+ assert.ok(r.warnings.some((w) => /verified/i.test(w)));
+ });
+
+ test("an oversized body warns about atomicity rather than failing", () => {
+ const r = validateMemory({ ...OK, body: "x. ".repeat(5000) }, ctx);
+ assert.equal(r.ok, true);
+ assert.ok(r.warnings.some((w) => /atomic/i.test(w)));
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 5. Input validation
+// ---------------------------------------------------------------------------
+
+describe("input validation", () => {
+ const ctx = { now: DAY, origin: "pocket" };
+
+ test("missing required fields are all reported at once, not one at a time", () => {
+ const r = validateMemory({}, ctx);
+ assert.equal(r.ok, false);
+ assert.ok(r.errors.length >= 3, "should report title, body and confidence together");
+ });
+
+ test("a too-short body is rejected with its actual length", () => {
+ const r = validateMemory({ ...OK, body: "it broke" }, ctx);
+ assert.equal(r.ok, false);
+ assert.ok(r.errors.some((e) => /\d+ chars/.test(e)));
+ });
+
+ test("bad confidence and scope enums are rejected", () => {
+ assert.equal(validateMemory({ ...OK, confidence: "pretty sure" }, ctx).ok, false);
+ assert.equal(validateMemory({ ...OK, scope: "universe" }, ctx).ok, false);
+ });
+
+ test("projects must be an array, not a string", () => {
+ const r = validateMemory({ ...OK, projects: "pocket" }, ctx);
+ assert.equal(r.ok, false);
+ assert.ok(r.errors.some((e) => /multi-valued/i.test(e)));
+ });
+
+ test("project slugs with separators or spaces are rejected", () => {
+ for (const bad of ["../etc", "a/b", "has space", "semi;colon", ""]) {
+ assert.equal(validateMemory({ ...OK, projects: [bad] }, ctx).ok, false, `should reject ${JSON.stringify(bad)}`);
+ }
+ });
+
+ test("non-string project entries are rejected rather than coerced", () => {
+ assert.equal(validateMemory({ ...OK, projects: [42] }, ctx).ok, false);
+ assert.equal(validateMemory({ ...OK, projects: [null] }, ctx).ok, false);
+ assert.equal(validateMemory({ ...OK, projects: [{}] }, ctx).ok, false);
+ });
+
+ test("null and undefined input do not throw", () => {
+ assert.equal(validateMemory(null, ctx).ok, false);
+ assert.equal(validateMemory(undefined, ctx).ok, false);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 6. Slug and path — the hostile section
+// ---------------------------------------------------------------------------
+
+describe("slug and path safety", () => {
+ test("path separators cannot survive a title", () => {
+ assert.ok(!slugify("a/b\\c").includes("/"));
+ assert.ok(!slugify("a/b\\c").includes("\\"));
+ });
+
+ test("traversal is neutralised", () => {
+ const s = slugify("../../etc/passwd");
+ assert.ok(!s.includes(".."));
+ assert.ok(!s.includes("/"));
+ });
+
+ test("windows reserved stems are escaped", () => {
+ for (const name of ["CON", "con", "PRN", "AUX", "NUL", "COM1", "LPT9"]) {
+ assert.ok(slugify(name).startsWith("_"), `${name} must not be a bare reserved name`);
+ }
+ });
+
+ test("trailing dots and spaces are folded (NTFS strips them silently)", () => {
+ assert.ok(!/[. ]$/.test(slugify("trailing dots...")));
+ assert.ok(!/[. ]$/.test(slugify("trailing space ")));
+ });
+
+ test("long titles are truncated on a word boundary", () => {
+ const s = slugify("the quick brown fox jumps over the lazy dog and keeps running for a very long time indeed");
+ assert.ok(s.length <= 60);
+ assert.ok(!s.endsWith(" "));
+ });
+
+ test("unicode titles survive as filenames", () => {
+ assert.ok(slugify("日本語のメモ").length > 0);
+ assert.ok(slugify("café déjà vu").length > 0);
+ });
+
+ test("a title that slugifies to nothing is rejected, not written as a dotfile", () => {
+ for (const bad of ["...", "///", " ", "***"]) {
+ const r = validateMemory({ ...OK, title: bad }, { now: DAY, origin: "p" });
+ assert.equal(r.ok, false, `should reject title ${JSON.stringify(bad)}`);
+ }
+ });
+
+ test("newlines in a title cannot break the path or the H1", () => {
+ const s = slugify("line one\nline two");
+ assert.ok(!s.includes("\n"));
+ });
+
+ test("the month folder is zero-padded and the year splits correctly", () => {
+ assert.equal(memoryPath(new Date(2026, 0, 5), "x"), "memories/2026/01/2026-01-05 x.md");
+ assert.equal(memoryPath(new Date(2026, 11, 31), "x"), "memories/2026/12/2026-12-31 x.md");
+ });
+
+ test("a custom memory root is honoured (config, not hardcoded)", () => {
+ assert.ok(memoryPath(DAY, "x", "recall").startsWith("recall/2026/07/"));
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 7. YAML safety — frontmatter that fails to parse is invisible
+// ---------------------------------------------------------------------------
+
+describe("frontmatter safety", () => {
+ test("quotes and colons in the body cannot break the description", () => {
+ const body =
+ 'He said: "it fails", and the config had key: value pairs inline — which is exactly the shape that breaks naive YAML.';
+ const v = validateMemory({ ...OK, body }, { now: DAY, origin: "p" });
+ const desc = fmRequired(renderMemory(v.value!, []), "description");
+ assert.doesNotThrow(() => JSON.parse(desc), "description must be a valid double-quoted scalar");
+ });
+
+ test("a newline in the body never reaches the description as a literal", () => {
+ const v = validateMemory({ ...OK, body: "first line\nsecond line, long enough to pass the minimum length check." }, { now: DAY, origin: "p" });
+ const desc = fmRequired(renderMemory(v.value!, []), "description");
+ assert.ok(!desc.includes("\n"));
+ assert.doesNotThrow(() => JSON.parse(desc));
+ });
+
+ test("an origin with a quote cannot escape its scalar", () => {
+ const v = validateMemory(OK, { now: DAY, origin: 'we"ird' });
+ const md = renderMemory(v.value!, []);
+ assert.doesNotThrow(() => JSON.parse(fmRequired(md, "origin")));
+ });
+
+ test("description stays within the vault's ~150 char convention", () => {
+ const v = validateMemory({ ...OK, body: "word ".repeat(200) }, { now: DAY, origin: "p" });
+ assert.ok(deriveDescription(v.value!.body).length <= 152);
+ });
+
+ test("frontmatter opens and closes exactly once", () => {
+ const v = validateMemory(OK, { now: DAY, origin: "p" });
+ const md = renderMemory(v.value!, []);
+ assert.equal((md.match(/^---$/gm) || []).length, 2);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 8. Write collisions — never clobber
+// ---------------------------------------------------------------------------
+
+describe("write collisions", () => {
+ test("two memories with the same title on the same day do not overwrite", () => {
+ const dir = tmpVault();
+ try {
+ const v = validateMemory(OK, { now: DAY, origin: "p" }).value!;
+ const a = writeMemory(dir, v, []);
+ const b = writeMemory(dir, { ...v, body: "different body, same title, same day, still needs saving." }, []);
+ assert.notEqual(a.rel, b.rel);
+ assert.ok(b.rel.includes("(2)"));
+ assert.ok(readMemory(dir, a.rel).includes(OK.body), "the first memory must survive intact");
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test("the collision suffix keeps the .md extension", () => {
+ const dir = tmpVault();
+ try {
+ const v = validateMemory(OK, { now: DAY, origin: "p" }).value!;
+ writeMemory(dir, v, []);
+ assert.ok(writeMemory(dir, v, []).rel.endsWith(".md"));
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test("missing month folders are created", () => {
+ const dir = tmpVault();
+ try {
+ const v = validateMemory(OK, { now: new Date(2027, 2, 3), origin: "p" }).value!;
+ assert.ok(existsSync(writeMemory(dir, v, []).full));
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 9. Containment property — the fuzz pass
+// ---------------------------------------------------------------------------
+
+describe("containment property", () => {
+ /**
+ * The one invariant that must hold for EVERY input: whatever a caller puts
+ * in a title, the resolved write path stays inside the memory root. A single
+ * escape here is an arbitrary-file-write through a tool description.
+ */
+ test("no title can produce a path outside the memory root", () => {
+ const hostile = [
+ "../../../etc/passwd",
+ "..\\..\\windows\\system32\\config",
+ "/etc/shadow",
+ "C:\\Windows\\System32",
+ "....//....//escape",
+ "a\u0000b",
+ "\u202Egnp.exe",
+ "CON",
+ "....",
+ "~/.ssh/authorized_keys",
+ "%2e%2e%2f",
+ "a".repeat(500),
+ "🙂".repeat(80),
+ "\n\n../x",
+ "..",
+ ".",
+ ];
+ const root = resolve("/vault");
+ for (const title of hostile) {
+ const slug = slugify(title);
+ if (!slug) continue; // rejected upstream by validateMemory
+ const rel = memoryPath(DAY, title);
+ const full = resolve(root, rel);
+ assert.ok(
+ full.startsWith(resolve(root, MEMORY_ROOT) + sep),
+ `escaped containment: ${JSON.stringify(title)} -> ${full}`,
+ );
+ assert.ok(!rel.includes(".."), `traversal survived: ${JSON.stringify(title)}`);
+ }
+ });
+
+ test("random titles always yield a containable, single-segment filename", () => {
+ const alphabet = "abc /\\.:*?\"<>|\u0000\n\t~%-_日🙂";
+ let checked = 0;
+ for (let i = 0; i < 400; i++) {
+ let title = "";
+ const len = 1 + ((i * 7) % 40);
+ for (let j = 0; j < len; j++) title += alphabet[(i * 13 + j * 31) % alphabet.length];
+ const slug = slugify(title);
+ if (!slug) continue;
+ assert.ok(!slug.includes("/"), `slug kept a separator: ${JSON.stringify(slug)}`);
+ assert.ok(!slug.includes("\\"), `slug kept a backslash: ${JSON.stringify(slug)}`);
+ assert.ok(!slug.includes(".."), `slug kept a traversal: ${JSON.stringify(slug)}`);
+ assert.ok(!/[. ]$/.test(slug), `slug ended in dot/space: ${JSON.stringify(slug)}`);
+ checked++;
+ }
+ assert.ok(checked > 100, `expected many usable slugs, got ${checked}`);
+ });
+
+ test("a memory written from a hostile title lands inside the vault", () => {
+ const dir = tmpVault();
+ try {
+ const v = validateMemory({ ...OK, title: "../../escape attempt" }, { now: DAY, origin: "p" });
+ assert.equal(v.ok, true, "this title still has usable characters, so it should validate");
+ const { full } = writeMemory(dir, v.value!, []);
+ assert.ok(resolve(full).startsWith(resolve(dir, MEMORY_ROOT) + sep));
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 10. Reachability — never write a memory nobody can ever see
+// ---------------------------------------------------------------------------
+
+describe("reachability guard", () => {
+ test("a project-scoped memory with no projects and no caller identity is REFUSED", () => {
+ // The observed hole: a client that never answered roots/list writes a
+ // memory that validates, indexes, reports success — and is invisible to
+ // every caller forever.
+ const r = validateMemory(OK, { now: DAY, origin: null });
+ assert.equal(r.ok, false);
+ assert.ok(r.errors.some((e) => /reach nobody/i.test(e)));
+ assert.ok(r.errors.some((e) => /general/.test(e)), "the error must name the way out");
+ });
+
+ test("the same memory is fine once the caller has an identity", () => {
+ assert.equal(validateMemory(OK, { now: DAY, origin: "atlas" }).ok, true);
+ });
+
+ test("the same memory is fine once it names its projects", () => {
+ assert.equal(validateMemory({ ...OK, projects: ["atlas"] }, { now: DAY, origin: null }).ok, true);
+ });
+
+ test("an explicitly general memory needs neither", () => {
+ const r = validateMemory({ ...OK, scope: "general" }, { now: DAY, origin: null });
+ assert.equal(r.ok, true);
+ assert.equal(r.value!.scope, "general");
+ });
+
+ test("a platform-scoped memory naming no platforms is REFUSED", () => {
+ const r = validateMemory({ ...OK, scope: "platform" }, { now: DAY, origin: "atlas" });
+ assert.equal(r.ok, false);
+ assert.ok(r.errors.some((e) => /reach nobody/i.test(e)));
+ });
+
+ test("a platform-scoped memory naming platforms is fine", () => {
+ assert.equal(
+ validateMemory({ ...OK, scope: "platform", platforms: ["ios"] }, { now: DAY, origin: "atlas" }).ok,
+ true,
+ );
+ });
+
+ test("refusing beats widening — an unscopable memory never becomes general", () => {
+ // Silently granting the WIDEST reach because the narrowest could not be
+ // determined is the opposite of what narrowing is for.
+ const r = validateMemory(OK, { now: DAY, origin: null });
+ assert.equal(r.value!, null, "nothing is written at all");
+ });
+
+ test("every memory that validates is visible to at least one caller", () => {
+ // The property the guard exists to hold. Any accepted memory must have a
+ // facet some caller could match.
+ const cases: [MemoryInput, { now: Date; origin: string | null }][] = [
+ [{ ...OK, projects: ["atlas"] }, { now: DAY, origin: null }],
+ [{ ...OK }, { now: DAY, origin: "atlas" }],
+ [{ ...OK, scope: "general" }, { now: DAY, origin: null }],
+ [{ ...OK, scope: "platform", platforms: ["ios"] }, { now: DAY, origin: "atlas" }],
+ ];
+ for (const [input, ctx] of cases) {
+ const r = validateMemory(input, ctx);
+ assert.equal(r.ok, true, JSON.stringify(r.errors));
+ const reachable =
+ r.value!.scope === "general" || r.value!.projects.length > 0 || r.value!.platforms.length > 0;
+ assert.ok(reachable, `accepted an unreachable memory: ${JSON.stringify(r.value!)}`);
+ }
+ });
+});
diff --git a/.claude/scripts/tests/om-mcp.integration.test.ts b/.claude/scripts/tests/om-mcp.integration.test.ts
new file mode 100644
index 0000000..b9da2ca
--- /dev/null
+++ b/.claude/scripts/tests/om-mcp.integration.test.ts
@@ -0,0 +1,295 @@
+/**
+ * The server, over real MCP JSON-RPC on stdio.
+ *
+ * Nothing here imports the modules directly — it spawns the launcher and
+ * speaks the protocol, exactly as a client does. That distinction has already
+ * earned its keep three times: a query filter that hid what an unfiltered call
+ * showed, a recall that returned a path the caller could not open, and a
+ * sanitiser that destroyed every URI in every error message. All three passed
+ * the unit suites.
+ *
+ * THE HANDSHAKE IS LOAD-BEARING. A client must advertise the `roots` capability
+ * AND send `notifications/initialized`, then answer the server's `roots/list`.
+ * Skip any of it and the caller is anonymous, sees only general-scoped
+ * memories, and the result is indistinguishable from an empty vault.
+ */
+
+import { test, describe, before, after } from "node:test";
+import assert from "node:assert/strict";
+import { spawn, type ChildProcess } from "node:child_process";
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync, existsSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, dirname } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const SCRIPTS = join(dirname(fileURLToPath(import.meta.url)), "..");
+const LAUNCHER = join(SCRIPTS, "om-mcp.mjs");
+const CALLER = "atlas";
+const TIMEOUT = 30_000;
+
+interface Rpc {
+ id?: number;
+ method?: string;
+ result?: Record<string, unknown>;
+ error?: { code?: number; message?: string };
+}
+
+let vault: string;
+let child: ChildProcess;
+let stderr = "";
+const pending = new Map<number, (m: Rpc) => void>();
+let nextId = 0;
+
+function put(rel: string, body: string): void {
+ const full = join(vault, rel);
+ mkdirSync(dirname(full), { recursive: true });
+ writeFileSync(full, body, "utf8");
+}
+
+const send = (m: unknown): void => {
+ child.stdin?.write(JSON.stringify(m) + "\n");
+};
+
+function call(method: string, params?: unknown): Promise<Rpc> {
+ return new Promise((res, rej) => {
+ const id = ++nextId;
+ pending.set(id, res);
+ send({ jsonrpc: "2.0", id, method, params });
+ const t = setTimeout(() => {
+ if (pending.delete(id)) rej(new Error(`timeout on ${method}`));
+ }, TIMEOUT);
+ t.unref?.();
+ });
+}
+
+const textOf = (r: Rpc): string =>
+ String((r.result?.content as { text?: string }[] | undefined)?.[0]?.text ?? "");
+
+before(async () => {
+ vault = mkdtempSync(join(tmpdir(), "om-int-"));
+ put(
+ "vault-manifest.json",
+ JSON.stringify({ template: "obsidian-mind", qmd_index: "om-int-test", mcp_exposed_roots: ["brain", "reference"] }),
+ );
+ put("brain/Gotchas.md", '---\ndate: 2026-07-26\ndescription: "things that bit us"\n---\n\n# Gotchas\n\nSee [[Patterns]].\n');
+ put("brain/Patterns.md", '---\ndate: 2026-07-26\ndescription: "how we do things"\n---\n\n# Patterns\n\nRelated: [[Gotchas]].\n');
+ put("reference/Arch.md", '---\ndate: 2026-07-26\ndescription: "architecture"\n---\n\n# Arch\n');
+ put("work/Secret.md", '---\ndate: 2026-07-26\ndescription: "CONFIDENTIAL"\n---\n\n# Secret\n');
+ put("work/atlas.md", "---\ndate: 2026-07-26\nplatforms: [ios]\n---\n\n# atlas\n");
+
+ child = spawn(process.execPath, [LAUNCHER], {
+ stdio: ["pipe", "pipe", "pipe"],
+ env: { ...process.env, OM_VAULT_PATH: vault },
+ });
+ child.stderr?.on("data", (d) => (stderr += String(d)));
+
+ let buf = "";
+ child.stdout?.on("data", (d) => {
+ buf += String(d);
+ let nl: number;
+ while ((nl = buf.indexOf("\n")) >= 0) {
+ const line = buf.slice(0, nl).trim();
+ buf = buf.slice(nl + 1);
+ if (!line) continue;
+ let msg: Rpc;
+ try {
+ msg = JSON.parse(line) as Rpc;
+ } catch {
+ continue;
+ }
+ // The server asking who we are. Answering is what makes this session
+ // identified rather than anonymous.
+ if (msg.method === "roots/list") {
+ send({ jsonrpc: "2.0", id: msg.id, result: { roots: [{ uri: `file:///C:/Dev/${CALLER}` }] } });
+ continue;
+ }
+ if (msg.method) continue;
+ const p = msg.id !== undefined ? pending.get(msg.id) : undefined;
+ if (p && msg.id !== undefined) {
+ pending.delete(msg.id);
+ p(msg);
+ }
+ }
+ });
+
+ const init = await call("initialize", {
+ protocolVersion: "2025-11-25",
+ capabilities: { roots: { listChanged: true } },
+ clientInfo: { name: "integration", version: "1" },
+ });
+ assert.equal((init.result?.serverInfo as { name?: string })?.name, "om");
+ send({ jsonrpc: "2.0", method: "notifications/initialized" });
+ await new Promise((r) => setTimeout(r, 300));
+});
+
+after(() => {
+ child?.kill();
+ if (vault) rmSync(vault, { recursive: true, force: true });
+});
+
+describe("the om server on the wire", () => {
+ test("the contract reaches the calling session", async () => {
+ const init = await call("initialize", { protocolVersion: "2025-11-25", capabilities: {} });
+ const instructions = String(init.result?.instructions ?? "");
+ assert.match(instructions, /personal knowledge vault/);
+ assert.match(instructions, /Claude-Session:/, "the prohibition is the half that actually propagates");
+ });
+
+ test("every tool is declared with behaviour annotations", async () => {
+ const r = await call("tools/list");
+ const tools = (r.result?.tools ?? []) as { name: string; annotations?: Record<string, unknown> }[];
+ const names = tools.map((t) => t.name).sort();
+ assert.deepEqual(names, ["expand", "health", "recall", "record_work", "remember", "search"]);
+ for (const t of tools) {
+ assert.ok(t.annotations, `${t.name} must annotate so a client can pick without trial-and-error`);
+ }
+ });
+
+ test("the resource listing honours the policy — work/ never appears", async () => {
+ const r = await call("resources/list");
+ const uris = ((r.result?.resources ?? []) as { uri: string }[]).map((x) => x.uri);
+ assert.equal(uris.length, 3);
+ assert.ok(!uris.some((u) => u.toLowerCase().includes("work")), uris.join(" "));
+ assert.ok(!uris.some((u) => u.toLowerCase().includes("secret")), uris.join(" "));
+ });
+
+ test("an exposed note reads back", async () => {
+ const r = await call("resources/read", { uri: "vault://note/brain/Gotchas.md" });
+ const contents = (r.result?.contents ?? []) as { text?: string }[];
+ assert.match(String(contents[0]?.text), /# Gotchas/);
+ });
+
+ test("an unserved note is refused, and the error keeps the URI intact", async () => {
+ const r = await call("resources/read", { uri: "vault://note/work/Secret.md" });
+ assert.ok(r.error, "must refuse");
+ // Regression: the sanitiser matched "t://note/..." as a drive path and
+ // returned "vaul<path>", destroying every URI in every error message.
+ assert.match(String(r.error?.message), /vault:\/\/note\/work\/Secret\.md/);
+ });
+
+ test("expand walks the graph", async () => {
+ const r = await call("tools/call", { name: "expand", arguments: { note: "Gotchas" } });
+ assert.match(textOf(r), /Patterns/);
+ });
+
+ test("health names the caller and its platforms", async () => {
+ const r = await call("tools/call", { name: "health", arguments: {} });
+ const t = textOf(r);
+ assert.match(t, new RegExp(`Caller: ${CALLER}`));
+ // The platform comes from work/atlas.md, which is OUTSIDE the exposure
+ // fence — proof the caller-identity lookup is not scoped by it.
+ assert.match(t, /Platforms: ios/);
+ });
+
+ test("recall on an empty store explains itself rather than returning nothing", async () => {
+ const r = await call("tools/call", { name: "recall", arguments: { explain: true } });
+ const t = textOf(r);
+ assert.match(t, /No memories are scoped to reach "atlas"/);
+ assert.match(t, /health/, "a dead end must point at the diagnostic");
+ });
+
+ test("remember previews without writing", async () => {
+ const r = await call("tools/call", {
+ name: "remember",
+ arguments: {
+ title: "an integration lesson about token expiry",
+ body: "Recorded by the integration test to prove the write path renders a real note.",
+ confidence: "verified",
+ verification: "observed directly in this run",
+ scope: "project",
+ projects: [CALLER],
+ dry_run: true,
+ },
+ });
+ const t = textOf(r);
+ assert.match(t, /Preview \(nothing written\)/);
+ assert.match(t, /source: mcp-capture/, "the rendered note carries its provenance");
+ });
+
+ test("an unknown tool is an error, not a silent success", async () => {
+ const r = await call("tools/call", { name: "nope", arguments: {} });
+ assert.ok(r.error);
+ assert.equal(r.error?.code, -32602);
+ });
+
+ test("prompts are offered and render an instruction", async () => {
+ const list = await call("prompts/list");
+ assert.equal(((list.result?.prompts ?? []) as unknown[]).length, 2);
+ const got = await call("prompts/get", { name: "prior_art", arguments: { question: "should we cache this" } });
+ const messages = (got.result?.messages ?? []) as { content?: { text?: string } }[];
+ assert.match(String(messages[0]?.content?.text), /should we cache this/);
+ });
+
+ test("record_work files a note and refuses an undeclared destination", async () => {
+ const ok = await call("tools/call", {
+ name: "record_work",
+ arguments: {
+ title: "Wire up the archive command",
+ summary: "Added the archive command behind a flag, with the reasoning recorded.",
+ changes: ["src/store.ts - added a pure archive()"],
+ informed_by: ["Gotchas", "A Note That Does Not Exist"],
+ folder: "brain",
+ },
+ });
+ const t = textOf(ok);
+ assert.match(t, /Recorded: brain\//);
+
+ const filed = readFileSync(join(vault, t.split("\n")[0]!.replace("Recorded: ", "")), "utf8");
+ assert.match(filed, /source_repo: atlas/, "provenance is derived, not asserted by the caller");
+ assert.match(filed, /- \[\[Gotchas\]\]/, "a resolvable reference becomes a link");
+ assert.match(filed, /_\(no note yet\)_/, "an unresolvable one must NOT become a broken link");
+
+ // The exposed roots bound writes too, not only reads.
+ const denied = await call("tools/call", {
+ name: "record_work",
+ arguments: { title: "sneak", summary: "should not land", folder: "work" },
+ });
+ assert.match(textOf(denied), /Not recorded:.*not an exposed root/);
+ assert.ok(!existsSync(join(vault, "work", "sneak.md")));
+ });
+
+ test("a memory written through remember comes back through recall", async () => {
+ // The whole point of the layer, asserted end to end over the wire: a write
+ // that cannot be read back is not a memory, and both halves must agree
+ // about scope without either being told what the other did.
+ const wrote = await call("tools/call", {
+ name: "remember",
+ arguments: {
+ title: "tsup externals decide what a patch can fix",
+ body: "A dependency marked external is resolved on the user's machine at install time, so a local patch never reaches them.",
+ confidence: "verified",
+ verification: "Checked the built artifact directly.",
+ scope: "project",
+ projects: [CALLER],
+ },
+ });
+ assert.match(textOf(wrote), /Recorded: memories\//);
+
+ const back = await call("tools/call", { name: "recall", arguments: {} });
+ const t = textOf(back);
+ assert.match(t, /tsup externals decide what a patch can fix/);
+ assert.match(t, /verified/, "the confidence marker survives the round trip");
+
+ // Writing the same lesson again must be caught rather than duplicated.
+ const dup = await call("tools/call", {
+ name: "remember",
+ arguments: {
+ title: "tsup externals decide what a patch can fix",
+ body: "A dependency marked external is resolved on the user's machine at install time, so a local patch never reaches them.",
+ confidence: "verified",
+ verification: "Checked the built artifact directly.",
+ scope: "project",
+ projects: [CALLER],
+ },
+ });
+ assert.match(textOf(dup), /near-identical memory already exists/);
+ });
+
+ test("ping works", async () => {
+ assert.ok((await call("ping")).result);
+ });
+
+ test("STDERR STAYS EMPTY — a stray byte on the wire corrupts the stream", () => {
+ assert.equal(stderr.trim(), "", stderr.slice(0, 400));
+ });
+});
diff --git a/.claude/scripts/tidy-fix.ts b/.claude/scripts/tidy-fix.ts
index 4c3b0da..8f081d7 100644
--- a/.claude/scripts/tidy-fix.ts
+++ b/.claude/scripts/tidy-fix.ts
@@ -58,7 +58,7 @@ import {
scanActiveHygiene,
walkMarkdown,
} from "./lib/active-hygiene.ts";
-import { generateMemoryIndex } from "./lib/memory-index.ts";
+import { generateMemoryIndex } from "./lib/automemory-index.ts";
import { collectBrainNotes } from "./generate-memory-index.ts";
const ACTIVE_REL = "work/active";
diff --git a/.gitignore b/.gitignore
index aca7754..339b43b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -36,3 +36,9 @@ node_modules/
# Hook runtime state (local, self-pruning / debounce sentinel)
.claude/scripts/.hint-state.json
.claude/scripts/.qmd-refresh-sentinel
+
+# MCP server audit log — every vault read, with the calling repo and the query
+# text. Local forensics, never history: it churns on every session, and the
+# query strings are the user's own thinking.
+.claude/om-mcp-audit.jsonl
+.claude/om-mcp-audit.jsonl.1
diff --git a/AGENTS.md b/AGENTS.md
index 5d4c27c..6f0ad61 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -23,7 +23,7 @@ The hook scripts in `.claude/scripts/` are agent-agnostic TypeScript and shell,
## Commands
-18 commands in `.claude/commands/` — agent-agnostic markdown with YAML frontmatter.
+Commands live in `.claude/commands/` — agent-agnostic markdown with YAML frontmatter. `brain/Skills.md` is the catalog.
- **Claude Code / Gemini CLI**: invoke as `/om-standup`, `/om-dump`, etc.
- **Codex CLI**: type the command name as a regular prompt without the `/` prefix (e.g. `om-standup`). Codex will find and execute the command file.
@@ -34,6 +34,14 @@ The vault's memory lives in `brain/` — `Memories.md`, `Patterns.md`, `Key Deci
The `~/.claude/` auto-loaded memory index is Claude Code-specific — skip that section in `CLAUDE.md`. The vault-side `brain/` notes are the source of truth.
+## Reaching this vault from another repo
+
+The `om` MCP server (`.claude/scripts/om-mcp.mjs`) exposes this vault over MCP, so a session running in a **different repository** can search it, read notes, follow the graph, and record durable lessons back into it. It speaks plain MCP over stdio, so any MCP-capable agent can register it — nothing about it is Claude Code-specific.
+
+Register it in the *consuming* project's MCP config, pointing at this vault's absolute path, then add a short section to that project's own agent doc telling it the vault exists. **Both steps are required**: measured, a session with the server wired but no repo-side instruction made zero vault calls, because a prohibition propagates into a session reliably while a positive "go look" does not.
+
+Do not register the raw `qmd` server in a consuming repo — it searches every note directly, so the repo matches against memories written for unrelated projects. Applying each memory's declared scope on top of the index is what `om` adds. Full details in `CLAUDE.md`.
+
## Subagents
9 subagents in `.claude/agents/` handle isolated tasks (brag spotting, vault auditing, cross-linking, etc.). The prompt content is agent-agnostic markdown.
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index b3e62f8..563fd5d 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -8,41 +8,56 @@ It is not a folder tour. For the day-to-day layout, read `CLAUDE.md`. For the us
## System Overview
-obsidian-mind is a plain Obsidian vault with three systems layered on top:
+obsidian-mind is a plain Obsidian vault with four systems layered on top:
1. **The vault itself** — Markdown files, frontmatter, wikilinks. Portable, git-tracked, Obsidian-browsable.
2. **A hook pipeline** — small TypeScript scripts invoked by the agent harness at lifecycle events (session start, every message, after writes, before compaction, at session end).
3. **A semantic search layer (QMD)** — a separate CLI + SQLite index + MCP server, all scoped to a named index read from `vault-manifest.json`.
+4. **The `om` MCP server** — the vault as a service, so a session running in a *different repository* can search it, read notes, follow the graph, and record back into it.
-The three layers communicate through one coordination point: **`vault-manifest.json`**. It declares the template version, the QMD index name, and the boundary between infrastructure files (shipped by the template) and user content (created by the human).
+The layers communicate through one coordination point: **`vault-manifest.json`**. It declares the template version, the QMD index name, which folders the server serves, where memories live, and the boundary between infrastructure files (shipped by the template) and user content (created by the human).
+
+The fourth layer is the one that changes the shape of the system. Layers 1–3 assume the agent is *sitting in the vault*; `om` removes that assumption, which is why identity — "which repo is asking?" — becomes a first-class concept below.
```mermaid
flowchart TB
User["Human operator"]
- subgraph Agent["AI coding agent (Claude Code / Codex / Gemini)"]
+ subgraph Agent["Agent session INSIDE the vault"]
Harness["Agent harness"]
Hooks["Hook pipeline<br/>(.claude/scripts/)"]
- MCP["MCP tools"]
+ end
+ subgraph Foreign["Agent session in ANOTHER repo"]
+ FSession["Coding session"]
+ FConfig[".mcp.json entry<br/>+ that repo's own CLAUDE.md"]
end
subgraph Vault["Obsidian vault"]
Manifest["vault-manifest.json<br/>(source of truth)"]
Notes["Markdown notes<br/>(work/, perf/, brain/, org/)"]
+ Memories["memories/<br/>(cross-repo, scope declared per memory)"]
Config[".claude/ .codex/ .gemini/<br/>(hook configs)"]
end
+ OM["om MCP server<br/>(om-mcp.ts)"]
QMD["QMD<br/>(named SQLite index + embeddings)"]
Obsidian["Obsidian app<br/>(graph, Bases, CLI)"]
User <--> Agent
+ User <--> Foreign
User <--> Obsidian
Harness --> Hooks
- Harness --> MCP
+ Harness -->|"mcp__qmd__*"| QMD
Hooks --> Manifest
Hooks --> Notes
Hooks --> QMD
- MCP --> QMD
+ Config --> Hooks
+ FConfig --> FSession
+ FSession <-->|"MCP over stdio"| OM
+ OM --> Manifest
+ OM --> Notes
+ OM --> Memories
+ OM -->|"MCP client"| QMD
QMD --> Notes
+ QMD --> Memories
Obsidian --> Notes
- Config --> Hooks
```
The vault is the persistent state. Everything else is machinery around it.
@@ -53,7 +68,7 @@ The vault is the persistent state. Everything else is machinery around it.
Two actors do the work, and the boundary between them is the most important design choice in the system.
-**Procedural code owns the environment.** Hooks in `.claude/scripts/` classify messages, validate writes, maintain the QMD index, inject context at session start, and back up transcripts before compaction. None of this logic is in the agent's head. It runs identically whether the agent is Claude Code, Codex, or Gemini, and it produces deterministic, testable behavior — the hook test suite has 400+ unit tests locking the contracts.
+**Procedural code owns the environment.** Hooks in `.claude/scripts/` classify messages, validate writes, maintain the QMD index, inject context at session start, and back up transcripts before compaction. None of this logic is in the agent's head. It runs identically whether the agent is Claude Code, Codex, or Gemini, and it produces deterministic, testable behavior — every contract in `.claude/scripts/lib/` is locked by a unit suite, run in CI on every push.
**The agent owns content.** Writing notes, choosing where to file them, adding wikilinks, updating indexes, promoting thinking drafts, drafting review briefs — these are judgments, not rules, and they live with the agent. `CLAUDE.md` documents the conventions the agent should follow; it does not replace the agent's judgment.
@@ -73,6 +88,10 @@ Folders group by purpose. Links group by meaning. A note lives in one folder (it
All durable knowledge lives in the vault, inside `brain/` topic notes. The agent-specific memory indexes (`~/.claude/.../MEMORY.md`) are pointers to vault locations, never the storage themselves. This keeps memory git-tracked, machine-portable, and visible in the Obsidian graph.
+The `om` server extends this outward rather than around it. A session in another repo writes into `memories/` — still Markdown, still in the graph, still yours to open in Obsidian — instead of into a private store belonging to some memory service. A generic memory server solves the wrong half of the problem: it gives you a *second* knowledge base that is not your vault.
+
+Because those memories are written from many repos and read by many repos, each one **declares its reach when written** — which projects and platforms it applies to. A reader never widens what a writer declared. That is a relevance rule, not an access-control rule: the store is the user's, the sessions are the user's, and the question being answered is "which lessons bear on the repo asking?" — not "who is allowed to know this?"
+
### 3. Progressive disclosure
`SessionStart` injects a small block of lightweight context (North Star excerpt, git summary, tasks, file listing). Full note contents are pulled on demand via QMD semantic search. A full file read is a last resort, not a default.
@@ -91,35 +110,45 @@ The hook scripts, subagent prompts, command definitions, and vault conventions a
## The Manifest as Source of Truth
-`vault-manifest.json` is the one file that every layer reads. It answers five questions:
+`vault-manifest.json` is the one file that every layer reads. It answers seven questions:
| Question | Field |
|----------|-------|
| What version of the template is this? | `version`, `released`, `version_fingerprints` |
-| What does QMD call its store? | `qmd_index`, `qmd_context` |
+| What does QMD call its store? | `qmd_index`, `qmd_context`, `qmd_min_version` |
| Which files are template infrastructure? | `infrastructure[]` |
| Which files are user content? | `user_content_roots[]`, `scaffold{}` |
| What frontmatter is required for each note type? | `frontmatter_required{}` |
+| Which notes does the `om` server serve, and where do memories live? | `mcp_exposed_roots[]`, `mcp_never_expose[]`, `memory_root`, `mcp_inbox` |
+| How much context may the eager layer spend? | `eager_layer_budget_bytes`, `listing_collapse_threshold` |
-The `qmd_index` field is the most load-bearing. Three independent callers read it:
+The `qmd_index` field is the most load-bearing. **Five independent callers** read it, and they fail *silently* when they disagree — one writes to a store another never reads, which surfaces only as "0 documents" or as an empty search:
```mermaid
flowchart LR
- Manifest["vault-manifest.json<br/>qmd_index (or folder slug)"]
+ Manifest["vault-manifest.json<br/>qmd_index, or the folder slug"]
+ Boot["qmd-bootstrap.ts<br/>(one-time setup)"]
SessionStart["SessionStart hook<br/>(session-start.ts)"]
MCP[".mcp.json wrapper<br/>(qmd-mcp.mjs)"]
- Refresh["Mid-session refresh<br/>(PostToolUse / Stop / PreCompact<br/>→ qmd-refresh-run.ts worker)"]
- Store[("QMD SQLite store<br/>(named: obsidian-mind)")]
+ Refresh["Mid-session refresh<br/>PostToolUse / Stop / PreCompact<br/>→ qmd-refresh-run.ts worker"]
+ OM["om MCP server<br/>(mcp-context.ts)"]
+ Store[("QMD SQLite store<br/>named per vault")]
+ Manifest --> Boot
Manifest --> SessionStart
Manifest --> MCP
Manifest --> Refresh
- SessionStart -->|re-index at startup| Store
- Refresh -->|debounced refresh| Store
- MCP -->|search tools| Store
+ Manifest --> OM
+ Boot -->|"create + first index"| Store
+ SessionStart -->|"re-index at startup"| Store
+ Refresh -->|"debounced refresh"| Store
+ MCP -->|"search tools"| Store
+ OM -->|"search, and re-index after a write"| Store
```
-Because all three callers resolve the index name the same way — the `qmd_index` field when pinned, otherwise the vault folder name slugified — the vault coexists with other QMD-indexed projects on the same machine without collision. The template ships the field empty so two installs never share a store by default. Set `qmd_index` and the next bootstrap creates a fresh, isolated store under that name.
+All five resolve the name through one function, `resolveQmdIndex` — the `qmd_index` field when pinned, otherwise the vault folder name slugified — so the vault coexists with other QMD-indexed projects on the same machine without collision. The template ships the field empty so two installs never share a store by default. Set `qmd_index` and the next bootstrap creates a fresh, isolated store under that name.
+
+Routing every caller through one resolver is the fix for a real class of failure rather than a tidiness preference: a hardcoded or independently-derived name in any one of the five produces a vault that indexes into one store and searches another, with nothing anywhere reporting an error. `health` on the `om` server checks that the index it would query actually belongs to this vault.
The `infrastructure[]` vs `user_content_roots[]` split is what makes `/om-vault-upgrade` work. When importing from an older template, the migrator overwrites infrastructure files wholesale and preserves user content untouched.
@@ -141,7 +170,7 @@ sequenceDiagram
Agent->>Hooks: SessionStart
Hooks->>Vault: read North Star, git log, tasks, file listing
Hooks->>QMD: re-index (async)
- Hooks-->>Agent: inject ~2K tokens of context
+ Hooks-->>Agent: inject a briefing, held under the byte budget
loop each user message
User->>Agent: prompt
@@ -168,7 +197,7 @@ sequenceDiagram
A few specific design choices are worth calling out:
-- **`SessionStart` injects, it does not load.** It builds a ~2K-token briefing (filename listing, North Star excerpt, git summary, open tasks aggregated from `work/active/` and the vault root) and hands it to the agent. Full note contents never flow through this hook. The open-tasks scan is filesystem-only so the hook never spawns the Obsidian CLI — that subprocess flashes the Electron app on macOS when no instance is running (#83).
+- **`SessionStart` injects, it does not load.** It builds a briefing (filename listing, North Star excerpt, git summary, open tasks aggregated from `work/active/` and the vault root) and hands it to the agent. Full note contents never flow through this hook. Its size is bounded by `eager_layer_budget_bytes` and reported by the meter on the last line of every injection, so the cost is visible rather than assumed. The open-tasks scan is filesystem-only so the hook never spawns the Obsidian CLI — that subprocess flashes the Electron app on macOS when no instance is running (#83).
- **`UserPromptSubmit` classifies, it does not route.** It tags the prompt with hints like `ARCHITECTURE discussion` or `DECISION`; the agent decides where to file. Keeping the hook opinion-free means the routing logic lives in `CLAUDE.md`, which is editable per-user without touching scripts.
- **QMD refresh is shared, debounced, and detached.** Three hook entries fire the same refresh helper — `PostToolUse` (after `.md` writes), `PreCompact` (before transcript backup; writes tend to cluster before compaction), and `Stop` (end of session) — sharing one sentinel file so a burst of events produces at most one worker per debounce window. The actual indexing runs in `.claude/scripts/qmd-refresh-run.ts` as a detached, stdio-silent worker (`qmd update` → `qmd embed` → tail-chase `qmd update`), so the parent hook returns in milliseconds and nothing flows to the agent's context.
- **`PreCompact` also backs up the transcript.** In addition to kicking the QMD refresh, it copies the current session transcript out to `thinking/session-logs/` so long conversations remain recoverable after compaction.
@@ -178,16 +207,70 @@ A few specific design choices are worth calling out:
## QMD Integration
-QMD provides semantic search. It is the mechanism behind most of the agent's retrieval intelligence. Three entry points all read from the same named index:
+QMD provides semantic search. It is the mechanism behind most of the agent's retrieval intelligence. Four entry points all read from the same named index:
| Caller | Entry point | When |
|--------|-------------|------|
-| Agent tool menu | `.mcp.json` → `qmd-mcp.mjs` | Every `mcp__qmd__*` tool call from the agent |
+| Agent tool menu | `.mcp.json` → `qmd-mcp.mjs` | Every `mcp__qmd__*` tool call from a session inside the vault |
| Session startup | `session-start.ts` | Re-index on every new session |
-| Mid-session refresh | `qmd-refresh.ts` / `stop-checklist.ts` / `pre-compact.ts` → shared debounce → `qmd-refresh-run.ts` | After `.md` writes, at session end, and before compaction |
+| Mid-session refresh | `validate-write.ts` / `stop-checklist.ts` / `pre-compact.ts` → `lib/qmd-refresh.ts` (shared sentinel + debounce) → detached `qmd-refresh-run.ts` | After `.md` writes, at session end, and before compaction |
+| The `om` server | `lib/mcp-qmd-client.ts` (search) and `reindexSync` (after a write) | Every `search`, every queried `recall`, every `remember` / `record_work` |
Every `qmd update` invocation re-reads the per-index YAML (`~/.config/qmd/<index>.yml`), so changes to the collection config — including the ignore list synced from `.obsidian/app.json` — propagate to every surface without a session restart.
+### What QMD actually runs
+
+Worth understanding, because it explains the cost profile of everything built on top. QMD runs **three small models locally**. There is no API key, no per-query cost, and it works offline.
+
+| model | size | job |
+|---|---|---|
+| `embeddinggemma-300M` | ~328 MB | turns notes and queries into vectors |
+| `qmd-query-expansion-1.7B` | ~1.28 GB | rewrites a query into better search terms, and writes hypothetical answers for HyDE |
+| `Qwen3-Reranker-0.6B` | ~640 MB | reorders the shortlist by actual relevance |
+
+They download on first use and are cached. QMD offloads to the GPU when it finds one — CUDA on a discrete card, Metal on Apple Silicon — and falls back to CPU otherwise. `qmd doctor` reports which.
+
+The CLI verbs map onto that stack, cheapest first:
+
+| verb | what runs | cost |
+|---|---|---|
+| `qmd search` | BM25 keyword matching, **no model at all** | instant |
+| `qmd vsearch` | vector search — embeds the query, then compares | one embed |
+| `qmd query` | the full hybrid: sub-queries, then rerank | embed + optional expansion + rerank |
+| `qmd update` | parse and index note **text** | no model |
+| `qmd embed` | build the **vectors** for new or changed notes | the embedding model, per note |
+
+Two consequences shape the design of everything downstream:
+
+- **`update` and `embed` answer different questions.** `update` decides whether a note is *findable at all*; `embed` decides only where it *ranks*. They are separated everywhere in this template, and the split is why a write can report success honestly without waiting on a local model run.
+- **Reads are the expensive side, not writes.** A query has to embed before it can search, so a semantic lookup costs a model pass while a keyword lookup costs none. This is the opposite of the usual database intuition, and it is why the retrieval paths below are careful about *when* they pay for a vector.
+
+```mermaid
+flowchart LR
+ subgraph Text["Text path — no model"]
+ Update["qmd update"]
+ FTS[("BM25 / FTS index")]
+ Update --> FTS
+ end
+ subgraph Vector["Vector path — local models"]
+ Embed["qmd embed"]
+ Emb["embeddinggemma-300M"]
+ Vec[("vector index")]
+ Embed --> Emb --> Vec
+ end
+ subgraph Read["Query time"]
+ Q["qmd query"]
+ Expand["qmd-query-expansion-1.7B<br/>expansion + HyDE"]
+ Rank["Qwen3-Reranker-0.6B"]
+ Q --> Expand
+ Q --> Rank
+ end
+ FTS --> Q
+ Vec --> Q
+ Notes["Markdown notes"] --> Update
+ Notes --> Embed
+```
+
```mermaid
flowchart TB
subgraph Reader["Agent tools"]
@@ -218,7 +301,9 @@ flowchart TB
QMD is technically optional. When it isn't installed at all, the agent falls back through a preference order defined in `CLAUDE.md` and the qmd skill: MCP tools first when registered, then the `qmd` CLI, then Grep/Glob/Read as a last resort. Every fallback step is non-fatal: `.mcp.json` entries that fail to launch are skipped with a harmless warning, the hook scripts detect a missing `qmd` binary and no-op, and the operating manual tells the agent what to reach for next.
-### MCP as the agent-facing contract
+### QMD over MCP — the in-vault retrieval path
+
+> This section is about the **`qmd`** MCP server, which a session *inside* the vault uses. The **`om`** server, which a session in another repo uses, is a different thing built on top of it — see [Reaching the Vault From Another Repo](#reaching-the-vault-from-another-repo). The one rule connecting them: a consuming repo registers `om`, never raw `qmd`.
When the MCP server is registered, the agent's normal path to QMD is through typed tools — `mcp__qmd__query`, `mcp__qmd__get`, `mcp__qmd__multi_get`, and `mcp__qmd__status` — that appear in its tool menu alongside Read and Edit. These come from the [Model Context Protocol](https://modelcontextprotocol.io) server declared in `.mcp.json`, launched by a thin wrapper (`.claude/scripts/qmd-mcp.mjs`) that reads `qmd_index` from the manifest and invokes `qmd mcp` underneath. The CLI remains available — and is documented as the fallback — but during a session with MCP live, the agent goes through typed tools, not shell.
@@ -248,6 +333,374 @@ This is why the list lives in Obsidian's config and not `vault-manifest.json`: u
---
+## Reaching the Vault From Another Repo
+
+Everything above assumes the agent is running *inside* the vault. The `om` MCP server removes that assumption.
+
+### The problem, precisely
+
+A session working in your app's repo has no durable memory of why anything was decided. It re-derives context every time, asks you, or guesses. The knowledge exists — it is in your vault — but the session is in a different directory with no way to reach it.
+
+Bolting a generic memory server onto that session solves the wrong half. Those write to their own store, in their own shape, and you end up with a second knowledge base that is not your vault, not in your graph, and not yours to browse. `om` exposes the vault itself.
+
+### An MCP server is four surfaces, not one
+
+The non-tool surfaces turned out to matter more than expected, so it is worth naming all four and which direction each runs.
+
+| surface | direction | what it is | who triggers it |
+|---|---|---|---|
+| `instructions` | vault → session | the vault's rules, injected into the calling session's system prompt at connect | automatic, once per connection |
+| `tools` | session → vault | `search`, `expand`, `recall`, `remember`, `record_work`, `health` | the **model** decides |
+| `resources` | session → vault | notes listable and readable by `vault://note/<path>` URI | the model or the client |
+| `prompts` | you → vault | `recall_topic`, `prior_art` — slash commands in the calling session | the **human** decides |
+
+The split between rows 2 and 4 is load-bearing, because of an asymmetry measured while building this:
+
+> **Prohibitions propagate. Routing instructions do not.**
+
+A rule in `instructions` — *"never put a session URL in a commit"* — held under direct pressure and under an authority override. A positive instruction — *"consult the vault before answering questions about past decisions"* — is advisory and gets skipped whenever a nearer source exists. **A server can stop a session doing something; it cannot make one go looking.**
+
+That is why `prompts` exist (the human invokes them, so no model decision is involved) and why the install requires a pointer in the *consuming repo's own* `CLAUDE.md` — the nearest source wins, so the nearest source has to be the thing that says "go look."
+
+### The tier ladder
+
+| tier | what | cost at call time |
+|---|---|---|
+| **0 — presence** | the contract reaches the calling session | one-off, no extra session spawned |
+| **1 — retrieval** | `search`, `expand`, resources | seconds, **no model call** beyond the local embedding |
+| **2 — capture** | `recall`, `remember`, `record_work` | no model call |
+| 3 — reasoning | a spawned session that reads and reasons | a full session, billed to the user — tracked in #158, not shipped |
+
+Tier 0 is the counterintuitive one. The original design assumed the vault would have to *think* for you: spawn its own session, hand back an answer. That works and it is expensive. Tier 0 instead hands the calling session the vault's contract and lets it think with the model you are already paying for.
+
+### Module map
+
+The entry script is deliberately thin. It owns only what a test cannot usefully drive — resolving the vault, opening stdio, holding the lazy qmd child. Every decision worth arguing about lives in a library module that can be driven in-process.
+
+```mermaid
+flowchart TB
+ Entry["om-mcp.ts<br/>vault resolution · stdio · qmd child lifecycle"]
+ Proto["mcp-protocol.ts<br/>JSON-RPC framing · identity handshake"]
+ Ctx["mcp-context.ts<br/>vault root · manifest · index name<br/>INSTRUCTIONS · PROMPTS"]
+ Server["mcp-server.ts<br/>method → behaviour wiring"]
+ Tools["mcp-tools.ts<br/>tool declarations + annotations"]
+ Exp["mcp-exposure.ts<br/>which notes are served"]
+ Qmd["mcp-qmd-client.ts<br/>qmd MCP client + result filter"]
+ Graph["mcp-graph.ts<br/>expand: links out, links back"]
+ Caller["mcp-caller.ts<br/>identity · sanitise · audit log"]
+ Bridge["mcp-memory-bridge.ts<br/>memory ↔ vault seam"]
+ Capture["mcp-capture.ts<br/>record_work filing"]
+ subgraph Core["Memory core — no MCP knowledge at all"]
+ MW["memory-write.ts"]
+ MR["memory-recall.ts"]
+ MS["memory-similarity.ts"]
+ MSup["memory-supersede.ts"]
+ MD["memory-discover.ts"]
+ end
+
+ Entry --> Proto
+ Entry --> Ctx
+ Entry --> Server
+ Entry --> Qmd
+ Entry --> Caller
+ Server --> Tools
+ Server --> Exp
+ Server --> Graph
+ Server --> Bridge
+ Server --> Capture
+ Server --> Core
+ Graph --> Exp
+ Qmd --> Exp
+ Bridge --> Core
+ Bridge --> Qmd
+```
+
+The memory core knows nothing about MCP. That is what lets the epistemic contract be hammered by tests without an MCP client, a vault on disk, or a search index.
+
+### Connection: the identity handshake
+
+Almost everything this server does depends on **who is asking**. MCP provides that: the server can ask the client which directories the calling session has open (`roots/list`). It is derived from the client, never declared by the caller, so there is no argument through which a session could claim to be a project it is not.
+
+The complication is that the handshake is *asynchronous*, and the client's first `resources/list` arrives before it resolves.
+
+```mermaid
+sequenceDiagram
+ participant Client as Calling session
+ participant Server as om server
+ participant Repo as The repo on disk
+
+ Client->>Server: initialize
+ Server-->>Client: capabilities + INSTRUCTIONS
+ Note over Client: instructions land in the system prompt
+ Client->>Server: notifications/initialized
+ Server->>Client: roots/list (server-initiated)
+
+ par the client asks early
+ Client->>Server: resources/list
+ Note over Server: WAITS on identityReady, capped at 2s
+ and identity is still in flight
+ Client-->>Server: roots result
+ Server->>Repo: read .om-project, else use folder name
+ Note over Server: identity resolved, gate opens
+ end
+
+ Server-->>Client: resources scoped to this caller
+```
+
+Announcing `notifications/resources/list_changed` after the fact was tried first, and the client did not re-fetch — the listing simply stayed unscoped. The deterministic fix is the wait: **something that scopes by caller must not answer before it knows the caller.** The cap matters too — a client that never answers gets an anonymous, general-only view rather than a hang.
+
+The same gate reopens on `notifications/roots/list_changed`. Without that, a tool call arriving between the notification and the reply was served under the *stale* identity: the same race, one step later in the lifecycle.
+
+**Identity resolution:**
+
+```mermaid
+flowchart TB
+ R["the first root URI<br/>from the handshake"] --> P["rootToPath<br/>file:// → plain path"]
+ P --> M{".om-project<br/>at the root?"}
+ M -->|"yes, and it is a valid name"| D["declared identity"]
+ M -->|no| F["folder name, lowercased"]
+ D --> Out["caller project"]
+ F --> Out
+ Out --> Plat["platforms: read from<br/>the project's own vault note"]
+```
+
+The folder name is right until it isn't: two repos both called `api` share one identity and therefore each other's memories. `.om-project` resolves that, and `health` reports which source was used so the collision is discoverable rather than mysterious.
+
+### Which notes the server serves
+
+```mermaid
+flowchart TB
+ Start["resolveExposure"] --> A{"mcp_exposed_roots<br/>declared?"}
+ A -->|yes| Man["source: manifest"]
+ A -->|no| B{"user_content_roots<br/>present on disk?"}
+ B -->|yes| Der["source: derived"]
+ B -->|no| Fall["source: fallback<br/>brain, reference"]
+ Man --> Strip["strip the memory root — always"]
+ Der --> Strip
+ Fall --> Strip
+ Strip --> Walk["walk each root, max depth 4"]
+ Walk --> S{"entry is a symlink?"}
+ S -->|no| C{"filename in<br/>mcp_never_expose?"}
+ S -->|yes| Cont{"target resolves<br/>inside the root?"}
+ Cont -->|"no, or broken"| Drop["not served"]
+ Cont -->|yes| C
+ C -->|yes| Drop
+ C -->|no| E{"tagged private<br/>in frontmatter?"}
+ E -->|"yes, or unreadable"| Drop
+ E -->|no| Serve["served"]
+```
+
+The default is the vault's own `user_content_roots`, at the granularity the manifest declares them — `work/active/`, not all of `work/`. Roots are **path prefixes**, matched on whole segments, so `work/active` does not admit `work/active-secrets`.
+
+`mcp_exposed_roots` narrows that, and exists for the unusual vault holding material that is *not the user's to share* — employer-confidential notes, a client's data. Both exposure keys ship empty: the template must not impose one vault's sensitivities on every install.
+
+> **What this list is, and is not.** It decides which notes the server *serves*. It is not an egress control: a session started with `--add-dir` reads the whole vault regardless, so narrowing the read surface prevents nothing on its own. Keeping vault material out of a public PR is the job of the **prohibition in `instructions`** — the form measured to hold — plus the **audit log**. Reading this list as a security boundary leads to a narrow default, and a narrow default fences off the user's own project notes, which are the single most useful thing a coding session could read.
+
+Three things hold regardless of configuration:
+
+- **`memories/` is never served as an ordinary note.** Memories carry their own declared reach, evaluated per caller; the note surface would bypass it. It is stripped from the root list unconditionally, and again during the walk.
+- **A symlink is contained before it is followed.** The walk `lstat`s each entry — which describes the entry rather than its target — and resolves any link against the root's realpath. Enumerating with `stat` instead means a `.md` link inside an exposed root pulls in a file from anywhere on disk.
+- **Every read is logged** to `.claude/om-mcp-audit.jsonl` (gitignored, rotated at 5 MB, one generation kept) with the calling repo — so "what did that session actually see" is answerable afterwards.
+
+Every read surface resolves through `visibleFiles`. `search` filters its hits against it, `expand` computes backlinks only over it, and the resource enumerators build from it. This is one implementation rather than three because the recurring defect in this layer is a *second* read path that reaches notes by its own route and applies a different rule.
+
+The symlink case is that defect in its most recent form, and worth keeping as the worked example: `resolveResourceUri` did realpath containment from the start, while the enumerator followed links silently. So the resource *listing* published an out-of-vault file's description and `expand` returned its body, while reading the very same URI was refused. Both ends now contain against the **matched declared root** — not the first path segment, since roots are prefixes and `work/active/` and `work/1-1/` share one.
+
+### A `search` call, end to end
+
+```mermaid
+sequenceDiagram
+ participant Session as Calling session
+ participant OM as om server
+ participant Exp as mcp-exposure
+ participant QC as qmd client
+ participant QMD as qmd MCP server
+
+ Session->>OM: tools/call search with query and limit
+ OM->>OM: await identityReady()
+ OM->>Exp: allowedSearchPaths(vault, policy)
+ Exp-->>OM: set of vault-relative keys
+ OM->>QC: qmdSearch(allowed, query, limit)
+ QC->>QC: subQueries → lex + vec (+ hyde if question-shaped)
+ QC->>QMD: tools/call query, limit = max(limit*4, 20)
+ QMD-->>QC: structuredContent.results — the WHOLE vault
+ QC->>QC: filter each hit against allowed
+ QC-->>OM: text + withheld + total
+ OM->>OM: audit the call — query, withheld, total
+ OM-->>Session: ranked passages with note paths
+```
+
+Four details in that flow are decisions rather than mechanics:
+
+**The server is an MCP *client* of the vault's own qmd server.** Reusing the existing launcher inherits two fixes for free — the Windows `.cmd` shim workaround and the named-index pin — and the launcher is *located* rather than hardcoded, because a stale path here kills search silently.
+
+**Filter the result, never the query.** The index covers the whole vault, including memories and any folder outside the served roots. Filtering the query would require every caller to construct a scoped query correctly; filtering the result means no query a caller can write returns more than the policy serves. Refusing to answer when `structuredContent` is absent belongs to the same rule — qmd's human-readable summary carries note paths too, so falling back to it would return results nothing ever checked.
+
+**Over-fetch, then trim.** Because the filter runs on the result, asking qmd for exactly `limit` means a vault with much unserved content returns far fewer than requested with no sign that more existed. The client asks for `max(limit * 4, 20)`.
+
+**HyDE is conditional.** `lex` and `vec` always go out together — keywords find the exact term, vectors find the note that answers the question without using the word. `hyde` writes a hypothetical answer and matches against *that*, which is what finds the note whose title shares no words with the question. It runs a local generation model, so it is added only for queries that are at least four words *and* question-shaped. A two-word keyword lookup, where lexical matching is already the right tool, does not pay for it.
+
+**Degradation is explicit.** qmd is optional in this template. A failed call degrades that one search and says so; it must never present as "the vault is empty". The client tracks liveness, so one qmd crash does not disable search for the life of the server, and the entry script replaces a dead child behind a 5-second cooldown so a permanently-broken qmd cannot fork a process per call.
+
+### Which memories reach which repo
+
+This is the part the layer exists for. Every memory declares its reach **when written**, and a reader never widens what a writer declared.
+
+```yaml
+scope: project # general | platform | project
+projects: [atlas, atlas-api] # a LIST — the multi-valued axis
+platforms: [ios]
+confidence: verified
+origin: atlas # derived from the roots handshake, not caller-asserted
+session: 2026-07-26T14:02:11Z
+```
+
+The list is the load-bearing choice. **A memory is multi-valued; a folder is not.** A lesson touching two projects and a cross-cutting theme has no correct folder — you would pick one and lose the rest, or duplicate and have two sources of truth. A `memories/<project>/` taxonomy was designed and rejected for exactly this. Time is the only thing in the path, because it is the only single-valued fact about a memory:
+
+```
+memories/2026/07/2026-07-26 <title>.md
+```
+
+Visibility is evaluated in order, and the order **is** the design:
+
+```mermaid
+flowchart TB
+ M["a memory"] --> S1{"scope: general?"}
+ S1 -->|yes| V["visible"]
+ S1 -->|no| S2{"the projects list names<br/>the calling repo?"}
+ S2 -->|yes| V
+ S2 -->|no| S3{"scope: platform<br/>AND platforms overlap?"}
+ S3 -->|yes| V
+ S3 -->|no| H["not visible — default deny"]
+```
+
+- `general` reaches everyone. The only scope that does, which is why the write path polices it hardest.
+- **An explicit project listing always wins**, whatever the declared scope. This is what makes the multi-project case work: `projects: [a, b]` reaches both, and neither has to know the other exists.
+- `platform` reaches any caller sharing a platform — an iOS lesson reaches the next iOS app and must *not* reach the web one.
+- Otherwise, not visible. A near-miss does not surface.
+
+A caller with no roots sees `general` only: the safest reading of "I don't know who you are", and it degrades to useless rather than to wide-open.
+
+**Ranking, once visibility has decided the set:**
+
+```mermaid
+flowchart LR
+ A["superseded sinks<br/>below live"] --> B["specificity<br/>project &gt; platform &gt; general"]
+ B --> C["date, newest first"]
+ C --> D["session timestamp<br/>breaks same-day ties"]
+```
+
+A memory naming *only* your project outranks one naming five. `date` is day-granular, so without the session tiebreak a just-written memory could sort arbitrarily and fall outside the caller's limit.
+
+**Adding a query on top:**
+
+```mermaid
+sequenceDiagram
+ participant S as Session
+ participant OM as om server
+ participant MR as memory-recall
+ participant QC as qmd
+
+ S->>OM: recall {query, limit, explain}
+ OM->>MR: recall(vault, caller)
+ MR-->>OM: visible set, ranked by declaration
+ alt query given and more than one result
+ OM->>QC: semanticMemoryOrder(query, visible)
+ alt index answered
+ QC-->>OM: reordered
+ else index down or no structured results
+ QC-->>OM: null
+ OM->>OM: lexical fallback — per-token, title AND body
+ end
+ OM->>OM: regroup — live first, superseded after
+ end
+ OM-->>S: entries with facets, reasons, and withheld count
+```
+
+Three properties in that path each closed a real defect:
+
+- **Retrieve semantically, then filter by visibility — never the reverse.** The index sees every memory including other projects'. Applying the scope rule to the *result* keeps one implementation of it, so semantic recall returns exactly the set plain recall would.
+- **Semantic ordering REORDERS; it does not filter.** An earlier version returned only the memories the index matched, so a just-written memory — no embedding yet — vanished from recall at every limit. Anything the index did not place is appended in declared order.
+- **Relevance orders within groups, never across the supersession boundary.** Reordering by relevance alone puts a corrected-away fact above the correction that replaced it, which is the one thing supersession exists to prevent.
+
+A missing index degrades *ordering*, never availability. "The vault knows nothing" is not an acceptable answer to a wiring problem.
+
+### The write path
+
+```mermaid
+flowchart TB
+ Call["remember — title, body,<br/>confidence, scope, projects"] --> Vault{"is the caller<br/>the vault itself?"}
+ Vault -->|yes| Refuse["refused — a memory written here<br/>reaches only sessions that<br/>already read every note"]
+ Vault -->|no| Neut["neutralise dangling wikilinks<br/>in title AND body"]
+ Neut --> Val["validateMemory<br/>epistemic contract"]
+ Val -->|fails| Report["refused, with reasons"]
+ Val --> Dup{"near-duplicate?<br/>facet-gated"}
+ Dup -->|"yes, and force is not set"| Collide["reports what it collided with,<br/>suggests supersedes"]
+ Dup -->|no| Links["resolve links — emitted only if the target exists"]
+ Links --> Write["claimFile: atomic exclusive create"]
+ Write --> Sup["mark superseded memories,<br/>kept and back-linked"]
+ Sup --> Idx["reindexSync"]
+ Idx --> Done["Recorded: path, scope, warnings"]
+```
+
+**The vault does not write to its own memory layer.** A session inside the vault already reads every note directly, and a memory written there would be scoped to the vault-as-a-project — reaching only sessions that by definition did not need it. Write-only by construction, so it is refused rather than allowed to accumulate.
+
+**The claim is atomic.** `writeMemory` originally used check-then-write. Six processes reporting success produced *four files* — silent loss, reproducible only across real processes, and one-server-per-repo is the actual deployment shape. It is now an exclusive create (`COPYFILE_EXCL`), guarded by a test that spawns real processes, since a single-threaded test serialises the calls and always passes.
+
+**Re-indexing splits by what each step guarantees:**
+
+```mermaid
+flowchart LR
+ W["a memory is written"] --> U["qmd update<br/>SYNCHRONOUS, bounded at 20s"]
+ U -->|"failed"| Warn["the response says so —<br/>reporting success would be<br/>a lie the caller cannot detect"]
+ U -->|"ok"| E["qmd embed<br/>DETACHED, unawaited"]
+ E --> R["ranking improves<br/>moments later"]
+```
+
+`update` decides whether the note is retrievable at all, so it is synchronous. `embed` only decides where it *ranks*, and recall appends everything the index did not match in declared order — so waiting on a local model run for ordering that corrects itself moments later buys nothing. Measured, it was most of the write.
+
+The vault normally re-indexes from a PostToolUse hook, but an MCP write is not a Claude Code tool call, so **no hook fires**. Without this step a note sits on disk and cannot be found, which is worse than no note because it looks like the system worked.
+
+**`record_work` is the sibling tool, and the two are constantly confused.** The distinction is single-valued vs multi-valued: a work record is about one project at one moment, so it has a correct folder and gets filed into it. Routing is *delegated* to the calling session — which already carries the vault's conventions and can search to see where similar notes live — and the server's job is to validate, never to guess. A caller-supplied folder must resolve inside a declared root, with containment checked against **that root** rather than merely the vault: `brain/../work` passes a first-segment check and still resolves inside the vault, which is how a capture once landed in a folder nobody named.
+
+### Failure modes, and how each is made visible
+
+Every failure in this layer presents identically as **"no results"**. That is what `health` exists for.
+
+| failure | how it presents | what surfaces it |
+|---|---|---|
+| memory root renamed in Obsidian | recall returns nothing | `health` reports the discovered root and the drift |
+| captures split across two roots | recall sees only one | `health` warns, naming both |
+| qmd index belongs to another vault | search returns nothing | `health` checks index ownership |
+| qmd not installed | search degrades to lexical | `health` reports the launcher missing |
+| `OM_VAULT_PATH` points elsewhere | *everything* describes the wrong vault | `health` warns when it disagrees with the launcher location |
+| caller unidentified | only general memories visible | `recall` says so in prose; `health` says ANONYMOUS |
+| memory scoped away | absent from recall | `recall` with `explain: true` gives counts and reasons |
+| two repos sharing a folder name | each sees the other's memories | `health` reports the identity source and suggests `.om-project` |
+
+A stray `VAULT_PATH` was honoured at one point, and that name is too generic to claim — it is set for unrelated reasons on real machines, and the result was a server serving a *different* vault while reporting that vault's config as if correct. Only `OM_VAULT_PATH` is read now.
+
+### The install is two steps, and both are required
+
+```json
+{
+ "mcpServers": {
+ "om": {
+ "command": "node",
+ "args": ["<absolute path to your vault>/.claude/scripts/om-mcp.mjs"]
+ }
+ }
+}
+```
+
+That goes in the **consuming project's** `.mcp.json`. Then add a short section to that project's own `CLAUDE.md` telling it the vault exists and to consult it.
+
+Step 2 is not documentation garnish. Measured: with the server wired and no repo-side instruction, a session made **zero** vault calls and implemented a design the vault had recorded as explicitly rejected. With the instruction present, it refused and cited the note. This follows directly from the prohibition/routing asymmetry above — and it makes the repo-side snippet a shipped deliverable, since a server installed without it is a server that gets ignored.
+
+> **Do not register the raw `qmd` server in a consuming repo.** It searches every note directly, with no notion of which memories were written for which project, so the repo matches against lessons meant for unrelated ones. Applying declared scope on top of the index is exactly what `om` adds, and going around it returns the **wrong** things, not merely more of them.
+
+---
+
## Multi-Agent Portability
The same scripts serve three agents. Each agent has its own config file mapping its own event names to the shared scripts. The event vocabularies differ — Claude Code calls it `Stop`, Gemini calls it `SessionEnd`, Codex has no compaction event — but the scripts are identical.
@@ -263,9 +716,9 @@ flowchart TB
S1["session-start.ts"]
S2["classify-message.ts"]
S3["validate-write.ts"]
- S4["qmd-refresh.ts"]
S5["pre-compact.ts"]
S6["stop-checklist.ts"]
+ S7["qmd-refresh-run.ts<br/>(detached worker, not a hook)"]
end
subgraph Manuals["Operating manuals"]
CM["CLAUDE.md"]
@@ -285,6 +738,8 @@ Commands in `.claude/commands/` are plain Markdown prompts. Claude Code invokes
Adding a fourth agent means writing one more config file and, ideally, one more operating manual if the agent reads context files natively.
+The `om` server sits outside this table on purpose. It speaks MCP over stdio and knows nothing about which harness is on the other end, so it needs no per-agent config at all — any MCP-capable client registers it the same way.
+
---
## Vault-First Memory
@@ -324,6 +779,23 @@ All actual memory content lives in `brain/` as real Obsidian notes — queryable
The rule that enforces this: "when asked to remember, write to the relevant `brain/` topic note, not to `~/.claude/`." It is restated in `CLAUDE.md` because it is the easiest rule to break and the hardest to detect breaking.
+### Two stores, one vault
+
+`brain/` and `memories/` look similar and answer different questions. Keeping them apart is deliberate.
+
+| | `brain/` | `memories/` |
+|---|---|---|
+| written by | a session **inside** the vault, or you | a session in **another repo**, through `om` |
+| shape | curated topic notes, edited over time | append-only atomic entries under `YYYY/MM/` |
+| reach | the whole vault, always | declared per entry — `scope`, `projects[]`, `platforms[]` |
+| corrections | edit the note | a new entry that `supersedes` the old, which is kept and back-linked |
+| browsing | the note itself, and the graph | `bases/Memories.base` — Recent, By project, Needs review, Superseded, General reach |
+| served as an MCP resource | yes, if inside an exposed root | **never** — reach is per caller, so the note surface would bypass it |
+
+Both are Markdown in the vault, both are in the graph, both are git-tracked. The difference is that a `brain/` note is a *document you maintain*, while a memory is an *immutable claim with a declared audience and a confidence level*.
+
+The third store is `~/.claude/.../MEMORY.md`, which holds no content at all — only pointers. The template creates nothing else there, and `validate-write.ts` blocks attempts to.
+
---
## Skills and Commands
@@ -352,12 +824,18 @@ The design makes these changes easy:
| Add a new agent (Cursor, Windsurf, …) | New config file mapping events to existing scripts, optionally a new operating manual |
| Add a new subagent | A new Markdown file in `.claude/agents/`, referenced from the command that invokes it |
| Add a new Base view | A new `.base` file in `bases/`, embedded from `Home.md` if it should surface |
+| Change which notes `om` serves | `vault-manifest.json` → `mcp_exposed_roots` / `mcp_never_expose`, or tag a note `private` |
+| Move the memory store | Rename the folder in Obsidian — discovery finds it and `health` reports the drift; pin it with `memory_root` to be explicit |
+| Add a new `om` tool | A declaration in `.claude/scripts/lib/mcp-tools.ts` + a case in `mcp-server.ts` — the description is what the model reads when deciding to call it |
+| Change what the eager layer may spend | `vault-manifest.json` → `eager_layer_budget_bytes`, `listing_collapse_threshold` |
The design is hostile to these changes (on purpose):
-- Storing memories outside the vault. The whole point of `brain/` is portability and graph visibility.
-- Bypassing the manifest. If a new component needs to know the index name or the infrastructure boundary, it should read the manifest rather than hardcode.
+- Storing memories outside the vault. The whole point of `brain/` and `memories/` is portability and graph visibility.
+- Bypassing the manifest. If a new component needs to know the index name, the memory root, or the infrastructure boundary, it should read the manifest rather than hardcode.
- Hardcoding agent event names inside scripts. Event name translation is a config-layer concern.
+- **Scoping vault notes per calling repo.** An earlier revision did this — a repo saw only its own notes — and it killed the most valuable measured capability, because the answers worth having come from *connecting* projects. Memories declare their reach; notes do not.
+- **Adding a second read path.** Any new surface that answers "which notes exist" must resolve through `visibleFiles` rather than walking the vault itself.
---
@@ -365,7 +843,9 @@ The design is hostile to these changes (on purpose):
Template versions are tracked in `vault-manifest.json` with fingerprints that let `/om-vault-upgrade` detect an older vault's version by presence or absence of specific files. The migrator uses the infrastructure/user-content split to decide what to overwrite versus preserve. `CHANGELOG.md` documents what changed in each version.
-The long-term stability guarantee is narrow: the manifest keys (`qmd_index`, `infrastructure`, `user_content_roots`, `frontmatter_required`), the hook script names under `.claude/scripts/`, and the folder layout for user content. Everything else — including command names, subagent internals, and classification logic — is allowed to evolve between versions.
+The long-term stability guarantee is narrow: the manifest keys (`qmd_index`, `infrastructure`, `user_content_roots`, `frontmatter_required`, `memory_root`), the hook script names under `.claude/scripts/`, the `om-mcp.mjs` launcher path that consuming repos put in their `.mcp.json`, and the folder layout for user content. Everything else — including command names, subagent internals, and classification logic — is allowed to evolve between versions.
+
+`memories/` is listed in `user_content_roots`, so an upgrade preserves it rather than treating it as template infrastructure. The launcher path is on this list because it is the one string that lives *outside* the vault, written into other repositories' config — moving it silently breaks every consumer.
## Install Paths
diff --git a/CLAUDE.md b/CLAUDE.md
index 0c506b8..e37cd5c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -42,6 +42,7 @@ Defined in `.claude/commands/`. Claude Code auto-surfaces every command with its
| `perf/evidence/` | PR deep scans, data extracts for reviews | Named `<Person> PRs - <Period>.md` |
| `perf/<cycle>/` | Review cycle briefs + artifacts | Review briefs (private, manager, peer) |
| `brain/` | Claude's operational knowledge | `Memories.md`, `Key Decisions.md`, `Patterns.md`, `Gotchas.md`, `Skills.md`, `North Star.md` |
+| `memories/YYYY/MM/` | **Cross-repo agent memory** -- durable lessons recorded over MCP by sessions working in *other* repositories. Time is the only thing in the path; reach is declared in frontmatter | Browse via `bases/Memories.base`; never edit by hand |
| `org/` | Organizational knowledge index | `People & Context.md` (MOC) |
| `org/people/` | Atomic person notes | One note per person |
| `org/teams/` | Team notes as graph nodes | One note per team |
@@ -50,7 +51,7 @@ Defined in `.claude/commands/`. Claude Code auto-surfaces every command with its
| `templates/` | Obsidian templates | `Work Note.md`, `Decision Record.md`, etc. |
| `.claude/commands/` | Slash commands (auto-surfaced in-session; catalog in `brain/Skills.md`) | One `.md` per command |
| `.claude/agents/` | Subagents | See subagents table below |
-| `.claude/scripts/` | Hook scripts | `session-start.ts`, `classify-message.ts`, `validate-write.ts`, `pre-compact.ts`, `stop-checklist.ts`, `charcount.ts` |
+| `.claude/scripts/` | Hook scripts + the MCP server | `session-start.ts`, `classify-message.ts`, `validate-write.ts`, `pre-compact.ts`, `stop-checklist.ts`, `charcount.ts`, `om-mcp.mjs` (see **Reaching the vault from another repo** below) |
| `.claude/skills/` | Obsidian + QMD skills | Loaded automatically via Skill tool |
## Obsidian CLI
@@ -252,6 +253,9 @@ Beyond tags, use these frontmatter properties to enable search and Bases views:
|--------|----------|---------|
| **MEMORY.md** | `~/.claude/projects/.../memory/MEMORY.md` | Auto-loaded index only. Pointers to vault notes. |
| **Vault memories** | `brain/` topic notes | Git-tracked, Obsidian-browsable, linked. All durable knowledge lives here. |
+| **Cross-repo memories** | `memories/YYYY/MM/` | Written by sessions in *other* repos over MCP, under an enforced epistemic contract. See below. |
+
+**Which one, when you are working inside the vault:** `brain/`. Always. The `memories/` tree is written by the `om` MCP server on behalf of sessions elsewhere, and the server **refuses** a write from a session running inside the vault — a memory recorded here would be scoped to the vault-as-a-project and reach only the sessions that already read every note directly. Write the note normally and let the hooks file it.
When asked to "remember" something:
1. Find or create the appropriate `brain/` topic note (Gotchas, Patterns, Key Decisions, etc.)
@@ -268,6 +272,78 @@ The SessionStart hook injects a **Brain Topics (read on demand)** index listing
- Skip notes marked `(empty)` in the index — they're stubs with no substantive content.
- After answering, if the conversation produced durable knowledge, update the relevant brain note (see the "remember" workflow above).
+## Reaching the Vault From Another Repo
+
+The vault normally only helps while you are sitting in it. The **`om` MCP server** makes it reachable from a coding session running in any other repository: that session can search the vault, read notes, follow the graph, and record back into it.
+
+### The install is two steps, and both are required
+
+**1. Register the server** in the consuming project's `.mcp.json`:
+
+```json
+{
+ "mcpServers": {
+ "om": {
+ "command": "node",
+ "args": ["<absolute path to your vault>/.claude/scripts/om-mcp.mjs"]
+ }
+ }
+}
+```
+
+**2. Add a short section to that project's own `CLAUDE.md`**, telling it the vault exists and to consult it.
+
+> [!warning] Step 2 is not documentation garnish.
+> **Measured:** with the server wired and *no* repo-side instruction, a session made **zero** vault calls and went on to implement a design the vault had recorded as explicitly rejected. With the instruction present, it refused and cited the note.
+>
+> The reason is an asymmetry in how MCP `instructions` propagate: a **prohibition** holds reliably, while a positive *"go consult the vault"* is advisory and gets skipped whenever a nearer source exists. The server can stop a session doing something; only the project's own law makes one go looking.
+
+> [!warning] Do not register the raw `qmd` server in a consuming repo.
+> It searches every note directly, with no notion of which memories were written for which project — so the repo matches against lessons meant for unrelated ones. Applying each memory's declared scope on top of the index is exactly what `om` adds, and going around it returns the **wrong** things, not merely more of them.
+
+### What it exposes
+
+| tool | purpose |
+|------|---------|
+| `search` | semantic + keyword search over exposed notes |
+| `expand` | a note's graph neighbourhood — links out and backlinks |
+| `recall` | durable lessons scoped to the calling repo, most specific first |
+| `remember` | record a lesson that will still be true in a different repo |
+| `record_work` | record what happened in this repo, filed where it belongs |
+| `health` | is the wiring intact? |
+
+Plus notes as readable **resources**, and `recall_topic` / `prior_art` as **prompts** you invoke yourself from the `/` menu.
+
+### Which memories reach which project
+
+This is the part worth understanding, and it is what the layer is for. Every memory declares its reach when written:
+
+- `scope: project`, `projects: [a, b]` — reaches those repos and no others
+- `scope: platform`, `platforms: [ios]` — reaches any repo on that platform
+- `scope: general` — reaches everywhere
+
+A reader never widens what the writer declared, so a sibling app on the same platform does not inherit another app's project-scoped constraints. `recall` with `explain: true` reports why each memory was shown and how many were withheld.
+
+**A repo is identified by its folder name**, which is usually right and occasionally not: two repos both called `api` share one identity, so each receives the other's memories. Write a distinct name into a `.om-project` file at the repo root to separate them — `health` reports which repo it thinks is calling and where that name came from.
+
+### Which notes the server serves
+
+Your vault, your notes, your session. The default is the vault's own `user_content_roots`, at the granularity it declares them (`work/active/`, not all of `work/`). Set `mcp_exposed_roots` only if this vault holds material that is **not yours to share** — employer-confidential notes, a client's data.
+
+| key | default | meaning |
+|-----|---------|---------|
+| `mcp_exposed_roots` | *(empty → `user_content_roots`)* | folders whose notes may be read |
+| `mcp_never_expose` | *(empty)* | filenames withheld regardless of folder |
+| `memory_root` | `memories` | where cross-repo memories live |
+| `mcp_inbox` | `inbox` | fallback destination for `record_work` |
+
+`memories/` is never served as an ordinary note whatever the config says — memories carry their own scope, and the note surface would bypass it. A note tagged `private` in frontmatter is never served either.
+
+> [!note] Keeping vault material out of repos is the contract's job, not this list's.
+> A session can read the vault directly, so narrowing what the server serves prevents nothing on its own. What works is the prohibition injected into the calling session, plus `.claude/om-mcp-audit.jsonl` (gitignored), which records every read with the calling repo.
+
+Run `health` when something that should be in the vault cannot be found — every failure in this layer presents identically as "no results", and that tool is what tells them apart.
+
## Agent Guidelines
### Graph-First Thinking
diff --git a/GEMINI.md b/GEMINI.md
index 5d4c27c..6f0ad61 100644
--- a/GEMINI.md
+++ b/GEMINI.md
@@ -23,7 +23,7 @@ The hook scripts in `.claude/scripts/` are agent-agnostic TypeScript and shell,
## Commands
-18 commands in `.claude/commands/` — agent-agnostic markdown with YAML frontmatter.
+Commands live in `.claude/commands/` — agent-agnostic markdown with YAML frontmatter. `brain/Skills.md` is the catalog.
- **Claude Code / Gemini CLI**: invoke as `/om-standup`, `/om-dump`, etc.
- **Codex CLI**: type the command name as a regular prompt without the `/` prefix (e.g. `om-standup`). Codex will find and execute the command file.
@@ -34,6 +34,14 @@ The vault's memory lives in `brain/` — `Memories.md`, `Patterns.md`, `Key Deci
The `~/.claude/` auto-loaded memory index is Claude Code-specific — skip that section in `CLAUDE.md`. The vault-side `brain/` notes are the source of truth.
+## Reaching this vault from another repo
+
+The `om` MCP server (`.claude/scripts/om-mcp.mjs`) exposes this vault over MCP, so a session running in a **different repository** can search it, read notes, follow the graph, and record durable lessons back into it. It speaks plain MCP over stdio, so any MCP-capable agent can register it — nothing about it is Claude Code-specific.
+
+Register it in the *consuming* project's MCP config, pointing at this vault's absolute path, then add a short section to that project's own agent doc telling it the vault exists. **Both steps are required**: measured, a session with the server wired but no repo-side instruction made zero vault calls, because a prohibition propagates into a session reliably while a positive "go look" does not.
+
+Do not register the raw `qmd` server in a consuming repo — it searches every note directly, so the repo matches against memories written for unrelated projects. Applying each memory's declared scope on top of the index is what `om` adds. Full details in `CLAUDE.md`.
+
## Subagents
9 subagents in `.claude/agents/` handle isolated tasks (brag spotting, vault auditing, cross-linking, etc.). The prompt content is agent-agnostic markdown.
diff --git a/README.ja.md b/README.ja.md
index 1bf1280..a1b6369 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -142,8 +142,27 @@ qmd --index obsidian-mind embed # 多数の新規ノート後
**MCPによるネイティブなエージェントツール。** `.mcp.json`に[Model Context Protocol](https://modelcontextprotocol.io)サーバーとして登録されています — QMDがインストールされていれば、`mcp__qmd__query`、`mcp__qmd__get`、`mcp__qmd__multi_get`がReadやEditと並んでエージェントのツールメニューに表示されます。サブエージェント、スラッシュコマンド、メイン会話はすべて同じ型付きコントラクトを呼び出します。後から別のMCP対応ツール(データベース、チケット管理、カレンダー)を追加しても、同じ方法でプラグインできます。
-> [!NOTE]
-> QMDがインストールされていなくても、すべて動作します — エージェントはObsidian CLIとgrepにフォールバックし、MCPサーバーのエントリは無害な警告とともにスキップされます。
+#### 内部の仕組み
+
+QMDは**3つの小さなモデルをローカルで**実行します。設定するAPIキーは不要で、クエリごとの費用もかからず、オフラインでも動作します:
+
+| モデル | サイズ | 役割 |
+|---|---|---|
+| `embeddinggemma-300M` | ~328MB | ノートとクエリをベクトルに変換 |
+| `qmd-query-expansion-1.7B` | ~1.28GB | クエリをより良い検索語に書き換え |
+| `Qwen3-Reranker-0.6B` | ~640MB | 候補を実際の関連性で並べ替え |
+
+初回使用時にダウンロードされ、キャッシュされます。GPUが見つかればオフロードし(ディスクリートGPUではCUDA、Apple SiliconではMetal)、なければCPUにフォールバックします。`qmd doctor`で自分の環境を確認できます。
+
+3つのCLIコマンドは、安い順にこのスタックへ対応します: `qmd search`は**モデルを一切使わない**BM25キーワード検索、`qmd vsearch`はベクトルのみ、`qmd query`は完全なハイブリッドです。大きなダウンロードを避けたい場合、`search`だけでも十分実用的です。
+
+#### MCPサーバーにとっての意味
+
+`om`サーバーは字句クエリとベクトルクエリの両方を送るため、キーワードが一致しなくても質問に答えるノートを見つけられます。実務上の要点:
+
+- **重いのは書き込みではなく読み取りです。** クエリは検索前にローカルで埋め込まれるため、クエリ付きの`recall`は数秒かかり、クエリなしの`recall`はほぼ即時です。ノートに対する`search`は高速で、コストがかかるのはベクトル処理の部分です。
+- **メモリの書き込みはモデルを待ちません。** インデックス更新は同期的なので新しいメモリはすぐ取得可能になり、ベクトル生成はバックグラウンドで行われます。ベクトルは**順位**にのみ影響し、見つかるかどうかには影響しないためです。
+- **インデックスが無くても動きます。** QMDが無い場合、サーバーは字句マッチにフォールバックします。順位は悪くなりますが、何も失われません。
---
@@ -190,7 +209,7 @@ obsidian-mindはボールト全体をコンテキストに読み込み**ませ
| 階層 | 内容 | タイミング | コスト |
|------|------|------------|--------|
-| **常時** | `CLAUDE.md` + SessionStartコンテキスト(North Star抜粋、git概要、タスク、ボールトファイル一覧) | セッション開始時 | ~2Kトークン |
+| **常時** | `CLAUDE.md` + SessionStartコンテキスト(North Star抜粋、git概要、タスク、ボールトファイル一覧) | セッション開始時 | マニフェストのバジェットが上限。実サイズは毎セッション末尾のメーターが表示 |
| **オンデマンド** | QMDセマンティック検索結果 | エージェントが特定のコンテキストを必要とした時 | 対象のみ |
| **トリガー** | 分類ルーティングヒント | 毎メッセージ | ~100トークン |
| **トリガー** | PostToolUse検証 | `.md`書き込み後 | ~200トークン |
@@ -215,6 +234,41 @@ obsidian-mindはClaude Code、Codex CLI、Gemini CLIで動作します。`CLAUDE
---
+## 🧠 どのリポジトリからでもボールトにアクセス
+
+ボールトは通常、その中で作業しているときにしか役立ちません。**`om` MCPサーバー**がそれを変えます。*他のあらゆるリポジトリ*のコーディングセッションが、ノートを検索し、読み、グラフをたどり、学んだことをボールトに記録できるようになります。
+
+```json
+{
+ "mcpServers": {
+ "om": {
+ "command": "node",
+ "args": ["/path/to/your-vault/.claude/scripts/om-mcp.mjs"]
+ }
+ }
+}
+```
+
+これは**利用側プロジェクト**の`.mcp.json`に記述します。次に、そのプロジェクト自身の`CLAUDE.md`にボールトを指し示す短いセクションを追加してください。
+
+> [!IMPORTANT]
+> **両方の手順が必須で、2つ目は事務作業ではありません。** 実測: サーバーを接続してもリポジトリ側の指示がない場合、セッションはボールトを**一度も**呼び出さず、ボールトが明確に却下したと記録していた設計をそのまま実装しました。指示があった場合は、実装を拒否しノートを引用しました。
+>
+> MCPの`instructions`フィールドにおける**禁止事項**は呼び出し側セッションへ確実に伝播します。一方`「ボールトを参照せよ」`という肯定的な指示は助言的で、より近い情報源があれば無視されます。サーバーはセッションを止められますが、セッションに探しに行かせられるのはそのプロジェクト自身の規約だけです。
+
+**セッションが得られるもの:** `search`(セマンティック+キーワード)、`expand`(ノートのリンクと被リンク)、`recall`(そのリポジトリにスコープされた恒久的な教訓)、`remember`(教訓の記録)、`record_work`(作業内容の記録)、`health`(配線は正常か)。加えて、ノートを読み取り可能なリソースとして提供します。
+
+**リポジトリはフォルダ名で識別されます。** これは通常正しく、稀に誤ります: `api`という名前のリポジトリが2つあると同一の識別子を共有し、互いのメモリを受け取ってしまいます。リポジトリのルートに`.om-project`ファイルを置き、別の名前を書けば分離できます。`health`がどのリポジトリとして認識しているか、その名前がどこから来たかを教えてくれます。
+
+**認識論的契約を伴うリポジトリ横断メモリ。** あるリポジトリで学んだ教訓は、スコープ指定されたリポジトリにのみ届きます。到達範囲は読み取り時に推測されるのではなく*書き込み時に宣言*されるため、兄弟プロジェクトが他方の制約を継承することはありません。記録されるすべてに`confidence: verified | inferred | unverified`、変動しやすい事実の日付、そしてサーバー側で導出される来歴が付随します — セッションが自分とは異なるプロジェクトを名乗ることはできません。訂正は上書きではなく置き換えとして記録されるため、ストアは矛盾を蓄積するのではなく、成長するほど信頼性が**高まります**。
+
+**何が提供されるか。** あなたのボールト、あなたのノート、あなたのセッションです。デフォルトは、ボールトがすでに自分のコンテンツとして宣言しているもの(`user_content_roots`)を、書いたままの粒度で使います(`work/`全体ではなく`work/active/`)。`vault-manifest.json`の`mcp_exposed_roots`を設定するのは、**あなたが共有する権限を持たない**素材 — 雇用主の機密情報やクライアントのデータ — をこのボールトが抱えている場合だけです。`private`タグの付いたノートは提供されず、メモリは独自のスコープを持つため通常のノートとしては提供されません。すべての読み取りは呼び出し元リポジトリとともに記録されます。
+
+> [!NOTE]
+> ボールトの内容を公開PRに出さないようにするのは、公開範囲リストではなく**契約**の仕事です。セッションはいずれにせよボールトを直接読めます。呼び出し側セッションに注入される禁止事項こそが、実測で効果を持つ部分です。
+
+---
+
## 📅 日常ワークフロー
**朝**: `/om-standup`を実行。エージェントがNorth Star、アクティブプロジェクト、未完了タスク、最近の変更を読み込みます。構造化されたサマリーと優先度の提案が表示されます。
diff --git a/README.ko.md b/README.ko.md
index a3760d9..070b4cb 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -142,8 +142,27 @@ qmd --index obsidian-mind embed # 많은 신규 노트 후
**MCP를 통한 네이티브 에이전트 도구.** `.mcp.json`에 [Model Context Protocol](https://modelcontextprotocol.io) 서버로 등록되어 있습니다 — QMD가 설치되어 있으면 `mcp__qmd__query`, `mcp__qmd__get`, `mcp__qmd__multi_get`가 Read와 Edit 옆에 에이전트의 도구 메뉴에 나타납니다. 서브에이전트, 슬래시 명령, 메인 대화 모두 동일한 타입 지정 계약을 호출합니다. 나중에 다른 MCP 호환 도구(데이터베이스, 티켓팅 시스템, 캘린더)를 추가하면 같은 방식으로 플러그인됩니다.
-> [!NOTE]
-> QMD가 설치되어 있지 않아도 모든 기능이 작동합니다 — 에이전트가 Obsidian CLI와 grep으로 대체하고, MCP 서버 항목은 무해한 경고와 함께 건너뜁니다.
+#### 내부 동작 방식
+
+QMD는 **세 개의 작은 모델을 로컬에서** 실행하므로, 설정할 API 키도 없고 쿼리당 비용도 없으며 오프라인에서도 동작합니다:
+
+| 모델 | 크기 | 역할 |
+|---|---|---|
+| `embeddinggemma-300M` | ~328MB | 노트와 쿼리를 벡터로 변환 |
+| `qmd-query-expansion-1.7B` | ~1.28GB | 쿼리를 더 나은 검색어로 재작성 |
+| `Qwen3-Reranker-0.6B` | ~640MB | 후보를 실제 관련성으로 재정렬 |
+
+첫 사용 시 다운로드되어 캐시됩니다. GPU를 찾으면 오프로드하며(외장 GPU는 CUDA, Apple Silicon은 Metal), 없으면 CPU로 폴백합니다. `qmd doctor`로 현재 상태를 확인할 수 있습니다.
+
+세 가지 CLI 명령은 저렴한 순서대로 이 스택에 대응합니다: `qmd search`는 **모델을 전혀 쓰지 않는** BM25 키워드 검색, `qmd vsearch`는 벡터 전용, `qmd query`는 완전한 하이브리드입니다. 큰 다운로드를 피하고 싶다면 `search`만으로도 충분히 유용합니다.
+
+#### MCP 서버에 주는 의미
+
+`om` 서버는 어휘 쿼리와 벡터 쿼리를 함께 보내므로, 키워드가 겹치지 않아도 질문에 답하는 노트를 찾아냅니다. 실무적으로 알아둘 점:
+
+- **비싼 쪽은 쓰기가 아니라 읽기입니다.** 쿼리는 검색 전에 로컬에서 임베딩되므로 쿼리가 있는 `recall`은 수 초가 걸리고, 쿼리 없는 `recall`은 거의 즉시입니다. 노트에 대한 `search`는 빠르며, 비용이 드는 것은 벡터 단계입니다.
+- **메모리 쓰기는 모델을 기다리지 않습니다.** 인덱스 갱신은 동기적이라 새 메모리는 즉시 검색 가능해지고, 벡터 생성은 백그라운드에서 진행됩니다. 벡터는 **순위**에만 영향을 줄 뿐 발견 여부에는 영향이 없기 때문입니다.
+- **인덱스가 없어도 동작합니다.** QMD가 없으면 서버는 어휘 매칭으로 폴백합니다. 순위는 나빠지지만 사라지는 것은 없습니다.
---
@@ -190,7 +209,7 @@ obsidian-mind는 전체 볼트를 컨텍스트에 로드하지 **않습니다**.
| 계층 | 내용 | 시점 | 비용 |
|------|------|------|------|
-| **항상** | `CLAUDE.md` + SessionStart 컨텍스트 (North Star 발췌, git 요약, 작업, 볼트 파일 목록) | 세션 시작 시 | ~2K 토큰 |
+| **항상** | `CLAUDE.md` + SessionStart 컨텍스트 (North Star 발췌, git 요약, 작업, 볼트 파일 목록) | 세션 시작 시 | 매니페스트 예산이 상한. 실제 크기는 매 세션 마지막 줄의 미터가 보고 |
| **온디맨드** | QMD 시맨틱 검색 결과 | 에이전트가 특정 컨텍스트 필요 시 | 대상만 |
| **트리거** | 분류 라우팅 힌트 | 매 메시지 | ~100 토큰 |
| **트리거** | PostToolUse 검증 | `.md` 작성 후 | ~200 토큰 |
@@ -215,6 +234,41 @@ obsidian-mind는 Claude Code, Codex CLI, Gemini CLI에서 작동합니다. `CLAU
---
+## 🧠 어떤 저장소에서든 볼트에 접근하기
+
+볼트는 보통 그 안에서 작업할 때만 도움이 됩니다. **`om` MCP 서버**가 이를 바꿉니다. *다른 어떤 저장소*의 코딩 세션이든 노트를 검색하고, 읽고, 그래프를 따라가고, 배운 것을 볼트에 다시 기록할 수 있습니다.
+
+```json
+{
+ "mcpServers": {
+ "om": {
+ "command": "node",
+ "args": ["/path/to/your-vault/.claude/scripts/om-mcp.mjs"]
+ }
+ }
+}
+```
+
+이것은 **사용하는 프로젝트**의 `.mcp.json`에 들어갑니다. 그런 다음 해당 프로젝트 자체의 `CLAUDE.md`에 볼트를 가리키는 짧은 섹션을 추가하세요.
+
+> [!IMPORTANT]
+> **두 단계 모두 필수이며, 두 번째는 형식적인 절차가 아닙니다.** 측정 결과: 서버가 연결되어 있어도 저장소 측 지침이 없으면 세션은 볼트를 **한 번도** 호출하지 않았고, 볼트가 명시적으로 거부했다고 기록한 설계를 그대로 구현했습니다. 지침이 있을 때는 구현을 거부하고 해당 노트를 인용했습니다.
+>
+> MCP `instructions` 필드의 **금지 사항**은 호출하는 세션으로 확실히 전파됩니다. 반면 `"볼트를 참조하라"`는 긍정형 지시는 권고적이며, 더 가까운 정보원이 있으면 건너뜁니다. 서버는 세션을 멈출 수는 있지만, 세션이 찾아보게 만드는 것은 그 프로젝트 자체의 규약뿐입니다.
+
+**세션이 얻는 것:** `search`(시맨틱 + 키워드), `expand`(노트의 링크와 백링크), `recall`(해당 저장소로 스코프된 지속적 교훈), `remember`(교훈 기록), `record_work`(작업 내용 기록), `health`(배선이 정상인지). 여기에 노트를 읽을 수 있는 리소스로 제공합니다.
+
+**저장소는 폴더 이름으로 식별됩니다.** 대개는 맞지만 가끔 틀립니다: `api`라는 이름의 저장소가 둘이면 하나의 정체성을 공유해 서로의 메모리를 받게 됩니다. 저장소 루트에 `.om-project` 파일을 두고 다른 이름을 적으면 분리됩니다. `health`가 어느 저장소로 인식하는지, 그 이름이 어디서 왔는지 알려줍니다.
+
+**인식론적 계약이 있는 저장소 간 메모리.** 한 저장소에서 배운 교훈은 스코프가 지정된 저장소에만 도달합니다. 도달 범위는 읽을 때 추측되는 것이 아니라 *쓸 때 선언*되므로, 형제 프로젝트가 다른 프로젝트의 제약을 물려받지 않습니다. 기록되는 모든 것에는 `confidence: verified | inferred | unverified`, 변동성 있는 사실의 날짜, 그리고 서버 측에서 도출된 출처가 함께 담깁니다 — 세션이 자신이 아닌 프로젝트를 사칭할 수 없습니다. 수정은 덮어쓰기가 아니라 대체로 기록되므로, 저장소는 모순을 쌓아가는 대신 커질수록 **더** 신뢰할 수 있게 됩니다.
+
+**무엇을 제공하는가.** 당신의 볼트, 당신의 노트, 당신의 세션입니다. 기본값은 볼트가 이미 자신의 콘텐츠로 선언한 것(`user_content_roots`)을, 작성한 그대로의 단위로 사용합니다(`work/` 전체가 아니라 `work/active/`). `vault-manifest.json`의 `mcp_exposed_roots`를 설정하는 것은 이 볼트가 **당신이 공유할 권한이 없는** 자료 — 고용주의 기밀 정보나 고객의 데이터 — 를 담고 있을 때뿐입니다. `private` 태그가 붙은 노트는 제공되지 않으며, 메모리는 자체 스코프를 갖기 때문에 일반 노트로 제공되지 않습니다. 모든 읽기는 호출한 저장소와 함께 기록됩니다.
+
+> [!NOTE]
+> 볼트 자료가 공개 PR에 들어가지 않게 하는 것은 공개 목록이 아니라 **계약**의 일입니다. 세션은 어차피 볼트를 직접 읽을 수 있습니다. 호출하는 세션에 주입되는 금지 사항이 실측으로 효과가 있는 부분입니다.
+
+---
+
## 📅 일일 워크플로우
**아침**: `/om-standup`을 실행합니다. 에이전트가 North Star, 활성 프로젝트, 미완료 작업, 최근 변경사항을 로드합니다. 구조화된 요약과 추천 우선순위를 받습니다.
diff --git a/README.md b/README.md
index 38d695b..c5c67d4 100644
--- a/README.md
+++ b/README.md
@@ -146,8 +146,27 @@ qmd --index obsidian-mind update # after bulk edits
qmd --index obsidian-mind embed # after many new notes
```
-> [!NOTE]
-> First-time `qmd embed` downloads a ~328MB embedding model. `qmd query` (with LLM reranking) also downloads a ~1.28GB model on first use — skip it with `qmd search` (BM25) or `qmd vsearch` (semantic only) if you want to avoid the larger download.
+#### How it works under the hood
+
+QMD runs **three small models locally**, so there is no API key to set up, no per-query cost, and it works offline:
+
+| model | size | job |
+|---|---|---|
+| `embeddinggemma-300M` | ~328MB | turns notes and queries into vectors |
+| `qmd-query-expansion-1.7B` | ~1.28GB | rewrites your query into better search terms |
+| `Qwen3-Reranker-0.6B` | ~640MB | reorders the shortlist by actual relevance |
+
+They download on first use and are cached. QMD offloads to the GPU when it finds one — CUDA on a discrete card, Metal on Apple Silicon — and falls back to CPU otherwise. Check what yours is doing with `qmd doctor`.
+
+The three CLI verbs map onto that stack, cheapest first: `qmd search` is BM25 keywords with **no model at all**, `qmd vsearch` is vector-only, and `qmd query` is the full hybrid. If you want to avoid the larger downloads, `search` alone is genuinely useful.
+
+#### What that means for the MCP server
+
+The `om` server sends a lexical *and* a vector sub-query, so retrieval finds the note that answers your question even when it shares no keywords with it. Practical consequences worth knowing:
+
+- **Reads are the expensive side, not writes.** A query embeds locally before it can search, so `recall` with a query takes a couple of seconds while `recall` without one is near-instant. `search` over notes is fast — it is the vector step that costs.
+- **Writing a memory does not wait for the model.** The index update is synchronous, so a new memory is immediately retrievable; generating its vector happens in the background, because that only affects where it *ranks*, not whether it is found.
+- **No index, no problem.** Without QMD the server falls back to lexical matching. Ordering gets worse; nothing disappears.
> [!NOTE]
> If QMD isn't installed, everything still works — the agent falls back to grep and the Obsidian CLI, and the MCP server entry is skipped with a harmless warning.
@@ -197,7 +216,7 @@ obsidian-mind does **not** dump your entire vault into context. It uses tiered l
| Tier | What | When | Cost |
|------|------|------|------|
-| **Always** | `CLAUDE.md` + SessionStart context (North Star excerpt, git summary, tasks, vault file listing) | Session start | ~2K tokens |
+| **Always** | `CLAUDE.md` + SessionStart context (North Star excerpt, git summary, tasks, vault file listing) | Session start | capped by the manifest budget; the meter reports the real size every session |
| **On-demand** | QMD semantic search results | When the agent needs specific context | Targeted |
| **Triggered** | Classification routing hints | Every message | ~100 tokens |
| **Triggered** | PostToolUse validation | After `.md` writes | ~200 tokens |
@@ -207,7 +226,7 @@ SessionStart loads **lightweight context** — small excerpts from key files, fi
### 🌐 Using with Other Agents
-obsidian-mind works with Claude Code, Codex CLI, and Gemini CLI. The vault conventions in `CLAUDE.md`, the hook scripts in `.claude/scripts/`, and the 18 commands in `.claude/commands/` are all agent-agnostic — pure Markdown, TypeScript, and shell with no SDK dependencies.
+obsidian-mind works with Claude Code, Codex CLI, and Gemini CLI. The vault conventions in `CLAUDE.md`, the hook scripts in `.claude/scripts/`, and the commands in `.claude/commands/` are all agent-agnostic — pure Markdown, TypeScript, and shell with no SDK dependencies.
**Claude Code** — full support. Hooks, commands, subagents, and the memory system all work out of the box.
@@ -222,6 +241,45 @@ obsidian-mind works with Claude Code, Codex CLI, and Gemini CLI. The vault conve
---
+## 🧠 Reach Your Vault From Any Repo
+
+Your vault normally only helps while you are sitting in it. The **`om` MCP server** changes that: a coding session in *any other repository* can search your notes, read them, follow the graph, and record what it learned back into the vault.
+
+```json
+{
+ "mcpServers": {
+ "om": {
+ "command": "node",
+ "args": ["/path/to/your-vault/.claude/scripts/om-mcp.mjs"]
+ }
+ }
+}
+```
+
+That goes in the **consuming project's** `.mcp.json`. Then add a short section to that project's own `CLAUDE.md` pointing at the vault.
+
+> [!IMPORTANT]
+> **Both steps are required, and the second is not paperwork.** Measured: with the server wired and no repo-side instruction, a session made **zero** vault calls and implemented a design the vault had recorded as explicitly rejected. With the instruction present, it refused and cited the note.
+>
+> A **prohibition** in the MCP `instructions` field propagates into the calling session reliably. A positive *"go consult the vault"* is advisory and gets skipped whenever a nearer source exists. The server can stop a session doing something; only the project's own law makes one go looking.
+
+**What the session gets:** `search` (semantic + keyword), `expand` (a note's links and backlinks), `recall` (durable lessons scoped to that repo), `remember` (record a lesson), `record_work` (file what happened), and `health` (is the wiring intact?). Plus your notes as readable resources.
+
+**Repos are identified by folder name**, which is right until it isn't — two repos both called `api` share one identity and therefore each other's memories. Drop a `.om-project` file with a distinct name at the repo root to separate them; `health` tells you which repo it thinks is calling and where that name came from.
+
+**Cross-repo memory with an epistemic contract.** A lesson learned in one repo reaches the repos it was scoped to and no others. Reach is *declared at write time*, never guessed at read time, so a sibling project does not inherit another's constraints. Everything recorded carries `confidence: verified | inferred | unverified`, dated volatile facts, and provenance derived server-side — a session cannot claim to be a project it is not. Corrections supersede rather than overwrite, so the store gets *more* trustworthy as it grows instead of accumulating contradictions.
+
+**Which notes it serves.** Your vault, your notes, your session — the default is simply what your vault already declares as your content (`user_content_roots`), at the granularity you wrote it (`work/active/`, not all of `work/`). Set `mcp_exposed_roots` in `vault-manifest.json` only if this vault holds material that is **not yours to share** — employer-confidential notes, a client's data. A note tagged `private` is never served, and memories are never served as ordinary notes, since they carry their own scope.
+
+Every read is logged with the calling repo, so "what did that session actually see" is answerable afterwards.
+
+> [!NOTE]
+> Keeping vault material out of a public PR is the **contract's** job, not the exposure list's — a session can read your vault directly regardless. The prohibition injected into the calling session is the part that measurably holds.
+
+**Want the mechanics?** `ARCHITECTURE.md` → *Reaching the Vault From Another Repo* walks the whole layer with diagrams: the four MCP surfaces and why the non-tool ones matter, the identity handshake, a `search` call traced end to end, how each memory's reach is evaluated, the write path, and every failure mode against the signal that reveals it.
+
+---
+
## 📅 Daily Workflow
**Morning**: Run `/om-standup`. Your agent loads your North Star, active projects, open tasks, and recent changes. You get a structured summary and suggested priorities.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 705df48..6762f68 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -142,8 +142,27 @@ qmd --index obsidian-mind embed # 大量新笔记后
**通过 MCP 原生集成为 Agent 工具。** 在 `.mcp.json` 中注册为 [Model Context Protocol](https://modelcontextprotocol.io) 服务器——当 QMD 已安装时,`mcp__qmd__query`、`mcp__qmd__get`、`mcp__qmd__multi_get` 会与 Read、Edit 一起出现在 Agent 的工具菜单中。子代理、斜杠命令和主对话都通过同一个带类型的契约进行调用。之后再接入其他 MCP 兼容工具(数据库、工单系统、日历),接入方式完全一致。
-> [!NOTE]
-> 如果没有安装 QMD,一切仍然正常运作——Agent 会回退到 Obsidian CLI 和 grep,MCP 服务器条目会以无害的警告被跳过。
+#### 底层是怎么工作的
+
+QMD **在本地运行三个小模型**,因此不需要配置 API 密钥,没有按次查询的费用,离线也能用:
+
+| 模型 | 大小 | 作用 |
+|---|---|---|
+| `embeddinggemma-300M` | ~328MB | 把笔记和查询转成向量 |
+| `qmd-query-expansion-1.7B` | ~1.28GB | 把你的查询改写成更好的检索词 |
+| `Qwen3-Reranker-0.6B` | ~640MB | 按真实相关性重排候选结果 |
+
+它们在首次使用时下载并缓存。QMD 在发现 GPU 时会做卸载计算(独立显卡走 CUDA,Apple Silicon 走 Metal),否则回退到 CPU。用 `qmd doctor` 可以查看你这边的实际情况。
+
+三个 CLI 命令按开销从低到高对应这套栈:`qmd search` 是 BM25 关键词检索、**完全不用模型**,`qmd vsearch` 只用向量,`qmd query` 是完整的混合检索。如果想避免较大的下载,单用 `search` 也已经很有用。
+
+#### 这对 MCP 服务器意味着什么
+
+`om` 服务器会同时发送词法查询和向量查询,因此即使笔记与你的问题没有共同关键词,也能被找到。几点实际影响:
+
+- **贵的是读取,不是写入。** 查询在检索前需要先在本地做嵌入,所以带查询的 `recall` 要几秒,而不带查询的 `recall` 几乎是瞬时的。对笔记的 `search` 很快,真正花时间的是向量那一步。
+- **写入记忆不会等待模型。** 索引更新是同步的,所以新记忆立刻可被检索;生成向量在后台进行,因为它只影响**排序**,不影响能否被找到。
+- **没有索引也能用。** 没有 QMD 时服务器回退到词法匹配。排序会变差,但不会丢东西。
---
@@ -190,7 +209,7 @@ obsidian-mind **不会**将整个 vault 加载到上下文中。它使用分层
| 层级 | 内容 | 时机 | 成本 |
|------|------|------|------|
-| **始终** | `CLAUDE.md` + SessionStart 上下文(北极星摘要、git 摘要、任务、vault 文件列表) | 会话启动时 | ~2K tokens |
+| **始终** | `CLAUDE.md` + SessionStart 上下文(北极星摘要、git 摘要、任务、vault 文件列表) | 会话启动时 | 以清单中的预算为上限;每次会话末尾的计量器报告实际大小 |
| **按需** | QMD 语义搜索结果 | Agent 需要特定上下文时 | 精准定向 |
| **触发** | 分类路由提示 | 每条消息 | ~100 tokens |
| **触发** | PostToolUse 验证 | `.md` 写入后 | ~200 tokens |
@@ -215,6 +234,41 @@ obsidian-mind 支持 Claude Code、Codex CLI 和 Gemini CLI。`CLAUDE.md` 中的
---
+## 🧠 从任意仓库访问你的 vault
+
+vault 通常只在你身处其中时才有用。**`om` MCP 服务器**改变了这一点:*任何其他仓库*中的编码会话都可以搜索你的笔记、阅读它们、沿图谱跳转,并把学到的东西记录回 vault。
+
+```json
+{
+ "mcpServers": {
+ "om": {
+ "command": "node",
+ "args": ["/path/to/your-vault/.claude/scripts/om-mcp.mjs"]
+ }
+ }
+}
+```
+
+这段配置放在**使用方项目**的 `.mcp.json` 中。然后在该项目自己的 `CLAUDE.md` 里加上一小节,指向这个 vault。
+
+> [!IMPORTANT]
+> **两步缺一不可,第二步不是走过场。** 实测:服务器已接好但没有仓库侧说明时,会话**一次**都没有调用 vault,并径直实现了一个 vault 明确记录为已否决的设计。有说明时,它拒绝实现并引用了那条笔记。
+>
+> MCP `instructions` 字段中的**禁止性规则**会可靠地传播到调用方会话;而“去查阅 vault”这类肯定式指令只是建议性的,只要存在更近的信息源就会被跳过。服务器能阻止会话做某件事,但只有项目自身的规约能让它主动去查。
+
+**会话得到的能力:** `search`(语义 + 关键词)、`expand`(笔记的出链与反链)、`recall`(限定到该仓库的持久经验)、`remember`(记录一条经验)、`record_work`(归档所做的工作)、`health`(接线是否完好)。此外还把笔记作为可读资源暴露出来。
+
+**仓库按文件夹名识别。** 这在大多数情况下是对的,偶尔不是:两个都叫 `api` 的仓库会共享同一个身份,于是彼此收到对方的记忆。在仓库根目录放一个 `.om-project` 文件并写入不同的名字即可分开;`health` 会告诉你它认为是哪个仓库在调用,以及这个名字从哪里来。
+
+**带认知契约的跨仓库记忆。** 在一个仓库学到的经验只会到达它被限定的那些仓库。触及范围是在*写入时声明*的,而非读取时猜测,因此同类项目不会继承彼此的约束。所有记录都带有 `confidence: verified | inferred | unverified`、易变事实的日期,以及服务端推导的来源 — 会话无法冒充自己以外的项目。更正以取代而非覆盖的方式记录,因此这个存储不会累积矛盾,反而会随着增长变得**更**可信。
+
+**它提供哪些笔记。** 你的 vault、你的笔记、你的会话。默认就是 vault 已经声明为你自己内容的部分(`user_content_roots`),并保持你书写时的粒度(是 `work/active/`,而不是整个 `work/`)。只有当这个 vault 存放着**并非你有权分享**的材料 —— 雇主的机密信息、客户的数据 —— 时,才需要在 `vault-manifest.json` 里设置 `mcp_exposed_roots`。标记为 `private` 的笔记不会被提供;记忆有自己的作用域,因此也不会作为普通笔记提供。每次读取都会连同调用方仓库一起记入日志。
+
+> [!NOTE]
+> 让 vault 内容不出现在公开 PR 里,是**契约**的职责,而不是这份开放清单的职责 —— 会话本来就能直接读取你的 vault。真正被实测证明有效的,是注入到调用方会话中的禁止性规则。
+
+---
+
## 📅 日常工作流
**早晨**:运行 `/om-standup`。Agent 加载你的北极星目标、活跃项目、待办任务和最近变更。你会得到一份结构化的摘要和优先事项建议。
diff --git a/bases/Memories.base b/bases/Memories.base
new file mode 100644
index 0000000..b5f2c3d
--- /dev/null
+++ b/bases/Memories.base
@@ -0,0 +1,93 @@
+filters:
+ and:
+ - file.ext == "md"
+ - source == "mcp-capture"
+formulas:
+ reach: if(scope == "general", "everywhere", if(scope == "platform", list(platforms).join(", "), list(projects).join(", ")))
+ age_days: if(date, (today() - date(date)).days, "")
+ corrected: if(list(superseded_by).isEmpty(), "", "superseded")
+properties:
+ file.name:
+ displayName: Memory
+ scope:
+ displayName: Scope
+ formula.reach:
+ displayName: Reaches
+ confidence:
+ displayName: Confidence
+ origin:
+ displayName: Learned in
+ date:
+ displayName: Recorded
+ formula.age_days:
+ displayName: Days Old
+ formula.corrected:
+ displayName: Status
+views:
+ - type: table
+ name: Recent
+ order:
+ - file.name
+ - formula.reach
+ - confidence
+ - origin
+ - date
+ sort:
+ - property: date
+ direction: DESC
+ limit: 50
+ - type: table
+ name: By project
+ filters:
+ and:
+ - scope == "project"
+ order:
+ - file.name
+ - formula.reach
+ - confidence
+ - date
+ sort:
+ - property: projects
+ direction: ASC
+ limit: 100
+ - type: table
+ name: Needs review
+ filters:
+ and:
+ - confidence != "verified"
+ order:
+ - file.name
+ - confidence
+ - origin
+ - formula.age_days
+ sort:
+ - property: date
+ direction: ASC
+ limit: 50
+ - type: table
+ name: Superseded
+ filters:
+ and:
+ - '!list(superseded_by).isEmpty()'
+ order:
+ - file.name
+ - superseded_by
+ - date
+ sort:
+ - property: date
+ direction: DESC
+ limit: 30
+ - type: table
+ name: General reach
+ filters:
+ and:
+ - scope == "general"
+ order:
+ - file.name
+ - confidence
+ - origin
+ - date
+ sort:
+ - property: date
+ direction: DESC
+ limit: 50
diff --git a/brain/Skills.md b/brain/Skills.md
index 7575a92..81685c9 100644
--- a/brain/Skills.md
+++ b/brain/Skills.md
@@ -118,6 +118,27 @@ If QMD is installed (`npm install -g @tobilu/qmd`), the vault has semantic searc
SessionStart hook runs `qmd --index <name> update` automatically, reading the index name from the manifest. First-time setup on a fresh clone: `node --experimental-strip-types .scripts/qmd-bootstrap.ts`. See `.claude/skills/qmd/SKILL.md` for full reference, and [[Memories]] for the topics QMD is most often asked to find across the vault.
+## The `om` MCP Server (reaching this vault from another repo)
+
+`.claude/scripts/om-mcp.mjs` exposes this vault over MCP so a session in **another repository** can use it. Registered in the *consuming* project's `.mcp.json`, never in this vault's own — the server refuses a memory write from a session running inside the vault, because such a memory would be scoped to the vault-as-a-project and reach only sessions that already read every note directly.
+
+| tool | purpose |
+|------|---------|
+| `search` | semantic + keyword over the notes this vault serves |
+| `expand` | a note's links out and backlinks |
+| `recall` | durable lessons scoped to the calling repo, most specific first; `explain: true` reports what was withheld and why |
+| `remember` | record a lesson that generalises beyond this repo |
+| `record_work` | record what happened here, filed where it belongs |
+| `health` | where memories live, which roots are exposed, is the index reachable |
+
+Two prompts you invoke yourself from the `/` menu: `recall_topic`, `prior_art`. They must be **selected** from the menu — typing the displayed label errors.
+
+**Debugging it:** call `health` first. Every failure in this layer presents identically as "no results" — a renamed memory folder, a moved launcher, an index registered to a different vault, a session with no identity — and `health` is what tells them apart. A caller reported as `ANONYMOUS` means the client never completed the roots handshake, so only `general`-scope memories are visible.
+
+**Two guards worth knowing:** memories are never served as ordinary notes (they carry their own declared scope), and a memory that would reach nobody is refused rather than silently widened to `general`.
+
+Full setup, which notes the server serves, and the required repo-side snippet: `CLAUDE.md` § *Reaching the Vault From Another Repo*. How the whole layer works — the four MCP surfaces, the identity handshake, a `search` call end to end, memory-visibility evaluation, the write path: `ARCHITECTURE.md` § *Reaching the Vault From Another Repo*.
+
## Workflow: Weekly Review
1. **`/om-weekly`** — synthesize the week's activity, check alignment, find patterns
diff --git a/vault-manifest.json b/vault-manifest.json
index 58a19ec..10ccddb 100644
--- a/vault-manifest.json
+++ b/vault-manifest.json
@@ -15,6 +15,10 @@
],
"eager_layer_budget_bytes": 80000,
"listing_collapse_threshold": 12,
+ "memory_root": "memories",
+ "mcp_exposed_roots": [],
+ "mcp_never_expose": [],
+ "mcp_inbox": "inbox",
"qmd_context": "Engineer's work vault built on obsidian-mind. Active projects and archive, 1:1 notes, incidents, brag log with quarterly evidence, competency map, people and teams, decisions and patterns in brain/, reference docs and runbooks. Multi-agent (Claude Code, Codex, Gemini) with lifecycle hooks and QMD semantic search. Ground for 'what did I ship?' reviews, project status, and personal knowledge management.",
"infrastructure": [
"CLAUDE.md",
@@ -67,7 +71,8 @@
"perf/h*-*/",
"perf/competencies/*.md",
"brain/*.md",
- "reference/"
+ "reference/",
+ "memories/"
],
"version_fingerprints": {
"v1": {
@@ -195,6 +200,13 @@
".claude/commands/om-tidy.md",
".claude/scripts/generate-memory-index.ts"
]
+ },
+ "v8.0": {
+ "exists": [
+ ".claude/scripts/om-mcp.mjs",
+ ".claude/scripts/lib/memory-write.ts",
+ "bases/Memories.base"
+ ]
}
},
"frontmatter_required": {