Skip to content

Self-hosted MCP server + dashboard giving Claude Code, Cursor & Hermes agents shared long-term memory over a git-backed markdown vault. Agent-native, Obsidian-compatible second brain — markdown RAG, no vector DB.

feat(validity): atomic brain_supersede + validity-aware live reads

Ronalds Palacisfcf9d5832ef8
diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.ts
index 1385734..83be6a2 100644
--- a/lib/mcp/tools.ts
+++ b/lib/mcp/tools.ts
@@ -9,13 +9,14 @@ import {
searchNotes,
vaultConventions,
} from "@/lib/vault/store";
-import { authorityOf } from "@/lib/vault/authority";
+import { effectiveAuthority } from "@/lib/vault/authority";
import { extractSection, listHeadings } from "@/lib/vault/parse";
import {
appendNote,
createFolder,
deleteNote,
moveNote,
+ supersedeNote,
writeNote,
writeNoteRaw,
} from "@/lib/vault/write";
@@ -131,11 +132,12 @@ export const TOOLS: Tool[] = [
handler: ({ path, section }) => {
const n = getNote(String(path));
if (!n) return { error: "not found", path };
+ const eff = effectiveAuthority(n);
const base = {
path: n.path,
title: n.title,
status: n.status,
- authority: authorityOf(n),
+ authority: eff.authority,
tags: n.tags,
frontmatter: n.frontmatter,
backlinks: getBacklinks(n.path).map((b) => b.path),
@@ -143,7 +145,11 @@ export const TOOLS: Tool[] = [
? {
warning: `This note's frontmatter is unparseable (${n.frontmatterError}), so its status, tags and title are being ignored — whatever it claims about itself is NOT in effect. Usual cause: an unquoted ":" in a value.`,
}
- : {}),
+ : eff.retired
+ ? {
+ warning: `This note is ${eff.reason} — it is history, not a current fact. Do not quote it as current; find the note that replaced it.`,
+ }
+ : {}),
};
if (!section) return { ...base, content: n.raw };
@@ -167,7 +173,7 @@ export const TOOLS: Tool[] = [
type: n.type,
tags: n.tags,
status: n.status,
- authority: authorityOf(n),
+ authority: effectiveAuthority(n).authority,
})),
},
{
@@ -188,7 +194,7 @@ export const TOOLS: Tool[] = [
title: n.title,
folder: n.folder,
status: n.status,
- authority: authorityOf(n),
+ authority: effectiveAuthority(n).authority,
modified: new Date(n.mtimeMs).toISOString(),
}));
},
@@ -277,6 +283,32 @@ export const TOOLS: Tool[] = [
inputSchema: { type: "object", properties: { path: s("folder path") }, required: ["path"] },
handler: async ({ path }) => ({ ok: true, path: await createFolder(String(path)) }),
},
+ {
+ name: "brain_supersede",
+ write: true,
+ description:
+ "Retire a fact and replace it, atomically. When a fact changes (a price, a term, a decision), DON'T just add a new note — the old value keeps matching searches and gets quoted. `brain_supersede(from, to)` marks the old note superseded in place (body preserved) and links it to the new one, in a single commit, so add-and-retire can't drift apart. After this, search withholds the old note with the reason \"superseded by <to>\".\n\n" +
+ "`from` = the note being retired; `to` = the note that replaces it. If `to` doesn't exist yet, pass `body` (its markdown) and it's created; otherwise write `to` first, then supersede. `reason` is recorded on the old note. Prefer this over brain_move for a value that changed (move is for relocation).",
+ inputSchema: {
+ type: "object",
+ properties: {
+ from: s("the note being retired (vault-relative path)"),
+ to: s("the note that replaces it (vault-relative path)"),
+ reason: s("optional — why it was retired, e.g. 'repriced Q3'"),
+ body: s("optional — markdown for `to` if it doesn't exist yet"),
+ },
+ required: ["from", "to"],
+ },
+ handler: async ({ from, to, reason, body }) => {
+ const r = await supersedeNote(
+ String(from),
+ String(to),
+ reason ? String(reason) : undefined,
+ body ? String(body) : undefined,
+ );
+ return { ok: true, ...r, path: r.to };
+ },
+ },
{
name: "brain_capture",
write: true,
diff --git a/lib/vault/write.ts b/lib/vault/write.ts
index 3bccc3b..6c86032 100644
--- a/lib/vault/write.ts
+++ b/lib/vault/write.ts
@@ -3,6 +3,7 @@ import path from "node:path";
import matter from "gray-matter";
import { activeVaultDir } from "@/lib/repos";
import { refreshPaths } from "./store";
+import { humanize, stemOf } from "./parse";
import { checkFrontmatter, frontmatterErrorMessage } from "./validate";
import { requestSync } from "@/lib/git";
import { currentActor } from "@/lib/actor";
@@ -137,6 +138,83 @@ export async function deleteNote(relPath: string): Promise<void> {
after(`delete ${relPath}`, [normalizeNotePath(relPath)]);
}
+/**
+ * Atomically retire OLD in favor of NEW, in a single commit.
+ *
+ * This is the "add and retire can't drift apart" primitive. It marks the old note superseded
+ * *in place* (frontmatter only — body preserved, so backlinks and chronology survive and the
+ * truncation guard never trips), ensures the replacement exists, and records both in ONE `after()`
+ * call so git-sync produces exactly one commit (the `moveNote` atomicity pattern). Query-time
+ * search then withholds the old note with the reason "superseded by <new>".
+ *
+ * Uses raw `fsp` writes deliberately — `writeNote`/`appendNote` each call `after()` themselves,
+ * which would split the operation across two commits.
+ */
+export async function supersedeNote(
+ from: string,
+ to: string,
+ reason?: string,
+ body?: string,
+): Promise<{ from: string; to: string }> {
+ const fromPath = normalizeNotePath(from);
+ const toPath = normalizeNotePath(to);
+ if (fromPath === toPath) throw new Error("supersede: `from` and `to` must be different notes.");
+ const fromAbs = safeAbs(fromPath);
+ const toAbs = safeAbs(toPath);
+
+ let oldRaw: string;
+ try {
+ oldRaw = await fsp.readFile(fromAbs, "utf8");
+ } catch {
+ throw new Error(`Cannot supersede ${fromPath}: it does not exist.`);
+ }
+ // Refuse rather than silently rewrite a note whose YAML is already broken.
+ const check = checkFrontmatter(oldRaw);
+ if (!check.ok) {
+ throw new Error(`Refusing to supersede ${fromPath}: its frontmatter is already unparseable (${check.error}). Fix it first.`);
+ }
+
+ const toStem = stemOf(toPath);
+ const fromStem = stemOf(fromPath);
+ const today = new Date(Date.now()).toISOString().slice(0, 10);
+
+ // 1. Mark OLD superseded in place — frontmatter only, body verbatim.
+ const g = matter(oldRaw);
+ const data: Record<string, unknown> = { ...(g.data as Record<string, unknown>) };
+ data.status = "superseded";
+ data.superseded_by = `[[${toStem}]]`;
+ data.superseded_at = today;
+ if (reason) data.superseded_reason = reason;
+ const oldOut = matter.stringify(g.content, data);
+
+ // 2. Prepare NEW if it doesn't exist yet (from `body`, or a minimal stub linking back).
+ let newContent: string | null = null;
+ try {
+ await fsp.access(toAbs);
+ } catch {
+ if (body && body.trim().startsWith("---")) {
+ const bc = checkFrontmatter(body);
+ if (!bc.ok) throw new Error(`supersede: the replacement's frontmatter is invalid (${bc.error}). Pass a plain body, or valid YAML.`);
+ newContent = body;
+ } else {
+ newContent = matter.stringify(body?.trim() || `Supersedes [[${fromStem}]]${reason ? ` — ${reason}` : ""}.`, {
+ title: humanize(toStem),
+ supersedes: `[[${fromStem}]]`,
+ });
+ }
+ }
+
+ // 3. Write both, then one after() → one refreshPaths + one commit.
+ await fsp.mkdir(path.dirname(fromAbs), { recursive: true });
+ await fsp.writeFile(fromAbs, oldOut, "utf8");
+ if (newContent !== null) {
+ await fsp.mkdir(path.dirname(toAbs), { recursive: true });
+ await fsp.writeFile(toAbs, newContent, "utf8");
+ }
+ after(`supersede ${fromPath} -> ${toPath}${reason ? `: ${reason}` : ""}`, [fromPath, toPath]);
+ return { from: fromPath, to: toPath };
+}
+
export async function createFolder(relPath: string): Promise<string> {
const p = relPath.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "").replace(/\.\.(\/|$)/g, "");
const abs = safeAbs(p);