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: guarantee server test temp cleanup with a run-scoped root (#9032)

[._.]/ Adam Eivyd8439453c3de
diff --git a/scripts/generate_ltx2.test.js b/scripts/generate_ltx2.test.js
index 6bee9e4cc7..33a6d8aaad 100644
--- a/scripts/generate_ltx2.test.js
+++ b/scripts/generate_ltx2.test.js
@@ -1122,9 +1122,15 @@ describe.skipIf(!pyBin)('generate_ltx2.py MLX allocator-cache policy', () => {
};
const installFakePin = (opts = {}) => [
- 'import sys, tempfile',
+ 'import atexit, shutil, sys, tempfile',
'from pathlib import Path',
'root = Path(tempfile.mkdtemp())',
+ // The pin dir must outlive this snippet (later snippets in the same
+ // `-c` invocation import from it), so it can't be removed inline —
+ // clean it when the interpreter exits instead (#9032). Each
+ // installFakePin() call spawns its own `python3 -c ...` process
+ // (runPython -> execFileSync), so this fires once per test.
+ 'atexit.register(shutil.rmtree, root, ignore_errors=True)',
'for pkg in ("ltx_core_mlx", "ltx_core_mlx/conditioning", "ltx_core_mlx/conditioning/types",',
' "ltx_pipelines_mlx", "ltx_pipelines_mlx/utils"):',
' (root / pkg).mkdir(parents=True, exist_ok=True)',
diff --git a/scripts/migrations/353-fable-catalog-model-slug.test.js b/scripts/migrations/353-fable-catalog-model-slug.test.js
index 79f4b6c3a4..0d2670d85b 100644
--- a/scripts/migrations/353-fable-catalog-model-slug.test.js
+++ b/scripts/migrations/353-fable-catalog-model-slug.test.js
@@ -5,10 +5,19 @@ import { join } from 'node:path';
import migration from './353-fable-catalog-model-slug.js';
let rootDir;
-afterEach(async () => { if (rootDir) await rm(rootDir, { recursive: true, force: true }); });
+// A test can call withCatalog() more than once (the "no-op ... on an install
+// with none" case mints a second root to check the missing-catalog path),
+// which reassigns `rootDir` and orphans the previous one — track every root
+// this file has handed out so afterEach removes all of them, not just the
+// last (#9032).
+const rootDirs = [];
+afterEach(async () => {
+ for (const dir of rootDirs.splice(0)) await rm(dir, { recursive: true, force: true });
+});
const withCatalog = async observations => {
rootDir = await mkdtemp(join(tmpdir(), 'fable-slug-migration-'));
+ rootDirs.push(rootDir);
await mkdir(join(rootDir, 'data'));
if (observations) {
await writeFile(join(rootDir, 'data/model-comparison.json'), JSON.stringify({ schemaVersion: 1, observations }));
diff --git a/server/envExampleDrift.test.js b/server/envExampleDrift.test.js
index 956b978174..d530bc17bf 100644
--- a/server/envExampleDrift.test.js
+++ b/server/envExampleDrift.test.js
@@ -102,6 +102,10 @@ const INHERITED_ENV = {
// Test-harness only — setting any of these on a real install is meaningless.
VITEST: 'set by the vitest runner',
+ TMPDIR: 'OS temp-dir convention, pointed at a run-scoped root by vitest.config.js (#9032)',
+ TMP: 'OS temp-dir convention, pointed at a run-scoped root by vitest.config.js (#9032)',
+ TEMP: 'OS temp-dir convention, pointed at a run-scoped root by vitest.config.js (#9032)',
+ PORTOS_TEST_TEMP_ROOT: 'in-process marker so a re-import of vitest.config.js (e.g. vitest.config.test.js) reuses the same run-scoped temp root instead of minting a second one (#9032)',
VITEST_FAST: 'opt-in fast-suite selector, CI/local test runs only',
CI_EXPECT_SLASHDO_SUBMODULE: 'CI flag that turns a skipped slashdo adapter contract into a failure',
TEST_DB_OK: 'test-harness flag for the DB-backed suites',
diff --git a/server/lib/mkdtempCleanup.guards.test.js b/server/lib/mkdtempCleanup.guards.test.js
index 8419f8d73c..7ec6d52a1c 100644
--- a/server/lib/mkdtempCleanup.guards.test.js
+++ b/server/lib/mkdtempCleanup.guards.test.js
@@ -1,6 +1,23 @@
/**
* Test suites that create mkdtemp directories must clean them up.
*
+ * ## This is a cheap hint, not the authority
+ *
+ * This is a static source-text scan (regex over `mkdtemp`/`rmSync` call
+ * sites) — cheap, but blind to a leak driven by a spawned child process, a
+ * fixed-name file, a module-scope root reused across a whole file, or the
+ * file-wide false-negative documented below. #9032 found ~50 such leaks this
+ * scan could not see and added a runner-level guarantee instead: every server
+ * test run gets its own `pvt-*` temp root (`server/vitest.config.js` points
+ * `TMPDIR`/`TMP`/`TEMP` at it before any worker spawns), and
+ * `server/test/runTempRoot.js` (a Vitest `globalSetup`) reports and removes
+ * whatever is left in that root once the whole run finishes, failing the run
+ * on anything unexpected. THAT mechanism is authoritative — it catches every
+ * leak regardless of shape, because a leaked directory has nowhere to escape
+ * to but the run root. This scan remains valuable as fast, IDE-visible
+ * feedback at the exact `mkdtemp` call site the runner-level check can only
+ * report by directory name.
+ *
* ## The bug class
*
* Test suites call `mkdtemp(join(tmpdir(), 'prefix-'))` to create isolated
diff --git a/server/lib/spawnCwd.test.js b/server/lib/spawnCwd.test.js
index 616a7f9da9..8e6eba3a90 100644
--- a/server/lib/spawnCwd.test.js
+++ b/server/lib/spawnCwd.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';
import { posixPath } from './testHelper.js';
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync } from 'fs';
@@ -203,6 +203,15 @@ describe('Creative Director scratch cwd (#4650)', () => {
expect(existsSync(dir)).toBe(false);
await expect(removeCreativeDirectorScratchCwd('agent-cd-rm')).resolves.toBeUndefined();
});
+
+ // removeCreativeDirectorScratchCwd only ever removes the per-agent leaf —
+ // in production the shared `portos-cd-cwd` container is meant to persist
+ // and be reused across runs. In this test file it is a throwaway created
+ // by `mkdirSync(dir, { recursive: true })` above, so clean the container
+ // itself once here (#9032).
+ afterAll(() => {
+ rmSync(join(tmpdir(), 'portos-cd-cwd'), { recursive: true, force: true });
+ });
});
describe('withSpawnCwdEnv', () => {
diff --git a/server/routes/database.test.js b/server/routes/database.test.js
index 44a8bf4063..d8265e113b 100644
--- a/server/routes/database.test.js
+++ b/server/routes/database.test.js
@@ -241,10 +241,16 @@ describe('isPg17OnlyDirective (sed-replacement line filter)', () => {
});
describe('importDumpFile (no-shell streaming import)', () => {
+ const dumpDirs = [];
+
beforeEach(() => {
vi.clearAllMocks();
});
+ afterEach(() => {
+ for (const dir of dumpDirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+ });
+
// Build a fake psql child process backed by real streams. `closeOnKill`
// models a terminated psql emitting 'close' asynchronously; tests that must
// control exactly when the close lands pass false and emit it themselves.
@@ -283,6 +289,7 @@ describe('importDumpFile (no-shell streaming import)', () => {
spawn.mockReturnValue(child);
const dir = mkdtempSync(pathJoin(tmpdir(), 'portos-dump-'));
+ dumpDirs.push(dir);
const dumpPath = pathJoin(dir, 'dump.sql');
writeFileSync(dumpPath,
'\\restrict token\n' +
@@ -320,6 +327,7 @@ describe('importDumpFile (no-shell streaming import)', () => {
spawn.mockReturnValue(child);
const dir = mkdtempSync(pathJoin(tmpdir(), 'portos-dump-'));
+ dumpDirs.push(dir);
const dumpPath = pathJoin(dir, 'dump.sql');
// A lone 0xE9 byte (LATIN1 'é') is NOT valid standalone UTF-8; a utf8
// decode→re-encode would replace it with 0xEFBFBD. Plus a valid multibyte
@@ -344,6 +352,7 @@ describe('importDumpFile (no-shell streaming import)', () => {
spawn.mockReturnValue(child);
const dir = mkdtempSync(pathJoin(tmpdir(), 'portos-dump-'));
+ dumpDirs.push(dir);
const dumpPath = pathJoin(dir, 'dump.sql');
// A CRLF file with a stripped directive line and two data lines. The CR
// bytes on the surviving lines must be preserved.
diff --git a/server/routes/tracks.test.js b/server/routes/tracks.test.js
index c0d7fc82ee..931551529b 100644
--- a/server/routes/tracks.test.js
+++ b/server/routes/tracks.test.js
@@ -71,7 +71,15 @@ vi.mock('../services/pipeline/musicLibrary.js', () => ({
isSupportedMusicUpload: () => true,
assertSafeMusicFilename: (f) => { if (f.includes('..') || f.includes('/')) throw Object.assign(new Error('bad'), { status: 400, code: 'X' }); },
listMusicLibrary: vi.fn(async () => [{ filename: 'music-1.mp3', label: 'theme', sizeBytes: 10, updatedAt: '2026-05-15T00:00:00.000Z' }]),
- importUploadedTrack: vi.fn(async () => ({ filename: 'music-up.mp3', sizeBytes: 11 })),
+ // The real importUploadedTrack copies tempPath into the library then
+ // unlinks it (best-effort) — the route's real (unmocked) multipart parser
+ // stages the upload under the OS temp dir before this is called, so the
+ // mock must consume it the same way or that staged file leaks (#9032).
+ importUploadedTrack: vi.fn(async (tempPath) => {
+ const { rm: rmTemp } = await import('fs/promises');
+ if (tempPath) await rmTemp(tempPath, { force: true }).catch(() => {});
+ return { filename: 'music-up.mp3', sizeBytes: 11 };
+ }),
statMusicTrack: vi.fn(async (f) => (lib.store.has(f) ? { filename: f, label: f, sizeBytes: 10 } : null)),
}));
diff --git a/server/services/agentActivity.test.js b/server/services/agentActivity.test.js
index 8ef59ef48d..f410176b46 100644
--- a/server/services/agentActivity.test.js
+++ b/server/services/agentActivity.test.js
@@ -22,13 +22,18 @@ const writeDay = async (agentId, date, activities) => {
const entry = (id, timestamp) => ({ id, action: 'example', status: 'completed', timestamp });
+// Module-scope, not nested in the first describe below: `cleanup()` removes
+// `tempRoot` itself, and a SECOND describe block (`cleanupOldActivity`)
+// recreates directories under it after that first block's own afterAll
+// would have already fired and removed it — so the root never got a final
+// cleanup that ran after every test in the file (#9032).
+afterAll(cleanup);
+
describe('getActivityTimeline', () => {
beforeEach(async () => {
await rm(activityRoot, { recursive: true, force: true });
});
- afterAll(cleanup);
-
it('continues across midnight into older day files', async () => {
await writeDay('agent-a', '2026-08-23', [entry('new', '2026-08-23T00:01:00.000Z')]);
await writeDay('agent-a', '2026-08-22', [entry('old', '2026-08-22T23:59:00.000Z')]);
diff --git a/server/services/agentFinalization.providerBench.test.js b/server/services/agentFinalization.providerBench.test.js
index 86de7cd2c8..4cffe576cb 100644
--- a/server/services/agentFinalization.providerBench.test.js
+++ b/server/services/agentFinalization.providerBench.test.js
@@ -27,7 +27,7 @@ vi.mock('./codeReview.js', async (importOriginal) => ({
getGoalFidelityConfig: vi.fn(async () => null),
}));
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
vi.mock('../lib/execGit.js', () => ({
execGit: vi.fn(async () => ({ stdout: 'main\n', stderr: '', exitCode: 0 })),
@@ -329,4 +329,16 @@ describe('finalizeAgent — Creative Director scratch cleanup (#4650)', () => {
});
expect(existsSync(dir)).toBe(false);
});
+
+ // finalizeAgent's real cleanup only removes the per-agent leaf — in
+ // production the shared `portos-cd-cwd` container is meant to persist and
+ // be reused across runs. `mkdirSync(dir, { recursive: true })` above also
+ // created that container, so remove it once here (#9032), mirroring
+ // spawnCwd.test.js.
+ afterAll(async () => {
+ const { rmSync } = await import('fs');
+ const { tmpdir } = await import('os');
+ const { join } = await import('path');
+ rmSync(join(tmpdir(), 'portos-cd-cwd'), { recursive: true, force: true });
+ });
});
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 84c42ee66c..8582f40438 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -1695,6 +1695,11 @@ describe('generateManifest', () => {
tmpRoot = await mkdtemp(join(tmpdir(), 'portos-manifest-'));
});
+ afterEach(async () => {
+ const { rm } = await import('fs/promises');
+ await rm(tmpRoot, { recursive: true, force: true });
+ });
+
it('writes the manifest file and returns hashes for every data file', async () => {
const { mkdir, writeFile, readFile } = await import('fs/promises');
const { join } = await import('path');
diff --git a/server/services/cosAgentFeedback.test.js b/server/services/cosAgentFeedback.test.js
index c702302663..80a40e3835 100644
--- a/server/services/cosAgentFeedback.test.js
+++ b/server/services/cosAgentFeedback.test.js
@@ -292,10 +292,6 @@ describe('submitAgentFeedback records the rating (#5594)', () => {
await rm(join(ledgerRoot, 'user-action-events.json'), { force: true });
});
- afterAll(async () => {
- await rm(ledgerRoot, { recursive: true, force: true });
- });
-
it('writes a cos.agent.feedback row with the rating, comment, and derived task type', async () => {
const result = await submitAgentFeedback('agent-1', { rating: 'negative', comment: 'Missed the root cause' });
expect(result).toMatchObject({ success: true });
@@ -404,3 +400,11 @@ describe('pending feedback served from the eligibility projection', () => {
});
});
});
+
+// ledgerRoot is the module-scope mkdtemp root every describe block above
+// shares. Remove it exactly once, after every test in the file has run —
+// nested inside one describe block, its own afterAll would fire before a
+// LATER describe block finishes writing to it (#9032).
+afterAll(async () => {
+ await rm(ledgerRoot, { recursive: true, force: true });
+});
diff --git a/server/services/dashboardLayouts.test.js b/server/services/dashboardLayouts.test.js
index 5bf4135bce..6b1d33f0f6 100644
--- a/server/services/dashboardLayouts.test.js
+++ b/server/services/dashboardLayouts.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync, unlinkSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -34,7 +34,12 @@ describe('dashboardLayouts service', () => {
if (existsSync(STATE_FILE)) unlinkSync(STATE_FILE);
});
- afterEach(() => {});
+ afterAll(() => {
+ // scratch.dir is minted once (vi.hoisted, before this file's mocked
+ // import resolves) and reused across every test in this file — remove
+ // the root itself once here, rather than per-test (#9032).
+ rmSync(scratch.dir, { recursive: true, force: true });
+ });
it('seeds one Actions preview while preserving saved legacy widget IDs and geometry', async () => {
const fresh = await svc.getState();
diff --git a/server/services/idealoomObsidian.test.js b/server/services/idealoomObsidian.test.js
index ab10dad4b5..41aa60e4bc 100644
--- a/server/services/idealoomObsidian.test.js
+++ b/server/services/idealoomObsidian.test.js
@@ -1,4 +1,4 @@
-import { describe, expect, it, beforeEach, vi } from 'vitest';
+import { describe, expect, it, beforeEach, afterAll, vi } from 'vitest';
import { mkdirSync, mkdtempSync, rmSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
@@ -51,6 +51,12 @@ const note = (overrides = {}) => ({
...overrides,
});
+// beforeEach removes the PREVIOUS test's vaultRoot before minting a fresh
+// one, so the LAST test's root is never removed — clean it once here (#9032).
+afterAll(() => {
+ if (vaultRoot) rmSync(vaultRoot, { recursive: true, force: true });
+});
+
beforeEach(() => {
vi.clearAllMocks();
if (vaultRoot) rmSync(vaultRoot, { recursive: true, force: true });
diff --git a/server/services/imageCleanTmpGc.test.js b/server/services/imageCleanTmpGc.test.js
index 86898219a2..3b9ec8a7bb 100644
--- a/server/services/imageCleanTmpGc.test.js
+++ b/server/services/imageCleanTmpGc.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeEach, afterAll } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync, existsSync, utimesSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
@@ -10,8 +10,9 @@ beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'portos-cleantmp-gc-test-'));
});
-afterAll(() => {
- // beforeEach makes a fresh dir per test; clean the last one.
+afterEach(() => {
+ // beforeEach makes a fresh dir per test; clean each one (#9032 — afterAll
+ // only removed the LAST dir, leaking one per prior test).
if (dir) rmSync(dir, { recursive: true, force: true });
});
diff --git a/server/services/imageGenQuota.test.js b/server/services/imageGenQuota.test.js
index 24b489be0b..b434b6de08 100644
--- a/server/services/imageGenQuota.test.js
+++ b/server/services/imageGenQuota.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';
import { mkdtemp, rm, writeFile } from 'fs/promises';
import { join } from 'path';
import { tmpdir } from 'os';
@@ -47,6 +47,14 @@ afterEach(async () => {
await rm(join(TEST_ROOT, 'imagegen-quota.json'), { force: true });
});
+// TEST_ROOT / FAB_DIR are module-scope roots (top-level-await mkdtemp, before
+// any per-test hook runs) — remove the roots themselves once, not just the
+// file inside TEST_ROOT the per-test hooks above clean (#9032).
+afterAll(async () => {
+ await rm(TEST_ROOT, { recursive: true, force: true });
+ await rm(FAB_DIR, { recursive: true, force: true });
+});
+
describe('parseImageQuotaSignal', () => {
it('reads the exact 429 the imagen backend returned', () => {
const signal = parseImageQuotaSignal(AGY_429, { now: FIXTURE_NOW });
diff --git a/server/services/jira.test.js b/server/services/jira.test.js
index d31b9747e4..53c405f144 100644
--- a/server/services/jira.test.js
+++ b/server/services/jira.test.js
@@ -1,9 +1,16 @@
import fs from 'fs/promises';
-import { describe, it, expect, vi, afterEach } from 'vitest';
+import { rmSync } from 'fs';
+import { describe, it, expect, vi, afterEach, afterAll } from 'vitest';
import { createTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
const tempRoot = createTempDataRoot('portos-jira-');
+// createTempDataRoot documents "caller is responsible for cleanup" — this
+// file never removed its root (#9032).
+afterAll(() => {
+ rmSync(tempRoot, { recursive: true, force: true });
+});
+
vi.mock('../lib/fileUtils.js', async () => {
const actual = await vi.importActual('../lib/fileUtils.js');
return makePathsProxy(actual, { dataRoot: tempRoot });
diff --git a/server/services/lmStudioManager.test.js b/server/services/lmStudioManager.test.js
index 2ad8b77eeb..eced94e6dd 100644
--- a/server/services/lmStudioManager.test.js
+++ b/server/services/lmStudioManager.test.js
@@ -498,12 +498,18 @@ describe('lmStudioManager.loadModelWithArgs', () => {
// that made `getStatus()` report an installed LM Studio as "Not installed" and
// offer to install it again.
describe('isAppInstalled', () => {
+ const homeDirs = [];
const home = () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'portos-lms-home-'));
+ homeDirs.push(dir);
fakeHome.path = dir;
return dir;
};
+ afterEach(() => {
+ for (const dir of homeDirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
+ });
+
it('counts an LM Studio home directory as installed on any platform', async () => {
fs.mkdirSync(path.join(home(), '.lmstudio'), { recursive: true });
const { isAppInstalled } = await import('./lmStudioManager.js');
diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.js
index a00d916238..df042bb069 100644
--- a/server/services/localLlm.test.js
+++ b/server/services/localLlm.test.js
@@ -854,6 +854,20 @@ describe('localLlm', () => {
const APP = '/Applications/Ollama.app';
const aside = () => [...appFs.entries.keys()].filter((p) => p.startsWith(`${APP}.portos-old-`));
+ // The download + extract steps in upgradeBackend() are real fs/pipeline
+ // code (only `cp.spawn` and `fetch` are stubbed), and a failed mv/install
+ // deliberately KEEPS its `portos-ollama-upgrade-<ts>` dir — the downloaded
+ // bundle is the user's only way to finish the upgrade by hand in
+ // production. This test uses the real `os.tmpdir()`, so sweep any such
+ // dirs this describe block created after each test (#9032).
+ afterEach(() => {
+ for (const name of fs.readdirSync(os.tmpdir())) {
+ if (name.startsWith('portos-ollama-upgrade-')) {
+ fs.rmSync(path.join(os.tmpdir(), name), { recursive: true, force: true });
+ }
+ }
+ });
+
// Runs the .app path end to end with every shell-out stubbed. `mv` mutates the
// in-memory /Applications model the way the real one would, so the assertions
// can read the resulting filesystem shape.
diff --git a/server/services/modelCapabilityTests.test.js b/server/services/modelCapabilityTests.test.js
index f38adc077b..d746957093 100644
--- a/server/services/modelCapabilityTests.test.js
+++ b/server/services/modelCapabilityTests.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';
import { mkdtemp, readFile, rm, writeFile } from 'fs/promises';
import { join } from 'path';
import { tmpdir } from 'os';
@@ -95,6 +95,13 @@ afterEach(async () => {
await rm(join(TEST_ROOT, 'model-tests'), { recursive: true, force: true });
});
+// TEST_ROOT is a module-scope root (top-level-await mkdtemp, before any
+// per-test hook runs) — remove the root itself once, not just the
+// subdirectories the per-test hooks above clean (#9032).
+afterAll(async () => {
+ await rm(TEST_ROOT, { recursive: true, force: true });
+});
+
describe('resolveModelCapabilities', () => {
it('keeps "the runtime reported nothing" distinct from "the model claims nothing"', async () => {
// A bare endpoint reports ids only — unknown, so tests stay on offer.
diff --git a/server/services/mtplxServerManager.test.js b/server/services/mtplxServerManager.test.js
index 9810b41f5e..8b50ac1114 100644
--- a/server/services/mtplxServerManager.test.js
+++ b/server/services/mtplxServerManager.test.js
@@ -1,7 +1,7 @@
import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';
import {
getMtplxServerStatus,
startMtplxServer,
@@ -405,7 +405,10 @@ describe('mtplxServerManager', () => {
describe('relaunchMtplxServerWithTuning', () => {
beforeEach(() => {
vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);
- resetForTest();
+ resetForTest({ logFiles: {
+ stdout: join(testLogDir, 'portos-mtplx-out.log'),
+ stderr: join(testLogDir, 'portos-mtplx-error.log'),
+ } });
});
// Readiness is what the caller's `applied: true` means, so most cases need
@@ -853,7 +856,10 @@ describe('mtplxServerManager', () => {
// A lazy start that never answers waits out the READINESS budget, not the
// startup one — five real minutes by default. Shorten it here rather than
// in the shared setup, which the give-up-path tests below depend on.
- resetForTest();
+ resetForTest({ logFiles: {
+ stdout: join(testLogDir, 'portos-mtplx-out.log'),
+ stderr: join(testLogDir, 'portos-mtplx-error.log'),
+ } });
});
it('is a no-op when the daemon is already online', async () => {
@@ -1048,4 +1054,18 @@ describe('mtplxServerManager', () => {
});
});
+ // Every test routes real log writes through testLogDir (cleaned above), but
+ // a `_resetMtplxServerStateForTests()` call with no `logFiles` falls back to
+ // the module's DEFAULT_MTPLX_LOG_FILES (a fixed `tmpdir()` path, not an
+ // mkdtemp root) — including the outer afterEach's own unconditional reset,
+ // and an idle-reaper/watchdog callback that can still be in flight when a
+ // test's assertions finish. Remove the DEFAULT path once here so a race
+ // against that fallback never leaves the fixed-name files behind (#9032).
+ afterAll(async () => {
+ const { rm: rmDefaults } = await import('fs/promises');
+ const { tmpdir: realTmpdir } = await import('os');
+ const { join: joinPath } = await import('path');
+ await rmDefaults(joinPath(realTmpdir(), 'portos-mtplx-out.log'), { force: true });
+ await rmDefaults(joinPath(realTmpdir(), 'portos-mtplx-error.log'), { force: true });
+ });
});
diff --git a/server/services/pipeline/coverFilenameHooks.integration.test.js b/server/services/pipeline/coverFilenameHooks.integration.test.js
index bf3d4251a1..7a6c761b35 100644
--- a/server/services/pipeline/coverFilenameHooks.integration.test.js
+++ b/server/services/pipeline/coverFilenameHooks.integration.test.js
@@ -8,7 +8,7 @@
* handlers run inside a `void (async () => {})` IIFE, so each test waits
* for the post-emit side effect rather than awaiting the handler.
*/
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';
import { mkdtempSync, rmSync, mkdirSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -108,6 +108,14 @@ afterEach(() => {
comicHook.__testing.reset();
});
+// tempData is minted once (module scope) and reused across every test in
+// this file — beforeEach only wipes-and-recreates it, so the LAST test's
+// contents (and the root itself) are never removed. Clean it once here
+// (#9032).
+afterAll(() => {
+ rmSync(tempData, { recursive: true, force: true });
+});
+
describe('seasonCoverFilenameHook — universe collection auto-file', () => {
it('files the cover into the universe collection when the active jobId still matches', async () => {
const universeId = 'u-season-1';
diff --git a/server/services/pipeline/musicGen.test.js b/server/services/pipeline/musicGen.test.js
index f1611d0ece..de191ec505 100644
--- a/server/services/pipeline/musicGen.test.js
+++ b/server/services/pipeline/musicGen.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';
import { tmpdir, platform as osPlatform, arch as osArch } from 'os';
import { join } from 'path';
import { rm, readdir } from 'fs/promises';
@@ -521,6 +521,13 @@ afterEach(async () => {
}
});
+// TEST_DIR (h.testDir) is a module-scope mkdtemp root reused across every
+// test in this file — the per-test afterEach above only empties it, so
+// remove the root itself once here (#9032).
+afterAll(async () => {
+ await rm(TEST_DIR, { recursive: true, force: true }).catch(() => {});
+});
+
describe('generateMusic backend selection', () => {
it('defaults to the musicgen sidecar', async () => {
const res = await generateMusic({ prompt: 'calm piano' });
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index 31ba3f2263..a788394fad 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -8,7 +8,7 @@
* local record updated and `overridden` populated.
*/
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync, existsSync, mkdirSync, readFileSync, statSync, utimesSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -108,6 +108,13 @@ describe('sharing round-trip', () => {
if (tempBucket) rmSync(tempBucket, { recursive: true, force: true });
});
+ // tempData is minted once (module scope) and reused across every test in
+ // this file — beforeEach only wipes-and-recreates it, so the LAST test's
+ // root is never removed. Clean it once here (#9032).
+ afterAll(() => {
+ rmSync(tempData, { recursive: true, force: true });
+ });
+
it('preserves local video holds while importing bundled media-job records', async () => {
const bucket = await buckets.createBucket({ name: 'Example Bucket', path: tempBucket, mode: 'inbox' });
const local = { id: 'retained-local', kind: 'video', status: 'queued', params: { modelId: 'example-video' } };
diff --git a/server/services/sharing/peerSyncAssets.concurrency.test.js b/server/services/sharing/peerSyncAssets.concurrency.test.js
index a9b65c02e1..49dcaaf695 100644
--- a/server/services/sharing/peerSyncAssets.concurrency.test.js
+++ b/server/services/sharing/peerSyncAssets.concurrency.test.js
@@ -5,7 +5,7 @@
* peers advertising the same filename both pass it; the destination-keyed
* `assetWriteQueue` is what serializes them.
*/
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';
import { mkdtempSync, rmSync, readFileSync, mkdirSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -13,6 +13,7 @@ import { createHash } from 'crypto';
import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';
let tempRoot = mkdtempSync(join(tmpdir(), 'portos-asset-race-boot-'));
+const bootRoot = tempRoot;
vi.mock('../../lib/fileUtils.js', async () => {
const actual = await vi.importActual('../../lib/fileUtils.js');
@@ -164,3 +165,11 @@ describe('#3929 — syncMediaLibraryWithAllPeers global re-entrancy guard', () =
expect(await syncMediaLibraryWithAllPeers()).toEqual({ peers: 2 });
});
});
+
+// bootRoot is the module-scope placeholder mkdtemp'd before any hook runs
+// (needed so the mocked PATHS.data resolves before the dynamic import below
+// evaluates) — once the first describe block's beforeEach reassigns
+// `tempRoot`, nothing else references it. Remove it once here (#9032).
+afterAll(() => {
+ rmSync(bootRoot, { recursive: true, force: true });
+});
diff --git a/server/services/sharing/peerSyncAssets.test.js b/server/services/sharing/peerSyncAssets.test.js
index 3ba025bd20..9517f30527 100644
--- a/server/services/sharing/peerSyncAssets.test.js
+++ b/server/services/sharing/peerSyncAssets.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -9,6 +9,7 @@ import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';
// pulls in modules that read PATHS.data at module-evaluation time, so the
// proxy's dataRoot getter must already resolve to a string.
let tempRoot = mkdtempSync(join(tmpdir(), 'portos-mv-assets-boot-'));
+const bootRoot = tempRoot;
vi.mock('../../lib/fileUtils.js', async () => {
const actual = await vi.importActual('../../lib/fileUtils.js');
@@ -563,3 +564,11 @@ describe('pullMissingAssetsFromPeer — unsafe and incomplete downloads (#5230)'
expect(listAssetFiles('audio')).toEqual(['shared.mp3']);
});
});
+
+// bootRoot is the module-scope placeholder mkdtemp'd before any hook runs
+// (needed so the mocked PATHS.data resolves before the dynamic import below
+// evaluates) — once the first describe block's beforeEach reassigns
+// `tempRoot`, nothing else references it. Remove it once here (#9032).
+afterAll(() => {
+ rmSync(bootRoot, { recursive: true, force: true });
+});
diff --git a/server/services/sharing/peerSyncAssets.videoThumbnail.test.js b/server/services/sharing/peerSyncAssets.videoThumbnail.test.js
index 92670264a4..fa74239031 100644
--- a/server/services/sharing/peerSyncAssets.videoThumbnail.test.js
+++ b/server/services/sharing/peerSyncAssets.videoThumbnail.test.js
@@ -11,7 +11,7 @@
* for a stitched timeline final (`timeline-<slice>-<ts>.mp4` beside an
* independent `randomUUID()` history id).
*/
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';
import { mkdtempSync, rmSync, mkdirSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -19,6 +19,7 @@ import { createHash } from 'crypto';
import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';
let tempRoot = mkdtempSync(join(tmpdir(), 'portos-vthumb-boot-'));
+const bootRoot = tempRoot;
vi.mock('../../lib/fileUtils.js', async () => {
const actual = await vi.importActual('../../lib/fileUtils.js');
@@ -183,3 +184,11 @@ describe('#4162 — pulled-video thumbnail naming + arrival event', () => {
expect(arrivals.map((a) => a.filename)).toEqual(['timeline-cafebabe-1700000000002.mp4']);
});
});
+
+// bootRoot is the module-scope placeholder mkdtemp'd before any hook runs
+// (needed so the mocked PATHS.data resolves before the dynamic import below
+// evaluates) — once the first describe block's beforeEach reassigns
+// `tempRoot`, nothing else references it. Remove it once here (#9032).
+afterAll(() => {
+ rmSync(bootRoot, { recursive: true, force: true });
+});
diff --git a/server/services/sharing/subscriptions.test.js b/server/services/sharing/subscriptions.test.js
index 9d40aef924..0329d0851e 100644
--- a/server/services/sharing/subscriptions.test.js
+++ b/server/services/sharing/subscriptions.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';
import { mkdtempSync, rmSync, mkdirSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -47,6 +47,13 @@ describe('sharing/subscriptions', () => {
if (tempBucket) rmSync(tempBucket, { recursive: true, force: true });
});
+ // tempData is minted once (module scope) and reused across every test in
+ // this file — beforeEach only wipes-and-recreates it, so the LAST test's
+ // root is never removed. Clean it once here (#9032).
+ afterAll(() => {
+ rmSync(tempData, { recursive: true, force: true });
+ });
+
it('subscribe creates a subscription and writes a deterministic-named manifest', async () => {
const bucket = await buckets.createBucket({ name: 'B', path: tempBucket, mode: 'inbox' });
const u = await universeBuilder.createUniverse({ name: 'U1' });
diff --git a/server/services/slotstreamServerManager.test.js b/server/services/slotstreamServerManager.test.js
index 1b2cbaa519..c318cbf06e 100644
--- a/server/services/slotstreamServerManager.test.js
+++ b/server/services/slotstreamServerManager.test.js
@@ -1,7 +1,7 @@
import { mkdir, mkdtemp, rm, writeFile } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';
// The manager reaches settings through a dynamic `import('./settings.js')` for
// both the saved launch line and the idle window. Backing it with an in-memory
@@ -384,4 +384,19 @@ describe('slotstreamServerManager', () => {
expect(await slotstreamCachedModelIds(local)).toBeNull();
});
});
+
+ // Every test routes real log writes through testLogDir (cleaned above), but
+ // a `_resetSlotstreamServerStateForTests()` call with no `logFiles` falls
+ // back to the module's fixed DEFAULT `tmpdir()` path (not an mkdtemp root)
+ // — including a reset that races an idle-reaper/watchdog callback still in
+ // flight when a test's assertions finish. Remove the DEFAULT path once here
+ // so that race never leaves the fixed-name files behind (#9032), mirroring
+ // mtplxServerManager.test.js.
+ afterAll(async () => {
+ const { rm: rmDefaults } = await import('fs/promises');
+ const { tmpdir: realTmpdir } = await import('os');
+ const { join: joinPath } = await import('path');
+ await rmDefaults(joinPath(realTmpdir(), 'portos-slotstream-out.log'), { force: true });
+ await rmDefaults(joinPath(realTmpdir(), 'portos-slotstream-error.log'), { force: true });
+ });
});
diff --git a/server/services/universeBuilderCollectionHook.test.js b/server/services/universeBuilderCollectionHook.test.js
index 673f21eecd..9a343688fe 100644
--- a/server/services/universeBuilderCollectionHook.test.js
+++ b/server/services/universeBuilderCollectionHook.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';
import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -95,6 +95,13 @@ describe('universeBuilderCollectionHook', () => {
hook.__testing.reset();
});
+ // tempData is minted once (module scope) and reused across every test in
+ // this file — beforeEach only wipes-and-recreates it, so the LAST test's
+ // root is never removed. Clean it once here (#9032).
+ afterAll(() => {
+ rmSync(tempData, { recursive: true, force: true });
+ });
+
async function makeCollection(universeId) {
return collections.findOrCreateCollectionByName({
name: `c-${Math.random().toString(36).slice(2, 8)}`,
diff --git a/server/services/videoGen/generateVideoHelpers.test.js b/server/services/videoGen/generateVideoHelpers.test.js
index c7cfcc2e54..87d5d8f58b 100644
--- a/server/services/videoGen/generateVideoHelpers.test.js
+++ b/server/services/videoGen/generateVideoHelpers.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
import { writeFileSync, rmSync, mkdirSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -776,6 +776,12 @@ describe('verifyPostCompletionOutputs', () => {
probeMock.duration.mockResolvedValue(EXPECTED_FRAMES / FPS);
});
+ // beforeEach removes-then-recreates `dir` before each test, so the LAST
+ // test's directory is never removed — clean it once after the suite (#9032).
+ afterAll(() => {
+ rmSync(dir, { recursive: true, force: true });
+ });
+
it('accepts an exact match', async () => {
await expect(verify()).resolves.toEqual({ ok: true });
});
diff --git a/server/test/runTempRoot.js b/server/test/runTempRoot.js
new file mode 100644
index 0000000000..63c3817fa7
--- /dev/null
+++ b/server/test/runTempRoot.js
@@ -0,0 +1,111 @@
+/**
+ * Vitest globalSetup — the other half of the run-scoped temp root (#9032).
+ *
+ * `server/vitest.config.js` creates a run-scoped `mkdtempSync` root and
+ * points `TMPDIR`/`TMP`/`TEMP` at it, at config-load time, before any worker
+ * spawns. `os.tmpdir()` reads those env vars dynamically, so every call in
+ * this process, in a forked worker (workers inherit `process.env` unless a
+ * suite overrides it), or in any spawned child that inherits `process.env`
+ * (Python's `tempfile` module, `ffmpeg`, `git`) resolves inside that root
+ * instead of the host's real temp directory — a leaked directory can no
+ * longer escape into `$TMPDIR` no matter which file left it behind.
+ *
+ * This module is that root's lifecycle manager as a Vitest `globalSetup`:
+ * it runs once in the main process, before test collection starts and again
+ * once after every test has finished (see
+ * https://vitest.dev/config/#globalsetup). `setup()` has nothing to do — the
+ * root already exists by the time this loads. `teardown()` reports and
+ * removes whatever is still sitting in the root: this is the STRICT check
+ * the issue asks for — once every per-file leaker in the tree is fixed, any
+ * new leak fails the run instead of silently reappearing in $TMPDIR.
+ */
+import { readdirSync, rmSync } from 'node:fs';
+
+export function setup() {
+ // No-op: server/vitest.config.js already created the root and pointed
+ // TMPDIR/TMP/TEMP at it before this module loaded.
+}
+
+// Vitest itself keeps a per-run module-transform scratch dir under
+// os.tmpdir() (vite-node's SSR/module fetch cache — `join(tmpdir(), nanoid())`
+// in vitest's own source) and removes it via `project.close()` -> `clearTmpDir
+// ()`. That close() call happens AFTER `_teardownGlobalSetup()` runs (see
+// vitest's `Vitest.close()`), so this module's own teardown always observes
+// it as still present — not a leak from PortOS test code, just an ordering
+// artifact of two independent teardown sequences. nanoid()'s default alphabet
+// (`A-Za-z0-9_-`) and length (21) make a false-negative collision with a real
+// PortOS leak (which always mkdtemps with a human-readable `prefix-` name)
+// effectively impossible, so entries matching it are excluded from the
+// report — the root-level rmSync below still removes them either way.
+const VITEST_INTERNAL_SCRATCH_DIR = /^[A-Za-z0-9_-]{21}$/;
+
+// A handful of PortOS's own provider-availability tests spawn a REAL,
+// installed third-party CLI (kilo, opencode, …) when one is present on the
+// developer's PATH (`hasCli()`-style gates) — a binary that then writes its
+// OWN scratch/cache state (a config dir, a Node module compile cache, …)
+// into whatever TMPDIR it inherits, which since this file is our run root.
+// That state is not a PortOS temp-file leak — it belongs to the third-party
+// tool, only appears on a machine that actually has the tool installed
+// (invisible in CI, where those tests are gated off), and fixing it means
+// giving each such CLI invocation its own isolated cache dir, tracked in
+// #9039. Reported for visibility but never fails the run — unlike an
+// unrecognized name, which still does.
+const KNOWN_THIRD_PARTY_CLI_SCRATCH = new Set(['kilo', 'opencode', 'escape', 'node-compile-cache']);
+
+/**
+ * Groups a leaked entry's basename by its mkdtemp call site as closely as a
+ * cheap heuristic can: mkdtemp appends a short random alphanumeric suffix
+ * directly after the prefix a caller passed in, so stripping a trailing run
+ * of 6+ alphanumeric characters recovers the prefix, e.g.
+ * `portos-dump-a1b2c3` -> `portos-dump-`. Fixed-name files (`*-out.log`)
+ * pass through unchanged and are reported individually. Exported for the
+ * regression test.
+ */
+export function groupLeakPrefix(name) {
+ return name.replace(/[0-9a-zA-Z]{6,}$/, '') || name;
+}
+
+export function teardown() {
+ const root = process.env.TMPDIR;
+ if (!root) return;
+
+ let entries = [];
+ try {
+ entries = readdirSync(root);
+ } catch {
+ // Root was never created (config didn't run, e.g. a unit test of this
+ // module) or was already removed — nothing to report or clean.
+ return;
+ }
+
+ entries = entries.filter((name) => !VITEST_INTERNAL_SCRATCH_DIR.test(name));
+
+ if (entries.length > 0) {
+ const byPrefix = new Map();
+ for (const name of entries) {
+ const prefix = groupLeakPrefix(name);
+ byPrefix.set(prefix, (byPrefix.get(prefix) || 0) + 1);
+ }
+ let hasUnknownLeak = false;
+ for (const [prefix, count] of byPrefix) {
+ const knownThirdParty = KNOWN_THIRD_PARTY_CLI_SCRATCH.has(prefix);
+ if (!knownThirdParty) hasUnknownLeak = true;
+ console.warn(`⚠️ test temp leak: ${prefix} ×${count}${knownThirdParty ? ' (known third-party CLI scratch, see #9039)' : ''}`);
+ }
+ // Strict mode (#9032): a leftover entry means some suite wrote outside
+ // its own cleanup path. Fail the run so a new leaker is caught locally
+ // and in CI instead of quietly growing $TMPDIR — the run root itself is
+ // still removed below either way, so the failure never reaches the
+ // host's real temp directory. A KNOWN_THIRD_PARTY_CLI_SCRATCH entry is
+ // still reported (so it does not silently balloon) but does not fail
+ // the run — see that constant's comment.
+ if (hasUnknownLeak) process.exitCode = 1;
+ }
+
+ try {
+ rmSync(root, { recursive: true, force: true });
+ } catch {
+ // Best-effort — a lingering open handle on a worker that hasn't fully
+ // exited yet must not crash teardown and mask the leak report above.
+ }
+}
diff --git a/server/vitest.config.js b/server/vitest.config.js
index 47ab4a651a..7fc1fc776c 100644
--- a/server/vitest.config.js
+++ b/server/vitest.config.js
@@ -1,4 +1,7 @@
import { defineConfig } from 'vitest/config';
+import { mkdtempSync, readdirSync, rmSync, statSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import { vitestCiPool } from '../scripts/vitestCiPool.js';
import { DB_TEST_INCLUDE } from './vitest.config.db.js';
@@ -8,6 +11,77 @@ if (process.env.npm_lifecycle_event === 'test:fast') {
process.env.VITEST_FAST = '1';
}
+// Run-scoped temp root (#9032). #9000 added the static `mkdtempCleanup.guards
+// .test.js` scan, and #9009 documented it as file-wide (any rmSync anywhere in
+// a file satisfies it for every mkdtemp call in that file) — a heuristic that
+// cannot see a leak driven by a spawned child process, a fixed-name log file,
+// or a partially-cleaned file. Rather than chasing more static patterns, give
+// every mkdtemp/tmpdir() call in the run nowhere to leak TO: create one root
+// for the whole run, in the REAL host tmpdir, and point TMPDIR/TMP/TEMP at it
+// before any worker spawns. `os.tmpdir()` reads those env vars dynamically —
+// in this process, in a forked worker (workers inherit process.env), and in
+// any spawned child that inherits process.env (Python's tempfile module,
+// ffmpeg, git) — so every one of those calls resolves inside the root instead
+// of the host's real temp directory. `server/test/runTempRoot.js` (wired
+// below as globalSetup) is the other half: it reports and removes whatever is
+// left in the root after the run.
+//
+// Stale-root sweep: remove `pvt-*` roots older than 6 hours from a PAST run
+// that was killed before its teardown ran (a killed CoS agent, a crashed
+// worker) — using the REAL tmpdir, before this run's own TMPDIR override
+// below. A root from a run that is still in flight (started recently, by
+// definition) survives; only the age check matters, not which process it
+// belongs to, since two runs never share a root path.
+// Idempotency guard: `server/vitest.config.test.js` (and any other suite
+// that asserts on this file's own NODE_ENV-forcing behavior) dynamically
+// re-imports this module after `vi.resetModules()`, re-running every
+// top-level statement — including the mkdtempSync below — even though a real
+// `vitest run` only ever loads this config once. Without a guard, each of
+// those re-imports mints and abandons its OWN "pvt-*" root (nobody's
+// globalSetup teardown owns it), which is itself a leak this same change is
+// fixing (#9032). `process.env.PORTOS_TEST_TEMP_ROOT` marks that this
+// process already has a run root; reuse it instead of minting another.
+const REAL_TMPDIR = tmpdir();
+let RUN_TEMP_ROOT = process.env.PORTOS_TEST_TEMP_ROOT;
+
+if (!RUN_TEMP_ROOT) {
+ // Stale-root sweep: remove `pvt-*` roots older than 6 hours from a PAST run
+ // that was killed before its teardown ran (a killed CoS agent, a crashed
+ // worker) — using the REAL tmpdir, before this run's own TMPDIR override
+ // below. A root from a run that is still in flight (started recently, by
+ // definition) survives; only the age check matters, not which process it
+ // belongs to, since two runs never share a root path.
+ const STALE_ROOT_AGE_MS = 6 * 60 * 60 * 1000;
+ try {
+ const now = Date.now();
+ for (const name of readdirSync(REAL_TMPDIR)) {
+ if (!name.startsWith('pvt-')) continue;
+ const path = join(REAL_TMPDIR, name);
+ try {
+ const stat = statSync(path);
+ if (stat.isDirectory() && now - stat.mtimeMs > STALE_ROOT_AGE_MS) {
+ rmSync(path, { recursive: true, force: true });
+ }
+ } catch {
+ // Already gone, or a permissions/race hiccup — never fail config load
+ // over a best-effort sweep of someone else's stale root.
+ }
+ }
+ } catch {
+ // REAL_TMPDIR unreadable — skip the sweep rather than fail config load.
+ }
+
+ // Short prefix: Unix-socket tests (e.g. services/itermBridge.test.js) build
+ // a `join(tmpdir(), 'prefix-XXXXXX', 'name.sock')` path, and macOS caps
+ // `sockaddr_un.sun_path` at 104 bytes — a long run-root prefix nested under
+ // another temp dir could push a legitimate socket path over that limit.
+ RUN_TEMP_ROOT = mkdtempSync(join(REAL_TMPDIR, 'pvt-'));
+ process.env.PORTOS_TEST_TEMP_ROOT = RUN_TEMP_ROOT;
+}
+process.env.TMPDIR = RUN_TEMP_ROOT;
+process.env.TMP = RUN_TEMP_ROOT;
+process.env.TEMP = RUN_TEMP_ROOT;
+
// The suite REQUIRES NODE_ENV=test: it is what selects the file storage backend
// (memoryBackend.js and every store facade) so no suite talks to the real
// Postgres. Vitest only DEFAULTS NODE_ENV to 'test' when it is unset, and PortOS
@@ -25,7 +99,12 @@ export default defineConfig({
test: {
...vitestCiPool(),
// Workers get their own process.env — set it there as well as above.
- env: { NODE_ENV: 'test' },
+ env: {
+ NODE_ENV: 'test',
+ TMPDIR: RUN_TEMP_ROOT,
+ TMP: RUN_TEMP_ROOT,
+ TEMP: RUN_TEMP_ROOT,
+ },
// 30s on every platform (#7951). This WAS 10s off Windows, and the split
// has always been a fiction: the cost it budgets for is vitest's transform
// pipeline, which is slower on Windows but not cheap anywhere. Measured on
@@ -153,5 +232,10 @@ export default defineConfig({
// Global setup: mocks getPeers → [] so test-created records never fan out
// to live sync peers. Per-suite vi.mock('./instances.js', …) overrides win.
setupFiles: ['./vitest.setup.js'],
+ // Runs once in the main process, before any worker starts and again once
+ // after the whole run finishes (unlike setupFiles, which runs per test
+ // file, per worker). Reports and removes whatever is left in
+ // RUN_TEMP_ROOT once every test has finished (#9032).
+ globalSetup: ['./test/runTempRoot.js'],
}
});