A self-organizing Obsidian vault that gives AI coding agents persistent memory.
TypeScript ai-agentsclaude-codecodex-cligemini-cliknowledge-managementobsidianobsidian-vaultpersistent-memorysecond-braintemplate
fix: stop the test suite leaving detached qmd-refresh-run workers behind (#338)
Brenno Ferrari0a58edfa0cd8
diff --git a/.claude/scripts/lib/qmd-refresh.ts b/.claude/scripts/lib/qmd-refresh.tsindex e05486e..4ea7e86 100644--- a/.claude/scripts/lib/qmd-refresh.ts+++ b/.claude/scripts/lib/qmd-refresh.ts@@ -276,6 +276,23 @@ function touchSentinel(sentinelPath: string): void {}}+/**+ * The switch that stops the detached qmd refresh: this trigger's worker, and+ * session-start's update. Every test process carries it, so a suite leaves+ * no qmd work behind (#337); wiki-mind's vendored copy uses the same name+ * (wiki-mind #93).+ */+export const REFRESH_SWITCH = "VAULT_QMD_REFRESH";++/**+ * Whether the detached qmd refresh is switched off for this process: exactly+ * "off". wiki-mind's copy reads the same variable the same way, and one+ * variable must mean the same to every vault's hooks.+ */+export function refreshDisabled(): boolean {+ return process.env[REFRESH_SWITCH] === "off";+}+/*** Spawn the detached worker. `stdio: 'ignore'` + `.unref()` + `detached`* survive parent exit without leaving file descriptors open, and@@ -348,9 +365,14 @@ export function triggerDebouncedRefresh(opts: {debug(`${opts.logPrefix}: qmd not resolvable; skipping`);return;}+ // VAULT_QMD_REFRESH=off (set by the test runner) stops the detached worker+ // and nothing else: the decision and its sentinel and pending stamps run+ // as usual, so the trigger's observable behaviour is unchanged (#337).const spawnWorker =opts.spawnWorker ??- ((path: string, args: readonly string[]) => spawnDetachedWorker(path, opts.logPrefix, args));+ (refreshDisabled()+ ? () => debug(`${opts.logPrefix}: refresh off (${REFRESH_SWITCH}=off); no worker spawned`)+ : (path: string, args: readonly string[]) => spawnDetachedWorker(path, opts.logPrefix, args));if (plan === "now") {touchSentinel(opts.sentinelPath);diff --git a/.claude/scripts/session-start.ts b/.claude/scripts/session-start.tsindex 8347a18..e52d4d0 100644--- a/.claude/scripts/session-start.ts+++ b/.claude/scripts/session-start.ts@@ -83,7 +83,8 @@ import {scanActiveHygiene,} from "./lib/active-hygiene.ts";-import { fitWithMeter, HOOK_OUTPUT_LIMIT, type OutputLimit, readStdinJson } from "./lib/hook-io.ts";+import { debug, fitWithMeter, HOOK_OUTPUT_LIMIT, type OutputLimit, readStdinJson } from "./lib/hook-io.ts";+import { REFRESH_SWITCH, refreshDisabled } from "./lib/qmd-refresh.ts";import { readOmMod } from "./lib/om-mod.ts";import { resolveProjectDir } from "./lib/project-dir.ts";@@ -272,17 +273,25 @@ const qmdUpdate = bootstrapNeeded// of the vault (or a test cleanup) never races a stale qmd handle on// Windows.const qmdCwd = bootstrapNeeded ? cwd : tmpdir();-const qmdChild = spawn(qmdUpdate.cmd, qmdUpdate.args as string[], {- stdio: "ignore",- shell: qmdUpdate.shell,- detached: true,- windowsHide: true,- cwd: qmdCwd,-});-// Silence the spawn-error event so a missing qmd doesn't crash the hook;-// qmd is optional and the hook already degrades when it's not installed.-qmdChild.on("error", () => undefined);-qmdChild.unref();+// VAULT_QMD_REFRESH=off (every test process carries it) stops this detached+// update too, the same as the write-time refresh worker (#337): a test's+// session-start would otherwise leave a qmd update or bootstrap running+// against its temp vault after the run.+if (refreshDisabled()) {+ debug(`session-start: qmd refresh off (${REFRESH_SWITCH}=off); nothing spawned`);+} else {+ const qmdChild = spawn(qmdUpdate.cmd, qmdUpdate.args as string[], {+ stdio: "ignore",+ shell: qmdUpdate.shell,+ detached: true,+ windowsHide: true,+ cwd: qmdCwd,+ });+ // Silence the spawn-error event so a missing qmd doesn't crash the hook;+ // qmd is optional and the hook already degrades when it's not installed.+ qmdChild.on("error", () => undefined);+ qmdChild.unref();+}type CmdResult =| { readonly kind: "ok"; readonly stdout: string }diff --git a/.claude/scripts/tests/_helpers.ts b/.claude/scripts/tests/_helpers.tsindex a2aa096..3381145 100644--- a/.claude/scripts/tests/_helpers.ts+++ b/.claude/scripts/tests/_helpers.ts@@ -21,15 +21,19 @@** Every hook that writes or stops refreshes QMD through a debounce sentinel* beside the scripts. A test that names no sentinel of its own gets- * TEST_SENTINEL instead, touched before each spawn: the real one is never- * written, and a sentinel that fresh keeps the refresh debounced, so no test- * starts a real index update of the checkout it runs in.+ * TEST_SENTINEL instead, touched before each spawn, so the real one is never+ * written. A fresh sentinel does NOT stop the refresh: it sends the trigger+ * down its trailing path, which schedules a detached worker. What stops it+ * is VAULT_QMD_REFRESH=off, which every test process carries (set by+ * `_run-tests.ts` and `_qmd-cache-guard.ts`), so no test starts a real+ * index update or leaves a worker behind (#337).*/import { spawnSync } from "node:child_process";import { mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";+import { REFRESH_SWITCH } from "../lib/qmd-refresh.ts";const SENTINEL_DIR = mkdtempSync(join(tmpdir(), "om-test-sentinel-"));export const TEST_SENTINEL = join(SENTINEL_DIR, ".qmd-refresh-sentinel");@@ -57,7 +61,9 @@ export function runScript(: typeof stdin === "string"? stdin: JSON.stringify(stdin);- const env = { ...process.env, QMD_REFRESH_SENTINEL: TEST_SENTINEL, ...envOverrides };+ // The switch before the caller's overrides: every hook a test runs gets it,+ // whatever this process carries, and a test can still opt back in (#337).+ const env = { ...process.env, [REFRESH_SWITCH]: "off", QMD_REFRESH_SENTINEL: TEST_SENTINEL, ...envOverrides };if (env.QMD_REFRESH_SENTINEL === TEST_SENTINEL) writeFileSync(TEST_SENTINEL, "");const proc = spawnSync(process.execPath,diff --git a/.claude/scripts/tests/_proc.ts b/.claude/scripts/tests/_proc.tsnew file mode 100644index 0000000..5c14440--- /dev/null+++ b/.claude/scripts/tests/_proc.ts@@ -0,0 +1,99 @@+/**+ * Process helpers for the test runner (#337): finding the qmd-refresh-run+ * workers a run may leave behind, and stopping each one's whole tree.+ *+ * A worker can be blocked in `qmd embed` for up to five minutes, so killing+ * only its own pid would leave that qmd running. A detached worker leads its+ * own process group on POSIX, so the group is killed; Windows has no groups,+ * and `taskkill /T` walks the tree instead.+ */++import { spawnSync, type SpawnSyncReturns } from "node:child_process";++export type Proc = { readonly pid: number; readonly cmd: string };++type Run = (cmd: string, args: readonly string[]) => SpawnSyncReturns<string>;+type Kill = (pid: number, signal: NodeJS.Signals) => boolean;++const run: Run = (cmd, args) =>+ spawnSync(cmd, args as string[], { encoding: "utf8", timeout: 60_000, windowsHide: true });++/**+ * The listing command for `platform`. Windows filters server-side on the+ * command line, never on the image name, which a Node version manager can+ * rename. POSIX lists everything with `-ww`, so a long command line is never+ * truncated before the match, and with the pid the kill needs.+ */+export function listingCommand(platform: NodeJS.Platform = process.platform): { cmd: string; args: string[] } {+ if (platform === "win32") {+ return {+ cmd: "powershell",+ args: [+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ // UTF-8 out, so a non-ASCII path survives the pipe; not this+ // PowerShell itself, whose own command line holds the filter text;+ // and each command line on one line, so a continuation line can+ // never read as a pid of its own.+ "[Console]::OutputEncoding = [Text.Encoding]::UTF8; Get-CimInstance Win32_Process -Filter \"CommandLine LIKE '%qmd-refresh-run%'\" | Where-Object { $_.ProcessId -ne $PID } | ForEach-Object { \"$($_.ProcessId)`t$($_.CommandLine -replace '[\\r\\n]+', ' ')\" }",+ ],+ };+ }+ return { cmd: "ps", args: ["-ax", "-ww", "-o", "pid=,args="] };+}++/** `{ pid, cmd }` for each `<pid><whitespace><command line>` line. */+export function parseProcessList(stdout: string): Proc[] {+ return stdout+ .split(/\r?\n/)+ .map((line) => /^\s*(\d+)\s+(.*\S)\s*$/.exec(line))+ .filter((m): m is RegExpExecArray => m !== null)+ .map((m) => ({ pid: Number(m[1]), cmd: m[2]! }));+}++/**+ * The running qmd-refresh-run workers, or why the listing failed (an error+ * such as a missing `ps` or PowerShell, a killing signal, a non-zero exit),+ * so the caller can say the check did not run rather than report none.+ */+export function listRefreshWorkers(+ runner: Run = run,+ platform: NodeJS.Platform = process.platform,+): { workers: Proc[] } | { failed: string } {+ const { cmd, args } = listingCommand(platform);+ const r = runner(cmd, args);+ if (r.error !== undefined) return { failed: `${cmd}: ${r.error.message}` };+ if (r.signal) return { failed: `${cmd} killed by ${r.signal}` };+ if (r.status !== 0 || typeof r.stdout !== "string") return { failed: `${cmd} exit ${r.status}` };+ return { workers: parseProcessList(r.stdout).filter((p) => p.pid !== process.pid && /qmd-refresh-run/.test(p.cmd)) };+}++const isEsrch = (err: unknown) => (err as NodeJS.ErrnoException)?.code === "ESRCH";++/**+ * Stop `pid` and every process it started. "gone" when it had already exited+ * (taskkill's exit 128; ESRCH on POSIX), "failed" when the kill itself did.+ * On POSIX the process group comes first; a worker that leads no group falls+ * back to its own pid.+ */+export function killTree(+ pid: number,+ platform: NodeJS.Platform = process.platform,+ runner: Run = run,+ kill: Kill = process.kill,+): "stopped" | "gone" | "failed" {+ if (platform === "win32") {+ const r = runner("taskkill", ["/T", "/F", "/PID", String(pid)]);+ return r.status === 0 ? "stopped" : r.status === 128 ? "gone" : "failed";+ }+ for (const target of [-pid, pid]) {+ try {+ kill(target, "SIGKILL");+ return "stopped";+ } catch (err) {+ if (!isEsrch(err)) return "failed";+ }+ }+ return "gone";+}diff --git a/.claude/scripts/tests/_qmd-cache-guard.ts b/.claude/scripts/tests/_qmd-cache-guard.tsindex 93a17fe..a68aa91 100644--- a/.claude/scripts/tests/_qmd-cache-guard.ts+++ b/.claude/scripts/tests/_qmd-cache-guard.ts@@ -1,5 +1,6 @@/**- * Per-process redirect of QMD's cache and config, for a direct+ * Per-process redirect of QMD's cache and config, and the switch that stops+ * the detached qmd refresh (#337), for a direct* `node --import ./tests/_qmd-cache-guard.ts --test` run.** `npm test` goes through `_run-tests.ts`, which sets the redirect once for@@ -14,6 +15,12 @@import { mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";+import { REFRESH_SWITCH } from "../lib/qmd-refresh.ts";++// Every test process, direct run or not: no hook a test runs spawns the+// detached qmd refresh (#337). Forced, not defaulted, so an exported "on" or+// "" cannot leak through. `_run-tests.ts` also sets it for the run.+process.env[REFRESH_SWITCH] = "off";if (process.env["OM_QMD_ISOLATED"] === undefined) {const isolated = mkdtempSync(join(tmpdir(), "om-test-qmd-"));diff --git a/.claude/scripts/tests/_run-tests.ts b/.claude/scripts/tests/_run-tests.tsindex 08f69c4..39133b7 100644--- a/.claude/scripts/tests/_run-tests.ts+++ b/.claude/scripts/tests/_run-tests.ts@@ -18,19 +18,28 @@* `~/.config/qmd`), and so do OM's own path helpers. `XDG_CONFIG_HOME`* itself is left alone: it also moves git's global config, which the* tests' git calls must keep seeing;- * 3. after the run, fails if a new store or config appeared in the user's- * folders, naming each, then removes the temp folder.+ * 3. sets `VAULT_QMD_REFRESH=off`, so no hook a test runs spawns the+ * detached qmd-refresh-run worker, each of which outlived the run by+ * ~30 s and made a qmd call (#337), and points `TMP`, `TEMP` and+ * `TMPDIR` into that same temp folder, so a process a test leaves+ * behind names it;+ * 4. after the run, stops and names any qmd-refresh-run worker still+ * running from this run, and fails;+ * 5. fails if a new store or config appeared in the user's folders, naming+ * each, then removes the temp folder.** A test that builds a subprocess env from scratch, without `process.env`,- * escapes the redirect; step 3 is what catches it. The wrapper exists+ * escapes the redirects; steps 4 and 5 are what catch it. The wrapper exists* because Node's runner applies `--import` to each test file's process and* never to itself, so a preload cannot see the run as a whole.*/import { spawnSync } from "node:child_process";-import { mkdtempSync, readdirSync, rmSync } from "node:fs";+import { mkdirSync, mkdtempSync, readdirSync, rmSync } from "node:fs";import { homedir, tmpdir } from "node:os";import { join } from "node:path";+import { REFRESH_SWITCH } from "../lib/qmd-refresh.ts";+import { killTree, listRefreshWorkers } from "./_proc.ts";const env = process.env;const watched: readonly { readonly dir: string; readonly ext: string }[] = [@@ -49,8 +58,13 @@ function listing(dir: string, ext: string): Set<string> {}}+/** Comparable form of a path inside a command line: forward slashes, lower case. */+const norm = (s: string) => s.replace(/\\/g, "/").toLowerCase();+const before = watched.map(({ dir, ext }) => listing(dir, ext));const isolated = mkdtempSync(join(tmpdir(), "om-test-qmd-"));+const isolatedTmp = join(isolated, "tmp");+mkdirSync(isolatedTmp, { recursive: true });const run = spawnSync(process.execPath,@@ -62,10 +76,29 @@ const run = spawnSync(XDG_CACHE_HOME: join(isolated, "cache"),QMD_CONFIG_DIR: join(isolated, "config", "qmd"),OM_QMD_ISOLATED: isolated,+ // No detached qmd-refresh-run worker from any hook a test runs+ // (#337): each one outlived the run by ~30 s and made a qmd call.+ [REFRESH_SWITCH]: "off",+ // Temp folders inside the isolated one, so any process a test leaves+ // behind names it, and the guard below can attribute it to this run.+ TMP: isolatedTmp,+ TEMP: isolatedTmp,+ TMPDIR: isolatedTmp,},},);+// A refresh worker still alive from this run means some hook ran without the+// switch (a test that built its env from scratch, or the switch no longer+// honoured). Every one is stopped before reporting, so a red run leaves+// nothing behind either: each one's whole tree, since a worker blocked in+// `qmd embed` has a live qmd child.+const listed = listRefreshWorkers();+const isolatedKey = norm(isolated);+const survivors = ("workers" in listed ? listed.workers : [])+ .filter(({ cmd }) => norm(cmd).includes(isolatedKey))+ .map((w) => ({ ...w, outcome: killTree(w.pid) }));+const added = watched.flatMap(({ dir, ext }, i) =>[...listing(dir, ext)].filter((f) => !before[i]!.has(f)).sort().map((f) => join(dir, f)),);@@ -75,12 +108,25 @@ try {/* a detached qmd may still hold a file; the OS cleans temp */}+if ("failed" in listed) {+ process.stderr.write(+ `\nrefresh-worker guard: couldn't list processes (${listed.failed}); surviving qmd-refresh-run workers were not checked.\n`,+ );+}+if (survivors.length > 0) {+ process.stderr.write(+ `\nrefresh-worker guard: the test run left ${survivors.length} qmd-refresh-run worker(s) alive:\n` ++ survivors.map(({ pid, cmd, outcome }) => ` ${pid} (${outcome}) ${cmd}`).join("\n") ++ "\nA hook ran without VAULT_QMD_REFRESH=off. Route its subprocess env through process.env (#337).\n",+ );+}if (added.length > 0) {process.stderr.write(`\nqmd cache guard: the test run created ${added.length} file(s) in the user's qmd folders:\n` +added.map((f) => ` ${f}`).join("\n") +"\nA test reached qmd with the user's environment. Route its subprocess env through process.env.\n",);- process.exit(1);}-process.exit(run.status ?? 1);+// Both guards report before either fails the run, so one leak cannot hide+// the other until the next run.+process.exit(survivors.length > 0 || added.length > 0 ? 1 : (run.status ?? 1));diff --git a/.claude/scripts/tests/proc.test.ts b/.claude/scripts/tests/proc.test.tsnew file mode 100644index 0000000..1328dab--- /dev/null+++ b/.claude/scripts/tests/proc.test.ts@@ -0,0 +1,145 @@+/**+ * The test runner's process helpers (tests/_proc.ts, #337): listing the+ * qmd-refresh-run workers a run may leave behind, and killing each one's+ * whole tree, since a worker blocked in `qmd embed` has a live qmd child.+ */++import { test, describe } from "node:test";+import assert from "node:assert/strict";+import { spawn, type SpawnSyncReturns } from "node:child_process";+import { existsSync, mkdtempSync, readFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { killTree, listingCommand, listRefreshWorkers, parseProcessList } from "./_proc.ts";+import { rmTemp, waitFor } from "./_helpers.ts";++const fake = (r: Partial<SpawnSyncReturns<string>>) => () => r as SpawnSyncReturns<string>;++describe("listingCommand", () => {+ test("POSIX lists every process with its pid and untruncated arguments", () => {+ const { cmd, args } = listingCommand("linux");+ assert.equal(cmd, "ps");+ assert.deepEqual(args, ["-ax", "-ww", "-o", "pid=,args="]);+ });++ test("Windows filters on the command line, never on the node image name a version manager can rename", () => {+ const { cmd, args } = listingCommand("win32");+ assert.equal(cmd, "powershell");+ const script = args.join(" ");+ assert.match(script, /CommandLine LIKE '%qmd-refresh-run%'/);+ assert.doesNotMatch(script, /Name\s*=/);+ });++ test("Windows leaves out the listing's own PowerShell, whose command line holds the filter text", () => {+ assert.match(listingCommand("win32").args.join(" "), /ProcessId -ne \$PID/);+ });++ test("Windows flattens a multi-line command line, so no continuation line reads as a pid of its own", () => {+ assert.match(listingCommand("win32").args.join(" "), /\$_\.CommandLine -replace '\[\\r\\n\]\+', ' '/);+ });++ test("Windows writes UTF-8, so a non-ASCII path in a command line still matches", () => {+ assert.match(listingCommand("win32").args.join(" "), /\[Console\]::OutputEncoding = \[Text\.Encoding\]::UTF8/);+ });+});++describe("parseProcessList", () => {+ test("reads pid and command line from tab- or space-separated lines, skipping blanks", () => {+ const out = " 123 node a.ts --x\r\n\n456\tC:\\node.exe b.ts\n";+ assert.deepEqual(parseProcessList(out), [+ { pid: 123, cmd: "node a.ts --x" },+ { pid: 456, cmd: "C:\\node.exe b.ts" },+ ]);+ });+});++describe("listRefreshWorkers", () => {+ test("a failed listing says why, so the caller reports 'not checked', never an empty 'none'", () => {+ const reason = (r: Partial<SpawnSyncReturns<string>>) => {+ const out = listRefreshWorkers(fake(r));+ assert.ok("failed" in out, "a failed listing must not read as a list");+ return out.failed;+ };+ assert.match(reason({ status: 1, stdout: "" }), /exit 1/);+ assert.match(reason({ status: null, error: new Error("spawn ps ENOENT"), stdout: "" }), /ENOENT/);+ assert.match(reason({ status: null, signal: "SIGTERM", stdout: "" }), /killed by SIGTERM/);+ });++ test("keeps only qmd-refresh-run workers", () => {+ const stdout = "1 node qmd-refresh-run.ts --trailing=x\n2 node other.ts\n";+ assert.deepEqual(listRefreshWorkers(fake({ status: 0, stdout })), {+ workers: [{ pid: 1, cmd: "node qmd-refresh-run.ts --trailing=x" }],+ });+ });+});++describe("killTree — outcomes", () => {+ test("Windows: taskkill's exit 128 (no such process) reads as already gone", () => {+ assert.equal(killTree(42, "win32", fake({ status: 0 })), "stopped");+ assert.equal(killTree(42, "win32", fake({ status: 128 })), "gone");+ assert.equal(killTree(42, "win32", fake({ status: 1 })), "failed");+ });++ test("POSIX: the process group first, then the bare pid when the worker leads no group", () => {+ const esrch = Object.assign(new Error("ESRCH"), { code: "ESRCH" });+ const calls: number[] = [];+ const groupless = (pid: number) => {+ calls.push(pid);+ if (pid < 0) throw esrch;+ return true;+ };+ assert.equal(killTree(42, "linux", undefined, groupless), "stopped");+ assert.deepEqual(calls, [-42, 42]);+ const gone = () => {+ throw esrch;+ };+ assert.equal(killTree(42, "linux", undefined, gone), "gone");+ });+});++describe("killTree — a real tree", () => {+ // A detached parent that starts a long-lived child and records its pid,+ // the shape of a refresh worker blocked in `qmd embed`. On Windows the+ // child is itself detached: otherwise libuv's job object would end it+ // with the parent and hide whether the kill reached it.+ test("stops the worker and the child it started", async () => {+ const dir = mkdtempSync(join(tmpdir(), "proc-tree-"));+ const childPidFile = join(dir, "child.pid");+ const detachChild = process.platform === "win32";+ const parentScript =+ "const { spawn } = require('node:child_process'); const fs = require('node:fs');" ++ `const c = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore', detached: ${detachChild}, windowsHide: true });` ++ `fs.writeFileSync(${JSON.stringify(childPidFile)}, String(c.pid)); setInterval(() => {}, 1000);`;+ const parent = spawn(process.execPath, ["-e", parentScript], { detached: true, stdio: "ignore", windowsHide: true });+ const alive = (pid: number) => {+ try {+ process.kill(pid, 0);+ return true;+ } catch {+ return false;+ }+ };+ let childPid = 0;+ try {+ await waitFor(() => existsSync(childPidFile), 10_000);+ childPid = Number(readFileSync(childPidFile, "utf8"));+ assert.ok(childPid > 0 && alive(childPid), "the child never started");+ killTree(parent.pid!);+ await waitFor(() => !alive(childPid) && !alive(parent.pid!), 10_000);+ assert.equal(alive(parent.pid!), false, "the worker survived");+ assert.equal(alive(childPid), false, "the worker's child survived: only the worker's pid was killed");+ } finally {+ // Whatever the outcome, this test leaves nothing running.+ for (const pid of [childPid, parent.pid!]) {+ if (pid > 0 && alive(pid)) {+ try {+ process.kill(pid, "SIGKILL");+ } catch {+ /* gone */+ }+ }+ }+ rmTemp(dir);+ }+ });+});diff --git a/.claude/scripts/tests/qmd-refresh.test.ts b/.claude/scripts/tests/qmd-refresh.test.tsindex 72883bf..2458dc4 100644--- a/.claude/scripts/tests/qmd-refresh.test.ts+++ b/.claude/scripts/tests/qmd-refresh.test.ts@@ -29,8 +29,10 @@ import {resolveVaultRoot,shouldRefreshForPath,triggerDebouncedRefresh,+ REFRESH_SWITCH,+ refreshDisabled,} from "../lib/qmd-refresh.ts";-import { rmTemp } from "./_helpers.ts";+import { rmTemp, waitFor } from "./_helpers.ts";/*** The debounce used to fire on the leading edge only: a note written inside@@ -121,6 +123,118 @@ describe("triggerDebouncedRefresh — schedules one trailing flush per window",});});+describe("VAULT_QMD_REFRESH=off — no detached worker (#337)", () => {+ // The test runner sets this so a suite leaves no qmd-refresh-run worker+ // behind. The real spawner is observed through a fake worker that writes+ // a marker when it runs: no seam, so the switch is what decides.+ function fixture() {+ const dir = mkdtempSync(join(tmpdir(), "qmd-refresh-off-"));+ const sentinel = join(dir, ".qmd-refresh-sentinel");+ const marker = join(dir, "worker-ran");+ const workerPath = join(dir, "fake-worker.mjs");+ writeFileSync(workerPath, `import { writeFileSync } from "node:fs";\nwriteFileSync(${JSON.stringify(marker)}, "");\n`);+ const fire = () =>+ triggerDebouncedRefresh({ sentinelPath: sentinel, workerPath, debounceMs: 30_000, logPrefix: "test", qmdAvailable: () => true });+ return { dir, sentinel, marker, fire };+ }+ /** Run `body` with VAULT_QMD_REFRESH set to `value` (or removed), restoring it after. */+ function withSwitch(value: string | undefined, body: () => Promise<void>): Promise<void> {+ const before = process.env[REFRESH_SWITCH];+ if (value === undefined) delete process.env[REFRESH_SWITCH];+ else process.env[REFRESH_SWITCH] = value;+ return body().finally(() => {+ if (before === undefined) delete process.env[REFRESH_SWITCH];+ else process.env[REFRESH_SWITCH] = before;+ });+ }+ const appears = async (path: string, ms: number) => {+ await waitFor(() => existsSync(path), ms);+ return existsSync(path);+ };++ // How long a real spawn took to show its marker, measured by the control.+ // The negative tests wait well past it, so a slow cold start cannot pass+ // for "nothing spawned".+ let spawnMs = 0;+ // Unmeasured (the control was filtered out or failed): the control's own+ // 10 s ceiling, never a guess that a slow spawn could outlast.+ const negativeWaitMs = () => (spawnMs === 0 ? 10_000 : Math.max(2_000, 3 * spawnMs));++ test("control: with the switch unset the real worker runs, so the observation works", async () => {+ await withSwitch(undefined, async () => {+ const f = fixture();+ try {+ const start = Date.now();+ f.fire();+ assert.ok(await appears(f.marker, 10_000), "the fake worker never ran: the test cannot see a spawn");+ spawnMs = Date.now() - start;+ } finally {+ rmTemp(f.dir);+ }+ });+ });++ test("the immediate path spawns nothing, and still stamps the sentinel", async () => {+ await withSwitch("off", async () => {+ const f = fixture();+ try {+ f.fire();+ assert.ok(existsSync(f.sentinel), "the sentinel is still stamped");+ assert.equal(await appears(f.marker, negativeWaitMs()), false, "a worker ran with VAULT_QMD_REFRESH=off");+ } finally {+ rmTemp(f.dir);+ }+ });+ });++ test("the trailing path spawns nothing, and still claims the pending marker", async () => {+ await withSwitch("off", async () => {+ const f = fixture();+ try {+ // Fresh, as runHook leaves it: the trailing path. Aged 10 s, because a+ // sentinel stamped in the same millisecond reads as clock skew.+ writeFileSync(f.sentinel, "");+ const t = (Date.now() - 10_000) / 1000;+ utimesSync(f.sentinel, t, t);+ f.fire();+ assert.ok(existsSync(pendingPathFor(f.sentinel)), "the pending marker is still claimed");+ assert.equal(await appears(f.marker, negativeWaitMs()), false, "a worker ran with VAULT_QMD_REFRESH=off");+ } finally {+ rmTemp(f.dir);+ }+ });+ });++ test("the switch is exactly 'off', as wiki-mind's copy reads it; anything else leaves the refresh on", async () => {+ // One variable read by two vaults' hooks must mean the same to both.+ for (const [value, off] of [["off", true], ["OFF", false], [" off ", false], ["on", false], ["", false], ["0", false]] as const) {+ await withSwitch(value, async () => {+ assert.equal(refreshDisabled(), off, JSON.stringify(value));+ });+ }+ });++ test("an explicit spawnWorker seam still runs when the switch is off", async () => {+ await withSwitch("off", async () => {+ const dir = mkdtempSync(join(tmpdir(), "qmd-refresh-off-seam-"));+ try {+ const spawned: (readonly string[])[] = [];+ triggerDebouncedRefresh({+ sentinelPath: join(dir, ".qmd-refresh-sentinel"),+ workerPath: "worker.ts",+ debounceMs: 30_000,+ logPrefix: "test",+ qmdAvailable: () => true,+ spawnWorker: (_p, args) => spawned.push(args),+ });+ assert.deepEqual(spawned, [[]]);+ } finally {+ rmTemp(dir);+ }+ });+ });+});+describe("claimTrailingFlush — the worker's gate after sleeping", () => {test("runs when no newer refresh started, clears the marker, stamps the sentinel", () => {const dir = mkdtempSync(join(tmpdir(), "qmd-claim-"));diff --git a/.claude/scripts/tests/refresh-switch.test.ts b/.claude/scripts/tests/refresh-switch.test.tsnew file mode 100644index 0000000..73a37e3--- /dev/null+++ b/.claude/scripts/tests/refresh-switch.test.ts@@ -0,0 +1,67 @@+/**+ * Every test process, and every hook a test runs, sees the detached qmd+ * refresh switched off (#337). Three places hold it, so no route around one+ * of them leaks a qmd-refresh-run worker:+ * - `npm test` (tests/_run-tests.ts) sets it for the whole run;+ * - the preload (tests/_qmd-cache-guard.ts) forces it in every test process,+ * so a direct `node --import ./tests/_qmd-cache-guard.ts --test <file>`+ * run is covered and an exported "on" cannot leak through;+ * - `runScript` (tests/_helpers.ts) sets it in every hook's env, the one+ * choke point every launcher goes through.+ */++import { test } from "node:test";+import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";+import { mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";+import { REFRESH_SWITCH } from "../lib/qmd-refresh.ts";+import { rmTemp, runScript } from "./_helpers.ts";++const testsDir = dirname(fileURLToPath(import.meta.url));++test("this test process sees the refresh switch off, wherever the preload or runner ran", (t) => {+ // A bare `node --test` (CI's test-without-qmd leg, the release job) loads+ // neither, so this process has no switch; every hook it runs still gets it+ // from runScript, which the last test below pins. OM_QMD_ISOLATED is set by+ // both the preload and the runner, so it says whether either ran.+ if (process.env["OM_QMD_ISOLATED"] === undefined) {+ t.skip("bare node --test: no preload or runner, so the switch reaches hooks through runScript only");+ return;+ }+ assert.equal(process.env[REFRESH_SWITCH], "off");+});++test("the preload forces the switch off, even over an exported 'on' or ''", () => {+ for (const exported of ["on", ""]) {+ const r = spawnSync(+ process.execPath,+ [+ "--experimental-strip-types",+ "--import",+ // A file URL: a bare Windows path's drive letter reads as a URL scheme.+ pathToFileURL(join(testsDir, "_qmd-cache-guard.ts")).href,+ "-e",+ `process.stdout.write(String(process.env.${REFRESH_SWITCH}))`,+ ],+ { encoding: "utf8", timeout: 30_000, env: { ...process.env, [REFRESH_SWITCH]: exported } },+ );+ assert.equal(r.stdout, "off", `with ${REFRESH_SWITCH}=${JSON.stringify(exported)} exported`);+ }+});++test("runScript gives every hook it runs the switch, even when this process lacks it", () => {+ const dir = mkdtempSync(join(tmpdir(), "refresh-switch-probe-"));+ const probe = join(dir, "probe.mjs");+ writeFileSync(probe, `process.stdout.write(String(process.env.${REFRESH_SWITCH}));\n`);+ const before = process.env[REFRESH_SWITCH];+ delete process.env[REFRESH_SWITCH];+ try {+ assert.equal(runScript(probe, null).stdout, "off");+ } finally {+ if (before !== undefined) process.env[REFRESH_SWITCH] = before;+ rmTemp(dir);+ }+});diff --git a/.claude/scripts/tests/session-start.integration.test.ts b/.claude/scripts/tests/session-start.integration.test.tsindex 4fdc76c..7517dfe 100644--- a/.claude/scripts/tests/session-start.integration.test.ts+++ b/.claude/scripts/tests/session-start.integration.test.ts@@ -82,6 +82,19 @@ const REQUIRED_SECTIONS = ["### Vault File Listing",];+describe("session-start — no detached qmd refresh under the switch (#337)", () => {+ // SessionStart always reaches its detached spawn: a resolvable qmd runs+ // `qmd update` (or the bootstrap, against a test's empty index), and+ // without one it falls back to a shell `qmd update`. Under+ // VAULT_QMD_REFRESH=off it must spawn nothing. The switch comes from+ // runScript's default, the choke point every hook a test runs goes through.+ test("under the switch, no detached qmd is spawned", () => {+ const { code, stderr } = spawnHook(SCRIPT, "", { CLAUDE_PROJECT_DIR: TMP_DIR, HOOK_DEBUG: "1" });+ assert.equal(code, 0);+ assert.match(stderr, /session-start: qmd refresh off \(VAULT_QMD_REFRESH=off\); nothing spawned/);+ });+});+describe("session-start — silence contract and structure", () => {test("exits 0 with empty stderr on a minimal vault", () => {const { code, stderr } = runHook();diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 100730d..a3c8770 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -206,6 +206,7 @@ A few specific design choices are worth calling out:- **`SessionStart` injects, it does not load.** It builds a briefing (filename listing, North Star excerpt, git summary, open tasks aggregated from `work/active/` and the vault root) and hands it to the agent. Full note contents never flow through this hook. Its size is bounded by `eager_layer_budget_bytes`, held under Claude Code's 10,000-character hook output cap, and reported by the meter on the last line of every injection, so the cost is visible rather than assumed. When the template's Claude Code mod delivers the same briefing as an instruction file instead, the hook stands down and the briefing is bounded by `eager_layer_instruction_budget_bytes`, since instruction files are not under the hook cap (#264). The same backstop holds there, in bytes: sections that never degrade are cut at the budget plus the meter's room, and the meter says "truncated to fit the instruction budget". The open-tasks scan is filesystem-only so the hook never spawns the Obsidian CLI — that subprocess flashes the Electron app on macOS when no instance is running (#83).- **`UserPromptSubmit` classifies, it does not route.** It tags the prompt with hints like `ARCHITECTURE discussion` or `DECISION`; the agent decides where to file. Keeping the hook opinion-free means the routing logic lives in `AGENTS.md`, which is editable per-user without touching scripts.- **QMD refresh is shared, debounced, and detached.** Three hook entries fire the same refresh helper — `PostToolUse` (after `.md` writes), `PreCompact` (before transcript backup; writes tend to cluster before compaction), and `Stop` (after a response) — sharing one sentinel file so a burst of events produces at most one worker per debounce window. The actual indexing runs in `.claude/scripts/qmd-refresh-run.ts` as a detached, stdio-silent worker (`qmd update` → `qmd embed` → tail-chase `qmd update`), so the parent hook returns in milliseconds and nothing flows to the agent's context.+- **`VAULT_QMD_REFRESH=off` switches the detached refresh off** (exactly `off`, as wiki-mind's copy reads it): no `qmd-refresh-run.ts` worker, and no detached `qmd update` or bootstrap from `SessionStart`. The debounce decision and its sentinel stamps still run. The test suite sets it in every test process and every hook a test runs. The test runner also stops and fails on any surviving worker whose command line names the run's temp folder, which every trailing worker's does; an immediate-path worker carries no path, so for those the switch is the guard (#337).- **`PreCompact` also backs up the transcript.** In addition to kicking the QMD refresh, it copies the current session transcript out to `thinking/session-logs/` so long conversations remain recoverable after compaction.- **`Stop` reports once, not every turn.** Claude and Codex fire it whenever the agent finishes a response, not when the session ends (#252). It triggers the shared refresh every time, but shows the checklist and hygiene findings only the first time a session sees that exact report, and again when the findings change; otherwise it returns the empty JSON envelope. A warning that repeats unchanged is one users learn to ignore (#155). The dedupe reuses the classifier's per-session state shape (#107): one self-pruning file, failing open to "show" on a missing `session_id` or unreadable state.- **A changed `Stop` report reaches the agent too (#256).** A `systemMessage` is shown to the user and never added to the model's context, so the drift the agent is best placed to fix never reached it. And every `Stop` output that does reach the model is printed in full for the user: a `decision: "block"` reason under a "Stop hook error" label (v8.5.0 shipped that), `Stop` `additionalContext` under "Stop hook feedback". `UserPromptSubmit` `additionalContext` is the one channel that reaches the model and is never shown. So when the findings change, `Stop` shows the user a one-line-per-section summary and saves the full report for the session (`lib/stop-handoff.ts`: written atomically, claimed by rename so it is delivered once, the newest report wins, a week-old one is pruned). The next prompt's `classify-message` takes it and hands it to the agent beside any routing hints, with a preface telling it to deal with the user's message first. If the report cannot be saved, `Stop` sends it as feedback instead (Claude Code; Codex's handling of Stop feedback is unverified): visible, but never lost. `SessionEnd` and a `Stop` without a `session_id` have no next prompt to ride, so the user gets the full report.