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
test: audit the server suite for tests reading the real data/ dir, isolate missions (#3687)
[._.]/ Adam Eivyac4ff2be5fee
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 56cea94cab..a738854a45 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -80,3 +80,5 @@- Internal: recorded a feasibility spike on Krea Realtime 14B as a local Apple Silicon video backend (`docs/research/2026-08-09-krea-realtime-apple-silicon.md`). The answer is **no-go for now** and nothing shipped: Krea's own runtime initializes CUDA at module import and pins `triton`, which publishes no macOS wheel, so it cannot even install on a Mac; its inference code is CC BY-NC-SA 4.0 (the weights are Apache-2.0 — two different licenses that PortOS has to track separately), and the only native-MLX implementation of the pipeline is a third party's unpublished, in-progress crate inside a product monorepo. The report pins every revision it inspected, distinguishes Krea 2 RAW/Turbo (image) from Krea Realtime 14B (video), marks every benchmark explicitly "not run" with the reason rather than guessing, and names the specific upstream change that would justify reevaluating.- Internal: the series-autopilot unlock-pass test suite no longer reads the checkout's real `data/` directory. It partial-mocked `fileUtils.js` with an in-memory store but left `PATHS.data` pointing at the repo, and the series collection store enumerates that directory with a real `readdir` the mock never intercepts — so on any checkout with real series on disk, two sole-universe-ownership tests failed with what looked like a regression on whatever branch happened to be checked out. CI never saw it because a fresh checkout has no `data/`. `PATHS.data` now resolves to a per-run temp dir via the shared `makePathsProxy` helper, and three added assertions pin the isolation so it cannot quietly come back. The three sibling pipeline suites named as suspects were audited and are already isolated — they replace `series.js` outright and never reach the store. Test-only change; no production code touched.++- Internal: audited the whole server test suite for the "test reads the checkout's real `data/`" class that #3683 fixed one instance of, and closed the one other case it found. The audit was empirical rather than static — a full-suite baseline against an empty `data/`, then a second run with obviously-fake probe records planted in every `data/` subdirectory a service enumerates (prefix-aware, so the stores whose id allowlists require `iss-`/`ser-`/`stb-`/`game-` were actually reached) — and exactly one of 1301 test files failed only in the second run: the missions suite, which addressed `<repo>/data/cos/missions` directly with no mock at all, so it read the developer's live missions *and* wrote its own fixtures into them. It now runs against a per-run temp root, with two assertions pinning the isolation. The 67 suites that partial-mock `fileUtils.js` without redirecting `PATHS` were cleared by the same two-run diff — they replace the service graph wholesale and never reach a real `readdir`. A new repo-wide guard keys on the thing that is never legitimate in a test, naming the checkout's own `data/` directory, so it needs no allowlist. Test-only change; no production code touched.diff --git a/server/lib/testDataIsolation.guards.test.js b/server/lib/testDataIsolation.guards.test.jsnew file mode 100644index 0000000000..17d1d5fb12--- /dev/null+++ b/server/lib/testDataIsolation.guards.test.js@@ -0,0 +1,94 @@+/**+ * Repo-wide guard: no test may address the checkout's real `data/` tree.+ *+ * ## The bug class+ *+ * A suite that resolves a path into `<repo>/data/` runs against the developer's+ * live install. It reads their records (so the fixture set silently gains rows+ * the assertions never accounted for) and, if it writes, drops test artifacts+ * into their data. The failure is invisible in CI by construction — a fresh+ * checkout has no `data/` — so it only ever surfaces on a populated machine,+ * where it reads as a spurious regression on whatever branch is checked out.+ *+ * Two suites have shipped this: #3683 (`unlockPass.test.js`, via a fileUtils+ * partial mock that left `PATHS` alone) and #3687 (`missions.test.js`, via+ * `join(process.cwd(), 'data', …)` with no mock at all).+ *+ * ## Why this rule and not "every fileUtils partial mock must redirect PATHS"+ *+ * #3687 audited the whole server suite empirically — two full runs, the second+ * with probe records planted in every `data/` subdirectory a service enumerates+ * — and found exactly ONE leaker in 1301 test files. The 67 suites that+ * partial-mock `fileUtils.js` without a `PATHS` redirect are overwhelmingly safe+ * (they replace the service graph wholesale, so nothing ever reaches a real+ * `readdir`), and a guard over that shape would need a 66-entry allowlist to+ * flag one file. So the rule keys on the thing that is *never* legitimate in a+ * test — naming the checkout's own `data/` directory — which needs no allowlist+ * at all.+ *+ * A test that genuinely needs a data root uses `createTempDataRoot()` ++ * `makePathsProxy()` from `lib/mockPathsDataRoot.js`.+ */++import { describe, it, expect } from 'vitest';+import { execFileSync } from 'child_process';+import { readFileSync } from 'fs';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';++const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');+// This file quotes the forbidden spellings in its own pattern assertions below,+// so it must exempt itself or it reports itself as the sole offender.+const SELF = 'server/lib/testDataIsolation.guards.test.js';++// Matches an install-root anchor (`process.cwd()`, `PATHS.root`,+// `PATHS.installRoot`) joined to a `data` segment — as a `join()` argument+// (`, 'data'`) or inside a template literal (`}/data`). Deliberately does NOT+// match `'test-data'` or any other name that merely ends in `data`.+const REAL_DATA_ROOT_RE =+ /(process\.cwd\(\)|PATHS\.(?:root|installRoot))(?:[^\n;]*?,\s*['"]data['"]|\}?\/data['"/`])/;++// Scope to the test files the server runner globs (`server/vitest.config.js`).+// Client tests run in jsdom and have no filesystem to leak into.+const scopedTests = () => execFileSync('git', ['ls-files', '*.test.js'], {+ cwd: REPO_ROOT,+ encoding: 'utf8',+})+ .split('\n')+ .filter((p) => /^(server|scripts|lib|autofixer)\//.test(p))+ .filter((p) => !p.startsWith('lib/slashdo/') && p !== SELF);++describe('test-data isolation guard', () => {+ it('finds test files to scan', () => {+ // Fails loudly if the glob or the path filter ever stops matching, rather+ // than reporting a vacuous pass over zero files.+ expect(scopedTests().length).toBeGreaterThan(100);+ });++ it('no test resolves a path into the checkout\'s real data/ directory', () => {+ const offenders = scopedTests().filter((rel) =>+ REAL_DATA_ROOT_RE.test(readFileSync(join(REPO_ROOT, rel), 'utf8'))+ );+ expect(offenders, [+ 'These tests address the checkout\'s own data/ directory, so they read (and may',+ 'overwrite) the developer\'s live records. Allocate a temp root instead:',+ '',+ " const tempRoot = createTempDataRoot('portos-<suite>-');",+ " vi.mock('../lib/fileUtils.js', async (importOriginal) =>",+ ' makePathsProxy(await importOriginal(), { dataRoot: tempRoot }));',+ '',+ 'See lib/mockPathsDataRoot.js and services/missions.test.js (#3687).',+ ].join('\n')).toEqual([]);+ });++ it('the pattern matches the shapes that shipped, and spares look-alikes', () => {+ // #3687's actual line, plus the PATHS-anchored and template-literal spellings.+ expect(REAL_DATA_ROOT_RE.test("path.join(process.cwd(), 'data', 'cos', 'missions')")).toBe(true);+ expect(REAL_DATA_ROOT_RE.test("join(PATHS.installRoot, 'data', 'runs')")).toBe(true);+ expect(REAL_DATA_ROOT_RE.test('`${process.cwd()}/data/cos`')).toBe(true);+ // Look-alikes that must stay legal.+ expect(REAL_DATA_ROOT_RE.test("join(process.cwd(), 'test-data')")).toBe(false);+ expect(REAL_DATA_ROOT_RE.test('workspacePath: process.cwd()')).toBe(false);+ expect(REAL_DATA_ROOT_RE.test("join(tempRoot, 'data', 'cos')")).toBe(false);+ });+});diff --git a/server/services/missions.test.js b/server/services/missions.test.jsindex 615bb73c59..5517cd7b13 100644--- a/server/services/missions.test.js+++ b/server/services/missions.test.js@@ -1,6 +1,7 @@-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';-import { promises as fs } from 'fs';+import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';+import { rmSync } from 'fs';import path from 'path';+import { createTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';// Mock cosEvents before importvi.mock('./cos.js', () => ({@@ -9,7 +10,30 @@ vi.mock('./cos.js', () => ({}}));-import {+// This suite exercises the REAL file-backed mission store — createMission writes+// `PATHS.missions/<id>.json` and loadMissions enumerates that dir with a real+// readdir. Without a PATHS redirect that dir is the checkout's own+// `data/cos/missions`, so the suite both read the developer's live missions (a+// hand-edited or legacy record with no `subTasks` crashed getStats) and wrote its+// own fixtures into it. Same leak class as #3683; see the isolation probe below.+//+// `PATHS.missions` is anchored on the install root rather than derived from+// `PATHS.data`, so redirecting `data` alone is not enough — it needs its own+// override, which is what `extraOverrides` is for.+const tempRoot = createTempDataRoot('portos-missions-');+vi.mock('../lib/fileUtils.js', async (importOriginal) => makePathsProxy(await importOriginal(), {+ dataRoot: tempRoot,+ extraOverrides: (root) => ({ missions: path.join(root, 'cos', 'missions') }),+}));++afterAll(() => rmSync(tempRoot, { recursive: true, force: true }));++// Dynamic import, not a static one: `missions.js` reads `PATHS.missions` into a+// module-level const at load time, and a static import would run that load+// BEFORE the `const tempRoot` line above — the mock factory would then close+// over an uninitialized binding. Top-level await defers the load until after the+// temp root exists.+const {createMission,getMission,getMissionsForApp,@@ -24,20 +48,16 @@ import {deleteMission,archiveCompletedMissions,invalidateCache-} from './missions.js';+} = await import('./missions.js');-const DATA_DIR = path.join(process.cwd(), 'data', 'cos', 'missions');+const DATA_DIR = path.join(tempRoot, 'cos', 'missions');describe('Missions Service', () => {- beforeEach(async () => {+ beforeEach(() => {invalidateCache();- // Clean up test missions- const files = await fs.readdir(DATA_DIR).catch(() => []);- for (const file of files) {- if (file.startsWith('test-')) {- await fs.unlink(path.join(DATA_DIR, file)).catch(() => {});- }- }+ // The temp root is this suite's alone, so wiping the whole missions dir is+ // both simpler and stricter than unlinking `test-`-prefixed files.+ rmSync(DATA_DIR, { recursive: true, force: true });});afterEach(() => {@@ -373,3 +393,24 @@ describe('Missions Service', () => {});});});++// Isolation probe (#3687). The suite above drives the real file-backed store, so+// without the PATHS redirect at the top of this file it reads AND writes the+// checkout's own `data/cos/missions`. These assertions fail the same way if the+// redirect is ever dropped, so the leak can't come back silently.+describe('Missions Service — the suite is isolated from the checkout\'s real data/', () => {+ it('resolves PATHS.missions to a temp dir outside the repo', async () => {+ const { PATHS } = await import('../lib/fileUtils.js');+ expect(PATHS.missions).toBe(DATA_DIR);+ expect(PATHS.missions).not.toContain('PortOS');+ });++ // The behavioral half: loadMissions enumerates the dir with a real readdir, so+ // a PATHS.missions pointing at the checkout would surface the developer's own+ // missions alongside this one.+ it('counts only the missions this suite created', async () => {+ await createMission({ id: 'test-isolation-probe', appId: 'test-app', name: 'Isolation Probe' });+ const stats = await getStats();+ expect(stats.totalMissions).toBe(1);+ });+});