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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: drain cancelled duplicate-detection test writes before removing fixtures (#9635)
Adam Eivy1209f2a78320
diff --git a/scripts/duplicateDetectionCleanup.test.js b/scripts/duplicateDetectionCleanup.test.jsnew file mode 100644index 0000000000..6d08ab4dc5--- /dev/null+++ b/scripts/duplicateDetectionCleanup.test.js@@ -0,0 +1,55 @@+import { expect, it } from 'vitest';+import { spawnSync } from 'node:child_process';+import { mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { createVitestTempFixture } from './lib/vitestTempRootFixture.js';++// Pins the regression uniquely: a different worker's --bail=1 failure cancels a+// duplicate-detection test while its body still owns store writes into the+// fixture root, which the suite's teardown must not remove underneath it.+it('drains duplicate-detection fixture writes after another worker triggers fail-fast', () => {+ const host = mkdtempSync(join(tmpdir(), 'dd-cancel-'));+ try {+ const fixture = join(host, 'fixture');+ const ready = join(fixture, 'ready');+ const finished = join(fixture, 'finished');+ const { args, options } = createVitestTempFixture(host, 'server', '');+ const sourcePath = fileURLToPath(new URL('../server/services/duplicateDetection.test.js', import.meta.url));+ const header = "it('reports linkedSeriesCount per universe', async () => {";+ const source = readFileSync(sourcePath, 'utf8')+ .replace(/(['"])(\.\.?\/[^'"]+)\1/g, (_, quote, specifier) => JSON.stringify(resolve(dirname(sourcePath), specifier)))+ .replace(header, `${header.replace('async () =>', 'async ({ signal }) =>')}+ const { writeFileSync } = await import('node:fs');+ const cancelled = new Promise(resolve => signal.addEventListener('abort', () => setImmediate(resolve), { once: true }));+ writeFileSync(${JSON.stringify(ready)}, 'ready');+ await cancelled;+ const interrupted = await universeSvc.createUniverse({ name: 'Interrupted' });+ await seriesSvc.createSeries({ name: 'Interrupted series', universeId: interrupted.id });+ writeFileSync(${JSON.stringify(finished)}, 'finished');+ return;`);+ expect(source).toContain('await cancelled;');+ writeFileSync(join(fixture, 'lifecycle.test.js'), source);+ writeFileSync(join(fixture, 'failure.test.js'), `+ import { it, expect } from 'vitest';+ import { existsSync } from 'node:fs';+ it('controlled sibling failure', async () => {+ await expect.poll(() => existsSync(${JSON.stringify(ready)}), { timeout: 10000 }).toBe(true);+ throw new Error('controlled sibling failure');+ });+ `);+ const workerIndex = args.indexOf('--maxWorkers');+ args[workerIndex + 1] = '2';+ args.push('--bail=1');+ const result = spawnSync(process.execPath, args, options);+ const output = `${result.stdout}\n${result.stderr}`;+ expect(result.error).toBeUndefined();+ expect(result.status, output).toBe(1);+ expect(output).toContain('controlled sibling failure');+ expect(existsSync(finished), output).toBe(true);+ expect(output).not.toMatch(/ENOTEMPTY|ENOENT|Unhandled|test temp leak:/);+ } finally {+ rmSync(host, { recursive: true, force: true });+ }+}, 25000);diff --git a/server/lib/README.md b/server/lib/README.mdindex db8f961bb5..a53dc85374 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -734,7 +734,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `dbTestGate.js` | `requireDbOrSkip(label, dbReady, reason)` keeps a missing local test database as a visible skipped suite, but throws when `PORTOS_REQUIRE_DB` is set so CI cannot pass after DB-backed suites disappear. || `gitTestRepo.js` | Shared real-git sandbox for integration tests (#4394): one initialized template (working tree + bare origin) per worker, then `fs.cp` into a fresh temp dir. `makeGitSandbox({ origin })`, `attachBareOrigin(scratch, repo)`, `materializeGitRepo(dest)`, `destroyGitSandbox`, plus `SKIP_HEAVY_INTEGRATION` (`VITEST_FAST=1`). `resetGitSandbox({ scratch, repo, initialHead })` / `resetGitWorktreeSandbox(repo, initialHead)` restore a sandbox in place (branches, worktrees, remote) so a `describe` can build one sandbox in `beforeAll` and reset between tests instead of paying the fs.cp/rm cycle per test (#5902). Every entry point runs `assertTempPath` first, so a path outside `os.tmpdir()` throws instead of `git init`-ing or `rm -rf`-ing a real checkout (#4554). Still real git — just not rebuilt from `init`+`commit`+`push` in every `beforeEach`. || `mirrorParity.js` | Source-extraction and comparison primitives for declaration-level contract tests: the vendored `aiToolkit/` copy of `TOOL_USE_RE` (`localModelHeuristics.mirror.test.js`), and the bootstrap sequence's body assertions (`bootstrap*.test.js`). A pure module the browser needs is imported by the client rather than mirrored, so no client↔server copy test should need these: `stripCommentsAndNormalize` (so per-side commentary may diverge but logic may not), `extractDeclaration(src, name)` (balanced `{}`/`()`/`[]` walk over `function` / `async function` / `const`), and `compareDeclaration(serverSrc, clientSrc, name)`. Use these instead of hand-rolling a brace-walker per mirror. Pure — no `vitest` import — so callers own the assertions. |-| `mockPathsDataRoot.js` | Shared Vitest helpers for `PATHS.data → temp dir`, no-peer record creation guards, and deterministic federation-identity doubles (`mockTestIdentity`). |+| `mockPathsDataRoot.js` | Shared Vitest helpers for `PATHS.data → temp dir`, no-peer record creation guards, deterministic federation-identity doubles (`mockTestIdentity`), and `ownTestBodies(it)` → `{ it, drain }`, which owns each test body so teardown can `await drain()` before removing a fixture root — a body left running by Vitest's fail-fast cancellation otherwise recreates the removed root (`test temp leak:`). || `settingsTestUtil.js` | `bindSettingsFile(dataRoot)` → `writeSettingsFile`/`mergeSettingsFile`: direct settings.json disk writes that also drop the `getSettings()` read cache (dynamic-import reset) so a stale cache can't survive a bypass-`save()` write. || `runtimeEnv.js` | `isTestRunner()` — NODE_ENV=test **or** the VITEST env var, so a run that dropped NODE_ENV is still armed. `isVitestRunner()` narrows to a real Vitest worker; `isSmokeBoot()` (`SMOKE_BOOT_ENV`) marks the server boot smoke, whose boot skips schedulers, agent recovery, and external integrations (#8343). Dependency-free and deliberately apart from `db.js`, which used to own it: the lowest-level file primitives need the same answer and must not pull in `pg`, and the many suites spelling `vi.mock('../lib/db.js', () => ({ query }))` used to strip it out of the graph for every other consumer. || `testDataIsolation.js` | Runtime backstop against a test WRITING into the install's real `data/` tree — the filesystem analogue of `db.js`'s row-write guard. `isInsideRealDataRoot(path)` canonicalizes a target through symlinked ancestors (it need not exist yet) and tests containment with `pathSafety.js#isPathAtOrInsideDir`, so a `..` climb, a relative path, a `data-archive` sibling, or a differently-cased spelling on a case-insensitive filesystem can't walk in sideways; the real root is re-derived through `dataRoot.js` rather than read from `PATHS`, so a suite that redirects `PATHS.data` to a temp root can't also redirect the guard. `assertNotRealDataWrite(path, operation)` throws under the test runner from `atomicWrite`, the guarded wrappers in `fileCore.js` (`writeFileGuarded`, `appendFileGuarded`, `copyFileGuarded`, `rmGuarded`, `unlinkGuarded`, `createWriteStreamGuarded`), and `collectionStore`'s record delete; `assertNotNewRealDataDir(dir)` is the create-only variant `ensureDir` uses, since `mkdir -p` on an existing directory mutates nothing. Inert outside the runner — the `isTestRunner()` check precedes every syscall. Services mutating files under `data/` route through these guarded wrappers. Closes the write half of the bug class `testDataIsolation.guards.test.js` covers statically and the two-run probe covers for reads (#6176, after #6171, #6203). |diff --git a/server/lib/mockPathsDataRoot.js b/server/lib/mockPathsDataRoot.jsindex 7b194cdd97..33bf1adc5c 100644--- a/server/lib/mockPathsDataRoot.js+++ b/server/lib/mockPathsDataRoot.js@@ -35,6 +35,8 @@* double the federation identity leaf instead of the real data file.* - `mockNoPeerSync(actual?, overrides?)` — shared `peerSync.js` mock guard* that makes fire-and-forget record auto-subscribe a clean no-op in tests.+ * - `ownTestBodies(it)` — owns each test body until it settles so teardown+ * can drain a fail-fast-cancelled body before removing its temp root.** Every `PATHS` member that lives under the real `data/` is re-rooted at the* temp dir automatically, so a suite that only wants the standard layout@@ -136,6 +138,49 @@ export async function sweepStrayTempRoots(prefix) {sweepOnce();}+/**+ * Own every test body until it settles, so fixture teardown cannot run under it.+ *+ * Vitest's fail-fast cancellation (`--bail`, triggered by a failure in ANOTHER+ * worker) settles a running test's wrapper while its async body keeps going. A+ * suite whose `afterAll`/`afterEach` removes a temp data root then deletes the+ * directory underneath that body, and the body's next store write recreates it+ * — the run-level guard reports it as `test temp leak:` (#9497, #9622, #9635).+ *+ * Pass vitest's `it`; use the returned `it` for every test that writes into the+ * fixture, and `await drain()` in teardown BEFORE removing it. A body that+ * failed after cancellation (vitest is no longer listening) is rethrown from+ * `drain()` rather than dropped; a failure vitest already reported is not.+ *+ * const owned = ownTestBodies(vitestIt);+ * const it = owned.it;+ * afterAll(async () => {+ * try { await owned.drain(); } finally { rmSync(root, { recursive: true, force: true }); }+ * });+ *+ * @param {Function} it - vitest's `it`/`test`+ * @returns {{ it: Function, drain: () => Promise<void> }}+ */+export function ownTestBodies(it) {+ const pending = new Set();+ const orphanedFailures = [];+ const ownedIt = (name, body, ...rest) => it(name, (context) => {+ const run = Promise.resolve().then(() => body(context));+ const settled = run.then(() => {}, (error) => { if (context.signal.aborted) orphanedFailures.push(error); });+ pending.add(settled);+ settled.then(() => pending.delete(settled));+ return run;+ }, ...rest);+ const drain = async () => {+ while (pending.size) await Promise.all(pending);+ if (orphanedFailures.length) {+ const failures = orphanedFailures.splice(0);+ throw new AggregateError(failures, 'Cancelled test body failed after cancellation');+ }+ };+ return { it: ownedIt, drain };+}+/*** Build the Proxy returned from a `vi.mock('../lib/fileUtils.js', ...)`* factory. Pass the already-resolved `actual` (from `vi.importActual`) anddiff --git a/server/services/duplicateDetection.test.js b/server/services/duplicateDetection.test.jsindex 83c97ebee8..afc4124d2f 100644--- a/server/services/duplicateDetection.test.js+++ b/server/services/duplicateDetection.test.js@@ -1,13 +1,30 @@-import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';-import { mkdtempSync, rmSync, mkdirSync } from 'fs';+import { describe, it as vitestIt, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';+import { mkdtempSync, rmSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';-import { mockNoPeerSync, mockNoPeers, makePathsProxy } from '../lib/mockPathsDataRoot.js';--const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'dup-detect-test-'));+import { mockNoPeerSync, mockNoPeers, makePathsProxy, ownTestBodies } from '../lib/mockPathsDataRoot.js';++// Each test gets its own root, allocated only when the test starts — never at+// module collection, so a run that bails before this file executes a test+// leaves nothing behind. Teardown drains every owned test body first: a body+// cancelled by another worker's fail-fast keeps writing, and removing the root+// under it lets the next store write recreate it (#9635).+let tempRoot;+const roots = new Set();+const owned = ownTestBodies(vitestIt);+const it = owned.it;++async function cleanupFixtures() {+ try {+ await owned.drain();+ } finally {+ for (const root of roots) rmSync(root, { recursive: true, force: true });+ roots.clear();+ }+}vi.mock('../lib/fileUtils.js', async (importOriginal) =>- makePathsProxy(await importOriginal(), { dataRoot: TEST_DATA_ROOT }));+ makePathsProxy(await importOriginal(), { dataRoot: () => tempRoot }));vi.mock('./instances.js', () => mockNoPeers());vi.mock('./sharing/peerSync.js', () => mockNoPeerSync());@@ -22,12 +39,13 @@ const seriesSvc = await import('./pipeline/series.js');const mediaCollections = await import('./mediaCollections.js');const dup = await import('./duplicateDetection.js');-afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));+afterEach(cleanupFixtures);+afterAll(cleanupFixtures);describe('duplicateDetection', () => {beforeEach(() => {- rmSync(TEST_DATA_ROOT, { recursive: true, force: true });- mkdirSync(TEST_DATA_ROOT, { recursive: true });+ tempRoot = mkdtempSync(join(tmpdir(), 'dup-detect-test-'));+ roots.add(tempRoot);uuidCounter = 0;});diff --git a/server/services/persistentMindProcessAudit.test.js b/server/services/persistentMindProcessAudit.test.jsindex 3fbb4fdb2d..d7a5289eb8 100644--- a/server/services/persistentMindProcessAudit.test.js+++ b/server/services/persistentMindProcessAudit.test.js@@ -1,6 +1,7 @@import { beforeEach, afterAll, expect, it as vitestIt, vi } from 'vitest';import { join } from 'node:path';import { mkdir, writeFile, rm } from 'node:fs/promises';+import { ownTestBodies } from '../lib/mockPathsDataRoot.js';const mocks = vi.hoisted(() => ({ root: {}, apps: [], records: {}, dir: null, file: vi.fn(), list: vi.fn(), git: vi.fn() }));vi.mock('../lib/fileUtils.js', async () => {const fs = await import('node:fs/promises');@@ -43,23 +44,16 @@ beforeEach(async () => {mocks.git.mockImplementation(async args => ({ stdout: args.slice(3).join('\0') + '\0', exitCode: 0 }));await addJob('agent-example');});-// Vitest's fail-fast cancellation rejects a test's wrapper while its async body-// keeps writing into the shared fixture root. Own each body until it settles so-// afterAll removes the root only after every write, and surface a body that-// failed after vitest stopped listening instead of dropping it.-const pendingBodies = new Set();-const orphanedFailures = [];-const it = (name, body) => vitestIt(name, context => {- const run = Promise.resolve().then(() => body(context));- const settled = run.then(() => {}, error => { if (context.signal.aborted) orphanedFailures.push(error); });- pendingBodies.add(settled);- settled.then(() => pendingBodies.delete(settled));- return run;-});+// Fail-fast cancellation can leave a test body writing into the shared fixture+// root; drain every owned body before removing it (see ownTestBodies).+const owned = ownTestBodies(vitestIt);+const it = owned.it;afterAll(async () => {- while (pendingBodies.size) await Promise.all(pendingBodies);- await rm(mocks.dir, { recursive: true, force: true });- if (orphanedFailures.length) throw new AggregateError(orphanedFailures, 'Cancelled process-audit test failed after cancellation');+ try {+ await owned.drain();+ } finally {+ await rm(mocks.dir, { recursive: true, force: true });+ }});const next = (context = turn) => audit.nextProcessAuditBatch({ appId: 'example' }, context);const finding = receipt => ({ appId: 'example', receiptId: receipt, outcome: 'finding', template: 'wrong-tool', targetAppId: 'slashdo', anchors: ['commands/next.md'] });diff --git a/server/services/writersRoom/promoteToPipeline.test.js b/server/services/writersRoom/promoteToPipeline.test.jsindex 73ff5160d1..a52c064151 100644--- a/server/services/writersRoom/promoteToPipeline.test.js+++ b/server/services/writersRoom/promoteToPipeline.test.js@@ -2,31 +2,22 @@ import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitesimport { mkdtempSync, rmSync, readFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';-import { makePathsProxy, mockNoPeerSync, mockNoPeers } from '../../lib/mockPathsDataRoot.js';+import { makePathsProxy, mockNoPeerSync, mockNoPeers, ownTestBodies } from '../../lib/mockPathsDataRoot.js';let tempRoot;const roots = new Set();-const pendingTests = new Set();--// Vitest's fail-fast cancellation settles its wrapper before the async test-// body stops. Own that body until its writes settle before removing fixtures.-function promotionTest(name, body) {- it(name, (context) => {- const pending = Promise.resolve().then(() => body(context));- pendingTests.add(pending);- pending.then(() => pendingTests.delete(pending), () => pendingTests.delete(pending));- return pending;- });-}+// Fail-fast cancellation can leave a test body writing into its fixture root;+// drain every owned body before removing the roots (see ownTestBodies).+const owned = ownTestBodies(it);+const promotionTest = owned.it;async function cleanupFixtures() {- const settled = await Promise.allSettled([...pendingTests]);- for (const root of roots) {- rmSync(root, { recursive: true, force: true });- roots.delete(root);+ try {+ await owned.drain();+ } finally {+ for (const root of roots) rmSync(root, { recursive: true, force: true });+ roots.clear();}- const failures = settled.filter(result => result.status === 'rejected').map(result => result.reason);- if (failures.length) throw new AggregateError(failures, 'Interrupted promotion test failed');}vi.mock('../../lib/fileUtils.js', async () => {