Skip to content

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

feat: (reason) answer judgement questions by reading the vault in a second session (#163)

Brenno Ferrari990946ce4829
diff --git a/.claude/scripts/lib/mcp-caller.ts b/.claude/scripts/lib/mcp-caller.ts
index fb87652..19246ed 100644
--- a/.claude/scripts/lib/mcp-caller.ts
+++ b/.claude/scripts/lib/mcp-caller.ts
@@ -8,7 +8,17 @@
* empty vault.
*/
-import { appendFileSync, mkdirSync, readFileSync, renameSync, statSync } from "node:fs";
+import {
+ appendFileSync,
+ closeSync,
+ fstatSync,
+ mkdirSync,
+ openSync,
+ readFileSync,
+ readSync,
+ renameSync,
+ statSync,
+} from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -184,3 +194,133 @@ export function createAuditor(
export function auditPath(vaultRoot: string): string {
return join(vaultRoot, ".claude", "om-mcp-audit.jsonl");
}
+
+/**
+ * How much of the tail to read back. The log is append-only and time-ordered, so
+ * one day's entries are contiguous at the end; a fixed window keeps a read
+ * bounded no matter how large the log has grown.
+ */
+const AUDIT_TAIL_BYTES = 512 * 1024;
+
+/**
+ * Read the last `AUDIT_TAIL_BYTES` of a file, dropping a torn leading line.
+ *
+ * `whole` says whether the window reached the start of the file. A caller
+ * summing a day cannot know from the numbers alone whether it saw all of them,
+ * and a silently-low figure is worse than an explicitly partial one.
+ */
+function tail(path: string): { text: string; whole: boolean } {
+ let fd: number;
+ try {
+ fd = openSync(path, "r");
+ } catch {
+ // Absent is "nothing to add", not "truncated" — a vault with no log yet
+ // must not report its zero as partial.
+ return { text: "", whole: true };
+ }
+ try {
+ // The OPEN FILE, not the path — that is the whole reason the fd is held.
+ // `createAuditor` can rotate between the open and the stat, and then
+ // `statSync(path)` describes the fresh live file while the fd still points
+ // at the renamed inode. Measured: a 61-byte stat against a 680KB fd made
+ // `from` compute to 0, which skipped the torn-line drop AND re-read the
+ // head of a generation the caller had already summed — double-counting it.
+ const size = fstatSync(fd).size;
+ // One byte BEFORE the window when there is one, so an aligned boundary can
+ // be told from a torn one. Without it, a window that happens to start
+ // exactly at a line start discards a whole valid entry — proven with
+ // fixed-width entries: 4,096 inside the window, 4,095 summed.
+ const from = size > AUDIT_TAIL_BYTES ? size - AUDIT_TAIL_BYTES - 1 : 0;
+ const buf = Buffer.allocUnsafe(size - from);
+ let read = 0;
+ while (read < buf.length) {
+ const n = readSync(fd, buf, read, buf.length - read, from + read);
+ if (n <= 0) break;
+ read += n;
+ }
+ // Decoding from an arbitrary byte offset can split a multi-byte character,
+ // but only at the START — the window always ends at EOF — and any partial
+ // leading line is dropped below.
+ const text = buf.subarray(0, read).toString("utf8");
+ if (from === 0) return { text, whole: true };
+ // The probe byte was a newline, so the window began on a line boundary and
+ // every line after it is complete. Otherwise the first line is torn.
+ return text.startsWith("\n")
+ ? { text: text.slice(1), whole: false }
+ : { text: text.slice(text.indexOf("\n") + 1), whole: false };
+ } catch {
+ return { text: "", whole: true };
+ } finally {
+ closeSync(fd);
+ }
+}
+
+/**
+ * Can we prove the oldest surviving entry predates the day?
+ *
+ * Only then is a partial read still a complete answer for that day. An
+ * unreadable or absent first entry proves nothing, so it counts as partial.
+ */
+function predatesDay(text: string, dayPrefix: string): boolean {
+ const first = text.split("\n", 1)[0];
+ if (!first?.trim()) return false;
+ try {
+ const at = (JSON.parse(first) as AuditEntry).at;
+ return typeof at === "string" && at < dayPrefix;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Sum a numeric field across today's entries for one action.
+ *
+ * Lives here, beside the writer, because everything it depends on is this
+ * module's business: the entry shape, the `at` format, the log's path, and the
+ * ROTATION. `createAuditor` renames the log to `.jsonl.1` once it crosses
+ * `AUDIT_MAX_BYTES`, so a reader that knows only the live path reports zero for
+ * a day that did spend — the rotated generation is read too, for exactly that
+ * reason. Kept away from its writer, this drifts the moment either side changes.
+ *
+ * Reads a bounded tail rather than the whole file: the caller is `health`, which
+ * is routinely the FIRST call a server serves, and the log records a line per
+ * read across every consuming repo sharing this vault.
+ *
+ * Unparseable lines are skipped rather than throwing — a torn write may
+ * under-report, but it must never take `health` down with it.
+ */
+export function sumAuditField(
+ vaultRoot: string,
+ action: string,
+ dayPrefix: string,
+ field: string,
+): { total: number; complete: boolean } {
+ const live = auditPath(vaultRoot);
+ const generations = [tail(`${live}.1`), tail(live)];
+ let complete = true;
+ let total = 0;
+ for (const { text, whole } of generations) {
+ // A partial read is only provably complete for the DAY if its oldest
+ // surviving entry already predates the day — then nothing of today can be
+ // hiding behind it. Anything else counts as partial, INCLUDING a window
+ // that yielded no readable entry at all: one audit line larger than the
+ // window leaves exactly that, and an earlier version read the resulting
+ // empty text as "no entries today" and reported a confident zero.
+ if (!whole) complete &&= predatesDay(text, dayPrefix);
+ for (const line of text.split("\n")) {
+ // Cheap reject before the parse: any encoding of an entry with this
+ // action contains the action's name somewhere in the line.
+ if (!line.includes(action)) continue;
+ try {
+ const e = JSON.parse(line) as AuditEntry;
+ if (e.action !== action) continue;
+ if (typeof e.at !== "string" || !e.at.startsWith(dayPrefix)) continue;
+ const v = e[field];
+ if (typeof v === "number" && Number.isFinite(v)) total += v;
+ } catch {
+ /* a torn or hand-edited line is skipped, never fatal */
+ }
+ }
+ }
+ return { total, complete };
+}
diff --git a/.claude/scripts/lib/mcp-reason.ts b/.claude/scripts/lib/mcp-reason.ts
new file mode 100644
index 0000000..2158fe6
--- /dev/null
+++ b/.claude/scripts/lib/mcp-reason.ts
@@ -0,0 +1,825 @@
+/**
+ * `reason` — judgement over vault context, in a spawned session.
+ *
+ * This is tier 3 of the ladder in ARCHITECTURE.md, but nothing a user touches
+ * says "tier 3": the tool is `reason` and the manifest block is `reason`. The
+ * tier numbering is our taxonomy for the design, not a name anyone should have
+ * to learn to configure a model pin.
+ *
+ * Some questions cannot be answered by retrieving a passage, because they need
+ * judgement ACROSS notes: is what I am about to do consistent with what these
+ * six notes decided, and what do I do about the two that disagree? Retrieval
+ * returns the notes. Something has to read them.
+ *
+ * It spawns because a server cannot borrow the calling session's inference —
+ * MCP calls that sampling, and Claude Code does not implement it
+ * (anthropics/claude-code#1785). So it starts a session through the user's own
+ * CLI, which is also why it passes no `--model`: MCP does not expose the
+ * caller's model, and the CLI's own default is the closest match to the level
+ * the caller is already working at.
+ *
+ * The spawn is isolated (`--strict-mcp-config` against an empty server map, so
+ * it cannot call back into `om`), read-only, and seeded with tier-1 results so
+ * it does not spend turns rediscovering what the server already has. Every
+ * invocation is appended to the audit log with its cost, turns, model and wall
+ * time.
+ */
+
+import { spawn, type ChildProcess, type ChildProcessByStdio } from "node:child_process";
+import type { Readable } from "node:stream";
+import { writeFileSync, mkdirSync, readFileSync, existsSync, copyFileSync, unlinkSync, constants } from "node:fs";
+import { createRequire } from "node:module";
+import { join, dirname } from "node:path";
+
+import { claimFile } from "./atomic-write.ts";
+
+const require = createRequire(import.meta.url);
+
+/** Where an answer and its provenance are written. */
+export const REASONING_DIR = ".claude/om-reasoning";
+
+export interface ReasonConfig {
+ /**
+ * null — the usual case — means DO NOT pass `--model`, so the spawn runs on
+ * the user's own CLI default: whatever they would get typing `claude`.
+ *
+ * MCP gives a server no way to see the calling session's model, so inheriting
+ * the CLI default is the closest reachable thing to "the same model I am
+ * using". Pinning one here would quietly hand back worse answers than the
+ * caller's own session would produce, for a choice that is theirs.
+ *
+ * A vault that wants to pin one sets it, and then it must be a FULL id:
+ * `--model haiku` is not honoured and does not error — it silently runs
+ * sonnet. An alias is ignored rather than passed on.
+ */
+ readonly model: string | null;
+}
+
+/**
+ * The audit log's name for this tool, exported so the stamp and the read of it
+ * move together. Renamed on one side only, the daily figure silently reads zero
+ * forever — indistinguishable from "no calls today". Same reason `MEMORY_SOURCE`
+ * is re-exported from the writer that stamps it.
+ */
+export const REASON_ACTION = "reason";
+
+/**
+ * How much of the question the audit line keeps.
+ *
+ * A log-hygiene bound, not a limit on the caller: an entry larger than the
+ * log's read window leaves nothing parseable in that window, which zeroes the
+ * day's reported usage. Generous enough that a real question survives whole.
+ */
+const AUDIT_QUESTION_MAX = 2000;
+
+/**
+ * How long a spawn may run before it is killed.
+ *
+ * Fixed, not configurable: this bounds a HUNG CHILD, which is a failure rather
+ * than a preference. Nobody wants a wedged process, and nobody has a reason to
+ * want a different number for it.
+ */
+const SPAWN_TIMEOUT_MS = 300_000;
+
+/**
+ * The bare aliases the CLI accepts and then quietly ignores.
+ *
+ * Rejecting THESE, rather than allow-listing an id shape, because an allow-list
+ * silently drops ids it did not anticipate: `^claude-[a-z]+-[0-9]` was the first
+ * attempt and it rejects `claude-3-5-sonnet-20241022`, a perfectly real id, for
+ * the same "quietly means something else" reason the aliases are rejected for.
+ * Anything not on this list is passed through, and the answer always names the
+ * model that actually ran — so a pin the CLI ignores is reported, not hidden.
+ */
+const BARE_ALIASES = new Set(["haiku", "sonnet", "opus", "default", "sonnet[1m]", "opusplan"]);
+
+/**
+ * Read the manifest's `reason` block. Exactly one thing is configurable — a model
+ * pin — and it defaults to using the user's own Claude settings.
+ *
+ * Pure, so the decision can be driven by a test without spawning anything.
+ */
+export function resolveReasonConfig(manifest: Record<string, unknown> | null | undefined): ReasonConfig {
+ const raw = (manifest?.reason ?? {}) as Record<string, unknown>;
+ const asked = typeof raw.model === "string" ? raw.model.trim() : "";
+ // A bare alias, or anything unset, falls back to inheriting rather than to a
+ // hardcoded id — a wrong pin is worse than no pin.
+ return { model: asked && !BARE_ALIASES.has(asked.toLowerCase()) ? asked : null };
+}
+
+/**
+ * The audit detail for one run, built HERE so the fields and the reader of them
+ * stay in one module rather than being composed a layer up.
+ */
+export function reasonAuditDetail(
+ question: string,
+ cfg: ReasonConfig,
+ r: ReasoningResult,
+ scope: ReasoningScope | undefined,
+): Record<string, unknown> {
+ return {
+ // Truncated for the LOG only — the question itself is never limited. One
+ // entry longer than the log's read window leaves nothing parseable in it,
+ // and the day's usage figure then reports a confident zero. Capping what
+ // is written keeps a long question from erasing the record of every call
+ // beside it; what may be ASKED is not this layer's business.
+ question: question.length > AUDIT_QUESTION_MAX ? `${question.slice(0, AUDIT_QUESTION_MAX)}…` : question,
+ cost_usd: r.costUsd,
+ turns: r.turns,
+ terminal: r.terminal,
+ model_asked: cfg.model,
+ model_used: r.modelUsed,
+ wall_ms: r.wallMs,
+ // What the spawn was TOLD it could read. The boundary is observed by the
+ // spawn rather than enforced by the filesystem, so recording it is what
+ // keeps "what did that session actually see" answerable afterwards.
+ roots: scope ? scope.roots.join(",") : "vault-wide",
+ };
+}
+
+/**
+ * What this vault's reasoning has cost today, as one line for `health`.
+ *
+ * Reported and used for nothing else — it does not gate a call. Nothing here
+ * bounds usage, so this line is the whole of the answer to "where did it go",
+ * and it reads the log already written on every invocation rather than a second
+ * counter that could disagree with it.
+ *
+ * Composed here rather than in the server so the wiring layer interpolates a
+ * string instead of knowing this tool's audit key, its config, and where the log
+ * lives — and so it can be tested without a wire.
+ */
+export function reasonUsage(
+ vaultRoot: string,
+ manifest: Record<string, unknown> | null | undefined,
+ today: string,
+ readSpend: (
+ vaultRoot: string,
+ action: string,
+ day: string,
+ field: string,
+ ) => { total: number; complete: boolean },
+): string {
+ const { total, complete } = readSpend(vaultRoot, REASON_ACTION, today, "cost_usd");
+ const model = resolveReasonConfig(manifest).model ?? "your CLI default";
+ // "at least" when the log was too large to read whole. A figure that is
+ // silently low is worse than one that says it is a floor — this line is the
+ // entire answer to where usage went, so it has to be honest about its own
+ // limits rather than quietly under-report on the busiest days.
+ const usage =
+ total > 0
+ ? `${complete ? "$" : "at least $"}${total.toFixed(4)} reported across today's calls`
+ : complete
+ ? "nothing yet today"
+ : "nothing in the readable tail of today's log";
+ return `${usage} · model: ${model}`;
+}
+
+export interface ReasoningResult {
+ readonly ok: boolean;
+ /** Empty when the run was cut short; never a partial answer. */
+ readonly answer: string;
+ readonly costUsd: number;
+ readonly turns: number;
+ /** The model the CLI reports actually running, which is not always the one asked for. */
+ readonly modelUsed: string;
+ /** Why the CLI stopped — reported verbatim, so an early end can be named. */
+ readonly terminal: string;
+ readonly wallMs: number;
+ readonly error: string | null;
+}
+
+/**
+ * The tools the spawn may use: enough to read the whole vault, and nothing that
+ * writes. `--tools` restricts the built-in set itself, so a blocked call comes
+ * back as "No such tool available: Write" rather than as a permission prompt
+ * nothing is there to answer.
+ *
+ * NOT `--permission-mode plan`, which was the first attempt and is wrong twice
+ * over. It is not read-only — it writes the plan to `~/.claude/plans/`, outside
+ * the vault entirely — and, worse, it changes what the spawn thinks it is
+ * producing. In a measured run the model composed its analysis AS A PLAN, tried
+ * to hand it back through `ExitPlanMode`, found no such tool headlessly, wrote
+ * the content to a plan file, and returned a one-line note about having done so.
+ * The entire answer was lost, and the failure is non-deterministic: an earlier
+ * run of the same build answered normally.
+ */
+const READ_ONLY_TOOLS = "Read,Grep,Glob";
+
+/** Build the argv. Separated so the flags can be asserted without spawning. */
+export function reasoningArgs(cfg: ReasonConfig, prompt: string, mcpConfigPath: string): string[] {
+ return [
+ "-p",
+ prompt,
+ // Omitted unless the vault pinned one, so the spawn runs on the user's own
+ // CLI default rather than on a model this server chose for them.
+ ...(cfg.model ? ["--model", cfg.model] : []),
+ "--output-format",
+ "json",
+ // The recursion guard. With an empty server map this leaves the spawn no
+ // MCP at all, so it cannot call back into this server and start a loop
+ // that multiplies at every level. Verified: the spawn reports no MCP servers.
+ "--strict-mcp-config",
+ "--mcp-config",
+ mcpConfigPath,
+ // A reasoning pass answers; it does not edit the vault.
+ "--tools",
+ READ_ONLY_TOOLS,
+ ];
+}
+
+/**
+ * Which of the vault the spawn may read, mirroring the exposure policy.
+ *
+ * All THREE of the policy's rules, not just the first. Roots alone are not the
+ * policy: `mcp_never_expose` filenames and `private:`-tagged notes live INSIDE
+ * exposed roots, so a boundary naming only folders grants exactly the files the
+ * other two rules exist to withhold.
+ */
+export interface ReasoningScope {
+ /** The exposure policy's roots — the folders this vault serves. */
+ readonly roots: readonly string[];
+ /** The memory root, which is never readable as an ordinary note. */
+ readonly memoryRoot: string;
+ /** `mcp_never_expose` — filenames withheld wherever they appear. */
+ readonly neverExpose: readonly string[];
+}
+
+/**
+ * The spawn's read boundary, stated as a PROHIBITION.
+ *
+ * `--tools Read,Grep,Glob` with `cwd` at the vault root gives the spawn the
+ * whole tree, while the seed it was handed went through `allowedSearchPaths`.
+ * Without this the two disagree, and the one tool that reads most is the one
+ * that ignores `mcp_exposed_roots` — which exists for the vault holding material
+ * that is not the user's to share. The memory root is named separately because
+ * "memories are never served as an ordinary note" holds whatever the config
+ * says, and a spawn reading `memories/` directly sees every caller's, not its
+ * own.
+ *
+ * A prohibition rather than a request, because that is the form measured to
+ * propagate reliably into a session — a positive "consult X" is advisory and
+ * gets skipped whenever something nearer answers. It is a boundary the spawn
+ * observes, not one the filesystem enforces; the audit line records the roots so
+ * what it was told is recoverable afterwards.
+ */
+function boundary(scope: ReasoningScope | undefined): string[] {
+ if (!scope) return [];
+
+ // The policy's other two rules. Both select files INSIDE an exposed root, so
+ // naming only folders would permit precisely what they withhold.
+ const alsoWithheld = [
+ `Never read ${scope.memoryRoot}/ or .claude/ — those are not yours to quote.`,
+ ...(scope.neverExpose.length
+ ? [`Never read any file named: ${scope.neverExpose.join(", ")} — wherever it appears.`]
+ : []),
+ "Skip any note whose frontmatter has `private: true` or a `private` tag, even",
+ "inside an allowed folder, and do not quote or summarise it.",
+ ];
+
+ // NO roots is a deny, never a permit. `resolveExposure` strips the memory root
+ // from whatever the manifest declared, so a vault that exposes only its
+ // memories resolves to an EMPTY list — and an empty list producing no
+ // prohibition would hand the spawn the run of the vault at exactly the moment
+ // the config said to serve almost none of it. `callReason` refuses this
+ // configuration outright; the branch stays so the prompt is never the thing
+ // that fails open.
+ if (scope.roots.length === 0) {
+ return ["This vault exposes NO folders to other repos. Do not read the note tree at all.", ...alsoWithheld, ""];
+ }
+
+ return [
+ `Read ONLY within these folders: ${scope.roots.join(", ")}. Do not read anything`,
+ "outside them; if the answer would require a note outside that boundary, say so",
+ "instead of reading it.",
+ ...alsoWithheld,
+ "",
+ ];
+}
+
+/**
+ * Compose the prompt.
+ *
+ * Seeded with tier-1 evidence so the spawn does not pay turns rediscovering what
+ * the server already has. Measured, that saves about a turn — less than the
+ * foreign-cwd comparison suggested, because a spawn with `cwd` = the vault
+ * already inherits the contract.
+ *
+ * It also biases: in a measured run the seeded answer leaned on the passages and
+ * repeated a framing the vault had since corrected. Hence the explicit licence
+ * to go further, and the instruction to say when the evidence is thin.
+ */
+export function reasoningPrompt(question: string, evidence: string, scope?: ReasoningScope): string {
+ const common = [
+ ...boundary(scope),
+ "Answer directly, with no preamble about what you are about to do. Cite the note",
+ "paths you relied on. Preserve any '(TBC)', '(inferred)' or 'as of <date>' markers",
+ "you find, and never promote an inferred claim to a stated one.",
+ ];
+
+ // An empty seed means the INDEX had nothing, which is not the same as the
+ // vault having nothing — a vault with no index built yet returns exactly this.
+ // Measured: handed an empty seed under the normal wording, the spawn reported
+ // "no prior decisions recorded" about a question the vault answered in a note
+ // sitting one directory away. That is this layer's signature failure, so the
+ // empty case gets its own instructions rather than a blank evidence block.
+ if (!hasEvidence(evidence)) {
+ return [
+ question,
+ "",
+ "Vault search returned nothing usable — the index may be missing or stale, so",
+ "this is NOT evidence that the vault is silent on the question. You are running",
+ "inside the vault: read it directly, within the folders named below. Look through",
+ "the note tree yourself before concluding anything.",
+ "",
+ "Only report that nothing is recorded if you have actually looked and found",
+ "nothing, and say how you looked.",
+ "",
+ ...common,
+ ].join("\n");
+ }
+
+ return [
+ question,
+ "",
+ "Vault search has already returned the passages below. Start from them rather",
+ "than searching from scratch, but treat them as a starting point and not as the",
+ "whole record — you are running inside the vault, so read further when they are",
+ "thin, and say so when they are.",
+ "",
+ ...common,
+ "",
+ "<evidence>",
+ evidence,
+ "</evidence>",
+ ].join("\n");
+}
+
+/**
+ * The prose `qmdSearch` returns INSTEAD of an error when it found nothing or
+ * broke. Prefixes, matched against the start of the seed — a passage that merely
+ * quotes one of these phrases is still evidence.
+ */
+const NO_EVIDENCE_PREFIXES = ["(no results", "(search unavailable", "search failed:"] as const;
+
+/**
+ * Did the seeding search actually find anything?
+ *
+ * `qmdSearch` reports its own failures in prose rather than by throwing, so an
+ * empty index and a broken one both arrive as text and both must be recognised.
+ *
+ * This is the FALLBACK signal. Prefer `visibleHits` when the caller still holds
+ * the structured result, because matching on wording means an edit to that
+ * wording silently turns "found nothing" into "found something" — and the
+ * empty-seed prompt branch, which exists to stop this layer reporting false
+ * absence, would stop firing.
+ */
+export function hasEvidence(evidence: string): boolean {
+ const t = evidence.trim().toLowerCase();
+ if (!t) return false;
+ return !NO_EVIDENCE_PREFIXES.some((p) => t.startsWith(p));
+}
+
+/**
+ * How many hits the caller may actually see, from a structured search result.
+ *
+ * NOT `total`: that counts what qmd returned BEFORE the exposure policy filtered
+ * it, so a search whose every hit was withheld has `total > 0` and nothing to
+ * show. The seed the spawn receives is the permitted set, so the permitted count
+ * is what decides which prompt it gets.
+ */
+export function visibleHits(seed: { readonly total: number; readonly withheld: number }): number {
+ return Math.max(0, seed.total - seed.withheld);
+}
+
+/**
+ * Cap on collected stdout, in UTF-16 units — approximately the ceiling
+ * `spawnSync`'s `maxBuffer` gave. Unlike `maxBuffer` it truncates rather than
+ * killing the child, so an over-cap answer degrades to "the CLI printed…" rather
+ * than to a kill. Nothing observed has come close: `--output-format json` emits
+ * one result object of a few KB.
+ */
+const MAX_STDOUT_BYTES = 64 * 1024 * 1024;
+
+/**
+ * Spawns still running, so shutdown can end them.
+ *
+ * Module-level because there is one server process per consuming repo and the
+ * set belongs to the process, not to any one call.
+ */
+const active = new Set<ChildProcess>();
+
+/**
+ * Read a finished run's output. PURE — no spawn, no clock, no filesystem.
+ *
+ * Split out because everything that decides how a run is REPORTED lives here,
+ * including `ok`, which gates the "no answer, refused by name" path. While this
+ * was inside the spawn it was the one decision in this module nothing could
+ * exercise without starting a session. Same seam as `parseMemory` / `readMemoryFile`
+ * and `digestsFrom` / `loadMemoryDigests`.
+ */
+export function interpretRun(
+ stdout: string,
+ stderr: string,
+ spawnError: string | null,
+ wallMs: number,
+ /** True when node killed the child for overrunning `SPAWN_TIMEOUT_MS`. */
+ timedOut = false,
+): ReasoningResult {
+ // A timeout is not a failure to start, and reporting it as one is a lie the
+ // caller waited five minutes for. The signal, the exit code and `child.killed`
+ // all carry it; an earlier version discarded all three, so a kill, an ENOENT
+ // and an over-long argv were indistinguishable in both the message and the log.
+ if (timedOut) {
+ return {
+ ok: false,
+ answer: "",
+ costUsd: 0,
+ turns: 0,
+ modelUsed: "unknown",
+ terminal: "timeout",
+ wallMs,
+ error: null,
+ };
+ }
+ const empty = (error: string): ReasoningResult => ({
+ ok: false,
+ answer: "",
+ costUsd: 0,
+ turns: 0,
+ modelUsed: "",
+ terminal: "spawn_failed",
+ wallMs,
+ error,
+ });
+
+ let j: Record<string, unknown>;
+ try {
+ // `?? {}` is load-bearing: `JSON.parse("null")` returns null, and reading a
+ // field off it throws a TypeError out of the spawn's `close` listener —
+ // where nothing catches it, so it surfaces as an uncaughtException and
+ // takes the whole server down while the tool call never settles. Every
+ // other non-object body (`[]`, `42`, `"hi"`, `true`) is harmless.
+ const parsed: unknown = JSON.parse(stdout);
+ if (parsed === null || typeof parsed !== "object") throw new Error("not an object");
+ j = parsed as Record<string, unknown>;
+ } catch {
+ // A non-JSON body means the CLI never got far enough to report. Whatever it
+ // printed is the only diagnostic there is — and a spawn error outranks it,
+ // since "ENOENT: claude" explains the empty output that follows.
+ const why = String(stderr || stdout || "no output").slice(0, 300);
+ return empty(spawnError ?? why);
+ }
+ // Valid JSON but the process still failed to launch cleanly: trust the error.
+ if (spawnError) return empty(spawnError);
+
+ // Only an object yields model names. A string here would enumerate its
+ // character indices — `"abc"` became the model `"0,1,2"` in testing.
+ const rawUsage = j.modelUsage;
+ const usage = rawUsage !== null && typeof rawUsage === "object" ? (rawUsage as Record<string, unknown>) : {};
+
+ return {
+ // `is_error` covers a run that stopped without concluding, which is the
+ // outcome this must never present as a complete answer.
+ ok: j.is_error !== true,
+ answer: typeof j.result === "string" ? j.result : "",
+ costUsd: typeof j.total_cost_usd === "number" ? j.total_cost_usd : 0,
+ turns: typeof j.num_turns === "number" ? j.num_turns : 0,
+ modelUsed: Object.keys(usage).join(",") || "unknown",
+ terminal: typeof j.terminal_reason === "string" ? j.terminal_reason : "unknown",
+ wallMs,
+ error: null,
+ };
+}
+
+/**
+ * Run the spawn. The thin IO half; `interpretRun` decides what its output means.
+ *
+ * ASYNC, and that is load-bearing rather than stylistic. `spawnSync` holds the
+ * whole event loop for the life of the child — measured at 73–80s, capped at
+ * 300s — during which the server parses no stdin at all: no other tool call, no
+ * `ping`, no `roots/list` reply, and no timers, so the identity gate's own 2s
+ * cap could not fire either. The entry script pays for concurrency deliberately
+ * ("serialising them here would make one slow search block every other call"),
+ * and a synchronous spawn took that back harder than serialising would have.
+ *
+ * Spawns the binary DIRECTLY with argv — never through a shell. On Windows
+ * `cmd.exe` strips the quotes out of an inline JSON argument and the CLI then
+ * tries to open the mangled string as a file path; the same class of failure as
+ * a shell rewriting an array join.
+ *
+ * `stdio.stdin` is closed explicitly. Left open, the CLI waits on it and the
+ * call hangs until the timeout rather than answering.
+ */
+export function runReasoning(
+ claude: { readonly cmd: string; readonly leading: readonly string[] },
+ vaultRoot: string,
+ cfg: ReasonConfig,
+ prompt: string,
+ mcpConfigPath: string,
+): Promise<ReasoningResult> {
+ const started = Date.now();
+ return new Promise((resolve) => {
+ // The concrete stdio shape, stated rather than inferred: `["ignore","pipe",
+ // "pipe"]` guarantees non-null stdout/stderr, and naming the type is what
+ // makes that a compiler-checked fact instead of an evolving-any accident.
+ let spawned: ChildProcessByStdio<null, Readable, Readable>;
+ try {
+ spawned = spawn(claude.cmd, [...claude.leading, ...reasoningArgs(cfg, prompt, mcpConfigPath)], {
+ cwd: vaultRoot,
+ // `timeout` + `killSignal` reproduce spawnSync's bound without holding
+ // the loop: node kills the child itself when it overruns.
+ timeout: SPAWN_TIMEOUT_MS,
+ killSignal: "SIGKILL",
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ } catch (e) {
+ resolve(interpretRun("", "", e instanceof Error ? e.message : String(e), Date.now() - started));
+ return;
+ }
+ const child = spawned;
+
+ // Tracked so shutdown can end it. The child is not detached, but nothing
+ // reaps it either: its `timeout` timer lives in THIS process, so a server
+ // that exits mid-spawn leaves a session with no bound on it at all and no
+ // audit line — the line is written after the await that will never return.
+ // "Usage is answered by the record" stops being true the moment a run can
+ // finish unrecorded.
+ active.add(child);
+ const done = (r: ReasoningResult) => {
+ active.delete(child);
+ resolve(r);
+ };
+
+ let out = "";
+ let err = "";
+ child.stdout.setEncoding("utf8");
+ child.stdout.on("data", (d: string) => {
+ if (out.length < MAX_STDOUT_BYTES) out += d;
+ });
+ child.stderr.setEncoding("utf8");
+ child.stderr.on("data", (d: string) => {
+ // Only ever used as a diagnostic string, so a small window is plenty.
+ if (err.length < 4096) err += d;
+ });
+
+ let spawnError: string | null = null;
+ child.on("error", (e: Error) => {
+ spawnError = e.message;
+ });
+ // `close` rather than `exit`: it fires once the pipes are drained, so the
+ // last chunk of a large answer is never lost to the race.
+ child.on("close", (_code: number | null, signal: NodeJS.Signals | null) => {
+ // Wrapped because this listener runs outside any await: a throw here is
+ // an uncaughtException, and the entry script installs no handler — so a
+ // malformed body would kill the server AND leave the call unsettled.
+ try {
+ // Node kills with `killSignal` on timeout; `killed` covers a kill that
+ // arrived from `killActiveReasoning` during shutdown.
+ const killed = signal === "SIGKILL" || child.killed;
+ done(interpretRun(out, err, spawnError, Date.now() - started, killed && spawnError === null));
+ } catch (e) {
+ done({
+ ok: false,
+ answer: "",
+ costUsd: 0,
+ turns: 0,
+ modelUsed: "",
+ terminal: "spawn_failed",
+ wallMs: Date.now() - started,
+ error: e instanceof Error ? e.message : String(e),
+ });
+ }
+ });
+ });
+}
+
+/**
+ * End every in-flight spawn. Called from the server's shutdown path.
+ *
+ * A `reason` child is not detached and nothing else reaps it, while the only
+ * bound on its lifetime — node's `timeout` — is a timer in THIS process. Exiting
+ * without this leaves an unbounded session running against the user's account,
+ * whose audit line can never be written because the await it would follow is
+ * gone. Returns how many were killed, so a shutdown can say so.
+ */
+export function killActiveReasoning(): number {
+ let n = 0;
+ for (const child of active) {
+ try {
+ child.kill("SIGKILL");
+ n++;
+ } catch {
+ /* already gone; nothing to do */
+ }
+ }
+ active.clear();
+ return n;
+}
+
+/** Human-readable refusal, so a caller learns what to change. */
+export function describeRefusal(reason: string, detail: string): string {
+ return `Not run: ${reason}\n\n${detail}`;
+}
+
+/** The npm package that ships the CLI, when it was installed that way. */
+const CLI_PACKAGE = "@anthropic-ai/claude-code";
+
+/**
+ * Locate the CLI's real JS entry when it came from npm. Null when it did not.
+ *
+ * Reads the package's own `bin` rather than guessing a path, so a layout change
+ * upstream degrades to null instead of to a wrong file.
+ */
+function resolveCliEntry(): string | null {
+ try {
+ const manifestPath = require.resolve(`${CLI_PACKAGE}/package.json`);
+ const pkg = JSON.parse(readFileSync(manifestPath, "utf8")) as {
+ bin?: string | Record<string, string>;
+ };
+ const rel = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.claude;
+ if (!rel) return null;
+ const entry = join(dirname(manifestPath), rel);
+ return existsSync(entry) ? entry : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * How to invoke the CLI: the command plus any leading args.
+ *
+ * Three layers, in order.
+ *
+ * `OM_CLAUDE_BIN` first, because a user whose CLI is not on this process's PATH
+ * has no other way to say so, and a spawn that cannot find its binary is
+ * otherwise an opaque failure.
+ *
+ * Then the npm entry run through `process.execPath`, which is the same fix
+ * `qmd.ts` carries and for the same reason: npm installs a CLI on Windows as a
+ * `.cmd` shim, and Node refuses to spawn one without a shell. `reason` cannot
+ * take the shell escape hatch that `buildQmdCommand` falls back to — the prompt
+ * is a JSON-bearing argument and `cmd.exe` strips its quotes — so resolving the
+ * real JS entry is the only portable route.
+ *
+ * Then the bare name, which is right for the native single-binary install and is
+ * what this ran on before. A failed resolution therefore lands exactly where it
+ * always did rather than somewhere new.
+ */
+export function resolveClaudeCommand(env: NodeJS.ProcessEnv = process.env): {
+ readonly cmd: string;
+ readonly leading: readonly string[];
+} {
+ const override = env.OM_CLAUDE_BIN;
+ if (override && override.trim()) return { cmd: override.trim(), leading: [] };
+
+ const entry = resolveCliEntry();
+ if (entry) return { cmd: process.execPath, leading: [entry] };
+
+ return { cmd: "claude", leading: [] };
+}
+
+/**
+ * An MCP config declaring NO servers.
+ *
+ * Paired with `--strict-mcp-config` this is the recursion guard: the spawn
+ * inherits no MCP at all, so it cannot reach back into this server and start a
+ * loop that multiplies at every level. Verified — a spawn under these flags reports
+ * no MCP servers available.
+ *
+ * It lives beside the audit log rather than in `REASONING_DIR`, because that
+ * directory is user-facing — every answer names a record inside it — and is
+ * otherwise a homogeneous set of timestamped transcripts. Runtime plumbing sits
+ * with runtime plumbing so "list or prune my reasoning records" never needs a
+ * filename exception.
+ *
+ * NEVER REWRITTEN IN PLACE. The content is a constant, so the steady state is
+ * to read it, find it usable, and write nothing — the only way to have no write
+ * window at all. It is created only when absent or unusable, and then by
+ * EXCLUSIVE create, so two processes racing to create it cannot truncate each
+ * other.
+ *
+ * Both obvious alternatives are wrong, and for one reason: a spawned CHILD
+ * holds this file open while it parses it, concurrently with the parent.
+ * - A plain `writeFileSync` truncates first, so a second call can empty the
+ * file while a first call's child is reading it. What that child is reading
+ * is the recursion guard.
+ * - A temp-file-plus-rename fixes that on POSIX and FAILS ON WINDOWS: rename
+ * over a path another process holds open throws EPERM, so the rewrite blows
+ * up precisely when one call overlaps another call's child. Measured, not
+ * theorised — eight processes churning this path reproduced it every run.
+ *
+ * Self-healing survives: a user who deletes the file mid-session gets it back on
+ * the next call, and so does one who corrupts it, since an unparseable body
+ * counts as absent.
+ */
+export function writeIsolatedMcpConfigPath(vaultRoot: string): string {
+ return join(vaultRoot, ".claude", "om-mcp-no-mcp.json");
+}
+
+/** Per-process counter, so two in-flight creates cannot share a temp name. */
+let cfgSeq = 0;
+
+/** Is there already a config here that would isolate a spawn correctly? */
+function isolationIntact(path: string): boolean {
+ try {
+ const parsed = JSON.parse(readFileSync(path, "utf8")) as { mcpServers?: unknown };
+ // An empty server map is the whole point; anything else is not this file.
+ return Boolean(parsed) && typeof parsed.mcpServers === "object" && parsed.mcpServers !== null;
+ } catch {
+ return false;
+ }
+}
+
+export function writeIsolatedMcpConfig(vaultRoot: string): string {
+ const path = writeIsolatedMcpConfigPath(vaultRoot);
+ if (isolationIntact(path)) return path;
+
+ mkdirSync(dirname(path), { recursive: true });
+ const tmp = `${path}.${process.pid}-${++cfgSeq}.tmp`;
+ writeFileSync(tmp, JSON.stringify({ mcpServers: {} }), "utf8");
+ try {
+ // Fails rather than clobbering, so the loser of a create race simply keeps
+ // the winner's identical file instead of truncating it under a reader.
+ copyFileSync(tmp, path, constants.COPYFILE_EXCL);
+ } catch (e) {
+ // EEXIST is the race resolving correctly. Anything else means the guard is
+ // genuinely not on disk, and a spawn without it is a spawn that can recurse.
+ if ((e as NodeJS.ErrnoException)?.code !== "EEXIST") throw e;
+ } finally {
+ try {
+ unlinkSync(tmp);
+ } catch {
+ /* temp cleanup is best-effort */
+ }
+ }
+ return path;
+}
+
+/**
+ * The record's text. PURE, so its shape is assertable without touching disk —
+ * the same split `renderCapture`/`captureNote` and `renderMemory`/`writeMemory`
+ * keep, and the reason neither of them needs a tmpdir to prove its frontmatter.
+ */
+export function renderReasoningRecord(now: Date, question: string, r: ReasoningResult): string {
+ return [
+ "---",
+ `date: ${now.toISOString()}`,
+ "source: mcp-reason",
+ `cost_usd: ${r.costUsd}`,
+ `turns: ${r.turns}`,
+ `model: ${r.modelUsed}`,
+ // Always inferred. A spawned conclusion is reasoning, not a verified fact,
+ // and the epistemic contract exists to keep those apart.
+ `confidence: inferred`,
+ "---",
+ "",
+ "# Question",
+ "",
+ question,
+ "",
+ "# Answer",
+ "",
+ r.answer.trim(),
+ "",
+ ].join("\n");
+}
+
+/**
+ * Persist the question, the answer and what it cost.
+ *
+ * Gitignored, beside the audit log: a spawned conclusion is INFERRED, so it does
+ * not belong in the vault as a note and is deliberately not recorded as a
+ * memory. The calling session decides whether any of it is worth a `remember` —
+ * auto-recording machine reasoning is how a store fills with claims nobody
+ * asked for and nobody verified.
+ *
+ * Returns null on failure: losing the transcript must not lose the answer.
+ */
+export function writeReasoningRecord(
+ vaultRoot: string,
+ now: Date,
+ question: string,
+ r: ReasoningResult,
+): string | null {
+ try {
+ // Inside the try: an invalid Date throws on `toISOString`, and this function
+ // promises to return null rather than take the answer down with it.
+ const stamp = now.toISOString().replace(/[:.]/g, "-");
+ const dir = join(vaultRoot, REASONING_DIR);
+ mkdirSync(dir, { recursive: true });
+ // An exclusive claim, not a plain write. The stamp is millisecond-precision
+ // and reads as collision-proof, but two runs CAN land on it: calls overlap
+ // now that the spawn is async, and the deployment shape is one server per
+ // consuming repo, all writing into one vault. A plain write makes the loser
+ // silently overwrite the winner while both report success — the exact
+ // outcome `claimFile` was extracted for after six processes produced four
+ // files in the memory layer.
+ const { name } = claimFile(dir, renderReasoningRecord(now, question, r), (n) =>
+ n === 1 ? `${stamp}.md` : `${stamp}-${n}.md`,
+ );
+ return `${REASONING_DIR}/${name}`;
+ } catch {
+ return null;
+ }
+}
diff --git a/.claude/scripts/lib/mcp-server.ts b/.claude/scripts/lib/mcp-server.ts
index 27bb792..6250dac 100644
--- a/.claude/scripts/lib/mcp-server.ts
+++ b/.claude/scripts/lib/mcp-server.ts
@@ -27,7 +27,7 @@ import {
} 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 { callerProject, callerProjectSource, isVaultItself, PROJECT_MARKER, sumAuditField, sanitize } from "./mcp-caller.ts";
import { callerPlatforms, digestsFrom, resolvableNames } from "./mcp-memory-bridge.ts";
import { captureNote } from "./mcp-capture.ts";
import { semanticMemoryOrder } from "./mcp-memory-bridge.ts";
@@ -39,12 +39,27 @@ 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";
+import {
+ resolveReasonConfig,
+ reasonUsage,
+ reasonAuditDetail,
+ runReasoning,
+ reasoningPrompt,
+ visibleHits,
+ resolveClaudeCommand,
+ writeIsolatedMcpConfig,
+ writeReasoningRecord,
+ describeRefusal,
+ REASON_ACTION,
+} from "./mcp-reason.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;
+/** How many search hits seed a reasoning spawn. */
+const REASON_SEED_HITS = 6;
export interface ServerDeps {
readonly ctx: VaultContext;
@@ -55,6 +70,13 @@ export interface ServerDeps {
readonly audit: (action: string, detail?: Record<string, unknown>) => void;
readonly reindex?: () => boolean;
readonly now?: () => Date;
+ /**
+ * Injectable for the same reason `reindex` and `now` are: without it, every
+ * `reason` outcome except the empty-question refusal needs a real spawn to
+ * reach, so the refusal paths — including "no answer, never a partial one",
+ * which is this tool's headline behaviour — could not be asserted at all.
+ */
+ readonly runReason?: typeof runReasoning;
}
const text = (s: string): { content: { type: "text"; text: string }[] } => ({
@@ -112,6 +134,7 @@ 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));
+ const runReason = deps.runReason ?? runReasoning;
// One cache per server, living exactly as long as the process that owns it.
const memoryIndex = createMemoryIndex(ctx.vaultRoot, ctx.memoryRoot);
@@ -379,6 +402,126 @@ export function createHandlers(deps: ServerDeps): Handlers {
].join("\n");
}
+ /**
+ * `reason` — seed from search, spawn, log, hand back the answer.
+ *
+ * A call with no question in it is the only one refused.
+ */
+ async function callReason(args: Record<string, unknown>): Promise<string> {
+ const question = String(args.question ?? "").trim();
+ if (!question) return describeRefusal("no question given.", "Ask the judgement you need, in full.");
+
+ // Nothing to reason over, and nothing coherent to say to a spawn about it:
+ // with no exposed roots the seed is always empty, so the prompt would tell
+ // it to go read the tree and not to read the tree at all, in the same
+ // breath. Refuse where the configuration is, not in the prompt.
+ if (policy.roots.length === 0) {
+ return describeRefusal(
+ "this vault exposes no folders, so there is nothing to reason over.",
+ "Declare mcp_exposed_roots in vault-manifest.json, or leave it unset to serve the vault's own user_content_roots. `health` reports what is currently exposed.",
+ );
+ }
+
+ const cfg = resolveReasonConfig(ctx.manifest);
+ // The spawn reads the vault with its own tools, so it is told the same
+ // boundary the seed was filtered through — all three of the policy's rules,
+ // since never-expose files and `private:` notes live INSIDE exposed roots.
+ // Without it the one tool that reads most is the one ignoring the config.
+ const scope = { roots: policy.roots, memoryRoot: ctx.memoryRoot, neverExpose: [...policy.neverExpose] };
+
+ // Seed with what the server already has, so the spawn does not spend turns
+ // rediscovering it.
+ const allowed = allowedSearchPaths(ctx.vaultRoot, policy);
+ const seed = await qmdSearch(qmd(), allowed, question, REASON_SEED_HITS);
+
+ // Written before the spawn, and a failure here is a refusal rather than a
+ // raw protocol error: without this file the spawn has no recursion guard,
+ // so it must not run. Its sibling `writeReasoningRecord` returns null on
+ // failure because losing provenance is survivable; losing this is not.
+ let mcpConfigPath: string;
+ try {
+ mcpConfigPath = writeIsolatedMcpConfig(ctx.vaultRoot);
+ } catch (e) {
+ return describeRefusal(
+ "the spawn could not be isolated, so it was not started.",
+ [
+ "Writing the empty MCP config failed, and without it the reasoning session",
+ "could call back into this server. Check that .claude/ is writable.",
+ "",
+ sanitize(e instanceof Error ? e.message : String(e)),
+ ].join("\n"),
+ );
+ }
+ // The PERMITTED count, not `total` — a search whose every hit was withheld
+ // has `total > 0` and nothing the spawn can see, and must take the
+ // read-the-vault-yourself branch rather than be handed an empty block.
+ const evidence = visibleHits(seed) > 0 ? seed.text : "";
+ const r = await runReason(
+ resolveClaudeCommand(),
+ ctx.vaultRoot,
+ cfg,
+ reasoningPrompt(question, evidence, scope),
+ mcpConfigPath,
+ );
+
+ audit(REASON_ACTION, reasonAuditDetail(question, cfg, r, scope));
+
+ if (r.error) {
+ // The evidence goes back here too. A spawn that never started is the case
+ // where the caller most needs something to work with, and the search has
+ // already been paid for either way.
+ return describeRefusal(
+ "the reasoning session could not start.",
+ [sanitize(r.error), "", "Set OM_CLAUDE_BIN if your Claude CLI is not on this server's PATH.", "", seed.text].join("\n"),
+ );
+ }
+
+ // A run can end without an answer — the timeout fires, the CLI errors, the
+ // session stops early. Reporting that as an answer is the one outcome worse
+ // than refusing, so it is named.
+ if (!r.ok || !r.answer.trim()) {
+ const why = `it ended early (${r.terminal}) after ${r.turns} turn(s).`;
+ return describeRefusal(
+ `no answer — ${why}`,
+ [
+ "Nothing partial is returned, because a truncated synthesis presented as a",
+ "complete one is worse than no answer. The evidence search already found is",
+ "below; a narrower question is usually the fix.",
+ "",
+ seed.text,
+ ].join("\n"),
+ );
+ }
+
+ // The model that ACTUALLY ran is always named. An answer's worth depends on
+ // which model produced it, and a pin can be silently ignored — that is the
+ // surprise this layer already got caught by once, so the reported value is
+ // the CLI's, never the one we asked for.
+ // `"unknown"`, not `""` — `interpretRun` never returns an empty modelUsed on
+ // a successful run, so testing for `""` never fired and every run whose JSON
+ // lacked `modelUsage` was reported as contradicting the pin when nothing
+ // was wrong.
+ const mismatch = cfg.model !== null && r.modelUsed !== "unknown" && !r.modelUsed.includes(cfg.model);
+ const record = writeReasoningRecord(ctx.vaultRoot, now(), question, r);
+
+ return [
+ // Returned as written. `sanitize` guards protocol ERRORS, where a raw
+ // path is noise; an answer is the user's own vault read by the user's own
+ // Claude, and redacting it would mangle legitimate content to defend
+ // against nobody. Egress belongs to the injected contract, not here.
+ r.answer.trim(),
+ "",
+ "---",
+ `Reasoned over the vault in ${r.turns} turn(s), ${(r.wallMs / 1000).toFixed(1)}s. Reported cost $${r.costUsd.toFixed(4)}.`,
+ mismatch
+ ? `⚠ Model: ${r.modelUsed} — NOT the pinned ${cfg.model}. Check reason.model in vault-manifest.json.`
+ : cfg.model === null
+ ? `Model: ${r.modelUsed} (your CLI default — pin reason.model to change it).`
+ : `Model: ${r.modelUsed} (pinned via reason.model).`,
+ ...(record ? [`Full record: ${record}`] : []),
+ ].join("\n");
+ }
+
function callHealth(): string {
const who = caller();
// Populate the cache before reporting on it. `recall` tells the user to run
@@ -414,6 +557,10 @@ export function createHandlers(deps: ServerDeps): Handlers {
`Parsed store: ${parsed} entr${parsed === 1 ? "y" : "ies"}${memoryIndex.stats.stale ? ` (${memoryIndex.stats.stale} served from an older parse — check permissions)` : ""}`,
`Exposed roots: ${policy.roots.join(", ") || "(none)"} [${policy.source}]`,
`Search index: ${ctx.qmdIndex ?? "(qmd default)"} · launcher ${ctx.qmdLauncher ? "found" : "NOT FOUND"}`,
+ // `reason` is the one tool that spawns a session, and nothing bounds it.
+ // Reporting the day's usage is what stands in for a limit: the answer to
+ // "where did that go" has to exist somewhere, and this is where.
+ `Reasoning today: ${reasonUsage(ctx.vaultRoot, ctx.manifest, now().toISOString().slice(0, 10), sumAuditField)}`,
"",
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")}`] : []),
@@ -457,6 +604,8 @@ export function createHandlers(deps: ServerDeps): Handlers {
return session.ok(id, text(callRemember(args)));
case "record_work":
return session.ok(id, text(callRecordWork(args)));
+ case "reason":
+ return session.ok(id, text(await callReason(args)));
case "health":
return session.ok(id, text(callHealth()));
default:
diff --git a/.claude/scripts/lib/mcp-tools.ts b/.claude/scripts/lib/mcp-tools.ts
index 33f7b8f..16b176b 100644
--- a/.claude/scripts/lib/mcp-tools.ts
+++ b/.claude/scripts/lib/mcp-tools.ts
@@ -233,6 +233,31 @@ export const TOOLS: readonly ToolDef[] = [
openWorldHint: false,
},
},
+ {
+ name: "reason",
+ description:
+ "Ask the vault a question that needs JUDGEMENT ACROSS several notes rather than retrieval of one — 'is what I am about to do consistent with what we decided', or 'these notes disagree, what did we actually conclude'. It reads the vault with a second Claude session, so it takes longer and uses more than the other tools: reach for it when search or recall returned the notes but not the answer, and use those instead when they would do. It seeds itself from search, so you do not need to search first.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ question: {
+ type: "string",
+ description:
+ "The judgement you need, stated in full. It is answered by a session that cannot see this conversation, so include what you are about to do and why it matters — a bare topic gets a summary rather than a verdict.",
+ },
+ },
+ required: ["question"],
+ },
+ annotations: {
+ title: "Reason over the vault (spawns a second session)",
+ readOnlyHint: true,
+ destructiveHint: false,
+ // Same question, different answer, different usage.
+ idempotentHint: false,
+ // It starts a process that reads the vault and calls a model.
+ openWorldHint: true,
+ },
+ },
{
name: "health",
description:
diff --git a/.claude/scripts/om-mcp.ts b/.claude/scripts/om-mcp.ts
index 4dd4af2..863b163 100644
--- a/.claude/scripts/om-mcp.ts
+++ b/.claude/scripts/om-mcp.ts
@@ -27,6 +27,7 @@ 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";
+import { killActiveReasoning } from "./lib/mcp-reason.ts";
const vaultRoot = resolveVaultRoot(import.meta.url);
const ctx = createContext(vaultRoot, derivedVaultRoot(import.meta.url));
@@ -86,6 +87,11 @@ createInterface({ input: process.stdin }).on("line", (line) => {
const shutdown = (): void => {
qmdClient?.dispose();
+ // A `reason` spawn is not detached and nothing else reaps it, while the only
+ // bound on its lifetime is a timer in THIS process. Exiting without this
+ // leaves a session running against the user's account that can never be
+ // recorded, because the audit line follows an await that will never return.
+ killActiveReasoning();
process.exit(0);
};
process.on("SIGTERM", shutdown);
diff --git a/.claude/scripts/tests/mcp-caller.test.ts b/.claude/scripts/tests/mcp-caller.test.ts
index 9c0e493..b95999e 100644
--- a/.claude/scripts/tests/mcp-caller.test.ts
+++ b/.claude/scripts/tests/mcp-caller.test.ts
@@ -12,7 +12,7 @@
import { test, describe } from "node:test";
import assert from "node:assert/strict";
-import { mkdtempSync, rmSync, readFileSync, existsSync, writeFileSync } from "node:fs";
+import { mkdtempSync, rmSync, readFileSync, existsSync, writeFileSync, mkdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, dirname, basename } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
@@ -27,6 +27,7 @@ import {
sanitize,
createAuditor,
auditPath,
+ sumAuditField,
type Root,
} from "../lib/mcp-caller.ts";
@@ -349,3 +350,92 @@ describe("the audit log", () => {
});
});
});
+
+// ---------------------------------------------------------------------------
+// Reading the log back — lives here so it cannot drift from the writer
+// ---------------------------------------------------------------------------
+
+describe("summing a field across one day's entries", () => {
+ function withVault(fn: (root: string) => void): void {
+ const dir = mkdtempSync(join(tmpdir(), "auditsum-"));
+ try {
+ fn(dir);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+
+ const entry = (o: Record<string, unknown>) => JSON.stringify(o);
+ const write = (path: string, lines: string[]) => {
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, lines.join("\n") + "\n", "utf8");
+ };
+
+ test("counts only the named action, on the named day", () => {
+ withVault((root) => {
+ write(auditPath(root), [
+ entry({ action: "reason", at: "2026-07-27T01:00:00Z", cost_usd: 0.1 }),
+ entry({ action: "reason", at: "2026-07-27T02:00:00Z", cost_usd: 0.25 }),
+ entry({ action: "reason", at: "2026-07-26T23:00:00Z", cost_usd: 99 }), // yesterday
+ entry({ action: "search", at: "2026-07-27T03:00:00Z", cost_usd: 99 }), // another action
+ entry({ action: "recall", at: "2026-07-27T04:00:00Z" }), // no such field
+ ]);
+ assert.equal(Number(sumAuditField(root, "reason", "2026-07-27", "cost_usd").total.toFixed(4)), 0.35);
+ });
+ });
+
+ test("reads the ROTATED generation too, not just the live log", () => {
+ // createAuditor renames the log to .jsonl.1 once it crosses AUDIT_MAX_BYTES.
+ // A reader that knows only the live path reports zero for a day that did
+ // spend — indistinguishable from "nothing ran", which is the one thing this
+ // figure exists to tell apart.
+ withVault((root) => {
+ write(`${auditPath(root)}.1`, [entry({ action: "reason", at: "2026-07-27T01:00:00Z", cost_usd: 0.5 })]);
+ write(auditPath(root), [entry({ action: "reason", at: "2026-07-27T09:00:00Z", cost_usd: 0.25 })]);
+ assert.equal(Number(sumAuditField(root, "reason", "2026-07-27", "cost_usd").total.toFixed(4)), 0.75);
+ });
+ });
+
+ test("a missing log is zero, not a crash", () => {
+ withVault((root) => assert.equal(sumAuditField(root, "reason", "2026-07-27", "cost_usd").total, 0));
+ });
+
+ test("a torn or hand-edited line is skipped, never fatal", () => {
+ // Read for reporting only, so a corrupt line may under-report — but it must
+ // never throw and take `health` down with it.
+ withVault((root) => {
+ write(auditPath(root), [
+ entry({ action: "reason", at: "2026-07-27T01:00:00Z", cost_usd: 0.1 }),
+ '{"action":"reason","at":"2026-07-27T02:00:00Z","cost_usd":', // truncated
+ "",
+ "not json at all",
+ entry({ action: "reason", at: "2026-07-27T03:00:00Z", cost_usd: "free" }), // wrong type
+ entry({ action: "reason", at: "2026-07-27T04:00:00Z", cost_usd: 0.2 }),
+ ]);
+ assert.equal(Number(sumAuditField(root, "reason", "2026-07-27", "cost_usd").total.toFixed(4)), 0.3);
+ });
+ });
+
+ test("an entry that merely MENTIONS the action is not counted as one", () => {
+ // The line is prefiltered on the action's name before parsing, for speed.
+ // The parse still has to be what decides.
+ withVault((root) => {
+ write(auditPath(root), [
+ entry({ action: "search", at: "2026-07-27T01:00:00Z", query: "why reason is slow", cost_usd: 99 }),
+ entry({ action: "reason", at: "2026-07-27T02:00:00Z", cost_usd: 0.4 }),
+ ]);
+ assert.equal(Number(sumAuditField(root, "reason", "2026-07-27", "cost_usd").total.toFixed(4)), 0.4);
+ });
+ });
+
+ test("what the auditor actually writes is what this reads", () => {
+ // The end-to-end guard: stamp through createAuditor, read through
+ // sumAuditField. Nothing hand-rolls the entry shape on either side.
+ withVault((root) => {
+ const audit = createAuditor(auditPath(root), () => "atlas", () => "2026-07-27T05:00:00Z");
+ audit("reason", { cost_usd: 0.6 });
+ audit("search", { cost_usd: 5 });
+ assert.equal(Number(sumAuditField(root, "reason", "2026-07-27", "cost_usd").total.toFixed(4)), 0.6);
+ });
+ });
+});
diff --git a/.claude/scripts/tests/mcp-reason.concurrency.test.ts b/.claude/scripts/tests/mcp-reason.concurrency.test.ts
new file mode 100644
index 0000000..65e7eec
--- /dev/null
+++ b/.claude/scripts/tests/mcp-reason.concurrency.test.ts
@@ -0,0 +1,149 @@
+/**
+ * Cross-process safety for the two files a `reason` call writes.
+ *
+ * Separate from the other reason tests for the reason `memory-write.concurrency`
+ * is separate: the defects here CANNOT reproduce in-process. Node runs the
+ * synchronous fs calls to completion, so a single-threaded test serialises them
+ * and always passes — which is exactly how both of these survived a full
+ * `/simplify` round.
+ *
+ * They became reachable when the spawn went async. While `runReasoning` used
+ * `spawnSync` the whole event loop was held for the child's lifetime, so two
+ * `reason` calls could never overlap and neither race existed. Making the server
+ * responsive during a spawn — the right fix — opened both windows. The
+ * deployment shape widens them further: one server process PER CONSUMING REPO,
+ * all writing into one vault.
+ *
+ * 1. THE RECORD. Named from a millisecond-precision ISO stamp, which reads as
+ * collision-proof and is not. Under a plain write the loser silently
+ * overwrote the winner while both reported success — the same shape that made
+ * six processes produce four memories.
+ *
+ * 2. THE ISOLATED MCP CONFIG. A FIXED path rewritten on every call. A plain
+ * write truncates first, so a concurrent call can empty the file while
+ * another spawn's child is reading it — and what that child is reading is the
+ * recursion guard, the only thing stopping a spawn tree that multiplies at
+ * every level.
+ */
+
+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", "mcp-reason.ts");
+const LIB_URL = JSON.stringify(pathToFileURL(LIB).href);
+const WRITERS = 8;
+
+/** Run N scripts concurrently — all started before any is awaited. */
+function runAll(script: string, argsFor: (i: number) => string[], n: number): Promise<string[]> {
+ return Promise.all(
+ Array.from(
+ { length: n },
+ (_, i) =>
+ new Promise<string>((res, rej) => {
+ execFile(
+ process.execPath,
+ ["--disable-warning=ExperimentalWarning", "--experimental-strip-types", script, ...argsFor(i)],
+ { encoding: "utf8" },
+ (err, stdout, stderr) => (err ? rej(new Error(String(stderr || err.message))) : res(stdout.trim())),
+ );
+ }),
+ ),
+ );
+}
+
+function withDir(fn: (dir: string) => Promise<void>): Promise<void> {
+ const dir = mkdtempSync(join(tmpdir(), "reason-conc-"));
+ return fn(dir).finally(() =>
+ // `maxRetries` is not optional on Windows here: these tests create and
+ // rename hundreds of files across eight processes, and the directory stays
+ // briefly busy after the last child exits — cleanup then throws ENOTEMPTY
+ // and fails a test whose assertions already passed. Observed on this
+ // suite; CI runs a Windows job, so without it the test is flaky there and
+ // green everywhere else, which is the worst kind of red.
+ rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }),
+ );
+}
+
+// Every process writes a record stamped at the SAME instant, which is what two
+// runs completing in the same millisecond produce.
+const RECORD_WRITER = `
+import { writeReasoningRecord } from ${LIB_URL};
+const [vault, tag] = process.argv.slice(2);
+const rel = writeReasoningRecord(vault, new Date("2026-07-27T10:00:00.123Z"), "question " + tag, {
+ ok: true, answer: "ANSWER-" + tag, costUsd: 0.1, turns: 3,
+ modelUsed: "m", terminal: "completed", wallMs: 1, error: null,
+});
+if (!rel) { console.error("no path returned"); process.exit(2); }
+process.stdout.write(rel);
+`;
+
+// Half rewrite the config in a tight loop, half read it back and parse. A reader
+// that ever sees a partial file fails loudly rather than silently.
+const CONFIG_CHURN = `
+import { readFileSync } from "node:fs";
+import { writeIsolatedMcpConfig, writeIsolatedMcpConfigPath } from ${LIB_URL};
+const [vault, role] = process.argv.slice(2);
+const path = writeIsolatedMcpConfigPath(vault);
+let torn = 0;
+for (let i = 0; i < 400; i++) {
+ if (role === "writer") {
+ writeIsolatedMcpConfig(vault);
+ } else {
+ try {
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
+ if (!parsed || typeof parsed.mcpServers !== "object") torn++;
+ } catch {
+ // ENOENT is fine only before the first write lands; an unparseable body
+ // never is — that is the truncate window.
+ torn++;
+ }
+ }
+}
+process.stdout.write(String(torn));
+`;
+
+describe("concurrent reason calls, from separate processes", () => {
+ test("records stamped at the same instant all survive — none is clobbered", async () => {
+ await withDir(async (dir) => {
+ const script = join(dir, "record-writer.mjs");
+ writeFileSync(script, RECORD_WRITER, "utf8");
+
+ const paths = await runAll(script, (i) => [dir, `p${i}`], WRITERS);
+
+ assert.equal(paths.length, WRITERS, "every writer must report a path");
+ assert.equal(new Set(paths).size, WRITERS, `paths must be distinct, got ${new Set(paths).size}`);
+
+ const onDisk = readdirSync(join(dir, ".claude", "om-reasoning")).filter((f) => f.endsWith(".md"));
+ assert.equal(
+ onDisk.length,
+ WRITERS,
+ `every reported record must exist — ${onDisk.length} files for ${WRITERS} successes means transcripts were lost`,
+ );
+
+ const leftovers = readdirSync(join(dir, ".claude", "om-reasoning")).filter((f) => f.endsWith(".tmp"));
+ assert.deepEqual(leftovers, [], "no half-written record may be left behind");
+ });
+ });
+
+ test("the recursion guard's config is never readable half-written", async () => {
+ await withDir(async (dir) => {
+ const script = join(dir, "config-churn.mjs");
+ mkdirSync(join(dir, ".claude"), { recursive: true });
+ writeFileSync(script, CONFIG_CHURN, "utf8");
+ // Seed it so a reader starting first does not count a legitimate ENOENT.
+ await runAll(script, () => [dir, "writer"], 1);
+
+ const torn = await runAll(script, (i) => [dir, i % 2 === 0 ? "writer" : "reader"], WRITERS);
+ const total = torn.reduce((a, s) => a + Number(s), 0);
+ assert.equal(total, 0, `a spawn read a truncated or missing recursion guard ${total} time(s)`);
+
+ const strays = readdirSync(join(dir, ".claude")).filter((f) => f.includes(".tmp"));
+ assert.deepEqual(strays, [], "temp files must not accumulate beside the config");
+ });
+ });
+});
diff --git a/.claude/scripts/tests/mcp-reason.test.ts b/.claude/scripts/tests/mcp-reason.test.ts
new file mode 100644
index 0000000..754c785
--- /dev/null
+++ b/.claude/scripts/tests/mcp-reason.test.ts
@@ -0,0 +1,588 @@
+/**
+ * `reason` — the pure parts: config, prompt, argv, refusals, records.
+ *
+ * Nothing here spawns. Splitting the decisions out from the spawn is what lets
+ * every one of them be driven by a test without starting a session to check it.
+ *
+ * The CLI facts pinned below were measured against the real binary first, and
+ * every one of them contradicted the obvious guess:
+ * - `--max-turns` does not exist
+ * - `--model haiku` silently runs sonnet, so an alias is dropped, not passed
+ * - `--permission-mode plan` writes outside the vault AND rewrites the task as
+ * "produce a plan", losing the answer — so the toolset is restricted instead
+ * - an empty seed reads as evidence of absence unless the prompt says not to
+ * - an early end returns an EMPTY result, so there is nothing to mistake for
+ * an answer
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, readdirSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, dirname } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import {
+ resolveReasonConfig,
+ reasonUsage,
+ reasonAuditDetail,
+ reasoningArgs,
+ reasoningPrompt,
+ hasEvidence,
+ visibleHits,
+ interpretRun,
+ renderReasoningRecord,
+ resolveClaudeCommand,
+ writeIsolatedMcpConfig,
+ writeIsolatedMcpConfigPath,
+ writeReasoningRecord,
+ describeRefusal,
+ REASON_ACTION,
+ REASONING_DIR,
+ type ReasoningResult,
+} from "../lib/mcp-reason.ts";
+
+function withDir(fn: (dir: string) => void): void {
+ const dir = mkdtempSync(join(tmpdir(), "reason-"));
+ try {
+ fn(dir);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+/** A completed run. Tests override only the field they are about. */
+const result = (over: Partial<ReasoningResult> = {}): ReasoningResult => ({
+ ok: true,
+ answer: "the answer",
+ costUsd: 0.12,
+ turns: 5,
+ modelUsed: "claude-haiku-4-5",
+ terminal: "completed",
+ wallMs: 21_000,
+ error: null,
+ ...over,
+});
+
+// ---------------------------------------------------------------------------
+// Config
+// ---------------------------------------------------------------------------
+
+describe("resolving the reason config", () => {
+ test("the config surface is exactly one key: model", () => {
+ assert.deepEqual(Object.keys(resolveReasonConfig({})), ["model"]);
+ // Unknown keys are inert rather than honoured — a manifest that asks for
+ // something this tool does not have gets the same config as one that does
+ // not ask. Pinned so the surface cannot quietly grow back.
+ const c = resolveReasonConfig({
+ reason: { max_usd_per_call: 0.05, max_usd_per_day: 0.05, enabled: false, timeout_ms: 5 },
+ }) as unknown as Record<string, unknown>;
+ assert.deepEqual(Object.keys(c), ["model"]);
+ });
+
+ test("no model is pinned by default, so the spawn follows the CLI", () => {
+ // MCP does not tell a server what model the CALLER is using, so inheriting
+ // the user's own CLI default is the closest reachable thing to "the same
+ // model I am already working at".
+ assert.equal(resolveReasonConfig({}).model, null);
+ // And the argv agrees — the default is one fact, not a constant that a
+ // second code path could disagree with.
+ assert.ok(!reasoningArgs(resolveReasonConfig({}), "q", "c.json").includes("--model"));
+ });
+
+ test("a model ALIAS falls back to inheriting, never to a hardcoded id", () => {
+ // Measured: `--model haiku` is not honoured and does not error — it runs
+ // claude-sonnet-5. A pin that silently means something else is worse than
+ // no pin, so an alias is dropped rather than passed on.
+ for (const alias of ["haiku", "sonnet", "opus", "", " "]) {
+ assert.equal(resolveReasonConfig({ reason: { model: alias } }).model, null, alias);
+ }
+ });
+
+ test("a full model id is honoured when a vault deliberately pins one", () => {
+ assert.equal(resolveReasonConfig({ reason: { model: "claude-opus-4-6" } }).model, "claude-opus-4-6");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// The daily ledger
+// ---------------------------------------------------------------------------
+
+describe("the daily usage line health reports", () => {
+ // The sum itself is `sumAuditField`'s job and is tested against the writer in
+ // mcp-caller.test.ts, including rotation. Here: the line this tool composes
+ // from it, with the read injected so no log is needed.
+ const spend = (total: number, complete = true) => () => ({ total, complete });
+
+ test("names the model a call would actually use", () => {
+ assert.match(reasonUsage("/v", {}, "2026-07-27", spend(0)), /model: your CLI default/);
+ assert.match(
+ reasonUsage("/v", { reason: { model: "claude-opus-4-6" } }, "2026-07-27", spend(0)),
+ /model: claude-opus-4-6/,
+ );
+ });
+
+ test("says so explicitly when nothing has run, rather than reporting $0", () => {
+ // An absent or zeroed line reads as "not tracked", and this line is the
+ // whole of the answer to where usage went.
+ assert.match(reasonUsage("/v", {}, "2026-07-27", spend(0)), /nothing yet today/);
+ });
+
+ test("reports the day's total when there is one", () => {
+ assert.match(reasonUsage("/v", {}, "2026-07-27", spend(0.3512)), /\$0\.3512 reported/);
+ });
+
+ test("says AT LEAST when the log was too large to read whole", () => {
+ // A silently-low figure is the failure to avoid: this line is the entire
+ // answer to where usage went, and it degrades exactly on the busiest days,
+ // so it has to admit being a floor rather than present one as a total.
+ assert.match(reasonUsage("/v", {}, "2026-07-27", spend(0.5, false)), /at least \$0\.5000/);
+ // And a truncated read with nothing found is not the same as "nothing ran".
+ assert.match(reasonUsage("/v", {}, "2026-07-27", spend(0, false)), /readable tail/);
+ });
+
+ test("asks the log for this tool's own action key", () => {
+ // The stamp and the read must move together; a rename on one side only
+ // makes the figure read zero forever, which looks like "no calls today".
+ let askedFor = "";
+ reasonUsage("/v", {}, "2026-07-27", (_root, action, _day, field) => {
+ askedFor = `${action}/${field}`;
+ return { total: 0, complete: true };
+ });
+ assert.equal(askedFor, `${REASON_ACTION}/cost_usd`);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// The audit detail — written here, read here
+// ---------------------------------------------------------------------------
+
+describe("the audit detail for a run", () => {
+ test("records what the spawn was TOLD it could read", () => {
+ // The boundary is observed by the spawn, not enforced by the filesystem,
+ // so the log is the only place it stays answerable afterwards.
+ const d = reasonAuditDetail("q", resolveReasonConfig({}), result(), {
+ roots: ["brain", "reference"],
+ memoryRoot: "memories",
+ neverExpose: [],
+ });
+ assert.equal(d.roots, "brain,reference");
+ });
+
+ test("a very long question is truncated in the LOG, not refused", () => {
+ // One entry bigger than the log's read window leaves nothing parseable in
+ // it, and the day's usage then reports a confident zero. What may be ASKED
+ // is not capped — only what is written beside every other call's record.
+ const d = reasonAuditDetail("x".repeat(50_000), resolveReasonConfig({}), result(), undefined);
+ assert.ok(String(d.question).length < 4000, `audit line kept ${String(d.question).length} chars`);
+ assert.match(String(d.question), /…$/);
+ });
+
+ test("says vault-wide when no boundary was given, rather than omitting it", () => {
+ const d = reasonAuditDetail("q", resolveReasonConfig({}), result(), undefined);
+ assert.equal(d.roots, "vault-wide");
+ });
+
+ test("separates the model asked for from the model that ran", () => {
+ const d = reasonAuditDetail("q", resolveReasonConfig({ reason: { model: "claude-opus-4-6" } }), result(), undefined);
+ assert.equal(d.model_asked, "claude-opus-4-6");
+ assert.equal(d.model_used, "claude-haiku-4-5");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// The spawn's argv — asserted without spawning
+// ---------------------------------------------------------------------------
+
+describe("the spawn arguments", () => {
+ const cfg = resolveReasonConfig({});
+ const args = reasoningArgs(cfg, "the question", "C:/v/.claude/om-reasoning/no-mcp.json");
+ const valueAfter = (flag: string) => args[args.indexOf(flag) + 1];
+
+ test("the argv is exactly these flags", () => {
+ // Pinned as a whole set rather than flag by flag, so anything added here has
+ // to be added here deliberately and read by a human first.
+ assert.deepEqual(args.filter((a) => a.startsWith("--")), [
+ "--output-format",
+ "--strict-mcp-config",
+ "--mcp-config",
+ "--tools",
+ ]);
+ });
+
+ test("the recursion guard is present and complete", () => {
+ // --strict-mcp-config alone is not enough; it needs the empty config to
+ // point at, or the spawn keeps the ambient servers — including this one.
+ assert.ok(args.includes("--strict-mcp-config"));
+ assert.match(String(valueAfter("--mcp-config")), /no-mcp\.json$/);
+ });
+
+ test("the spawn is read-only and machine-readable", () => {
+ // `--tools` restricts the built-in set itself, so a write comes back as
+ // "No such tool available" rather than as a prompt nothing can answer.
+ const tools = String(valueAfter("--tools")).split(",");
+ assert.deepEqual(tools, ["Read", "Grep", "Glob"]);
+ for (const w of ["Write", "Edit", "NotebookEdit", "Bash"]) {
+ assert.ok(!tools.includes(w), `${w} must not be reachable from a reasoning pass`);
+ }
+ assert.equal(valueAfter("--output-format"), "json");
+ });
+
+ test("plan mode is never used, for two separate reasons", () => {
+ // It writes the plan to ~/.claude/plans/ — outside the vault, so it is not
+ // read-only — and it reframes the task as producing a plan for approval.
+ // Measured: the spawn composed its analysis as a plan, could not hand it
+ // back without ExitPlanMode, and returned a note about that instead of the
+ // answer. Non-deterministic, so a passing run proves nothing; the flag goes.
+ assert.ok(!args.includes("--permission-mode"), "no permission mode is set at all");
+ assert.ok(!args.includes("plan"));
+ });
+
+ test("no --model flag at all unless the vault pinned one", () => {
+ assert.ok(!args.includes("--model"), "an unpinned vault inherits the user's CLI default");
+ });
+
+ test("a pinned model reaches the spawn as a full id", () => {
+ const pinned = reasoningArgs(
+ resolveReasonConfig({ reason: { model: "claude-opus-4-6" } }),
+ "q",
+ "c.json",
+ );
+ assert.equal(pinned[pinned.indexOf("--model") + 1], "claude-opus-4-6");
+ });
+});
+
+describe("the prompt", () => {
+ const p = reasoningPrompt("why did we choose X", "PASSAGE-ONE\nPASSAGE-TWO");
+
+ test("carries the question and the seeded evidence", () => {
+ assert.match(p, /why did we choose X/);
+ assert.match(p, /PASSAGE-ONE/);
+ assert.match(p, /<evidence>/);
+ });
+
+
+ test("licenses the spawn to go beyond the seed", () => {
+ // Measured: a seeded run leaned on its passages and repeated a framing the
+ // vault had since corrected. Seeding saves about a turn and costs some
+ // independence, so the instruction has to push back.
+ assert.match(p, /starting point/i);
+ assert.match(p, /read further/i);
+ });
+
+ test("asks for the vault's own epistemic markers to survive", () => {
+ assert.match(p, /TBC/);
+ assert.match(p, /inferred/);
+ });
+
+ test("an EMPTY seed is not presented as evidence of absence", () => {
+ // Caught in a live run: handed an empty seed, the spawn answered "there are
+ // no prior decisions recorded" about a question the vault answered in a note
+ // one directory away. The index was simply not built. That is this layer's
+ // signature failure — nothing found reading as nothing there — so the empty
+ // case must tell the spawn to go and look.
+ for (const empty of ["", " ", "(no results)", "search failed: qmd unavailable", "(search unavailable: results could not be scope-checked)"]) {
+ const q = reasoningPrompt("did we decide about caching", empty);
+ assert.match(q, /NOT evidence that the vault is silent/i, JSON.stringify(empty));
+ assert.match(q, /read it directly/i, JSON.stringify(empty));
+ assert.ok(!q.includes("<evidence>"), "an empty evidence block invites the wrong inference");
+ assert.match(q, /say how you looked/i, JSON.stringify(empty));
+ }
+ });
+
+ test("only qmd's own failure prose reads as an empty seed", () => {
+ // The sentinels are PREFIXES. A retrieved passage that happens to quote one
+ // of those phrases is still evidence, and must not flip the branch.
+ assert.ok(hasEvidence("[1] brain/Search.md — logs 'no results' when the index is cold"));
+ assert.ok(!hasEvidence("(no results visible to this repo; 3 match(es) withheld as out of scope)"));
+ });
+
+ test("the permitted count decides, not what qmd returned before filtering", () => {
+ // `total` counts hits BEFORE the exposure policy filtered them, so a search
+ // whose every hit was withheld has total > 0 and nothing the spawn can see.
+ // Reading `total` alone would hand it an empty evidence block — the exact
+ // shape that produced the false-absence answer above.
+ assert.equal(visibleHits({ total: 5, withheld: 5 }), 0);
+ assert.equal(visibleHits({ total: 5, withheld: 2 }), 3);
+ assert.equal(visibleHits({ total: 0, withheld: 0 }), 0);
+ });
+});
+
+describe("the read boundary in the prompt", () => {
+ const scope = { roots: ["brain", "reference"], memoryRoot: "memories", neverExpose: [] };
+
+ test("names the exposed roots as a prohibition, not a suggestion", () => {
+ // `--tools Read,Grep,Glob` with cwd at the vault root gives the spawn the
+ // whole tree, while its seed came through the exposure policy. A prohibition
+ // is the form measured to propagate into a session; a positive "consult X"
+ // is advisory and gets skipped whenever something nearer answers.
+ const p = reasoningPrompt("q", "PASSAGE", scope);
+ assert.match(p, /Read ONLY within these folders: brain, reference/);
+ assert.match(p, /Do not read anything/i);
+ });
+
+ test("keeps the memory root and .claude out, whatever the roots say", () => {
+ // A spawn reading memories/ directly sees every caller's, not its own —
+ // and "memories are never served as an ordinary note" holds regardless of
+ // configuration everywhere else in this layer. `.claude/` holds the audit
+ // log, which is every caller's query text.
+ const p = reasoningPrompt("q", "PASSAGE", scope);
+ assert.match(p, /Never read memories\//);
+ assert.match(p, /\.claude\//);
+ });
+
+ test("states ALL THREE of the policy's rules, not just the folders", () => {
+ // never-expose filenames and `private:` notes live INSIDE exposed roots, so
+ // a boundary naming only folders grants exactly the files the other two
+ // rules exist to withhold. Demonstrated: with roots ["brain"], a spawn was
+ // permitted brain/SOUL.md (never-expose) and a private-tagged note.
+ const p = reasoningPrompt("q", "PASSAGE", {
+ roots: ["brain"],
+ memoryRoot: "memories",
+ neverExpose: ["SOUL.md", "Memories.md"],
+ });
+ assert.match(p, /Never read any file named: SOUL\.md, Memories\.md/);
+ assert.match(p, /private/i);
+ });
+
+ test("applies to the unseeded branch too", () => {
+ // The empty-seed branch tells the spawn to go read the tree itself, so it is
+ // the branch where an unbounded read is most likely.
+ const p = reasoningPrompt("q", "", scope);
+ assert.match(p, /Read ONLY within these folders/);
+ assert.match(p, /read it directly/i);
+ });
+
+ test("no scope means no fabricated boundary", () => {
+ assert.ok(!reasoningPrompt("q", "PASSAGE").includes("Read ONLY"));
+ });
+
+ test("empty roots DENY rather than permit", () => {
+ // `resolveExposure` strips the memory root from whatever was declared, so a
+ // vault exposing only its memories resolves to an empty list. An empty list
+ // that produced no prohibition would hand the spawn the run of the vault at
+ // exactly the moment the config said to serve almost none of it.
+ const p = reasoningPrompt("q", "PASSAGE", { roots: [], memoryRoot: "memories", neverExpose: [] });
+ assert.match(p, /Do not read the note tree at all/);
+ assert.match(p, /Never read memories\//);
+ });
+});
+
+
+// ---------------------------------------------------------------------------
+// Reading a finished run — the half that used to be unreachable
+// ---------------------------------------------------------------------------
+
+describe("interpreting a finished run", () => {
+ const json = (o: Record<string, unknown>) => JSON.stringify(o);
+
+ test("a completed run carries its answer and telemetry", () => {
+ const r = interpretRun(
+ json({
+ result: "because of X",
+ num_turns: 4,
+ total_cost_usd: 0.42,
+ terminal_reason: "completed",
+ modelUsage: { "claude-opus-5": {} },
+ }),
+ "",
+ null,
+ 16_000,
+ );
+ assert.equal(r.ok, true);
+ assert.equal(r.answer, "because of X");
+ assert.equal(r.turns, 4);
+ assert.equal(r.costUsd, 0.42);
+ assert.equal(r.modelUsed, "claude-opus-5");
+ assert.equal(r.wallMs, 16_000);
+ assert.equal(r.error, null);
+ });
+
+ test("is_error is NOT ok, even with a result string present", () => {
+ // This is the flag gating the "no answer, refused by name" path. A run that
+ // stopped early must never be handed back as a complete answer.
+ const r = interpretRun(json({ is_error: true, result: "partial…", terminal_reason: "budget_exhausted" }), "", null, 5);
+ assert.equal(r.ok, false);
+ assert.equal(r.terminal, "budget_exhausted");
+ });
+
+ test("a non-JSON body reports whatever the CLI printed", () => {
+ const r = interpretRun("Usage: claude [options]", "", null, 5);
+ assert.equal(r.ok, false);
+ assert.equal(r.terminal, "spawn_failed");
+ assert.match(String(r.error), /Usage: claude/);
+ });
+
+ test("stderr is used when stdout is empty", () => {
+ const r = interpretRun("", "command not found", null, 5);
+ assert.match(String(r.error), /command not found/);
+ });
+
+ test("a spawn error outranks the output, because it explains it", () => {
+ const r = interpretRun("", "", "spawn claude ENOENT", 5);
+ assert.match(String(r.error), /ENOENT/);
+ });
+
+ test("a spawn error still wins when the body happens to parse", () => {
+ const r = interpretRun(json({ result: "x" }), "", "spawn claude ENOENT", 5);
+ assert.equal(r.ok, false);
+ assert.match(String(r.error), /ENOENT/);
+ });
+
+ test("silence reports as silence rather than as an empty answer", () => {
+ assert.match(String(interpretRun("", "", null, 5).error), /no output/);
+ });
+
+ test("missing telemetry fields degrade to zero, never to NaN", () => {
+ const r = interpretRun(json({ result: "x" }), "", null, 5);
+ assert.equal(r.costUsd, 0);
+ assert.equal(r.turns, 0);
+ assert.equal(r.modelUsed, "unknown");
+ assert.equal(r.terminal, "unknown");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Isolation and provenance
+// ---------------------------------------------------------------------------
+
+describe("isolation and provenance", () => {
+ test("the isolated MCP config declares no servers at all", () => {
+ withDir((dir) => {
+ const p = writeIsolatedMcpConfig(dir);
+ assert.deepEqual(JSON.parse(readFileSync(p, "utf8")), { mcpServers: {} });
+ });
+ });
+
+ test("the isolated config is plumbing, kept out of the provenance directory", () => {
+ // REASONING_DIR is user-facing — every answer names a record inside it — and
+ // is otherwise a homogeneous set of timestamped transcripts. A config file
+ // in there means any future list-or-prune needs a filename exception.
+ withDir((dir) => {
+ assert.ok(!writeIsolatedMcpConfig(dir).includes("om-reasoning"));
+ });
+ });
+
+ test("the CLI can be pointed somewhere else, and the override wins", () => {
+ // A CLI that is not on this process's PATH has no other way to be found.
+ assert.deepEqual(resolveClaudeCommand({ OM_CLAUDE_BIN: "/opt/claude/bin/claude" }), {
+ cmd: "/opt/claude/bin/claude",
+ leading: [],
+ });
+ assert.deepEqual(resolveClaudeCommand({ OM_CLAUDE_BIN: " " }), resolveClaudeCommand({}));
+ });
+
+ test("without an override it is spawnable without a shell", () => {
+ // Either the npm entry through this Node binary, or the bare name for a
+ // native install. Never a shell: the prompt is a JSON-bearing argument and
+ // cmd.exe strips its quotes.
+ const c = resolveClaudeCommand({});
+ assert.ok(c.cmd === "claude" || c.cmd === process.execPath, c.cmd);
+ // When it resolved the npm entry, that entry is the first argument.
+ assert.equal(c.leading.length, c.cmd === process.execPath ? 1 : 0);
+ });
+
+ test("the record's text is assertable without touching disk", () => {
+ // A spawned conclusion is reasoning, not verified knowledge. Recording it
+ // as anything else is how a store fills with claims nobody checked.
+ const md = renderReasoningRecord(new Date("2026-07-27T01:02:03Z"), "the question", result());
+ assert.match(md, /confidence: inferred/);
+ assert.match(md, /source: mcp-reason/);
+ assert.match(md, /cost_usd: 0\.12/);
+ assert.match(md, /date: 2026-07-27T01:02:03/);
+ assert.match(md, /the question/);
+ assert.match(md, /the answer/);
+ });
+
+ test("a record is written outside the vault's note tree", () => {
+ withDir((dir) => {
+ const rel = writeReasoningRecord(dir, new Date("2026-07-27T01:02:03Z"), "the question", result());
+ assert.ok(rel, "a record path is returned");
+ assert.ok(rel!.startsWith(REASONING_DIR), "kept beside the audit log, not filed as a note");
+ assert.match(readFileSync(join(dir, rel!), "utf8"), /confidence: inferred/);
+ });
+ });
+
+ test("losing the record does not lose the answer", () => {
+ // The transcript is provenance, not the result.
+ assert.equal(writeReasoningRecord("\0 not a path", new Date(), "q", result()), null);
+ });
+
+ test("two records stamped at the same instant BOTH survive", () => {
+ // The stamp is millisecond-precision and reads as collision-proof, but
+ // calls overlap now that the spawn is async, and one vault can have a
+ // server per consuming repo. Under a plain write the loser silently
+ // overwrote the winner while both reported success — the same shape that
+ // made six processes produce four files in the memory layer.
+ withDir((dir) => {
+ const t = new Date("2026-07-27T10:00:00.123Z");
+ const a = writeReasoningRecord(dir, t, "question A", result({ answer: "ANSWER-A" }));
+ const b = writeReasoningRecord(dir, t, "question B", result({ answer: "ANSWER-B" }));
+ assert.ok(a && b, "both calls report a path");
+ assert.notEqual(a, b, "and the paths differ");
+ const bodies = readdirSync(join(dir, REASONING_DIR))
+ .filter((f) => f.endsWith(".md"))
+ .map((f) => readFileSync(join(dir, REASONING_DIR, f), "utf8"));
+ assert.equal(bodies.length, 2, "no answer was overwritten");
+ assert.ok(bodies.some((s) => s.includes("ANSWER-A")));
+ assert.ok(bodies.some((s) => s.includes("ANSWER-B")));
+ });
+ });
+
+ test("the isolated config is never observable half-written", () => {
+ // A plain write truncates first. With overlapping calls, one call's
+ // truncate can land while another call's child is reading this exact path
+ // — and what it would read is the recursion guard. Rewritten many times
+ // here; the file must parse as a complete config after every one.
+ withDir((dir) => {
+ for (let i = 0; i < 25; i++) {
+ const p = writeIsolatedMcpConfig(dir);
+ assert.deepEqual(JSON.parse(readFileSync(p, "utf8")), { mcpServers: {} }, `rewrite ${i}`);
+ }
+ // And no temp files are left behind beside it.
+ const strays = readdirSync(join(dir, ".claude")).filter((f) => f.includes(".tmp"));
+ assert.deepEqual(strays, [], "temp files must not accumulate");
+ });
+ });
+
+ test("the record directory is not inside the note tree", () => {
+ // It must not be walked by visibleFiles, indexed, or served as a resource:
+ // dot-directories are skipped by every read surface.
+ assert.ok(REASONING_DIR.startsWith("."), REASONING_DIR);
+ });
+
+ test("both artefacts are actually gitignored, and the two places agree", () => {
+ // Two sources of truth per path: the code decides where the file goes,
+ // .gitignore decides whether it is tracked. Move one without the other and
+ // a machine config, or a transcript of the user's own questions and the
+ // answers to them, starts appearing in commits.
+ const repoRoot = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
+ const ignored = readFileSync(join(repoRoot, ".gitignore"), "utf8")
+ .split(/\r?\n/)
+ .map((l) => l.trim());
+ const rel = (abs: string) => abs.slice("/v/".length).split(/[\\/]/).join("/");
+
+ assert.ok(ignored.includes(`${REASONING_DIR}/`), `.gitignore must contain "${REASONING_DIR}/"`);
+
+ // A trailing `*` is allowed and wanted: the config is created through a
+ // `.tmp` sibling, which a crash between write and claim can leave behind.
+ const cfg = rel(writeIsolatedMcpConfigPath("/v"));
+ const covers = (line: string) => line === cfg || line === `${cfg}*`;
+ assert.ok(
+ ignored.some(covers),
+ `.gitignore must contain "${cfg}" or "${cfg}*" — the path and the ignore rule have drifted`,
+ );
+ assert.ok(
+ ignored.some((l) => l === `${cfg}*`),
+ `"${cfg}*" is what also covers the .tmp sibling this file is created through`,
+ );
+ });
+});
+
+describe("refusals", () => {
+ test("a refusal says what to change", () => {
+ const r = describeRefusal("no question given.", "Ask the judgement you need, in full.");
+ assert.match(r, /^Not run:/);
+ assert.match(r, /Ask the judgement you need/);
+ });
+});
diff --git a/.claude/scripts/tests/om-mcp.integration.test.ts b/.claude/scripts/tests/om-mcp.integration.test.ts
index b9da2ca..c726282 100644
--- a/.claude/scripts/tests/om-mcp.integration.test.ts
+++ b/.claude/scripts/tests/om-mcp.integration.test.ts
@@ -139,10 +139,24 @@ describe("the om server on the wire", () => {
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"]);
+ assert.deepEqual(names, ["expand", "health", "reason", "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`);
}
+ // `reason` starts a process and calls a model, so a client choosing between
+ // tools must be able to tell it apart from a local read without trying it.
+ const reason = tools.find((t) => t.name === "reason");
+ assert.equal(reason?.annotations?.openWorldHint, true, "reason reaches outside this process");
+ assert.equal(reason?.annotations?.idempotentHint, false, "same question, different answer");
+ });
+
+ test("reason refuses an empty question without spawning anything", async () => {
+ // This suite must never hand `reason` a real question — that would start a
+ // second Claude session from a unit test. The empty-question path is the one
+ // refusal reachable without spawning, and it proves the handler is wired.
+ const out = textOf(await call("tools/call", { name: "reason", arguments: { question: " " } }));
+ assert.match(out, /Not run:/);
+ assert.match(out, /no question/);
});
test("the resource listing honours the policy — work/ never appears", async () => {
@@ -181,6 +195,19 @@ describe("the om server on the wire", () => {
assert.match(t, /Platforms: ios/);
});
+ test("health reports the day's reasoning usage, which is what replaces a cap", async () => {
+ // Nothing bounds `reason`, so this line is the entire answer to "where did
+ // that usage go". If it stops being reported, the argument for having no
+ // cap stops holding — hence a test rather than a docstring.
+ const t = textOf(await call("tools/call", { name: "health", arguments: {} }));
+ assert.match(t, /Reasoning today: /);
+ // No spawn has happened in this suite, so it must say so rather than omit
+ // the line — an absent line reads as "not tracked".
+ assert.match(t, /Reasoning today: nothing yet today/);
+ // And it names the model that a call would actually use.
+ assert.match(t, /model: your CLI default/);
+ });
+
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);
diff --git a/.gitignore b/.gitignore
index 339b43b..578e5d9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -42,3 +42,13 @@ node_modules/
# query strings are the user's own thinking.
.claude/om-mcp-audit.jsonl
.claude/om-mcp-audit.jsonl.1
+
+# `reason` transcripts. A spawned session's conclusion is INFERRED, so it is
+# kept for provenance and cost review but never committed as vault knowledge —
+# the calling session decides whether any of it is worth a memory.
+.claude/om-reasoning/
+
+# The empty MCP config `reason` spawns against — the recursion guard. Runtime
+# plumbing, created when absent. The glob also covers the `.tmp` sibling it is
+# created through, which a crash between write and claim can leave behind.
+.claude/om-mcp-no-mcp.json*
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 1ecd92c..2128c57 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -110,7 +110,7 @@ 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 seven questions:
+`vault-manifest.json` is the one file that every layer reads. It answers eight questions:
| Question | Field |
|----------|-------|
@@ -121,6 +121,7 @@ The hook scripts, subagent prompts, command definitions, and vault conventions a
| 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` |
+| Which model does a `reason` spawn run on? | `reason.model` — unset means the user's own CLI default |
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:
@@ -350,7 +351,7 @@ The non-tool surfaces turned out to matter more than expected, so it is worth na
| 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 |
+| `tools` | session → vault | `search`, `expand`, `recall`, `remember`, `record_work`, `reason`, `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 |
@@ -364,14 +365,16 @@ That is why `prompts` exist (the human invokes them, so no model decision is inv
### The tier ladder
-| tier | what | cost at call time |
+| tier | what | what it costs you 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 |
+| **3 — reasoning** | `reason` — a spawned session reads the vault and judges | seconds to minutes of waiting |
-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.
+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 using.
+
+The ladder is about **latency**, not money. Tier 3 runs your CLI, on your machine, under your auth — the same thing you get typing `claude`. Prefer `search` when `search` would do because it answers in two seconds, not because a second session is a hazard.
### Module map
@@ -390,6 +393,7 @@ flowchart TB
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"]
+ Reason["mcp-reason.ts<br/>tier 3: argv · prompt · spawn · record"]
RH["read-head.ts<br/>bounded frontmatter prefix"]
subgraph Core["Memory core — no MCP knowledge at all"]
MW["memory-write.ts"]
@@ -410,8 +414,10 @@ flowchart TB
Server --> Graph
Server --> Bridge
Server --> Capture
+ Server --> Reason
Server --> Idx
Server --> Core
+ Server --> Qmd
Idx --> MR
Graph --> Exp
Qmd --> Exp
@@ -694,6 +700,77 @@ The vault normally re-indexes from a PostToolUse hook, but an MCP write is not a
**`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.
+### Tier 3: reasoning, and why it has to spawn
+
+Everything above answers without inference. `search` returns passages, `expand` returns neighbours, `recall` returns memories in a defensible order. None of them can answer *"is what I am about to do consistent with what these six notes decided, and what do I do about the two that disagree?"* — retrieval hands you the notes. Something has to read them.
+
+The server cannot borrow the calling session's inference to do that. MCP has a name for it — **sampling**, where a server asks its client to run a completion — and Claude Code does not implement it ([anthropics/claude-code#1785](https://github.com/anthropics/claude-code/issues/1785)). So `reason` starts a session through the user's own CLI.
+
+```mermaid
+flowchart TB
+ Q["reason(question)"] --> Seed["tier-1 search, 6 hits<br/>inside the exposure policy"]
+ Seed --> HasEv{"any hits the caller<br/>may actually see?"}
+ HasEv -->|yes| P1["prompt: start from these passages,<br/>read further when they are thin"]
+ HasEv -->|no| P2["prompt: the INDEX was silent,<br/>the vault may not be —<br/>go read it yourself"]
+ P1 --> Spawn
+ P2 --> Spawn
+ Spawn["spawn claude, async, cwd = vault root"] --> Flags["--strict-mcp-config + empty server map<br/>--tools Read,Grep,Glob<br/>--output-format json<br/>stdin closed"]
+ Flags --> Log["audit — EVERY run, before any refusal:<br/>question, cost, turns, terminal,<br/>model asked, model used, wall ms, roots"]
+ Log --> Run{"answer came back?"}
+ Run -->|no| Ref["refuse by name — timeout, early end,<br/>or could-not-start — with the evidence"]
+ Run -->|yes| Rec["write the record<br/>.claude/om-reasoning/, gitignored"]
+```
+
+**It runs on the caller's own model, by running on none of its own.** MCP gives a server no way to see which model the calling session is using, so there is nothing to mirror. Passing no `--model` at all makes the spawn take the user's CLI default — whatever they get typing `claude` — which is the closest reachable thing to *the level they are already working at*. A vault that wants something else sets `reason.model`. Bare aliases — `haiku`, `sonnet`, `opus` — are dropped in favour of inheriting, because `--model haiku` is not honoured and does **not** error: it silently runs `claude-sonnet-5`, and a pin that quietly means a different model is worse than no pin. Anything else is passed through as written rather than matched against a shape, since an id-shaped allow-list drops real ids it did not anticipate. Every answer names the model that actually ran, and says whether that was the pinned one.
+
+**Usage is answered by the record, not by a limit.** Every invocation is appended to the audit log — before any refusal, so a run that produced no answer is still recorded — with the question, cost, turns, terminal reason, model asked for, model that ran, wall time, and the roots the spawn was given. `health` reports the day's figure from the tail of that log, and says *at least* when the log was too large to read whole: a number standing in for a cap has to admit being a floor rather than quietly under-report on the busiest day. The spawn is Claude, on the user's machine, under the user's auth, on the account the calling session already runs on; a server-side bound there would be this layer rationing the user's own resource back to them. The one bound present is a 300-second timeout, which kills a **hung child** — a failure, not a preference.
+
+**Isolation is what stops it recursing.** `--strict-mcp-config` pointed at a config declaring no servers leaves the spawn with no MCP at all, so it cannot call back into `om` and start a tree that multiplies at every level. Verified on the wire: a spawn under those flags reports no MCP servers available.
+
+**Read-only comes from restricting the toolset, not from a permission mode.** `--tools Read,Grep,Glob` removes the writing tools outright, so an attempted write returns `No such tool available: Write` rather than waiting on a prompt nothing is there to answer. `--permission-mode plan` was the first attempt and is wrong twice over: it writes the plan under `~/.claude/plans/`, outside the vault, and it changes what the spawn believes it is producing — in a measured run the model composed its analysis *as a plan*, could not hand it back without `ExitPlanMode` headlessly, wrote the content to a file and returned a one-line note about having done so. The whole answer was lost, and the failure is non-deterministic, so it survived the first round of testing.
+
+A related trap, since it is how that one nearly got mis-diagnosed: **a spawn's account of its own tools is unreliable.** Asked to list them under this allowlist, it returns the full default set including `Write`. Asked to actually write a file, it cannot. It reports its prior, not its runtime — so capability is checked by trying, never by asking.
+
+**The spawn is told the same boundary its seed was filtered through.** `Read,Grep,Glob` with `cwd` at the vault root reaches the whole tree, while the seed came through `allowedSearchPaths` — so without an explicit boundary the one tool that reads most would be the only one ignoring `mcp_exposed_roots`, and could quote `memories/` scoped to other callers into its answer. The prompt therefore names the exposed roots and prohibits everything else, in the prohibition form measured to propagate. It is a boundary the spawn observes, not one the filesystem enforces, which is exactly why the audit line records the roots it was given: what it was allowed to read stays answerable afterwards.
+
+**It runs asynchronously, and that is load-bearing.** A synchronous spawn holds the whole event loop for the life of the child — measured at 73–80s, capped at 300s — during which the server parses no stdin at all: no other tool call, no `ping`, no `roots/list` reply, and no timers, so even the identity gate's own 2s cap could not fire. The entry script buys concurrency deliberately (*"serialising them here would make one slow search block every other call"*), and a synchronous spawn took that back harder than serialising would have. Verified on the wire: with `reason` running for 80.3s, a `search` and a `health` issued two seconds in came back at 2.9s and 2.8s.
+
+Two things about the spawn are non-obvious and were found the hard way. **stdin must be closed**, or the CLI waits on it and the call hangs to the timeout instead of answering. And the binary is spawned **directly with argv, never through a shell** — on Windows `cmd.exe` strips the quotes out of an inline JSON argument, and the CLI then tries to open the mangled string as a file path.
+
+**The seed prompt has two branches, and the second one exists because of a measured failure.**
+
+```mermaid
+flowchart LR
+ E["empty seed"] --> R1["read as: the vault<br/>has nothing on this"]
+ R1 --> W["reports 'no prior decisions recorded'<br/>about a question answered<br/>one directory away"]
+ E --> R2["read as: the INDEX<br/>had nothing"]
+ R2 --> G["go read the vault directly,<br/>and say how you looked"]
+
+ style W fill:#5f1e1e,color:#fff
+ style G fill:#1e4620,color:#fff
+```
+
+A vault whose index is missing or stale returns exactly what a vault with nothing to say returns. Under the normal wording the spawn treated the first as the second and reported silence — the same *absence-read-as-answer* failure this layer already had in retrieval, reproduced one tier up. The empty case therefore gets its own instructions rather than a blank evidence block.
+
+Which branch fires is decided by the **permitted** hit count, not by qmd's total: `total` counts what the index returned *before* the exposure policy filtered it, so a search whose every hit was withheld has `total > 0` and nothing the spawn can see. Reading the total alone would hand it an empty evidence block — precisely the shape that produced the false-absence answer. The prose sentinels (`(no results)`, `search failed: …`) remain as a fallback for callers holding only the text, matched as prefixes so a passage that merely quotes one of those phrases still counts as evidence.
+
+Against a vault whose index is working, seeding is worth about **one turn** — less than it looks like it should be, because a spawn with `cwd` set to the vault already inherits the vault's contract and can search for itself. Its value there is mostly that it starts in the right place, and it carries a bias: in a measured run the seeded answer leaned on the passages and repeated a framing the vault had since corrected. Hence the explicit licence in the prompt to read past the evidence, and the instruction to say when it is thin.
+
+Losing the index entirely costs less than it sounds like it should. Same vault, same question, same build, run solo and sequentially so nothing competes for the machine:
+
+| condition | turns | wall | reported cost |
+|---|--:|--:|--:|
+| index working, seeded | 23 | 72.8s | $0.37 |
+| no index at all, 1,267 notes | 26 | 76.2s | $0.44 |
+
+Three turns and four seconds. The fallback branch does exactly what it is told — enumerates the note tree, greps it, reads every distinct note, correctly identifies the 1,200 synthetic filler notes as filler, reports *how it looked*, and only then says nothing is recorded — and a spawn sitting in the vault turns out to be good at that. **The index makes tier 3 cheaper, not viable.** The thing that would make it useless is the failure above: concluding silence without looking.
+
+> Both figures are from the shipped flags. An earlier measurement here showed 143s for the unindexed case and was wrong about the cause — it was taken under `--permission-mode plan`, where the turns went into composing a plan rather than into reading the vault.
+
+**An early end returns no answer, not a short one.** If the spawn errors, times out, or stops before producing a result, the tool refuses and hands back the evidence the search already found. A truncated synthesis presented as a complete one is the single outcome worse than admitting there isn't one.
+
+**Answers are not memories.** The record lands in `.claude/om-reasoning/` — gitignored, outside the note tree, skipped by every read surface because it is a dot-directory — carrying `confidence: inferred`. Auto-recording it would fill the store with machine conclusions nobody asked for and nobody verified, and the epistemic contract exists precisely to stop that. The calling session decides whether any of it earns a `remember`.
+
### Failure modes, and how each is made visible
Every failure in this layer presents identically as **"no results"**. That is what `health` exists for.
@@ -708,6 +785,11 @@ Every failure in this layer presents identically as **"no results"**. That is wh
| 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` |
+| the CLI is not on the server's PATH | `reason` cannot start at all | the refusal names the spawn error; `OM_CLAUDE_BIN` points at the binary |
+| a pinned `reason.model` is ignored | answers come from another model, silently | the answer names the model that actually ran, and flags the mismatch |
+| a reasoning spawn ends early | would otherwise read as a complete answer | refused by name, with the turn count, the terminal reason and the evidence |
+| a reasoning spawn hits the 300s timeout | looks identical to a spawn that never started | the kill signal is read, so the terminal reason is `timeout`, in the message and the log |
+| the server exits mid-spawn | a session runs on with no bound and no audit line | shutdown kills every in-flight spawn |
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.
diff --git a/CLAUDE.md b/CLAUDE.md
index e37cd5c..8148f3f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -310,10 +310,38 @@ The vault normally only helps while you are sitting in it. The **`om` MCP server
| `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 |
+| `reason` | judgement across several notes — spawns a second session, so it takes longer |
| `health` | is the wiring intact? |
Plus notes as readable **resources**, and `recall_topic` / `prior_art` as **prompts** you invoke yourself from the `/` menu.
+### `reason` — judgement across notes
+
+The other tools answer without inference. `reason` reads the vault with a second Claude session, so it is slower and uses more — reach for it when `search` or `recall` returned the notes but not the judgement. It seeds itself from search, so there is no need to search first.
+
+**It runs on your own CLI default model**, so the vault answers at the level you are already working at. MCP gives a server no way to see the calling session's model, so inheriting the CLI default is the closest reachable thing to "the same model I am using".
+
+**Every call is on the record** — including one that produced no answer, since the log is written before any refusal. It lands in `.claude/om-mcp-audit.jsonl` with the question, cost, turns, terminal reason, model asked for, model that ran, wall time, and the roots the spawn was given. `health` reports the day's figure, and says *at least* when the log was too big to read whole rather than quietly under-reporting.
+
+**It reads what this vault serves, and nothing else.** The spawn is handed the same three rules the exposure policy applies to search results: your `mcp_exposed_roots`, your `mcp_never_expose` filenames, and `private:`-tagged notes — the last two matter because they live *inside* exposed roots. Unset, that is simply your `user_content_roots`, so the boundary is whatever you already declared rather than anything this tool adds. It is also told not to read the memory root, since a memory belongs to the project it was scoped to.
+
+**The server stays responsive while it runs.** Other tools answer normally mid-call, and a shutdown ends any spawn still in flight rather than orphaning it.
+
+One optional key, which does not ship set:
+
+```json
+"reason": { "model": "claude-haiku-4-5" } // pin a model instead of inheriting
+```
+
+Left unset — the default — it uses your own Claude settings.
+
+> [!warning] If you pin a model, use a FULL id.
+> `--model haiku` is not honoured by the CLI and does not error — it silently runs `claude-sonnet-5`. Bare aliases (`haiku`, `sonnet`, `opus`) are therefore dropped in favour of inheriting; anything else is passed through as written. Every answer names the model that actually ran, and says whether it was the pinned one.
+
+If a run ends early you get **no answer**, not a truncated one, plus the evidence search already found — a partial synthesis presented as complete is the one outcome worse than none.
+
+Answers land in `.claude/om-reasoning/` (gitignored) marked `confidence: inferred`. They are deliberately **not** recorded as memories — a spawned conclusion is reasoning, not verified knowledge, and the calling session decides whether any of it earns a `remember`.
+
### 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:
diff --git a/README.ja.md b/README.ja.md
index a1b6369..6a0c35b 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -256,7 +256,9 @@ obsidian-mindはClaude Code、Codex CLI、Gemini CLIで動作します。`CLAUDE
>
> MCPの`instructions`フィールドにおける**禁止事項**は呼び出し側セッションへ確実に伝播します。一方`「ボールトを参照せよ」`という肯定的な指示は助言的で、より近い情報源があれば無視されます。サーバーはセッションを止められますが、セッションに探しに行かせられるのはそのプロジェクト自身の規約だけです。
-**セッションが得られるもの:** `search`(セマンティック+キーワード)、`expand`(ノートのリンクと被リンク)、`recall`(そのリポジトリにスコープされた恒久的な教訓)、`remember`(教訓の記録)、`record_work`(作業内容の記録)、`health`(配線は正常か)。加えて、ノートを読み取り可能なリソースとして提供します。
+**セッションが得られるもの:** `search`(セマンティック+キーワード)、`expand`(ノートのリンクと被リンク)、`recall`(そのリポジトリにスコープされた恒久的な教訓)、`remember`(教訓の記録)、`record_work`(作業内容の記録)、`reason`(複数ノートにまたがる判断)、`health`(配線は正常か)。加えて、ノートを読み取り可能なリソースとして提供します。
+
+**思考するのは`reason`だけです。** 他が検索するのに対し、これは2つ目のClaudeセッションでボールトを読み、ノートをまたぐ判断を要する問いに答えます — *これから行おうとしていることは、これら6つのノートが決めた内容と整合しているか?* 内部で先に検索を行うため、事前に検索する必要はありません。あなた自身のCLIデフォルトモデルで動くので、ボールトは今あなたが作業しているのと同じ水準で答えます。そして一切の上限はありません — これはあなたのマシン上で、あなたの認証のもとで動くClaudeです。呼び出しごとにコスト・ターン数・モデル・実経過時間が記録されます。回答は`confidence: inferred`が付き、それ単体でメモリとして記録されることはありません — 残す価値があるかはあなたのセッションが決めます。
**リポジトリはフォルダ名で識別されます。** これは通常正しく、稀に誤ります: `api`という名前のリポジトリが2つあると同一の識別子を共有し、互いのメモリを受け取ってしまいます。リポジトリのルートに`.om-project`ファイルを置き、別の名前を書けば分離できます。`health`がどのリポジトリとして認識しているか、その名前がどこから来たかを教えてくれます。
diff --git a/README.ko.md b/README.ko.md
index 070b4cb..6a29dfb 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -256,7 +256,9 @@ obsidian-mind는 Claude Code, Codex CLI, Gemini CLI에서 작동합니다. `CLAU
>
> MCP `instructions` 필드의 **금지 사항**은 호출하는 세션으로 확실히 전파됩니다. 반면 `"볼트를 참조하라"`는 긍정형 지시는 권고적이며, 더 가까운 정보원이 있으면 건너뜁니다. 서버는 세션을 멈출 수는 있지만, 세션이 찾아보게 만드는 것은 그 프로젝트 자체의 규약뿐입니다.
-**세션이 얻는 것:** `search`(시맨틱 + 키워드), `expand`(노트의 링크와 백링크), `recall`(해당 저장소로 스코프된 지속적 교훈), `remember`(교훈 기록), `record_work`(작업 내용 기록), `health`(배선이 정상인지). 여기에 노트를 읽을 수 있는 리소스로 제공합니다.
+**세션이 얻는 것:** `search`(시맨틱 + 키워드), `expand`(노트의 링크와 백링크), `recall`(해당 저장소로 스코프된 지속적 교훈), `remember`(교훈 기록), `record_work`(작업 내용 기록), `reason`(여러 노트에 걸친 판단), `health`(배선이 정상인지). 여기에 노트를 읽을 수 있는 리소스로 제공합니다.
+
+**생각하는 것은 `reason` 하나입니다.** 나머지가 검색이라면, 이것은 두 번째 Claude 세션으로 볼트를 읽고 노트를 가로지르는 판단이 필요한 질문에 답합니다 — *지금 하려는 일이 이 여섯 개의 노트가 결정한 바와 일치하는가?* 스스로 먼저 검색을 수행하므로 먼저 검색할 필요가 없습니다. 당신 본인의 CLI 기본 모델로 동작하므로, 볼트는 지금 작업 중인 수준과 같은 수준으로 답합니다. 그리고 어떤 상한도 없습니다 — 당신의 기기에서, 당신의 인증으로 돌아가는 Claude이기 때문입니다. 호출마다 비용·턴 수·모델·실제 소요 시간이 기록됩니다. 답변에는 `confidence: inferred`가 붙고 그 자체로 메모리에 기록되지 않습니다 — 남길 가치가 있는지는 당신의 세션이 정합니다.
**저장소는 폴더 이름으로 식별됩니다.** 대개는 맞지만 가끔 틀립니다: `api`라는 이름의 저장소가 둘이면 하나의 정체성을 공유해 서로의 메모리를 받게 됩니다. 저장소 루트에 `.om-project` 파일을 두고 다른 이름을 적으면 분리됩니다. `health`가 어느 저장소로 인식하는지, 그 이름이 어디서 왔는지 알려줍니다.
diff --git a/README.md b/README.md
index c5c67d4..5c14c0a 100644
--- a/README.md
+++ b/README.md
@@ -263,7 +263,9 @@ That goes in the **consuming project's** `.mcp.json`. Then add a short section t
>
> 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.
+**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), `reason` (judgement across several notes), and `health` (is the wiring intact?). Plus your notes as readable resources.
+
+**`reason` is the one that thinks.** The others retrieve; this one reads the vault with a second Claude session and answers questions that need judgement across notes — *is what I am about to do consistent with what these six notes decided?* It seeds itself from search, so you never have to search first. It runs on your own CLI default model, so the vault answers at the level you are already working at, and nothing about it is capped: it is Claude, on your machine, under your auth. Every call is logged with its cost, turns, model and wall time. Its answers are marked `confidence: inferred` and are never recorded as memories on their own — your session decides whether any of it is worth keeping.
**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.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 6762f68..e688e72 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -256,7 +256,9 @@ vault 通常只在你身处其中时才有用。**`om` MCP 服务器**改变了
>
> MCP `instructions` 字段中的**禁止性规则**会可靠地传播到调用方会话;而“去查阅 vault”这类肯定式指令只是建议性的,只要存在更近的信息源就会被跳过。服务器能阻止会话做某件事,但只有项目自身的规约能让它主动去查。
-**会话得到的能力:** `search`(语义 + 关键词)、`expand`(笔记的出链与反链)、`recall`(限定到该仓库的持久经验)、`remember`(记录一条经验)、`record_work`(归档所做的工作)、`health`(接线是否完好)。此外还把笔记作为可读资源暴露出来。
+**会话得到的能力:** `search`(语义 + 关键词)、`expand`(笔记的出链与反链)、`recall`(限定到该仓库的持久经验)、`remember`(记录一条经验)、`record_work`(归档所做的工作)、`reason`(跨多条笔记的判断)、`health`(接线是否完好)。此外还把笔记作为可读资源暴露出来。
+
+**真正会思考的是 `reason`。** 其余的都是检索,而它会用第二个 Claude 会话读你的 vault,回答那些需要跨笔记做判断的问题 — *我接下来要做的事,和这六条笔记当初的决定一致吗?* 它会先自行检索一遍作为起点,所以你不需要先搜。它跑在你自己的 CLI 默认模型上,因此 vault 会以你当前工作的水准回答;并且没有任何上限 — 这就是 Claude,在你的机器上、用你的凭证运行。每次调用都会记录费用、轮数、模型和实际耗时。答案标记为 `confidence: inferred`,不会自行写入记忆 — 值不值得留下由你的会话决定。
**仓库按文件夹名识别。** 这在大多数情况下是对的,偶尔不是:两个都叫 `api` 的仓库会共享同一个身份,于是彼此收到对方的记忆。在仓库根目录放一个 `.om-project` 文件并写入不同的名字即可分开;`health` 会告诉你它认为是哪个仓库在调用,以及这个名字从哪里来。
diff --git a/brain/Skills.md b/brain/Skills.md
index 81685c9..6119a59 100644
--- a/brain/Skills.md
+++ b/brain/Skills.md
@@ -129,10 +129,13 @@ SessionStart hook runs `qmd --index <name> update` automatically, reading the in
| `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 |
+| `reason` | judgement across several notes, by reading the vault with a second Claude session |
| `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.
+**`reason` is the slow one.** The rest answer without inference; this one spawns a session, so it takes seconds to minutes. Reach for it when `search` or `recall` returned the notes but not the answer — it seeds itself from search, so there is no need to search first. It runs on your own CLI default model unless `reason.model` pins one, nothing about it is capped, and every call is logged with its cost, turns, model and wall time. Answers land in `.claude/om-reasoning/` marked `confidence: inferred` and are never auto-recorded as memories.
+
**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`.