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(write): enforce parseable frontmatter at the write boundary

Ronalds Palacis3ddf5336dc06
diff --git a/app/api/notes/[...path]/route.ts b/app/api/notes/[...path]/route.ts
index c8fe184..a1ec8ad 100644
--- a/app/api/notes/[...path]/route.ts
+++ b/app/api/notes/[...path]/route.ts
@@ -1,4 +1,5 @@
import { getBacklinks, getNote, getOutlinks } from "@/lib/vault/store";
+import { checkFrontmatter } from "@/lib/vault/validate";
import { deleteNote, writeNoteRaw } from "@/lib/vault/write";
export const dynamic = "force-dynamic";
@@ -16,8 +17,19 @@ export async function PUT(req: Request, { params }: { params: Promise<{ path: st
const rel = path.map(decodeURIComponent).join("/");
const { content } = await req.json().catch(() => ({}));
if (typeof content !== "string") return Response.json({ error: "content (string) required" }, { status: 400 });
+ // Non-strict: a human may autosave half-typed frontmatter. Save it, but tell them it is broken —
+ // otherwise the note silently loses its status and tags. (Agents are refused; see lib/mcp/tools.ts.)
const saved = await writeNoteRaw(rel, content);
- return Response.json({ ok: true, path: saved });
+ const check = checkFrontmatter(content);
+ return Response.json({
+ ok: true,
+ path: saved,
+ ...(check.ok
+ ? {}
+ : {
+ warning: `Frontmatter is not valid YAML (${check.error}) — this note's status, tags and title are being ignored. Usual cause: an unquoted ":" in a value.`,
+ }),
+ });
}
export async function DELETE(_req: Request, { params }: { params: Promise<{ path: string[] }> }) {
diff --git a/lib/curator.ts b/lib/curator.ts
index b67099b..15cc036 100644
--- a/lib/curator.ts
+++ b/lib/curator.ts
@@ -2,6 +2,7 @@ import Anthropic from "@anthropic-ai/sdk";
import { DEFAULT_CURATOR_MODEL, SUPPORTED_MODEL_IDS } from "@/lib/models";
import { anthropicApiKey } from "@/lib/settings";
import { getBacklinks, getNote, listNotes, readVaultFile, searchNotes } from "@/lib/vault/store";
+import { authorityOf } from "@/lib/vault/authority";
/**
* The Curator — the resident chat agent of the brain. It answers questions about the
@@ -15,6 +16,7 @@ function systemPrompt(): string {
return `You are the Curator — the resident agent of this markdown "second brain". You help the operator recall, connect, and reason over their own notes.
Rules:
+- Every note carries an "authority": authoritative > current > provisional > superseded > archived. Search ranks by keyword relevance, not truth, so a superseded note can outrank the live one. Prefer the authoritative note. Never present a superseded, archived, or provisional note as current fact; if that is all you have, say so explicitly.
- Ground every factual claim about the vault in the notes. Use brain_search to find notes, brain_read to read their full content, brain_list to see what exists. Never invent facts about the vault — if it isn't in the notes, say so plainly.
- Cite notes in wikilink form so the user can click through, e.g. [[clients/mks/mks|MKS]] or [[decisions/foo-2026-07-09]].
- Be direct, specific, and concise. Lead with the answer, then the supporting detail.
@@ -26,17 +28,19 @@ ${schema ? `\nThe vault's SCHEMA (folder taxonomy + conventions):\n"""\n${schema
const TOOLS: Anthropic.Tool[] = [
{
name: "brain_search",
- description: "Full-text + fuzzy search across all notes. Returns ranked results (path, title, folder). Use this first to find relevant notes.",
+ description:
+ "Keyword search across all notes. Use this first. Returns ranked hits with path, title, folder, status, a snippet, and `authority`. Ranking is by keyword relevance, NOT by truth: a superseded note repeats the query words as often as the live one. Trust `authority` (authoritative > current > provisional > superseded > archived) over rank order.",
input_schema: { type: "object", properties: { query: { type: "string", description: "search query" } }, required: ["query"] },
},
{
name: "brain_read",
- description: "Read a note's full markdown (frontmatter + body) plus its backlinks. Path is vault-relative, e.g. 'clients/mks/mks.md'.",
+ description:
+ "Read a note's full markdown (frontmatter + body) plus its backlinks and `authority`. Path is vault-relative, e.g. 'clients/mks/mks.md'.",
input_schema: { type: "object", properties: { path: { type: "string", description: "vault-relative path" } }, required: ["path"] },
},
{
name: "brain_list",
- description: "List all notes with metadata (path, title, folder, type, tags). Use to discover what exists.",
+ description: "List all notes with metadata (path, title, folder, type, tags, status, authority). Use to discover what exists.",
input_schema: { type: "object", properties: {} },
},
];
@@ -46,9 +50,17 @@ function runTool(name: string, input: Record<string, unknown>): unknown {
if (name === "brain_read") {
const p = String(input.path ?? "");
const n = getNote(p);
- return n ? { path: p, frontmatter: n.frontmatter, content: n.raw, backlinks: getBacklinks(p) } : { error: `not found: ${p}` };
+ if (!n) return { error: `not found: ${p}` };
+ return {
+ path: p,
+ authority: authorityOf(n),
+ frontmatter: n.frontmatter,
+ content: n.raw,
+ backlinks: getBacklinks(p),
+ ...(n.frontmatterError ? { warning: `Unparseable frontmatter (${n.frontmatterError}) — this note's status and tags are ignored.` } : {}),
+ };
}
- if (name === "brain_list") return listNotes();
+ if (name === "brain_list") return listNotes().map((n) => ({ ...n, authority: authorityOf(n) }));
return { error: `unknown tool: ${name}` };
}
diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.ts
index 9b01934..67d578f 100644
--- a/lib/mcp/tools.ts
+++ b/lib/mcp/tools.ts
@@ -48,7 +48,8 @@ async function writeFromArgs(a: Args): Promise<string> {
const bodyStr = typeof a.body === "string" ? a.body : "";
const contentStr = typeof a.content === "string" ? a.content : "";
const raw = contentStr.trim() !== "" ? contentStr : !hasFm && bodyStr.trim().startsWith("---") ? bodyStr : "";
- if (raw.trim() !== "") return writeNoteRaw(p, raw);
+ // strict: an agent that hand-writes unparseable YAML is refused, not silently accepted.
+ if (raw.trim() !== "") return writeNoteRaw(p, raw, { strict: true });
if (bodyStr.trim() !== "" || hasFm) return writeNote(p, bodyStr, fm);
throw new Error(
"Nothing to write. Pass `body` (markdown, + optional `frontmatter` object) or `content` (full raw markdown incl. frontmatter). Refusing to create an empty note.",
@@ -208,7 +209,7 @@ export const TOOLS: Tool[] = [
{
name: "brain_write",
description:
- "Create or overwrite a note. Pass EITHER `body` (markdown) + optional `frontmatter` (object), OR `content` (full raw markdown incl. frontmatter, same as brain_edit) — either works. Follow SCHEMA.md: kebab-case path, dated names for daily/decisions, frontmatter with title/type/tags/status. Path vault-relative (e.g. decisions/foo-2026-07-09.md).",
+ "Create or overwrite a note. PREFER `body` (markdown, no frontmatter) + `frontmatter` (an object): the YAML is serialised for you and always parses. Hand-writing frontmatter into `content` risks invalid YAML — a note whose frontmatter fails to parse loses its status, tags and title on every read, so a note claiming `status: locked` would rank as an ordinary one. Such a write is REJECTED. Follow SCHEMA.md: kebab-case path, dated names for daily/decisions, frontmatter with title/type/tags/status. Path vault-relative (e.g. decisions/foo-2026-07-09.md).",
inputSchema: {
type: "object",
properties: {
diff --git a/lib/vault/validate.ts b/lib/vault/validate.ts
new file mode 100644
index 0000000..7094fde
--- /dev/null
+++ b/lib/vault/validate.ts
@@ -0,0 +1,36 @@
+import matter from "gray-matter";
+
+/**
+ * Guard the one chokepoint every writer passes through.
+ *
+ * Instructions in a system prompt are persuasion; a check here is a guarantee. An agent that
+ * hand-writes YAML into `content` can produce frontmatter that gray-matter refuses to parse
+ * (the classic: an unquoted second colon in a title). On read that frontmatter is discarded
+ * silently, so the note loses its status, tags and title — and a note claiming `status: locked`
+ * quietly ranks as an ordinary one. Cheaper to refuse the write than to hunt the ghost later.
+ */
+export interface FrontmatterCheck {
+ ok: boolean;
+ error?: string;
+}
+
+/** Notes without frontmatter are fine. Notes that open with `---` must parse. */
+export function checkFrontmatter(content: string): FrontmatterCheck {
+ if (!content.trimStart().startsWith("---")) return { ok: true };
+ try {
+ matter(content);
+ return { ok: true };
+ } catch (e) {
+ return { ok: false, error: (e as Error).message.split("\n")[0] };
+ }
+}
+
+export function frontmatterErrorMessage(relPath: string, error: string): string {
+ return (
+ `Refusing to write ${relPath}: its frontmatter is not valid YAML (${error}). ` +
+ `If it were written, the status, tags and title would be silently ignored on every read. ` +
+ `Usual cause: an unquoted ":" in a value — write title: "Decision: X" instead of title: Decision: X. ` +
+ `Safest fix: pass a \`frontmatter\` object and a plain \`body\` instead of hand-writing YAML into \`content\`; ` +
+ `it is serialised for you and always parses.`
+ );
+}
diff --git a/lib/vault/write.ts b/lib/vault/write.ts
index b22930d..1b9d982 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 { checkFrontmatter, frontmatterErrorMessage } from "./validate";
import { requestSync } from "@/lib/git";
/** Resolve a vault-relative path to an absolute path in the active vault, refusing escapes. */
@@ -24,9 +25,23 @@ function after(message: string, touched: string[]) {
requestSync(message);
}
+export interface WriteOpts {
+ /**
+ * Reject the write when the frontmatter cannot be parsed back.
+ * True for agents (MCP) — a machine has no excuse for emitting broken YAML, and a corrupt
+ * note silently loses its authority. False for the dashboard editor, where a human may save
+ * a half-typed document; they get a warning instead of losing their work.
+ */
+ strict?: boolean;
+}
+
/** Write a note from a raw markdown string (frontmatter included). Used by the editor. */
-export async function writeNoteRaw(relPath: string, content: string): Promise<string> {
+export async function writeNoteRaw(relPath: string, content: string, opts: WriteOpts = {}): Promise<string> {
const p = normalizeNotePath(relPath);
+ if (opts.strict) {
+ const check = checkFrontmatter(content);
+ if (!check.ok) throw new Error(frontmatterErrorMessage(p, check.error!));
+ }
const abs = safeAbs(p);
await fsp.mkdir(path.dirname(abs), { recursive: true });
await fsp.writeFile(abs, content, "utf8");
@@ -34,11 +49,15 @@ export async function writeNoteRaw(relPath: string, content: string): Promise<st
return p;
}
-/** Write a note from a body + optional frontmatter object. Used by agents (MCP). */
+/**
+ * Write a note from a body + optional frontmatter object. Used by agents (MCP) and the harness.
+ * `matter.stringify` serialises the object, so the YAML always parses — this path cannot
+ * produce the corruption that hand-written frontmatter can.
+ */
export async function writeNote(relPath: string, body: string, frontmatter?: Record<string, unknown>): Promise<string> {
const content =
frontmatter && Object.keys(frontmatter).length > 0 ? matter.stringify(body ?? "", frontmatter) : (body ?? "");
- return writeNoteRaw(relPath, content);
+ return writeNoteRaw(relPath, content, { strict: true });
}
export async function appendNote(relPath: string, text: string): Promise<string> {