A self-organizing Obsidian vault that gives AI coding agents persistent memory.
TypeScript ai-agentsclaude-codecodex-cligemini-cliknowledge-managementobsidianobsidian-vaultpersistent-memorysecond-braintemplate
fix: validate every note a Codex apply_patch writes (#370)
Brenno Ferraric6d690022ca2
diff --git a/.claude/scripts/lib/write-targets.ts b/.claude/scripts/lib/write-targets.tsnew file mode 100644index 0000000..cd1faf8--- /dev/null+++ b/.claude/scripts/lib/write-targets.ts@@ -0,0 +1,97 @@+/**+ * The files a write hook's payload says were written (#354).+ *+ * Claude Code and Gemini name one `tool_input.file_path`. Codex's+ * apply_patch names none: its hook input is `tool_input: { command: <the raw+ * patch> }` (openai/codex core/src/tools/handlers/apply_patch.rs, as of+ * 2026-10-13), and the files are the patch's own headers. Relative headers+ * resolve against the payload's `cwd`, which Codex sends as an absolute path+ * (hooks/src/events/post_tool_use.rs).+ */++import { resolve } from "node:path";++// openai/codex apply-patch/src/parser.rs: a hunk header starts its own line.+const ADD_FILE = "*** Add File: ";+const UPDATE_FILE = "*** Update File: ";+const DELETE_FILE = "*** Delete File: ";+const MOVE_TO = "*** Move to: ";++/** The path after `marker` on a header line, or null when the line is not that header or names nothing. */+function matchHeader(line: string, marker: string): string | null {+ if (!line.startsWith(marker)) return null;+ const path = line.slice(marker.length).trim();+ return path === "" ? null : path;+}++/**+ * What a patch leaves on disk to validate (`written`: added and updated files,+ * a moved file at its new path) and what it takes away (`removed`: deleted+ * files, a moved file's old path), in patch order.+ */+function patchPaths(patch: string): { written: string[]; removed: string[] } {+ const written: string[] = [];+ const removed: string[] = [];+ let afterUpdate = false;+ for (const raw of patch.split(/\r?\n/)) {+ // Hunk bodies start with "+", "-", " " or "@@", so a header line is never+ // content; a body line that happens to read like one is prefixed.+ const line = raw.trimEnd();+ const wasUpdate = afterUpdate;+ afterUpdate = false;+ const added = matchHeader(line, ADD_FILE);+ const updated = added === null ? matchHeader(line, UPDATE_FILE) : null;+ const deleted = matchHeader(line, DELETE_FILE);+ const movedTo = wasUpdate ? matchHeader(line, MOVE_TO) : null;+ if (added !== null) written.push(added);+ else if (updated !== null) {+ written.push(updated);+ afterUpdate = true;+ } else if (deleted !== null) removed.push(deleted);+ else if (movedTo !== null) {+ // The file now lives at the new path and the old one is gone: the new+ // path is validated, and both count for the index.+ removed.push(written[written.length - 1] as string);+ written[written.length - 1] = movedTo;+ }+ }+ return { written, removed };+}++/** The payload's paths, absolute and normalised, once each; null when it names none. */+function payloadPaths(input: unknown, projectDir: string): { written: string[]; removed: string[] } | null {+ if (!input || typeof input !== "object") return null;+ const payload = input as { tool_name?: unknown; tool_input?: unknown; cwd?: unknown };+ const toolInput = payload.tool_input;+ if (!toolInput || typeof toolInput !== "object") return null;+ const fields = toolInput as { file_path?: unknown; command?: unknown };++ if (typeof fields.file_path === "string" && fields.file_path !== "") return { written: [fields.file_path], removed: [] };+ if (payload.tool_name !== "apply_patch" || typeof fields.command !== "string") return null;++ // resolve() keeps an absolute path absolute and normalises it, so one file+ // spelled two ways is still one target.+ const base = typeof payload.cwd === "string" && payload.cwd !== "" ? payload.cwd : projectDir;+ const absolute = (paths: string[]) => [...new Set(paths.map((p) => resolve(base, p)))];+ const { written, removed } = patchPaths(fields.command);+ return { written: absolute(written), removed: absolute(removed) };+}++/**+ * Every file the payload left to validate, absolute and once each. A+ * `file_path` is returned as given, exactly as validate-write read it before+ * (#354). Empty when the payload names none.+ */+export function writeTargets(input: unknown, projectDir: string): string[] {+ return payloadPaths(input, projectDir)?.written ?? [];+}++/**+ * Every file whose change the search index should see: what was written and+ * what was removed (a deleted note, a moved note's old path), once each. The+ * index would otherwise keep serving a note that is gone.+ */+export function refreshTargets(input: unknown, projectDir: string): string[] {+ const paths = payloadPaths(input, projectDir);+ return paths === null ? [] : [...new Set([...paths.removed, ...paths.written])];+}diff --git a/.claude/scripts/tests/hook-config.test.ts b/.claude/scripts/tests/hook-config.test.tsindex b4f82b2..7bdd07e 100644--- a/.claude/scripts/tests/hook-config.test.ts+++ b/.claude/scripts/tests/hook-config.test.ts@@ -497,8 +497,8 @@ describe("hook config — write validation fires on each agent's own file tools{ label: "Claude Code", path: ".claude/settings.json", event: "PostToolUse", tools: ["Write", "Edit"] },// Codex: "For file edits through apply_patch, matcher values can use// apply_patch, Edit, or Write" (developers.openai.com/codex/hooks, as of- // 2026-10-13). The payload is a separate gap (#354).- { label: "Codex CLI", path: ".codex/hooks.json", event: "PostToolUse", tools: ["Write", "Edit"] },+ // 2026-10-13). An apply_patch payload names its files in the patch (#354).+ { label: "Codex CLI", path: ".codex/hooks.json", event: "PostToolUse", tools: ["Write", "Edit", "apply_patch"] },// Gemini: write_file and replace (gemini-cli// tools/definitions/base-declarations.ts, as of 2026-10-13); tool-event// matchers are regexes (hooks/hookPlanner.ts).diff --git a/.claude/scripts/tests/validate-write.test.ts b/.claude/scripts/tests/validate-write.test.tsindex b2d7f72..23515f1 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 { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { runScript as spawnHook, rmTemp } from "./_helpers.ts";@@ -300,3 +300,124 @@ describe("validate-write — under Gemini's AfterTool (#353)", () => {assert.match(data.hookSpecificOutput.additionalContext, /frontmatter/i);});});++// With HOOK_DEBUG=1 the refresh trigger logs "refresh requested" before it+// branches, so whether a write asked for a refresh shows with or without qmd+// installed; a sentinel appears only where qmd resolves, and the leg without+// qmd failed on it. Each sentinel is touched first, so the request is+// debounced and no worker spawns.+const refreshEnv = (name: string): Record<string, string> => {+ const sentinel = join(TMP_DIR, `${name}.sentinel`);+ writeFileSync(sentinel, "");+ return { HOOK_DEBUG: "1", QMD_REFRESH_SENTINEL: sentinel };+};+const refreshed = (stderr: string) => stderr.includes("validate-write: refresh requested");++describe("validate-write — Codex apply_patch, whose payload names no file_path (#354)", () => {+ // openai/codex core/src/tools/handlers/apply_patch.rs: tool_input is+ // { command: <raw patch> }, and the request carries an absolute cwd+ // (hooks/src/events/post_tool_use.rs), as of 2026-10-13.+ const applyPatch = (patch: string, env: Record<string, string> = {}) =>+ spawnHook(+ SCRIPT,+ { hook_event_name: "PostToolUse", tool_name: "apply_patch", cwd: TMP_DIR, tool_input: { command: patch } },+ { CLAUDE_PROJECT_DIR: TMP_DIR, ...env },+ );+ const context = (stdout: string) =>+ (JSON.parse(stdout) as { hookSpecificOutput: { hookEventName: string; additionalContext: string } }).hookSpecificOutput;++ test("an added note without frontmatter gets its warning, relative to the payload's cwd", () => {+ makeMd("No frontmatter here\n" + "x".repeat(300), "codex-added.md");+ const { stdout, code } = applyPatch("*** Begin Patch\n*** Add File: codex-added.md\n+No frontmatter here\n*** End Patch\n");+ assert.equal(code, 0);+ const out = context(stdout);+ assert.equal(out.hookEventName, "PostToolUse");+ assert.match(out.additionalContext, /codex-added\.md/);+ });++ test("every note a patch writes is validated, in one envelope", () => {+ makeMd("No frontmatter one\n" + "x".repeat(300), "codex-one.md");+ makeMd("No frontmatter two\n" + "x".repeat(300), "codex-two.md");+ const { stdout } = applyPatch(+ "*** Begin Patch\n*** Add File: codex-one.md\n+a\n*** Update File: codex-two.md\n@@\n+b\n*** End Patch\n",+ );+ const out = context(stdout);+ assert.match(out.additionalContext, /Vault hygiene warnings for `codex-one\.md`/);+ assert.match(out.additionalContext, /Vault hygiene warnings for `codex-two\.md`/);+ });++ test("a misplaced memory file in a patch is flagged, with its policy result", () => {+ const { stdout } = applyPatch(+ "*** Begin Patch\n*** Add File: /Users/foo/.claude/projects/-Users-foo-dev-bar/memory/feedback_x.md\n+x\n*** End Patch\n",+ );+ const out = JSON.parse(stdout) as {+ hookSpecificOutput: { additionalContext: string; policyResults?: Array<{ policy_id: string }> };+ };+ assert.match(out.hookSpecificOutput.additionalContext, /Memory location violation/);+ assert.deepEqual(out.hookSpecificOutput.policyResults?.map((p) => p.policy_id), ["memory-location"]);+ });++ test("a patch that writes a vault note triggers the refresh (the control for the case below)", () => {+ makeMd("---\ndate: 2026-10-13\n---\n" + "x".repeat(300), "codex-refresh.md");+ const { stderr } = applyPatch("*** Begin Patch\n*** Add File: codex-refresh.md\n+x\n*** End Patch\n", refreshEnv("md"));+ assert.ok(refreshed(stderr), "the refresh was requested");+ });++ test("a patch touching only non-.md files warns nothing and triggers no refresh", () => {+ writeFileSync(join(TMP_DIR, "code.ts"), "export {};\n");+ const { stdout, stderr, code } = applyPatch("*** Begin Patch\n*** Add File: code.ts\n+export {};\n*** End Patch\n", refreshEnv("nomd"));+ assert.equal(code, 0);+ assert.equal(stdout, "");+ assert.equal(refreshed(stderr), false, "no refresh was requested");+ });++ test("a patch touching only a note outside the vault warns nothing, as a single-file write does", () => {+ const outside = mkdtempSync(join(tmpdir(), "validate-write-outside-"));+ try {+ const note = join(outside, "elsewhere.md");+ writeFileSync(note, "No frontmatter here\n" + "x".repeat(300));+ const { stdout, code } = applyPatch(`*** Begin Patch\n*** Add File: ${note}\n+x\n*** End Patch\n`);+ assert.equal(code, 0);+ assert.equal(stdout, "");+ } finally {+ rmTemp(outside);+ }+ });+});++describe("validate-write — apply_patch review follow-ups (#354)", () => {+ const applyPatch = (patch: string, env: Record<string, string> = {}) =>+ spawnHook(+ SCRIPT,+ { hook_event_name: "PostToolUse", tool_name: "apply_patch", cwd: TMP_DIR, tool_input: { command: patch } },+ { CLAUDE_PROJECT_DIR: TMP_DIR, ...env },+ );++ test("a patch that only deletes a note still refreshes the index, which would otherwise serve it", () => {+ const { stdout, stderr } = applyPatch("*** Begin Patch\n*** Delete File: gone.md\n*** End Patch\n", refreshEnv("delete"));+ assert.equal(stdout, "", "nothing to validate");+ assert.ok(refreshed(stderr), "the refresh was requested");+ });++ test("three new notes joining one cluster give its hint once, not once per note", () => {+ const active = join(TMP_DIR, "work", "active");+ mkdirSync(active, { recursive: true });+ const fm = "---\ndate: 2026-10-13\ndescription: d\ntags: [work-note]\nquarter: Q4-2026\n---\n\nSee [[Home]].\n" + "x".repeat(300);+ // A cluster needs a root of at least 4 notes, its token in no more than+ // half of them (lib/active-hygiene.ts): 3 Pelican notes beside 3 others.+ for (const n of ["Pelican Plan.md", "Pelican Notes.md", "Pelican Risks.md", "Zebra Budget.md", "Otter Hiring.md", "Falcon Launch.md"]) {+ writeFileSync(join(active, n), fm);+ }+ const { stdout } = applyPatch(+ "*** Begin Patch\n*** Add File: work/active/Pelican Plan.md\n+x\n*** Add File: work/active/Pelican Notes.md\n+x\n*** Add File: work/active/Pelican Risks.md\n+x\n*** End Patch\n",+ );+ const out = JSON.parse(stdout) as { hookSpecificOutput: { additionalContext: string; policyResults?: Array<{ policy_id: string }> } };+ assert.equal(out.hookSpecificOutput.additionalContext.split("loose sibling(s)").length - 1, 1, out.hookSpecificOutput.additionalContext);+ // The machine-readable results stay one per file: each names its own path.+ const clusterPaths = (out.hookSpecificOutput.policyResults as Array<{ policy_id: string; path: string }> | undefined)+ ?.filter((p) => p.policy_id === "topic-cluster")+ .map((p) => p.path)+ .sort();+ assert.deepEqual(clusterPaths, ["work/active/Pelican Notes.md", "work/active/Pelican Plan.md", "work/active/Pelican Risks.md"]);+ });+});diff --git a/.claude/scripts/tests/write-targets.test.ts b/.claude/scripts/tests/write-targets.test.tsnew file mode 100644index 0000000..0462073--- /dev/null+++ b/.claude/scripts/tests/write-targets.test.ts@@ -0,0 +1,110 @@+/**+ * writeTargets: the files a write hook's payload says were written. Claude+ * Code and Gemini name one `file_path`; Codex's apply_patch names none and+ * carries the raw patch in `tool_input.command` (#354).+ */++import { test, describe } from "node:test";+import assert from "node:assert/strict";+import { join, resolve } from "node:path";++import { refreshTargets, writeTargets } from "../lib/write-targets.ts";++const PROJECT = resolve("/vault");+const CWD = resolve("/vault/work");++/** A Codex apply_patch payload for `patch`, run in `cwd`. */+const applyPatch = (patch: string, cwd: string = CWD) => ({+ hook_event_name: "PostToolUse",+ tool_name: "apply_patch",+ cwd,+ tool_input: { command: patch },+});++const patch = (...hunks: string[]) => ["*** Begin Patch", ...hunks, "*** End Patch", ""].join("\n");++describe("writeTargets — file_path (Claude Code, Gemini)", () => {+ test("a file_path is the one target, as given", () => {+ assert.deepEqual(writeTargets({ tool_input: { file_path: join(PROJECT, "a.md") } }, PROJECT), [join(PROJECT, "a.md")]);+ });++ test("no tool_input, or neither field, gives no target", () => {+ assert.deepEqual(writeTargets(null, PROJECT), []);+ assert.deepEqual(writeTargets({}, PROJECT), []);+ assert.deepEqual(writeTargets({ tool_input: { file_path: "" } }, PROJECT), []);+ });+});++describe("writeTargets — Codex apply_patch (#354)", () => {+ // Markers from openai/codex apply-patch/src/parser.rs, as of 2026-10-13.+ test("an added file is a target, resolved against the payload's cwd", () => {+ const input = applyPatch(patch("*** Add File: notes/a.md", "+hello"));+ assert.deepEqual(writeTargets(input, PROJECT), [join(CWD, "notes/a.md")]);+ });++ test("an updated file is a target, and a move targets where it lands", () => {+ const input = applyPatch(+ patch("*** Update File: b.md", "@@", "-old", "+new", "*** Update File: c.md", "*** Move to: d.md", "@@", "-x", "+y"),+ );+ assert.deepEqual(writeTargets(input, PROJECT), [join(CWD, "b.md"), join(CWD, "d.md")]);+ });++ test("a deleted file is not a target: there is nothing left to validate", () => {+ assert.deepEqual(writeTargets(applyPatch(patch("*** Delete File: gone.md")), PROJECT), []);+ });++ test("every file in a patch is a target, once each", () => {+ const input = applyPatch(patch("*** Add File: a.md", "+1", "*** Update File: b.md", "@@", "+2", "*** Update File: a.md", "@@", "+3"));+ assert.deepEqual(writeTargets(input, PROJECT), [join(CWD, "a.md"), join(CWD, "b.md")]);+ });++ test("an absolute path stays as written", () => {+ const abs = resolve("/elsewhere/x.md");+ assert.deepEqual(writeTargets(applyPatch(patch(`*** Add File: ${abs}`, "+1")), PROJECT), [abs]);+ });++ test("without a cwd, relative paths resolve against the project dir", () => {+ const input = { tool_name: "apply_patch", tool_input: { command: patch("*** Add File: a.md", "+1") } };+ assert.deepEqual(writeTargets(input, PROJECT), [join(PROJECT, "a.md")]);+ });++ test("a CRLF patch reads the same", () => {+ const input = applyPatch(patch("*** Add File: a.md", "+1").replaceAll("\n", "\r\n"));+ assert.deepEqual(writeTargets(input, PROJECT), [join(CWD, "a.md")]);+ });++ test("a command with no patch markers gives no target", () => {+ assert.deepEqual(writeTargets(applyPatch("echo hello"), PROJECT), []);+ assert.deepEqual(writeTargets({ tool_name: "apply_patch", tool_input: { command: 42 } }, PROJECT), []);+ });++ test("a header naming no file, or a move with no update before it, gives no target", () => {+ assert.deepEqual(writeTargets(applyPatch(patch("*** Add File: ", "+1")), PROJECT), []);+ assert.deepEqual(writeTargets(applyPatch(patch("*** Move to: stray.md")), PROJECT), []);+ assert.deepEqual(writeTargets(applyPatch("*** Begin Patch\n*** Add File: cut.md"), PROJECT), [join(CWD, "cut.md")]);+ });++ test("a file line inside a hunk's body is content, not a target", () => {+ const input = applyPatch(patch("*** Add File: a.md", "+*** Add File: not-a-target.md"));+ assert.deepEqual(writeTargets(input, PROJECT), [join(CWD, "a.md")]);+ });+});++describe("writeTargets / refreshTargets — review follow-ups (#354)", () => {+ test("an absolute path is normalised, so it and its relative spelling are one target", () => {+ // Concatenated, not joined: join() would normalise the ".." away before the code under test sees it.+ const unnormalised = `${CWD}/../work/a.md`;+ const input = applyPatch(patch(`*** Update File: ${unnormalised}`, "@@", "+1", "*** Update File: a.md", "@@", "+2"));+ assert.deepEqual(writeTargets(input, PROJECT), [join(CWD, "a.md")]);+ });++ test("the refresh sees what a patch removed as well as what it wrote", () => {+ const input = applyPatch(patch("*** Delete File: gone.md", "*** Update File: old.md", "*** Move to: new.txt", "@@", "+x"));+ assert.deepEqual(writeTargets(input, PROJECT), [join(CWD, "new.txt")]);+ assert.deepEqual(refreshTargets(input, PROJECT), [join(CWD, "gone.md"), join(CWD, "old.md"), join(CWD, "new.txt")]);+ });++ test("for a file_path payload, the refresh sees the one file", () => {+ assert.deepEqual(refreshTargets({ tool_input: { file_path: join(PROJECT, "a.md") } }, PROJECT), [join(PROJECT, "a.md")]);+ });+});diff --git a/.claude/scripts/validate-write.ts b/.claude/scripts/validate-write.tsindex e1fc0df..6c59d6b 100644--- a/.claude/scripts/validate-write.ts+++ b/.claude/scripts/validate-write.ts@@ -2,7 +2,9 @@/*** PostToolUse hook — validate vault notes after Write/Edit operations.*- * Reads the hook JSON payload from stdin, inspects the tool_input.file_path,+ * Reads the hook JSON payload from stdin and inspects each file it wrote: the+ * tool_input.file_path (Claude Code, Gemini), or every file a Codex+ * apply_patch adds, updates or moves (lib/write-targets.ts, #354). It* skips files outside the vault-note scope (dotfiles, templates, root docs,* translated READMEs, thinking drafts), and emits a hookSpecificOutput with* vault hygiene warnings when frontmatter or wikilinks are missing.@@ -36,9 +38,9 @@ import {triggerDebouncedRefresh,} from "./lib/qmd-refresh.ts";import { resolveProjectDir } from "./lib/project-dir.ts";+import { refreshTargets, writeTargets } from "./lib/write-targets.ts";type HookInput = {- readonly tool_input?: unknown;readonly hook_event_name?: unknown;};@@ -48,15 +50,19 @@ if (!input) {process.exit(0);}-const toolInput = input.tool_input;-if (!toolInput || typeof toolInput !== "object") {- debug("validate: missing tool_input");- process.exit(0);-}+// Boundary-safe vault root: "/vault" must not match "/vaulting/…"; an empty+// env value falls back to cwd (lib/project-dir.ts).+const vaultRoot = resolveProjectDir(process.cwd())+ .replaceAll("\\", "/")+ .replace(/\/+$/, "");-const filePath = (toolInput as Record<string, unknown>).file_path;-if (typeof filePath !== "string" || !filePath) {- debug("validate: missing file_path");+// One file for Claude Code and Gemini (file_path); every file a Codex+// apply_patch adds, updates or moves, whose payload names none (#354). The+// index also sees what a patch deleted or moved away.+const targets = writeTargets(input, vaultRoot);+const refreshed = refreshTargets(input, vaultRoot);+if (refreshed.length === 0) {+ debug("validate: no file_path and no patch targets");process.exit(0);}@@ -70,7 +76,7 @@ const SENTINEL_PATH =process.env["QMD_REFRESH_SENTINEL"] ??join(SCRIPT_DIR, ".qmd-refresh-sentinel");const WORKER_PATH = resolvePath(SCRIPT_DIR, "qmd-refresh-run.ts");-if (shouldRefreshForPath(filePath)) {+if (refreshed.some(shouldRefreshForPath)) {triggerDebouncedRefresh({sentinelPath: SENTINEL_PATH,workerPath: WORKER_PATH,@@ -79,165 +85,183 @@ if (shouldRefreshForPath(filePath)) {});}-// 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/rules/memory.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/rules/memory.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, [- {+// 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. Read lazily, once per call: a write the skip+// ladder discards never pays for it, and a patch's files share it.+let manifest: unknown;+const loadManifest = (): unknown => {+ if (manifest !== undefined) return manifest;+ try {+ manifest = JSON.parse(readFileSync(join(vaultRoot, "vault-manifest.json"), "utf-8"));+ } catch {+ manifest = null;+ }+ return manifest;+};++/** What one written file adds to the call's single envelope. */+type FileFindings = { readonly blocks: string[]; readonly policyResults: PolicyResult[] };++function checkFile(filePath: string): FileFindings {+ const blocks: string[] = [];+ const policyResults: PolicyResult[] = [];++ // 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/rules/memory.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}`);+ blocks.push(+ [+ `⚠️ Memory location violation: \`${file}\` was written to \`~/.claude/.../memory/\`.`,+ "",+ "Per .claude/rules/memory.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"),+ );+ policyResults.push({policy_id: "memory-location",path: filePath,classification: "misplaced-memory",suggested_target: "brain/",action: "warn",- },- ]);- process.exit(0);-}+ });+ return { blocks, policyResults };+ }-// 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/…"; an empty env value-// falls back to cwd (lib/project-dir.ts).-const vaultRoot = resolveProjectDir(process.cwd())- .replaceAll("\\", "/")- .replace(/\/+$/, "");-const filePathFwd = filePath.replaceAll("\\", "/");-if (filePathFwd !== vaultRoot && !filePathFwd.startsWith(vaultRoot + "/")) {- debug(`validate: skipped (outside vault root) ${filePath}`);- 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.+ const filePathFwd = filePath.replaceAll("\\", "/");+ if (filePathFwd !== vaultRoot && !filePathFwd.startsWith(vaultRoot + "/")) {+ debug(`validate: skipped (outside vault root) ${filePath}`);+ return { blocks, policyResults };+ }-if (shouldSkipFile(filePath)) {- debug(`validate: skipped ${filePath}`);- process.exit(0);-}+ if (shouldSkipFile(filePath)) {+ debug(`validate: skipped ${filePath}`);+ return { blocks, policyResults };+ }-// Single read: prose warnings AND policy results derive from the same-// content snapshot — no second read, no TOCTOU window between them.-let content: string;-try {- content = readFileSync(filePath, { encoding: "utf-8" });-} catch {- debug(`validate: could not read ${filePath}`);- process.exit(0);-}-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[] = [];--if (warnings.length > 0) {- const hintList = warnings.map((w) => ` - ${w}`).join("\n");- const base = basename(filePath.replaceAll("\\", "/"));- blocks.push(- `Vault hygiene warnings for \`${base}\`:\n${hintList}\nFix these before moving on.`,- );- // Phantom-edge findings ride the #117 contract like every other- // detector — counted from the SAME content snapshot the prose came from.- if (countTicketIdWikilinks(content) > 0) {- policyResults.push({- policy_id: "phantom-edge",- path: relPath,- classification: "ticket-id-wikilink",- action: "warn",- });+ // Single read: prose warnings AND policy results derive from the same+ // content snapshot — no second read, no TOCTOU window between them.+ let content: string;+ try {+ content = readFileSync(filePath, { encoding: "utf-8" });+ } catch {+ debug(`validate: could not read ${filePath}`);+ return { blocks, policyResults };}-}+ const relPath = filePathFwd.startsWith(vaultRoot + "/")+ ? filePathFwd.slice(vaultRoot.length + 1)+ : filePathFwd;+ const warnings = validateContent(content, {+ required: parseFrontmatterRequired(loadManifest()),+ relPath,+ });+ debug(`validate: ${filePath} — ${warnings.length} warning(s)`);-// Write-time organization flags (#103): the same detectors the scan hooks-// run, moved to the moment of growth — the session that just made a note-// oversized (or added the note that completes a cluster) has the context-// to organize it NOW. Each detector is isolated so a future unguarded-// edit inside one can't kill the sibling checks in the same write.-try {- const size = statSync(filePath).size;- if (- size >= MONOLITH_BYTES &&- !isMonolithExempt(basename(filePathFwd))- ) {- blocks.push(formatMonolithHint(relPath, size));- policyResults.push({- policy_id: "organization-threshold",- path: relPath,- classification: "oversized-note",- action: "flag",- });+ if (warnings.length > 0) {+ const hintList = warnings.map((w) => ` - ${w}`).join("\n");+ const base = basename(filePathFwd);+ blocks.push(+ `Vault hygiene warnings for \`${base}\`:\n${hintList}\nFix these before moving on.`,+ );+ // Phantom-edge findings ride the #117 contract like every other+ // detector — counted from the SAME content snapshot the prose came from.+ if (countTicketIdWikilinks(content) > 0) {+ policyResults.push({+ policy_id: "phantom-edge",+ path: relPath,+ classification: "ticket-id-wikilink",+ action: "warn",+ });+ }}-} catch {- debug("validate: monolith check failed — skipped");-}-try {- const cluster = newNoteClusterCandidate(filePath, vaultRoot);- if (cluster !== null) {- blocks.push(formatClusterHint(cluster));- policyResults.push({- policy_id: "topic-cluster",- path: relPath,- classification: "ungrouped-cluster",- suggested_target: "work/active/<Topic>/",- action: "flag",- });++ // Write-time organization flags (#103): the same detectors the scan hooks+ // run, moved to the moment of growth — the session that just made a note+ // oversized (or added the note that completes a cluster) has the context+ // to organize it NOW. Each detector is isolated so a future unguarded+ // edit inside one can't kill the sibling checks in the same write.+ try {+ const size = statSync(filePath).size;+ if (+ size >= MONOLITH_BYTES &&+ !isMonolithExempt(basename(filePathFwd))+ ) {+ blocks.push(formatMonolithHint(relPath, size));+ policyResults.push({+ policy_id: "organization-threshold",+ path: relPath,+ classification: "oversized-note",+ action: "flag",+ });+ }+ } catch {+ debug("validate: monolith check failed — skipped");+ }+ try {+ const cluster = newNoteClusterCandidate(filePath, vaultRoot);+ if (cluster !== null) {+ blocks.push(formatClusterHint(cluster));+ policyResults.push({+ policy_id: "topic-cluster",+ path: relPath,+ classification: "ungrouped-cluster",+ suggested_target: "work/active/<Topic>/",+ action: "flag",+ });+ }+ } catch {+ debug("validate: cluster check failed — skipped");}-} catch {- debug("validate: cluster check failed — skipped");++ return { blocks, policyResults };}+// One envelope for the call, however many files it wrote: each file's+// findings in patch order, a file that throws costing only its own. A finding+// several files share (the cluster they all join) is said once. A single+// write reads exactly as before.+const findings = targets.map((t): FileFindings => {+ try {+ return checkFile(t);+ } catch (err) {+ debug(`validate: ${t} — check failed: ${(err as Error)?.message ?? err}`);+ return { blocks: [], policyResults: [] };+ }+});+const blocks = [...new Set(findings.flatMap((f) => f.blocks))];if (blocks.length > 0) {const eventName =typeof input.hook_event_name === "string"? input.hook_event_name: "PostToolUse";- writeHookOutput(eventName, blocks.join("\n\n"), policyResults);+ const policies = new Map(findings.flatMap((f) => f.policyResults).map((p) => [JSON.stringify(p), p] as const));+ writeHookOutput(eventName, blocks.join("\n\n"), [...policies.values()]);}process.exit(0);diff --git a/.codex/hooks.json b/.codex/hooks.jsonindex 3428b25..1e37a18 100644--- a/.codex/hooks.json+++ b/.codex/hooks.json@@ -27,7 +27,7 @@],"PostToolUse": [{- "matcher": "Write|Edit",+ "matcher": "Write|Edit|apply_patch","hooks": [{"type": "command",