Skip to content

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

feat: memory-location guard, machine-readable policy results, phantom-edge warning (#124)

Brenno Ferrarid24f23d8f221
diff --git a/.claude/scripts/lib/frontmatter.ts b/.claude/scripts/lib/frontmatter.ts
index 98ff22b..79c9ec7 100644
--- a/.claude/scripts/lib/frontmatter.ts
+++ b/.claude/scripts/lib/frontmatter.ts
@@ -3,7 +3,7 @@
* frontmatter fields, and wikilink presence on non-trivial notes.
*/
-import { basename } from "node:path";
+import { basename, posix } from "node:path";
import { readFileSync } from "node:fs";
const ROOT_FILES: ReadonlySet<string> = new Set([
@@ -26,6 +26,33 @@ const SKIP_PATH_SEGMENTS: readonly string[] = [
"thinking/",
];
+/**
+ * Return true if the path is an auto-memory file in ~/.claude/ that should
+ * be flagged (#81). Only MEMORY.md (the auto-loaded index) is allowed there
+ * — all durable knowledge goes to brain/ topic notes per CLAUDE.md.
+ *
+ * The path is lexically normalized first (separators unified, `.`/`..`
+ * segments collapsed) so a path can't dodge the check by spelling the
+ * memory dir indirectly. Callers should additionally pass a
+ * realpath-resolved path when the file exists, so symlinked spellings are
+ * caught too — see the guard in validate-write.ts.
+ *
+ * The predicate requires BOTH `/.claude/` and `/memory/` segments and
+ * exempts `MEMORY.md` by basename, so it never fires on vault paths like
+ * `brain/Memories.md`, project paths containing the word "memory", or
+ * other `.claude/projects/<x>/` subdirs (transcripts, hook output).
+ */
+export function isBlockedMemoryPath(filePath: string): boolean {
+ // Separators unified FIRST, then posix-normalize: normalize() on a POSIX
+ // host doesn't treat "\" as a separator, so backslash-spelled ".."
+ // segments would otherwise survive uncollapsed.
+ const normalized = posix.normalize(filePath.replaceAll("\\", "/"));
+ if (!normalized.includes("/memory/")) return false;
+ if (!normalized.includes("/.claude/")) return false;
+ const base = basename(normalized);
+ return base !== "MEMORY.md";
+}
+
/**
* Return true if the file should be skipped (not validated).
* Skips non-markdown, dotfiles, templates, root docs, and translated READMEs.
@@ -80,6 +107,17 @@ export function validateContent(content: string): string[] {
);
}
+ // Ticket IDs are not notes — [[PROJ-12345]] creates a phantom graph edge
+ // that a broken-link gate then trips on (#108). Matches the bare form and
+ // the table-escaped-pipe forms. Plain text or a tracker URL, never a
+ // wikilink.
+ const ticketLinks = content.match(/\[\[[A-Z]{2,10}-\d+(\\\||&#124;|\||\]\])/g);
+ if (ticketLinks && ticketLinks.length > 0) {
+ warnings.push(
+ `${ticketLinks.length} ticket-ID wikilink(s) (e.g. [[PROJ-…]]) — ticket IDs are plain text or tracker links, never wikilinks (they are not notes)`,
+ );
+ }
+
return warnings;
}
diff --git a/.claude/scripts/lib/hook-io.ts b/.claude/scripts/lib/hook-io.ts
index 1830c27..d00f4a0 100644
--- a/.claude/scripts/lib/hook-io.ts
+++ b/.claude/scripts/lib/hook-io.ts
@@ -40,13 +40,33 @@ export async function readStdinJson<T = unknown>(): Promise<T | null> {
}
}
+/**
+ * Machine-readable finding riding hookSpecificOutput next to the prose
+ * (#117). Prose stays the primary surface (the model acts on it); this
+ * block is additive so deterministic tooling — a future `--fix`, a
+ * headless tidy — can consume the same decision without parsing text.
+ * `policy_id` is the stable per-detector identifier and versions the
+ * contract.
+ */
+export type PolicyResult = {
+ readonly policy_id: string;
+ readonly path: string;
+ readonly classification: string;
+ readonly suggested_target?: string;
+ readonly action: "warn" | "flag" | "none";
+};
+
export function writeHookOutput(
hookEventName: string,
additionalContext: string,
+ policyResults?: readonly PolicyResult[],
): void {
process.stdout.write(
JSON.stringify({
- hookSpecificOutput: { hookEventName, additionalContext },
+ hookSpecificOutput:
+ policyResults && policyResults.length > 0
+ ? { hookEventName, additionalContext, policyResults }
+ : { hookEventName, additionalContext },
}),
);
}
diff --git a/.claude/scripts/tests/frontmatter.test.ts b/.claude/scripts/tests/frontmatter.test.ts
index 3f67555..327197f 100644
--- a/.claude/scripts/tests/frontmatter.test.ts
+++ b/.claude/scripts/tests/frontmatter.test.ts
@@ -5,7 +5,11 @@
import { test, describe } from "node:test";
import assert from "node:assert/strict";
-import { shouldSkipFile, validateContent } from "../lib/frontmatter.ts";
+import {
+ isBlockedMemoryPath,
+ shouldSkipFile,
+ validateContent,
+} from "../lib/frontmatter.ts";
describe("shouldSkipFile — skip rules", () => {
test("skips non-markdown", () => {
@@ -131,3 +135,64 @@ describe("validateContent — frontmatter + wikilinks", () => {
assert.deepEqual(validateContent(c), []);
});
});
+
+describe("isBlockedMemoryPath", () => {
+ test("blocks non-MEMORY.md files in the auto-memory dir", () => {
+ assert.equal(
+ isBlockedMemoryPath("/u/x/.claude/projects/-p/memory/notes.md"),
+ true,
+ );
+ assert.equal(
+ isBlockedMemoryPath("C:\\u\\x\\.claude\\projects\\-p\\memory\\n.md"),
+ true,
+ );
+ });
+ test("allows MEMORY.md itself", () => {
+ assert.equal(
+ isBlockedMemoryPath("/u/x/.claude/projects/-p/memory/MEMORY.md"),
+ false,
+ );
+ });
+ test("requires both .claude and memory segments", () => {
+ assert.equal(isBlockedMemoryPath("/vault/brain/Memories.md"), false);
+ assert.equal(isBlockedMemoryPath("/u/x/.claude/projects/-p/transcripts/t.md"), false);
+ assert.equal(isBlockedMemoryPath("/u/memory/notes.md"), false);
+ });
+ test("normalizes dot-dot segments before matching, both directions", () => {
+ assert.equal(
+ isBlockedMemoryPath("/u/.claude/projects/-p/transcripts/../memory/x.md"),
+ true,
+ );
+ assert.equal(
+ isBlockedMemoryPath("/u/.claude/projects/-p/memory/../transcripts/x.md"),
+ false,
+ );
+ });
+ test("collapses backslash-spelled dot-dot segments on any host", () => {
+ // Separator unification must precede normalization, or this Windows
+ // spelling would false-positive on POSIX hosts.
+ assert.equal(
+ isBlockedMemoryPath(
+ "C:\\u\\.claude\\projects\\-p\\memory\\..\\transcripts\\x.md",
+ ),
+ false,
+ );
+ });
+});
+
+describe("validateContent — ticket-ID phantom edges", () => {
+ const BASE = "---\ntags: [x]\ndescription: \"d\"\ndate: 2026-01-01\n---\n[[Real Note]]\n";
+ test("warns on bare and aliased ticket-ID wikilinks", () => {
+ const warnings = validateContent(
+ BASE + "See [[PROJ-1234]] and [[ABC-77|the ticket]].\n",
+ );
+ assert.equal(warnings.filter((w) => w.includes("ticket-ID")).length, 1);
+ assert.match(warnings.find((w) => w.includes("ticket-ID")) ?? "", /2 ticket-ID/);
+ });
+ test("silent on normal wikilinks and plain-text ticket IDs", () => {
+ const warnings = validateContent(
+ BASE + "See PROJ-1234 (plain) and [[Architecture Notes]].\n",
+ );
+ assert.equal(warnings.filter((w) => w.includes("ticket-ID")).length, 0);
+ });
+});
diff --git a/.claude/scripts/tests/validate-write.memory.test.ts b/.claude/scripts/tests/validate-write.memory.test.ts
new file mode 100644
index 0000000..aa6808d
--- /dev/null
+++ b/.claude/scripts/tests/validate-write.memory.test.ts
@@ -0,0 +1,101 @@
+/**
+ * Subprocess integration tests for validate-write.ts's memory-location
+ * guard (#81) — fires only on writes inside ~/.claude/…/memory/, allows
+ * MEMORY.md, silent on everything else, and emits the machine-readable
+ * policy result (#117) alongside the prose. Vault-file cases stay silent
+ * here because the test paths fall outside the subprocess's vault root
+ * (cwd), hitting the outside-vault skip.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { fileURLToPath } from "node:url";
+import { dirname, resolve } from "node:path";
+import { runScript as spawnHook } from "./_helpers.ts";
+
+const SCRIPT = resolve(
+ dirname(fileURLToPath(import.meta.url)),
+ "../validate-write.ts",
+);
+
+const runScript = (stdin: object | null) => spawnHook(SCRIPT, stdin);
+const runOn = (filePath: string) =>
+ runScript({ tool_input: { file_path: filePath } });
+
+describe("validate-write memory guard — fires on misplaced memory files", () => {
+ test("warns on a non-MEMORY.md file in memory dir", () => {
+ const { stdout, code } = runOn(
+ "/Users/foo/.claude/projects/-Users-foo-dev-bar/memory/feedback_x.md",
+ );
+ assert.equal(code, 0);
+ assert.match(stdout, /Memory location violation/);
+ assert.match(stdout, /feedback_x\.md/);
+ assert.match(stdout, /brain\//);
+ });
+
+ test("emits the machine-readable policy result next to the prose (#117)", () => {
+ const { stdout } = runOn(
+ "/Users/foo/.claude/projects/-Users-foo-dev-bar/memory/notes.md",
+ );
+ const parsed = JSON.parse(stdout) as {
+ hookSpecificOutput: { policyResults?: unknown[] };
+ };
+ assert.deepEqual(parsed.hookSpecificOutput.policyResults, [
+ {
+ policy_id: "memory-location",
+ path: "/Users/foo/.claude/projects/-Users-foo-dev-bar/memory/notes.md",
+ classification: "misplaced-memory",
+ suggested_target: "brain/",
+ action: "warn",
+ },
+ ]);
+ });
+
+ test("warns on Windows-style backslash path", () => {
+ const { stdout, code } = runOn(
+ "C:\\Users\\foo\\.claude\\projects\\-bar\\memory\\project_y.md",
+ );
+ assert.equal(code, 0);
+ assert.match(stdout, /Memory location violation/);
+ assert.match(stdout, /project_y\.md/);
+ });
+
+ test("catches dot-dot spellings that resolve into the memory dir", () => {
+ const { stdout, code } = runOn(
+ "/Users/foo/.claude/projects/-bar/transcripts/../memory/sneaky.md",
+ );
+ assert.equal(code, 0);
+ assert.match(stdout, /Memory location violation/);
+ });
+});
+
+describe("validate-write memory guard — silent on allowed paths", () => {
+ test("silent on MEMORY.md in memory dir", () => {
+ const { stdout, code } = runOn(
+ "/Users/foo/.claude/projects/-Users-foo-dev-bar/memory/MEMORY.md",
+ );
+ assert.equal(code, 0);
+ assert.equal(stdout, "");
+ });
+
+ test("silent on other .claude/projects subdirs (transcripts, hook output)", () => {
+ const { stdout } = runOn(
+ "/Users/foo/.claude/projects/-bar/transcripts/session.md",
+ );
+ assert.equal(stdout, "");
+ });
+
+ test("silent on vault paths containing the word memory", () => {
+ const { stdout } = runOn("/vault/brain/Memories.md");
+ assert.equal(stdout, "");
+ });
+
+ test("silent on paths that lexically mention memory/ but normalize out of it", () => {
+ // A naive substring predicate false-positives here; the normalized
+ // path lands in transcripts/, which is allowed.
+ const { stdout } = runOn(
+ "/Users/foo/.claude/projects/-bar/memory/../transcripts/notes.md",
+ );
+ assert.equal(stdout, "");
+ });
+});
diff --git a/.claude/scripts/tests/validate-write.test.ts b/.claude/scripts/tests/validate-write.test.ts
index 712ad5f..2c7f99f 100644
--- a/.claude/scripts/tests/validate-write.test.ts
+++ b/.claude/scripts/tests/validate-write.test.ts
@@ -26,7 +26,11 @@ after(() => {
if (TMP_DIR) rmSync(TMP_DIR, { recursive: true, force: true });
});
-const runScript = (stdin: string | object | null) => spawnHook(SCRIPT, stdin);
+// The hook skips files outside the vault root; fixtures live in the OS
+// tmpdir, so route the subprocess's vault root there — scoped to the spawn
+// via envOverrides rather than mutating this process's env.
+const runScript = (stdin: string | object | null) =>
+ spawnHook(SCRIPT, stdin, { CLAUDE_PROJECT_DIR: TMP_DIR });
function makeMd(content: string, name = "test.md"): string {
const path = join(TMP_DIR, name);
diff --git a/.claude/scripts/validate-write.ts b/.claude/scripts/validate-write.ts
index e84a116..7fde930 100644
--- a/.claude/scripts/validate-write.ts
+++ b/.claude/scripts/validate-write.ts
@@ -9,8 +9,13 @@
*/
import { basename } from "node:path";
+import { realpathSync } from "node:fs";
import { debug, readStdinJson, writeHookOutput } from "./lib/hook-io.ts";
-import { shouldSkipFile, validateFile } from "./lib/frontmatter.ts";
+import {
+ isBlockedMemoryPath,
+ shouldSkipFile,
+ validateFile,
+} from "./lib/frontmatter.ts";
type HookInput = {
readonly tool_input?: unknown;
@@ -35,6 +40,68 @@ if (typeof filePath !== "string" || !filePath) {
process.exit(0);
}
+// Memory-location guard (#81) runs BEFORE the vault-root skip: the
+// auto-memory directory lives in ~/.claude/, outside the vault, and would
+// otherwise be skipped. Only MEMORY.md (the auto-loaded index) belongs
+// there — durable knowledge goes to brain/ topic notes per CLAUDE.md.
+// PostToolUse can't block the write, but a loud warning makes the
+// violation immediately visible so the file gets migrated before the
+// index drifts. The predicate checks the lexically-normalized path AND
+// the realpath-resolved one (the file exists by PostToolUse time), so
+// neither `..` spellings nor symlinks dodge it.
+let resolvedPath = filePath;
+try {
+ resolvedPath = realpathSync(filePath);
+} catch {
+ /* unreadable/racing path — lexical check below still applies */
+}
+if (isBlockedMemoryPath(filePath) || isBlockedMemoryPath(resolvedPath)) {
+ const file = basename(filePath.replaceAll("\\", "/"));
+ debug(`validate: misplaced memory file detected — ${file}`);
+ const memoryContext = [
+ `⚠️ Memory location violation: \`${file}\` was written to \`~/.claude/.../memory/\`.`,
+ "",
+ "Per CLAUDE.md, this directory should contain only MEMORY.md (the auto-loaded index).",
+ "All durable knowledge belongs in the vault under `brain/` topic notes:",
+ "",
+ "- Patterns/conventions → `brain/Patterns.md`",
+ "- Things that bit before → `brain/Gotchas.md`",
+ "- Architectural/workflow decisions → `brain/Key Decisions.md`",
+ "- Recent context, relationships, tools → `brain/Memories.md`",
+ "- New topic → new `brain/<Topic>.md` note + index in `brain/Memories.md`",
+ "",
+ `Migrate the content from \`${file}\` into the right brain note, then delete the file from \`~/.claude/\`.`,
+ "`MEMORY.md` itself can keep an index pointer to the brain note(s).",
+ ].join("\n");
+ const memoryEventName =
+ typeof input.hook_event_name === "string"
+ ? input.hook_event_name
+ : "PostToolUse";
+ writeHookOutput(memoryEventName, memoryContext, [
+ {
+ policy_id: "memory-location",
+ path: filePath,
+ classification: "misplaced-memory",
+ suggested_target: "brain/",
+ action: "warn",
+ },
+ ]);
+ process.exit(0);
+}
+
+// Vault-root skip AFTER the memory guard (which must inspect outside-vault
+// paths): files outside the vault are not vault notes — no validation.
+// Boundary-safe: "/vault" must not match "/vaulting/…", and an empty env
+// value falls back to cwd (|| not ??).
+const vaultRoot = (process.env["CLAUDE_PROJECT_DIR"] || process.cwd())
+ .replaceAll("\\", "/")
+ .replace(/\/+$/, "");
+const filePathFwd = filePath.replaceAll("\\", "/");
+if (filePathFwd !== vaultRoot && !filePathFwd.startsWith(vaultRoot + "/")) {
+ debug(`validate: skipped (outside vault root) ${filePath}`);
+ process.exit(0);
+}
+
if (shouldSkipFile(filePath)) {
debug(`validate: skipped ${filePath}`);
process.exit(0);