A self-organizing Obsidian vault that gives AI coding agents persistent memory.
TypeScript ai-agentsclaude-codecodex-cligemini-cliknowledge-managementobsidianobsidian-vaultpersistent-memorysecond-braintemplate
feat: keep QMD index fresh mid-session via detached hooks (#61)
Brenno Ferrari7b97d6321c4e
diff --git a/.claude/scripts/.gitignore b/.claude/scripts/.gitignoreindex 504afef..a4c22ba 100644--- a/.claude/scripts/.gitignore+++ b/.claude/scripts/.gitignore@@ -1,2 +1,3 @@node_modules/package-lock.json+.qmd-refresh-sentineldiff --git a/.claude/scripts/lib/qmd-refresh.ts b/.claude/scripts/lib/qmd-refresh.tsnew file mode 100644index 0000000..d698d77--- /dev/null+++ b/.claude/scripts/lib/qmd-refresh.ts@@ -0,0 +1,226 @@+/**+ * Mid-session QMD refresh — pure predicates, spawn composition, and the+ * shared debounced-trigger flow. Consumed by the PostToolUse hook+ * (`.claude/scripts/qmd-refresh.ts`), the Stop hook+ * (`.claude/scripts/stop-checklist.ts`), and the detached worker+ * (`.claude/scripts/qmd-refresh-run.ts`). Centralizing the lifecycle+ * here guarantees both hook entries honor the same debounce contract+ * and spawn shape — the only way to drift is to bypass this module.+ *+ * The pure helpers at the top of this file (path filter, debounce math,+ * vault-root resolver, invocation composer) run identically on Windows,+ * macOS, and Linux and are exercised in the CI matrix without side+ * effects. The impure orchestration at the bottom (sentinel + spawn)+ * delegates platform-specific spawn shape to `lib/qmd.ts`.+ */++import { spawn } from "node:child_process";+import { statSync, writeFileSync } from "node:fs";+import { resolve as resolvePath } from "node:path";+import { buildQmdCommand, resolveQmdEntry } from "./qmd.ts";+import { debug } from "./hook-io.ts";+import { qmdArgsWithIndex } from "./session-start.ts";++/**+ * Path segments that must never trigger a QMD refresh — writes into these+ * aren't vault content. Matched case-sensitively against the forward-slash+ * normalized path; Windows paths are normalized by the caller before this+ * check. Leading "/" on each segment prevents accidental substring matches+ * like ".github" matching under ".git".+ */+const SKIP_SEGMENTS: readonly string[] = [+ "/.git/",+ "/.obsidian/",+ "/node_modules/",+];++/**+ * Return true if a Write/Edit to `filePath` should trigger a QMD refresh.+ * Accepts `.md` files that aren't under an excluded segment. Rejects non-+ * markdown writes and writes into version control, plugin config, or+ * dependency trees. Accepts absolute or relative paths; backslashes are+ * normalized so Windows paths (`C:\\vault\\note.md`) are handled the same+ * as Unix paths.+ *+ * Over-triggering is harmless (qmd update is idempotent and silent on+ * no-op); under-triggering is the failure mode we optimize against, so+ * the filter is deliberately permissive beyond the three skip segments.+ */+export function shouldRefreshForPath(filePath: string): boolean {+ if (typeof filePath !== "string" || filePath === "") return false;+ if (!filePath.toLowerCase().endsWith(".md")) return false;+ const normalized = "/" + filePath.replaceAll("\\", "/");+ return !SKIP_SEGMENTS.some((seg) => normalized.includes(seg));+}++/**+ * Return true when a previous refresh ran recently enough that this one+ * should be skipped. `sentinelMtimeMs` is the mtime of the debounce+ * sentinel (or null when it doesn't exist yet); `nowMs` is Date.now();+ * `debounceMs` is the minimum gap between refreshes.+ *+ * Null sentinel → not debounced (first run in this session or sentinel+ * was cleared). Clock skew going backwards (nowMs < mtime) is treated as+ * "not debounced" so we don't wedge indefinitely on a bad clock — if+ * anything, that's the safer failure mode.+ */+export function isDebounced(+ sentinelMtimeMs: number | null,+ nowMs: number,+ debounceMs: number,+): boolean {+ if (sentinelMtimeMs === null) return false;+ const elapsed = nowMs - sentinelMtimeMs;+ if (elapsed < 0) return false;+ return elapsed < debounceMs;+}++/**+ * Return the absolute vault root derived from a hook script's own+ * directory. Hook scripts live at `<vault>/.claude/scripts/`, so going+ * two segments up resolves the vault root irrespective of the invoking+ * shell's cwd or whether any `*_PROJECT_DIR` env var is set.+ *+ * This anchor lets the worker read the manifest from a known-good+ * absolute path, eliminating a class of silent bug where a drifted cwd+ * caused the worker to update QMD's default global collection instead+ * of the vault's named index.+ */+export function resolveVaultRoot(scriptDirAbsolute: string): string {+ return resolvePath(scriptDirAbsolute, "..", "..");+}++/**+ * A single qmd subcommand spawn — cmd, args, shell flag (from+ * `buildQmdCommand`) plus the per-step timeout budget. Pairing the+ * timeout with its invocation keeps the worker's execution loop from+ * needing a parallel positional array; reordering the pipeline can+ * never silently swap timeouts onto the wrong step.+ */+type QmdInvocation = {+ readonly cmd: string;+ readonly args: readonly string[];+ readonly shell: boolean;+ readonly timeoutMs: number;+};++/**+ * Compose the invocation sequence the detached worker must spawn in+ * order: `update` (refresh BM25/FTS index), then `embed` (refresh+ * vector index), then a tail-chase `update` that catches files written+ * during the first two steps so they're BM25-searchable immediately+ * rather than waiting 30s+ for the next trigger. The tail update's new+ * content picks up vector coverage on the next refresh cycle.+ *+ * Per-step timeouts: `update` caps at 60s each (enough for an+ * incremental re-index on a 10k-note vault); `embed` caps at 5 minutes+ * (first run may download the embedding model on a fresh machine). All+ * three run detached — the budgets bound machine drag, not user+ * latency.+ *+ * Kept pure so tests can assert the full invocation list across+ * platforms without spawning anything. Locking argv and timeouts at the+ * unit level means the CI matrix catches drift on every OS, not just+ * the OS where a live qmd happens to be installed.+ */+export function composeWorkerInvocations(+ qmdIndex: string | null,+ entry: string | null,+): readonly QmdInvocation[] {+ const update: QmdInvocation = {+ ...buildQmdCommand(entry, qmdArgsWithIndex(qmdIndex, ["update"])),+ timeoutMs: 60_000,+ };+ const embed: QmdInvocation = {+ ...buildQmdCommand(entry, qmdArgsWithIndex(qmdIndex, ["embed"])),+ timeoutMs: 300_000,+ };+ return [update, embed, update];+}++// --- Impure orchestration ---------------------------------------------------++/**+ * Read the debounce sentinel's mtime, or null when it doesn't exist.+ * Any fs error (permission, race against deletion) collapses to null+ * and the caller treats it as "no prior refresh" — the worst outcome+ * is an extra worker spawn, which qmd serializes internally.+ */+function readSentinelMtime(sentinelPath: string): number | null {+ try {+ return statSync(sentinelPath).mtimeMs;+ } catch {+ return null;+ }+}++/**+ * Stamp the sentinel so subsequent triggers within `debounceMs` skip.+ * A single `writeFileSync` is one syscall on Windows and POSIX alike+ * and atomically bumps mtime — simpler than an open/futimes/close+ * dance, and the sentinel's contents are never read (only its mtime).+ */+function touchSentinel(sentinelPath: string): void {+ try {+ writeFileSync(sentinelPath, "");+ } catch (err) {+ debug(+ `qmd-refresh: sentinel write failed: ${(err as Error)?.message ?? "?"}`,+ );+ }+}++/**+ * Spawn the detached worker. `stdio: 'ignore'` + `.unref()` + `detached`+ * survive parent exit without leaving file descriptors open, and+ * `windowsHide: true` suppresses the transient console window that a+ * naked `spawn` creates on Windows. Errors are logged under HOOK_DEBUG+ * only — production is silent per the hook protocol.+ */+function spawnDetachedWorker(workerPath: string, logPrefix: string): void {+ const child = spawn(+ process.execPath,+ ["--experimental-strip-types", workerPath],+ {+ detached: true,+ stdio: "ignore",+ windowsHide: true,+ cwd: process.cwd(),+ },+ );+ child.on("error", (err) => {+ debug(`${logPrefix}: worker spawn error: ${err.message}`);+ });+ child.unref();+}++/**+ * The end-to-end refresh trigger both hook entries call: check the+ * debounce window, bail if qmd isn't resolvable, otherwise stamp the+ * sentinel and fire the detached worker. Returns immediately — every+ * path is non-blocking.+ *+ * Callers set their own `logPrefix` so HOOK_DEBUG traces distinguish+ * the PostToolUse path ("qmd-refresh") from the Stop path+ * ("stop-checklist"). Both share the same sentinel + debounce window+ * so a Stop firing seconds after a PostToolUse refresh won't spawn a+ * redundant second worker.+ */+export function triggerDebouncedRefresh(opts: {+ readonly sentinelPath: string;+ readonly workerPath: string;+ readonly debounceMs: number;+ readonly logPrefix: string;+}): void {+ const mtime = readSentinelMtime(opts.sentinelPath);+ if (isDebounced(mtime, Date.now(), opts.debounceMs)) {+ debug(`${opts.logPrefix}: debounced`);+ return;+ }+ if (resolveQmdEntry() === null) {+ debug(`${opts.logPrefix}: qmd not resolvable; skipping`);+ return;+ }+ touchSentinel(opts.sentinelPath);+ spawnDetachedWorker(opts.workerPath, opts.logPrefix);+}diff --git a/.claude/scripts/pre-compact.ts b/.claude/scripts/pre-compact.tsindex 129734c..cb411fe 100644--- a/.claude/scripts/pre-compact.ts+++ b/.claude/scripts/pre-compact.ts@@ -15,9 +15,10 @@ import {statSync,unlinkSync,} from "node:fs";-import { join } from "node:path";+import { dirname, join, resolve as resolvePath } from "node:path";import { fileURLToPath } from "node:url";import { debug, readStdinJson } from "./lib/hook-io.ts";+import { triggerDebouncedRefresh } from "./lib/qmd-refresh.ts";type HookInput = {readonly transcript_path?: unknown;@@ -64,6 +65,23 @@ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {const input = await readStdinJson<HookInput>();if (!input) process.exit(0);+ // Fire a debounced QMD refresh before (or alongside) the backup.+ // Writes tend to cluster right before compaction, and catching them+ // now means the session-resume SessionStart runs `qmd update` against+ // an index that's already current. Uses the same sentinel as the+ // PostToolUse and Stop hooks so we never spawn a redundant worker.+ {+ const scriptDir = dirname(fileURLToPath(import.meta.url));+ triggerDebouncedRefresh({+ sentinelPath:+ process.env["QMD_REFRESH_SENTINEL"] ??+ join(scriptDir, ".qmd-refresh-sentinel"),+ workerPath: resolvePath(scriptDir, "qmd-refresh-run.ts"),+ debounceMs: 30_000,+ logPrefix: "pre-compact",+ });+ }+const transcriptPath =typeof input.transcript_path === "string" ? input.transcript_path : "";const trigger =diff --git a/.claude/scripts/qmd-refresh-run.ts b/.claude/scripts/qmd-refresh-run.tsnew file mode 100644index 0000000..91f72b0--- /dev/null+++ b/.claude/scripts/qmd-refresh-run.ts@@ -0,0 +1,71 @@+#!/usr/bin/env node+/**+ * Detached worker for the mid-session QMD refresh. Invoked by+ * `qmd-refresh.ts` (PostToolUse hook) and `stop-checklist.ts` (Stop+ * hook) as a backgrounded child so the hook itself returns in+ * milliseconds.+ *+ * Runs `qmd update` (BM25/FTS) followed by `qmd embed` (vector index)+ * so mid-session writes become searchable through every retrieval arm,+ * not just keyword search. Each step's timeout travels on the+ * invocation tuple from `composeWorkerInvocations`, so reordering the+ * pipeline can never silently swap timeouts onto the wrong step.+ *+ * Never writes to stdout/stderr. Never exits non-zero in a way the+ * user sees, since both parents `stdio: 'ignore'` the child. qmd+ * failures are swallowed deliberately: QMD is optional infrastructure,+ * and a flaky refresh must not pollute the next session's context or+ * terminal.+ *+ * Cwd independence: the vault root is derived from the worker's own+ * absolute script path (`<vault>/.claude/scripts/`), not from+ * `process.cwd()` or env vars. This survives the case where the parent+ * hook fires from a drifted shell cwd without CLAUDE_PROJECT_DIR set —+ * without that anchor, the manifest read failed silently and the+ * worker updated QMD's default global collection instead of the+ * vault's named one.+ *+ * Multi-platform: delegates the spawn shape to `lib/qmd.ts`, which+ * routes through `process.execPath qmd.js` on every OS, bypassing the+ * .cmd shim on Windows.+ */++import { spawnSync } from "node:child_process";+import { readFileSync } from "node:fs";+import { dirname, resolve as resolvePath } from "node:path";+import { fileURLToPath } from "node:url";+import { debug } from "./lib/hook-io.ts";+import { parseQmdIndex } from "./lib/session-start.ts";+import { resolveQmdEntry } from "./lib/qmd.ts";+import {+ composeWorkerInvocations,+ resolveVaultRoot,+} from "./lib/qmd-refresh.ts";++const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));+const VAULT_ROOT = resolveVaultRoot(SCRIPT_DIR);+const MANIFEST_PATH = resolvePath(VAULT_ROOT, "vault-manifest.json");++function readManifestRaw(): string | null {+ try {+ return readFileSync(MANIFEST_PATH, { encoding: "utf-8" });+ } catch {+ return null;+ }+}++const qmdIndex = parseQmdIndex(readManifestRaw());+const invocations = composeWorkerInvocations(qmdIndex, resolveQmdEntry());++for (const inv of invocations) {+ const result = spawnSync(inv.cmd, inv.args as string[], {+ stdio: "ignore",+ timeout: inv.timeoutMs,+ shell: inv.shell,+ windowsHide: true,+ cwd: VAULT_ROOT,+ });+ if (result.error) {+ debug(`qmd-refresh-run: ${inv.args.join(" ")} — ${result.error.message}`);+ }+}diff --git a/.claude/scripts/qmd-refresh.ts b/.claude/scripts/qmd-refresh.tsnew file mode 100644index 0000000..dbfa8b6--- /dev/null+++ b/.claude/scripts/qmd-refresh.ts@@ -0,0 +1,75 @@+#!/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/stop-checklist.ts b/.claude/scripts/stop-checklist.tsindex 22ccc2b..f178107 100644--- a/.claude/scripts/stop-checklist.ts+++ b/.claude/scripts/stop-checklist.ts@@ -1,13 +1,30 @@#!/usr/bin/env node/**- * Stop hook — remind the user of session-wrap-up tasks.+ * Stop hook — remind the user of session-wrap-up tasks and kick a+ * debounced QMD refresh so the next session opens against a current+ * index.*- * Silently exits when the hook is being re-entered by a secondary agent- * (stop_hook_active=true) to avoid recursive reminder output. Otherwise- * prints a short vault-hygiene checklist.+ * Silently exits when the hook is being re-entered by a secondary+ * agent (stop_hook_active=true) to avoid recursive reminder output and+ * duplicated refresh spawns. Otherwise prints the vault-hygiene+ * checklist and routes through the same `triggerDebouncedRefresh`+ * entry the PostToolUse hook uses — one debounce contract, one spawn+ * shape, zero drift between the two paths.*/+import { dirname, join, resolve as resolvePath } from "node:path";+import { fileURLToPath } from "node:url";import { readStdinJson } from "./lib/hook-io.ts";+import { triggerDebouncedRefresh } from "./lib/qmd-refresh.ts";++const DEBOUNCE_MS = 30_000;+const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));+// See qmd-refresh.ts for the rationale behind the env override — it+// keeps parallel test workers from racing on the shared repo sentinel.+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 stop_hook_active?: unknown;@@ -25,3 +42,10 @@ const checklist = [].join("\n");process.stdout.write(checklist + "\n");++triggerDebouncedRefresh({+ sentinelPath: SENTINEL_PATH,+ workerPath: WORKER_PATH,+ debounceMs: DEBOUNCE_MS,+ logPrefix: "stop-checklist",+});diff --git a/.claude/scripts/tests/_helpers.ts b/.claude/scripts/tests/_helpers.tsindex 111c07d..cae0b0d 100644--- a/.claude/scripts/tests/_helpers.ts+++ b/.claude/scripts/tests/_helpers.ts@@ -18,6 +18,7 @@ export type RunResult = {export function runScript(scriptPath: string,stdin: string | object | null,+ envOverrides?: Readonly<Record<string, string>>,): RunResult {const input =stdin === null@@ -28,7 +29,14 @@ export function runScript(const proc = spawnSync(process.execPath,["--experimental-strip-types", scriptPath],- { input, encoding: "utf-8", timeout: 10_000 },+ {+ input,+ encoding: "utf-8",+ timeout: 10_000,+ env: envOverrides+ ? { ...process.env, ...envOverrides }+ : process.env,+ },);return {stdout: proc.stdout ?? "",diff --git a/.claude/scripts/tests/qmd-refresh.integration.test.ts b/.claude/scripts/tests/qmd-refresh.integration.test.tsnew file mode 100644index 0000000..ca31f7b--- /dev/null+++ b/.claude/scripts/tests/qmd-refresh.integration.test.ts@@ -0,0 +1,241 @@+/**+ * Subprocess integration tests for the qmd-refresh.ts PostToolUse hook.+ *+ * Exercises the real stdin → decision → sentinel pipeline by spawning+ * the hook entry script exactly the way each agent's settings.json+ * would: `node --experimental-strip-types qmd-refresh.ts` with a JSON+ * payload on stdin. The sentinel file is the only observable the hook+ * produces (stdout must stay silent), so each test asserts on sentinel+ * presence / mtime + exit code.+ *+ * Deliberately does NOT depend on qmd being installed. The hook'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.+ *+ * Runs identically on Windows, macOS, and Linux — the hook's+ * cross-platform shape is asserted through the same spawn mechanism+ * that powers validate-write.test.ts and stop-checklist.test.ts.+ */++import { test, describe, after, before, beforeEach } from "node:test";+import assert from "node:assert/strict";+import { fileURLToPath } from "node:url";+import { dirname, join, resolve } from "node:path";+import {+ mkdtempSync,+ rmSync,+ statSync,+ utimesSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+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");++// Route the hook's debounce sentinel through a per-file tmp path so+// this test can't race with any other test file (notably+// stop-checklist.test.ts, which also invokes triggerDebouncedRefresh+// and would otherwise share the repo's .claude/scripts/.qmd-refresh-+// sentinel). The hook reads QMD_REFRESH_SENTINEL when set.+let TMP_DIR = "";+let SENTINEL = "";++before(() => {+ TMP_DIR = mkdtempSync(join(tmpdir(), "qmd-refresh-integration-"));+ SENTINEL = join(TMP_DIR, ".qmd-refresh-sentinel");+});++after(() => {+ if (TMP_DIR) rmSync(TMP_DIR, { recursive: true, force: true });+});++// Used to build realistic absolute `file_path` fixtures for hook payloads.+const VAULT_ROOT = resolve(SCRIPT_DIR, "..", "..", "..");++const runHook = (stdin: string | object | null) =>+ spawnHook(SCRIPT, stdin, { QMD_REFRESH_SENTINEL: SENTINEL });++function clearSentinel(): void {+ try {+ rmSync(SENTINEL, { force: true });+ } catch {+ /* ignored */+ }+}++function sentinelMtime(): number | null {+ try {+ return statSync(SENTINEL).mtimeMs;+ } catch {+ return null;+ }+}++function makeStaleSentinel(minutesAgo: number): void {+ // Create a sentinel whose mtime is outside the debounce window, so+ // "not debounced" paths can be asserted deterministically.+ writeFileSync(SENTINEL, "");+ // utimesSync accepts seconds-since-epoch for both atime and mtime+ // on every platform.+ const staleSec = (Date.now() - minutesAgo * 60_000) / 1000;+ utimesSync(SENTINEL, staleSec, staleSec);+}++// Every test starts from a clean slate.+beforeEach(() => {+ clearSentinel();+});++// --- Silent no-op paths (must not touch the sentinel) ---+describe("qmd-refresh — 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);+ assert.equal(stdout, "");+ assert.equal(stderr, "");+ assert.equal(sentinelMtime(), null);+ });++ test("malformed JSON exits 0 silently", () => {+ const { stdout, code } = runHook("not json {{{");+ assert.equal(code, 0);+ assert.equal(stdout, "");+ assert.equal(sentinelMtime(), null);+ });++ test("missing tool_input exits 0 silently", () => {+ const { stdout, code } = runHook({});+ assert.equal(code, 0);+ assert.equal(stdout, "");+ assert.equal(sentinelMtime(), null);+ });++ test("null tool_input exits 0 silently", () => {+ const { stdout, code } = runHook({ tool_input: null });+ assert.equal(code, 0);+ assert.equal(stdout, "");+ assert.equal(sentinelMtime(), null);+ });++ test("non-string file_path exits 0 silently", () => {+ const { stdout, code } = runHook({ tool_input: { file_path: 42 } });+ assert.equal(code, 0);+ assert.equal(stdout, "");+ assert.equal(sentinelMtime(), null);+ });++ test("non-markdown path exits 0 silently", () => {+ const { stdout, code } = runHook({+ tool_input: { file_path: "/vault/work/active/note.txt" },+ });+ assert.equal(code, 0);+ assert.equal(stdout, "");+ assert.equal(sentinelMtime(), null);+ });++ test(".git path exits 0 silently", () => {+ const { stdout, code } = runHook({+ tool_input: { file_path: "/vault/.git/HEAD.md" },+ });+ assert.equal(code, 0);+ assert.equal(stdout, "");+ assert.equal(sentinelMtime(), null);+ });++ test(".obsidian path exits 0 silently", () => {+ const { stdout, code } = runHook({+ tool_input: { file_path: "/vault/.obsidian/workspace.md" },+ });+ assert.equal(code, 0);+ assert.equal(stdout, "");+ assert.equal(sentinelMtime(), null);+ });++ test("node_modules path exits 0 silently", () => {+ const { stdout, code } = runHook({+ tool_input: {+ file_path: "/vault/.claude/scripts/node_modules/foo/README.md",+ },+ });+ assert.equal(code, 0);+ assert.equal(stdout, "");+ assert.equal(sentinelMtime(), null);+ });++ test("Windows-form skip path exits 0 silently", () => {+ const { stdout, code } = runHook({+ tool_input: { file_path: "C:\\vault\\.git\\info\\note.md" },+ });+ assert.equal(code, 0);+ assert.equal(stdout, "");+ assert.equal(sentinelMtime(), null);+ });+});++// --- Debounce path (sentinel controls whether worker is spawned) ---+describe("qmd-refresh — debounce", () => {+ test("fresh sentinel blocks a subsequent trigger (sentinel unchanged)", () => {+ // Arrange: sentinel was just "touched" (mtime = now).+ writeFileSync(SENTINEL, "");+ const before = sentinelMtime();+ assert.ok(before !== null, "sentinel should exist after writeFileSync");++ const { stdout, code } = runHook({+ tool_input: { file_path: join(VAULT_ROOT, "work/active/note.md") },+ });++ assert.equal(code, 0);+ assert.equal(stdout, "");+ // A debounced run must not bump the sentinel mtime; the whole+ // point is that a burst of writes only spawns one worker per+ // window.+ assert.equal(sentinelMtime(), before);+ });+});++// --- 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+ // 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.+ test("sentinel is bumped when qmd resolves; skipped otherwise", () => {+ const qmdAvailable = resolveQmdEntry() !== null;++ // Stale sentinel keeps the debounce branch inactive. 5 minutes+ // is well beyond the 30s debounce window the hook uses.+ makeStaleSentinel(5);+ const before = sentinelMtime();+ assert.ok(before !== null);++ const { stdout, code } = runHook({+ tool_input: { file_path: join(VAULT_ROOT, "work/active/note.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,+ `expected sentinel mtime to advance when qmd is installed; got before=${before}, after=${after}`,+ );+ } else {+ assert.equal(+ after,+ before,+ "sentinel must not be touched when qmd is not resolvable — the hook exits before touchSentinel()",+ );+ }+ });+});+diff --git a/.claude/scripts/tests/qmd-refresh.test.ts b/.claude/scripts/tests/qmd-refresh.test.tsnew file mode 100644index 0000000..00c95a2--- /dev/null+++ b/.claude/scripts/tests/qmd-refresh.test.ts@@ -0,0 +1,273 @@+/**+ * Unit tests for lib/qmd-refresh.ts pure helpers.+ *+ * Locks the predicates and composition logic the PostToolUse hook, the+ * Stop hook, and the detached worker all depend on. Pure tests run+ * identically on every OS in the CI matrix, so argv drift (wrong order,+ * missing `--index`, dropped subcommand) fails here before any live qmd+ * invocation would notice on macOS/Linux only.+ *+ * Subprocess integration coverage for the hook entry script lives in+ * `qmd-refresh.integration.test.ts` — both are exercised by+ * `npm test` in the hook-scripts package.+ */++import { test, describe } from "node:test";+import assert from "node:assert/strict";+import { resolve as resolvePath, sep as pathSep } from "node:path";+import {+ composeWorkerInvocations,+ isDebounced,+ resolveVaultRoot,+ shouldRefreshForPath,+} from "../lib/qmd-refresh.ts";++describe("shouldRefreshForPath — accepts vault markdown", () => {+ test("accepts a relative vault note", () => {+ assert.equal(shouldRefreshForPath("work/active/project.md"), true);+ });+ test("accepts an absolute Unix vault note", () => {+ assert.equal(+ shouldRefreshForPath("/Users/me/vault/work/active/project.md"),+ true,+ );+ });+ test("accepts an absolute Windows vault note", () => {+ assert.equal(+ shouldRefreshForPath("C:\\Users\\me\\vault\\work\\active\\project.md"),+ true,+ );+ });+ test("accepts a Windows UNC path", () => {+ assert.equal(+ shouldRefreshForPath("\\\\server\\share\\vault\\note.md"),+ true,+ );+ });+ test("accepts uppercase .MD extension", () => {+ assert.equal(shouldRefreshForPath("work/active/project.MD"), true);+ });+ test("accepts brain/, org/, perf/ paths (vault content roots)", () => {+ assert.equal(shouldRefreshForPath("brain/Patterns.md"), true);+ assert.equal(shouldRefreshForPath("org/people/Alice.md"), true);+ assert.equal(shouldRefreshForPath("perf/Brag Doc.md"), true);+ });+ test("accepts paths with spaces (Obsidian-style filenames)", () => {+ assert.equal(shouldRefreshForPath("work/1-1/Jane Smith 2026-04-05.md"), true);+ });+});++describe("shouldRefreshForPath — rejects non-markdown writes", () => {+ test("rejects empty path", () => {+ assert.equal(shouldRefreshForPath(""), false);+ });+ test("rejects non-string (defensive)", () => {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ assert.equal(shouldRefreshForPath(undefined as any), false);+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ assert.equal(shouldRefreshForPath(null as any), false);+ });+ test("rejects .txt, .json, .ts, .yaml", () => {+ assert.equal(shouldRefreshForPath("work/note.txt"), false);+ assert.equal(shouldRefreshForPath("vault-manifest.json"), false);+ assert.equal(shouldRefreshForPath(".claude/scripts/foo.ts"), false);+ assert.equal(shouldRefreshForPath("config.yaml"), false);+ });+ test("rejects .mdx (not qmd's `**/*.md` pattern)", () => {+ assert.equal(shouldRefreshForPath("page.mdx"), false);+ });+ test("rejects extensionless paths", () => {+ assert.equal(shouldRefreshForPath("Makefile"), false);+ assert.equal(shouldRefreshForPath("LICENSE"), false);+ });+});++describe("shouldRefreshForPath — rejects skip-segment paths", () => {+ test("rejects .git internals", () => {+ assert.equal(shouldRefreshForPath(".git/COMMIT_EDITMSG.md"), false);+ assert.equal(+ shouldRefreshForPath("/Users/me/vault/.git/info/exclude.md"),+ false,+ );+ });+ test("rejects .obsidian config", () => {+ assert.equal(shouldRefreshForPath(".obsidian/workspace.md"), false);+ assert.equal(+ shouldRefreshForPath("/vault/.obsidian/plugins/foo/README.md"),+ false,+ );+ });+ test("rejects node_modules trees", () => {+ assert.equal(+ shouldRefreshForPath(".claude/scripts/node_modules/foo/README.md"),+ false,+ );+ assert.equal(+ shouldRefreshForPath("/vault/node_modules/pkg/CHANGELOG.md"),+ false,+ );+ });+ test("rejects Windows-form skip paths (backslash normalization)", () => {+ assert.equal(+ shouldRefreshForPath("C:\\vault\\.git\\info\\note.md"),+ false,+ );+ assert.equal(+ shouldRefreshForPath("C:\\vault\\.obsidian\\workspace.md"),+ false,+ );+ assert.equal(+ shouldRefreshForPath(+ "C:\\vault\\.claude\\scripts\\node_modules\\pkg\\README.md",+ ),+ false,+ );+ });+ test("segment-boundary enforcement — .github does NOT match .git", () => {+ assert.equal(+ shouldRefreshForPath(".github/ISSUE_TEMPLATE.md"),+ true,+ );+ });+ test("segment-boundary enforcement — node_modules_backup does NOT match", () => {+ assert.equal(+ shouldRefreshForPath("archive/node_modules_backup_docs.md"),+ true,+ );+ });+});++describe("isDebounced — fresh sentinel", () => {+ test("returns true when elapsed < debounce window", () => {+ assert.equal(isDebounced(1_000, 1_500, 30_000), true);+ });+ test("returns true at the very start of the window (0ms elapsed)", () => {+ assert.equal(isDebounced(1_000, 1_000, 30_000), true);+ });+ test("returns false exactly at the debounce boundary", () => {+ assert.equal(isDebounced(1_000, 31_000, 30_000), false);+ });+ test("returns false when elapsed exceeds window", () => {+ assert.equal(isDebounced(1_000, 60_000, 30_000), false);+ });+});++describe("isDebounced — absent or invalid sentinel", () => {+ test("returns false when sentinel doesn't exist (null mtime)", () => {+ assert.equal(isDebounced(null, 1_000, 30_000), false);+ });+ test("returns false on negative elapsed (clock skew backwards)", () => {+ // Safer failure mode: wall-clock going backwards should not wedge+ // the refresh indefinitely.+ assert.equal(isDebounced(10_000, 5_000, 30_000), false);+ });+ test("returns false when debounce window is zero", () => {+ assert.equal(isDebounced(1_000, 1_000, 0), false);+ });+});++describe("resolveVaultRoot", () => {+ // These tests compare `resolveVaultRoot` output to the platform's own+ // `path.resolve` output on the expected vault root. Using resolvePath+ // on both sides dodges Windows's drive-letter prepending (e.g.+ // `/vault/.claude/scripts` becomes `D:\vault\.claude\scripts`) that+ // tripped up an earlier version of these tests on the CI matrix.+ test("strips the .claude/scripts suffix from an absolute input", () => {+ const result = resolveVaultRoot(+ resolvePath("/Users/me/vault/.claude/scripts"),+ );+ assert.equal(result, resolvePath("/Users/me/vault"));+ });+ test("handles a trailing separator gracefully", () => {+ const result = resolveVaultRoot(+ resolvePath("/vault/.claude/scripts") + pathSep,+ );+ assert.equal(result, resolvePath("/vault"));+ });+ test("always returns an absolute path (path.resolve guarantees this)", () => {+ // Relative inputs get resolved against cwd; we only assert+ // absoluteness here — the suffix-stripping semantics are locked+ // by the absolute-input test above.+ const result = resolveVaultRoot("a/b/.claude/scripts");+ const isAbsolute =+ /^[A-Za-z]:[\\/]/.test(result) ||+ result.startsWith("\\\\") ||+ result.startsWith("/");+ assert.ok(isAbsolute, `expected absolute path, got: ${result}`);+ });+});++describe("composeWorkerInvocations", () => {+ test("returns update, embed, and a tail-chase update in that order", () => {+ const invs = composeWorkerInvocations(+ "obsidian-mind",+ "/opt/qmd/qmd.js",+ );+ assert.equal(invs.length, 3);+ assert.ok(invs[0]?.args.includes("update"));+ assert.ok(invs[1]?.args.includes("embed"));+ assert.ok(invs[2]?.args.includes("update"));+ // The tail-chase step must NOT be an embed — keeping the worker+ // bounded means we accept one cycle of vec-staleness for+ // tail-landed content.+ assert.equal(invs[2]?.args.includes("embed"), false);+ });++ test("threads --index <name> through every invocation when set", () => {+ const invs = composeWorkerInvocations("vault-2", "/opt/qmd/qmd.js");+ for (const inv of invs) {+ assert.deepEqual(+ inv.args.slice(0, 3),+ ["/opt/qmd/qmd.js", "--index", "vault-2"],+ `expected --index vault-2 to precede the subcommand in ${inv.args.join(" ")}`,+ );+ }+ assert.equal(invs[0]?.args.at(-1), "update");+ assert.equal(invs[1]?.args.at(-1), "embed");+ assert.equal(invs[2]?.args.at(-1), "update");+ });++ test("omits --index when qmdIndex is null (legacy / pre-named fork)", () => {+ const invs = composeWorkerInvocations(null, "/opt/qmd/qmd.js");+ for (const inv of invs) {+ assert.equal(inv.args.includes("--index"), false);+ }+ assert.deepEqual(invs[0]?.args, ["/opt/qmd/qmd.js", "update"]);+ assert.deepEqual(invs[1]?.args, ["/opt/qmd/qmd.js", "embed"]);+ assert.deepEqual(invs[2]?.args, ["/opt/qmd/qmd.js", "update"]);+ });++ test("every invocation goes through process.execPath when entry resolves", () => {+ const invs = composeWorkerInvocations("v", "/opt/qmd/qmd.js");+ for (const inv of invs) {+ assert.equal(inv.cmd, process.execPath);+ assert.equal(inv.shell, false);+ }+ });++ test("falls back to bare `qmd` with shell: true when entry is null", () => {+ const invs = composeWorkerInvocations("v", null);+ for (const inv of invs) {+ assert.equal(inv.cmd, "qmd");+ assert.equal(inv.shell, true);+ }+ });++ test("fallback preserves --index threading across all steps", () => {+ const invs = composeWorkerInvocations("vault-2", null);+ assert.deepEqual(invs[0]?.args, ["--index", "vault-2", "update"]);+ assert.deepEqual(invs[1]?.args, ["--index", "vault-2", "embed"]);+ assert.deepEqual(invs[2]?.args, ["--index", "vault-2", "update"]);+ });++ test("embed gets a longer budget than update (model download slot)", () => {+ const [update, embed, tail] = composeWorkerInvocations("v", "/opt/qmd.js");+ assert.ok(+ update && embed && tail && embed.timeoutMs > update.timeoutMs,+ `embed budget (${embed?.timeoutMs}) must exceed update budget (${update?.timeoutMs})`,+ );+ // Tail-chase update reuses the leading update's budget — same+ // subcommand, same time shape.+ assert.equal(tail?.timeoutMs, update?.timeoutMs);+ });+});diff --git a/.claude/settings.json b/.claude/settings.jsonindex 5773fe4..18b219a 100644--- a/.claude/settings.json+++ b/.claude/settings.json@@ -31,6 +31,11 @@"type": "command","command": "node --experimental-strip-types \"${CLAUDE_PROJECT_DIR:-.}/.claude/scripts/validate-write.ts\"","timeout": 15+ },+ {+ "type": "command",+ "command": "node --experimental-strip-types \"${CLAUDE_PROJECT_DIR:-.}/.claude/scripts/qmd-refresh.ts\"",+ "timeout": 15}]}diff --git a/.codex/hooks.json b/.codex/hooks.jsonindex e6f7011..762e848 100644--- a/.codex/hooks.json+++ b/.codex/hooks.json@@ -31,6 +31,11 @@"type": "command","command": "node --experimental-strip-types \"${CODEX_PROJECT_DIR:-.}/.claude/scripts/validate-write.ts\"","timeout": 15+ },+ {+ "type": "command",+ "command": "node --experimental-strip-types \"${CODEX_PROJECT_DIR:-.}/.claude/scripts/qmd-refresh.ts\"",+ "timeout": 15}]}@@ -40,7 +45,7 @@"hooks": [{"type": "command",- "command": "bash -c 'printf \"Session end checklist:\\n- Archive completed projects?\\n- Update indexes?\\n- New notes linked? (orphans are bugs)\\n\"'",+ "command": "node --experimental-strip-types \"${CODEX_PROJECT_DIR:-.}/.claude/scripts/stop-checklist.ts\"","timeout": 5}]diff --git a/.gemini/settings.json b/.gemini/settings.jsonindex efa1879..6e01cd9 100644--- a/.gemini/settings.json+++ b/.gemini/settings.json@@ -31,6 +31,11 @@"type": "command","command": "node --experimental-strip-types \"${GEMINI_PROJECT_DIR:-.}/.claude/scripts/validate-write.ts\"","timeout": 15000+ },+ {+ "type": "command",+ "command": "node --experimental-strip-types \"${GEMINI_PROJECT_DIR:-.}/.claude/scripts/qmd-refresh.ts\"",+ "timeout": 15000}]}@@ -51,7 +56,7 @@"hooks": [{"type": "command",- "command": "bash -c 'printf \"Session end checklist:\\n- Archive completed projects?\\n- Update indexes?\\n- New notes linked? (orphans are bugs)\\n\"'",+ "command": "node --experimental-strip-types \"${GEMINI_PROJECT_DIR:-.}/.claude/scripts/stop-checklist.ts\"","timeout": 5000}]