Skip to content

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

feat: inject brain topic index with empty-stub markers in SessionStart (#47)

Brenno Ferrari79ac3bcdb439
diff --git a/.claude/scripts/lib/session-start.ts b/.claude/scripts/lib/session-start.ts
index e9b1da5..53007af 100644
--- a/.claude/scripts/lib/session-start.ts
+++ b/.claude/scripts/lib/session-start.ts
@@ -61,3 +61,109 @@ export function isSkippedPath(
(p) => pathRel === p || pathRel.startsWith(p + "/"),
);
}
+
+/**
+ * Escape regex metacharacters in a string so it can be embedded safely
+ * inside a `new RegExp(...)` pattern as a literal.
+ */
+function escapeRegex(s: string): string {
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+/**
+ * Find the closing `---` delimiter of a YAML frontmatter block. The input
+ * is assumed to start with `---` (caller checks). Returns the index of the
+ * newline before the closing delimiter, or -1 if the block is unterminated.
+ *
+ * Matches only a full delimiter line (`\n---\n`, `\n---\r\n`, or `\n---` at
+ * EOF) so body content like `---foo` after a newline is not treated as the
+ * terminator.
+ */
+function findFrontmatterEnd(content: string): number {
+ const m = content.slice(3).match(/\n---(?:\r?\n|$)/);
+ return m && m.index !== undefined ? m.index + 3 : -1;
+}
+
+/**
+ * Extract a string value for `field` from YAML frontmatter at the top of
+ * a markdown document. Supports quoted ("..."), single-quoted ('...'),
+ * and bare values on the same line as the key. Returns null when the
+ * frontmatter block or field is absent.
+ *
+ * This is a deliberately small parser — just enough for one-line string
+ * fields like `description:`. Multi-line/block YAML is out of scope.
+ * Handles CRLF line endings and escapes regex metacharacters in `field`.
+ */
+export function extractFrontmatterField(
+ content: string,
+ field: string,
+): string | null {
+ if (!content.startsWith("---")) return null;
+ const end = findFrontmatterEnd(content);
+ if (end === -1) return null;
+ const fm = content.slice(3, end);
+ const re = new RegExp(
+ `^${escapeRegex(field)}:[ \\t]*(.*?)[ \\t]*\\r?$`,
+ "m",
+ );
+ const m = fm.match(re);
+ if (!m) return null;
+ const raw = m[1] ?? "";
+ if (raw === "") return null;
+ if (
+ (raw.startsWith('"') && raw.endsWith('"')) ||
+ (raw.startsWith("'") && raw.endsWith("'"))
+ ) {
+ return raw.slice(1, -1);
+ }
+ return raw;
+}
+
+/**
+ * Return the body of a markdown document with its leading YAML frontmatter
+ * stripped. If there's no frontmatter block, returns the input unchanged.
+ * Handles both LF and CRLF delimiters.
+ */
+export function stripFrontmatter(content: string): string {
+ if (!content.startsWith("---")) return content;
+ const end = findFrontmatterEnd(content);
+ if (end === -1) return content;
+ const rest = content.slice(end);
+ const m = rest.match(/^\n---(\r?\n|$)/);
+ return m ? rest.slice(m[0].length) : rest;
+}
+
+/**
+ * True if the body contains at least one list item with text content —
+ * i.e. a bullet like `- foo`, not a bare `-` placeholder. Brain topic
+ * notes are list-shaped by template, so this is the clearest signal of
+ * "has the user actually added anything here yet?"
+ */
+export function hasBrainContent(body: string): boolean {
+ return /^[ \t]*[-*+][ \t]+\S.*$/m.test(body);
+}
+
+/**
+ * Format the "Brain Topics" section — one line per brain/ note with its
+ * description from frontmatter, so Claude sees what topic notes exist
+ * without loading their full content. Omits North Star (already loaded
+ * in its own section) and Memories (an index that just points here).
+ * Appends "(empty)" when the note has no filled bullets, so Claude
+ * knows not to waste a read on a stub.
+ */
+export function formatBrainIndex(
+ entries: readonly {
+ readonly name: string;
+ readonly description: string | null;
+ readonly hasContent: boolean;
+ }[],
+): string {
+ const lines = entries
+ .filter((e) => e.name !== "North Star" && e.name !== "Memories")
+ .map((e) => {
+ const desc = e.description ?? "(no description)";
+ const suffix = e.hasContent ? "" : " (empty)";
+ return `- [[${e.name}]] — ${desc}${suffix}`;
+ });
+ return lines.length > 0 ? lines.join("\n") : "(none)";
+}
diff --git a/.claude/scripts/session-start.ts b/.claude/scripts/session-start.ts
index 05c8903..133e820 100644
--- a/.claude/scripts/session-start.ts
+++ b/.claude/scripts/session-start.ts
@@ -23,6 +23,10 @@ import {
formatActiveWork,
formatRecentChanges,
isSkippedPath,
+ extractFrontmatterField,
+ formatBrainIndex,
+ stripFrontmatter,
+ hasBrainContent,
} from "./lib/session-start.ts";
const cwd =
@@ -99,6 +103,33 @@ function openTasks(): string {
return take(r.stdout, 10);
}
+function brainIndex(): string {
+ let entries: Dirent[];
+ try {
+ entries = readdirSync("brain", { withFileTypes: true });
+ } catch {
+ return "(none)";
+ }
+ const files = entries
+ .filter((e) => e.isFile() && e.name.endsWith(".md"))
+ .map((e) => e.name)
+ .sort();
+ const parsed = files.map((f) => {
+ const name = f.replace(/\.md$/, "");
+ let description: string | null = null;
+ let hasContent = false;
+ try {
+ const content = readFileSync(join("brain", f), { encoding: "utf-8" });
+ description = extractFrontmatterField(content, "description");
+ hasContent = hasBrainContent(stripFrontmatter(content));
+ } catch {
+ /* unreadable file → show name with no description, treat as empty */
+ }
+ return { name, description, hasContent };
+ });
+ return formatBrainIndex(parsed);
+}
+
function activeWork(): string {
let entries: Dirent[];
try {
@@ -146,6 +177,9 @@ const sections = [
"### North Star (current goals)",
northStar(),
"",
+ "### Brain Topics (read on demand)",
+ brainIndex(),
+ "",
"### Recent Changes (last 48h)",
recentChanges(),
"",
diff --git a/.claude/scripts/tests/session-start.test.ts b/.claude/scripts/tests/session-start.test.ts
index 0240230..8b9c0e3 100644
--- a/.claude/scripts/tests/session-start.test.ts
+++ b/.claude/scripts/tests/session-start.test.ts
@@ -13,6 +13,10 @@ import {
formatActiveWork,
formatRecentChanges,
isSkippedPath,
+ extractFrontmatterField,
+ formatBrainIndex,
+ stripFrontmatter,
+ hasBrainContent,
} from "../lib/session-start.ts";
describe("take", () => {
@@ -93,3 +97,139 @@ describe("isSkippedPath", () => {
assert.equal(isSkippedPath(".git/foo", []), false);
});
});
+
+describe("extractFrontmatterField", () => {
+ test("extracts double-quoted string value", () => {
+ const content = '---\ndescription: "hello world"\ntags:\n - brain\n---\n\n# body';
+ assert.equal(extractFrontmatterField(content, "description"), "hello world");
+ });
+ test("extracts single-quoted string value", () => {
+ const content = "---\ndescription: 'hi there'\n---\n";
+ assert.equal(extractFrontmatterField(content, "description"), "hi there");
+ });
+ test("extracts bare value", () => {
+ const content = "---\ndescription: bare text here\ntags:\n - brain\n---\n";
+ assert.equal(extractFrontmatterField(content, "description"), "bare text here");
+ });
+ test("returns null when field is present but empty", () => {
+ const content = "---\ndate:\ndescription: \"x\"\n---\n";
+ assert.equal(extractFrontmatterField(content, "date"), null);
+ });
+ test("returns null when field is absent", () => {
+ const content = "---\ntags:\n - brain\n---\n";
+ assert.equal(extractFrontmatterField(content, "description"), null);
+ });
+ test("returns null when content has no frontmatter", () => {
+ assert.equal(extractFrontmatterField("# just a heading\n\nbody", "description"), null);
+ });
+ test("returns null when frontmatter is unterminated", () => {
+ assert.equal(extractFrontmatterField("---\ndescription: \"x\"\n", "description"), null);
+ });
+ test("ignores matches that appear only in the body", () => {
+ const content = "---\ntags: []\n---\n\ndescription: not frontmatter\n";
+ assert.equal(extractFrontmatterField(content, "description"), null);
+ });
+ test("handles CRLF line endings (Windows)", () => {
+ const content = '---\r\ndescription: "hello"\r\ntags: []\r\n---\r\n# body';
+ assert.equal(extractFrontmatterField(content, "description"), "hello");
+ });
+ test("does not mistake body line starting with --- for frontmatter terminator", () => {
+ const content =
+ '---\ndescription: "real"\n---\n\n---this-is-not-a-delimiter\n';
+ assert.equal(extractFrontmatterField(content, "description"), "real");
+ });
+ test("escapes regex metacharacters in field name", () => {
+ const content = "---\nfoo.bar: actual-value\n---\n";
+ assert.equal(extractFrontmatterField(content, "foo.bar"), "actual-value");
+ // An unescaped `.` would have matched `fooxbar:` — confirm it doesn't.
+ const decoy = "---\nfooxbar: decoy\n---\n";
+ assert.equal(extractFrontmatterField(decoy, "foo.bar"), null);
+ });
+});
+
+describe("stripFrontmatter", () => {
+ test("removes a complete frontmatter block", () => {
+ const out = stripFrontmatter("---\ntags: []\n---\n\n# body\n");
+ assert.equal(out, "\n# body\n");
+ });
+ test("leaves content without frontmatter unchanged", () => {
+ assert.equal(stripFrontmatter("# just a heading\n"), "# just a heading\n");
+ });
+ test("leaves unterminated frontmatter unchanged", () => {
+ const content = "---\ntags: []\n# never closed\n";
+ assert.equal(stripFrontmatter(content), content);
+ });
+ test("handles CRLF line endings", () => {
+ const out = stripFrontmatter("---\r\ntags: []\r\n---\r\n# body\r\n");
+ assert.equal(out, "# body\r\n");
+ });
+ test("does not mistake body line starting with --- for terminator", () => {
+ const content = "---\ntags: []\n---\n\n---this-is-body\n";
+ assert.equal(stripFrontmatter(content), "\n---this-is-body\n");
+ });
+});
+
+describe("hasBrainContent", () => {
+ test("false when only a bare-hyphen placeholder exists", () => {
+ assert.equal(hasBrainContent("\n# Gotchas\n\nSome intro.\n\n-\n"), false);
+ });
+ test("true for a bullet with text", () => {
+ assert.equal(hasBrainContent("- first real gotcha\n"), true);
+ });
+ test("true for indented bullets", () => {
+ assert.equal(hasBrainContent(" - nested item\n"), true);
+ });
+ test("true for asterisk and plus markers", () => {
+ assert.equal(hasBrainContent("* item\n"), true);
+ assert.equal(hasBrainContent("+ item\n"), true);
+ });
+ test("false for empty body", () => {
+ assert.equal(hasBrainContent(""), false);
+ });
+ test("false for prose-only content with no bullets", () => {
+ assert.equal(hasBrainContent("Just a paragraph of prose.\n"), false);
+ });
+});
+
+describe("formatBrainIndex", () => {
+ test("renders one wikilink + description per entry", () => {
+ const out = formatBrainIndex([
+ { name: "Patterns", description: "recurring patterns", hasContent: true },
+ { name: "Gotchas", description: "things that bite", hasContent: true },
+ ]);
+ assert.equal(
+ out,
+ "- [[Patterns]] — recurring patterns\n- [[Gotchas]] — things that bite",
+ );
+ });
+ test("appends '(empty)' for stub notes", () => {
+ const out = formatBrainIndex([
+ { name: "Gotchas", description: "things that bite", hasContent: false },
+ ]);
+ assert.equal(out, "- [[Gotchas]] — things that bite (empty)");
+ });
+ test("skips North Star and Memories (already surfaced elsewhere)", () => {
+ const out = formatBrainIndex([
+ { name: "North Star", description: "goals", hasContent: true },
+ { name: "Memories", description: "index", hasContent: true },
+ { name: "Patterns", description: "patterns", hasContent: true },
+ ]);
+ assert.equal(out, "- [[Patterns]] — patterns");
+ });
+ test("falls back to '(no description)' for null description", () => {
+ const out = formatBrainIndex([
+ { name: "Patterns", description: null, hasContent: true },
+ ]);
+ assert.equal(out, "- [[Patterns]] — (no description)");
+ });
+ test("empty input → '(none)'", () => {
+ assert.equal(formatBrainIndex([]), "(none)");
+ });
+ test("all-filtered-out → '(none)'", () => {
+ const out = formatBrainIndex([
+ { name: "North Star", description: "x", hasContent: true },
+ { name: "Memories", description: "y", hasContent: true },
+ ]);
+ assert.equal(out, "(none)");
+ });
+});