Skip to content

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

feat: MEMORY.md as a rebuildable index (generator + regen tests) (#136)

Brenno Ferrariba8cb7444c93
diff --git a/.claude/commands/om-wrap-up.md b/.claude/commands/om-wrap-up.md
index 6c5ef8f..35321e6 100644
--- a/.claude/commands/om-wrap-up.md
+++ b/.claude/commands/om-wrap-up.md
@@ -38,6 +38,7 @@ For each note created or modified this session:
- `work/Index.md` — are new notes linked? Are completed projects in the right section?
- `brain/Memories.md` — does Recent Context reflect what happened this session?
+- Auto-memory index — if brain/ notes were added or their descriptions changed, REGENERATE the index instead of hand-editing it: `node --experimental-strip-types .claude/scripts/generate-memory-index.ts > <your ~/.claude/projects/<slug>/memory/MEMORY.md path>`. MEMORY.md is a derived view (pointers only); hand edits get overwritten by design.
- `org/People & Context.md` — any new people or relationship changes to capture?
- `perf/Brag Doc.md` — any wins or achievements from this session?
- `Home.md` — are embedded Bases still valid?
diff --git a/.claude/scripts/generate-memory-index.ts b/.claude/scripts/generate-memory-index.ts
new file mode 100644
index 0000000..ba30f7c
--- /dev/null
+++ b/.claude/scripts/generate-memory-index.ts
@@ -0,0 +1,49 @@
+#!/usr/bin/env node
+/**
+ * Emit the auto-memory MEMORY.md index to stdout (#125), derived from
+ * brain/ frontmatter. The caller owns the destination — the memory dir
+ * path is session-specific (~/.claude/projects/<slug>/memory/), so the
+ * agent redirects:
+ *
+ * node --experimental-strip-types .claude/scripts/generate-memory-index.ts \
+ * > ~/.claude/projects/<slug>/memory/MEMORY.md
+ *
+ * Run from the vault root (or with CLAUDE_PROJECT_DIR set).
+ */
+
+import { readdirSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+import { isMainModule } from "./lib/main-guard.ts";
+import {
+ extractFrontmatterField,
+ isMarkdownFilename,
+} from "./lib/session-start.ts";
+import { generateMemoryIndex, type BrainNote } from "./lib/memory-index.ts";
+
+function main(): void {
+ const root = process.env["CLAUDE_PROJECT_DIR"] || process.cwd();
+ let entries: string[] = [];
+ try {
+ entries = readdirSync(join(root, "brain")).filter((n) =>
+ isMarkdownFilename(n),
+ );
+ } catch {
+ process.stderr.write("brain/ not found — run from the vault root.\n");
+ process.exit(1);
+ }
+ const notes: BrainNote[] = entries.map((f) => {
+ let description: string | null = null;
+ try {
+ description = extractFrontmatterField(
+ readFileSync(join(root, "brain", f), "utf-8"),
+ "description",
+ );
+ } catch {
+ /* unreadable → no description */
+ }
+ return { name: f.replace(/\.md$/i, ""), description };
+ });
+ process.stdout.write(generateMemoryIndex(notes));
+}
+
+if (isMainModule(import.meta.url)) main();
diff --git a/.claude/scripts/lib/memory-index.ts b/.claude/scripts/lib/memory-index.ts
new file mode 100644
index 0000000..7aeaf4a
--- /dev/null
+++ b/.claude/scripts/lib/memory-index.ts
@@ -0,0 +1,45 @@
+/**
+ * MEMORY.md generation (#125) — the auto-memory index as a DERIVED view.
+ *
+ * CLAUDE.md doctrine: `~/.claude/.../memory/MEMORY.md` is an auto-loaded
+ * index ONLY — pointers to brain/ topic notes, never content. The doctrine
+ * only holds if the index is derivable: the moment authored knowledge
+ * accumulates there, it forks the source of truth and silently desyncs
+ * from the vault. This module makes it derivable — deterministic output
+ * from brain/ sources, byte-for-byte reproducible, so nothing authored
+ * can be lost on regeneration because nothing authored is permitted.
+ */
+
+export type BrainNote = {
+ /** Note name without extension, e.g. "Gotchas". */
+ readonly name: string;
+ /** Frontmatter description, or null when absent. */
+ readonly description: string | null;
+};
+
+export const MEMORY_INDEX_HEADER =
+ "All durable memory lives in the vault under `brain/` per CLAUDE.md. " +
+ "This index points to vault topic notes — never write content here. " +
+ "Regenerated from brain/ frontmatter (see `generate-memory-index.ts`); " +
+ "hand edits will be overwritten.";
+
+/**
+ * Render the pointer-list index. Deterministic: notes are sorted by name
+ * (case-insensitive), the same input always produces the same bytes.
+ */
+export function generateMemoryIndex(notes: readonly BrainNote[]): string {
+ // Codepoint comparison, not locale collation (collation rules can vary
+ // across ICU versions and would leak into the bytes); case-insensitive
+ // primary with a case-sensitive tie-break so "Foo" vs "foo" still has
+ // ONE canonical order regardless of input order.
+ const cmp = (x: string, y: string): number => (x < y ? -1 : x > y ? 1 : 0);
+ const sorted = [...notes].sort(
+ (a, b) =>
+ cmp(a.name.toLowerCase(), b.name.toLowerCase()) || cmp(a.name, b.name),
+ );
+ const lines = [MEMORY_INDEX_HEADER, ""];
+ for (const n of sorted) {
+ lines.push(`- [[brain/${n.name}]] — ${n.description ?? "(no description)"}`);
+ }
+ return lines.join("\n") + "\n";
+}
diff --git a/.claude/scripts/tests/memory-index.test.ts b/.claude/scripts/tests/memory-index.test.ts
new file mode 100644
index 0000000..460a5f2
--- /dev/null
+++ b/.claude/scripts/tests/memory-index.test.ts
@@ -0,0 +1,78 @@
+/**
+ * Tests for the MEMORY.md regen property (#125): the index is a DERIVED
+ * view — deterministic, pointer-only, rebuildable with zero authored loss
+ * because nothing authored is permitted in it.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import {
+ MEMORY_INDEX_HEADER,
+ generateMemoryIndex,
+ type BrainNote,
+} from "../lib/memory-index.ts";
+
+const NOTES: readonly BrainNote[] = [
+ { name: "Patterns", description: "Recurring patterns and conventions" },
+ { name: "Gotchas", description: "Things that bit before" },
+ { name: "Key Decisions", description: null },
+];
+
+describe("generateMemoryIndex", () => {
+ test("deterministic: same input → byte-identical output, order-independent", () => {
+ const a = generateMemoryIndex(NOTES);
+ const b = generateMemoryIndex([...NOTES].reverse());
+ assert.equal(a, b);
+ });
+
+ test("pointer-only: every content line is traceable to an input note", () => {
+ const out = generateMemoryIndex(NOTES);
+ const contentLines = out
+ .split("\n")
+ .filter((l) => l.startsWith("- "));
+ assert.equal(contentLines.length, NOTES.length);
+ for (const line of contentLines) {
+ assert.match(line, /^- \[\[brain\/.+\]\] — /);
+ const name = line.match(/^\- \[\[brain\/(.+?)\]\]/)?.[1];
+ assert.ok(NOTES.some((n) => n.name === name), `untraceable line: ${line}`);
+ }
+ });
+
+ test("regen property: delete-and-rebuild loses nothing authored (there is nothing authored)", () => {
+ const first = generateMemoryIndex(NOTES);
+ // Simulate deletion + regeneration from the same sources.
+ const rebuilt = generateMemoryIndex(NOTES);
+ assert.equal(first, rebuilt);
+ // Header declares the contract.
+ assert.ok(first.startsWith(MEMORY_INDEX_HEADER));
+ assert.match(first, /hand edits will be overwritten/);
+ });
+
+ test("sorted case-insensitively; missing description gets the fallback", () => {
+ const out = generateMemoryIndex(NOTES);
+ const lines = out.split("\n").filter((l) => l.startsWith("- "));
+ assert.match(lines[0] ?? "", /Gotchas/);
+ assert.match(lines[1] ?? "", /Key Decisions.*\(no description\)/);
+ assert.match(lines[2] ?? "", /Patterns/);
+ });
+
+ test("empty brain → header only, no dangling lines", () => {
+ const out = generateMemoryIndex([]);
+ assert.equal(out, MEMORY_INDEX_HEADER + "\n\n");
+ });
+});
+
+describe("determinism under case-collisions", () => {
+ test("names differing only by case get one canonical order, input-order-independent", () => {
+ const a = generateMemoryIndex([
+ { name: "foo", description: "lower" },
+ { name: "Foo", description: "upper" },
+ ]);
+ const b = generateMemoryIndex([
+ { name: "Foo", description: "upper" },
+ { name: "foo", description: "lower" },
+ ]);
+ assert.equal(a, b);
+ assert.ok(a.indexOf("[[brain/Foo]]") < a.indexOf("[[brain/foo]]"));
+ });
+});