A self-organizing Obsidian vault that gives AI coding agents persistent memory.
TypeScript ai-agentsclaude-codecodex-cligemini-cliknowledge-managementobsidianobsidian-vaultpersistent-memorysecond-braintemplate
test: wait for the signal, and never fail a passing test on cleanup (#236)
HoangThai183022877dbeb7
diff --git a/.claude/scripts/tests/_helpers.test.ts b/.claude/scripts/tests/_helpers.test.tsnew file mode 100644index 0000000..f9cdba1--- /dev/null+++ b/.claude/scripts/tests/_helpers.test.ts@@ -0,0 +1,134 @@+/**+ * The shared test helpers, which are load-bearing for CI honesty.+ *+ * Both halves of #235 were assumptions about timing rather than defects in+ * what was under test, and both fixes live here — so the properties that make+ * them correct are pinned here too. Each one is a way the fix could be wrong+ * while still looking right: a `waitFor` that hangs instead of returning at+ * the deadline would hide a dead assertion, and an `rmTemp` that throws would+ * reintroduce the exact failure it was written to remove.+ */++import { test, describe } from "node:test";+import assert from "node:assert/strict";+import { chmodSync, existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { leakedTempDirs, rmTemp, waitFor } from "./_helpers.ts";++describe("waitFor", () => {+ test("returns as soon as the condition holds", async () => {+ let ready = false;+ const t = setTimeout(() => (ready = true), 40);+ const started = Date.now();+ await waitFor(() => ready);+ clearTimeout(t);+ assert.equal(ready, true);+ // The point of polling: it does not pay the full timeout when the signal+ // arrives early, which is what a fixed sleep does by construction.+ assert.ok(Date.now() - started < 2_000, "must not sit out the 5s default");+ });++ test("returns at the deadline instead of hanging, so the caller's assertion is the one that fails", async () => {+ const started = Date.now();+ await waitFor(() => false, 100, 10);+ const elapsed = Date.now() - started;+ // Returning is the whole contract. A helper that threw would replace the+ // test's own message; one that hung would turn a failure into a timeout.+ assert.ok(elapsed >= 80, `waited ${elapsed}ms — must not return before the deadline`);+ assert.ok(elapsed < 5_000, `waited ${elapsed}ms — must not outlive its deadline`);+ });++ test("accepts an async condition", async () => {+ let n = 0;+ await waitFor(async () => ++n >= 3, 2_000, 1);+ assert.ok(n >= 3);+ });+});++describe("rmTemp", () => {+ test("removes the tree", () => {+ const dir = mkdtempSync(join(tmpdir(), "rmtemp-"));+ mkdirSync(join(dir, "nested"), { recursive: true });+ writeFileSync(join(dir, "nested", "note.md"), "x");+ rmTemp(dir);+ assert.equal(existsSync(dir), false);+ });++ test("is a no-op for an unset path", () => {+ // `let dir = ""` before the `before` hook runs is the shape in every+ // suite, so the guard the call sites used to write inline lives here.+ rmTemp("");+ rmTemp(null);+ rmTemp(undefined);+ });++ test(+ "swallows a removal it is not permitted to make, and RECORDS it",+ { skip: process.platform === "win32" || process.getuid?.() === 0 },+ () => {+ // The red for #235: with a bare rmSync this throws EACCES out of an+ // `after` hook and fails a suite whose assertions all passed.+ const parent = mkdtempSync(join(tmpdir(), "rmtemp-locked-"));+ const child = join(parent, "child");+ mkdirSync(child);+ chmodSync(parent, 0o500);+ try {+ const before = leakedTempDirs().length;+ rmTemp(child);+ assert.equal(existsSync(child), true, "the removal really did fail");++ // The swallow is only acceptable because it is counted. A silent one+ // keeps the build green and takes away the signal that something+ // outlives the suite, which is the question #235 left open.+ const after = leakedTempDirs();+ assert.equal(after.length, before + 1, "a swallowed failure must be recorded");+ const entry = after.at(-1);+ assert.equal(entry?.dir, child);+ assert.ok(entry?.code, "the errno travels with the path, or the report cannot say why");+ } finally {+ chmodSync(parent, 0o700);+ rmTemp(parent);+ }+ },+ );++ test("records nothing when the removal succeeds", () => {+ // The other half, and the one that would let a false positive through:+ // a recorder that logged every call would report residue on every green+ // run and be ignored inside a week.+ const dir = mkdtempSync(join(tmpdir(), "rmtemp-ok-"));+ const before = leakedTempDirs().length;+ rmTemp(dir);+ assert.equal(existsSync(dir), false);+ assert.equal(leakedTempDirs().length, before, "a successful removal is not residue");+ });++ test(+ "records one entry per surviving tree, not one per attempt",+ { skip: process.platform === "win32" || process.getuid?.() === 0 },+ () => {+ // The count is read as "how many trees survived". Retrying the same+ // directory must not inflate it. Uses the same locked parent as the+ // test above, because it is the one shape known to fail here: a first+ // draft reached for a path under a regular file, which `force: true`+ // swallows silently, so nothing was recorded and the assertion held+ // for the wrong reason.+ const parent = mkdtempSync(join(tmpdir(), "rmtemp-dedupe-"));+ const child = join(parent, "child");+ mkdirSync(child);+ chmodSync(parent, 0o500);+ try {+ const before = leakedTempDirs().length;+ rmTemp(child);+ assert.equal(leakedTempDirs().length, before + 1, "the first attempt must record, or this proves nothing");+ rmTemp(child);+ assert.equal(leakedTempDirs().length, before + 1, "the second attempt on one path must not add a row");+ } finally {+ chmodSync(parent, 0o700);+ rmTemp(parent);+ }+ },+ );+});diff --git a/.claude/scripts/tests/_helpers.ts b/.claude/scripts/tests/_helpers.tsindex b061515..0776390 100644--- a/.claude/scripts/tests/_helpers.ts+++ b/.claude/scripts/tests/_helpers.ts@@ -13,9 +13,15 @@* to the host platform via path.resolve. Needed on Windows, where the raw* string is treated as drive-relative and pathToFileURL prepends the current* drive letter — so a round trip stops matching the literal argv[1] value.+ *+ * rmTemp and waitFor exist because both CI flakes in #235 were assumptions+ * about timing rather than defects in what was under test: a cleanup that+ * cannot delete a temp tree, and a fixed sleep standing in for a condition.+ * Both shapes recur across suites, so the reasoning lives here once.*/import { spawnSync } from "node:child_process";+import { rmSync } from "node:fs";import { resolve } from "node:path";export function hostPath(literal: string): string {@@ -61,3 +67,98 @@ export function runScript(code: proc.status ?? -1,};}++/**+ * Temp trees this could not remove, deduplicated, in the order they failed.+ *+ * Module state rather than a return value because the callers are `after` and+ * `finally` hooks: none of them is in a position to do anything with an error,+ * which is the whole reason the throw was removed.+ */+const leaked: { readonly dir: string; readonly code: string }[] = [];++/**+ * What {@link rmTemp} has failed to remove so far, as a snapshot.+ *+ * Exported so the recording is assertable. A swallow that nothing can observe+ * is the thing this file is trying not to be, and a test proving the swallow+ * happens is not the same as a test proving it was *counted*.+ */+export function leakedTempDirs(): readonly { readonly dir: string; readonly code: string }[] {+ return leaked.slice();+}++/**+ * Remove a temp tree, and never fail the run for not managing it.+ *+ * Cleanup is not the assertion. A temp directory that survives is residue in+ * the OS temp dir, which the OS reclaims; a throw here turns that cosmetic+ * problem into a red build — and does so on Windows, where a handle held open+ * a moment longer than expected is ordinary rather than exceptional. #235+ * lost a passing suite to exactly that, `EPERM` out of an `after` hook.+ *+ * Retries first, because a handle race usually clears in milliseconds, then+ * gives up **loudly**. A test that needs the removal to have SUCCEEDED must+ * assert on it, not rely on this throwing.+ *+ * **The report is the point of the swallow being acceptable at all.** Before+ * this, a held handle turned CI red: a bad test result, and also a real signal+ * that something outlives the suite. Silently swallowing it keeps the build+ * honest and takes the signal away, leaving the open question of what holds the+ * handle on Windows with nothing feeding it. So the failure is recorded and+ * announced at exit instead: green stays green, and the handle holder keeps+ * naming itself until someone fixes it properly.+ *+ * The `errno` code travels with the path because that is the question the+ * report exists to answer. `EPERM` and `EBUSY` mean a live handle; `EACCES`+ * means permissions and is a different bug with a different owner.+ */+export function rmTemp(dir: string | null | undefined): void {+ if (!dir) return;+ try {+ rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });+ } catch (e) {+ const code = (e as NodeJS.ErrnoException)?.code ?? "UNKNOWN";+ // Deduplicated so the count means "how many trees survived" rather than+ // "how many times we tried", which is what a reader will take it for.+ if (!leaked.some((l) => l.dir === dir)) leaked.push({ dir, code });+ }+}++// One handler per process, because a module is a singleton and the test runner+// gives each file its own process — so each file reports its own residue.+//+// stderr rather than stdout: this is diagnostic output about the run, not a+// result of it, and `runScript` captures the stderr of the *spawned hook*+// rather than the runner's, so nothing that asserts stderr cleanliness can see+// this line.+process.on("exit", () => {+ if (leaked.length === 0) return;+ console.error(`rmTemp: ${leaked.length} temp dir(s) survived cleanup:`);+ for (const { dir, code } of leaked) console.error(` ${code} ${dir}`);+});++/**+ * Wait until `condition` holds, or until the deadline passes.+ *+ * Returns rather than throws, so the caller's own assertion reports the+ * failure: `await waitFor(() => !c.alive)` followed by the existing+ * `assert.equal(c.alive, false, ...)` still fails when the client never dies,+ * and fails with the message the test already wrote.+ *+ * This replaces `await new Promise((r) => setTimeout(r, 400))`, which is a bet+ * on how long an async signal takes — too short and it flakes on a loaded+ * runner (#235), too long and every green run pays for it. Polling is fast+ * when the signal is fast and patient when it is not.+ */+export async function waitFor(+ condition: () => boolean | Promise<boolean>,+ timeoutMs = 5_000,+ intervalMs = 25,+): Promise<void> {+ const deadline = Date.now() + timeoutMs;+ while (!(await condition())) {+ if (Date.now() >= deadline) return;+ await new Promise((r) => setTimeout(r, intervalMs));+ }+}diff --git a/.claude/scripts/tests/active-hygiene.test.ts b/.claude/scripts/tests/active-hygiene.test.tsindex 53ceb5b..f2bfce0 100644--- a/.claude/scripts/tests/active-hygiene.test.ts+++ b/.claude/scripts/tests/active-hygiene.test.ts@@ -12,7 +12,6 @@ import {mkdirSync,writeFileSync,utimesSync,- rmSync,} from "node:fs";import { join } from "node:path";import { tmpdir } from "node:os";@@ -31,6 +30,8 @@ import {walkMarkdown,} from "../lib/active-hygiene.ts";+import { rmTemp } from "./_helpers.ts";+const DAY_MS = 24 * 60 * 60 * 1000;const NOW = Date.UTC(2026, 6, 13);const DEFAULTS = parseOpenLoopConfig(null);@@ -58,7 +59,7 @@ before(() => {});after(() => {- rmSync(ROOT, { recursive: true, force: true });+ rmTemp(ROOT);});describe("parseOpenLoopConfig", () => {@@ -244,7 +245,7 @@ describe("scanActiveHygiene — detectors", () => {assert.ok(withExport !== null);assert.equal(withExport!.count, 1);} finally {- rmSync(solo, { recursive: true, force: true });+ rmTemp(solo);}});@@ -264,7 +265,7 @@ describe("scanActiveHygiene — detectors", () => {assert.equal(found!.count, 1);assert.equal(found!.oldestDays, 3);} finally {- rmSync(solo, { recursive: true, force: true });+ rmTemp(solo);}});@@ -276,7 +277,7 @@ describe("scanActiveHygiene — detectors", () => {// Undrained because nobody has judged it, which is true immediately.assert.equal(scanActiveHygiene(solo, NOW, DEFAULTS).memoryInbox?.count, 1);} finally {- rmSync(solo, { recursive: true, force: true });+ rmTemp(solo);}});@@ -288,7 +289,7 @@ describe("scanActiveHygiene — detectors", () => {// Same permanently-unclearable trap the meetings scaffold already fixed.assert.equal(scanActiveHygiene(solo, NOW, DEFAULTS).memoryInbox, null);} finally {- rmSync(solo, { recursive: true, force: true });+ rmTemp(solo);}});@@ -304,7 +305,7 @@ describe("scanActiveHygiene — detectors", () => {1,);} finally {- rmSync(solo, { recursive: true, force: true });+ rmTemp(solo);}});@@ -325,7 +326,7 @@ describe("scanActiveHygiene — detectors", () => {);assert.equal(scanActiveHygiene(solo, NOW, DEFAULTS).memoryInbox, null);} finally {- rmSync(solo, { recursive: true, force: true });+ rmTemp(solo);}});@@ -364,7 +365,7 @@ describe("scanActiveHygiene — detectors", () => {const text = formatActiveHygiene(scanActiveHygiene(solo, NOW, DEFAULTS)).join("\n");assert.match(text, /1 already-promoted capture\(s\) here carry a bare marker/);} finally {- rmSync(solo, { recursive: true, force: true });+ rmTemp(solo);}});@@ -394,7 +395,7 @@ describe("scanActiveHygiene — detectors", () => {);}} finally {- rmSync(solo, { recursive: true, force: true });+ rmTemp(solo);}});@@ -410,7 +411,7 @@ describe("scanActiveHygiene — detectors", () => {writeFileSync(join(solo, "memories/2026/07/y.md"), "# y\n\npromoted: brain/Thing\n");assert.equal(scanActiveHygiene(solo, NOW, DEFAULTS).memoryInbox?.count, 2);} finally {- rmSync(solo, { recursive: true, force: true });+ rmTemp(solo);}});@@ -444,7 +445,7 @@ describe("scanActiveHygiene — detectors", () => {assert.equal(report.inboxPressure, null);assert.deepEqual(formatActiveHygiene(report), []);} finally {- rmSync(empty, { recursive: true, force: true });+ rmTemp(empty);}});});diff --git a/.claude/scripts/tests/manifest-check.test.ts b/.claude/scripts/tests/manifest-check.test.tsindex e9c142d..7d1521c 100644--- a/.claude/scripts/tests/manifest-check.test.ts+++ b/.claude/scripts/tests/manifest-check.test.ts@@ -6,7 +6,7 @@import { test, describe } from "node:test";import assert from "node:assert/strict";-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { mkdtempSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import {@@ -16,6 +16,8 @@ import {listTopLevelFiles,} from "../../../.github/scripts/manifest-check.ts";+import { rmTemp } from "./_helpers.ts";+/** The real manifest's shape, in miniature. */const GLOBS = ["CLAUDE.md", ".claude/**", "templates/**", "brain/Skills.md"];@@ -151,7 +153,7 @@ describe("listTopLevelFiles", () => {assert.ok(isCovered(p, globs), `walk emitted a path its own glob cannot match: ${p}`);}} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}});diff --git a/.claude/scripts/tests/mcp-caller.test.ts b/.claude/scripts/tests/mcp-caller.test.tsindex 93902cc..9cacfd2 100644--- a/.claude/scripts/tests/mcp-caller.test.ts+++ b/.claude/scripts/tests/mcp-caller.test.ts@@ -12,7 +12,7 @@import { test, describe } from "node:test";import assert from "node:assert/strict";-import { mkdtempSync, rmSync, readFileSync, existsSync, writeFileSync, mkdirSync } from "node:fs";+import { mkdtempSync, readFileSync, existsSync, writeFileSync, mkdirSync } from "node:fs";import { tmpdir } from "node:os";import { join, dirname, basename } from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";@@ -31,6 +31,8 @@ import {type Root,} from "../lib/mcp-caller.ts";+import { rmTemp } from "./_helpers.ts";+const root = (uri: string): Root => ({ uri });// ---------------------------------------------------------------------------@@ -109,7 +111,7 @@ describe("reading the caller's identity from roots", () => {assert.equal(callerProject([root(uri)]), "billing-api");assert.equal(callerProjectSource([root(uri)]), "declared");} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}});@@ -122,7 +124,7 @@ describe("reading the caller's identity from roots", () => {assert.equal(callerProject([root(uri)]), basename(dir).toLowerCase(), `refused: ${JSON.stringify(bad)}`);}} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}});});@@ -254,7 +256,7 @@ describe("the audit log", () => {try {fn(dir);} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}}@@ -382,7 +384,7 @@ describe("summing a field across one day's entries", () => {try {fn(dir);} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}}diff --git a/.claude/scripts/tests/mcp-capture.test.ts b/.claude/scripts/tests/mcp-capture.test.tsindex b665f49..c0025ad 100644--- a/.claude/scripts/tests/mcp-capture.test.ts+++ b/.claude/scripts/tests/mcp-capture.test.ts@@ -14,7 +14,7 @@import { test, describe } from "node:test";import assert from "node:assert/strict";-import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readdirSync, readFileSync } from "node:fs";+import { mkdtempSync, mkdirSync, writeFileSync, readdirSync, readFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -31,6 +31,8 @@ import {import type { ExposurePolicy } from "../lib/mcp-exposure.ts";import { resolvableNames } from "../lib/mcp-memory-bridge.ts";+import { rmTemp } from "./_helpers.ts";+const NOW = new Date("2026-07-26T10:00:00Z");const POLICY: ExposurePolicy = { roots: ["brain", "projects"], neverExpose: new Set(), source: "manifest", memoryRoot: "memories" };@@ -39,7 +41,7 @@ function withVault(fn: (dir: string) => void): void {try {fn(dir);} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}}diff --git a/.claude/scripts/tests/mcp-context.test.ts b/.claude/scripts/tests/mcp-context.test.tsindex 907f4c5..b71c8bb 100644--- a/.claude/scripts/tests/mcp-context.test.ts+++ b/.claude/scripts/tests/mcp-context.test.ts@@ -13,7 +13,7 @@import { test, describe } from "node:test";import assert from "node:assert/strict";-import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs";+import { mkdtempSync, writeFileSync, mkdirSync } from "node:fs";import { tmpdir } from "node:os";import { join, dirname, resolve, sep } from "node:path";import { pathToFileURL } from "node:url";@@ -27,6 +27,8 @@ import {PROMPTS,} from "../lib/mcp-context.ts";+import { rmTemp } from "./_helpers.ts";+function tmpVault(): string {return mkdtempSync(join(tmpdir(), "ctx-"));}@@ -44,7 +46,7 @@ function withVault(fn: (dir: string) => void): void {try {fn(dir);} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}}diff --git a/.claude/scripts/tests/mcp-exposure.test.ts b/.claude/scripts/tests/mcp-exposure.test.tsindex 965b552..a7ab772 100644--- a/.claude/scripts/tests/mcp-exposure.test.ts+++ b/.claude/scripts/tests/mcp-exposure.test.ts@@ -12,7 +12,7 @@import { test, describe } from "node:test";import assert from "node:assert/strict";-import { mkdtempSync, rmSync, writeFileSync, mkdirSync, symlinkSync } from "node:fs";+import { mkdtempSync, writeFileSync, mkdirSync, symlinkSync } from "node:fs";import { tmpdir } from "node:os";import { join, dirname } from "node:path";@@ -31,6 +31,8 @@ import {import type { ExposurePolicy } from "../lib/mcp-exposure.ts";import { vaultRelKey } from "../lib/mcp-qmd-client.ts";+import { rmTemp } from "./_helpers.ts";+const NL = String.fromCharCode(10);const NOTE = (desc = "a note") => `---\ndate: 2026-07-26\ndescription: "${desc}"\n---\n\n# n\n\nbody\n`;@@ -49,7 +51,7 @@ function withVault(fn: (dir: string) => void): void {try {fn(dir);} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}}diff --git a/.claude/scripts/tests/mcp-graph.test.ts b/.claude/scripts/tests/mcp-graph.test.tsindex 50c809c..32f5d69 100644--- a/.claude/scripts/tests/mcp-graph.test.ts+++ b/.claude/scripts/tests/mcp-graph.test.ts@@ -14,13 +14,15 @@import { test, describe } from "node:test";import assert from "node:assert/strict";-import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs";+import { mkdtempSync, writeFileSync, mkdirSync } from "node:fs";import { tmpdir } from "node:os";import { join, dirname } from "node:path";import { normalizeKey, resolveVisible, outboundLinks, expandNote } from "../lib/mcp-graph.ts";import { resolveExposure, visibleFiles, type VisibleFile } from "../lib/mcp-exposure.ts";+import { rmTemp } from "./_helpers.ts";+function put(dir: string, rel: string, body: string): void {const full = join(dir, rel);mkdirSync(dirname(full), { recursive: true });@@ -44,7 +46,7 @@ function withVault(fn: (dir: string, files: VisibleFile[]) => void, roots = ["brconst policy = resolveExposure(dir, { mcp_exposed_roots: roots });fn(dir, visibleFiles(dir, policy));} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}}diff --git a/.claude/scripts/tests/mcp-memory-bridge.test.ts b/.claude/scripts/tests/mcp-memory-bridge.test.tsindex 7031d12..ed43637 100644--- a/.claude/scripts/tests/mcp-memory-bridge.test.ts+++ b/.claude/scripts/tests/mcp-memory-bridge.test.ts@@ -10,7 +10,7 @@import { test, describe } from "node:test";import assert from "node:assert/strict";-import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs";+import { mkdtempSync, writeFileSync, mkdirSync } from "node:fs";import { tmpdir } from "node:os";import { join, dirname } from "node:path";@@ -24,6 +24,8 @@ import {import type { VisibleFile } from "../lib/mcp-exposure.ts";import type { QmdClient } from "../lib/mcp-qmd-client.ts";+import { rmTemp } from "./_helpers.ts";+function put(dir: string, rel: string, body: string): string {const full = join(dir, rel);mkdirSync(dirname(full), { recursive: true });@@ -36,7 +38,7 @@ function withVault(fn: (dir: string) => void): void {try {fn(dir);} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}}diff --git a/.claude/scripts/tests/mcp-qmd-client.test.ts b/.claude/scripts/tests/mcp-qmd-client.test.tsindex 53918ff..e387052 100644--- a/.claude/scripts/tests/mcp-qmd-client.test.ts+++ b/.claude/scripts/tests/mcp-qmd-client.test.ts@@ -30,6 +30,7 @@ import {type QmdHit,type QmdClient,} from "../lib/mcp-qmd-client.ts";+import { waitFor } from "./_helpers.ts";/*** Write a stand-in qmd launcher that speaks just enough MCP to exercise the@@ -289,8 +290,10 @@ describe("client liveness", () => {// later call — search stays broken for the life of the server.const c = createQmdClient(process.cwd(), join(process.cwd(), "definitely-not-a-launcher.mjs"));assert.equal(c.alive, true, "alive until proven otherwise");- // Spawning a missing script fails asynchronously; wait for the signal.- await new Promise((r) => setTimeout(r, 400));+ // Spawning a missing script fails asynchronously, and the property under+ // test is that the client EVENTUALLY reports itself dead. A fixed sleep+ // cannot express that: 400ms was a bet a loaded Windows runner won (#235).+ await waitFor(() => !c.alive);assert.equal(c.alive, false, "a failed launcher must mark the client dead");c.dispose();});@@ -303,7 +306,7 @@ describe("client liveness", () => {test("a call against a dead client rejects rather than hanging", async () => {const c = createQmdClient(process.cwd(), join(process.cwd(), "still-missing.mjs"));- await new Promise((r) => setTimeout(r, 400));+ await waitFor(() => !c.alive);await assert.rejects(() => c.call("tools/call", {}), /qmd/i);c.dispose();});diff --git a/.claude/scripts/tests/mcp-reason.concurrency.test.ts b/.claude/scripts/tests/mcp-reason.concurrency.test.tsindex 65e7eec..1aae3e3 100644--- a/.claude/scripts/tests/mcp-reason.concurrency.test.ts+++ b/.claude/scripts/tests/mcp-reason.concurrency.test.ts@@ -29,10 +29,11 @@import { test, describe } from "node:test";import assert from "node:assert/strict";import { execFile } from "node:child_process";-import { mkdtempSync, rmSync, readdirSync, writeFileSync, mkdirSync } from "node:fs";+import { mkdtempSync, readdirSync, writeFileSync, mkdirSync } from "node:fs";import { tmpdir } from "node:os";import { join, dirname } from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";+import { rmTemp } from "./_helpers.ts";const LIB = join(dirname(fileURLToPath(import.meta.url)), "..", "lib", "mcp-reason.ts");const LIB_URL = JSON.stringify(pathToFileURL(LIB).href);@@ -59,13 +60,14 @@ function runAll(script: string, argsFor: (i: number) => string[], n: number): Prfunction withDir(fn: (dir: string) => Promise<void>): Promise<void> {const dir = mkdtempSync(join(tmpdir(), "reason-conc-"));return fn(dir).finally(() =>- // `maxRetries` is not optional on Windows here: these tests create and- // rename hundreds of files across eight processes, and the directory stays- // briefly busy after the last child exits — cleanup then throws ENOTEMPTY- // and fails a test whose assertions already passed. Observed on this- // suite; CI runs a Windows job, so without it the test is flaky there and- // green everywhere else, which is the worst kind of red.- rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }),+ // Retrying is not optional on Windows here: these tests create and rename+ // hundreds of files across eight processes, and the directory stays briefly+ // busy after the last child exits — a bare rmSync then throws ENOTEMPTY and+ // fails a test whose assertions already passed. Observed on this suite; CI+ // runs a Windows job, so without the retries the test is flaky there and+ // green everywhere else, which is the worst kind of red. `rmTemp` retries,+ // and swallows the case where retrying is not enough.+ rmTemp(dir),);}@@ -87,6 +89,7 @@ process.stdout.write(rel);const CONFIG_CHURN = `import { readFileSync } from "node:fs";import { writeIsolatedMcpConfig, writeIsolatedMcpConfigPath } from ${LIB_URL};+const [vault, role] = process.argv.slice(2);const path = writeIsolatedMcpConfigPath(vault);let torn = 0;diff --git a/.claude/scripts/tests/mcp-reason.test.ts b/.claude/scripts/tests/mcp-reason.test.tsindex 754c785..6733681 100644--- a/.claude/scripts/tests/mcp-reason.test.ts+++ b/.claude/scripts/tests/mcp-reason.test.ts@@ -17,7 +17,7 @@import { test, describe } from "node:test";import assert from "node:assert/strict";-import { mkdtempSync, rmSync, writeFileSync, readFileSync, readdirSync } from "node:fs";+import { mkdtempSync, writeFileSync, readFileSync, readdirSync } from "node:fs";import { tmpdir } from "node:os";import { join, dirname } from "node:path";import { fileURLToPath } from "node:url";@@ -42,12 +42,14 @@ import {type ReasoningResult,} from "../lib/mcp-reason.ts";+import { rmTemp } from "./_helpers.ts";+function withDir(fn: (dir: string) => void): void {const dir = mkdtempSync(join(tmpdir(), "reason-"));try {fn(dir);} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}}diff --git a/.claude/scripts/tests/mcp-refusal-audit.test.ts b/.claude/scripts/tests/mcp-refusal-audit.test.tsindex d8604a8..23345fa 100644--- a/.claude/scripts/tests/mcp-refusal-audit.test.ts+++ b/.claude/scripts/tests/mcp-refusal-audit.test.ts@@ -17,12 +17,14 @@import { test, describe } from "node:test";import assert from "node:assert/strict";-import { mkdtempSync, rmSync } from "node:fs";+import { mkdtempSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { createHandlers } from "../lib/mcp-server.ts";+import { rmTemp } from "./_helpers.ts";+interface Logged {readonly action: string;readonly detail: Record<string, unknown>;@@ -77,7 +79,7 @@ describe("a refused call is auditable", () => {const serialised = JSON.stringify(refusals[0]);assert.ok(!serialised.includes("the prose is fine"), "the log must not become a copy of the call");} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}});@@ -91,7 +93,7 @@ describe("a refused call is auditable", () => {assert.equal(refusals.length, 1);assert.equal(refusals[0]!.detail["tool"], "record_work");} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}});@@ -113,7 +115,7 @@ describe("a refused call is auditable", () => {"a call that was not refused must not log a refusal",);} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}});});diff --git a/.claude/scripts/tests/memory-discover.test.ts b/.claude/scripts/tests/memory-discover.test.tsindex 7d0e290..be2e287 100644--- a/.claude/scripts/tests/memory-discover.test.ts+++ b/.claude/scripts/tests/memory-discover.test.ts@@ -14,7 +14,7 @@import { test, describe } from "node:test";import assert from "node:assert/strict";-import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs";+import { mkdtempSync, writeFileSync, mkdirSync } from "node:fs";import { tmpdir } from "node:os";import { join, dirname } from "node:path";@@ -32,6 +32,8 @@ import {type IndexPathInfo,} from "../lib/memory-discover.ts";+import { rmTemp } from "./_helpers.ts";+// ---------------------------------------------------------------------------// Fixtures// ---------------------------------------------------------------------------@@ -72,7 +74,7 @@ function withVault(fn: (dir: string) => void): void {try {fn(dir);} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}}diff --git a/.claude/scripts/tests/memory-index.test.ts b/.claude/scripts/tests/memory-index.test.tsindex 3960048..e7dbea2 100644--- a/.claude/scripts/tests/memory-index.test.ts+++ b/.claude/scripts/tests/memory-index.test.ts@@ -19,7 +19,6 @@ import { test, describe } from "node:test";import assert from "node:assert/strict";import {mkdtempSync,- rmSync,writeFileSync,mkdirSync,unlinkSync,@@ -34,6 +33,8 @@ import { createMemoryIndex } from "../lib/memory-index.ts";import { readMemories, recall, recallFrom, agentMemories, MEMORY_SOURCE } from "../lib/memory-recall.ts";import { loadMemoryDigests, digestsFrom } from "../lib/mcp-memory-bridge.ts";+import { rmTemp } from "./_helpers.ts";+const ROOT = "memories";function withVault(fn: (dir: string) => void): void {@@ -41,7 +42,7 @@ function withVault(fn: (dir: string) => void): void {try {fn(dir);} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}}diff --git a/.claude/scripts/tests/memory-promoted.test.ts b/.claude/scripts/tests/memory-promoted.test.tsindex 4077eba..767752c 100644--- a/.claude/scripts/tests/memory-promoted.test.ts+++ b/.claude/scripts/tests/memory-promoted.test.ts@@ -24,7 +24,7 @@import { test, describe } from "node:test";import assert from "node:assert/strict";-import { mkdtempSync, rmSync, mkdirSync, writeFileSync, symlinkSync } from "node:fs";+import { mkdtempSync, mkdirSync, writeFileSync, symlinkSync } from "node:fs";import { tmpdir } from "node:os";import { join, dirname } from "node:path";@@ -40,6 +40,8 @@ import {} from "../lib/memory-promoted.ts";import type { ExposurePolicy } from "../lib/mcp-exposure.ts";+import { rmTemp } from "./_helpers.ts";+const POLICY: ExposurePolicy = {// `work/active` is the shape that matters: multi-segment, as every root in// the shipping manifest is.@@ -54,7 +56,7 @@ function withVault(fn: (dir: string) => void): void {try {fn(dir);} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}}diff --git a/.claude/scripts/tests/memory-recall.test.ts b/.claude/scripts/tests/memory-recall.test.tsindex 2781e5d..fe699ec 100644--- a/.claude/scripts/tests/memory-recall.test.ts+++ b/.claude/scripts/tests/memory-recall.test.ts@@ -22,7 +22,7 @@import { test, describe, before, after } from "node:test";import assert from "node:assert/strict";-import { mkdtempSync, rmSync } from "node:fs";+import { mkdtempSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { readFileSync } from "node:fs";@@ -44,6 +44,8 @@ import {type MemoryEntry,} from "../lib/memory-recall.ts";+import { rmTemp } from "./_helpers.ts";+const DAY = new Date(2026, 6, 26);const CALLERS = {@@ -127,7 +129,7 @@ before(() => {}});-after(() => rmSync(VAULT, { recursive: true, force: true }));+after(() => rmTemp(VAULT));/** Ids visible to a caller, as a sorted array. */function seen(caller: Caller): string[] {@@ -295,7 +297,7 @@ describe("reader robustness", () => {assert.deepEqual(facetsOf(fm).projects, ["atlas"]);assert.equal(facetsOf(fm).confidence, "verified");} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}});@@ -351,7 +353,7 @@ describe("reader robustness", () => {try {assert.deepEqual(recall(dir, CALLERS.atlas), []);} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}});});diff --git a/.claude/scripts/tests/memory-supersede.test.ts b/.claude/scripts/tests/memory-supersede.test.tsindex 065338f..92f55f1 100644--- a/.claude/scripts/tests/memory-supersede.test.ts+++ b/.claude/scripts/tests/memory-supersede.test.ts@@ -9,7 +9,7 @@import { test, describe } from "node:test";import assert from "node:assert/strict";-import { mkdtempSync, rmSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";+import { mkdtempSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";import { tmpdir } from "node:os";import { join, dirname } from "node:path";@@ -17,6 +17,8 @@ import { addToFrontmatterList, markSuperseded, resolveSupersedes } from "../lib/import { validateMemory, writeMemory } from "../lib/memory-write.ts";import { recall, parseFrontmatter, facetsOf } from "../lib/memory-recall.ts";+import { rmTemp } from "./_helpers.ts";+const MD = "---\ndate: 2026-07-26\nsource: mcp-capture\nscope: general\n---\n\n# t\n\nbody\n";function vaultWith(md: string): { dir: string; rel: string } {@@ -69,7 +71,7 @@ describe("markSuperseded", () => {assert.equal(r.changed, true);assert.ok(readFileSync(join(dir, rel), "utf8").includes('superseded_by: ["The Correction"]'));} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}});@@ -89,7 +91,7 @@ describe("markSuperseded", () => {assert.equal(r.matched.length, 1);assert.equal(r.matched[0]!.rel, "new.md");} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}});@@ -104,7 +106,7 @@ describe("markSuperseded", () => {assert.match(r.reason, /refusing to modify/);assert.equal(readFileSync(join(dir, rel), "utf8"), original);} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}});@@ -113,7 +115,7 @@ describe("markSuperseded", () => {try {assert.equal(markSuperseded(dir, "memories/nope.md", "x").ok, false);} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}});});@@ -203,7 +205,7 @@ describe("correction round trip", () => {"the corrected memory carries its back-link",);} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}});@@ -225,7 +227,7 @@ describe("correction round trip", () => {assert.deepEqual(fm.projects, ["atlas"]);assert.deepEqual(fm.superseded_by, ["the newer one"]);} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}});});diff --git a/.claude/scripts/tests/memory-write.concurrency.test.ts b/.claude/scripts/tests/memory-write.concurrency.test.tsindex aedc713..8278032 100644--- a/.claude/scripts/tests/memory-write.concurrency.test.ts+++ b/.claude/scripts/tests/memory-write.concurrency.test.ts@@ -20,10 +20,11 @@import { test, describe } from "node:test";import assert from "node:assert/strict";import { execFile } from "node:child_process";-import { mkdtempSync, rmSync, readdirSync, writeFileSync, mkdirSync } from "node:fs";+import { mkdtempSync, readdirSync, writeFileSync, mkdirSync } from "node:fs";import { tmpdir } from "node:os";import { join, dirname } from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";+import { rmTemp } from "./_helpers.ts";const LIB = join(dirname(fileURLToPath(import.meta.url)), "..", "lib", "memory-write.ts");const WRITERS = 8;@@ -36,6 +37,7 @@ const WRITERS = 8;*/const WRITER_SRC = `import { validateMemory, writeMemory } from ${JSON.stringify(pathToFileURL(LIB).href)};+const [vault, origin] = process.argv.slice(2);const v = validateMemory({@@ -89,7 +91,7 @@ describe("concurrent writes from separate processes", () => {const leftovers = readdirSync(join(dir, "memories", "2026", "07")).filter((f) => f.endsWith(".tmp"));assert.deepEqual(leftovers, [], "no half-written note may be left for the indexer");} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}});});diff --git a/.claude/scripts/tests/memory-write.test.ts b/.claude/scripts/tests/memory-write.test.tsindex bea6623..0e5f409 100644--- a/.claude/scripts/tests/memory-write.test.ts+++ b/.claude/scripts/tests/memory-write.test.ts@@ -12,7 +12,7 @@import { test, describe } from "node:test";import { extractAliases, buildResolver } from "../lib/wikilinks.ts";import assert from "node:assert/strict";-import { mkdtempSync, rmSync, existsSync, readFileSync, mkdirSync, writeFileSync } from "node:fs";+import { mkdtempSync, existsSync, readFileSync, mkdirSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join, sep, resolve } from "node:path";@@ -31,6 +31,8 @@ import {type MemoryInput,} from "../lib/memory-write.ts";+import { rmTemp } from "./_helpers.ts";+const DAY = new Date(2026, 6, 26, 14, 2, 11); // 2026-07-26, localconst OK = {title: "tsup externals decide what a patch can fix",@@ -77,7 +79,7 @@ describe("real usage", () => {assert.equal(rel, "memories/2026/07/2026-07-26 tsup externals decide what a patch can fix.md");assert.ok(existsSync(join(dir, rel)));} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}});@@ -473,7 +475,7 @@ describe("write collisions", () => {assert.ok(b.rel.includes("(2)"));assert.ok(readMemory(dir, a.rel).includes(OK.body), "the first memory must survive intact");} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}});@@ -484,7 +486,7 @@ describe("write collisions", () => {writeMemory(dir, v, []);assert.ok(writeMemory(dir, v, []).rel.endsWith(".md"));} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}});@@ -494,7 +496,7 @@ describe("write collisions", () => {const v = validateMemory(OK, { now: new Date(2027, 2, 3), origin: "p" }).value!;assert.ok(existsSync(writeMemory(dir, v, []).full));} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}});});@@ -568,7 +570,7 @@ describe("containment property", () => {const { full } = writeMemory(dir, v.value!, []);assert.ok(resolve(full).startsWith(resolve(dir, MEMORY_ROOT) + sep));} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}});});diff --git a/.claude/scripts/tests/om-mcp.integration.test.ts b/.claude/scripts/tests/om-mcp.integration.test.tsindex f7758f4..424027e 100644--- a/.claude/scripts/tests/om-mcp.integration.test.ts+++ b/.claude/scripts/tests/om-mcp.integration.test.ts@@ -17,10 +17,11 @@import { test, describe, before, after } from "node:test";import assert from "node:assert/strict";import { spawn, type ChildProcess } from "node:child_process";-import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync, existsSync } from "node:fs";+import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync } from "node:fs";import { tmpdir } from "node:os";import { join, dirname } from "node:path";import { fileURLToPath } from "node:url";+import { rmTemp, waitFor } from "./_helpers.ts";const SCRIPTS = join(dirname(fileURLToPath(import.meta.url)), "..");const LAUNCHER = join(SCRIPTS, "om-mcp.mjs");@@ -39,6 +40,8 @@ let child: ChildProcess;let stderr = "";const pending = new Map<number, (m: Rpc) => void>();let nextId = 0;+/** Set when we have answered `roots/list` — the moment this session stops being anonymous. */+let rootsAnswered = false;function put(rel: string, body: string): void {const full = join(vault, rel);@@ -118,6 +121,7 @@ before(async () => {// identified rather than anonymous.if (msg.method === "roots/list") {send({ jsonrpc: "2.0", id: msg.id, result: { roots: [{ uri: `file:///C:/Dev/${CALLER}` }] } });+ rootsAnswered = true;continue;}if (msg.method) continue;@@ -136,12 +140,17 @@ before(async () => {});assert.equal((init.result?.serverInfo as { name?: string })?.name, "om");send({ jsonrpc: "2.0", method: "notifications/initialized" });- await new Promise((r) => setTimeout(r, 300));+ // Wait for the handshake itself rather than for 300ms and hope. Until+ // `roots/list` has been asked and answered this session is anonymous, and an+ // anonymous run fails as though the vault were empty — so a runner slow+ // enough to lose that bet loses the whole suite, not one test (#235).+ await waitFor(() => rootsAnswered, TIMEOUT);+ assert.ok(rootsAnswered, "the server must ask who is calling, or every scope assertion below is meaningless");});after(() => {child?.kill();- if (vault) rmSync(vault, { recursive: true, force: true });+ rmTemp(vault);});describe("the om server on the wire", () => {diff --git a/.claude/scripts/tests/pre-compact.test.ts b/.claude/scripts/tests/pre-compact.test.tsindex 759a4e6..09d2e42 100644--- a/.claude/scripts/tests/pre-compact.test.ts+++ b/.claude/scripts/tests/pre-compact.test.ts@@ -4,7 +4,7 @@import { test, describe, before, after } from "node:test";import assert from "node:assert/strict";-import { mkdtempSync, writeFileSync, rmSync, readdirSync, utimesSync } from "node:fs";+import { mkdtempSync, writeFileSync, readdirSync, utimesSync } from "node:fs";import { join } from "node:path";import { tmpdir } from "node:os";import {@@ -13,6 +13,8 @@ import {pruneBackups,} from "../pre-compact.ts";+import { rmTemp } from "./_helpers.ts";+describe("formatTimestamp", () => {test("pads single digits (YYYYMMDD_HHMMSS)", () => {const d = new Date(2026, 3, 5, 9, 7, 3); // month is 0-indexed → April@@ -32,7 +34,7 @@ describe("listBackups + pruneBackups", () => {});after(() => {- if (dir) rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);});function makeBackup(name: string, ageSeconds: number): void {diff --git a/.claude/scripts/tests/qmd-ignore.test.ts b/.claude/scripts/tests/qmd-ignore.test.tsindex 19998bd..b79a2a7 100644--- a/.claude/scripts/tests/qmd-ignore.test.ts+++ b/.claude/scripts/tests/qmd-ignore.test.ts@@ -10,7 +10,7 @@import { test, describe } from "node:test";import assert from "node:assert/strict";-import { mkdtempSync, rmSync, writeFileSync, readFileSync } from "node:fs";+import { mkdtempSync, writeFileSync, readFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -22,6 +22,8 @@ import {qmdConfigPath,} from "../lib/qmd-ignore.ts";+import { rmTemp } from "./_helpers.ts";+const YAML_BASE = `collections:obsidian-mind:path: /Users/dev/obsidian-mind@@ -74,7 +76,7 @@ describe("translateToGlob", () => {describe("readObsidianIgnore", () => {const tmp = mkdtempSync(join(tmpdir(), "qmd-bootstrap-obsidian-"));- test.after(() => rmSync(tmp, { recursive: true, force: true }));+ test.after(() => rmTemp(tmp));test("missing file (ENOENT) returns empty array — user has no filters", () => {assert.deepEqual(readObsidianIgnore(join(tmp, "does-not-exist.json")), []);@@ -274,7 +276,7 @@ describe("upsertIgnoreInYaml — pure transform", () => {describe("writeQmdIgnore — file IO wrapper", () => {const tmp = mkdtempSync(join(tmpdir(), "qmd-bootstrap-yaml-"));- test.after(() => rmSync(tmp, { recursive: true, force: true }));+ test.after(() => rmTemp(tmp));test("writes the transformed YAML when patterns are non-empty", () => {const path = join(tmp, "write.yml");diff --git a/.claude/scripts/tests/qmd-refresh.integration.test.ts b/.claude/scripts/tests/qmd-refresh.integration.test.tsindex e4a1b66..a4c94aa 100644--- a/.claude/scripts/tests/qmd-refresh.integration.test.ts+++ b/.claude/scripts/tests/qmd-refresh.integration.test.ts@@ -35,7 +35,7 @@ import {writeFileSync,} from "node:fs";import { tmpdir } from "node:os";-import { runScript as spawnHook } from "./_helpers.ts";+import { runScript as spawnHook, rmTemp } from "./_helpers.ts";import { resolveQmdEntry } from "../lib/qmd.ts";const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));@@ -55,7 +55,7 @@ before(() => {});after(() => {- if (TMP_DIR) rmSync(TMP_DIR, { recursive: true, force: true });+ rmTemp(TMP_DIR);});// Used to build realistic absolute `file_path` fixtures for hook payloads.diff --git a/.claude/scripts/tests/read-head.test.ts b/.claude/scripts/tests/read-head.test.tsindex 60cf7f1..8826484 100644--- a/.claude/scripts/tests/read-head.test.ts+++ b/.claude/scripts/tests/read-head.test.ts@@ -11,18 +11,20 @@import { test, describe } from "node:test";import assert from "node:assert/strict";-import { mkdtempSync, rmSync, writeFileSync, mkdirSync, readFileSync } from "node:fs";+import { mkdtempSync, writeFileSync, mkdirSync, readFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { readHead } from "../lib/read-head.ts";+import { rmTemp } from "./_helpers.ts";+function withDir(fn: (dir: string) => void): void {const dir = mkdtempSync(join(tmpdir(), "head-"));try {fn(dir);} finally {- rmSync(dir, { recursive: true, force: true });+ rmTemp(dir);}}diff --git a/.claude/scripts/tests/session-start.integration.test.ts b/.claude/scripts/tests/session-start.integration.test.tsindex 7dfc235..1f245dd 100644--- a/.claude/scripts/tests/session-start.integration.test.ts+++ b/.claude/scripts/tests/session-start.integration.test.ts@@ -33,7 +33,7 @@ import {writeFileSync,} from "node:fs";import { tmpdir } from "node:os";-import { runScript as spawnHook } from "./_helpers.ts";+import { runScript as spawnHook, rmTemp } from "./_helpers.ts";const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));const SCRIPT = resolve(SCRIPT_DIR, "../session-start.ts");@@ -61,21 +61,11 @@ before(() => {);});-after(() => {- // `maxRetries` + `retryDelay` is Node's documented Windows guard against- // transient `EBUSY` / `EPERM` on rmdir when child processes or the OS- // haven't fully released file handles yet. On Windows CI the test's tmp- // dir occasionally lingers a few seconds after the detached qmd worker- // finishes; retrying with linear backoff is the idiomatic fix.- if (TMP_DIR) {- rmSync(TMP_DIR, {- recursive: true,- force: true,- maxRetries: 10,- retryDelay: 200,- });- }-});+// `rmTemp` retries — Node's documented Windows guard against transient+// `EBUSY` / `EPERM` on rmdir while a handle is still held — and then gives up+// quietly. The retries alone were not enough: #235 lost a green suite to an+// `EPERM` thrown out of this hook after the assertions had already passed.+after(() => rmTemp(TMP_DIR));const runHook = () => spawnHook(SCRIPT, "", { CLAUDE_PROJECT_DIR: TMP_DIR });@@ -209,11 +199,7 @@ describe("session-start — listing collapse and injection budget", () => {}});- after(() => {- if (BIG_DIR) {- rmSync(BIG_DIR, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });- }- });+ after(() => rmTemp(BIG_DIR));const runBig = () => spawnHook(SCRIPT, "", { CLAUDE_PROJECT_DIR: BIG_DIR });const listingOf = (stdout: string) =>diff --git a/.claude/scripts/tests/session-start.test.ts b/.claude/scripts/tests/session-start.test.tsindex 2341852..9e74e35 100644--- a/.claude/scripts/tests/session-start.test.ts+++ b/.claude/scripts/tests/session-start.test.ts@@ -8,7 +8,7 @@import { test, describe } from "node:test";import assert from "node:assert/strict";import { join, dirname } from "node:path";-import { readFileSync, writeFileSync, mkdtempSync, rmSync } from "node:fs";+import { readFileSync, writeFileSync, mkdtempSync } from "node:fs";import { fileURLToPath } from "node:url";import { tmpdir } from "node:os";import { spawnSync } from "node:child_process";@@ -47,6 +47,8 @@ import {collectOpenTasks,} from "../lib/session-start.ts";+import { rmTemp } from "./_helpers.ts";+describe("take", () => {test("keeps first N lines", () => {assert.equal(take("a\nb\nc\nd", 2), "a\nb");@@ -246,7 +248,7 @@ describe("quoteForPosixShell — verified against a real POSIX shell", () => {parts.pop(); // trailing empty after the final delimiterreturn parts;} finally {- rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });+ rmTemp(dir);}}@@ -289,7 +291,7 @@ describe("quoteForPosixShell — verified against a real POSIX shell", () => {"quoting leaked — a command substitution executed",);} finally {- rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });+ rmTemp(dir);}});@@ -324,7 +326,7 @@ describe("quoteForPosixShell — verified against a real POSIX shell", () => {assert.equal(r.status, 0, r.stderr);assert.equal(r.stdout, value, "sourcing the file must restore the exact path");} finally {- rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });+ rmTemp(dir);}});});diff --git a/.claude/scripts/tests/stop-checklist.test.ts b/.claude/scripts/tests/stop-checklist.test.tsindex 0603f07..4b94990 100644--- a/.claude/scripts/tests/stop-checklist.test.ts+++ b/.claude/scripts/tests/stop-checklist.test.ts@@ -14,11 +14,11 @@import { test, describe, before, after } from "node:test";import assert from "node:assert/strict";-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { mkdtempSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { fileURLToPath } from "node:url";import { dirname, join, resolve } from "node:path";-import { runScript as spawnHook } from "./_helpers.ts";+import { runScript as spawnHook, rmTemp } from "./_helpers.ts";const SCRIPT = resolve(dirname(fileURLToPath(import.meta.url)),@@ -48,7 +48,7 @@ before(() => {});after(() => {- if (TMP_DIR) rmSync(TMP_DIR, { recursive: true, force: true });+ rmTemp(TMP_DIR);});const runScript = (stdin: string | object | null) =>diff --git a/.claude/scripts/tests/tidy-fix.test.ts b/.claude/scripts/tests/tidy-fix.test.tsindex 15fce52..c74d4b3 100644--- a/.claude/scripts/tests/tidy-fix.test.ts+++ b/.claude/scripts/tests/tidy-fix.test.ts@@ -14,13 +14,14 @@ import {mkdirSync,mkdtempSync,readFileSync,- rmSync,writeFileSync,} from "node:fs";import { join, dirname, resolve } from "node:path";import { tmpdir } from "node:os";import { fileURLToPath } from "node:url";+import { rmTemp } from "./_helpers.ts";+const SCRIPT = resolve(dirname(fileURLToPath(import.meta.url)),"../tidy-fix.ts",@@ -77,8 +78,8 @@ before(() => {});after(() => {- rmSync(ROOT, { recursive: true, force: true });- rmSync(MEMDIR, { recursive: true, force: true });+ rmTemp(ROOT);+ rmTemp(MEMDIR);});describe("tidy-fix", () => {diff --git a/.claude/scripts/tests/validate-write.test.ts b/.claude/scripts/tests/validate-write.test.tsindex 703a452..3e7c541 100644--- a/.claude/scripts/tests/validate-write.test.ts+++ b/.claude/scripts/tests/validate-write.test.ts@@ -7,9 +7,9 @@ import { test, describe, before, after } from "node:test";import assert from "node:assert/strict";import { fileURLToPath } from "node:url";import { dirname, join, resolve } from "node:path";-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { mkdtempSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";-import { runScript as spawnHook } from "./_helpers.ts";+import { runScript as spawnHook, rmTemp } from "./_helpers.ts";const SCRIPT = resolve(dirname(fileURLToPath(import.meta.url)),@@ -23,7 +23,7 @@ before(() => {});after(() => {- if (TMP_DIR) rmSync(TMP_DIR, { recursive: true, force: true });+ rmTemp(TMP_DIR);});// The hook skips files outside the vault root; fixtures live in the OS