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

Keep Vite and Vitest caches inside their owning checkout (#11576)

[._.]/4f976d30b898
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 1229d96446..6562370f46 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -246,18 +246,16 @@ jobs:
node scripts/trusted-rebuilds.js server
node scripts/trusted-rebuild-stamp.js write server
- # After the install: `npm ci` wipes node_modules, so a restore ordered
- # ahead of it is lost. Vite/Vitest write transform artifacts under
- # node_modules/.vite (and historically .vitest); reusing them skips
- # re-transforming unchanged files. Separate from the cache above, and
- # deliberately: this is where a near miss is safe, so this is the entry
- # that keeps restore-keys and stays warm across a lockfile bump.
+ # Reuse Vite/Vitest artifacts from checkout-owned .cache paths, outside
+ # node_modules (which may be shared by worktrees). Unlike the installed
+ # dependency tree above, these artifacts can safely use a near-miss
+ # restore and stay warm across a lockfile bump.
- name: Cache Vitest transform artifacts
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: |
- server/node_modules/.vite
- server/node_modules/.vitest
+ server/.cache/vitest
+ server/.cache/vitest-db
key: vitest-server-${{ runner.os }}-${{ hashFiles('server/package-lock.json', 'server/vitest.config.js', 'scripts/vitestCiPool.js') }}-${{ matrix.shard }}of${{ strategy.job-total }}
restore-keys: |
vitest-server-${{ runner.os }}-${{ hashFiles('server/package-lock.json') }}-
@@ -395,8 +393,7 @@ jobs:
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: |
- client/node_modules/.vite
- client/node_modules/.vitest
+ client/.cache/vitest
key: vitest-client-${{ runner.os }}-${{ hashFiles('client/package-lock.json', 'client/vitest.config.js', 'scripts/vitestCiPool.js') }}-${{ matrix.shard }}of${{ strategy.job-total }}
restore-keys: |
vitest-client-${{ runner.os }}-${{ hashFiles('client/package-lock.json') }}-
@@ -634,18 +631,16 @@ jobs:
node scripts/trusted-rebuilds.js server
node scripts/trusted-rebuild-stamp.js write server
- # After the install: `npm ci` wipes node_modules, so a restore ordered
- # ahead of it is lost. Vite/Vitest write transform artifacts under
- # node_modules/.vite (and historically .vitest); reusing them skips
- # re-transforming unchanged files. Separate from the cache above, and
- # deliberately: this is where a near miss is safe, so this is the entry
- # that keeps restore-keys and stays warm across a lockfile bump.
+ # Reuse Vite/Vitest artifacts from checkout-owned .cache paths, outside
+ # node_modules (which may be shared by worktrees). Unlike the installed
+ # dependency tree above, these artifacts can safely use a near-miss
+ # restore and stay warm across a lockfile bump.
- name: Cache Vitest transform artifacts
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: |
- server/node_modules/.vite
- server/node_modules/.vitest
+ server/.cache/vitest
+ server/.cache/vitest-db
key: vitest-server-${{ runner.os }}-${{ hashFiles('server/package-lock.json', 'server/vitest.config.js', 'server/vitest.config.db.js', 'scripts/vitestCiPool.js') }}
restore-keys: |
vitest-server-${{ runner.os }}-${{ hashFiles('server/package-lock.json') }}-
@@ -828,18 +823,16 @@ jobs:
node scripts/trusted-rebuilds.js server
node scripts/trusted-rebuild-stamp.js write server
- # After the install: `npm ci` wipes node_modules, so a restore ordered
- # ahead of it is lost. Vite/Vitest write transform artifacts under
- # node_modules/.vite (and historically .vitest); reusing them skips
- # re-transforming unchanged files. Separate from the cache above, and
- # deliberately: this is where a near miss is safe, so this is the entry
- # that keeps restore-keys and stays warm across a lockfile bump.
+ # Reuse Vite/Vitest artifacts from checkout-owned .cache paths, outside
+ # node_modules (which may be shared by worktrees). Unlike the installed
+ # dependency tree above, these artifacts can safely use a near-miss
+ # restore and stay warm across a lockfile bump.
- name: Cache Vitest transform artifacts
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: |
- server/node_modules/.vite
- server/node_modules/.vitest
+ server/.cache/vitest
+ server/.cache/vitest-db
key: vitest-server-${{ runner.os }}-${{ hashFiles('server/package-lock.json', 'server/vitest.config.js', 'scripts/vitestCiPool.js') }}-${{ matrix.shard }}of${{ strategy.job-total }}
restore-keys: |
vitest-server-${{ runner.os }}-${{ hashFiles('server/package-lock.json') }}-
diff --git a/.gitignore b/.gitignore
index b1e1118b96..b5c1e827e7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,6 +10,10 @@
# this reason; unanchored, this one line covers every depth instead.
node_modules
+# Reusable tool caches belong to the checkout, outside shared dependency links.
+/client/.cache/
+/server/.cache/
+
# Build output
dist/
build/
diff --git a/client/package.json b/client/package.json
index a57ff0b5db..1a7a610cea 100644
--- a/client/package.json
+++ b/client/package.json
@@ -8,15 +8,15 @@
"npm": ">=11.11.0"
},
"scripts": {
- "dev": "vite --host 0.0.0.0 --port 5554",
+ "dev": "vite --configLoader runner --host 0.0.0.0 --port 5554",
"build": "node ../scripts/publish-client-build.js",
"build:analyze": "node ../scripts/publish-client-build.js --analyze",
"lint": "biome lint --error-on-warnings src",
- "preview": "vite preview",
- "test": "vitest run",
- "test:ci": "vitest run --bail=1 --silent=passed-only --reporter=default --reporter=github-actions",
- "test:ci:related": "vitest related --run --bail=1 --silent=passed-only --reporter=default --reporter=github-actions",
- "test:watch": "vitest"
+ "preview": "vite preview --configLoader runner",
+ "test": "vitest run --configLoader runner",
+ "test:ci": "vitest run --bail=1 --silent=passed-only --reporter=default --reporter=github-actions --configLoader runner",
+ "test:ci:related": "vitest related --run --bail=1 --silent=passed-only --reporter=default --reporter=github-actions --configLoader runner",
+ "test:watch": "vitest --configLoader runner"
},
"dependencies": {
"@dnd-kit/core": "6.3.1",
diff --git a/client/src/test/workspaceCaches.test.js b/client/src/test/workspaceCaches.test.js
new file mode 100644
index 0000000000..125e043709
--- /dev/null
+++ b/client/src/test/workspaceCaches.test.js
@@ -0,0 +1,13 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+import { checkDevCacheIsolation, checkWorkspaceCacheIsolation } from '../../../scripts/lib/workspaceCacheFixture.js';
+
+describe('checkout-owned client Vite caches with shared dependencies', () => {
+ it('client vitest.config.js keeps concurrent publications separate and reuses its owned cache', async () => {
+ await checkWorkspaceCacheIsolation('client', 'vitest.config.js', 'vitest', expect);
+ });
+
+ it.each(['npm', 'PM2'])('%s resolves real dev configs relative to each checkout without config-bundle scratch', async source => {
+ await checkDevCacheIsolation(source, expect);
+ });
+});
diff --git a/client/vite.config.js b/client/vite.config.js
index 4ecd696256..a07051f86a 100644
--- a/client/vite.config.js
+++ b/client/vite.config.js
@@ -177,6 +177,8 @@ export default defineConfig(({ command, mode }) => {
const API_TARGET = `${API_SCHEME}://${API_HOST}:5555`;
return {
+ // Dependencies may be shared by symlink; mutable caches belong to this checkout.
+ cacheDir: resolve(CONFIG_DIR, '.cache/vite'),
define: {
__APP_VERSION__: JSON.stringify(rootPkg.version),
__BUILD_STAMP__: JSON.stringify(buildStamp())
diff --git a/client/vitest.config.js b/client/vitest.config.js
index 52c0570558..96bc747737 100644
--- a/client/vitest.config.js
+++ b/client/vitest.config.js
@@ -9,6 +9,8 @@ import { TEST_TIMEOUT_MS } from './src/test/timeouts.js';
const RUN_TEMP_ROOT = bootstrapVitestTempRoot();
export default defineConfig({
+ // Anchor to the config, even when --root or the caller cwd differs.
+ cacheDir: fileURLToPath(new URL('./.cache/vitest', import.meta.url)),
plugins: [react()],
resolve: {
// Share Three.js without bypassing its package exports with a directory alias.
diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md
index 2a1cfbe6ed..dd2260de16 100644
--- a/docs/CONTRIBUTING.md
+++ b/docs/CONTRIBUTING.md
@@ -78,6 +78,24 @@ See [VERSIONING.md](./VERSIONING.md) for full details.
Pregate proves only the stages it runs; it does not replace required CI or resource-dependent checks. A full-suite plan runs only the always-run guards unless `--full` is supplied; DB suites, Windows, client build, and boot smoke are reported but not run by pregate.
+### Checkout-owned development caches
+
+Vite dev mode stores reusable dependency data in `client/.cache/vite`. Vitest
+uses `client/.cache/vitest`, `server/.cache/vitest`, and the separate
+`server/.cache/vitest-db` for DB suites. These ignored directories are anchored
+to the config file, including the server's derived capture projects, so shared
+`node_modules` links and a different invocation directory do not share writers.
+They are reused across runs and removed with their checkout; temporary test
+roots retain their separate teardown lifecycle. CI caches the same owned paths.
+
+The npm Vite/Vitest commands, PM2's `portos-ui` launcher, and subprocess fixtures
+use `--configLoader runner` to load ESM configs without writing bundles into shared
+`node_modules/.vite-temp`.
+For a direct CLI invocation, include that flag too. Vite's default `bundle`
+loader writes unique temporary config files into the nearest dependency tree
+before config options can redirect caches, so explicitly selecting that loader
+opts back into shared scratch. Existing shared caches are left in place.
+
### Changelog
Nothing to write here — there is no per-branch changelog file or fragment.
diff --git a/ecosystem.config.cjs b/ecosystem.config.cjs
index cb4fcc42ea..70d36bbbab 100644
--- a/ecosystem.config.cjs
+++ b/ecosystem.config.cjs
@@ -309,7 +309,7 @@ module.exports = {
interpreter: 'node',
log_date_format: LOG_DATE_FORMAT,
windowsHide: IS_WIN,
- args: `--host 0.0.0.0 --port ${PORTS.UI}`,
+ args: `--configLoader runner --host 0.0.0.0 --port ${PORTS.UI}`,
env: {
...BASE_ENV,
VITE_PORT: PORTS.UI
diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.js
index 2ae46d4cef..7dbfa3f903 100644
--- a/scripts/ci-test-plan.js
+++ b/scripts/ci-test-plan.js
@@ -471,12 +471,43 @@ const featureDirectory = (path) => {
return null;
};
+// The cache boundary copies configs/helpers into synthetic checkouts and reads
+// launcher arguments as data. Those runtime edges are invisible to Vitest's
+// import graph; select their shared contract explicitly instead of running its
+// subprocesses on every unrelated or documentation-only change.
+const WORKSPACE_CACHE_COMMON_INPUTS = new Set([
+ '.github/workflows/ci.yml', 'package.json', 'scripts/lib/workspaceCacheFixture.js',
+ 'scripts/lib/vitestTempRootFixture.js', 'scripts/lib/vitestTempRoot.js',
+ 'scripts/lib/vitestStaleRunRoots.js', 'scripts/lib/dbTestFiles.js',
+ 'scripts/vitestCiPool.js', 'scripts/vitestTempRootSetup.js', 'server/lib/killWithEscalation.js',
+]);
+const WORKSPACE_CACHE_SERVER_INPUTS = new Set([
+ 'server/package.json', 'server/package-lock.json',
+ 'server/vitest.config.js', 'server/vitest.config.db.js', 'server/vitest.setup.js',
+ 'server/test/admissionSetup.js', 'server/test/mediaRegistryEnvironment.js',
+]);
+const WORKSPACE_CACHE_CLIENT_INPUTS = new Set([
+ 'ecosystem.config.cjs', 'client/package.json', 'client/package-lock.json',
+ 'client/vite.config.js', 'client/vite.buildEnv.js', 'client/vite.chunkGroups.js',
+ 'client/vitest.config.js', 'client/src/test/timeouts.js',
+ 'scripts/dev-start.js', 'scripts/publish-client-build.js',
+ 'scripts/lib/envFile.cjs', 'scripts/lib/databaseSettings.cjs',
+ 'lib/portosAuthCore.js', 'server/lib/eidoverseProxyRoutes.js',
+]);
+
export const structuralTestsFor = (changedFiles, trackedSet) => {
const selected = [];
const add = (path) => {
if (trackedSet.has(path)) selected.push(path);
};
+ const sharedCacheInputChanged = changedFiles.some((path) => WORKSPACE_CACHE_COMMON_INPUTS.has(path));
+ if (sharedCacheInputChanged || changedFiles.some((path) => WORKSPACE_CACHE_SERVER_INPUTS.has(path))) {
+ add('scripts/workspaceCaches.test.js');
+ }
+ if (sharedCacheInputChanged || changedFiles.some((path) => WORKSPACE_CACHE_CLIENT_INPUTS.has(path))) {
+ add('client/src/test/workspaceCaches.test.js');
+ }
if (changedFiles.some((path) => /^server\/lib\//.test(path))) {
add('server/lib/index.test.js');
}
@@ -1008,7 +1039,9 @@ export function emitGitHubPlan(plan) {
suite_reasons: JSON.stringify(plan.suiteReasons),
};
- Object.entries(outputs).forEach(([name, value]) => writeStepOutput(name, value));
+ Object.entries(outputs).forEach(([name, value]) => {
+ writeStepOutput(name, value);
+ });
console.log(JSON.stringify({ ...outputs, changed_files: plan.changedFiles }, null, 2));
}
diff --git a/scripts/ci-test-plan.test.js b/scripts/ci-test-plan.test.js
index 9c12704388..8f45f0c898 100644
--- a/scripts/ci-test-plan.test.js
+++ b/scripts/ci-test-plan.test.js
@@ -20,6 +20,7 @@ import {
SLASHDO_GITLINK_PATH,
sourceReferencePattern,
splitByRunner,
+ structuralTestsFor,
WINDOWS_CONTRACT_TESTS,
WINDOWS_RISK_RULES,
} from './ci-test-plan.js';
@@ -68,6 +69,51 @@ const TRACKED = [
'scripts/fix-windows-console.js',
];
+it('selects checkout-cache contracts only in their installed-dependency runners', () => {
+ const serverContract = 'scripts/workspaceCaches.test.js';
+ const clientContract = 'client/src/test/workspaceCaches.test.js';
+ const shared = [
+ '.github/workflows/ci.yml', 'package.json', 'scripts/lib/workspaceCacheFixture.js',
+ 'scripts/lib/vitestTempRootFixture.js', 'scripts/lib/vitestTempRoot.js',
+ 'scripts/lib/vitestStaleRunRoots.js', 'scripts/lib/dbTestFiles.js',
+ 'scripts/vitestCiPool.js', 'scripts/vitestTempRootSetup.js', 'server/lib/killWithEscalation.js',
+ ];
+ const server = [
+ 'server/package.json', 'server/package-lock.json',
+ 'server/vitest.config.js', 'server/vitest.config.db.js', 'server/vitest.setup.js',
+ 'server/test/admissionSetup.js', 'server/test/mediaRegistryEnvironment.js',
+ ];
+ const client = [
+ 'ecosystem.config.cjs', 'client/package.json', 'client/package-lock.json',
+ 'client/vite.config.js', 'client/vite.buildEnv.js', 'client/vite.chunkGroups.js',
+ 'client/vitest.config.js', 'client/src/test/timeouts.js',
+ 'scripts/dev-start.js', 'scripts/publish-client-build.js',
+ 'scripts/lib/envFile.cjs', 'scripts/lib/databaseSettings.cjs',
+ 'lib/portosAuthCore.js', 'server/lib/eidoverseProxyRoutes.js',
+ ];
+ const trackedFiles = [...TRACKED, ...shared, ...server, ...client, serverContract, clientContract];
+ for (const [inputs, owners] of [[shared, [serverContract, clientContract]], [server, [serverContract]], [client, [clientContract]]]) {
+ for (const input of inputs) {
+ const selected = structuralTestsFor([input], new Set(trackedFiles));
+ const plan = buildCiTestPlan([input], { trackedFiles });
+ for (const [contract, runner] of [[serverContract, 'server'], [clientContract, 'client']]) {
+ expect(selected.includes(contract), input + ' -> ' + runner).toBe(owners.includes(contract));
+ // Full CI still runs both complete workspaces; scoped plans preserve ownership.
+ if (owners.includes(contract)) expect(plan[runner].mode === 'full' || plan[runner].files.includes(contract), input).toBe(true);
+ }
+ expect(plan.server.files, input).not.toContain(clientContract);
+ expect(plan.client.files, input).not.toContain(serverContract);
+ }
+ }
+ for (const input of ['docs/CONTRIBUTING.md', 'server/services/auth.js']) {
+ const plan = buildCiTestPlan([input], { trackedFiles });
+ expect(plan.full, input).toBe(false);
+ expect(plan.server.files, input).not.toContain(serverContract);
+ expect(plan.client.files, input).not.toContain(clientContract);
+ }
+ expect(structuralTestsFor([...shared, ...server, ...client], new Set())).toEqual([]);
+});
+
const REVIEW_LOOP_SNAPSHOT = 'server/services/promptSections/__snapshots__/reviewLoopMatrix/local-gh.txt';
const REVIEW_LOOP_OWNER = 'server/services/promptSections/reviewLifecycleMatrix.test.js';
const REVIEW_LIFECYCLE_SOURCE = 'server/services/promptSections/reviewLifecycle.js';
diff --git a/scripts/lib/vitestTempRootFixture.js b/scripts/lib/vitestTempRootFixture.js
index 43e83484ce..51d7ac4432 100644
--- a/scripts/lib/vitestTempRootFixture.js
+++ b/scripts/lib/vitestTempRootFixture.js
@@ -43,7 +43,7 @@ export function createVitestTempFixture(host, workspace, body, config = 'vitest.
delete env.VITEST_POOL_ID;
delete env.VITEST_WORKER_ID;
return {
- args: [join(repo, workspace, 'node_modules/vitest/vitest.mjs'), 'run',
+ args: [join(repo, workspace, 'node_modules/vitest/vitest.mjs'), 'run', '--configLoader', 'runner',
'--config', join(repo, workspace, config), '--root', root, '--maxWorkers', '1'],
options: { cwd: join(repo, workspace), env, encoding: 'utf8', timeout: 20000 },
};
diff --git a/scripts/lib/workspaceCacheFixture.js b/scripts/lib/workspaceCacheFixture.js
new file mode 100644
index 0000000000..e385722d35
--- /dev/null
+++ b/scripts/lib/workspaceCacheFixture.js
@@ -0,0 +1,169 @@
+import { spawn } from 'node:child_process';
+import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { createRequire } from 'node:module';
+import { dirname, join, relative } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import { createVitestTempFixture } from './vitestTempRootFixture.js';
+
+const REPO = fileURLToPath(new URL('../../', import.meta.url));
+const link = (target, path) => {
+ mkdirSync(dirname(path), { recursive: true });
+ if (statSync(target).isDirectory()) {
+ symlinkSync(target, path, process.platform === 'win32' ? 'junction' : 'dir');
+ } else {
+ // Re-export real helpers without requiring Windows file-symlink privileges.
+ writeFileSync(path, `export * from ${JSON.stringify(pathToFileURL(target).href)};\n`);
+ }
+};
+const put = (path, text) => {
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, text);
+};
+
+// Snapshot bytes and metadata: a replacement with identical contents is a write too.
+function snapshot(root) {
+ if (!existsSync(root)) return [];
+ return [['.', statSync(root).mtimeMs, null], ...readdirSync(root, { recursive: true }).sort().map(name => {
+ const path = join(root, name);
+ const stat = statSync(path);
+ return [name, stat.mtimeMs, stat.isFile() ? readFileSync(path, 'utf8') : null];
+ })];
+}
+
+function primaryDependencies(host, workspace) {
+ const dependencies = join(host, 'primary/node_modules');
+ mkdirSync(dependencies, { recursive: true });
+ for (const name of ['vite', 'vitest', ...(workspace === 'client' ? ['@vitejs', 'rollup-plugin-visualizer'] : [])]) {
+ link(join(REPO, workspace, 'node_modules', name), join(dependencies, name));
+ }
+ put(join(dependencies, '.vite/keep'), 'primary persistent cache');
+ put(join(dependencies, '.vite-temp/keep'), 'primary config scratch');
+ return dependencies;
+}
+
+function checkout(host, name, workspace, configName, dependencies) {
+ const parent = join(host, name);
+ mkdirSync(parent);
+ put(join(parent, 'package.json'), '{"type":"module"}');
+ const fixture = createVitestTempFixture(parent, workspace, 'expect(true).toBe(true);', configName);
+ const root = fixture.args[fixture.args.indexOf('--root') + 1];
+ unlinkSync(join(root, 'node_modules'));
+ link(dependencies, join(root, 'node_modules'));
+ put(join(root, 'package.json'), '{"type":"module"}');
+ // Copy the real config so import.meta.url names THIS checkout; its existing
+ // helpers stay shared read-only, just like dependencies in an ordinary worktree.
+ copyFileSync(join(REPO, workspace, configName), join(root, configName));
+ for (const file of ['lib/vitestTempRoot.js', 'lib/dbTestFiles.js', 'vitestCiPool.js', 'vitestTempRootSetup.js']) {
+ link(join(REPO, 'scripts', file), join(parent, 'scripts', file));
+ }
+ if (workspace === 'server') {
+ mkdirSync(join(root, 'test'), { recursive: true });
+ // Both server configs load this environment relative to themselves. Copy
+ // its default export intact so registry setup and teardown still run.
+ copyFileSync(join(REPO, 'server/test/mediaRegistryEnvironment.js'), join(root, 'test/mediaRegistryEnvironment.js'));
+ }
+ if (workspace === 'client') copyFileSync(join(REPO, 'client/src/test/timeouts.js'), join(root, 'src/test/timeouts.js'));
+ if (workspace === 'server' && configName === 'vitest.config.js') {
+ put(join(root, 'lib/filmLook.browser.test.js'), "import { test, expect } from 'vitest'; test('synthetic capture project', () => expect(true).toBe(true));");
+ }
+ // Exercise the documented npm command's loader, including the DB entry point.
+ const scripts = JSON.parse(readFileSync(join(REPO, workspace, 'package.json'), 'utf8')).scripts;
+ const args = scripts[configName === 'vitest.config.db.js' ? 'test:db' : 'test'].split(' ').slice(1);
+ const configAt = args.indexOf('--config');
+ if (configAt === -1) args.push('--config', join(root, configName));
+ else args[configAt + 1] = join(root, configName);
+ args.push('--root', root, '--maxWorkers', '1');
+ // Test roots and the caller's cwd differ from the config's parent directory.
+ const cwd = join(parent, 'caller');
+ mkdirSync(cwd);
+ return { ...fixture, args: [fixture.args[0], ...args], options: { ...fixture.options, cwd }, root };
+}
+
+function run({ args, options }) {
+ return new Promise((resolve, reject) => {
+ const child = spawn(process.execPath, args, { ...options, stdio: ['ignore', 'pipe', 'pipe'] });
+ let output = '';
+ child.stdout.on('data', chunk => { output += chunk; });
+ child.stderr.on('data', chunk => { output += chunk; });
+ child.once('error', reject);
+ child.once('close', (code, signal) => {
+ if (code === 0) resolve(output);
+ else reject(new Error(`fixture failed (${code ?? signal}): ${output}`));
+ });
+ });
+}
+
+async function runTogether(fixtures) {
+ const results = await Promise.allSettled(fixtures.map(run));
+ for (const result of results) if (result.status === 'rejected') throw result.reason;
+ return results.map(result => result.value);
+}
+
+const cachedResults = root => snapshot(root).filter(([name]) => name.endsWith('results.json'));
+
+// Assertions are supplied by the owning Vitest workspace; this shared fixture
+// imports only Node builtins and dependency-free fixture support.
+export async function checkWorkspaceCacheIsolation(workspace, configName, cacheName, expect) {
+ const host = mkdtempSync(join(tmpdir(), 'workspace-cache-'));
+ try {
+ const dependencies = primaryDependencies(host, workspace);
+ const primary = [snapshot(join(dependencies, '.vite')), snapshot(join(dependencies, '.vite-temp'))];
+ const a = checkout(host, 'a', workspace, configName, dependencies);
+ const b = checkout(host, 'b', workspace, configName, dependencies);
+ await runTogether([a, b]);
+ const cacheA = join(a.root, '.cache', cacheName);
+ const cacheB = join(b.root, '.cache', cacheName);
+ expect(cachedResults(cacheA).length).toBeGreaterThan(0);
+ expect(cachedResults(cacheB).length).toBeGreaterThan(0);
+ const sibling = snapshot(cacheB);
+ const names = snapshot(cacheA).map(([name]) => name);
+ await run(a);
+ expect(snapshot(cacheA).map(([name]) => name)).toEqual(names);
+ expect(snapshot(cacheB)).toEqual(sibling);
+ expect([snapshot(join(dependencies, '.vite')), snapshot(join(dependencies, '.vite-temp'))]).toEqual(primary);
+ rmSync(a.root, { recursive: true });
+ expect(existsSync(cacheA)).toBe(false);
+ expect(snapshot(cacheB)).toEqual(sibling);
+ } finally {
+ rmSync(host, { recursive: true, force: true });
+ }
+}
+
+export async function checkDevCacheIsolation(source, expect) {
+ const host = mkdtempSync(join(tmpdir(), 'workspace-dev-cache-'));
+ try {
+ const dependencies = primaryDependencies(host, 'client');
+ const primary = [snapshot(join(dependencies, '.vite')), snapshot(join(dependencies, '.vite-temp'))];
+ const commands = {
+ npm: JSON.parse(readFileSync(join(REPO, 'client/package.json'), 'utf8')).scripts.dev.split(' '),
+ PM2: createRequire(import.meta.url)(join(REPO, 'ecosystem.config.cjs')).apps.find(app => app.name === 'portos-ui').args.split(' '),
+ };
+ const devArgs = commands[source];
+ const loaderAt = devArgs.indexOf('--configLoader');
+ const loader = loaderAt === -1 ? undefined : devArgs[loaderAt + 1];
+ expect(loader).toBe('runner');
+ const fixtures = ['a', 'b'].map(name => checkout(host, name, 'client', 'vitest.config.js', dependencies));
+ for (const fixture of fixtures) {
+ const parent = dirname(fixture.root);
+ for (const file of ['vite.config.js', 'vite.buildEnv.js', 'vite.chunkGroups.js']) {
+ copyFileSync(join(REPO, 'client', file), join(fixture.root, file));
+ }
+ put(join(parent, 'package.json'), '{"type":"module","version":"0.0.0"}');
+ for (const file of ['lib/portosAuthCore.js', 'server/lib/eidoverseProxyRoutes.js']) link(join(REPO, file), join(parent, file));
+ const cache = join(realpathSync(fixture.root), '.cache/vite').replaceAll('\\', '/');
+ const script = join(fixture.root, 'inspect-dev.mjs');
+ put(script, `import { resolveConfig } from 'vite';
+ const config = await resolveConfig({ configFile: ${JSON.stringify(join(fixture.root, 'vite.config.js'))}, configLoader: ${JSON.stringify(loader)} }, 'serve');
+ if (config.cacheDir !== ${JSON.stringify(cache)}) throw Error('dev cache escaped its config owner');
+ process.stdout.write(config.cacheDir);`);
+ fixture.args = [script];
+ }
+ const outputs = await runTogether(fixtures);
+ expect(outputs[0]).not.toBe(outputs[1]);
+ expect([snapshot(join(dependencies, '.vite')), snapshot(join(dependencies, '.vite-temp'))]).toEqual(primary);
+ expect(fixtures.map(fixture => relative(host, fixture.options.cwd).replaceAll('\\', '/'))).toEqual(['a/caller', 'b/caller']);
+ } finally {
+ rmSync(host, { recursive: true, force: true });
+ }
+}
diff --git a/scripts/publish-client-build.js b/scripts/publish-client-build.js
index 4b3f8d5054..2fcd9cd4f0 100644
--- a/scripts/publish-client-build.js
+++ b/scripts/publish-client-build.js
@@ -264,7 +264,7 @@ function runViteBuild(stageDir, clientDir) {
throw new Error('publish-client-build owns Vite --outDir; remove the custom value');
}
const viteBin = join(clientDir, 'node_modules', 'vite', 'bin', 'vite.js');
- const child = spawn(process.execPath, [viteBin, 'build', ...viteArgs, '--outDir', stageDir, '--emptyOutDir'], {
+ const child = spawn(process.execPath, [viteBin, 'build', '--configLoader', 'runner', ...viteArgs, '--outDir', stageDir, '--emptyOutDir'], {
cwd: clientDir,
env: {
...process.env,
diff --git a/scripts/repo-scan-guards.test.js b/scripts/repo-scan-guards.test.js
index e216d403f8..a8a5b07cd4 100644
--- a/scripts/repo-scan-guards.test.js
+++ b/scripts/repo-scan-guards.test.js
@@ -50,6 +50,9 @@ const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
* entry.
*/
const STRUCTURALLY_SELECTED = new Map([
+ // The checkout-cache contracts now share a recursive fixture helper rather
+ // than scanning in either test file. They need no scanner exemption here;
+ // ci-test-plan.test.js pins explicit selection into their respective runners.
// structuralTestsFor() in ci-test-plan.js adds these whenever any
// client/src/**.jsx (a11y) or .js/.jsx (mounted-ref) file changes, which is
// the only way either can start failing.
diff --git a/scripts/vitestCiPool.js b/scripts/vitestCiPool.js
index 42a0410638..65d43da24d 100644
--- a/scripts/vitestCiPool.js
+++ b/scripts/vitestCiPool.js
@@ -66,7 +66,7 @@ const EXCLUSIVE_TESTS = [
'../scripts/writersRoomPromotionCleanup.test.js',
];
-export function vitestCaptureProjects(test) {
+export function vitestCaptureProjects(test, { cacheDir } = {}) {
const { include, exclude, ...shared } = test;
// Vite concatenates inherited include arrays: extending the broad root
// glob would also run EVERY unit file in the capture project. Copy shared
@@ -76,6 +76,8 @@ export function vitestCaptureProjects(test) {
return [
{
extends: false,
+ // These projects also opt out of Vite config inheritance.
+ cacheDir,
test: {
...shared,
name: 'parallel',
@@ -86,6 +88,8 @@ export function vitestCaptureProjects(test) {
},
{
extends: false,
+ // These projects also opt out of Vite config inheritance.
+ cacheDir,
test: {
...shared,
name: 'capture',
diff --git a/scripts/vitestCiPool.test.js b/scripts/vitestCiPool.test.js
index aeea257b0a..143b125391 100644
--- a/scripts/vitestCiPool.test.js
+++ b/scripts/vitestCiPool.test.js
@@ -141,7 +141,7 @@ it('runs parallel units before exclusive, nonduplicated captures and cutover pro
const env = { ...process.env, NODE_ENV: 'development', TMPDIR: scratch, TMP: scratch, TEMP: scratch };
delete env.PORTOS_TEST_TEMP_ROOT;
delete env.VITEST_FAST;
- const result = spawnSync(process.execPath, [join(server, 'node_modules/vitest/vitest.mjs'), 'run',
+ const result = spawnSync(process.execPath, [join(server, 'node_modules/vitest/vitest.mjs'), 'run', '--configLoader', 'runner',
'--config', join(server, 'vitest.config.js'), '--root', fixture, '--maxWorkers', '2',
], { cwd: server, env, encoding: 'utf8', timeout: 30000 });
expect(result.error).toBeUndefined();
diff --git a/scripts/workspaceCaches.test.js b/scripts/workspaceCaches.test.js
new file mode 100644
index 0000000000..d74bc8af1f
--- /dev/null
+++ b/scripts/workspaceCaches.test.js
@@ -0,0 +1,30 @@
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, it } from 'vitest';
+import { checkWorkspaceCacheIsolation } from './lib/workspaceCacheFixture.js';
+
+const REPO = fileURLToPath(new URL('../', import.meta.url));
+
+describe('checkout-owned server Vite caches with shared dependencies', () => {
+ it('keeps CI artifact-cache restores pointed at the owned test cache roots', () => {
+ const workflow = readFileSync(join(REPO, '.github/workflows/ci.yml'), 'utf8');
+ const caches = workflow.split('- name: Cache Vitest transform artifacts').slice(1)
+ .map(block => block.split('\n - name:')[0]);
+ expect(caches).toHaveLength(4);
+ for (const cache of caches) {
+ expect(cache).not.toContain('node_modules/.vite');
+ if (cache.includes('key: vitest-server-')) {
+ expect(cache).toContain('server/.cache/vitest\n');
+ expect(cache).toContain('server/.cache/vitest-db\n');
+ } else expect(cache).toContain('client/.cache/vitest\n');
+ }
+ });
+
+ it.each([
+ ['vitest.config.js', 'vitest'],
+ ['vitest.config.db.js', 'vitest-db'],
+ ])('server %s keeps concurrent publications separate and reuses its owned cache', async (configName, cacheName) => {
+ await checkWorkspaceCacheIsolation('server', configName, cacheName, expect);
+ });
+});
diff --git a/server/package.json b/server/package.json
index d21e884a72..e482875bb4 100644
--- a/server/package.json
+++ b/server/package.json
@@ -11,15 +11,15 @@
"dev": "node --watch start.js",
"start": "node start.js",
"lint": "node ../client/node_modules/@biomejs/biome/bin/biome lint --max-diagnostics=20 .",
- "test": "vitest run",
- "test:fast": "vitest run",
- "test:watch": "vitest",
- "test:ci": "vitest run --bail=1 --silent=passed-only --reporter=default --reporter=github-actions",
- "test:ci:related": "vitest related --run --bail=1 --silent=passed-only --reporter=default --reporter=github-actions",
- "test:coverage": "vitest run --coverage",
+ "test": "vitest run --configLoader runner",
+ "test:fast": "vitest run --configLoader runner",
+ "test:watch": "vitest --configLoader runner",
+ "test:ci": "vitest run --bail=1 --silent=passed-only --reporter=default --reporter=github-actions --configLoader runner",
+ "test:ci:related": "vitest related --run --bail=1 --silent=passed-only --reporter=default --reporter=github-actions --configLoader runner",
+ "test:coverage": "vitest run --coverage --configLoader runner",
"setup:db:test": "node scripts/setup-db-test.mjs",
- "test:db": "vitest run --config vitest.config.db.js",
- "test:db:ci": "vitest run --config vitest.config.db.js --bail=1 --reporter=default --reporter=github-actions"
+ "test:db": "vitest run --config vitest.config.db.js --configLoader runner",
+ "test:db:ci": "vitest run --config vitest.config.db.js --bail=1 --reporter=default --reporter=github-actions --configLoader runner"
},
"dependencies": {
"@babel/parser": "8.0.7",
diff --git a/server/vitest.config.db.js b/server/vitest.config.db.js
index d4a4b1ecdd..7cd9d0cd9b 100644
--- a/server/vitest.config.db.js
+++ b/server/vitest.config.db.js
@@ -38,6 +38,8 @@ export { DB_TEST_INCLUDE } from '../scripts/lib/dbTestFiles.js';
* checkHealth consumer is left out.
*/
export default defineConfig({
+ // Anchor to the config, even when --root or the caller cwd differs.
+ cacheDir: fileURLToPath(new URL('./.cache/vitest-db', import.meta.url)),
test: {
// Environment teardown also owns collection-only/skipped suite fixtures.
environment: fileURLToPath(new URL('./test/mediaRegistryEnvironment.js', import.meta.url)),
diff --git a/server/vitest.config.js b/server/vitest.config.js
index 4176236346..bcfbd55c4b 100644
--- a/server/vitest.config.js
+++ b/server/vitest.config.js
@@ -40,6 +40,8 @@ process.env.NODE_ENV = 'test';
process.env.NODE_DISABLE_COMPILE_CACHE = '1';
const config = defineConfig({
+ // Anchor to the config, even when --root or the caller cwd differs.
+ cacheDir: fileURLToPath(new URL('./.cache/vitest', import.meta.url)),
test: {
// Environment teardown also owns collection-only/skipped suite fixtures.
environment: fileURLToPath(new URL('./test/mediaRegistryEnvironment.js', import.meta.url)),
@@ -197,5 +199,5 @@ const config = defineConfig({
// Both projects share the safety env, setup files and time budgets. The
// root globalSetup owns one temp root across BOTH groups; project teardown
// must not remove it while another group still needs it.
-config.test.projects = vitestCaptureProjects(config.test);
+config.test.projects = vitestCaptureProjects(config.test, { cacheDir: config.cacheDir });
export default config;