Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Clean up Open Knowledge test scratch directories (#5562)

Nick Gomez912b8dc665a2
diff --git a/packages/app/tests/integration/link-graph-metadata.test.ts b/packages/app/tests/integration/link-graph-metadata.test.ts
index 217a617d2..d133c5fc5 100644
--- a/packages/app/tests/integration/link-graph-metadata.test.ts
+++ b/packages/app/tests/integration/link-graph-metadata.test.ts
@@ -1,11 +1,20 @@
-import { mkdtempSync, realpathSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
+import { realpathSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../../test-support/temp-dir.test-helper.ts';
+import { runTeardownPhases } from '../stress/_helpers/teardown-fs';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
import { createTestServer, type TestServer } from './test-harness';
+const makeTempDir = createTempDirFactory((cleanup) => {
+ afterAll(() =>
+ runTeardownPhases(async () => {
+ await server?.cleanup();
+ }, cleanup),
+ );
+});
+
interface LinkGraphResponse {
nodes: Array<{
id: string;
@@ -23,7 +32,7 @@ interface LinkGraphResponse {
let server: TestServer;
beforeAll(async () => {
- const contentDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-linkgraph-meta-')));
+ const contentDir = realpathSync(makeTempDir('ok-linkgraph-meta-'));
writeFileSync(
join(contentDir, 'hub.md'),
@@ -50,10 +59,6 @@ beforeAll(async () => {
await wait(1500);
}, HARNESS_BOOT_TIMEOUT_MS);
-afterAll(async () => {
- await server.cleanup();
-});
-
async function fetchLinkGraph(): Promise<LinkGraphResponse> {
const res = await fetch(`http://127.0.0.1:${server.port}/api/link-graph`);
return res.json() as Promise<LinkGraphResponse>;
diff --git a/packages/app/tests/integration/qa-healing-probe.test.ts b/packages/app/tests/integration/qa-healing-probe.test.ts
index 7c4ba934b..ea73552d5 100644
--- a/packages/app/tests/integration/qa-healing-probe.test.ts
+++ b/packages/app/tests/integration/qa-healing-probe.test.ts
@@ -1,9 +1,10 @@
-import { appendFileSync, mkdtempSync } from 'node:fs';
-import { tmpdir } from 'node:os';
+import { appendFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
-import { describe, expect, test } from 'vitest';
+import { afterAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
+import { createTempDirFactory } from '../../../../test-support/temp-dir.test-helper.ts';
+import { runTeardownPhases } from '../stress/_helpers/teardown-fs';
import {
agentWriteMd,
createRestartableServer,
@@ -16,6 +17,8 @@ import {
type TestClient,
} from './test-harness';
+const makeTempDir = createTempDirFactory(afterAll);
+
const DIAG = process.env.QA_DIAG_OUT;
function diag(probe: string, data: Record<string, unknown>): void {
if (!DIAG) return;
@@ -50,12 +53,13 @@ describe('healing bounds for the stranded states', () => {
test('HEAL-A: repeated source-side drains eventually surface a source-authored edge run in the WYSIWYG', async () => {
const server = await createTestServer();
const docName = `qa-heal-a-${crypto.randomUUID()}`;
- const clients = await createTestClients(server.port, {
- count: 2,
- docName,
- perClientOptions: { skipInvariantWatcher: true },
- });
+ let clients: TestClient[] = [];
try {
+ clients = await createTestClients(server.port, {
+ count: 2,
+ docName,
+ perClientOptions: { skipInvariantWatcher: true },
+ });
const seed = 'Above.\n\nBelow.\n';
await agentWriteMd(server.port, seed, { docName, position: 'replace' });
await pollUntil(() => clients.every((c) => c.ytext.toString() === seed), 10_000);
@@ -101,20 +105,22 @@ describe('healing bounds for the stranded states', () => {
'WYSIWYG converged to the full source state within 10 further drains',
).toBeGreaterThanOrEqual(0);
} finally {
- for (const c of clients) await c.cleanup();
- await server.cleanup();
+ await runTeardownPhases(...clients.map((client) => () => client.cleanup()), () =>
+ server.cleanup(),
+ );
}
}, 90_000);
test('HEAL-B: repeated source-side drains eventually surface the merge-seam stranded keystroke', async () => {
const server = await createTestServer();
const docName = `qa-heal-b-${crypto.randomUUID()}`;
- const clients = await createTestClients(server.port, {
- count: 2,
- docName,
- perClientOptions: { skipInvariantWatcher: true },
- });
+ let clients: TestClient[] = [];
try {
+ clients = await createTestClients(server.port, {
+ count: 2,
+ docName,
+ perClientOptions: { skipInvariantWatcher: true },
+ });
const seed = 'Above.\n\nBelow.\n';
await agentWriteMd(server.port, seed, { docName, position: 'replace' });
await pollUntil(() => clients.every((c) => c.ytext.toString() === seed), 10_000);
@@ -157,20 +163,22 @@ describe('healing bounds for the stranded states', () => {
'WYSIWYG converged to the full source state within 10 further drains',
).toBeGreaterThanOrEqual(0);
} finally {
- for (const c of clients) await c.cleanup();
- await server.cleanup();
+ await runTeardownPhases(...clients.map((client) => () => client.cleanup()), () =>
+ server.cleanup(),
+ );
}
}, 90_000);
test('INV-04b: the phantom fragment run does not resurrect into Y.Text on a later WYSIWYG edit', async () => {
const server = await createTestServer();
const docName = `qa-heal-c-${crypto.randomUUID()}`;
- const clients = await createTestClients(server.port, {
- count: 2,
- docName,
- perClientOptions: { skipInvariantWatcher: true },
- });
+ let clients: TestClient[] = [];
try {
+ clients = await createTestClients(server.port, {
+ count: 2,
+ docName,
+ perClientOptions: { skipInvariantWatcher: true },
+ });
const seed = 'Above.\n\nBelow.\n';
await agentWriteMd(server.port, seed, { docName, position: 'replace' });
await pollUntil(() => clients.every((c) => c.ytext.toString() === seed), 10_000);
@@ -202,79 +210,96 @@ describe('healing bounds for the stranded states', () => {
);
}
} finally {
- for (const c of clients) await c.cleanup();
- await server.cleanup();
+ await runTeardownPhases(...clients.map((client) => () => client.cleanup()), () =>
+ server.cleanup(),
+ );
}
}, 60_000);
});
describe('restart lifecycle (corrected: no testReset truncation)', () => {
test('RESTART-CLEAN: a source-authored edge run survives a clean server restart and re-derives', async () => {
- const contentDir = mkdtempSync(join(tmpdir(), 'qa-restart-clean-'));
+ const contentDir = makeTempDir('qa-restart-clean-');
const docName = `qa-restart-${crypto.randomUUID()}`;
const withRun = 'Above.\n\nBelow.\n\n\n';
const s1 = await createTestServer({ contentDir, keepContentDir: true });
- const c1 = await createTestClient(s1.port, docName, { skipInvariantWatcher: true });
- await agentWriteMd(s1.port, 'Above.\n\nBelow.\n', { docName, position: 'replace' });
- await pollUntil(() => c1.ytext.toString() === 'Above.\n\nBelow.\n', 10_000);
- c1.doc.transact(() => {
- c1.ytext.insert(c1.ytext.length, '\n\n');
- });
- expect(
- await settle(() => readTestDoc(contentDir, docName) === withRun, 15_000),
- 'flushed pre-restart',
- ).toBe(true);
- detachClient(c1);
- await s1.cleanup();
+ try {
+ const c1 = await createTestClient(s1.port, docName, { skipInvariantWatcher: true });
+ try {
+ await agentWriteMd(s1.port, 'Above.\n\nBelow.\n', { docName, position: 'replace' });
+ await pollUntil(() => c1.ytext.toString() === 'Above.\n\nBelow.\n', 10_000);
+ c1.doc.transact(() => {
+ c1.ytext.insert(c1.ytext.length, '\n\n');
+ });
+ expect(
+ await settle(() => readTestDoc(contentDir, docName) === withRun, 15_000),
+ 'flushed pre-restart',
+ ).toBe(true);
+ } finally {
+ detachClient(c1);
+ }
+ } finally {
+ await s1.cleanup();
+ }
const diskAfterShutdown = readTestDoc(contentDir, docName);
const s2 = await createTestServer({ contentDir, keepContentDir: true });
- const c2 = await createTestClient(s2.port, docName, { skipInvariantWatcher: true });
try {
- const loaded = await settle(
- () => c2.ytext.toString() === withRun && serializeFragment(c2.fragment) === withRun,
- 10_000,
- );
- await wait(3000);
- const result = {
- diskAfterShutdown,
- loaded,
- ytext: c2.ytext.toString(),
- fragment: serializeFragment(c2.fragment),
- blanks: countBlankLineNodes(c2.fragment),
- diskFinal: readTestDoc(contentDir, docName),
- };
- diag('RESTART-CLEAN', result);
- expect(diskAfterShutdown, 'clean shutdown preserves bytes').toBe(withRun);
- expect(c2.ytext.toString(), 'reload restores bytes').toBe(withRun);
- expect(serializeFragment(c2.fragment), 'reload re-derives the run into the fragment').toBe(
- withRun,
- );
- expect(countBlankLineNodes(c2.fragment)).toBe(2);
- expect(readTestDoc(contentDir, docName), 'no creep after a reload store cycle').toBe(withRun);
+ const c2 = await createTestClient(s2.port, docName, { skipInvariantWatcher: true });
+ try {
+ const loaded = await settle(
+ () => c2.ytext.toString() === withRun && serializeFragment(c2.fragment) === withRun,
+ 10_000,
+ );
+ await wait(3000);
+ const result = {
+ diskAfterShutdown,
+ loaded,
+ ytext: c2.ytext.toString(),
+ fragment: serializeFragment(c2.fragment),
+ blanks: countBlankLineNodes(c2.fragment),
+ diskFinal: readTestDoc(contentDir, docName),
+ };
+ diag('RESTART-CLEAN', result);
+ expect(diskAfterShutdown, 'clean shutdown preserves bytes').toBe(withRun);
+ expect(c2.ytext.toString(), 'reload restores bytes').toBe(withRun);
+ expect(serializeFragment(c2.fragment), 'reload re-derives the run into the fragment').toBe(
+ withRun,
+ );
+ expect(countBlankLineNodes(c2.fragment)).toBe(2);
+ expect(readTestDoc(contentDir, docName), 'no creep after a reload store cycle').toBe(
+ withRun,
+ );
+ } finally {
+ detachClient(c2);
+ }
} finally {
- detachClient(c2);
await s2.cleanup();
}
}, 90_000);
test('RESTART-CRASH: a flushed edge run survives a crash-simulated fast restart', async () => {
- let restartable = await createRestartableServer({ keepContentDir: true });
+ const contentDir = makeTempDir('ok-restartable-');
+ writeFileSync(join(contentDir, 'test-doc.md'), '', 'utf8');
+ let restartable = await createRestartableServer({ contentDir, keepContentDir: true });
try {
const docName = `qa-crash-${crypto.randomUUID()}`;
await agentWriteMd(restartable.port, 'Above.\n\nBelow.\n', { docName, position: 'replace' });
- const c1 = await createTestClient(restartable.port, docName, { skipInvariantWatcher: true });
- await pollUntil(() => c1.ytext.toString() === 'Above.\n\nBelow.\n', 10_000);
- c1.doc.transact(() => {
- c1.ytext.insert(c1.ytext.length, '\n\n');
- });
const withRun = 'Above.\n\nBelow.\n\n\n';
- expect(
- await settle(() => readTestDoc(restartable.contentDir, docName) === withRun, 15_000),
- 'flushed pre-crash',
- ).toBe(true);
- detachClient(c1);
+ const c1 = await createTestClient(restartable.port, docName, { skipInvariantWatcher: true });
+ try {
+ await pollUntil(() => c1.ytext.toString() === 'Above.\n\nBelow.\n', 10_000);
+ c1.doc.transact(() => {
+ c1.ytext.insert(c1.ytext.length, '\n\n');
+ });
+ expect(
+ await settle(() => readTestDoc(restartable.contentDir, docName) === withRun, 15_000),
+ 'flushed pre-crash',
+ ).toBe(true);
+ } finally {
+ detachClient(c1);
+ }
restartable = await restartable.killAndRestartOnSamePort({ downtimeMs: 5000 });
const c2 = await createTestClient(restartable.port, docName, { skipInvariantWatcher: true });
@@ -310,12 +335,13 @@ describe('defer-guard innocence under the honest early-exit', () => {
test('C17: a pending WYSIWYG paragraph and a concurrent source keystroke both survive', async () => {
const server = await createTestServer();
const docName = `qa-c17-${crypto.randomUUID()}`;
- const clients = await createTestClients(server.port, {
- count: 2,
- docName,
- perClientOptions: { skipInvariantWatcher: true },
- });
+ let clients: TestClient[] = [];
try {
+ clients = await createTestClients(server.port, {
+ count: 2,
+ docName,
+ perClientOptions: { skipInvariantWatcher: true },
+ });
const seed = 'Alpha.\n\nOmega.\n';
await agentWriteMd(server.port, seed, { docName, position: 'replace' });
await pollUntil(() => clients.every((c) => c.ytext.toString() === seed), 10_000);
@@ -350,8 +376,9 @@ describe('defer-guard innocence under the honest early-exit', () => {
true,
);
} finally {
- for (const c of clients) await c.cleanup();
- await server.cleanup();
+ await runTeardownPhases(...clients.map((client) => () => client.cleanup()), () =>
+ server.cleanup(),
+ );
}
}, 30_000);
});
diff --git a/packages/app/tests/temp-dir.test-helper.ts b/packages/app/tests/temp-dir.test-helper.ts
index 6e8d24974..c6b8125f9 100644
--- a/packages/app/tests/temp-dir.test-helper.ts
+++ b/packages/app/tests/temp-dir.test-helper.ts
@@ -1,15 +1 @@
-import { mkdtemp, rm } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-
-export async function withTempDir<T>(
- prefix: string,
- fn: (dir: string) => T | Promise<T>,
-): Promise<T> {
- const dir = await mkdtemp(join(tmpdir(), prefix));
- try {
- return await fn(dir);
- } finally {
- await rm(dir, { recursive: true, force: true });
- }
-}
+export { withTempDir } from '../../../test-support/temp-dir.test-helper.ts';
diff --git a/packages/cli/src/commands/migrate.test.ts b/packages/cli/src/commands/migrate.test.ts
index eb3c7e101..b5608dd59 100644
--- a/packages/cli/src/commands/migrate.test.ts
+++ b/packages/cli/src/commands/migrate.test.ts
@@ -1,7 +1,14 @@
-import { afterEach, describe, expect, test } from 'vitest';
-import { makeTree } from './migrate/notion/mktree.test-helper.ts';
+import { afterAll, afterEach, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../../test-support/temp-dir.test-helper.ts';
+import { makeTree as populateTree } from './migrate/notion/mktree.test-helper.ts';
import { migrateCommand } from './migrate.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
+function makeTree(files: Parameters<typeof populateTree>[1]): string {
+ return populateTree(makeTempDir('ok-migrate-'), files);
+}
+
const ID = '30545f35b5ad80a38049d283dae66763';
const R1 = '11111111111111111111111111111111';
const R2 = '22222222222222222222222222222222';
diff --git a/packages/cli/src/commands/migrate/notion/detect.test.ts b/packages/cli/src/commands/migrate/notion/detect.test.ts
index b6f18579e..d7a20a0b2 100644
--- a/packages/cli/src/commands/migrate/notion/detect.test.ts
+++ b/packages/cli/src/commands/migrate/notion/detect.test.ts
@@ -1,6 +1,13 @@
-import { describe, expect, test } from 'vitest';
+import { afterAll, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../../../../test-support/temp-dir.test-helper.ts';
import { isNotionExport } from './detect.ts';
-import { makeTree } from './mktree.test-helper.ts';
+import { makeTree as populateTree } from './mktree.test-helper.ts';
+
+const makeTempDir = createTempDirFactory(afterAll);
+
+function makeTree(files: Parameters<typeof populateTree>[1]): string {
+ return populateTree(makeTempDir('ok-migrate-'), files);
+}
const ID = '2a145f35b5ad808e9200ff850d964d8f';
diff --git a/packages/cli/src/commands/migrate/notion/fs-walk.test.ts b/packages/cli/src/commands/migrate/notion/fs-walk.test.ts
index d53f52481..9e73d7af5 100644
--- a/packages/cli/src/commands/migrate/notion/fs-walk.test.ts
+++ b/packages/cli/src/commands/migrate/notion/fs-walk.test.ts
@@ -1,8 +1,15 @@
import { symlinkSync } from 'node:fs';
import { basename, join } from 'node:path';
-import { describe, expect, test } from 'vitest';
+import { afterAll, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../../../../test-support/temp-dir.test-helper.ts';
import { walkFiles } from './fs-walk.ts';
-import { makeTree } from './mktree.test-helper.ts';
+import { makeTree as populateTree } from './mktree.test-helper.ts';
+
+const makeTempDir = createTempDirFactory(afterAll);
+
+function makeTree(files: Parameters<typeof populateTree>[1]): string {
+ return populateTree(makeTempDir('ok-migrate-'), files);
+}
describe('walkFiles', () => {
test('lists files recursively', () => {
diff --git a/packages/cli/src/commands/migrate/notion/mktree.test-helper.ts b/packages/cli/src/commands/migrate/notion/mktree.test-helper.ts
index daa2de6e8..a0f2bc6ad 100644
--- a/packages/cli/src/commands/migrate/notion/mktree.test-helper.ts
+++ b/packages/cli/src/commands/migrate/notion/mktree.test-helper.ts
@@ -1,9 +1,7 @@
-import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
-export function makeTree(files: Record<string, string | Uint8Array>): string {
- const root = mkdtempSync(join(tmpdir(), 'ok-migrate-'));
+export function makeTree(root: string, files: Record<string, string | Uint8Array>): string {
for (const [rel, content] of Object.entries(files)) {
const full = join(root, rel);
mkdirSync(dirname(full), { recursive: true });
diff --git a/packages/cli/src/commands/migrate/notion/plan.test.ts b/packages/cli/src/commands/migrate/notion/plan.test.ts
index 2c3237934..4a35bdc38 100644
--- a/packages/cli/src/commands/migrate/notion/plan.test.ts
+++ b/packages/cli/src/commands/migrate/notion/plan.test.ts
@@ -1,9 +1,16 @@
import { readFileSync } from 'node:fs';
-import { describe, expect, test } from 'vitest';
+import { afterAll, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../../../../test-support/temp-dir.test-helper.ts';
import { walkFiles } from './fs-walk.ts';
-import { makeTree, read } from './mktree.test-helper.ts';
+import { makeTree as populateTree, read } from './mktree.test-helper.ts';
import { applyPlan, buildPlan } from './plan.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
+function makeTree(files: Parameters<typeof populateTree>[1]): string {
+ return populateTree(makeTempDir('ok-migrate-'), files);
+}
+
const PNG =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';
const ID = '2a145f35b5ad808e9200ff850d964d8f';
diff --git a/packages/core/src/config/inspect-config-paths.test.ts b/packages/core/src/config/inspect-config-paths.test.ts
index ece61c56e..22ec3f8be 100644
--- a/packages/core/src/config/inspect-config-paths.test.ts
+++ b/packages/core/src/config/inspect-config-paths.test.ts
@@ -1,12 +1,14 @@
-import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
+import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
-import { describe, expect, test } from 'vitest';
+import { afterAll, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../../test-support/temp-dir.test-helper.ts';
import { inspectConfigPaths } from './inspect-config-paths.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
function makeTempProject(): { cwd: string; home: string } {
- const cwd = mkdtempSync(join(tmpdir(), 'ok-inspect-cwd-'));
- const home = mkdtempSync(join(tmpdir(), 'ok-inspect-home-'));
+ const cwd = makeTempDir('ok-inspect-cwd-');
+ const home = makeTempDir('ok-inspect-home-');
mkdirSync(join(cwd, '.ok'), { recursive: true });
mkdirSync(join(home, '.ok'), { recursive: true });
return { cwd, home };
diff --git a/packages/core/tests/perf/regression-gate.test.ts b/packages/core/tests/perf/regression-gate.test.ts
index 962d3fb0e..c82ca57c1 100644
--- a/packages/core/tests/perf/regression-gate.test.ts
+++ b/packages/core/tests/perf/regression-gate.test.ts
@@ -1,8 +1,8 @@
import { spawnSync } from 'node:child_process';
-import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
+import { readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
-import { describe, expect, test } from 'vitest';
+import { afterAll, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../../test-support/temp-dir.test-helper.ts';
import { withForcedGc } from './gc.ts';
import {
ACCEPT_MISMATCH_FLAG,
@@ -27,6 +27,13 @@ import {
resultsStalenessFailure,
} from './run-regression-gate.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
+function comparatorEnv(): NodeJS.ProcessEnv {
+ const temporary = makeTempDir('ok-perf-cli-');
+ return { ...process.env, TMPDIR: temporary, TMP: temporary, TEMP: temporary };
+}
+
function makeBaseline(overrides: Partial<Baseline> = {}): Baseline {
return {
schemaVersion: 2,
@@ -268,7 +275,7 @@ describe('evaluateRegression (R4 synthetic gate)', () => {
describe('loadBaseline / loadFreshResults finite-value validation', () => {
function writeTmp(name: string, data: unknown): string {
- const dir = mkdtempSync(join(tmpdir(), 'regression-gate-load-'));
+ const dir = makeTempDir('regression-gate-load-');
const path = join(dir, name);
writeFileSync(path, JSON.stringify(data));
return path;
@@ -469,7 +476,7 @@ describe('toolchain provenance warning', () => {
});
test('RED: a schemaVersion 1 baseline is rejected, because `toolchain` meant something else there', () => {
- const dir = mkdtempSync(join(tmpdir(), 'perf-baseline-schema-'));
+ const dir = makeTempDir('perf-baseline-schema-');
const path = join(dir, 'baseline.json');
const legacy = { ...makeBaseline(), schemaVersion: 1 };
writeFileSync(path, JSON.stringify(legacy));
@@ -477,7 +484,7 @@ describe('toolchain provenance warning', () => {
});
test('RED: targetToolchain without capturedUnder is rejected as unrecorded provenance', () => {
- const dir = mkdtempSync(join(tmpdir(), 'perf-baseline-schema-'));
+ const dir = makeTempDir('perf-baseline-schema-');
const path = join(dir, 'baseline.json');
const { capturedUnder: _dropped, ...noProvenance } = makeBaseline();
writeFileSync(
@@ -491,7 +498,7 @@ describe('toolchain provenance warning', () => {
});
test('RED: the version-1 `toolchain` spelling under schemaVersion 2 is rejected, not silently accepted', () => {
- const dir = mkdtempSync(join(tmpdir(), 'perf-baseline-schema-'));
+ const dir = makeTempDir('perf-baseline-schema-');
const path = join(dir, 'baseline.json');
const { capturedUnder, ...rest } = makeBaseline();
writeFileSync(path, JSON.stringify({ ...rest, toolchain: capturedUnder }));
@@ -500,14 +507,14 @@ describe('toolchain provenance warning', () => {
});
test('RED: capturedUnder null is rejected the same way absence is', () => {
- const dir = mkdtempSync(join(tmpdir(), 'perf-baseline-schema-'));
+ const dir = makeTempDir('perf-baseline-schema-');
const path = join(dir, 'baseline.json');
writeFileSync(path, JSON.stringify({ ...makeBaseline(), capturedUnder: null }));
expect(() => loadBaseline(path)).toThrow(/capturedUnder must be an object declaring runtime/);
});
test('RED: a baseline with no provenance at all is rejected, so no run can be silently comparable', () => {
- const dir = mkdtempSync(join(tmpdir(), 'perf-baseline-schema-'));
+ const dir = makeTempDir('perf-baseline-schema-');
const path = join(dir, 'baseline.json');
const { capturedUnder: _c, targetToolchain: _t, ...stripped } = makeBaseline();
writeFileSync(path, JSON.stringify(stripped));
@@ -523,7 +530,7 @@ describe('toolchain provenance warning', () => {
['an object whose fields are empty strings', { runtime: '', testRunner: '' }],
] as const) {
test(`RED: capturedUnder as ${label} is rejected, not carried through as silent provenance`, () => {
- const dir = mkdtempSync(join(tmpdir(), 'perf-baseline-schema-'));
+ const dir = makeTempDir('perf-baseline-schema-');
const path = join(dir, 'baseline.json');
writeFileSync(path, JSON.stringify({ ...makeBaseline(), capturedUnder: value }));
expect(() => loadBaseline(path)).toThrow(/capturedUnder must be an object declaring runtime/);
@@ -531,7 +538,7 @@ describe('toolchain provenance warning', () => {
}
test('RED: a results file with no toolchain is rejected, so a foreign capture cannot compare silently', () => {
- const dir = mkdtempSync(join(tmpdir(), 'perf-fresh-schema-'));
+ const dir = makeTempDir('perf-fresh-schema-');
const path = join(dir, 'results.json');
const { toolchain: _dropped, ...bare } = makeFresh();
writeFileSync(path, JSON.stringify(bare));
@@ -539,7 +546,7 @@ describe('toolchain provenance warning', () => {
});
test('RED: a version-1 results file is rejected on the VERSION, not on a field version 1 never had', () => {
- const dir = mkdtempSync(join(tmpdir(), 'perf-fresh-schema-'));
+ const dir = makeTempDir('perf-fresh-schema-');
const path = join(dir, 'results.json');
const { toolchain: _dropped, ...preToolchain } = makeFresh();
writeFileSync(path, JSON.stringify({ ...preToolchain, schemaVersion: 1 }));
@@ -549,7 +556,7 @@ describe('toolchain provenance warning', () => {
});
test('a version-2 results file carrying toolchain loads, so the bump is not a blanket rejection', () => {
- const dir = mkdtempSync(join(tmpdir(), 'perf-fresh-schema-'));
+ const dir = makeTempDir('perf-fresh-schema-');
const path = join(dir, 'results.json');
writeFileSync(path, JSON.stringify(makeFresh()));
const loaded = loadFreshResults(path);
@@ -558,7 +565,7 @@ describe('toolchain provenance warning', () => {
});
test('RED: a version-1 results file that already declares a toolchain is told to renumber, not to re-capture', () => {
- const dir = mkdtempSync(join(tmpdir(), 'perf-fresh-schema-'));
+ const dir = makeTempDir('perf-fresh-schema-');
const path = join(dir, 'results.json');
writeFileSync(path, JSON.stringify({ ...makeFresh(), schemaVersion: 1 }));
expect(() => loadFreshResults(path)).toThrow(/results\.json schemaVersion must be 2/);
@@ -574,7 +581,7 @@ describe('toolchain provenance warning', () => {
['an object whose fields are empty strings', { runtime: '', testRunner: '' }],
] as const) {
test(`RED: a version-1 results file whose toolchain is ${label} is told to re-capture, not to renumber`, () => {
- const dir = mkdtempSync(join(tmpdir(), 'perf-fresh-schema-'));
+ const dir = makeTempDir('perf-fresh-schema-');
const path = join(dir, 'results.json');
writeFileSync(path, JSON.stringify({ ...makeFresh(), schemaVersion: 1, toolchain: value }));
expect(() => loadFreshResults(path)).toThrow(/declares no `toolchain`/);
@@ -589,7 +596,7 @@ describe('toolchain provenance warning', () => {
});
test('RED: a results file with no methodology block is rejected', () => {
- const dir = mkdtempSync(join(tmpdir(), 'perf-fresh-schema-'));
+ const dir = makeTempDir('perf-fresh-schema-');
const path = join(dir, 'results.json');
const { methodology: _dropped, ...bare } = makeFresh();
writeFileSync(path, JSON.stringify(bare));
@@ -602,7 +609,7 @@ describe('toolchain provenance warning', () => {
['a non-finite varianceMultiplier', { floorPct: 0.1, varianceMultiplier: Number.NaN }],
] as const) {
test(`RED: threshold with ${label} is rejected rather than computing an NaN allowance`, () => {
- const dir = mkdtempSync(join(tmpdir(), 'perf-baseline-threshold-'));
+ const dir = makeTempDir('perf-baseline-threshold-');
const path = join(dir, 'baseline.json');
writeFileSync(path, JSON.stringify({ ...makeBaseline(), threshold }));
expect(() => loadBaseline(path)).toThrow(
@@ -618,7 +625,7 @@ describe('toolchain provenance warning', () => {
});
test('RED: capturedUnder equal to targetToolchain is rejected as a finished re-baseline', () => {
- const dir = mkdtempSync(join(tmpdir(), 'perf-baseline-schema-'));
+ const dir = makeTempDir('perf-baseline-schema-');
const path = join(dir, 'baseline.json');
const same = { runtime: '[email protected]', testRunner: '[email protected]' };
writeFileSync(
@@ -629,7 +636,7 @@ describe('toolchain provenance warning', () => {
});
test('NEGATIVE: capturedUnder alone, and capturedUnder differing from targetToolchain, both load', () => {
- const dir = mkdtempSync(join(tmpdir(), 'perf-baseline-schema-'));
+ const dir = makeTempDir('perf-baseline-schema-');
const soloPath = join(dir, 'solo.json');
writeFileSync(
soloPath,
@@ -737,7 +744,7 @@ describe('the standalone comparator CLI surfaces methodology warnings and refuse
script: string,
extraArgs: string[] = [],
): { status: number | null; stdout: string; stderr: string } {
- const dir = mkdtempSync(join(tmpdir(), 'perf-entrypoint-'));
+ const dir = makeTempDir('perf-entrypoint-');
const freshPath = join(dir, 'fresh.json');
writeFileSync(
freshPath,
@@ -746,7 +753,7 @@ describe('the standalone comparator CLI surfaces methodology warnings and refuse
const result = spawnSync(
'pnpm',
['exec', 'tsx', join(PERF_DIR, script), COMMITTED_BASELINE_PATH, freshPath, ...extraArgs],
- { cwd: join(PERF_DIR, '..', '..'), encoding: 'utf8', timeout: 30_000 },
+ { cwd: join(PERF_DIR, '..', '..'), encoding: 'utf8', env: comparatorEnv(), timeout: 30_000 },
);
if (result.error) {
throw new Error(
@@ -763,7 +770,7 @@ describe('the standalone comparator CLI surfaces methodology warnings and refuse
}, 60_000);
test('RED: an unreadable baseline exits EXIT_DATA with the validator message, not a stack on 1', () => {
- const dir = mkdtempSync(join(tmpdir(), 'perf-baddata-'));
+ const dir = makeTempDir('perf-baddata-');
const badPath = join(dir, 'baseline.json');
writeFileSync(badPath, JSON.stringify({ ...makeBaseline(), capturedUnder: {} }));
const freshPath = join(dir, 'fresh.json');
@@ -774,7 +781,7 @@ describe('the standalone comparator CLI surfaces methodology warnings and refuse
const result = spawnSync(
'pnpm',
['exec', 'tsx', join(PERF_DIR, 'regression-gate.ts'), badPath, freshPath],
- { cwd: join(PERF_DIR, '..', '..'), encoding: 'utf8', timeout: 30_000 },
+ { cwd: join(PERF_DIR, '..', '..'), encoding: 'utf8', env: comparatorEnv(), timeout: 30_000 },
);
expect(result.status).toBe(EXIT_DATA);
expect(result.stderr).toContain('capturedUnder must be an object declaring runtime');
@@ -785,14 +792,14 @@ describe('the standalone comparator CLI surfaces methodology warnings and refuse
const result = spawnSync(
'pnpm',
['exec', 'tsx', join(PERF_DIR, 'regression-gate.ts'), baselinePath, freshPath],
- { cwd: join(PERF_DIR, '..', '..'), encoding: 'utf8', timeout: 30_000 },
+ { cwd: join(PERF_DIR, '..', '..'), encoding: 'utf8', env: comparatorEnv(), timeout: 30_000 },
);
if (result.error) throw result.error;
return result;
}
function badInputFixtures() {
- const dir = mkdtempSync(join(tmpdir(), 'perf-badinput-'));
+ const dir = makeTempDir('perf-badinput-');
const freshPath = join(dir, 'fresh.json');
writeFileSync(
freshPath,
@@ -860,7 +867,7 @@ describe('the standalone comparator CLI surfaces methodology warnings and refuse
}, 60_000);
test('NEGATIVE: a comparable run needs no escape hatch', () => {
- const dir = mkdtempSync(join(tmpdir(), 'perf-comparable-'));
+ const dir = makeTempDir('perf-comparable-');
const baseline = loadBaseline(COMMITTED_BASELINE_PATH);
const baselinePath = join(dir, 'baseline.json');
const freshPath = join(dir, 'fresh.json');
@@ -876,7 +883,7 @@ describe('the standalone comparator CLI surfaces methodology warnings and refuse
const result = spawnSync(
'pnpm',
['exec', 'tsx', join(PERF_DIR, 'regression-gate.ts'), baselinePath, freshPath],
- { cwd: join(PERF_DIR, '..', '..'), encoding: 'utf8', timeout: 30_000 },
+ { cwd: join(PERF_DIR, '..', '..'), encoding: 'utf8', env: comparatorEnv(), timeout: 30_000 },
);
expect(result.stderr).not.toContain('INCONCLUSIVE');
expect(result.status).toBe(0);
@@ -936,7 +943,7 @@ describe('p50 and p95 are recorded alongside p99', () => {
});
test('a baseline recording a non-finite p50 is rejected at load', () => {
- const dir = mkdtempSync(join(tmpdir(), 'regression-gate-percentiles-'));
+ const dir = makeTempDir('regression-gate-percentiles-');
const path = join(dir, 'baseline.json');
const baseline = makeBaseline();
baseline.results[0].parseMs.p50 = Number.NaN;
diff --git a/packages/desktop/src/main/consent-dialog.test.ts b/packages/desktop/src/main/consent-dialog.test.ts
index 0f9b5f079..92be0e246 100644
--- a/packages/desktop/src/main/consent-dialog.test.ts
+++ b/packages/desktop/src/main/consent-dialog.test.ts
@@ -1,7 +1,7 @@
-import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
+import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
-import { describe, expect, test } from 'vitest';
+import { afterAll, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../../test-support/temp-dir.test-helper.ts';
import type { OnboardingConfirmRequest, OnboardingShowPayload } from '../shared/ipc-channels.ts';
import {
type ConsentIpcMainLike,
@@ -11,6 +11,8 @@ import {
runProbe,
} from './consent-dialog.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
interface IpcStub extends ConsentIpcMainLike {
handlers: Map<string, (event: unknown, ...args: unknown[]) => unknown | Promise<unknown>>;
invoke(channel: string, senderId: number, ...args: unknown[]): Promise<unknown>;
@@ -352,7 +354,7 @@ describe('requestUserConsent — cancel', () => {
describe('runProbe', () => {
test('returns ok with count + sample for a real tmp-dir fixture', async () => {
- const tmp = mkdtempSync(join(tmpdir(), 'ok-probe-'));
+ const tmp = makeTempDir('ok-probe-');
writeFileSync(join(tmp, 'a.md'), '# a');
writeFileSync(join(tmp, 'b.md'), '# b');
const recordedPreview: PreviewContentFn = ({ sampleCap }) => ({
@@ -381,7 +383,7 @@ describe('runProbe', () => {
});
test('small fixture is not truncated', async () => {
- const tmp = mkdtempSync(join(tmpdir(), 'ok-probe-small-'));
+ const tmp = makeTempDir('ok-probe-small-');
writeFileSync(join(tmp, 'one.md'), 'x');
const result = await runProbe(fakePreview, tmp, { contentDir: '.' });
expect(result.ok).toBe(true);
@@ -389,7 +391,7 @@ describe('runProbe', () => {
});
test('throwing previewContent surfaces ok:false', async () => {
- const tmp = mkdtempSync(join(tmpdir(), 'ok-probe-throw-'));
+ const tmp = makeTempDir('ok-probe-throw-');
writeFileSync(join(tmp, 'a.md'), '# a');
const throwingPreview: PreviewContentFn = () => {
throw new Error('synthetic boom');
@@ -429,7 +431,7 @@ describe('runProbe', () => {
});
test('subdirectory contentDir resolves correctly', async () => {
- const tmp = mkdtempSync(join(tmpdir(), 'ok-probe-subdir-'));
+ const tmp = makeTempDir('ok-probe-subdir-');
mkdirSync(join(tmp, 'docs'));
writeFileSync(join(tmp, 'docs', 'a.md'), '# a');
let receivedContentDir = '';
@@ -447,7 +449,7 @@ describe('runProbe', () => {
describe('requestUserConsent — probe-content pins to captured projectDir', () => {
test('IPC probe-content uses captured payload.projectDir; renderer-supplied projectDir is ignored', async () => {
- const tmp = mkdtempSync(join(tmpdir(), 'ok-probe-pin-'));
+ const tmp = makeTempDir('ok-probe-pin-');
writeFileSync(join(tmp, 'a.md'), '# a');
let capturedProjectDir = '';
let capturedContentDir = '';
diff --git a/packages/desktop/src/main/path-install.test.ts b/packages/desktop/src/main/path-install.test.ts
index 56c52e47e..3aaa19abb 100644
--- a/packages/desktop/src/main/path-install.test.ts
+++ b/packages/desktop/src/main/path-install.test.ts
@@ -2,16 +2,15 @@ import {
existsSync,
lstatSync,
mkdirSync,
- mkdtempSync,
readFileSync,
readlinkSync,
symlinkSync,
unlinkSync,
writeFileSync,
} from 'node:fs';
-import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
-import { describe, expect, test, vi } from 'vitest';
+import { afterAll, describe, expect, test, vi } from 'vitest';
+import { createTempDirFactory } from '../../../../test-support/temp-dir.test-helper.ts';
import { okManagedBinDirs } from '../shared/ok-child-env.ts';
import {
computePathInstallDescriptor,
@@ -23,6 +22,8 @@ import {
removePathShimFromRcFiles,
} from './path-install.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
const EXE = '/Applications/OpenKnowledge.app/Contents/MacOS/OpenKnowledge';
const WRAPPER = '/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh';
@@ -30,7 +31,7 @@ const GRANTED = { status: 'granted', at: '2026-07-02T00:00:00.000Z' } as const;
const DECLINED = { status: 'declined', at: '2026-07-02T00:00:00.000Z' } as const;
function home() {
- return mkdtempSync(join(tmpdir(), 'ok-path-install-'));
+ return makeTempDir('ok-path-install-');
}
type EnsureOpts = Parameters<typeof ensureCliOnPath>[0];
diff --git a/packages/desktop/tests/smoke/_helpers/launch-readiness.test.ts b/packages/desktop/tests/smoke/_helpers/launch-readiness.test.ts
index e1615cf4c..25b626601 100644
--- a/packages/desktop/tests/smoke/_helpers/launch-readiness.test.ts
+++ b/packages/desktop/tests/smoke/_helpers/launch-readiness.test.ts
@@ -4,14 +4,13 @@ import {
appendFileSync,
existsSync,
mkdirSync,
- mkdtempSync,
readFileSync,
rmSync,
writeFileSync,
} from 'node:fs';
-import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { describe, expect, it } from 'vitest';
+import { afterAll, describe, expect, it } from 'vitest';
+import { createTempDirFactory } from '../../../../../test-support/temp-dir.test-helper.ts';
import type { WaterfallPhase } from '../../../src/main/startup-waterfall.ts';
import {
BOOT_HEARTBEAT_ABANDONED_SUFFIX,
@@ -88,12 +87,14 @@ import {
utilityForkWhoseFirstBeatLandsOnTheLastStagePoll,
} from './readiness-reach.test-helper.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
function markLine(phase: WaterfallPhase, elapsedMs: number, time: string): string {
return JSON.stringify({ time, ...startupMarkLine(phase, elapsedMs) });
}
function seedHome(lines: string[] = []): string {
- const home = mkdtempSync(join(tmpdir(), 'ok-readiness-'));
+ const home = makeTempDir('ok-readiness-');
if (lines.length > 0) {
const dir = bootLogDirFor(home);
mkdirSync(dir, { recursive: true });
@@ -490,7 +491,7 @@ describe('waitForWindowByMode', () => {
});
it('handles a page rejection that arrives after the cap', () => {
- const scriptDir = mkdtempSync(join(tmpdir(), 'ok-window-readiness-strict-'));
+ const scriptDir = makeTempDir('ok-window-readiness-strict-');
const script = join(scriptDir, 'late-rejection.mjs');
const home = seedHome();
try {
@@ -2685,7 +2686,7 @@ describe('the cap bounds the wait itself, not only the gaps between polls', () =
});
it('swallows a probe rejection that arrives after the cap, so no worker dies of it', () => {
- const script = join(mkdtempSync(join(tmpdir(), 'ok-readiness-strict-')), 'late-rejection.mjs');
+ const script = join(makeTempDir('ok-readiness-strict-'), 'late-rejection.mjs');
writeFileSync(
script,
[
diff --git a/packages/desktop/tests/unit/ok-wrapper.test.ts b/packages/desktop/tests/unit/ok-wrapper.test.ts
index 7d8cac9ec..73fc03fa2 100644
--- a/packages/desktop/tests/unit/ok-wrapper.test.ts
+++ b/packages/desktop/tests/unit/ok-wrapper.test.ts
@@ -1,7 +1,10 @@
import { spawnSync } from 'node:child_process';
import { accessSync, constants, readFileSync } from 'node:fs';
import { join } from 'node:path';
-import { describe, expect, test } from 'vitest';
+import { afterAll, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../../test-support/temp-dir.test-helper.ts';
+
+const makeTempDir = createTempDirFactory(afterAll);
const WRAPPER = join(import.meta.dir, '..', '..', 'resources', 'cli', 'bin', 'ok.sh');
@@ -27,9 +30,8 @@ describe('ok.sh wrapper', () => {
});
test('missing Electron binary but present CLI also diagnoses missing-bundle', async () => {
- const { mkdtempSync, mkdirSync, writeFileSync } = await import('node:fs');
- const { tmpdir } = await import('node:os');
- const fixture = mkdtempSync(join(tmpdir(), 'ok-wrapper-'));
+ const { mkdirSync, writeFileSync } = await import('node:fs');
+ const fixture = makeTempDir('ok-wrapper-');
const appRoot = join(fixture, 'OpenKnowledge.app');
mkdirSync(join(appRoot, 'Contents', 'Resources', 'cli', 'dist'), { recursive: true });
writeFileSync(join(appRoot, 'Contents', 'Resources', 'cli', 'dist', 'cli.mjs'), '// stub');
@@ -43,9 +45,8 @@ describe('ok.sh wrapper', () => {
});
test('Pass 0 Major #10: empty APP_PATH branch emits structured stderr + exit 69', async () => {
- const { mkdtempSync, copyFileSync, chmodSync } = await import('node:fs');
- const { tmpdir } = await import('node:os');
- const dir = mkdtempSync(join(tmpdir(), 'ok-wrapper-empty-'));
+ const { copyFileSync, chmodSync } = await import('node:fs');
+ const dir = makeTempDir('ok-wrapper-empty-');
const wrapperCopy = join(dir, 'ok.sh');
copyFileSync(WRAPPER, wrapperCopy);
chmodSync(wrapperCopy, 0o755);
diff --git a/packages/server/src/conflict-authority.test-helper.ts b/packages/server/src/conflict-authority.test-helper.ts
index 49aa88c5b..42b3c9483 100644
--- a/packages/server/src/conflict-authority.test-helper.ts
+++ b/packages/server/src/conflict-authority.test-helper.ts
@@ -1,6 +1,3 @@
-import { mkdtempSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
import { ConflictAuthority } from './conflict-authority.ts';
export const RECONCILE_TEST_CONFLICTS: Pick<
@@ -28,7 +25,3 @@ export function createTestConflictAuthority(
},
});
}
-
-export function createTestConflictAuthorityInTmpDir(prefix: string): ConflictAuthority {
- return createTestConflictAuthority(mkdtempSync(join(tmpdir(), prefix)));
-}
diff --git a/packages/server/src/content/generated-index-git-attributes.test.ts b/packages/server/src/content/generated-index-git-attributes.test.ts
index a69152121..357462eb6 100644
--- a/packages/server/src/content/generated-index-git-attributes.test.ts
+++ b/packages/server/src/content/generated-index-git-attributes.test.ts
@@ -2,25 +2,26 @@ import { execFileSync } from 'node:child_process';
import {
existsSync,
mkdirSync,
- mkdtempSync,
readFileSync,
symlinkSync,
unlinkSync,
writeFileSync,
} from 'node:fs';
-import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { afterEach, describe, expect, test, vi } from 'vitest';
+import { afterAll, afterEach, describe, expect, test, vi } from 'vitest';
+import { createTempDirFactory } from '../../../../test-support/temp-dir.test-helper.ts';
import { getLogger } from '../logger.ts';
import {
inspectGeneratedIndexGitAttributes,
updateGeneratedIndexGitAttributes,
} from './generated-index-git-attributes.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
afterEach(() => vi.restoreAllMocks());
function makeProject(contentSubdir = '.'): { projectDir: string; contentDir: string } {
- const projectDir = mkdtempSync(join(tmpdir(), 'ok-generated-index-attrs-'));
+ const projectDir = makeTempDir('ok-generated-index-attrs-');
execFileSync('git', ['init', '-q'], { cwd: projectDir });
if (contentSubdir !== '.') mkdirSync(join(projectDir, contentSubdir), { recursive: true });
return {
@@ -33,7 +34,7 @@ const generatedDocNames = ['index', 'guides/index'];
describe('generated-index git attributes', () => {
test('is not applicable outside a Git working tree', async () => {
- const projectDir = mkdtempSync(join(tmpdir(), 'ok-generated-index-no-git-'));
+ const projectDir = makeTempDir('ok-generated-index-no-git-');
const result = await updateGeneratedIndexGitAttributes({
projectDir,
contentDir: projectDir,
diff --git a/packages/server/src/copy-dir.test.ts b/packages/server/src/copy-dir.test.ts
index 96d5915c1..37bba0ac2 100644
--- a/packages/server/src/copy-dir.test.ts
+++ b/packages/server/src/copy-dir.test.ts
@@ -1,11 +1,13 @@
-import { mkdirSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
+import { mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
-import { describe, expect, test } from 'vitest';
+import { afterAll, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../test-support/temp-dir.test-helper.ts';
import { copyDirSync } from './copy-dir.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
function tmpDir(): string {
- return mkdtempSync(join(tmpdir(), 'ok-copy-dir-'));
+ return makeTempDir('ok-copy-dir-');
}
function seedSource(): string {
diff --git a/packages/server/src/http/file-ops-routes.test.ts b/packages/server/src/http/file-ops-routes.test.ts
index 4022d0f34..eec5c824a 100644
--- a/packages/server/src/http/file-ops-routes.test.ts
+++ b/packages/server/src/http/file-ops-routes.test.ts
@@ -1,8 +1,9 @@
import type { IncomingMessage, ServerResponse } from 'node:http';
import { Readable } from 'node:stream';
-import { describe, expect, test } from 'vitest';
+import { afterAll, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../../test-support/temp-dir.test-helper.ts';
import { SymlinkEscapeError } from '../apply-managed-rename.ts';
-import { createTestConflictAuthorityInTmpDir } from '../conflict-authority.test-helper.ts';
+import { createTestConflictAuthority } from '../conflict-authority.test-helper.ts';
import { DocInConflictError } from '../conflict-errors.ts';
import { ContentRootUnavailableError } from '../fs-safety.ts';
import { loggerFactory } from '../logger.ts';
@@ -10,6 +11,8 @@ import type { AssetService } from '../services/assets.ts';
import type { FileOpsService } from '../services/file-ops.ts';
import { createFileOpsRoutes } from './file-ops-routes.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
type Deps = Parameters<typeof createFileOpsRoutes>[0];
function buildGroup(overrides: Partial<Deps> = {}) {
@@ -20,7 +23,7 @@ function buildGroup(overrides: Partial<Deps> = {}) {
getPrincipal: undefined,
contentFilter: undefined,
signalChannel: undefined,
- conflicts: createTestConflictAuthorityInTmpDir('file-ops-routes-authority-'),
+ conflicts: createTestConflictAuthority(makeTempDir('file-ops-routes-authority-')),
flushContributors: undefined,
fileOpsService: {} as FileOpsService,
assetService: {} as AssetService,
diff --git a/packages/server/src/http/sync-routes.test.ts b/packages/server/src/http/sync-routes.test.ts
index f526b0603..e8130e7b3 100644
--- a/packages/server/src/http/sync-routes.test.ts
+++ b/packages/server/src/http/sync-routes.test.ts
@@ -5,19 +5,20 @@ import { join } from 'node:path';
import { Readable } from 'node:stream';
import { Hocuspocus } from '@hocuspocus/server';
import simpleGit from 'simple-git';
-import { describe, expect, test } from 'vitest';
+import { afterAll, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../../test-support/temp-dir.test-helper.ts';
import { makeCaptureRes, makeSyntheticReq } from '../composition-rig.test-helper.ts';
-import {
- createTestConflictAuthority,
- createTestConflictAuthorityInTmpDir,
-} from '../conflict-authority.test-helper.ts';
+import { createTestConflictAuthority } from '../conflict-authority.test-helper.ts';
+import type { ConflictAuthority } from '../conflict-authority.ts';
import { loggerFactory } from '../logger.ts';
import { createSyncRoutes } from './sync-routes.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
const makeAuthority = createTestConflictAuthority;
function emptyAuthority(): ConflictAuthority {
- return createTestConflictAuthorityInTmpDir('sync-routes-authority-');
+ return createTestConflictAuthority(makeTempDir('sync-routes-authority-'));
}
function buildGroup() {
diff --git a/packages/server/src/maintenance-consolidation.test.ts b/packages/server/src/maintenance-consolidation.test.ts
index 24a09d76a..0134d6207 100644
--- a/packages/server/src/maintenance-consolidation.test.ts
+++ b/packages/server/src/maintenance-consolidation.test.ts
@@ -1,14 +1,15 @@
import { mkdirSync, writeFileSync } from 'node:fs';
-import { mkdtemp } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { parseCheckpoint } from '@inkeep/open-knowledge-core/shadow-repo-layout';
import simpleGit from 'simple-git';
-import { beforeEach, describe, expect, test } from 'vitest';
+import { afterAll, beforeEach, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../test-support/temp-dir.test-helper.ts';
import { createMaintenanceCoordinator } from './maintenance-coordinator.ts';
import { commitWip, initShadowRepo, type ShadowHandle, shadowGit } from './shadow-repo.ts';
import { getDocumentHistory } from './timeline-query.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
let tmpDir: string;
let projectRoot: string;
let contentDir: string;
@@ -16,7 +17,7 @@ let shadow: ShadowHandle;
let liveWriters: Set<string>;
beforeEach(async () => {
- tmpDir = await mkdtemp(resolve(tmpdir(), 'ok-consolidate-test-'));
+ tmpDir = makeTempDir('ok-consolidate-test-');
projectRoot = resolve(tmpDir, 'project');
contentDir = resolve(projectRoot, 'content/docs');
mkdirSync(contentDir, { recursive: true });
diff --git a/packages/server/src/mcp/tools/config.test.ts b/packages/server/src/mcp/tools/config.test.ts
index 4e7a5a27f..47e6f5b5e 100644
--- a/packages/server/src/mcp/tools/config.test.ts
+++ b/packages/server/src/mcp/tools/config.test.ts
@@ -1,11 +1,13 @@
-import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
+import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
-import { describe, expect, test } from 'vitest';
+import { afterAll, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../../../test-support/temp-dir.test-helper.ts';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { register } from './config.ts';
import type { ServerInstance } from './shared.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
const BASE_CONFIG: Config = ConfigSchema.parse({
content: { dir: '.' },
appearance: { theme: 'dark' },
@@ -40,7 +42,7 @@ function captureRegistration(cwd: string, configOverride?: Partial<Config>): Too
describe('config tool', () => {
test('returns the full effective merged config when path is omitted', async () => {
- const cwd = mkdtempSync(join(tmpdir(), 'ok-get-config-'));
+ const cwd = makeTempDir('ok-get-config-');
const handler = captureRegistration(cwd);
const result = await handler({});
expect(result.isError).toBeUndefined();
@@ -50,7 +52,7 @@ describe('config tool', () => {
});
test('returns sub-tree when path is provided', async () => {
- const cwd = mkdtempSync(join(tmpdir(), 'ok-get-config-'));
+ const cwd = makeTempDir('ok-get-config-');
const handler = captureRegistration(cwd);
const result = await handler({ key: 'appearance' });
const value = result.structuredContent?.value as { theme: string };
@@ -58,14 +60,14 @@ describe('config tool', () => {
});
test('returns scalar leaf when path resolves to a primitive', async () => {
- const cwd = mkdtempSync(join(tmpdir(), 'ok-get-config-'));
+ const cwd = makeTempDir('ok-get-config-');
const handler = captureRegistration(cwd);
const result = await handler({ key: 'content.dir' });
expect(result.structuredContent?.value).toBe('.');
});
test('returns null + exists:false for a nonexistent path', async () => {
- const cwd = mkdtempSync(join(tmpdir(), 'ok-get-config-'));
+ const cwd = makeTempDir('ok-get-config-');
const handler = captureRegistration(cwd);
const result = await handler({ key: 'nonexistent.leaf' });
expect(result.structuredContent?.value).toBeNull();
@@ -74,14 +76,14 @@ describe('config tool', () => {
});
test('content[0].text is JSON-serialized for agent consumption', async () => {
- const cwd = mkdtempSync(join(tmpdir(), 'ok-get-config-'));
+ const cwd = makeTempDir('ok-get-config-');
const handler = captureRegistration(cwd);
const result = await handler({ key: 'appearance.theme' });
expect(result.content[0]?.text).toBe('"dark"');
});
test('reads any field — no allowlist gating on read', async () => {
- const cwd = mkdtempSync(join(tmpdir(), 'ok-get-config-'));
+ const cwd = makeTempDir('ok-get-config-');
const handler = captureRegistration(cwd);
const result = await handler({ key: 'appearance.theme' });
expect(result.isError).toBeUndefined();
@@ -89,7 +91,7 @@ describe('config tool', () => {
});
test('reflects on-disk config when caller passes a resolver that loads it', async () => {
- const cwd = mkdtempSync(join(tmpdir(), 'ok-get-config-disk-'));
+ const cwd = makeTempDir('ok-get-config-disk-');
mkdirSync(join(cwd, '.ok'), { recursive: true });
writeFileSync(join(cwd, '.ok', 'config.yml'), 'appearance:\n theme: light\n');
const merged: Config = {
diff --git a/packages/server/src/mcp/tools/output-schema-strictness.test.ts b/packages/server/src/mcp/tools/output-schema-strictness.test.ts
index bdc0b28b5..7c4cc9940 100644
--- a/packages/server/src/mcp/tools/output-schema-strictness.test.ts
+++ b/packages/server/src/mcp/tools/output-schema-strictness.test.ts
@@ -1,5 +1,4 @@
-import { mkdirSync, mkdtempSync } from 'node:fs';
-import { tmpdir } from 'node:os';
+import { mkdirSync } from 'node:fs';
import { join } from 'node:path';
import {
AUDIT_EMPTY_SCOPE_WARNING,
@@ -8,7 +7,8 @@ import {
import { normalizeObjectSchema } from '@modelcontextprotocol/sdk/server/zod-compat.js';
import { toJsonSchemaCompat } from '@modelcontextprotocol/sdk/server/zod-json-schema-compat.js';
import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';
-import { afterEach, describe, expect, test, vi } from 'vitest';
+import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest';
+import { createTempDirFactory } from '../../../../../test-support/temp-dir.test-helper.ts';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { register as registerAudit } from './audit.ts';
import { register as registerConfig } from './config.ts';
@@ -21,6 +21,8 @@ import { register as registerPalette } from './palette.ts';
import { register as registerSearch } from './search.ts';
import { AUDIT_WARNING_CAP, type ServerInstance, WARNINGS_FIELD_CONTRACT } from './shared.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
const BASE_CONFIG: Config = ConfigSchema.parse({});
const legacyReLint = (message: string) => `${RE_LINT_FAILED_WARNING_PREFIX}${message}`;
@@ -59,7 +61,7 @@ function captureRegistration<TDeps>(
}
function newProject(): string {
- const cwd = mkdtempSync(join(tmpdir(), 'ok-output-strict-'));
+ const cwd = makeTempDir('ok-output-strict-');
mkdirSync(join(cwd, '.ok'), { recursive: true });
return cwd;
}
@@ -84,7 +86,10 @@ describe('MCP outputSchema strictness — every registerTool+textPlusStructured
return compileOutputSchemaForClient(captured.cfg.outputSchema);
}
- const cwd = newProject();
+ let cwd: string;
+ beforeAll(() => {
+ cwd = newProject();
+ });
const deps = { config: BASE_CONFIG, resolveCwd: async () => cwd };
const depsWithServer = {
config: BASE_CONFIG,
diff --git a/packages/server/src/mcp/tools/registry.test.ts b/packages/server/src/mcp/tools/registry.test.ts
index a80dac901..d3af422e7 100644
--- a/packages/server/src/mcp/tools/registry.test.ts
+++ b/packages/server/src/mcp/tools/registry.test.ts
@@ -1,12 +1,12 @@
-import { mkdtempSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
import { OK_GATED_TOOL_NAMES, OPEN_KNOWLEDGE_MCP_TOOLS } from '@inkeep/open-knowledge-core';
-import { describe, expect, test } from 'vitest';
+import { afterAll, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../../../test-support/temp-dir.test-helper.ts';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { registerAllTools } from './index.ts';
import type { ServerInstance } from './shared.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
const BASE_CONFIG: Config = ConfigSchema.parse({});
const EXPECTED_TOOLS = OPEN_KNOWLEDGE_MCP_TOOLS;
@@ -53,7 +53,7 @@ const RETIRED_TOOL_NAMES = [
function captureRegistered(): string[] {
const names: string[] = [];
- const cwd = mkdtempSync(join(tmpdir(), 'ok-registry-assertion-'));
+ const cwd = makeTempDir('ok-registry-assertion-');
const server = {
registerTool(name: string, _cfg: unknown, _handler: unknown) {
names.push(name);
diff --git a/packages/server/src/mcp/tools/search.test.ts b/packages/server/src/mcp/tools/search.test.ts
index 3ae9a8317..46670f26a 100644
--- a/packages/server/src/mcp/tools/search.test.ts
+++ b/packages/server/src/mcp/tools/search.test.ts
@@ -1,12 +1,12 @@
-import { mkdtempSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { afterAll, afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { createTempDirFactory } from '../../../../../test-support/temp-dir.test-helper.ts';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { bindTestUiServerLock } from './preview-url-test-helpers.ts';
import { DESCRIPTION, register } from './search.ts';
import type { ServerInstance } from './shared.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
const DEFAULT_CONFIG: Config = ConfigSchema.parse({});
interface RegisteredTool {
@@ -681,7 +681,7 @@ describe('search MCP tool — happy path', () => {
describe('search MCP tool — route-only previewUrl + no ui block (PRD-6735)', () => {
test('result rows carry route-only previewUrl; structured output has no ui block', async () => {
- const cwd = mkdtempSync(join(tmpdir(), 'ok-search-preview-'));
+ const cwd = makeTempDir('ok-search-preview-');
bindTestUiServerLock(cwd);
mockFetchOk({
ok: true,
diff --git a/packages/server/src/mcp/tools/tool-schema-ref-free.test.ts b/packages/server/src/mcp/tools/tool-schema-ref-free.test.ts
index 5ede7ce7f..43c328e6a 100644
--- a/packages/server/src/mcp/tools/tool-schema-ref-free.test.ts
+++ b/packages/server/src/mcp/tools/tool-schema-ref-free.test.ts
@@ -1,13 +1,15 @@
-import { mkdirSync, mkdtempSync } from 'node:fs';
-import { tmpdir } from 'node:os';
+import { mkdirSync } from 'node:fs';
import { join } from 'node:path';
import { normalizeObjectSchema } from '@modelcontextprotocol/sdk/server/zod-compat.js';
import { toJsonSchemaCompat } from '@modelcontextprotocol/sdk/server/zod-json-schema-compat.js';
-import { describe, expect, test } from 'vitest';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../../../test-support/temp-dir.test-helper.ts';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { registerAllTools } from './index.ts';
import type { ServerInstance } from './shared.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
const BASE_CONFIG: Config = ConfigSchema.parse({});
interface Registration {
@@ -16,7 +18,7 @@ interface Registration {
outputSchema?: unknown;
}
-function captureAllRegistrations(cwd: string): Registration[] {
+function captureAllRegistrations(cwd: () => string): Registration[] {
const captured: Registration[] = [];
const server = {
registerTool(name: string, cfg: { inputSchema?: unknown; outputSchema?: unknown }) {
@@ -26,7 +28,7 @@ function captureAllRegistrations(cwd: string): Registration[] {
} as unknown as ServerInstance;
registerAllTools(server, {
config: BASE_CONFIG,
- resolveCwd: async () => cwd,
+ resolveCwd: async () => cwd(),
serverUrl: undefined,
});
return captured;
@@ -50,9 +52,12 @@ function refOffenders(rawShape: unknown, pipeStrategy: 'input' | 'output'): stri
}
describe('MCP tool schema portability — no intra-schema $ref (LM Studio / Gemini compat)', () => {
- const cwd = mkdtempSync(join(tmpdir(), 'ok-reffree-'));
- mkdirSync(join(cwd, '.ok'), { recursive: true });
- const registrations = captureAllRegistrations(cwd);
+ let cwd: string;
+ beforeAll(() => {
+ cwd = makeTempDir('ok-reffree-');
+ mkdirSync(join(cwd, '.ok'), { recursive: true });
+ });
+ const registrations = captureAllRegistrations(() => cwd);
test('registration sweep is non-empty (guards against a broken capture)', () => {
expect(registrations.length).toBeGreaterThan(10);
diff --git a/packages/server/src/mcp/tools/verb-tools.test.ts b/packages/server/src/mcp/tools/verb-tools.test.ts
index e1040eb2a..b905b534c 100644
--- a/packages/server/src/mcp/tools/verb-tools.test.ts
+++ b/packages/server/src/mcp/tools/verb-tools.test.ts
@@ -1,16 +1,8 @@
-import {
- existsSync,
- mkdirSync,
- mkdtempSync,
- readdirSync,
- readFileSync,
- statSync,
- writeFileSync,
-} from 'node:fs';
-import { tmpdir } from 'node:os';
+import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { describe, expect, test } from 'vitest';
+import { afterAll, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../../../test-support/temp-dir.test-helper.ts';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { register as registerDelete } from './delete.ts';
import { register as registerEdit } from './edit.ts';
@@ -18,6 +10,8 @@ import { startFetchTestServer } from './fetch-test-server.test-helper.ts';
import type { ServerInstance } from './shared.ts';
import { register as registerWrite } from './write.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
const BASE_CONFIG: Config = ConfigSchema.parse({});
interface ToolResult {
@@ -44,7 +38,7 @@ function capture<D>(register: (server: ServerInstance, deps: D) => void, cwd: st
}
function newProject(): string {
- return mkdtempSync(join(tmpdir(), 'ok-verb-tools-'));
+ return makeTempDir('ok-verb-tools-');
}
function textOf(r: ToolResult): string {
diff --git a/packages/server/src/mcp/tools/write-link-suppression.test.ts b/packages/server/src/mcp/tools/write-link-suppression.test.ts
index 06ecabd0d..f339c16d4 100644
--- a/packages/server/src/mcp/tools/write-link-suppression.test.ts
+++ b/packages/server/src/mcp/tools/write-link-suppression.test.ts
@@ -1,16 +1,16 @@
-import { mkdtempSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
import { normalizeObjectSchema } from '@modelcontextprotocol/sdk/server/zod-compat.js';
import { toJsonSchemaCompat } from '@modelcontextprotocol/sdk/server/zod-json-schema-compat.js';
import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';
-import { describe, expect, test } from 'vitest';
+import { afterAll, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../../../test-support/temp-dir.test-helper.ts';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { register as registerEdit } from './edit.ts';
import { startFetchTestServer } from './fetch-test-server.test-helper.ts';
import type { ServerInstance } from './shared.ts';
import { register as registerWrite } from './write.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
const BASE_CONFIG: Config = ConfigSchema.parse({});
interface ToolResult {
@@ -50,7 +50,7 @@ async function withStub(
payload: Record<string, unknown>,
body: (tools: StubbedTools) => Promise<void>,
): Promise<void> {
- const cwd = mkdtempSync(join(tmpdir(), 'ok-mcp-link-suppression-'));
+ const cwd = makeTempDir('ok-mcp-link-suppression-');
const stub = await startFetchTestServer({
port: 0,
async fetch(req) {
diff --git a/packages/server/src/removed-docs-journal.test.ts b/packages/server/src/removed-docs-journal.test.ts
index 2f084ab42..ddde1dd45 100644
--- a/packages/server/src/removed-docs-journal.test.ts
+++ b/packages/server/src/removed-docs-journal.test.ts
@@ -1,7 +1,7 @@
-import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { dirname, join } from 'node:path';
-import { describe, expect, test } from 'vitest';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { dirname } from 'node:path';
+import { afterAll, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../test-support/temp-dir.test-helper.ts';
import { RecentlyRemovedDocs } from './recently-removed-docs.ts';
import {
loadRemovedDocsJournal,
@@ -9,8 +9,10 @@ import {
saveRemovedDocsJournal,
} from './removed-docs-journal.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
function makeProjectDir(): string {
- return mkdtempSync(join(tmpdir(), 'ok-removed-docs-journal-'));
+ return makeTempDir('ok-removed-docs-journal-');
}
describe('removed-docs journal — round trip', () => {
diff --git a/packages/server/src/shadow-repo-stats.test.ts b/packages/server/src/shadow-repo-stats.test.ts
index e93329ea9..977a4a5a5 100644
--- a/packages/server/src/shadow-repo-stats.test.ts
+++ b/packages/server/src/shadow-repo-stats.test.ts
@@ -1,17 +1,18 @@
import { mkdirSync, writeFileSync } from 'node:fs';
-import { mkdtemp } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import simpleGit from 'simple-git';
-import { beforeEach, describe, expect, test } from 'vitest';
+import { afterAll, beforeEach, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../test-support/temp-dir.test-helper.ts';
import { initShadowRepo, type ShadowHandle, shadowGit } from './shadow-repo.ts';
import { countStaleAgentWipRefs } from './shadow-repo-stats.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
let tmpDir: string;
let shadow: ShadowHandle;
beforeEach(async () => {
- tmpDir = await mkdtemp(resolve(tmpdir(), 'ok-stale-stats-'));
+ tmpDir = makeTempDir('ok-stale-stats-');
const projectRoot = resolve(tmpDir, 'project');
const contentDir = resolve(projectRoot, 'content/docs');
mkdirSync(contentDir, { recursive: true });
diff --git a/packages/server/src/showall-cap.test.ts b/packages/server/src/showall-cap.test.ts
index 16e2ab909..3de334fc5 100644
--- a/packages/server/src/showall-cap.test.ts
+++ b/packages/server/src/showall-cap.test.ts
@@ -1,8 +1,8 @@
-import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
+import { mkdirSync, realpathSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import type { DocumentListEntry } from '@inkeep/open-knowledge-core';
-import { afterEach, describe, expect, test } from 'vitest';
+import { afterAll, afterEach, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../test-support/temp-dir.test-helper.ts';
import {
__getShowAllWalkStatsForTesting,
__resetShowAllWalkStatsForTesting,
@@ -13,8 +13,10 @@ import {
} from './api-extension.ts';
import { createContentFilter } from './content-filter.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
function makeFlatFixture(fileCount: number): string {
- const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-walk-')));
+ const dir = realpathSync(makeTempDir('ok-showall-walk-'));
for (let i = 0; i < fileCount; i++) {
writeFileSync(join(dir, `file-${String(i).padStart(3, '0')}.md`), `# File ${i}\n`);
}
@@ -111,7 +113,7 @@ describe('walkContentDirForShowAll — entry-cap boundary honesty', () => {
});
test('cap consumed by a folder entry short-circuits the recursive descent', async () => {
- const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-nested-')));
+ const dir = realpathSync(makeTempDir('ok-showall-nested-'));
mkdirSync(join(dir, 'sub'));
writeFileSync(join(dir, 'sub', 'a.md'), '# A\n');
writeFileSync(join(dir, 'sub', 'b.md'), '# B\n');
diff --git a/packages/server/src/showall-stream.test.ts b/packages/server/src/showall-stream.test.ts
index a1c6365df..840c5c421 100644
--- a/packages/server/src/showall-stream.test.ts
+++ b/packages/server/src/showall-stream.test.ts
@@ -1,15 +1,8 @@
-import {
- chmodSync,
- mkdirSync,
- mkdtempSync,
- realpathSync,
- symlinkSync,
- writeFileSync,
-} from 'node:fs';
-import { tmpdir } from 'node:os';
+import { chmodSync, mkdirSync, realpathSync, symlinkSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { ASSET_EXTENSIONS, type DocumentListEntry } from '@inkeep/open-knowledge-core';
-import { afterEach, describe, expect, test, vi } from 'vitest';
+import { afterAll, afterEach, describe, expect, test, vi } from 'vitest';
+import { createTempDirFactory } from '../../../test-support/temp-dir.test-helper.ts';
import {
__getShowAllWalkStatsForTesting,
__resetShowAllWalkStatsForTesting,
@@ -20,8 +13,10 @@ import {
import { createContentFilter, createContentFilterAsync } from './content-filter.ts';
import { getLogger } from './logger.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
function makeFlatFixture(fileCount: number): string {
- const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-stream-')));
+ const dir = realpathSync(makeTempDir('ok-showall-stream-'));
for (let i = 0; i < fileCount; i++) {
writeFileSync(join(dir, `file-${String(i).padStart(3, '0')}.md`), `# File ${i}\n`);
}
@@ -29,7 +24,7 @@ function makeFlatFixture(fileCount: number): string {
}
function makeNestedFixture(): string {
- const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-stream-nested-')));
+ const dir = realpathSync(makeTempDir('ok-showall-stream-nested-'));
writeFileSync(join(dir, 'root.md'), '# root\n');
writeFileSync(join(dir, 'note.txt'), 'plain\n');
for (const sub of ['alpha', 'beta']) {
@@ -133,7 +128,7 @@ describe('streamShowAllEntries — abort + laziness', () => {
});
test('abort between queued directories is honored when the remaining dirs are empty', async () => {
- const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-stream-abort-')));
+ const dir = realpathSync(makeTempDir('ok-showall-stream-abort-'));
for (const sub of ['a', 'b', 'c']) {
mkdirSync(join(dir, sub));
}
@@ -160,7 +155,7 @@ function entryPath(e: DocumentListEntry): string {
describe('streamShowAllEntries — .okignore', () => {
test('root patterns hide matching folders from the all-files sidebar', async () => {
- const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-okignore-')));
+ const dir = realpathSync(makeTempDir('ok-showall-okignore-'));
mkdirSync(join(dir, 'src', 'adapters'), { recursive: true });
writeFileSync(join(dir, 'src', 'main.rs'), 'fn main() {}\n');
writeFileSync(join(dir, 'src', 'adapters', 'mod.rs'), 'pub mod adapter;\n');
@@ -196,7 +191,7 @@ describe('streamShowAllEntries — .okignore', () => {
});
test('async content filters apply the same all-files hide rules', async () => {
- const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-okignore-async-')));
+ const dir = realpathSync(makeTempDir('ok-showall-okignore-async-'));
mkdirSync(join(dir, 'src'));
writeFileSync(join(dir, 'src', 'main.rs'), 'fn main() {}\n');
mkdirSync(join(dir, 'target'));
@@ -223,7 +218,7 @@ describe('streamShowAllEntries — .okignore', () => {
});
test('nested .okignore patterns hide matching folders from the all-files sidebar', async () => {
- const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-okignore-nested-')));
+ const dir = realpathSync(makeTempDir('ok-showall-okignore-nested-'));
mkdirSync(join(dir, 'docs', 'drafts'), { recursive: true });
writeFileSync(join(dir, 'docs', 'drafts', 'wip.md'), '# Draft\n');
writeFileSync(join(dir, 'docs', 'guide.md'), '# Guide\n');
@@ -250,7 +245,7 @@ describe('streamShowAllEntries — .okignore', () => {
describe('streamShowAllEntries — level-order emission (PRD-6858)', () => {
function makeStarvationFixture(): { dir: string; rootFolders: string[]; rootDocs: string[] } {
- const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-bfs-')));
+ const dir = realpathSync(makeTempDir('ok-showall-bfs-'));
const rootFolders: string[] = [];
const rootDocs: string[] = [];
for (let d = 0; d < 5; d++) {
@@ -283,7 +278,7 @@ describe('streamShowAllEntries — level-order emission (PRD-6858)', () => {
});
test('every depth-N entry emits before the first depth-N+1 entry, parents before children', async () => {
- const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-levelorder-')));
+ const dir = realpathSync(makeTempDir('ok-showall-levelorder-'));
writeFileSync(join(dir, 'root.md'), '# root\n');
mkdirSync(join(dir, 'a', 'sub'), { recursive: true });
mkdirSync(join(dir, 'b'));
@@ -310,7 +305,7 @@ describe('streamShowAllEntries — level-order emission (PRD-6858)', () => {
});
test('maxDepth=1 yields a single level with hasChildren stamped, never recursing', async () => {
- const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-depth1-')));
+ const dir = realpathSync(makeTempDir('ok-showall-depth1-'));
writeFileSync(join(dir, 'top.md'), '# top\n');
mkdirSync(join(dir, 'full', 'grandchild'), { recursive: true });
writeFileSync(join(dir, 'full', 'child.md'), '# child\n');
@@ -331,7 +326,7 @@ describe('streamShowAllEntries — level-order emission (PRD-6858)', () => {
});
test('co-located .md and .mdx emit separate extension-qualified document rows', async () => {
- const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-doc-ext-collision-')));
+ const dir = realpathSync(makeTempDir('ok-showall-doc-ext-collision-'));
writeFileSync(join(dir, 'foo.md'), '# Markdown\n');
writeFileSync(join(dir, 'foo.mdx'), '# MDX\n');
writeFileSync(join(dir, 'bar.mdx'), '# Bar\n');
@@ -361,8 +356,8 @@ describe('streamShowAllEntries — level-order emission (PRD-6858)', () => {
});
test('escaping same-stem symlink does not force admitted document to extension-qualified row', async () => {
- const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-doc-ext-symesc-')));
- const outside = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-doc-ext-outside-')));
+ const dir = realpathSync(makeTempDir('ok-showall-doc-ext-symesc-'));
+ const outside = realpathSync(makeTempDir('ok-showall-doc-ext-outside-'));
writeFileSync(join(dir, 'foo.md'), '# Markdown\n');
writeFileSync(join(outside, 'foo.mdx'), '# Escaped MDX\n');
symlinkSync(join(outside, 'foo.mdx'), join(dir, 'foo.mdx'));
@@ -384,7 +379,7 @@ describe('streamShowAllEntries — level-order emission (PRD-6858)', () => {
describe('streamShowAllEntries — cap accounting boundary quirks', () => {
test('an excludable entry past the cap still reports truncated (cap checked before exclusion)', async () => {
- const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-quirk-')));
+ const dir = realpathSync(makeTempDir('ok-showall-quirk-'));
const CAP = 4;
mkdirSync(join(dir, 'sub'));
for (let i = 0; i < CAP - 1; i++) {
@@ -399,7 +394,7 @@ describe('streamShowAllEntries — cap accounting boundary quirks', () => {
});
test('the same tree under a roomier cap drains untruncated — the exclusion gate still prunes', async () => {
- const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-quirk-roomy-')));
+ const dir = realpathSync(makeTempDir('ok-showall-quirk-roomy-'));
mkdirSync(join(dir, 'sub'));
for (let i = 0; i < 3; i++) {
writeFileSync(join(dir, `f-${i}.md`), `# f ${i}\n`);
@@ -419,7 +414,7 @@ describe('streamShowAllEntries — unreadable directory mid-queue', () => {
test.skipIf(runningAsRoot)(
'a permission-denied directory skips with a warn while every other entry still emits',
async () => {
- const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-eacces-')));
+ const dir = realpathSync(makeTempDir('ok-showall-eacces-'));
writeFileSync(join(dir, 'root.md'), '# root\n');
mkdirSync(join(dir, 'locked'));
writeFileSync(join(dir, 'locked', 'hidden.md'), '# hidden\n');
@@ -457,7 +452,7 @@ describe('streamShowAllEntries — unreadable directory mid-queue', () => {
describe('streamShowAllEntries — .base/.canvas mediaKind', () => {
test('.base and .canvas entries report mediaKind text in showAll output', async () => {
- const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-mediakind-')));
+ const dir = realpathSync(makeTempDir('ok-showall-mediakind-'));
writeFileSync(join(dir, 'note.md'), '# Note\n');
writeFileSync(join(dir, 'Characters.base'), 'fields:\n - name\n');
writeFileSync(join(dir, 'Board.canvas'), '{"nodes":[],"edges":[]}\n');
@@ -481,7 +476,7 @@ describe('streamShowAllEntries — .base/.canvas mediaKind', () => {
describe('streamShowAllEntries — symlinked directories', () => {
function makeSymlinkDirFixture(): string {
- const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-symdir-')));
+ const dir = realpathSync(makeTempDir('ok-showall-symdir-'));
const canonical = join(dir, 'canonical-folder');
mkdirSync(canonical);
writeFileSync(join(canonical, 'note-one.md'), '# one\n');
@@ -525,8 +520,8 @@ describe('streamShowAllEntries — symlinked directories', () => {
});
test('refuses a symlinked directory whose target escapes contentDir', async () => {
- const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-symesc-')));
- const outside = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-outside-')));
+ const dir = realpathSync(makeTempDir('ok-showall-symesc-'));
+ const outside = realpathSync(makeTempDir('ok-showall-outside-'));
writeFileSync(join(outside, 'secret.md'), '# secret\n');
symlinkSync(outside, join(dir, 'escape'));
const { entries } = await drain(streamShowAllEntries(streamOptsFor(dir, 50_000)));
@@ -536,7 +531,7 @@ describe('streamShowAllEntries — symlinked directories', () => {
});
test('does not infinitely recurse on cyclic symlinked directories', async () => {
- const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-symcycle-')));
+ const dir = realpathSync(makeTempDir('ok-showall-symcycle-'));
mkdirSync(join(dir, 'A'));
mkdirSync(join(dir, 'B'));
writeFileSync(join(dir, 'A', 'a.md'), '# a\n');
@@ -552,7 +547,7 @@ describe('streamShowAllEntries — symlinked directories', () => {
describe('streamShowAllEntries — showOk reveal', () => {
function makeOkFixture(): string {
- const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-showok-')));
+ const dir = realpathSync(makeTempDir('ok-showall-showok-'));
writeFileSync(join(dir, 'note.md'), '# note\n');
mkdirSync(join(dir, '.ok', 'templates'), { recursive: true });
writeFileSync(join(dir, '.ok', 'config.yml'), 'content:\n dir: .\n');
diff --git a/packages/server/src/skill-install-report-config.test.ts b/packages/server/src/skill-install-report-config.test.ts
index 67bf46e50..5da151566 100644
--- a/packages/server/src/skill-install-report-config.test.ts
+++ b/packages/server/src/skill-install-report-config.test.ts
@@ -1,12 +1,14 @@
-import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { dirname, join } from 'node:path';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { dirname } from 'node:path';
import { resolveConfigPath } from '@inkeep/open-knowledge-core/server';
-import { describe, expect, test } from 'vitest';
+import { afterAll, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../test-support/temp-dir.test-helper.ts';
import { resolveSkillInstallReportSettings } from './skill-install-report-config.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
function freshHome(): string {
- return mkdtempSync(join(tmpdir(), 'ok-report-config-'));
+ return makeTempDir('ok-report-config-');
}
function writeUserConfig(home: string, yaml: string): string {
diff --git a/packages/server/src/skill-install.test.ts b/packages/server/src/skill-install.test.ts
index 849b788f4..95d7aef3a 100644
--- a/packages/server/src/skill-install.test.ts
+++ b/packages/server/src/skill-install.test.ts
@@ -1,17 +1,10 @@
import type { SpawnOptions } from 'node:child_process';
-import {
- existsSync,
- mkdirSync,
- mkdtempSync,
- readdirSync,
- readFileSync,
- writeFileSync,
-} from 'node:fs';
+import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { HOSTS_WITH_USER_SKILL_DIR } from '@inkeep/open-knowledge-core';
-import { beforeEach, describe, expect, test } from 'vitest';
+import { afterAll, beforeEach, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../test-support/temp-dir.test-helper.ts';
import { BUNDLE_SKILL_NAME } from './skill-bundles.ts';
import {
buildAndOpenSkill,
@@ -23,6 +16,8 @@ import {
} from './skill-install.ts';
import { writeBundleDecision } from './skill-state.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
async function readServerVersion(): Promise<string> {
const raw = await readFile(new URL('../package.json', import.meta.url), 'utf-8');
return (JSON.parse(raw) as { version: string }).version;
@@ -44,7 +39,7 @@ function makeRecordingLogger(): { logger: SkillInstallLogger; records: RecordedL
}
function freshHome(): string {
- return mkdtempSync(join(tmpdir(), 'ok-skill-install-'));
+ return makeTempDir('ok-skill-install-');
}
function installHost(home: string, hostDir: string): void {
diff --git a/packages/server/src/skill-state.test.ts b/packages/server/src/skill-state.test.ts
index 02d77c98b..2e671d050 100644
--- a/packages/server/src/skill-state.test.ts
+++ b/packages/server/src/skill-state.test.ts
@@ -1,9 +1,9 @@
-import { mkdtempSync, readFileSync } from 'node:fs';
+import { readFileSync } from 'node:fs';
import { mkdir, readFile, writeFile } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { afterEach, describe, expect, test, vi } from 'vitest';
+import { afterAll, afterEach, describe, expect, test, vi } from 'vitest';
+import { createTempDirFactory } from '../../../test-support/temp-dir.test-helper.ts';
import {
clearInstallReported,
readAllTargets,
@@ -20,8 +20,10 @@ import {
writeTargetVersion,
} from './skill-state.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
function freshHome(): string {
- return mkdtempSync(join(tmpdir(), 'ok-skill-state-'));
+ return makeTempDir('ok-skill-state-');
}
describe('per-bundle opt-in decisions', () => {
diff --git a/packages/server/src/skills-sh-install-report.test.ts b/packages/server/src/skills-sh-install-report.test.ts
index d4169a07e..e0419aa46 100644
--- a/packages/server/src/skills-sh-install-report.test.ts
+++ b/packages/server/src/skills-sh-install-report.test.ts
@@ -1,11 +1,13 @@
-import { mkdirSync, mkdtempSync } from 'node:fs';
-import { tmpdir } from 'node:os';
+import { mkdirSync } from 'node:fs';
import { join } from 'node:path';
-import { describe, expect, test } from 'vitest';
+import { afterAll, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../../../test-support/temp-dir.test-helper.ts';
import { reportSkillInstall } from './skills-sh-install-report.ts';
+const makeTempDir = createTempDirFactory(afterAll);
+
function freshHome(): string {
- return mkdtempSync(join(tmpdir(), 'ok-install-report-'));
+ return makeTempDir('ok-install-report-');
}
function recordingFetch(): { calls: string[]; impl: typeof fetch } {
diff --git a/scripts/check-server-test-inputs.test.mjs b/scripts/check-server-test-inputs.test.mjs
index 7c199f86b..cda9aaeb9 100644
--- a/scripts/check-server-test-inputs.test.mjs
+++ b/scripts/check-server-test-inputs.test.mjs
@@ -1,9 +1,9 @@
import { spawnSync } from 'node:child_process';
-import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { describe, expect, test } from 'vitest';
+import { afterAll, describe, expect, test } from 'vitest';
+import { createTempDirFactory } from '../test-support/temp-dir.test-helper.ts';
import {
escapingReads,
globalDependencyCovers,
@@ -16,6 +16,8 @@ import {
import { memberDirs } from './check-typescript-resolution.mjs';
import { readJsoncOrError } from './read-jsonc.mjs';
+const makeTempDir = createTempDirFactory(afterAll);
+
const OK_ROOT = fileURLToPath(new URL('..', import.meta.url));
const TASK = '@inkeep/open-knowledge-server#test';
@@ -25,7 +27,7 @@ function fixtureRootWithout(glob) {
expect(inputs, `fixture precondition: ${glob} must be declared`).toContain(glob);
turbo.tasks[TASK].inputs = inputs.filter((entry) => entry !== glob);
- const root = mkdtempSync(join(tmpdir(), 'ok-server-inputs-'));
+ const root = makeTempDir('ok-server-inputs-');
writeFileSync(join(root, 'turbo.json'), JSON.stringify(turbo, null, 2));
for (const [target, readers] of escapingReads(OK_ROOT)) {
@@ -60,7 +62,7 @@ describe('check-server-test-inputs', () => {
);
function fixtureRootReading(testFile) {
- const root = mkdtempSync(join(tmpdir(), 'ok-server-inputs-'));
+ const root = makeTempDir('ok-server-inputs-');
mkdirSync(join(root, 'packages/server/src'), { recursive: true });
mkdirSync(join(root, 'docs'), { recursive: true });
writeFileSync(join(root, 'docs/guide.md'), '');
@@ -177,7 +179,9 @@ describe('the uncached tier is a root task of its own', () => {
refused,
'pnpm-workspace.yaml has entries this derivation cannot read or that name no member, so their turbo configs would leave the scan',
).toEqual([]);
- expect(members.map((dir) => relative(OK_ROOT, dir))).toEqual(expect.arrayContaining(['packages/server', 'docs']));
+ expect(members.map((dir) => relative(OK_ROOT, dir))).toEqual(
+ expect.arrayContaining(['packages/server', 'docs']),
+ );
const configs = [['turbo.json', turbo]];
for (const dir of members) {
for (const name of ['turbo.json', 'turbo.jsonc']) {
@@ -189,7 +193,10 @@ describe('the uncached tier is a root task of its own', () => {
}
const finiteWith = configs.flatMap(([path, config]) =>
Object.entries(config.tasks ?? {})
- .filter(([name, task]) => task.with !== undefined && (task.persistent ?? turbo.tasks[name]?.persistent) !== true)
+ .filter(
+ ([name, task]) =>
+ task.with !== undefined && (task.persistent ?? turbo.tasks[name]?.persistent) !== true,
+ )
.map(([name]) => `${path}: ${name}`),
);
expect(
diff --git a/test-support/temp-dir.test-helper.ts b/test-support/temp-dir.test-helper.ts
new file mode 100644
index 000000000..b4b8ca72c
--- /dev/null
+++ b/test-support/temp-dir.test-helper.ts
@@ -0,0 +1,37 @@
+import { mkdtempSync } from 'node:fs';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+export async function withTempDir<T>(
+ prefix: string,
+ fn: (dir: string) => T | Promise<T>,
+): Promise<T> {
+ const dir = await mkdtemp(join(tmpdir(), prefix));
+ try {
+ return await fn(dir);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+}
+
+export function createTempDirFactory(
+ registerCleanup: (cleanup: () => Promise<void>) => unknown,
+): (prefix: string) => string {
+ const paths: string[] = [];
+ registerCleanup(async () => {
+ const results = await Promise.allSettled(
+ paths.splice(0).map((path) => rm(path, { recursive: true, force: true })),
+ );
+ const failures = results.flatMap((result) =>
+ result.status === 'rejected' ? [result.reason] : [],
+ );
+ if (failures.length === 1) throw failures[0];
+ if (failures.length > 1) throw new AggregateError(failures, 'Temp dir cleanup failed');
+ });
+ return (prefix) => {
+ const path = mkdtempSync(join(tmpdir(), prefix));
+ paths.push(path);
+ return path;
+ };
+}
diff --git a/test-support/temp-dir.test.ts b/test-support/temp-dir.test.ts
new file mode 100644
index 000000000..81722309a
--- /dev/null
+++ b/test-support/temp-dir.test.ts
@@ -0,0 +1,113 @@
+import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { expect, test, vi } from 'vitest';
+import { runningAsRoot } from './capabilities.test-helper.ts';
+import { createTempDirFactory, withTempDir } from './temp-dir.test-helper.ts';
+
+async function withSystemTempDirAt(fn: (root: string) => Promise<void>): Promise<void> {
+ await withTempDir('ok-temp-owner-', async (root) => {
+ for (const key of ['TMPDIR', 'TMP', 'TEMP']) vi.stubEnv(key, root);
+ try {
+ await fn(root);
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+}
+
+test('registered cleanup removes owned trees and preserves neighboring files', async () => {
+ await withSystemTempDirAt(async (root) => {
+ let cleanup = async () => {};
+ const create = createTempDirFactory((registered) => {
+ cleanup = registered;
+ });
+ const neighbor = join(root, 'neighbor.txt');
+ writeFileSync(neighbor, 'retained');
+ const first = create('first-');
+ const second = create('second-');
+ mkdirSync(join(first, 'nested'));
+ writeFileSync(join(first, 'nested', 'data.txt'), 'fixture');
+ expect(existsSync(first)).toBe(true);
+ expect(existsSync(second)).toBe(true);
+ await cleanup();
+ expect(existsSync(first)).toBe(false);
+ expect(existsSync(second)).toBe(false);
+ expect(readFileSync(neighbor, 'utf8')).toBe('retained');
+ expect([dirname(first), dirname(second)]).toEqual([root, root]);
+ });
+});
+
+test('registered cleanup can release a later allocation after an earlier cleanup', async () => {
+ await withSystemTempDirAt(async () => {
+ let cleanup = async () => {};
+ const create = createTempDirFactory((registered) => {
+ cleanup = registered;
+ });
+ const first = create('round-');
+ await cleanup();
+ const second = create('round-');
+ expect(existsSync(first)).toBe(false);
+ expect(existsSync(second)).toBe(true);
+ await cleanup();
+ expect(existsSync(second)).toBe(false);
+ });
+});
+
+test('registered cleanup attempts every removal and reports each failure', async (ctx) => {
+ ctx.skip(runningAsRoot, 'root bypasses the chmod refusal this test induces');
+ await withSystemTempDirAt(async (root) => {
+ let cleanup = async () => {};
+ const create = createTempDirFactory((registered) => {
+ cleanup = registered;
+ });
+ const allocateUnder = (parentName: string, prefix: string) => {
+ const parent = join(root, parentName);
+ mkdirSync(parent);
+ for (const key of ['TMPDIR', 'TMP', 'TEMP']) vi.stubEnv(key, parent);
+ return { parent, path: create(prefix) };
+ };
+ const first = allocateUnder('locked-first', 'first-');
+ const second = allocateUnder('locked-second', 'second-');
+ const removable = allocateUnder('writable', 'removable-');
+ expect(existsSync(removable.path)).toBe(true);
+ let failure: unknown;
+ try {
+ chmodSync(first.parent, 0o500);
+ chmodSync(second.parent, 0o500);
+ failure = await cleanup().then(
+ () => undefined,
+ (error: unknown) => error,
+ );
+ } finally {
+ chmodSync(first.parent, 0o700);
+ chmodSync(second.parent, 0o700);
+ }
+ expect(failure).toBeInstanceOf(AggregateError);
+ expect((failure as AggregateError).errors).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ code: 'EACCES', path: first.path }),
+ expect.objectContaining({ code: 'EACCES', path: second.path }),
+ ]),
+ );
+ expect(existsSync(removable.path)).toBe(false);
+ });
+});
+
+test('registered cleanup rejects with the original error when one removal fails', async (ctx) => {
+ ctx.skip(runningAsRoot, 'root bypasses the chmod refusal this test induces');
+ await withSystemTempDirAt(async (root) => {
+ let cleanup = async () => {};
+ const create = createTempDirFactory((registered) => {
+ cleanup = registered;
+ });
+ const locked = create('locked-');
+ chmodSync(root, 0o500);
+ const failure = await cleanup()
+ .then(
+ () => undefined,
+ (error: unknown) => error,
+ )
+ .finally(() => chmodSync(root, 0o700));
+ expect(failure).toMatchObject({ code: 'EACCES', path: locked });
+ });
+});