Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: clean up mkdtemp directories in test suites (#9000)

[._.]/ Adam Eivy6777b83540b3
diff --git a/scripts/lib/envFile.test.js b/scripts/lib/envFile.test.js
index 07bf9ddf7a..6928c01964 100644
--- a/scripts/lib/envFile.test.js
+++ b/scripts/lib/envFile.test.js
@@ -1,14 +1,25 @@
-import { describe, it, expect, beforeEach } from 'vitest';
-import { mkdtempSync, writeFileSync } from 'fs';
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, writeFileSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { parseEnvFile, upsertEnvKey } from './envFile.js';
+const tempDirs = [];
+
+beforeEach(() => {
+ const dir = mkdtempSync(join(tmpdir(), 'envFile-test-'));
+ tempDirs.push(dir);
+});
+
+afterEach(() => {
+ for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
let dir;
let envPath;
beforeEach(() => {
- dir = mkdtempSync(join(tmpdir(), 'envFile-test-'));
+ dir = tempDirs[tempDirs.length - 1];
envPath = join(dir, '.env');
});
diff --git a/scripts/lib/githubOutput.test.js b/scripts/lib/githubOutput.test.js
index ee789a6f20..4ea21d3cf0 100644
--- a/scripts/lib/githubOutput.test.js
+++ b/scripts/lib/githubOutput.test.js
@@ -1,4 +1,4 @@
-import { mkdtempSync, readFileSync, writeFileSync } from 'fs';
+import { mkdtempSync, readFileSync, writeFileSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -10,15 +10,18 @@ import {
describe('writeStepOutput', () => {
let outputPath;
+ let tempRoot;
const previous = process.env.GITHUB_OUTPUT;
beforeEach(() => {
- outputPath = join(mkdtempSync(join(tmpdir(), 'gh-output-')), 'output.txt');
+ tempRoot = mkdtempSync(join(tmpdir(), 'gh-output-'));
+ outputPath = join(tempRoot, 'output.txt');
writeFileSync(outputPath, '');
process.env.GITHUB_OUTPUT = outputPath;
});
afterEach(() => {
+ if (tempRoot) rmSync(tempRoot, { recursive: true, force: true });
if (previous === undefined) delete process.env.GITHUB_OUTPUT;
else process.env.GITHUB_OUTPUT = previous;
});
@@ -46,15 +49,20 @@ describe('writeStepOutput', () => {
describe('writeStepEnv', () => {
let envPath;
+ let tempRoot;
const previous = process.env.GITHUB_ENV;
+ const tempRoots = [];
beforeEach(() => {
- envPath = join(mkdtempSync(join(tmpdir(), 'gh-env-')), 'env.txt');
+ tempRoot = mkdtempSync(join(tmpdir(), 'gh-env-'));
+ tempRoots.push(tempRoot);
+ envPath = join(tempRoot, 'env.txt');
writeFileSync(envPath, '');
process.env.GITHUB_ENV = envPath;
});
afterEach(() => {
+ for (const root of tempRoots.splice(0)) rmSync(root, { recursive: true, force: true });
if (previous === undefined) delete process.env.GITHUB_ENV;
else process.env.GITHUB_ENV = previous;
});
@@ -72,7 +80,9 @@ describe('writeStepEnv', () => {
});
it('writes to GITHUB_ENV, not GITHUB_OUTPUT', () => {
- const outputPath = join(mkdtempSync(join(tmpdir(), 'gh-output-')), 'output.txt');
+ const outputRoot = mkdtempSync(join(tmpdir(), 'gh-output-'));
+ tempRoots.push(outputRoot);
+ const outputPath = join(outputRoot, 'output.txt');
writeFileSync(outputPath, '');
const previousOutput = process.env.GITHUB_OUTPUT;
process.env.GITHUB_OUTPUT = outputPath;
@@ -95,12 +105,18 @@ describe('writeStepEnv', () => {
describe('writeStepSummary', () => {
let summaryPath;
+ let tempRoot;
beforeEach(() => {
- summaryPath = join(mkdtempSync(join(tmpdir(), 'gh-summary-')), 'summary.md');
+ tempRoot = mkdtempSync(join(tmpdir(), 'gh-summary-'));
+ summaryPath = join(tempRoot, 'summary.md');
writeFileSync(summaryPath, '');
});
+ afterEach(() => {
+ if (tempRoot) rmSync(tempRoot, { recursive: true, force: true });
+ });
+
it('appends the markdown block verbatim, newlines and all', () => {
// The key/value writers collapse newlines because a newline forges a second
// entry there. In markdown a newline is content, and collapsing it would
diff --git a/server/lib/mkdtempCleanup.guards.test.js b/server/lib/mkdtempCleanup.guards.test.js
new file mode 100644
index 0000000000..912f4974dd
--- /dev/null
+++ b/server/lib/mkdtempCleanup.guards.test.js
@@ -0,0 +1,176 @@
+/**
+ * Test suites that create mkdtemp directories must clean them up.
+ *
+ * ## The bug class
+ *
+ * Test suites call `mkdtemp(join(tmpdir(), 'prefix-'))` to create isolated
+ * temp directories but never call `rmSync` to remove them. After repeated test
+ * runs on a dev machine (CoS agents, pregate), $TMPDIR accumulates tens of
+ * thousands of stale directories, consuming disk space and creating FSEvents
+ * churn. Issue #9000 observed ~50k leaked directories from ~3 weeks of uptime.
+ *
+ * ## The rule
+ *
+ * Every git-tracked `*.test.js` file in test-bearing trees and test-helper
+ * modules that call `mkdtemp(join(tmpdir(), …))` or `mkdtempSync(join(tmpdir(), …))` MUST also:
+ *
+ * - Import `rmSync` from `fs` (or `fs/promises`)
+ * - Track each root directory created by `mkdtemp`/`mkdtempSync`
+ * - Call `rmSync(root, { recursive: true, force: true })` in an `afterEach` hook
+ *
+ * For async `mkdtemp`, the pattern is:
+ * - Create a `tempRoots` array at module level
+ * - Track each root: `tempRoots.push(await mkdtemp(…))`
+ * - Clean in afterEach: `afterEach(() => { for (const r of tempRoots.splice(0)) rmSync(r, { recursive: true, force: true }); })`
+ *
+ * For sync `mkdtempSync`, the pattern is:
+ * - Create a `tempRoots` array
+ * - Track: `const root = mkdtempSync(…); tempRoots.push(root);`
+ * - Clean: `afterEach(() => { for (const r of tempRoots.splice(0)) rmSync(r, { recursive: true, force: true }); })`
+ *
+ * See `server/lib/apiRouteGraph.test.js` for a worked example.
+ *
+ * ## Opt-out
+ *
+ * A justified case (e.g., a helper that intentionally retains temp state across
+ * test runs or cleans up via a separate mechanism) may opt out with an explicit
+ * comment on the line calling mkdtemp:
+ *
+ * // SKIP: mkdtemp cleanup — [reason]
+ * const root = mkdtemp(join(tmpdir(), 'myprefix-'));
+ *
+ * The comment must appear on the mkdtemp line itself (or immediately before it).
+ */
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'fs';
+import { execFileSync } from 'child_process';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+
+const SERVER_ROOT = dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = dirname(SERVER_ROOT);
+
+// Test-bearing trees where mkdtemp cleanup is required
+const TEST_ROOTS = [
+ 'server/',
+ 'scripts/',
+ 'lib/',
+ 'autofixer/',
+];
+
+// Test helper modules where cleanup is required
+const TEST_HELPER_PATTERNS = [
+ 'server/lib/gitTestRepo.js',
+ 'scripts/migrations/_*.js',
+];
+
+const MKDTEMP_PATTERN = /\b(?:mkdtemp|mkdtempSync)\s*\(\s*(?:join|path\.join)\s*\(\s*(?:tmpdir|process\.env\.\w+|os\.tmpdir)\s*\(\s*\)/g;
+const SKIP_MARKER = /SKIP\s*:\s*mkdtemp\s*cleanup/i;
+const CLEANUP_PATTERN = /\b(?:rmSync|destroyGitSandbox|rm\()\s*\(/;
+
+/**
+ * Finds all git-tracked files in test-bearing trees that match test patterns or are test helpers.
+ */
+function findTestFiles() {
+ const files = execFileSync('git', ['ls-files', '*.js', '*.mjs', '*.cjs'], {
+ cwd: REPO_ROOT,
+ encoding: 'utf8',
+ maxBuffer: 64 * 1024 * 1024,
+ }).split('\n').filter((f) => f && (
+ (f.endsWith('.test.js') && TEST_ROOTS.some((root) => f.startsWith(root))) ||
+ TEST_HELPER_PATTERNS.some((pattern) => {
+ // Simple glob pattern matching: _*.js becomes a startsWith check
+ const regexPattern = pattern.replace(/\*/, '.*');
+ return new RegExp(regexPattern).test(f);
+ })
+ ));
+ return files;
+}
+
+describe('mkdtemp cleanup guard (#9000)', () => {
+ it('finds test files to scan', () => {
+ const files = findTestFiles();
+ expect(files.length).toBeGreaterThan(100);
+ expect(files.some((f) => f.endsWith('.test.js'))).toBe(true);
+ });
+
+ it('scans for mkdtemp calls without cleanup', () => {
+ const violations = [];
+
+ for (const file of findTestFiles()) {
+ const src = readFileSync(join(REPO_ROOT, file), 'utf8');
+
+ // Skip files with no mkdtemp calls
+ if (!MKDTEMP_PATTERN.test(src)) continue;
+
+ // Check if there's any cleanup mechanism (rmSync, destroyGitSandbox, rm, etc.)
+ const hasCleanup = CLEANUP_PATTERN.test(src);
+
+ // Find each mkdtemp call and check for skip marker
+ MKDTEMP_PATTERN.lastIndex = 0; // Reset regex
+ for (const match of src.matchAll(MKDTEMP_PATTERN)) {
+ // Check if this specific call has the skip marker nearby (within 2 lines before)
+ const callIndex = match.index;
+ const beforeCall = src.slice(Math.max(0, callIndex - 200), callIndex);
+ const hasSkipMarker = SKIP_MARKER.test(beforeCall);
+
+ if (!hasSkipMarker && !hasCleanup) {
+ const lineNum = src.slice(0, callIndex).split('\n').length;
+ violations.push(`${file} line ${lineNum}: mkdtemp without cleanup (add skip marker if justified)`);
+ }
+ }
+ }
+
+ if (violations.length > 0) {
+ throw new Error(
+ `Found ${violations.length} mkdtemp call(s) without cleanup:\n`
+ + ` ${violations.join('\n ')}\n`
+ + `\nEach mkdtemp/mkdtempSync must track roots and clean with rmSync in afterEach.\n`
+ + `See server/lib/apiRouteGraph.test.js for the pattern.\n`
+ + `Or add "// SKIP: mkdtemp cleanup — [reason]" if this is a special case.`,
+ );
+ }
+ });
+
+ describe('the guard recognizer', () => {
+ it('detects mkdtemp calls', () => {
+ const src = `
+ import { mkdtemp, mkdtempSync } from 'fs/promises';
+ const d1 = mkdtemp(join(tmpdir(), 'prefix-'));
+ const d2 = mkdtempSync(join(os.tmpdir(), 'prefix-'));
+ `;
+ expect(src.match(MKDTEMP_PATTERN)).toHaveLength(2);
+ });
+
+ it('ignores mkdtemp calls outside tmpdir()', () => {
+ const src = `
+ const d1 = mkdtemp('./localdir-');
+ const d2 = mkdtempSync(process.cwd());
+ `;
+ expect(src.match(MKDTEMP_PATTERN)).toBeNull();
+ });
+
+ it('detects skip markers', () => {
+ const src = `// SKIP: mkdtemp cleanup — special case\nconst d = mkdtemp(join(tmpdir(), 'prefix-'));`;
+ const beforeCall = src.slice(0, src.indexOf('mkdtemp'));
+ expect(SKIP_MARKER.test(beforeCall)).toBe(true);
+ });
+
+ it('detects cleanup mechanisms', () => {
+ const rmSyncSrc = `
+ afterEach(() => {
+ rmSync(tempRoot, { recursive: true, force: true });
+ });
+ `;
+ expect(CLEANUP_PATTERN.test(rmSyncSrc)).toBe(true);
+
+ const destroySrc = `
+ afterEach(async () => {
+ await destroyGitSandbox(scratch);
+ });
+ `;
+ expect(CLEANUP_PATTERN.test(destroySrc)).toBe(true);
+ });
+ });
+});
diff --git a/server/lib/opencodeCatalogCache.test.js b/server/lib/opencodeCatalogCache.test.js
index a11c63bcdd..3d4ba47ffb 100644
--- a/server/lib/opencodeCatalogCache.test.js
+++ b/server/lib/opencodeCatalogCache.test.js
@@ -1,5 +1,6 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';
import { mkdtemp, readFile, utimes } from 'node:fs/promises';
+import { rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -11,6 +12,8 @@ const CATALOG = JSON.stringify({
const respondWith = (body, ok = true) => async () => ({ ok, text: async () => body });
+const tempRoots = [];
+
let cacheHome;
let env;
let cachePath;
@@ -24,10 +27,15 @@ const seedStaleCatalog = async (body = CATALOG) => {
beforeEach(async () => {
cacheHome = await mkdtemp(join(tmpdir(), 'opencode-catalog-'));
+ tempRoots.push(cacheHome);
env = { XDG_CACHE_HOME: cacheHome };
cachePath = join(cacheHome, 'opencode', 'models.json');
});
+afterEach(() => {
+ for (const root of tempRoots.splice(0)) rmSync(root, { recursive: true, force: true });
+});
+
describe('primeOpencodeCatalogCache', () => {
// The path is the whole point: `opencode models` prints from this exact file,
// so a catalog written anywhere else is a catalog the harness never reads.
diff --git a/server/services/agentSentinelSweep.test.js b/server/services/agentSentinelSweep.test.js
index ede9ee141c..dfda606d31 100644
--- a/server/services/agentSentinelSweep.test.js
+++ b/server/services/agentSentinelSweep.test.js
@@ -1,11 +1,13 @@
import { mkdtemp, readdir, utimes, writeFile } from 'fs/promises';
+import { rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
-import { describe, it, expect, beforeEach } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { sweepStaleDoneSentinels, STALE_SENTINEL_MIN_AGE_MS } from './agentSentinelSweep.js';
+const tempRoots = [];
let dir;
/** Write a file and back-date it so the sweep's age floor is satisfied. */
@@ -21,6 +23,11 @@ const OLD = STALE_SENTINEL_MIN_AGE_MS * 2;
beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), 'sentinel-sweep-'));
+ tempRoots.push(dir);
+});
+
+afterEach(() => {
+ for (const root of tempRoots.splice(0)) rmSync(root, { recursive: true, force: true });
});
describe('sweepStaleDoneSentinels', () => {