Skip to content

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

fix: drive the frontmatter write check from frontmatter_required in the manifest (#298)

Brenno Ferrari2ebf3880877d
diff --git a/.claude/scripts/lib/frontmatter.ts b/.claude/scripts/lib/frontmatter.ts
index 6889930..3006344 100644
--- a/.claude/scripts/lib/frontmatter.ts
+++ b/.claude/scripts/lib/frontmatter.ts
@@ -74,11 +74,126 @@ export function shouldSkipFile(filePath: string): boolean {
return false;
}
+/** `vault-manifest.json`'s `frontmatter_required`: `global` plus per-type sets. */
+export type FrontmatterRequired = Readonly<Record<string, readonly string[]>>;
+
+/** Used when the manifest declares no usable `global` set. */
+const DEFAULT_GLOBAL: readonly string[] = ["date", "description", "tags"];
+
+/**
+ * Which note type a vault path is, by folder. The folder→type map is
+ * vault-specific; a future extension point. It mirrors the placement table
+ * in CLAUDE.md and /om-vault-audit's per-type rules, which are keyed by
+ * folder too. Tags cannot carry this: 1:1 notes are tagged `work-note`, yet
+ * do not need a work note's `status`.
+ */
+const NOTE_TYPE_BY_FOLDER: readonly (readonly [string, string])[] = [
+ ["work/incidents/", "incident"],
+ ["work/1-1/", "1-1"],
+ ["work/active/", "work-note"],
+ ["work/archive/", "work-note"],
+ ["org/people/", "person"],
+ ["org/teams/", "team"],
+];
+
+export function noteTypeForPath(relPath: string): string | null {
+ const p = relPath.replaceAll("\\", "/");
+ for (const [prefix, type] of NOTE_TYPE_BY_FOLDER) {
+ if (p.startsWith(prefix)) return type;
+ }
+ return null;
+}
+
+/**
+ * Read `frontmatter_required` from a parsed manifest, keeping only string
+ * lists. Anything malformed is dropped rather than guessed at.
+ */
+export function parseFrontmatterRequired(manifest: unknown): FrontmatterRequired {
+ const raw = (manifest as { frontmatter_required?: unknown } | null)?.frontmatter_required;
+ const out: Record<string, readonly string[]> = {};
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) {
+ for (const [type, fields] of Object.entries(raw)) {
+ if (Array.isArray(fields)) {
+ out[type] = fields.filter((f): f is string => typeof f === "string" && f !== "");
+ }
+ }
+ }
+ return out;
+}
+
+/**
+ * The top-level keys of a frontmatter block, and its `tags`. A key counts
+ * when its line exists, even with an empty value — a template-born note with
+ * a blank `description:` is filled in afterwards, and was never warned
+ * about. Matched as a KEY at the start of a line: `update:` is not `date`,
+ * which a substring test used to accept.
+ */
+export function readFrontmatterKeys(fm: string): { keys: Set<string>; tags: string[] } {
+ const keys = new Set<string>();
+ const tags: string[] = [];
+ let inTags = false;
+ for (const line of fm.split(/\r?\n/)) {
+ const kv = /^([A-Za-z_][\w-]*)\s*:\s*(.*)$/.exec(line);
+ if (kv) {
+ const key = kv[1] as string;
+ keys.add(key);
+ inTags = key === "tags";
+ if (inTags) {
+ const v = (kv[2] ?? "").trim();
+ const inner = v.startsWith("[") && v.endsWith("]") ? v.slice(1, -1) : v;
+ for (const t of inner.split(",")) {
+ const s = t.trim().replace(/^["']|["']$/g, "");
+ if (s) tags.push(s);
+ }
+ }
+ continue;
+ }
+ const item = inTags ? /^\s+-\s*(.+)$/.exec(line) : null;
+ if (item) tags.push((item[1] as string).trim().replace(/^["']|["']$/g, ""));
+ else if (line.trim() !== "" && !/^\s/.test(line)) inTags = false;
+ }
+ return { keys, tags };
+}
+
+/** The tag that marks a MAIN incident note, the only one the incident set applies to. */
+const INCIDENT_ONLY_TAG = "incident";
+
+/**
+ * The fields a note must declare: the manifest's `global` set (or the
+ * built-in three), plus its folder type's set. In `work/incidents/` the
+ * incident set applies only to a note tagged `incident` — RCAs, deep dives
+ * and drafts live beside the main note and carry the global set alone.
+ */
+export function requiredFieldsFor(
+ required: FrontmatterRequired,
+ relPath: string | null,
+ tags: readonly string[],
+): string[] {
+ const global = required["global"]?.length ? required["global"] : DEFAULT_GLOBAL;
+ const type = relPath === null ? null : noteTypeForPath(relPath);
+ const typed =
+ type === null || (type === "incident" && !tags.includes(INCIDENT_ONLY_TAG))
+ ? []
+ : (required[type] ?? []);
+ return [...new Set([...global, ...typed])];
+}
+
+const FIELD_MESSAGES: Readonly<Record<string, string>> = {
+ tags: "Missing `tags` in frontmatter",
+ description: "Missing `description` in frontmatter (~150 chars required by vault convention)",
+ date: "Missing `date` in frontmatter",
+};
+
/**
* Inspect markdown content and return a list of warnings. Empty list means
- * the note is valid by our conventions.
+ * the note is valid by our conventions. `required` comes from the manifest's
+ * `frontmatter_required`; `relPath` (vault-relative) decides the note type.
+ * Without either, the three global fields are checked, as before.
*/
-export function validateContent(content: string): string[] {
+export function validateContent(
+ content: string,
+ opts: { readonly required?: FrontmatterRequired; readonly relPath?: string | null } = {},
+): string[] {
const warnings: string[] = [];
if (!content.startsWith("---")) {
@@ -86,18 +201,14 @@ export function validateContent(content: string): string[] {
} else {
const parts = content.split("---");
if (parts.length >= 3) {
- const fm = parts[1] ?? "";
- if (!fm.includes("tags:") && !fm.includes("tags :")) {
- warnings.push("Missing `tags` in frontmatter");
- }
- if (!fm.includes("description:") && !fm.includes("description :")) {
+ const { keys, tags } = readFrontmatterKeys(parts[1] ?? "");
+ for (const field of requiredFieldsFor(opts.required ?? {}, opts.relPath ?? null, tags)) {
+ if (keys.has(field)) continue;
warnings.push(
- "Missing `description` in frontmatter (~150 chars required by vault convention)",
+ FIELD_MESSAGES[field] ??
+ `Missing \`${field}\` in frontmatter (required by vault-manifest.json frontmatter_required)`,
);
}
- if (!fm.includes("date:") && !fm.includes("date :")) {
- warnings.push("Missing `date` in frontmatter");
- }
}
}
diff --git a/.claude/scripts/tests/frontmatter.test.ts b/.claude/scripts/tests/frontmatter.test.ts
index 327197f..fd2caae 100644
--- a/.claude/scripts/tests/frontmatter.test.ts
+++ b/.claude/scripts/tests/frontmatter.test.ts
@@ -5,12 +5,133 @@
import { test, describe } from "node:test";
import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
import {
isBlockedMemoryPath,
+ noteTypeForPath,
+ parseFrontmatterRequired,
+ readFrontmatterKeys,
shouldSkipFile,
validateContent,
} from "../lib/frontmatter.ts";
+const VAULT = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
+
+/**
+ * `frontmatter_required` was declared in the manifest and documented as the
+ * place to add a note type, but no hook read it: the validator hardcoded
+ * three fields. These drive it from the declaration.
+ */
+describe("validateContent — frontmatter_required drives the check", () => {
+ const REQUIRED = parseFrontmatterRequired({
+ frontmatter_required: {
+ global: ["date", "description", "tags"],
+ "work-note": ["date", "status", "quarter"],
+ incident: ["date", "status", "quarter", "ticket", "severity", "role"],
+ person: ["date", "title"],
+ "1-1": ["date", "quarter"],
+ },
+ });
+ const note = (fm: string) => `---\n${fm}\n---\nShort.`;
+ const base = "date: 2026-01-01\ndescription: d\ntags:\n - x";
+ const missing = (w: string[]) =>
+ w.map((x) => /Missing `([^`]+)`/.exec(x)?.[1]).filter(Boolean).sort();
+
+ test("a work note must carry the work-note set", () => {
+ const w = validateContent(note(base), { required: REQUIRED, relPath: "work/active/A.md" });
+ assert.deepEqual(missing(w), ["quarter", "status"]);
+ });
+
+ test("an archived work note too", () => {
+ const w = validateContent(note(`${base}\nstatus: completed\nquarter: Q1-2026`), {
+ required: REQUIRED,
+ relPath: "work/archive/2026/A.md",
+ });
+ assert.deepEqual(w, []);
+ });
+
+ test("a 1:1 note needs quarter but not a work note's status, though it is tagged work-note", () => {
+ const w = validateContent(note("date: 2026-01-01\ndescription: d\ntags:\n - work-note"), {
+ required: REQUIRED,
+ relPath: "work/1-1/Alex 2026-01-01.md",
+ });
+ assert.deepEqual(missing(w), ["quarter"]);
+ });
+
+ test("a main incident note (tagged incident) needs the incident set", () => {
+ const w = validateContent(note("date: 2026-01-01\ndescription: d\ntags: [work-note, incident]\nstatus: open\nquarter: Q1-2026"), {
+ required: REQUIRED,
+ relPath: "work/incidents/INC-1.md",
+ });
+ assert.deepEqual(missing(w), ["role", "severity", "ticket"]);
+ });
+
+ test("an incident satellite (not tagged incident) carries the global set alone", () => {
+ const w = validateContent(note(`${base}`), {
+ required: REQUIRED,
+ relPath: "work/incidents/INC-1 RCA.md",
+ });
+ assert.deepEqual(w, []);
+ });
+
+ test("a person note needs title", () => {
+ const w = validateContent(note(base), { required: REQUIRED, relPath: "org/people/Alex Doe.md" });
+ assert.deepEqual(missing(w), ["title"]);
+ });
+
+ test("a note outside the typed folders gets the global set only", () => {
+ assert.deepEqual(validateContent(note(base), { required: REQUIRED, relPath: "brain/Patterns.md" }), []);
+ });
+
+ test("a custom global set replaces the built-in three", () => {
+ const w = validateContent(note("date: 2026-01-01"), {
+ required: parseFrontmatterRequired({ frontmatter_required: { global: ["date", "owner"] } }),
+ relPath: "brain/X.md",
+ });
+ assert.deepEqual(missing(w), ["owner"]);
+ });
+
+ test("no frontmatter_required → the built-in three, as before", () => {
+ const w = validateContent(note("date: 2026-01-01"), { required: {}, relPath: "work/active/A.md" });
+ assert.deepEqual(missing(w), ["description", "tags"]);
+ });
+
+ test("`update:` does not satisfy `date`", () => {
+ const w = validateContent(note("update: 2026-01-01\ndescription: d\ntags: [x]"));
+ assert.deepEqual(missing(w), ["date"]);
+ });
+
+ test("a key nested under another does not count", () => {
+ const w = validateContent(note("description: d\ntags: [x]\nmeta:\n date: 2026-01-01"));
+ assert.deepEqual(missing(w), ["date"]);
+ });
+
+ test("the shipped Work Note template declares every field the shipped manifest requires of a work note", () => {
+ const manifest = JSON.parse(readFileSync(join(VAULT, "vault-manifest.json"), "utf-8"));
+ const tpl = readFileSync(join(VAULT, "templates", "Work Note.md"), "utf-8");
+ const w = validateContent(tpl, { required: parseFrontmatterRequired(manifest), relPath: "work/active/New.md" });
+ assert.deepEqual(missing(w), [], w.join("\n"));
+ });
+});
+
+describe("readFrontmatterKeys and noteTypeForPath", () => {
+ test("tags as a block list, an inline list, or a scalar", () => {
+ assert.deepEqual(readFrontmatterKeys("tags:\n - a\n - \"b\"\ndate: x").tags, ["a", "b"]);
+ assert.deepEqual(readFrontmatterKeys("tags: [a, 'b']").tags, ["a", "b"]);
+ assert.deepEqual(readFrontmatterKeys("tags: a").tags, ["a"]);
+ });
+ test("a list item after another key is not a tag", () => {
+ assert.deepEqual(readFrontmatterKeys("tags:\n - a\naliases:\n - b").tags, ["a"]);
+ });
+ test("folder → type, with Windows separators", () => {
+ assert.equal(noteTypeForPath("work\\incidents\\X.md"), "incident");
+ assert.equal(noteTypeForPath("org/teams/Core.md"), "team");
+ assert.equal(noteTypeForPath("thinking/x.md"), null);
+ });
+});
+
describe("shouldSkipFile — skip rules", () => {
test("skips non-markdown", () => {
assert.equal(shouldSkipFile("/tmp/test.txt"), true);
diff --git a/.claude/scripts/tests/validate-write.test.ts b/.claude/scripts/tests/validate-write.test.ts
index 3e7c541..6eb7d6d 100644
--- a/.claude/scripts/tests/validate-write.test.ts
+++ b/.claude/scripts/tests/validate-write.test.ts
@@ -7,7 +7,7 @@ import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { fileURLToPath } from "node:url";
import { dirname, join, resolve } from "node:path";
-import { mkdtempSync, writeFileSync } from "node:fs";
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { runScript as spawnHook, rmTemp } from "./_helpers.ts";
@@ -259,3 +259,24 @@ describe("phantom-edge policy result (#117)", () => {
);
});
});
+
+describe("validate-write — required fields come from the manifest", () => {
+ test("a work note missing `quarter` is flagged when the manifest requires it", () => {
+ const vault = mkdtempSync(join(tmpdir(), "validate-write-manifest-"));
+ try {
+ mkdirSync(join(vault, "work", "active"), { recursive: true });
+ writeFileSync(
+ join(vault, "vault-manifest.json"),
+ JSON.stringify({ frontmatter_required: { "work-note": ["status", "quarter"] } }),
+ );
+ const note = join(vault, "work", "active", "A.md");
+ writeFileSync(note, "---\ndate: 2026-01-01\ndescription: d\ntags: [work-note]\nstatus: active\n---\nShort.");
+ const { stdout, code } = spawnHook(SCRIPT, { tool_input: { file_path: note } }, { CLAUDE_PROJECT_DIR: vault });
+ assert.equal(code, 0);
+ assert.match(stdout, /Missing `quarter`/);
+ assert.doesNotMatch(stdout, /Missing `status`/);
+ } finally {
+ rmTemp(vault);
+ }
+ });
+});
diff --git a/.claude/scripts/validate-write.ts b/.claude/scripts/validate-write.ts
index bdc930e..87d1167 100644
--- a/.claude/scripts/validate-write.ts
+++ b/.claude/scripts/validate-write.ts
@@ -20,6 +20,7 @@ import {
import {
countTicketIdWikilinks,
isBlockedMemoryPath,
+ parseFrontmatterRequired,
shouldSkipFile,
validateContent,
} from "./lib/frontmatter.ts";
@@ -154,14 +155,26 @@ try {
debug(`validate: could not read ${filePath}`);
process.exit(0);
}
-const warnings = validateContent(content);
+const relPath = filePathFwd.startsWith(vaultRoot + "/")
+ ? filePathFwd.slice(vaultRoot.length + 1)
+ : filePathFwd;
+// The required fields come from the manifest's frontmatter_required, the
+// same declaration the docs point at; an unreadable manifest falls back to
+// the three global fields.
+let manifest: unknown = null;
+try {
+ manifest = JSON.parse(readFileSync(join(vaultRoot, "vault-manifest.json"), "utf-8"));
+} catch {
+ /* defaults */
+}
+const warnings = validateContent(content, {
+ required: parseFrontmatterRequired(manifest),
+ relPath,
+});
debug(`validate: ${filePath} — ${warnings.length} warning(s)`);
const blocks: string[] = [];
const policyResults: PolicyResult[] = [];
-const relPath = filePathFwd.startsWith(vaultRoot + "/")
- ? filePathFwd.slice(vaultRoot.length + 1)
- : filePathFwd;
if (warnings.length > 0) {
const hintList = warnings.map((w) => ` - ${w}`).join("\n");
diff --git a/templates/Work Note.md b/templates/Work Note.md
index 74d425a..4729323 100644
--- a/templates/Work Note.md
+++ b/templates/Work Note.md
@@ -2,6 +2,7 @@
date: "{{date}}"
description:
project:
+quarter:
status: active
tags:
- work-note