A self-organizing Obsidian vault that gives AI coding agents persistent memory.
TypeScript ai-agentsclaude-codecodex-cligemini-cliknowledge-managementobsidianobsidian-vaultpersistent-memorysecond-braintemplate
feat: wikilink parser lib + vault-wide broken-link ratchet gate (#128)
Brenno Ferrari5edf1b1244ea
diff --git a/.claude/scripts/lib/wikilinks.ts b/.claude/scripts/lib/wikilinks.tsnew file mode 100644index 0000000..915d3e1--- /dev/null+++ b/.claude/scripts/lib/wikilinks.ts@@ -0,0 +1,216 @@+/**+ * Wikilink extraction + resolution — pure helpers behind the vault's+ * broken-link zero gate (tests/vault-wikilinks.test.ts).+ *+ * Resolution implements the vault's link semantics, deliberately including+ * one assumption beyond stock Obsidian: a `[[target]]` also RESOLVES when+ * some file lists the target in its frontmatter `aliases:`. Alias links+ * are the vault's dominant idiom — `[[obsidian-mind]]` (×144) and+ * `[[ShardMind]]` (×138) point at project READMEs via aliases — and the+ * graph treats them as edges, so the gate must too.+ *+ * Rules:+ * - Fenced code blocks AND inline code spans are stripped before+ * extraction — CLAUDE.md and the skills carry literal `[[...]]`+ * syntax examples that are documentation, not edges.+ * - `!` embed prefix, `|alias` tails (including the table-escaped `\|`+ * form), `#heading` and `#^block` fragments are stripped from targets.+ * - `[[#Heading]]` (same-file anchor) always resolves.+ * - `{{placeholder}}` targets (templates) and non-note asset targets+ * (.png, .canvas, …) are ignored — the gate covers note edges only.+ * - `./` / `../` targets resolve against the source file's directory;+ * `/`-containing targets also resolve by path suffix (Obsidian+ * shortest-path semantics, approximated); bare targets resolve by+ * case-insensitive basename or alias.+ */++const ASSET_EXTENSIONS = new Set([+ "png",+ "jpg",+ "jpeg",+ "gif",+ "svg",+ "webp",+ "pdf",+ "canvas",+ "base",+ "excalidraw",+ "html",+ "htm",+ "mp3",+ "mp4",+ "mov",+ "zip",+]);++/**+ * Remove fenced code blocks (``` / ~~~) and inline code spans so literal+ * wikilink examples inside them never count as edges. Fence-aware line+ * scan (not a lazy regex) so an unclosed fence strips to EOF instead of+ * leaking the tail.+ */+export function stripCodeRegions(content: string): string {+ const out: string[] = [];+ let inFence = false;+ let fenceMarker = "";+ for (const line of content.split("\n")) {+ const trimmed = line.trimStart();+ if (inFence) {+ if (trimmed.startsWith(fenceMarker)) inFence = false;+ continue;+ }+ if (trimmed.startsWith("```") || trimmed.startsWith("~~~")) {+ inFence = true;+ fenceMarker = trimmed.slice(0, 3);+ continue;+ }+ // Inline code spans: remove `...` runs, including multi-backtick+ // spans (``…`` — CommonMark closes N backticks with exactly N, and+ // shorter runs are legal INSIDE the span, so ``[[x]]`` and+ // ``code with ` inside`` must both strip whole). Content charwise+ // forbids starting the same-length run early; the trailing (?!`)+ // pins the closer to an exact-length run.+ out.push(line.replace(/(`+)(?:(?!\1)[^\n])*?\1(?!`)/g, ""));+ }+ return out.join("\n");+}++/**+ * Extract resolution targets from every `[[...]]` in the content+ * (code regions pre-stripped). Returns raw target strings — alias tails,+ * fragments, and embed prefixes removed; empties/placeholders/assets+ * dropped.+ */+export function extractWikilinkTargets(content: string): string[] {+ const targets: string[] = [];+ const re = /!?\[\[([^\[\]\n]+?)\]\]/g;+ for (const m of stripCodeRegions(content).matchAll(re)) {+ let inner = m[1] ?? "";+ // Table-escaped alias pipes — both forms Obsidian accepts inside+ // tables: backslash (`[[Target\|alias]]`) and HTML entity+ // (`[[Target|alias]]`). Normalize before splitting so the+ // target doesn't keep a trailing `\` or `&`.+ inner = inner.replaceAll("\\|", "|").replaceAll("|", "|");+ const target = (inner.split("|")[0] ?? "").split("#")[0]?.trim() ?? "";+ if (target === "") continue; // [[#heading]] / [[|alias]] — same-file+ if (target.includes("{{")) continue; // template placeholder+ const ext = target.includes(".")+ ? (target.split(".").pop() ?? "").toLowerCase()+ : "";+ if (ASSET_EXTENSIONS.has(ext)) continue;+ targets.push(target);+ }+ return targets;+}++/**+ * Minimal frontmatter `aliases:` reader — YAML block list and inline+ * `[a, b]` forms, quoted or bare. Returns [] when absent/malformed.+ */+export function extractAliases(content: string): string[] {+ if (!content.startsWith("---")) return [];+ const end = content.indexOf("\n---", 3);+ if (end === -1) return [];+ const fm = content.slice(3, end);+ const lines = fm.split("\n");+ const idx = lines.findIndex((l) => /^aliases:\s*(\[.*\])?\s*$/.test(l.trim()) || /^aliases:\s*\[/.test(l.trim()));+ if (idx === -1) return [];+ const head = lines[idx]?.trim() ?? "";+ const unquote = (s: string): string => {+ const t = s.trim();+ if (+ (t.startsWith('"') && t.endsWith('"')) ||+ (t.startsWith("'") && t.endsWith("'"))+ ) {+ return t.slice(1, -1);+ }+ return t;+ };+ const inline = head.match(/^aliases:\s*\[(.*)\]\s*$/);+ if (inline) {+ return (inline[1] ?? "")+ .split(",")+ .map(unquote)+ .filter((s) => s !== "");+ }+ const out: string[] = [];+ for (let i = idx + 1; i < lines.length; i++) {+ const line = lines[i] ?? "";+ const item = line.match(/^\s+-\s+(.*)$/);+ if (!item) break; // end of the block list+ const value = unquote(item[1] ?? "");+ if (value !== "") out.push(value);+ }+ return out;+}++const stripMdExt = (p: string): string => p.replace(/\.md$/i, "");++/** POSIX-normalize `dir/../x` style paths; returns null when escaping root. */+function normalizeRelative(path: string): string | null {+ const parts: string[] = [];+ for (const seg of path.split("/")) {+ if (seg === "" || seg === ".") continue;+ if (seg === "..") {+ if (parts.length === 0) return null;+ parts.pop();+ continue;+ }+ parts.push(seg);+ }+ return parts.join("/");+}++export type Resolver = (target: string, sourceRelPath: string) => boolean;++/**+ * Build a resolver over the vault's file set.+ *+ * @param files vault-relative POSIX paths of every .md file (target set)+ * @param aliasesByFile frontmatter aliases per file (same path keys)+ */+export function buildResolver(+ files: readonly string[],+ aliasesByFile: ReadonlyMap<string, readonly string[]>,+): Resolver {+ const pathSet = new Set(files.map((f) => stripMdExt(f).toLowerCase()));+ const basenames = new Set(+ files.map((f) => {+ const base = f.split("/").pop() ?? f;+ return stripMdExt(base).toLowerCase();+ }),+ );+ const aliases = new Set(+ [...aliasesByFile.values()].flat().map((a) => a.toLowerCase()),+ );++ return (target: string, sourceRelPath: string): boolean => {+ const clean = stripMdExt(target.replace(/\\/g, "/")).toLowerCase();++ // Source-relative (./ or ../) — resolve against the source's dir.+ if (clean.startsWith("./") || clean.startsWith("../")) {+ const sourceDir = sourceRelPath+ .replace(/\\/g, "/")+ .toLowerCase()+ .split("/")+ .slice(0, -1)+ .join("/");+ const resolved = normalizeRelative(+ sourceDir === "" ? clean : `${sourceDir}/${clean}`,+ );+ return resolved !== null && pathSet.has(resolved);+ }++ // Path-form target — exact vault path or unambiguous suffix.+ if (clean.includes("/")) {+ if (pathSet.has(clean)) return true;+ for (const p of pathSet) {+ if (p.endsWith(`/${clean}`)) return true;+ }+ return false;+ }++ // Bare name — basename or alias.+ return basenames.has(clean) || aliases.has(clean);+ };+}diff --git a/.claude/scripts/tests/vault-wikilinks.test.ts b/.claude/scripts/tests/vault-wikilinks.test.tsnew file mode 100644index 0000000..cd81f8c--- /dev/null+++ b/.claude/scripts/tests/vault-wikilinks.test.ts@@ -0,0 +1,120 @@+/**+ * Broken-wikilink RATCHET GATE (#108) — scans the REAL vault and asserts+ * the number of unresolvable wikilinks never EXCEEDS the recorded baseline+ * (`wikilink-baseline.json`).+ *+ * Why a ratchet and not a zero gate: user vaults legitimately carry gray+ * links (notes-to-be — a wikilink to a note you haven't written yet is an+ * Obsidian workflow, not a bug). The gate therefore fails only on+ * REGRESSION — a split, rename, or new note that breaks links that used+ * to resolve. The template repo itself ships at baseline 0; a vault+ * adopting this test with existing gray links records its own count in+ * the baseline file (the failure message says how) and ratchets DOWN+ * from there — lowering the baseline is always a one-line change, raising+ * it should hurt.+ *+ * Scan rules (mirror lib/wikilinks.ts semantics):+ * - target set: every vault .md except machinery/config trees+ * - source set: additionally excludes templates/ (placeholder links by+ * design) and thinking/session-logs/ (transcripts)+ * - resolution: basename OR frontmatter alias OR path suffix OR+ * source-relative — see lib/wikilinks.ts header+ */++import { test, describe } from "node:test";+import assert from "node:assert/strict";+import { readFileSync, readdirSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import {+ extractWikilinkTargets,+ extractAliases,+ buildResolver,+} from "../lib/wikilinks.ts";++const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");+const BASELINE_PATH = resolve(+ dirname(fileURLToPath(import.meta.url)),+ "wikilink-baseline.json",+);++const TARGET_SKIP = [+ ".git",+ ".obsidian",+ ".claude",+ ".codex",+ ".gemini",+ ".github",+ ".shardmind",+ "node_modules",+];+const SOURCE_SKIP_EXTRA = ["templates", "thinking/session-logs"];++function walkMd(root: string): string[] {+ const out: string[] = [];+ function walk(rel: string): void {+ let entries;+ try {+ entries = readdirSync(join(root, rel), { withFileTypes: true });+ } catch {+ return;+ }+ for (const e of entries) {+ const r = rel === "" ? e.name : `${rel}/${e.name}`;+ if (TARGET_SKIP.some((s) => r === s || r.startsWith(`${s}/`))) continue;+ if (e.isDirectory()) walk(r);+ else if (e.isFile() && /\.md$/i.test(e.name)) out.push(r);+ }+ }+ walk("");+ return out;+}++describe("vault wikilinks — ratchet gate", () => {+ test("broken wikilinks never exceed the recorded baseline", () => {+ const baseline = (+ JSON.parse(readFileSync(BASELINE_PATH, "utf-8")) as {+ allowedBroken: number;+ }+ ).allowedBroken;++ const files = walkMd(repoRoot);+ assert.ok(+ files.length > 10,+ `sanity: expected a real vault, got ${files.length} files`,+ );++ const aliasesByFile = new Map<string, readonly string[]>();+ const contents = new Map<string, string>();+ for (const f of files) {+ const c = readFileSync(join(repoRoot, f), { encoding: "utf-8" });+ contents.set(f, c);+ const a = extractAliases(c);+ if (a.length > 0) aliasesByFile.set(f, a);+ }++ const resolves = buildResolver(files, aliasesByFile);+ const skippedSource = (f: string): boolean =>+ SOURCE_SKIP_EXTRA.some((s) => f === s || f.startsWith(`${s}/`));++ const broken: string[] = [];+ for (const f of files) {+ if (skippedSource(f)) continue;+ for (const t of extractWikilinkTargets(contents.get(f) ?? "")) {+ if (!resolves(t, f)) broken.push(` ${f} → [[${t}]]`);+ }+ }++ assert.ok(+ broken.length <= baseline,+ `${broken.length} broken wikilink(s) exceed the baseline of ${baseline} — a change in this branch broke links that used to resolve. Fix the link, add an alias to the target, or create the note:\n${broken.join("\n")}\n(If these are intentional gray links in an adopting vault, raise allowedBroken in ${BASELINE_PATH} consciously.)`,+ );++ if (broken.length < baseline) {+ // Improvement — not a failure, but say so, so the ratchet tightens.+ console.log(+ `wikilink ratchet: ${broken.length} broken < baseline ${baseline} — lower allowedBroken in wikilink-baseline.json to lock the gain.`,+ );+ }+ });+});diff --git a/.claude/scripts/tests/wikilink-baseline.json b/.claude/scripts/tests/wikilink-baseline.jsonnew file mode 100644index 0000000..af65ed7--- /dev/null+++ b/.claude/scripts/tests/wikilink-baseline.json@@ -0,0 +1,3 @@+{+ "allowedBroken": 0+}diff --git a/.claude/scripts/tests/wikilinks.test.ts b/.claude/scripts/tests/wikilinks.test.tsnew file mode 100644index 0000000..e16f041--- /dev/null+++ b/.claude/scripts/tests/wikilinks.test.ts@@ -0,0 +1,181 @@+/**+ * Unit tests for lib/wikilinks.ts — the parser + resolver behind the+ * vault's broken-link zero gate. Fixture strings only; the real-vault+ * scan lives in vault-wikilinks.test.ts.+ */++import { test, describe } from "node:test";+import assert from "node:assert/strict";+import {+ stripCodeRegions,+ extractWikilinkTargets,+ extractAliases,+ buildResolver,+} from "../lib/wikilinks.ts";++describe("stripCodeRegions", () => {+ test("removes fenced blocks including their wikilinks", () => {+ const md = "before\n```md\n[[Fenced Link]]\n```\nafter";+ const out = stripCodeRegions(md);+ assert.ok(!out.includes("Fenced Link"));+ assert.ok(out.includes("before"));+ assert.ok(out.includes("after"));+ });+ test("removes tilde fences", () => {+ assert.ok(+ !stripCodeRegions("~~~\n[[X]]\n~~~").includes("X"),+ );+ });+ test("unclosed fence strips to EOF", () => {+ assert.ok(!stripCodeRegions("```\n[[X]]\n[[Y]]").includes("[["));+ });+ test("removes inline code spans, keeps surrounding text", () => {+ const out = stripCodeRegions("use `[[wikilinks]]` for links to [[Real]]");+ assert.ok(!out.includes("wikilinks"));+ assert.ok(out.includes("[[Real]]"));+ });+ test("removes multi-backtick code spans (CommonMark N-closes-N)", () => {+ const out = stripCodeRegions(+ "double ``[[Not A Link]]`` and triple ```[[Also Not]]``` beside [[Real]]",+ );+ assert.ok(!out.includes("Not A Link"));+ assert.ok(!out.includes("Also Not"));+ assert.ok(out.includes("[[Real]]"));+ });+ test("spans containing lone backticks strip whole (`` x ` y ``)", () => {+ const out = stripCodeRegions("odd ``code with ` inside`` then [[Real]]");+ assert.ok(out.includes("[[Real]]"));+ assert.ok(!out.includes("code with"));+ });+});++describe("extractWikilinkTargets", () => {+ test("plain link", () => {+ assert.deepEqual(extractWikilinkTargets("see [[North Star]]"), [+ "North Star",+ ]);+ });+ test("alias tail stripped", () => {+ assert.deepEqual(extractWikilinkTargets("[[North Star|goals]]"), [+ "North Star",+ ]);+ });+ test("table-escaped alias pipe stripped (no trailing backslash)", () => {+ assert.deepEqual(+ extractWikilinkTargets("| [[North Star\\|goals]] |"),+ ["North Star"],+ );+ });+ test("embed prefix accepted", () => {+ assert.deepEqual(extractWikilinkTargets("![[North Star]]"), [+ "North Star",+ ]);+ });+ test("heading and block fragments stripped", () => {+ assert.deepEqual(+ extractWikilinkTargets("[[North Star#Goals]] and [[Note#^abc123]]"),+ ["North Star", "Note"],+ );+ });+ test("same-file heading link is not a target", () => {+ assert.deepEqual(extractWikilinkTargets("[[#Local Section]]"), []);+ });+ test("template placeholders ignored", () => {+ assert.deepEqual(extractWikilinkTargets("[[{{project}}]]"), []);+ });+ test("asset embeds ignored, note-like dots kept", () => {+ assert.deepEqual(+ extractWikilinkTargets(+ "![[chart.png]] [[Dashboard.base]] [[example.com Analytics]]",+ ),+ ["example.com Analytics"],+ );+ });+ test("relative path target preserved", () => {+ assert.deepEqual(extractWikilinkTargets("[[../personas]]"), [+ "../personas",+ ]);+ });+});++describe("extractAliases", () => {+ test("block list form", () => {+ const md = '---\ndate: 2026-01-01\naliases:\n - Soul\n - "Vigil"\n---\nbody';+ assert.deepEqual(extractAliases(md), ["Soul", "Vigil"]);+ });+ test("inline array form", () => {+ const md = "---\naliases: [obsidian-mind, 'OM']\n---\n";+ assert.deepEqual(extractAliases(md), ["obsidian-mind", "OM"]);+ });+ test("no frontmatter / no aliases → empty", () => {+ assert.deepEqual(extractAliases("# Title"), []);+ assert.deepEqual(extractAliases("---\ndate: x\n---\n"), []);+ });+ test("block list ends at next scalar field", () => {+ const md = "---\naliases:\n - One\ntags:\n - brain\n---\n";+ assert.deepEqual(extractAliases(md), ["One"]);+ });+});++describe("buildResolver", () => {+ const files = [+ "brain/North Star.md",+ "projects/obsidian-mind/README.md",+ "reference/cv-system/tracks/apple-audio.md",+ "work/career/inbound-recruiter-log.md",+ ];+ const aliases = new Map<string, readonly string[]>([+ ["projects/obsidian-mind/README.md", ["obsidian-mind"]],+ ["work/career/inbound-recruiter-log.md", ["Inbound Recruiter Log"]],+ ]);+ const resolves = buildResolver(files, aliases);++ test("basename match, case-insensitive", () => {+ assert.ok(resolves("North Star", "Home.md"));+ assert.ok(resolves("north star", "Home.md"));+ });+ test("alias match", () => {+ assert.ok(resolves("obsidian-mind", "Home.md"));+ assert.ok(resolves("inbound recruiter log", "Home.md"));+ });+ test("path suffix match", () => {+ assert.ok(resolves("obsidian-mind/README", "Home.md"));+ assert.ok(resolves("projects/obsidian-mind/README", "Home.md"));+ });+ test("relative target resolves against source dir", () => {+ assert.ok(+ resolves("../tracks/apple-audio", "reference/cv-system/regions/de.md"),+ );+ assert.ok(+ !resolves(+ "../../tracks/apple-audio",+ "reference/cv-system/regions/de.md",+ ),+ "one ../ too many must NOT resolve",+ );+ });+ test("relative target escaping the vault root does not resolve", () => {+ assert.ok(!resolves("../../../../etc/passwd", "brain/North Star.md"));+ });+ test("unknown name does not resolve", () => {+ assert.ok(!resolves("Nonexistent Note", "Home.md"));+ });+ test("explicit .md extension accepted", () => {+ assert.ok(resolves("North Star.md", "Home.md"));+ });+});++describe("extractWikilinkTargets — parser gaps found in the field (2026-07-14)", () => {+ test("HTML-entity escaped pipe (|) in tables", () => {+ assert.deepEqual(+ extractWikilinkTargets("| [[North Star|goals]] |"),+ ["North Star"],+ );+ });+ test("html artifact targets are not note edges", () => {+ assert.deepEqual(+ extractWikilinkTargets("[[2026-01-01 Briefing (Thing).html]]"),+ [],+ );+ });+});