A self-organizing Obsidian vault that gives AI coding agents persistent memory.
TypeScript ai-agentsclaude-codecodex-cligemini-cliknowledge-managementobsidianobsidian-vaultpersistent-memorysecond-braintemplate
feat: eager-layer token efficiency — source-aware injection, spawn merge, hint dedupe, listing collapse (#129)
Brenno Ferrarieb04464ad218
diff --git a/.claude/scripts/classify-message.ts b/.claude/scripts/classify-message.tsindex 28e711e..18e0cc1 100644--- a/.claude/scripts/classify-message.ts+++ b/.claude/scripts/classify-message.ts@@ -8,12 +8,23 @@* malformed input, missing prompt, or zero matches.*/+import { readFileSync, writeFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";import { debug, readStdinJson, writeHookOutput } from "./lib/hook-io.ts";import { classify } from "./lib/matcher.ts";+import { parseHintState, prune, record, unseen } from "./lib/hint-state.ts";++const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));+// CLASSIFY_HINT_STATE routes the state file into a tmp path for tests+// (mirrors the QMD_REFRESH_SENTINEL pattern). Production never sets it.+const STATE_PATH =+ process.env["CLASSIFY_HINT_STATE"] ?? join(SCRIPT_DIR, ".hint-state.json");type HookInput = {readonly prompt?: unknown;readonly hook_event_name?: unknown;+ readonly session_id?: unknown;};const input = await readStdinJson<HookInput>();@@ -31,8 +42,39 @@ if (typeof prompt !== "string" || !prompt) {const signals = classify(prompt);debug(`classify: matched ${signals.length} signal(s)`);-if (signals.length > 0) {- const hints = signals.map((s) => `- ${s}`).join("\n");+// Once-per-session dedupe (#107): each hint fires once per session_id via+// a self-pruning state file (7-day age + 200-session cap). Missing/invalid+// session_id fails OPEN — every hint emits, matching today's behavior.+let toEmit = signals;+const sessionId = input.session_id;+if (typeof sessionId === "string" && sessionId && signals.length > 0) {+ let state = parseHintState(null);+ try {+ state = parseHintState(readFileSync(STATE_PATH, { encoding: "utf-8" }));+ } catch {+ /* missing/unreadable state → empty (fail open) */+ }+ const unseenHints = new Set(unseen(state, sessionId, signals));+ toEmit = signals.filter((s) => unseenHints.has(s));+ debug(+ `classify: ${signals.length - toEmit.length} signal(s) already fired this session`,+ );+ if (toEmit.length > 0) {+ try {+ const now = new Date();+ const next = prune(+ record(state, sessionId, toEmit, now.toISOString()),+ now.getTime(),+ );+ writeFileSync(STATE_PATH, JSON.stringify(next));+ } catch {+ /* best-effort — a failed state write must never block the hint */+ }+ }+}++if (toEmit.length > 0) {+ const hints = toEmit.map((s) => `- ${s}`).join("\n");const additionalContext ="Content classification hints (act on these if the user's message contains relevant info):\n" +hints +diff --git a/.claude/scripts/lib/hint-state.ts b/.claude/scripts/lib/hint-state.tsnew file mode 100644index 0000000..f2f6a55--- /dev/null+++ b/.claude/scripts/lib/hint-state.ts@@ -0,0 +1,107 @@+/**+ * Once-per-session hint state — pure helpers for the classify-message+ * dedupe (Vault Improvement Backlog, 2026-07-14).+ *+ * The classifier fires the same routing hint every time a keyword recurs;+ * a long shipping session pays the WIN hint dozens of times. This module+ * keys "already fired" signal names by Claude Code's session_id in a+ * single JSON state file (`.claude/scripts/.hint-state.json`, gitignored;+ * tests route it elsewhere via the CLASSIFY_HINT_STATE env var).+ *+ * Design constraints, in order:+ * - Fail open. A missing session_id, unreadable file, or malformed JSON+ * must degrade to today's behavior (all hints fire), never to silence.+ * - Single file, self-pruning. Per-session files would accumulate without+ * bound and would put session_id into filesystem paths; a JSON key has+ * no traversal surface. Sessions older than PRUNE_MAX_AGE_MS or beyond+ * PRUNE_MAX_SESSIONS (most-recently-updated kept) are dropped on write.+ * - Best-effort concurrency. Two hooks racing is last-writer-wins; the+ * worst case is one duplicate hint, which is acceptable.+ */++export type HintSessionEntry = {+ readonly seen: readonly string[];+ readonly updated: string; // ISO timestamp of last write+};++export type HintState = Readonly<Record<string, HintSessionEntry>>;++export const PRUNE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;+export const PRUNE_MAX_SESSIONS = 200;++/**+ * Parse the state file's raw contents. Anything that isn't a well-formed+ * state object — null input, malformed JSON, wrong shapes — degrades to+ * an empty state (fail open). Individually malformed session entries are+ * dropped rather than poisoning the whole file.+ */+export function parseHintState(raw: string | null): HintState {+ if (raw === null) return {};+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ return {};+ }+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {+ return {};+ }+ const out: Record<string, HintSessionEntry> = {};+ for (const [sessionId, entry] of Object.entries(parsed)) {+ if (entry === null || typeof entry !== "object") continue;+ const seen = (entry as Record<string, unknown>)["seen"];+ const updated = (entry as Record<string, unknown>)["updated"];+ if (!Array.isArray(seen) || typeof updated !== "string") continue;+ out[sessionId] = {+ seen: seen.filter((s): s is string => typeof s === "string"),+ updated,+ };+ }+ return out;+}++/** Signal names that have NOT yet fired for this session. */+export function unseen(+ state: HintState,+ sessionId: string,+ names: readonly string[],+): string[] {+ const seen = new Set(state[sessionId]?.seen ?? []);+ return names.filter((n) => !seen.has(n));+}++/** New state with `names` merged into the session's seen set. */+export function record(+ state: HintState,+ sessionId: string,+ names: readonly string[],+ nowIso: string,+): HintState {+ const seen = new Set(state[sessionId]?.seen ?? []);+ for (const n of names) seen.add(n);+ return {+ ...state,+ [sessionId]: { seen: [...seen].sort(), updated: nowIso },+ };+}++/**+ * Drop sessions older than `maxAgeMs` (by their `updated` stamp; entries+ * with unparseable stamps are treated as expired) and cap the total at+ * `maxSessions`, keeping the most recently updated.+ */+export function prune(+ state: HintState,+ nowMs: number,+ maxAgeMs: number = PRUNE_MAX_AGE_MS,+ maxSessions: number = PRUNE_MAX_SESSIONS,+): HintState {+ const fresh = Object.entries(state).filter(([, entry]) => {+ const t = Date.parse(entry.updated);+ return Number.isFinite(t) && nowMs - t <= maxAgeMs;+ });+ fresh.sort(+ ([, a], [, b]) => Date.parse(b.updated) - Date.parse(a.updated),+ );+ return Object.fromEntries(fresh.slice(0, maxSessions));+}diff --git a/.claude/scripts/lib/session-start.ts b/.claude/scripts/lib/session-start.tsindex f2665d7..9b57d57 100644--- a/.claude/scripts/lib/session-start.ts+++ b/.claude/scripts/lib/session-start.ts@@ -421,3 +421,14 @@ export function resolveIndexStorePath(const base = env["XDG_CACHE_HOME"] ?? join(home, ".cache");return join(base, "qmd", `${indexName}.sqlite`);}++/**+ * Eager-layer injection mode (#107): on `resume`/`compact` the static bulk+ * (North Star, brain index, file listing) is ALREADY in-conversation from+ * the session's first injection — re-injecting doubles cost for zero new+ * information. Full mode on `startup`/`clear` and on any missing/unknown+ * source (fail open — Codex/Gemini hosts don't send one).+ */+export function injectionMode(source: unknown): "full" | "pointer" {+ return source === "resume" || source === "compact" ? "pointer" : "full";+}diff --git a/.claude/scripts/qmd-refresh.ts b/.claude/scripts/qmd-refresh.tsdeleted file mode 100644index dbfa8b6..0000000--- a/.claude/scripts/qmd-refresh.ts+++ /dev/null@@ -1,75 +0,0 @@-#!/usr/bin/env node-/**- * PostToolUse hook — trigger a detached QMD refresh after the agent- * writes or edits a vault markdown file. Closes the staleness window- * between SessionStart's initial `qmd update` and the next session's- * hook run, so mid-session writes become searchable without a restart.- *- * Design contract:- * - Returns in milliseconds. Never blocks the agent or user.- * - Never writes to stdout. Hook protocol: silent = success.- * - Fire-and-forget child: detached + unref + stdio: 'ignore' so the- * worker survives parent exit and the parent doesn't wait on it.- * - Debounced via `.qmd-refresh-sentinel` mtime so a burst of N writes- * triggers ≤ 1 worker in the debounce window (default 30s).- * - Graceful no-op when qmd isn't installed, the path is ineligible,- * or debouncing is active. Each short-circuit exits 0 silently.- *- * Cross-platform: path normalization + skip filtering runs on the- * forward-slash form of the input, so `C:\\vault\\note.md` and- * `/vault/note.md` are treated identically. The detached spawn uses- * `windowsHide: true` to prevent a transient console window on Windows.- */--import { dirname, join, resolve as resolvePath } from "node:path";-import { fileURLToPath } from "node:url";-import { debug, readStdinJson } from "./lib/hook-io.ts";-import {- shouldRefreshForPath,- triggerDebouncedRefresh,-} from "./lib/qmd-refresh.ts";--const DEBOUNCE_MS = 30_000;-const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));-// QMD_REFRESH_SENTINEL lets tests route the debounce sentinel into a-// per-file tmp path so parallel test workers don't race on the shared-// repo sentinel. Production never sets it, so the default applies.-const SENTINEL_PATH =- process.env["QMD_REFRESH_SENTINEL"] ??- join(SCRIPT_DIR, ".qmd-refresh-sentinel");-const WORKER_PATH = resolvePath(SCRIPT_DIR, "qmd-refresh-run.ts");--type HookInput = {- readonly tool_input?: unknown;-};--const input = await readStdinJson<HookInput>();-if (!input) {- debug("qmd-refresh: null input");- process.exit(0);-}--const toolInput = input.tool_input;-if (!toolInput || typeof toolInput !== "object") {- debug("qmd-refresh: missing tool_input");- process.exit(0);-}--const filePath = (toolInput as Record<string, unknown>).file_path;-if (typeof filePath !== "string") {- debug("qmd-refresh: missing file_path");- process.exit(0);-}--if (!shouldRefreshForPath(filePath)) {- debug(`qmd-refresh: skipped ${filePath}`);- process.exit(0);-}--triggerDebouncedRefresh({- sentinelPath: SENTINEL_PATH,- workerPath: WORKER_PATH,- debounceMs: DEBOUNCE_MS,- logPrefix: "qmd-refresh",-});-process.exit(0);diff --git a/.claude/scripts/session-start.ts b/.claude/scripts/session-start.tsindex bf04a3f..f19ffc3 100644--- a/.claude/scripts/session-start.ts+++ b/.claude/scripts/session-start.ts@@ -23,6 +23,7 @@ import { join } from "node:path";import {take,formatDateHeader,+ injectionMode,formatInjectionSize,formatActiveWork,formatRecentChanges,@@ -53,6 +54,37 @@ import {scanActiveHygiene,} from "./lib/active-hygiene.ts";+import { readStdinJson } from "./lib/hook-io.ts";++type HookInput = { readonly source?: unknown };++// The SessionStart payload carries `source` (startup/clear/resume/compact).+// Missing or unparseable stdin fails open to full mode. stdin is OPTIONAL+// for this hook (unlike the payload-driven ones), so guard the read: a+// TTY (manual run) skips it entirely, and a pipe that never delivers EOF+// is abandoned after a short deadline — the injection must never hang on+// a harness that doesn't send the payload.+async function readHookInput(): Promise<HookInput | null> {+ if (process.stdin.isTTY) return null;+ let timer: NodeJS.Timeout | undefined;+ const result = await Promise.race([+ readStdinJson<HookInput>(),+ new Promise<null>((resolveRace) => {+ timer = setTimeout(() => resolveRace(null), 2_000);+ timer.unref();+ }),+ ]);+ if (timer !== undefined) clearTimeout(timer);+ if (result === null) {+ // Abandoned or empty read: drop the stream so a still-open pipe+ // can't keep the process alive after the injection is written.+ process.stdin.destroy();+ }+ return result;+}+const hookInput = await readHookInput();+const mode = injectionMode(hookInput?.source);+function readManifestRaw(): string | null {try {return readFileSync("vault-manifest.json", { encoding: "utf-8" });@@ -235,8 +267,32 @@ function northStar(): string {// Filesystem-only: the path is fixed by template convention, so there's no// wikilink-resolution value worth a CLI hop — and `spawnSync("obsidian", …)`// launches the Electron app on macOS when no instance is running (#83).+ //+ // The 30-line budget must carry LIVE goals (#107): anchor at+ // "## Current Focus" (skipping frontmatter + preamble) and drop+ // struck-through completed bullets, which otherwise consume the slice+ // and truncate current strategy.try {- return take(readFileSync("brain/North Star.md", { encoding: "utf-8" }), 30);+ const raw = readFileSync("brain/North Star.md", { encoding: "utf-8" });+ const lines = stripFrontmatter(raw).split("\n");+ const anchor = lines.findIndex((l) =>+ l.trim().startsWith("## Current Focus"),+ );+ const scoped = anchor >= 0 ? lines.slice(anchor) : lines;+ const struckCount = scoped.filter((l) =>+ l.trimStart().startsWith("- ~~"),+ ).length;+ const live = scoped.filter((l) => !l.trimStart().startsWith("- ~~"));+ if (struckCount > 0) {+ // Struck bullets can carry live tails — keep a pointer so sessions+ // know completed context exists in the file.+ live.splice(+ 1,+ 0,+ `_(${struckCount} completed item${struckCount === 1 ? "" : "s"} hidden — full history in brain/North Star.md)_`,+ );+ }+ return take(live.join("\n"), 30);} catch {return "(not found)";}@@ -347,6 +403,27 @@ const SKIP_PREFIXES: readonly string[] = [".claude",];+// High-volume dirs the listing collapses to one count line (#107): the+// archive grows forever and its enumeration is orientation noise — Glob+// or QMD reach it on demand.+const COLLAPSED_DIRS: readonly string[] = ["work/archive"];++function countMd(dir: string): number {+ let entries: Dirent[];+ try {+ entries = readdirSync(dir, { withFileTypes: true });+ } catch {+ return 0;+ }+ let n = 0;+ for (const e of entries) {+ const full = join(dir, e.name);+ if (e.isDirectory()) n += countMd(full);+ else if (e.isFile() && isMarkdownFilename(e.name)) n += 1;+ }+ return n;+}+function listMd(): string[] {const results: string[] = [];function walk(dir: string): void {@@ -359,26 +436,44 @@ function listMd(): string[] {for (const e of entries) {const full = dir === "." ? e.name : join(dir, e.name);if (isSkippedPath(full, SKIP_PREFIXES)) continue;- if (e.isDirectory()) walk(full);- else if (e.isFile() && isMarkdownFilename(e.name)) results.push(`./${full}`);+ if (e.isDirectory()) {+ const posix = full.replaceAll("\\", "/");+ if (COLLAPSED_DIRS.includes(posix)) {+ results.push(+ `./${posix}/ — ${countMd(full)} notes (listing collapsed — Glob or QMD on demand)`,+ );+ continue;+ }+ walk(full);+ } else if (e.isFile() && isMarkdownFilename(e.name)) results.push(`./${full}`);}}walk(".");return results.sort();}+// Source-aware assembly (#107): on resume/compact the static bulk (North+// Star, brain index, file listing) is already in-conversation — a pointer+// replaces it, and only the volatile sections (recent changes, tasks,+// active work, hygiene, QMD notes) re-inject.const sections = ["## Session Context","","### Date",formatDateHeader(new Date()),"",- "### North Star (current goals)",- northStar(),- "",- "### Brain Topics (read on demand)",- brainIndex(),- "",+];+if (mode === "full") {+ sections.push(+ "### North Star (current goals)",+ northStar(),+ "",+ "### Brain Topics (read on demand)",+ brainIndex(),+ "",+ );+}+sections.push("### Recent Changes (last 48h)",recentChanges(),"",@@ -387,10 +482,16 @@ const sections = ["","### Active Work",activeWork(),- "",- "### Vault File Listing",- listMd().join("\n"),-];+);+if (mode === "full") {+ sections.push("", "### Vault File Listing", listMd().join("\n"));+} else {+ sections.push(+ "",+ "### Context Pointer",+ "(Re-entry via resume/compact — North Star, brain index, and the file listing were injected at session start and are unchanged; re-read on demand.)",+ );+}if (qmdSelfHealNote !== null) {sections.push("", "### QMD Self-Heal", qmdSelfHealNote);diff --git a/.claude/scripts/tests/hint-state.test.ts b/.claude/scripts/tests/hint-state.test.tsnew file mode 100644index 0000000..2130d1e--- /dev/null+++ b/.claude/scripts/tests/hint-state.test.ts@@ -0,0 +1,110 @@+/**+ * Unit tests for lib/hint-state.ts — the once-per-session hint dedupe+ * state. Pure-function coverage; the entry-script wiring is exercised in+ * classify-message.test.ts via runScript + CLASSIFY_HINT_STATE.+ */++import { test, describe } from "node:test";+import assert from "node:assert/strict";+import {+ parseHintState,+ unseen,+ record,+ prune,+ PRUNE_MAX_AGE_MS,+} from "../lib/hint-state.ts";++describe("parseHintState — fail open on anything malformed", () => {+ test("null input → empty state", () => {+ assert.deepEqual(parseHintState(null), {});+ });+ test("malformed JSON → empty state", () => {+ assert.deepEqual(parseHintState("not json {{{"), {});+ });+ test("non-object JSON (array, string, number) → empty state", () => {+ assert.deepEqual(parseHintState("[1,2]"), {});+ assert.deepEqual(parseHintState('"hi"'), {});+ assert.deepEqual(parseHintState("42"), {});+ });+ test("well-formed entries survive, malformed entries are dropped", () => {+ const raw = JSON.stringify({+ good: { seen: ["WIN"], updated: "2026-07-14T08:00:00Z" },+ badSeen: { seen: "WIN", updated: "2026-07-14T08:00:00Z" },+ badUpdated: { seen: ["WIN"], updated: 42 },+ nullEntry: null,+ });+ const state = parseHintState(raw);+ assert.deepEqual(Object.keys(state), ["good"]);+ assert.deepEqual(state["good"]?.seen, ["WIN"]);+ });+ test("non-string members of seen are filtered out", () => {+ const raw = JSON.stringify({+ s: { seen: ["WIN", 42, null, "DECISION"], updated: "2026-07-14T08:00:00Z" },+ });+ assert.deepEqual(parseHintState(raw)["s"]?.seen, ["WIN", "DECISION"]);+ });+});++describe("unseen", () => {+ const state = parseHintState(+ JSON.stringify({+ abc: { seen: ["WIN", "DECISION"], updated: "2026-07-14T08:00:00Z" },+ }),+ );+ test("filters names the session has already fired", () => {+ assert.deepEqual(unseen(state, "abc", ["WIN", "STRATEGY"]), ["STRATEGY"]);+ });+ test("unknown session → everything is unseen", () => {+ assert.deepEqual(unseen(state, "other", ["WIN"]), ["WIN"]);+ });+ test("empty names → empty result", () => {+ assert.deepEqual(unseen(state, "abc", []), []);+ });+});++describe("record", () => {+ test("merges names into the session's seen set, sorted, and stamps updated", () => {+ const s0 = record({}, "abc", ["WIN"], "2026-07-14T08:00:00Z");+ const s1 = record(s0, "abc", ["DECISION", "WIN"], "2026-07-14T09:00:00Z");+ assert.deepEqual(s1["abc"]?.seen, ["DECISION", "WIN"]);+ assert.equal(s1["abc"]?.updated, "2026-07-14T09:00:00Z");+ });+ test("does not mutate the input state", () => {+ const before: ReturnType<typeof parseHintState> = {};+ record(before, "abc", ["WIN"], "2026-07-14T08:00:00Z");+ assert.deepEqual(before, {});+ });+});++describe("prune", () => {+ const NOW = Date.parse("2026-07-14T12:00:00Z");+ test("drops sessions older than maxAge, keeps fresh ones", () => {+ const state = parseHintState(+ JSON.stringify({+ old: { seen: ["WIN"], updated: "2026-07-01T00:00:00Z" },+ fresh: { seen: ["WIN"], updated: "2026-07-14T08:00:00Z" },+ }),+ );+ const pruned = prune(state, NOW, PRUNE_MAX_AGE_MS);+ assert.deepEqual(Object.keys(pruned), ["fresh"]);+ });+ test("unparseable updated stamps are treated as expired", () => {+ const state = parseHintState(+ JSON.stringify({+ junk: { seen: ["WIN"], updated: "not-a-date" },+ }),+ );+ assert.deepEqual(prune(state, NOW), {});+ });+ test("caps total sessions at maxSessions, keeping most recent", () => {+ const entries: Record<string, { seen: string[]; updated: string }> = {};+ for (let i = 0; i < 10; i++) {+ entries[`s${i}`] = {+ seen: ["WIN"],+ updated: new Date(NOW - i * 60_000).toISOString(),+ };+ }+ const pruned = prune(parseHintState(JSON.stringify(entries)), NOW, PRUNE_MAX_AGE_MS, 3);+ assert.deepEqual(Object.keys(pruned).sort(), ["s0", "s1", "s2"]);+ });+});diff --git a/.claude/scripts/tests/qmd-refresh.integration.test.ts b/.claude/scripts/tests/qmd-refresh.integration.test.tsindex 421535e..e4a1b66 100644--- a/.claude/scripts/tests/qmd-refresh.integration.test.ts+++ b/.claude/scripts/tests/qmd-refresh.integration.test.ts@@ -1,19 +1,22 @@/**- * Subprocess integration tests for the qmd-refresh.ts PostToolUse hook.+ * Subprocess integration tests for the QMD-refresh trigger inside the+ * validate-write.ts PostToolUse hook (which absorbed the retired+ * standalone qmd-refresh.ts entry on 2026-07-14 — one spawn per write).** Exercises the real stdin → decision → sentinel pipeline by spawning* the hook entry script exactly the way each agent's settings.json* would: `node --disable-warning=ExperimentalWarning --experimental-strip-types- * qmd-refresh.ts` with a JSON payload on stdin. The sentinel file is the- * only observable the hook produces (stdout AND stderr must stay silent),- * so each test asserts on sentinel presence / mtime + exit code.+ * validate-write.ts` with a JSON payload on stdin. The sentinel file is+ * the refresh trigger's only observable (the fixtures below all resolve+ * to nonexistent or out-of-root files, so validation itself stays+ * silent), so each test asserts on sentinel presence / mtime + exit code.*- * Deliberately does NOT depend on qmd being installed. The hook's+ * Deliberately does NOT depend on qmd being installed. The trigger's* short-circuit when `resolveQmdEntry()` returns null means the* "sentinel NOT touched" path still runs cleanly on a minimal CI image* without polluting anyone's QMD cache. The qmd-installed path is- * handled by one guarded test that checks `resolveQmdEntry()` directly- * and skips itself when qmd isn't available.+ * handled by guarded tests that check `resolveQmdEntry()` directly+ * and assert the alternate branch when qmd isn't available.** Runs identically on Windows, macOS, and Linux — the hook's* cross-platform shape is asserted through the same spawn mechanism@@ -36,7 +39,7 @@ import { runScript as spawnHook } from "./_helpers.ts";import { resolveQmdEntry } from "../lib/qmd.ts";const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));-const SCRIPT = resolve(SCRIPT_DIR, "../qmd-refresh.ts");+const SCRIPT = resolve(SCRIPT_DIR, "../validate-write.ts");// Route the hook's debounce sentinel through a per-file tmp path so// this test can't race with any other test file (notably@@ -93,7 +96,7 @@ beforeEach(() => {});// --- Silent no-op paths (must not touch the sentinel) ----describe("qmd-refresh — silent no-op on ineligible inputs", () => {+describe("validate-write refresh trigger — silent no-op on ineligible inputs", () => {test("empty stdin exits 0 silently without touching sentinel", () => {const { stdout, stderr, code } = runHook(null);assert.equal(code, 0);@@ -190,7 +193,7 @@ describe("qmd-refresh — silent no-op on ineligible inputs", () => {});// --- Debounce path (sentinel controls whether worker is spawned) ----describe("qmd-refresh — debounce", () => {+describe("validate-write refresh trigger — debounce", () => {test("fresh sentinel blocks a subsequent trigger (sentinel unchanged)", () => {// Arrange: sentinel was just "touched" (mtime = now).writeFileSync(SENTINEL, "");@@ -212,12 +215,12 @@ describe("qmd-refresh — debounce", () => {});// --- Happy path: qmd installed, eligible .md → sentinel gets touched ----describe("qmd-refresh — eligible .md path", () => {- // Guard: this test asserts the sentinel gets bumped when qmd is+describe("validate-write refresh trigger — eligible .md path", () => {+ // Guard: these tests assert the sentinel gets bumped when qmd is// available. On a CI image without qmd, `resolveQmdEntry()` returns- // null and the hook correctly short-circuits BEFORE touching the- // sentinel — we assert that alternate path explicitly below so CI- // covers both branches regardless of qmd presence.+ // null and the trigger correctly short-circuits BEFORE touching the+ // sentinel — we assert that alternate path explicitly so CI covers+ // both branches regardless of qmd presence.test("sentinel is bumped when qmd resolves; skipped otherwise", () => {const qmdAvailable = resolveQmdEntry() !== null;@@ -249,5 +252,34 @@ describe("qmd-refresh — eligible .md path", () => {);}});-});+ test("path skipped by validation (templates/) still triggers the refresh", () => {+ // The merge's ordering contract: the refresh trigger fires BEFORE+ // validate-write's skip ladder. templates/ is skipped by+ // shouldSkipFile but was always refreshed by the old standalone+ // hook — the sentinel must still move (when qmd resolves).+ const qmdAvailable = resolveQmdEntry() !== null;++ makeStaleSentinel(5);+ const before = sentinelMtime();+ assert.ok(before !== null);++ const { stdout, code } = runHook({+ tool_input: { file_path: join(VAULT_ROOT, "templates/x.md") },+ });+ const after = sentinelMtime();++ assert.equal(code, 0);+ assert.equal(stdout, "");+ assert.ok(after !== null, "sentinel should remain present");++ if (qmdAvailable) {+ assert.ok(+ after > before,+ "validation-skipped paths must still refresh the QMD index",+ );+ } else {+ assert.equal(after, before);+ }+ });+});diff --git a/.claude/scripts/tests/session-start.test.ts b/.claude/scripts/tests/session-start.test.tsindex 3f115d7..ac322b4 100644--- a/.claude/scripts/tests/session-start.test.ts+++ b/.claude/scripts/tests/session-start.test.ts@@ -12,6 +12,7 @@ import {take,formatDateHeader,formatInjectionSize,+ injectionMode,formatActiveWork,formatRecentChanges,isSkippedPath,@@ -673,3 +674,20 @@ describe("resolveIndexStorePath", () => {);});});++describe("injectionMode", () => {+ const cases: ReadonlyArray<readonly [unknown, "full" | "pointer"]> = [+ ["startup", "full"],+ ["clear", "full"],+ ["resume", "pointer"],+ ["compact", "pointer"],+ [undefined, "full"], // missing source (Codex/Gemini)+ [null, "full"],+ [42, "full"], // non-string+ ];+ for (const [source, expected] of cases) {+ test(`${String(source)} → ${expected}`, () => {+ assert.equal(injectionMode(source), expected);+ });+ }+});diff --git a/.claude/scripts/validate-write.ts b/.claude/scripts/validate-write.tsindex be4cafb..d5d2a94 100644--- a/.claude/scripts/validate-write.ts+++ b/.claude/scripts/validate-write.ts@@ -8,7 +8,8 @@* vault hygiene warnings when frontmatter or wikilinks are missing.*/-import { basename } from "node:path";+import { basename, dirname, join, resolve as resolvePath } from "node:path";+import { fileURLToPath } from "node:url";import { realpathSync, statSync } from "node:fs";import {debug,@@ -28,6 +29,10 @@ import {isMonolithExempt,newNoteClusterCandidate,} from "./lib/active-hygiene.ts";+import {+ shouldRefreshForPath,+ triggerDebouncedRefresh,+} from "./lib/qmd-refresh.ts";type HookInput = {readonly tool_input?: unknown;@@ -52,6 +57,25 @@ if (typeof filePath !== "string" || !filePath) {process.exit(0);}+// Debounced QMD refresh (#107) — fire-and-forget, never blocks validation.+// Folded here from the retired qmd-refresh.ts entry so every .md write+// costs ONE process spawn, not two (~150-300ms each on Windows). Runs+// before the skip ladder so template/root/memory paths still refresh.+const DEBOUNCE_MS = 30_000;+const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));+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)) {+ triggerDebouncedRefresh({+ sentinelPath: SENTINEL_PATH,+ workerPath: WORKER_PATH,+ debounceMs: DEBOUNCE_MS,+ logPrefix: "validate-write",+ });+}+// 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) belongsdiff --git a/.claude/settings.json b/.claude/settings.jsonindex f3557d1..f76bc7e 100644--- a/.claude/settings.json+++ b/.claude/settings.json@@ -31,11 +31,6 @@"type": "command","command": "node --disable-warning=ExperimentalWarning --experimental-strip-types \"${CLAUDE_PROJECT_DIR:-.}/.claude/scripts/validate-write.ts\"","timeout": 15- },- {- "type": "command",- "command": "node --disable-warning=ExperimentalWarning --experimental-strip-types \"${CLAUDE_PROJECT_DIR:-.}/.claude/scripts/qmd-refresh.ts\"",- "timeout": 15}]}diff --git a/.codex/hooks.json b/.codex/hooks.jsonindex 90747e4..03379a7 100644--- a/.codex/hooks.json+++ b/.codex/hooks.json@@ -31,11 +31,6 @@"type": "command","command": "node --disable-warning=ExperimentalWarning --experimental-strip-types \"${CODEX_PROJECT_DIR:-.}/.claude/scripts/validate-write.ts\"","timeout": 15- },- {- "type": "command",- "command": "node --disable-warning=ExperimentalWarning --experimental-strip-types \"${CODEX_PROJECT_DIR:-.}/.claude/scripts/qmd-refresh.ts\"",- "timeout": 15}]}diff --git a/.gemini/settings.json b/.gemini/settings.jsonindex 3382bd4..e2b51b6 100644--- a/.gemini/settings.json+++ b/.gemini/settings.json@@ -31,11 +31,6 @@"type": "command","command": "node --disable-warning=ExperimentalWarning --experimental-strip-types \"${GEMINI_PROJECT_DIR:-.}/.claude/scripts/validate-write.ts\"","timeout": 15000- },- {- "type": "command",- "command": "node --disable-warning=ExperimentalWarning --experimental-strip-types \"${GEMINI_PROJECT_DIR:-.}/.claude/scripts/qmd-refresh.ts\"",- "timeout": 15000}]}diff --git a/.gitignore b/.gitignoreindex b089651..aca7754 100644--- a/.gitignore+++ b/.gitignore@@ -32,3 +32,7 @@ thinking/session-logs/# Node typecheck deps (CI + local dev only; runtime is zero-deps)node_modules/.claude/scripts/node_modules/++# Hook runtime state (local, self-pruning / debounce sentinel)+.claude/scripts/.hint-state.json+.claude/scripts/.qmd-refresh-sentinel