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

refuse test writes into the install's real data/ tree at runtime (#6176)

[._.]/ Adam Eivyd5521b2a5cec
diff --git a/server/lib/README.md b/server/lib/README.md
index e196918ac0..3fbf84dbbe 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -241,6 +241,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `jsonIo.js` | JSON/JSONL parsing and file IO, strict read sentinels, append/read/write helpers, and `createCachedStore`. |
| `mimeTypes.js` | MIME tables and extension allowlists, image format detection, and filename sanitization. |
| `paths.js` | Canonical source/install `PATHS`, `dataPath`, and home-directory expansion. |
+| `pathContainment.js` | Dependency-free leaf holding `isPathAtOrInsideDir(dir, path)` (containment where the root itself counts as inside — what a guard policing a whole tree wants, as opposed to `pathSafety.js`'s strict `isPathInsideDir`; case-folded on Windows/macOS) and `canonicalizePath(path)` (realpath of the deepest EXISTING ancestor plus the not-yet-created tail, so a target that does not exist yet still resolves through symlinked ancestors). Split out so `fileCore.js`'s #6176 guard can reach them without dragging `errorHandler.js`/`paths.js` into the closure of every server suite — see the budget in `importScoping.test.js`. Keep it free of non-builtin imports. |
| `pathSafety.js` | Filename/traversal validation, path containment, and approved image-asset resolvers. |
| `uploads.js` | Upload staging/import, base64/image persistence, and safe local-file serving. |
| `icloudFile.js` | Guards against blocking reads of **evicted (dataless) cloud files**. macOS Optimize-Mac-Storage offloads a file in an iCloud ubiquity container (or a `~/Library/CloudStorage` File Provider mount); the path and `size` remain but no blocks are local, and the first **data access** BLOCKS in the kernel until materialization completes — indefinitely and uncancellably when iCloud is wedged. Four such reads exhaust libuv's 4-thread fs pool and every later `fs` call in the process queues forever, including the `express.static` read that serves the UI bundle (the whole UI hangs while memory-only routes still answer). Retry-on-error can't help: the read doesn't fail, it hangs. `readIfMaterialized(path, {encoding, label})` screens with a `stat()` (safe — never materializes) and rejects with `err.code === ICLOUD_NOT_MATERIALIZED` instead of issuing the read, kicking a background `brctl download` so the next cycle succeeds; concurrent callers for one path+encoding share a single read. `isUbiquityPath(path)` resolves the containing directory's real path (memoized) rather than substring-matching, so a **symlinked** route into iCloud — `~/Documents/...` under "Desktop & Documents Folders" sync — is still recognized. `isDatalessStats(stats)` is the raw predicate (`size > 0 && blocks === 0`) and is **not safe alone** (a sparse or `decmpfs`-compressed ordinary file matches it); pair it with the platform + cloud-root scoping via `isEvictedStats(path, stats)`, which is what a caller holding a `Stats` should use, or `isSuspectedDataless(path)` which does the `stat` itself. `requestMaterialization(path, {label, retryAfterExit, onFailure})` is the fire-and-forget `brctl download` every brctl caller shares — read paths kick it (default `retryAfterExit: true`) to heal an evicted file, per-path-deduped in a shared in-flight map capped at 4 concurrent children (an evicted vault walk would otherwise fork one per note) and each killed at `DOWNLOAD_DEADLINE_MS` so a wedged `brctl` can't hold every slot for the life of the process; the boot/settings pin in `mortalLoomStore` passes `retryAfterExit: false` so it is NOT tracked in that shared map (it owns a single-sticky-path dedupe at its call site) plus an `onFailure` hook to clear that sticky path on a failed/killed download. `claimBrctlMissingWarning()` returns `true` on the first call only, so the "brctl not found on PATH" warning fires at most once per process across every brctl caller (the fire-and-forget path here and the awaited `materializeAndWait`). `materializeAndWait(path, {label, timeoutMs})` is the **awaited, bounded** counterpart used by WRITE paths (`mortalLoomStore` before overwriting its store, `obsidian.updateNote` before overwriting a note): a write must not silently skip, so it materializes and waits rather than firing and forgetting, bounded by `MATERIALIZE_TIMEOUT_MS` (20s — much tighter than the background `DOWNLOAD_DEADLINE_MS` because a caller is blocked on it) and run in a child process, which is what makes the wait cancellable when the kernel write it replaces would not be. It resolves `true` only on brctl exit-0, which means the download was **accepted, not completed** — always re-screen before trusting the file. Measured (#3706, #3713), and recorded in the module docblock's syscall table: `stat`/`open`/`rename`/`unlink` never materialize, while `read`, `write` (including after `O_TRUNC` — truncating does NOT skip the download), `link`, and `clonefile` all do. `unlink` being free is a measurement, not the POSIX inference — `link` is pure metadata too and it *does* materialize — so delete paths need no screen. The docblock also carries the reproduction recipe: `brctl evict <path>` works (undocumented, like `brctl download`), which is what makes the evict/measure/heal loop scriptable. Consumed by `services/mortalLoomStore.js` and `services/obsidian.js`. |
@@ -530,4 +531,6 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `mirrorParity.js` | Source-comparison primitives for the `*.mirror.test.js` server↔client parity tests: `stripCommentsAndNormalize` (so per-side commentary may diverge but logic may not), `extractDeclaration(src, name)` (balanced `{}`/`()`/`[]` walk over `function` / `async function` / `const`), `compareDeclaration(serverSrc, clientSrc, name)`, and `compareRegexDeclaration(serverSrc, clientSrc, serverName, clientName?)` / `regexAlternationSource(declText)` (for a regex spelled as a `new RegExp([…].join('|'), 'i')` array on one side and an inline `/…/i` literal on the other — compares what it matches, not how it is typeset, and returns `null` rather than a partial read on any shape it can't decode). 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` and no-peer record creation guards. |
| `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. 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 `writeFile`/`appendFile`/`copyFile` wrappers in `fileCore.js`, 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. NOT yet universal: ~40 services still write to `PATHS.*` with raw `fs`, tracked as follow-up. 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). |
| `testHelper.js` | Test helpers: `request()` (supertest-style HTTP) + `mockJsonResponse`/`mockTextResponse` (fetch `Response` mocks with `.text()`, `.json()`, and a `headers.get` content-type), `startLoopbackServer(app)`/`closeLoopbackServer(server)`/`waitForAbort(signal)` for tests that need a real socket (raw disconnects, SSE streaming) that `request()`'s run-to-completion fetch harness can't model, plus the source-scan pair `collectServerSources()` / `readServerSource(rel)` (and `SERVER_DIR`) used by the whole-tree guard suites — `spawnCwd.test.js` (#3193) and `cliChildEnv.test.js` (#3194). Those guards overlap deliberately, so they share one definition of "a source file"; change the ignore rules here and both move together. Cross-platform trio: `posixPath(v)` normalizes a RECEIVED path before comparing it to a POSIX-spelled literal (no-op on POSIX — never normalize the expectation, which would hide a genuinely wrong path), and `resolveTestPython()` returns an interpreter that actually runs, probing by execution because Windows ships a `python` Store-alias stub that exists but fails; `null` when there is none, for `describe.skipIf`; `pinPlatform(value)` pins `process.platform` and returns a restore that reinstates the ORIGINAL descriptor (deleting the pin when there was none) — it carries the one hazard every hand-rolled pin had to rediscover: never pin above an import that loads a native addon, which picks its prebuilt binary off the platform at load time (#4085). Python-shelling suites also take their two nested budgets from here: `PY_TEST_TIMEOUT_MS` (vitest per-test, passed as `it()`'s third argument — a real interpreter's wall time tracks machine load, not the assertion, so a ~4s case crosses the tight global 10s `testTimeout` on a contended full-suite worker) and the strictly smaller `PY_SUBPROCESS_TIMEOUT_MS` (every `execFileSync` spawn's own `timeout`, so a hung interpreter trips the spawn guard first and names the command instead of producing a bare vitest timeout; a subprocess allowance ABOVE the vitest budget is dead intent — vitest always wins). |
diff --git a/server/lib/assetHash.test.js b/server/lib/assetHash.test.js
index 8718c2580a..6c4322ed6b 100644
--- a/server/lib/assetHash.test.js
+++ b/server/lib/assetHash.test.js
@@ -1,16 +1,23 @@
-import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';
import { mkdir, rm, writeFile, readFile } from 'fs/promises';
import { join, dirname } from 'path';
import { tmpdir } from 'os';
-import { sidecarPathForImage, getOrComputeImageSha256, sidecarGenParamsHash } from './assetHash.js';
-
-// PATHS.images is resolved at module-load from fileUtils and we deliberately
-// do NOT monkey-patch it — the absent-file tests use a tmpdir-rooted dir for
-// negative cases, but the positive sha256-compute / cache / invalidate tests
-// write fixtures into the REAL PATHS.images dir under a unique
-// `portos-assethash-test-*` token so the sidecar resolver hits a real
-// callsite. Each test wraps in try/finally to clean up the fixture even on
-// assertion failure (see the body of each `it()` below).
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from './mockPathsDataRoot.js';
+
+// The positive sha256-compute / cache / invalidate cases need the sidecar
+// resolver to hit a REAL callsite — i.e. a path it derives from `PATHS.images`
+// itself, not one the test hands it. They used to get that by writing fixtures
+// into the install's live `data/images`, which is the write-leak class #6176
+// closed at runtime: a stray failure between the write and the try/finally
+// cleanup left `portos-assethash-test-*` fixtures in the user's image library.
+// Redirecting the data root keeps the callsite exactly as honest — the helper
+// still resolves through `PATHS.images` — while pointing it somewhere
+// disposable.
+vi.mock('./fileUtils.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-assethash-') }));
+afterAll(cleanupTempDataRoots);
+
+const { sidecarPathForImage, getOrComputeImageSha256, sidecarGenParamsHash } = await import('./assetHash.js');
let imageDir;
@@ -23,13 +30,7 @@ afterEach(async () => {
await rm(imageDir, { recursive: true, force: true });
});
-// The helpers above use PATHS.images from fileUtils. Rather than monkey-patch
-// that, we test the sidecar-key invariant directly with a controlled writePath
-// that lives under PATHS.images (using a unique-name token so cleanup is
-// scoped). This keeps the tests honest about real-world callsites.
-//
-// We re-import PATHS so each test resolves to the real images dir.
-import { PATHS } from './fileUtils.js';
+const { PATHS } = await import('./fileUtils.js');
describe('assetHash', () => {
describe('sidecarPathForImage', () => {
@@ -66,8 +67,8 @@ describe('assetHash', () => {
});
it('computes + persists sha256 in sidecar on first call', async () => {
- // Use a name in the real PATHS.images dir so the sidecar write hits a
- // real location. Token makes cleanup easy.
+ // A name under the (redirected) PATHS.images dir, so the sidecar write
+ // hits a path the helper derived rather than one the test supplied.
const token = `portos-assethash-test-${Date.now()}-${Math.random()}.png`;
const imagePath = join(PATHS.images, token);
const sidecarPath = sidecarPathForImage(imagePath);
@@ -84,8 +85,8 @@ describe('assetHash', () => {
expect(sidecarJson.sha256.value).toBe(result.hash);
expect(sidecarJson.sha256.size).toBe(11);
} finally {
- // try/finally so a thrown assertion above doesn't leave the
- // portos-assethash-test-* fixture in PATHS.images.
+ // try/finally so a thrown assertion above doesn't leave the fixture
+ // behind for the sibling cases that enumerate PATHS.images.
await rm(imagePath, { force: true });
await rm(sidecarPath, { force: true });
}
diff --git a/server/lib/collectionStore.js b/server/lib/collectionStore.js
index 186d01e784..a2c9ad671d 100644
--- a/server/lib/collectionStore.js
+++ b/server/lib/collectionStore.js
@@ -85,6 +85,7 @@ import { join } from 'path';
import { readdir, lstat, rm } from 'fs/promises';
import { atomicWrite, readJSONFile, ensureDir } from './fileUtils.js';
import { createFileWriteQueue, createRecordWriteQueue } from './fileWriteQueue.js';
+import { isTestRunner } from './runtimeEnv.js';
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
@@ -374,6 +375,13 @@ export function createCollectionStore({
if (!isValidId(id)) {
throw new Error(`collectionStore[${type}]: invalid record id "${id}" — must match ${idPattern}`);
}
+ // #6176 — a recursive delete is the most destructive form of a data-root
+ // leak, so it takes the same guard the write primitives do. Loaded lazily
+ // for the same import-budget reason as fileCore.js.
+ if (isTestRunner()) {
+ const { assertNotRealDataWrite } = await import('./testDataIsolation.js');
+ assertNotRealDataWrite(recordDir(id), 'collectionStore delete');
+ }
await rm(recordDir(id), { recursive: true, force: true });
knownIds.delete(id);
}
diff --git a/server/lib/db.guards.test.js b/server/lib/db.guards.test.js
index 6e93a16616..2824b70492 100644
--- a/server/lib/db.guards.test.js
+++ b/server/lib/db.guards.test.js
@@ -10,7 +10,10 @@
* - isTestDatabase() — names a DB safe for destructive tests.
* - isTestRunner() — detects the runner via NODE_ENV=test OR the VITEST env
* var (set in every vitest worker), so a worktree run
- * that left NODE_ENV unset is still gated.
+ * that left NODE_ENV unset is still gated. Now declared in
+ * lib/runtimeEnv.js (the file guards need it too, and must
+ * not import `pg`), still covered here because these DB
+ * guards are what it was introduced for.
* - checkHealth() — reports "disconnected" under the test runner on a real
* DB so every db-backed suite skips via its existing branch.
* - query() — hard backstop: throws on ANY row write — INSERT/UPDATE/
@@ -34,7 +37,8 @@ import { describe, it, expect, afterEach } from 'vitest';
import { readdirSync, openSync, readSync, closeSync, existsSync } from 'node:fs';
import { dirname, join, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { isTestDatabase, isTestRunner, checkHealth, query, assertWriteAllowed } from './db.js';
+import { isTestDatabase, checkHealth, query, assertWriteAllowed } from './db.js';
+import { isTestRunner } from './runtimeEnv.js';
import { DB_TEST_INCLUDE } from '../vitest.config.db.js';
// NODE_ENV is 'test' throughout (vitest default); we vary PGDATABASE / TEST_DB_OK.
diff --git a/server/lib/db.js b/server/lib/db.js
index 63866f9589..080aa87b64 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -6,6 +6,7 @@
*/
import pg from 'pg';
+import { isTestRunner } from './runtimeEnv.js';
const { Pool } = pg;
@@ -64,25 +65,6 @@ export function isTestDatabase() {
return /_test$/.test(db) || db === 'portos_test';
}
-/**
- * Are we executing under a test runner?
- *
- * `NODE_ENV === 'test'` alone is not reliable: a suite run from a CoS-agent
- * worktree (or any wrapper that sets NODE_ENV=development / leaves it unset)
- * still executes test code, and the backend selectors that key off NODE_ENV
- * (e.g. seriesStore's `useFileBackend()`) then quietly choose the *Postgres*
- * backend — so the test writes land in the real `portos` DB with the guard
- * below disarmed. Vitest always sets `process.env.VITEST` in every worker
- * process, so OR-ing it in arms the guard regardless of how NODE_ENV was
- * (mis)configured. This is the signal that actually closed the 2026-06-14
- * fixture leak into prod.
- *
- * @returns {boolean}
- */
-export function isTestRunner() {
- return process.env.NODE_ENV === 'test' || process.env.VITEST != null;
-}
-
// Guard ALL row writes — not just deletions. The original guard only blocked
// DELETE/TRUNCATE, which let a mis-pointed suite INSERT fixtures into prod
// (their cleanup DELETE then threw, *stranding* the rows) — exactly how test
diff --git a/server/lib/fileCore.js b/server/lib/fileCore.js
index 6341d6a787..f835a4df2f 100644
--- a/server/lib/fileCore.js
+++ b/server/lib/fileCore.js
@@ -1,10 +1,21 @@
/** Cross-cutting filesystem, time, formatting, and hashing helpers. */
-import { access, chmod, mkdir, readFile, readdir, stat, writeFile, rename, unlink } from 'fs/promises';
+import { access, appendFile, chmod, copyFile, mkdir, readFile, readdir, stat, writeFile, rename, unlink } from 'fs/promises';
import { createReadStream, existsSync, statSync, watch as watchFileSystem } from 'fs';
import { createHash, randomUUID } from 'crypto';
import { basename, dirname, extname, join } from 'path';
import { promisify } from 'util';
import { execFile } from './childProcess.js';
+import { isTestRunner } from './runtimeEnv.js';
+
+// The #6176 data-root guard is loaded ONLY under the test runner. `fileCore` is
+// reached by essentially every server suite, so a static import of the guard
+// (and its `dataRoot`/`pathContainment` closure) landed on every one of them and
+// pushed `importScoping.test.js`'s tree-wide budget over its ceiling. Deferring
+// it behind `isTestRunner()` — the shape server/AGENTS.md prescribes — also means
+// production never loads the guard at all, rather than loading it to no-op.
+// The module promise is memoized, so the dynamic import resolves once per worker.
+let guardModule = null;
+const loadGuard = () => (guardModule ??= import('./testDataIsolation.js'));
export const execFileAsync = promisify(execFile);
const IS_WIN = process.platform === 'win32';
@@ -87,6 +98,9 @@ export function watchForFile(filePath, onDetected, { settleMs = 50, pollMs = FIL
* await ensureDir('/custom/path/to/dir');
*/
export async function ensureDir(dir) {
+ // #6176 — refuse a NEW dir in the real data/ tree under the runner. Only the
+ // CREATE path: `mkdir -p` on an existing directory mutates nothing.
+ if (isTestRunner()) (await loadGuard()).assertNotNewRealDataDir(dir);
// mkdir with recursive: true is idempotent - it succeeds if dir exists.
// BUT on Windows it can intermittently throw UNKNOWN/EPERM/EEXIST even when
// the directory already exists or is created concurrently — antivirus locks,
@@ -159,6 +173,10 @@ export async function ensureDirs(dirs) {
* await atomicWrite(LOG_FILE, 'raw string content');
*/
export async function atomicWrite(filePath, data) {
+ // #6176 — the filesystem analogue of db.js's row-write backstop. Refuses
+ // before any bytes are produced, so a leaking suite cannot even leave a temp
+ // file behind in the real tree.
+ if (isTestRunner()) (await loadGuard()).assertNotRealDataWrite(filePath, 'atomicWrite');
// Buffer must pass through unchanged — JSON.stringify on a Buffer produces
// `{"type":"Buffer","data":[...]}` which corrupts binary writes (PNG, etc.).
const payload = typeof data === 'string' || Buffer.isBuffer(data) ? data : JSON.stringify(data, null, 2);
@@ -224,6 +242,39 @@ export async function atomicWrite(filePath, data) {
}
}
+/**
+ * `writeFile`, `appendFile` and `copyFile` with the #6176 data-root guard.
+ *
+ * `atomicWrite` is the primitive almost every writer should use, and it is
+ * guarded. These exist for the writers that genuinely cannot: an append (which
+ * replaces nothing), an exclusive `{ flag: 'wx' }` create (where the flag IS
+ * the mechanism), a byte-for-byte copy, and a destination whose name is already
+ * clamped to NAME_MAX (atomicWrite's `.<pid>.<ts>.<uuid>.tmp` suffix would push
+ * the temp file past it).
+ *
+ * Exported as wrappers rather than left as an `assertNotRealDataWrite` call at
+ * each site, so the NEXT raw writer inherits the guard instead of having to
+ * remember the import.
+ */
+
+/** Guarded `fs/promises.writeFile`. Same signature. */
+export async function writeFileGuarded(filePath, data, options) {
+ if (isTestRunner()) (await loadGuard()).assertNotRealDataWrite(filePath, 'writeFile');
+ return writeFile(filePath, data, options);
+}
+
+/** Guarded `fs/promises.appendFile`. Same signature. */
+export async function appendFileGuarded(filePath, data, options) {
+ if (isTestRunner()) (await loadGuard()).assertNotRealDataWrite(filePath, 'appendFile');
+ return appendFile(filePath, data, options);
+}
+
+/** Guarded `fs/promises.copyFile` — the DESTINATION is what gets written. */
+export async function copyFileGuarded(src, dest, mode) {
+ if (isTestRunner()) (await loadGuard()).assertNotRealDataWrite(dest, 'copyFile');
+ return copyFile(src, dest, mode);
+}
+
export const MINUTE = 60 * 1000;
export const HOUR = 60 * MINUTE;
export const DAY = 24 * HOUR;
diff --git a/server/lib/heavyJobClaim.js b/server/lib/heavyJobClaim.js
index 867a49f547..f50efe4fa6 100644
--- a/server/lib/heavyJobClaim.js
+++ b/server/lib/heavyJobClaim.js
@@ -8,10 +8,10 @@
*/
import { randomUUID } from 'crypto';
-import { mkdir, readFile, unlink, writeFile } from 'fs/promises';
+import { mkdir, readFile, unlink } from 'fs/promises';
import { existsSync, readFileSync, unlinkSync } from 'fs';
import { dirname, join } from 'path';
-import { PATHS, sleep } from './fileUtils.js';
+import { PATHS, sleep, writeFileGuarded } from './fileUtils.js';
export const HEAVY_LOCAL_JOB_CLAIM_PATH = join(PATHS.data, 'heavy-local-job.claim.json');
export const HEAVY_LOCAL_JOB_STALE_MS = 24 * 60 * 60 * 1000;
@@ -95,7 +95,7 @@ export async function claimHeavyLocalJob({
for (;;) {
try {
- await writeFile(claimPath, JSON.stringify(ours), { flag: 'wx' });
+ await writeFileGuarded(claimPath, JSON.stringify(ours), { flag: 'wx' });
heldClaims.set(claimPath, token);
installExitCleanup();
let released = false;
@@ -110,7 +110,7 @@ export async function claimHeavyLocalJob({
const current = await readHolder(claimPath);
if (current?.token !== token) return;
ours.pid = childPid;
- await writeFile(claimPath, JSON.stringify(ours));
+ await writeFileGuarded(claimPath, JSON.stringify(ours));
heldClaims.delete(claimPath);
},
async release() {
diff --git a/server/lib/index.js b/server/lib/index.js
index 9f5df74dce..1fdc42257a 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -228,6 +228,7 @@ export * from './portosEnv.js';
export * from './homePath.js';
export * from './jsonIo.js';
export * from './mimeTypes.js';
+export * from './pathContainment.js';
export * from './paths.js';
export * from './pathSafety.js';
export * from './uploads.js';
@@ -504,4 +505,6 @@ export * from './gitTestRepo.js';
export * from './mockPathsDataRoot.js';
export * from './settingsTestUtil.js';
export * from './dbTestGate.js';
+export * from './runtimeEnv.js';
+export * from './testDataIsolation.js';
export * from './testHelper.js';
diff --git a/server/lib/jsonIo.js b/server/lib/jsonIo.js
index 641cd45c4a..2679e8ce3b 100644
--- a/server/lib/jsonIo.js
+++ b/server/lib/jsonIo.js
@@ -1,8 +1,8 @@
/** JSON, JSONL, and cached-store file IO helpers. */
import { existsSync } from 'fs';
-import { appendFile, open, readFile, readdir, stat } from 'fs/promises';
+import { open, readFile, readdir, stat } from 'fs/promises';
import { basename, dirname } from 'path';
-import { atomicWrite, ensureDir, sleep } from './fileCore.js';
+import { appendFileGuarded, atomicWrite, ensureDir, sleep } from './fileCore.js';
import { createFileWriteQueue } from './fileWriteQueue.js';
const isWindows = () => process.platform === 'win32';
@@ -472,7 +472,7 @@ export async function appendJSONLine(filePath, value) {
throw new TypeError('appendJSONLine value must be JSON-serializable');
}
await ensureDir(dirname(filePath));
- await appendFile(filePath, serialized + '\n');
+ await appendFileGuarded(filePath, serialized + '\n');
}
/**
diff --git a/server/lib/mockPathsDataRoot.js b/server/lib/mockPathsDataRoot.js
index ac33a4c217..50ad26ac7b 100644
--- a/server/lib/mockPathsDataRoot.js
+++ b/server/lib/mockPathsDataRoot.js
@@ -52,6 +52,45 @@ export function createTempDataRoot(prefix = 'portos-test-') {
return mkdtempSync(join(tmpdir(), prefix));
}
+/**
+ * A temp data root allocated on FIRST USE and memoized per prefix.
+ *
+ * `vi.mock` is hoisted above every `const` in the file, so a suite whose SUT is
+ * reached through a static `import` trips the mock factory while a
+ * `const TEST_DATA_ROOT = createTempDataRoot(...)` is still in its temporal dead
+ * zone — a `ReferenceError` at collection time. Passing this function as
+ * `makePathsProxy`'s `dataRoot` sidesteps that: the root is created the first
+ * time the Proxy reads `PATHS`, which is always after module evaluation.
+ *
+ * Memoized per prefix so every read in one file gets the SAME root (a fresh dir
+ * per read would scatter a suite's writes across directories), and so two
+ * suites naming different prefixes never share one.
+ *
+ * Pair with `afterAll(cleanupTempDataRoots)`.
+ *
+ * vi.mock('../lib/fileUtils.js', async (importOriginal) =>
+ * makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-foo-') }));
+ * afterAll(cleanupTempDataRoots);
+ *
+ * @param {string} prefix - mkdtemp prefix, also the memo key
+ * @returns {string} absolute path to this prefix's temp root
+ */
+const lazyRoots = new Map();
+export function lazyTempDataRoot(prefix = 'portos-test-') {
+ let root = lazyRoots.get(prefix);
+ if (!root) {
+ root = createTempDataRoot(prefix);
+ lazyRoots.set(prefix, root);
+ }
+ return root;
+}
+
+/** Remove every root `lazyTempDataRoot` handed out in this worker. */
+export function cleanupTempDataRoots() {
+ for (const root of lazyRoots.values()) rmSync(root, { recursive: true, force: true });
+ lazyRoots.clear();
+}
+
/**
* Build the Proxy returned from a `vi.mock('../lib/fileUtils.js', ...)`
* factory. Pass the already-resolved `actual` (from `vi.importActual`) and
diff --git a/server/lib/pathContainment.js b/server/lib/pathContainment.js
new file mode 100644
index 0000000000..c3bdc1fdc5
--- /dev/null
+++ b/server/lib/pathContainment.js
@@ -0,0 +1,78 @@
+/**
+ * Path containment and canonicalization — the questions "is this path inside
+ * that directory" and "what path would the filesystem really act on".
+ *
+ * A dependency-free LEAF on purpose. The #6176 data-root guard reaches these
+ * from `fileCore.js`, which essentially every server suite imports — taking
+ * them from `pathSafety.js` instead would drag `errorHandler.js` and `paths.js`
+ * into that closure and push `importScoping.test.js`'s tree-wide budget over its
+ * ceiling. Keep this module free of imports beyond node builtins.
+ *
+ * `pathSafety.js` keeps its own `isPathInsideDir` — the STRICT form, where the
+ * root is not "inside" itself, which is what file containment wants. The two
+ * are separate declarations rather than one importing the other precisely so
+ * this leaf stays unreachable from that module's consumers; the shared part is
+ * one case-folding expression, not the subtle part. A flat-barrel name
+ * collision would also force a namespace export on one of them.
+ */
+
+import { realpathSync } from 'fs';
+import { platform } from 'os';
+import { basename, dirname, join, resolve as resolvePath, sep as PATH_SEP } from 'path';
+
+const CASE_INSENSITIVE_FS = platform() === 'win32' || platform() === 'darwin';
+
+/**
+ * `pathSafety.js`'s `isPathInsideDir`, but the root itself also counts as inside.
+ *
+ * File containment wants the strict form — a directory is not one of the files
+ * in it. A guard that refuses to WRITE anywhere in a tree wants this one:
+ * writing a file over the tree's own path is no more acceptable than writing
+ * under it. Case-folded on Windows/macOS for the same reason the strict form is.
+ *
+ * @param {string} dir - the containing directory
+ * @param {string} candidatePath - the path to test
+ * @returns {boolean}
+ */
+export function isPathAtOrInsideDir(dir, candidatePath) {
+ if (typeof dir !== 'string' || typeof candidatePath !== 'string' || !dir || !candidatePath) {
+ return false;
+ }
+ const fold = (p) => (CASE_INSENSITIVE_FS ? p.toLowerCase() : p);
+ const root = fold(resolvePath(dir));
+ const target = fold(resolvePath(candidatePath));
+ return target === root || target.startsWith(root + PATH_SEP);
+}
+
+/**
+ * The path the filesystem would really act on: realpath of the deepest
+ * EXISTING ancestor, plus the not-yet-created tail. `realpathSync` throws
+ * ENOENT on a path that has not been created yet — which is every first write
+ * to a destination — and a component that does not exist cannot be a symlink,
+ * so resolving the ancestor and re-attaching the tail is both safe and the
+ * only form that works before the target exists.
+ *
+ * Without it a symlinked ancestor (`/tmp` → `/private/tmp` on macOS, or a
+ * data dir symlinked onto another volume) compares unresolved, and a
+ * containment check reads two spellings of one directory as two directories.
+ *
+ * Returns `resolved` unchanged when nothing along the chain resolves.
+ *
+ * @param {string} target - path to canonicalize (resolved to absolute first)
+ * @returns {string}
+ */
+export function canonicalizePath(target) {
+ const resolved = resolvePath(target);
+ const tail = [];
+ let existing = resolved;
+ for (;;) {
+ try {
+ return join(realpathSync(existing), ...tail);
+ } catch {
+ const parent = dirname(existing);
+ if (parent === existing) return resolved; // hit the root; nothing resolved
+ tail.unshift(basename(existing));
+ existing = parent;
+ }
+ }
+}
diff --git a/server/lib/pathSafety.js b/server/lib/pathSafety.js
index f0221f04cd..81ce57ab99 100644
--- a/server/lib/pathSafety.js
+++ b/server/lib/pathSafety.js
@@ -114,26 +114,25 @@ export function isTopLevelEntryName(name) {
/**
* True when `candidatePath` resolves to a location strictly inside `dir`.
*
- * Uses the same anchored-prefix containment idiom as `makePathResolver`
- * (`resolvePath(dir) + PATH_SEP`): appending the platform separator to the
- * resolved root means a sibling directory whose name merely *starts with* the
- * root (e.g. `/data/uploads-evil` vs `/data/uploads`) can't slip past a bare
- * `startsWith(root)` check. This is stricter than the `resolvedPath.startsWith(DIR)`
- * guard the upload/attachment/screenshot routes used before. The root itself is
- * NOT reported as "inside" (there's no trailing separator on the bare root),
- * which is the desired behavior for file-containment checks.
+ * The root itself is NOT reported as "inside", which is the desired behavior
+ * for file containment. `pathContainment.js` owns the root-inclusive variant
+ * (`isPathAtOrInsideDir`) for guards that police a whole tree; the two are
+ * deliberately separate declarations rather than one importing the other,
+ * because that module is a leaf `fileCore.js` reaches and this one drags
+ * `errorHandler`/`paths` — see the budget in `importScoping.test.js`.
+ *
+ * Uses an anchored-prefix idiom (`resolvePath(dir) + PATH_SEP`): appending the
+ * platform separator means a sibling whose name merely *starts with* the root
+ * (`/data/uploads-evil` vs `/data/uploads`) can't slip past a bare
+ * `startsWith(root)` check.
*
* Comparison is case-INSENSITIVE on Windows and macOS, whose filesystems are.
* A bare `startsWith` there reports `C:\\Users\\Foo\\wt` as outside
* `C:\\Users\\foo`, even though both name the same directory — so a managed
* worktree read as `worktree-unmanaged-location` and was silently never reaped.
- * Git is a live source of such spellings: `git worktree list` reports paths the
- * way git normalized them (drive-letter case, 8.3 short names like
- * `C:\\Users\\RUNNER~1`), which need not match how PortOS spelled the root.
* Case-folding only ever makes containment recognize paths that ARE the same
* file on that platform; it can never admit a path from outside the root, so
- * the security posture is unchanged. Linux stays case-sensitive, where two
- * spellings really are two different directories.
+ * the security posture is unchanged. Linux stays case-sensitive.
*
* @param {string} dir - the containing directory (absolute or relative)
* @param {string} candidatePath - the path to test
diff --git a/server/lib/runtimeEnv.js b/server/lib/runtimeEnv.js
new file mode 100644
index 0000000000..cdb53f725d
--- /dev/null
+++ b/server/lib/runtimeEnv.js
@@ -0,0 +1,31 @@
+/**
+ * Which runtime is this process? Dependency-free on purpose.
+ *
+ * Kept apart from every module that has an opinion about storage, paths, or
+ * the database, because the lowest-level file primitives (`fileCore.js`) and
+ * the highest-level backend selectors both need this answer. `db.js` used to
+ * own `isTestRunner`, which forced anything asking the question to pull in
+ * `pg` — and, worse, meant the many suites that write
+ * `vi.mock('../lib/db.js', () => ({ query }))` silently stripped it out of the
+ * module graph for every other consumer in that suite.
+ */
+
+/**
+ * Are we executing under a test runner?
+ *
+ * `NODE_ENV === 'test'` alone is not reliable: a suite run from a CoS-agent
+ * worktree (or any wrapper that sets NODE_ENV=development / leaves it unset)
+ * still executes test code, and every guard and backend selector keyed on
+ * NODE_ENV then quietly chooses the production path. Vitest always sets
+ * `process.env.VITEST` in every worker process, so OR-ing it in arms them
+ * regardless of how NODE_ENV was (mis)configured. This is the signal that
+ * actually closed the 2026-06-14 fixture leak into the real Postgres.
+ *
+ * Read on every call rather than captured at module load, so a test can pin
+ * either variable and observe the change.
+ *
+ * @returns {boolean}
+ */
+export function isTestRunner() {
+ return process.env.NODE_ENV === 'test' || process.env.VITEST != null;
+}
diff --git a/server/lib/tempPathGuard.js b/server/lib/tempPathGuard.js
index 29d90ce8a0..8bb133f637 100644
--- a/server/lib/tempPathGuard.js
+++ b/server/lib/tempPathGuard.js
@@ -23,34 +23,14 @@
* itself is not an acceptable target: `destroyGitSandbox(tmpdir())` would
* recursively delete the whole system temp directory.
*/
-import { realpathSync } from 'fs';
import { tmpdir } from 'os';
-import { basename, dirname, isAbsolute, join, resolve, sep } from 'path';
-
-/**
- * The path the filesystem would really act on: realpath of the deepest existing
- * ancestor, plus the not-yet-created tail (a fixture's `scratch/primary` does
- * not exist yet, and a path component that does not exist cannot be a symlink).
- */
-function canonicalize(resolved) {
- const tail = [];
- let existing = resolved;
- for (;;) {
- try {
- return join(realpathSync(existing), ...tail);
- } catch {
- const parent = dirname(existing);
- if (parent === existing) return resolved; // hit the root; nothing resolved
- tail.unshift(basename(existing));
- existing = parent;
- }
- }
-}
+import { isAbsolute, resolve, sep } from 'path';
+import { canonicalizePath } from './pathContainment.js';
function tempRoots() {
// Read `tmpdir()` on every call: TMPDIR is per-process env, and tests stub it.
const raw = resolve(tmpdir());
- return [...new Set([raw, canonicalize(raw)])];
+ return [...new Set([raw, canonicalizePath(raw)])];
}
// Windows paths compare case-insensitively, and a TEMP env var spelled with
@@ -73,7 +53,7 @@ function isStrictlyUnder(child, parent) {
export function isTempPath(target) {
if (typeof target !== 'string' || target.length === 0 || !isAbsolute(target)) return false;
if (target.split(/[\\/]+/).includes('..')) return false;
- const canonical = canonicalize(resolve(target));
+ const canonical = canonicalizePath(target);
return tempRoots().some((root) => isStrictlyUnder(canonical, root));
}
diff --git a/server/lib/testDataIsolation.guards.test.js b/server/lib/testDataIsolation.guards.test.js
index 0cd4da37b8..04126f02ef 100644
--- a/server/lib/testDataIsolation.guards.test.js
+++ b/server/lib/testDataIsolation.guards.test.js
@@ -26,8 +26,18 @@
* a data-rooted member (`PATHS.missions`, `PATHS.brain`, …) with no redirect.
* 50 of the ~1300 scoped test files do that, nearly all of them safely, because
* they replace the service graph wholesale and never reach a real `readdir`; a
- * static rule there would be a 50-entry allowlist. That spelling is covered
- * **empirically** instead, by the two-run probe #3687 introduced:
+ * static rule there would be a 50-entry allowlist.
+ *
+ * ## Both halves of that spelling are now covered
+ *
+ * WRITES are covered at RUNTIME by `lib/testDataIsolation.js` (#6176), which
+ * refuses a write landing in the real root from the shared primitives — read its
+ * header for what is and is not yet routed through them.
+ *
+ * READS are still covered **empirically**, by the two-run probe #3687 introduced.
+ * That split is not arbitrary: a read leak changes whether assertions pass, which
+ * is exactly what lets a probe see it, and exactly why the silent write half
+ * needed a guard instead.
*
* 1. Run the server suite on a checkout with an empty `data/`; record failures.
* 2. Plant probe records in every `data/` subdirectory a service enumerates —
@@ -39,8 +49,8 @@
*
* That audit found 2 leakers across 1301 files — `missions.test.js` (fixed in
* #3687) and nothing the static rule below doesn't already catch. Re-run it when
- * touching this area; it is the ground truth, and this rule is the cheap
- * always-on approximation of it.
+ * touching this area; it is the ground truth for reads, and this rule is the
+ * cheap always-on approximation of it.
*
* A test that genuinely needs a data root uses `createTempDataRoot()` +
* `makePathsProxy()` from `lib/mockPathsDataRoot.js`.
diff --git a/server/lib/testDataIsolation.js b/server/lib/testDataIsolation.js
new file mode 100644
index 0000000000..cf586d5876
--- /dev/null
+++ b/server/lib/testDataIsolation.js
@@ -0,0 +1,163 @@
+/**
+ * Runtime backstop: no test may WRITE into the checkout's real `data/` tree.
+ *
+ * ## Why a runtime guard, not another static rule
+ *
+ * `testDataIsolation.guards.test.js` is the always-on *static* half of this
+ * defense: it text-scans every test file for a path spelling that names the
+ * install's `data/` directory. Its own header explains the hole it leaves — a
+ * suite that imports the real `PATHS` and reads a data-rooted member
+ * (`PATHS.brain`, `PATHS.missions`, …) with no redirect is invisible to a text
+ * scan, and ~50 of ~1300 scoped test files legitimately use that spelling, so
+ * closing it statically would need a 50-entry allowlist that rots.
+ *
+ * That spelling was covered *empirically* by the two-run read probe (#3687):
+ * plant records in the real tree, re-run, and a test that now fails is leaking.
+ * A read leak announces itself as a failing assertion. A WRITE leak does not —
+ * persisting fixture bytes over the user's records changes nothing about
+ * whether assertions pass, so the more damaging half went undetected. PR #6171
+ * is the proof it is not hypothetical: `providerUsage.test.js` persisted its
+ * fixture quota cards over the machine's real `data/provider-quotas.json` and
+ * then invalidated the `usage` sync checksum, federating the fabricated values
+ * to subscribed peers.
+ *
+ * So the write half is closed at RUNTIME instead, in the shared write
+ * primitives. This is the filesystem analogue of the database protection in
+ * `lib/db.js` — `isTestRunner()` plus the `query()` backstop that refuses row
+ * writes to a non-test database — which exists because a suite once wiped real
+ * records. A runtime backstop needs no allowlist: it fires on the write that
+ * actually reaches the real root, and stays silent for the ~50 suites that
+ * name `PATHS.*` but never get there.
+ *
+ * ## Scope
+ *
+ * Inert outside the test runner — production writes are never touched, and the
+ * `isTestRunner()` check comes first everywhere so a production call costs two
+ * `process.env` reads and no syscall.
+ *
+ * Under the runner it fires from the shared primitives in `fileCore.js` /
+ * `jsonIo.js` (`atomicWrite`, `ensureDir`'s create path, `writeFileGuarded`,
+ * `appendFileGuarded`, `copyFileGuarded`, `appendJSONLine`) and from
+ * `collectionStore`'s record delete. It is NOT yet universal: roughly forty
+ * services still reach `PATHS.*` with raw `fs` calls of their own (see
+ * `sharing/importer.js`, `videoUpload.js`, `catalogMedia.js`, `genome.js`),
+ * and on a populated install their target directories already exist, so
+ * `ensureDir`'s create-path check is a no-op for them. Routing those onto the
+ * guarded wrappers is tracked as follow-up work — do not read this module as
+ * proof that every write is covered.
+ *
+ * A suite that genuinely needs a data root redirects it with
+ * `createTempDataRoot()` + `makePathsProxy()` from `lib/mockPathsDataRoot.js`;
+ * those roots live under `os.tmpdir()`, so they resolve outside the real root
+ * and pass untouched.
+ *
+ * `server/lib/aiToolkit/` deliberately has NO such guard: that tree is vendored
+ * and self-contained and must not import out to other PortOS modules (see
+ * `aiToolkit/AGENTS.md`).
+ */
+
+import { existsSync } from 'fs';
+import { basename, dirname, join, resolve } from 'path';
+import { resolveCodeRootForModule, resolveInstallRoot } from './dataRoot.js';
+import { canonicalizePath, isPathAtOrInsideDir } from './pathContainment.js';
+import { isTestRunner } from './runtimeEnv.js';
+
+// Resolved lazily, not at module load, so the realpath below sees a tree that
+// exists. Derived through `resolveCodeRootForModule`/`resolveInstallRoot` — the
+// same helpers `lib/paths.js` itself uses, so the two can't silently drift —
+// rather than by importing `PATHS`. That is deliberate: a suite that redirects
+// `PATHS.data` to a temp root (which is exactly what a well-behaved suite does)
+// must not also be able to redirect the guard's idea of what the real root is,
+// or the guard would approve every write it is supposed to refuse.
+let cachedRoot = null;
+const realDataRoot = () => (cachedRoot ??= canonicalizePath(
+ join(resolveInstallRoot(resolveCodeRootForModule(import.meta.url)), 'data'),
+));
+
+// Memo of already-canonicalized DIRECTORIES. Without it every guarded write
+// re-walks its whole path with `realpathSync`, and the misses go through a
+// thrown-and-caught ENOENT — ~0.9ms for a six-deep target, paid by every write
+// in a ~1300-file suite. Only successful resolutions are cached: an existing
+// directory's realpath is stable, while a not-yet-created one could still be
+// created as a symlink, and caching that guess would go stale.
+const resolvedDirs = new Map();
+
+function canonicalDir(dir) {
+ const cached = resolvedDirs.get(dir);
+ if (cached !== undefined) return cached;
+ const resolved = canonicalizePath(dir);
+ if (existsSync(dir)) resolvedDirs.set(dir, resolved);
+ return resolved;
+}
+
+/**
+ * Canonicalize a write target: resolve symlinked ANCESTORS, but never follow a
+ * symlinked final component. That matches what the write actually does —
+ * `atomicWrite` replaces a symlink with a regular file rather than following it
+ * (see its header), so the bytes land at the link's own location.
+ */
+const canonicalTarget = (target) => {
+ const abs = resolve(target);
+ const parent = dirname(abs);
+ return parent === abs ? abs : join(canonicalDir(parent), basename(abs));
+};
+
+/**
+ * Does `target` resolve to the real `data/` root or anything beneath it?
+ *
+ * Containment goes through `isPathAtOrInsideDir`, so it picks up that helper's
+ * case-folding on case-insensitive filesystems — a hand-rolled `relative()`
+ * test would read `…/Data/x.json` on macOS as outside the root it is in fact
+ * inside. Relative paths and `..` climbs are resolved first, so neither can
+ * walk in sideways.
+ *
+ * @param {string} target - path to test
+ * @returns {boolean}
+ */
+export function isInsideRealDataRoot(target) {
+ if (typeof target !== 'string' || target === '') return false;
+ return isPathAtOrInsideDir(realDataRoot(), canonicalTarget(target));
+}
+
+/**
+ * Throw when a test is about to write into the real `data/` tree.
+ *
+ * No-op outside the test runner, so production writes are unaffected.
+ *
+ * @param {string} target - the path about to be written, created, or removed
+ * @param {string} operation - what the caller was about to do, named in the
+ * error (e.g. `'atomicWrite'`) so the failure text alone identifies it
+ * @throws {Error} when the runner is active and `target` lands in the real root
+ */
+export function assertNotRealDataWrite(target, operation) {
+ if (!isTestRunner() || !isInsideRealDataRoot(target)) return;
+ throw new Error(
+ `${operation} refused: this test tried to write ${target} inside the install's real data/ tree ` +
+ `(${realDataRoot()}). A test must never write into the developer's live data — see ` +
+ 'server/lib/testDataIsolation.js. Redirect the data root first: `createTempDataRoot()` + ' +
+ "`makePathsProxy()` from server/lib/mockPathsDataRoot.js, via `vi.mock('<rel>/lib/fileUtils.js', ...)`. " +
+ 'If the write comes from a collaborator the suite forgot to mock (a store, a sync/federation ' +
+ 'path, a usage recorder), mock that collaborator instead of pointing it at the real tree.',
+ );
+}
+
+/**
+ * `assertNotRealDataWrite` for `ensureDir`, which is a no-op on a directory
+ * that already exists.
+ *
+ * Only the CREATE path is refused. Plenty of read-only suites `ensureDir` a
+ * real data subdirectory on their way to reading it, and `mkdir -p` mutates
+ * nothing there — faulting that would be noise, not a leak. Materializing a NEW
+ * directory in the developer's tree IS a write, and it is the step every raw-fs
+ * writer takes before its own `writeFile`.
+ *
+ * Lives here rather than as an `isTestRunner() && !existsSync(dir)` condition
+ * spelled out at the call site, so `fileCore.js` imports one symbol and the
+ * reasoning stays beside the logic.
+ *
+ * @param {string} dir - the directory `ensureDir` is about to create
+ */
+export function assertNotNewRealDataDir(dir) {
+ if (!isTestRunner() || existsSync(dir)) return;
+ assertNotRealDataWrite(dir, 'ensureDir');
+}
diff --git a/server/lib/testDataIsolation.test.js b/server/lib/testDataIsolation.test.js
new file mode 100644
index 0000000000..3c9b47127e
--- /dev/null
+++ b/server/lib/testDataIsolation.test.js
@@ -0,0 +1,162 @@
+/**
+ * Contract for the runtime write backstop (#6176).
+ *
+ * The sibling `testDataIsolation.guards.test.js` is the static half — it scans
+ * test SOURCE for a forbidden path spelling. This file exercises the runtime
+ * half: the primitive actually refuses the write, and only the writes it should.
+ *
+ * The assertions deliberately go through the real `atomicWrite`/`ensureDir`/
+ * `appendJSONLine` rather than calling `assertNotRealDataWrite` alone, because
+ * "the helper throws" is not the product behavior — "the write primitive every
+ * store funnels through throws, before it produces bytes" is. And they assert
+ * the thrown MESSAGE, not merely that something threw: a guard whose error
+ * doesn't name the offending path and the escape hatch sends the next reader
+ * hunting, which is most of the cost of hitting it.
+ */
+
+import { describe, it, expect, vi, afterEach, afterAll } from 'vitest';
+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { appendFileGuarded, atomicWrite, copyFileGuarded, ensureDir, writeFileGuarded } from './fileCore.js';
+import { appendJSONLine } from './jsonIo.js';
+import { assertNotNewRealDataDir, assertNotRealDataWrite, isInsideRealDataRoot } from './testDataIsolation.js';
+import { isTestRunner } from './runtimeEnv.js';
+import { PATHS } from './paths.js';
+
+// The real tree this guard defends. Read from the unmocked PATHS on purpose:
+// this suite mocks nothing, so it is the same root the guard re-derives, and
+// referencing it here proves the two agree.
+const REAL_DATA = PATHS.data;
+const tempRoot = mkdtempSync(join(tmpdir(), 'portos-test-isolation-'));
+
+afterAll(() => rmSync(tempRoot, { recursive: true, force: true }));
+
+afterEach(() => vi.unstubAllEnvs());
+
+describe('isTestRunner', () => {
+ it('is armed by VITEST even when NODE_ENV was dropped by a wrapper', () => {
+ vi.stubEnv('NODE_ENV', 'development');
+ expect(process.env.VITEST).toBeDefined();
+ expect(isTestRunner()).toBe(true);
+ });
+
+ it('is disarmed when neither signal is present', () => {
+ vi.stubEnv('NODE_ENV', 'production');
+ vi.stubEnv('VITEST', undefined);
+ expect(isTestRunner()).toBe(false);
+ });
+});
+
+describe('isInsideRealDataRoot', () => {
+ it('accepts the real data root itself and anything beneath it', () => {
+ expect(isInsideRealDataRoot(REAL_DATA)).toBe(true);
+ expect(isInsideRealDataRoot(join(REAL_DATA, 'brain', 'entries.json'))).toBe(true);
+ });
+
+ it('rejects a temp data root — the sanctioned escape hatch', () => {
+ expect(isInsideRealDataRoot(join(tempRoot, 'brain', 'entries.json'))).toBe(false);
+ });
+
+ it('rejects a sibling that merely shares the prefix', () => {
+ // `startsWith(root)` would match this; `relative()` yields `../data-archive`.
+ expect(isInsideRealDataRoot(`${REAL_DATA}-archive/x.json`)).toBe(false);
+ });
+
+ it('catches a `..` climb back into the real tree', () => {
+ expect(isInsideRealDataRoot(join(REAL_DATA, 'brain', '..', '..', 'data', 'sneaky.json'))).toBe(true);
+ });
+
+ it('is not fooled by a non-string or empty target', () => {
+ expect(isInsideRealDataRoot(undefined)).toBe(false);
+ expect(isInsideRealDataRoot('')).toBe(false);
+ });
+});
+
+describe('assertNotRealDataWrite', () => {
+ it('is inert outside the test runner, so production writes are unaffected', () => {
+ vi.stubEnv('NODE_ENV', 'production');
+ vi.stubEnv('VITEST', undefined);
+ expect(() => assertNotRealDataWrite(join(REAL_DATA, 'x.json'), 'atomicWrite')).not.toThrow();
+ });
+});
+
+describe('atomicWrite', () => {
+ it('writes to a temp data root untouched', async () => {
+ const target = join(tempRoot, 'nested', 'ok.json');
+ await atomicWrite(target, { ok: true });
+ expect(JSON.parse(readFileSync(target, 'utf8'))).toEqual({ ok: true });
+ });
+
+ it('refuses a write into the real data tree, naming the path and the escape hatch', async () => {
+ const target = join(REAL_DATA, 'portos-guard-probe.json');
+ await expect(atomicWrite(target, { leaked: true })).rejects.toThrow(
+ /atomicWrite refused[\s\S]*portos-guard-probe\.json[\s\S]*createTempDataRoot\(\)/,
+ );
+ // Refused BEFORE any bytes were produced — no target and no stranded temp file.
+ expect(existsSync(target)).toBe(false);
+ });
+});
+
+describe('ensureDir', () => {
+ it('refuses to materialize a new directory in the real data tree', async () => {
+ const target = join(REAL_DATA, 'portos-guard-probe-dir');
+ await expect(ensureDir(target)).rejects.toThrow(/ensureDir refused[\s\S]*portos-guard-probe-dir/);
+ expect(existsSync(target)).toBe(false);
+ });
+
+ it('exposes the create-only check as assertNotNewRealDataDir', () => {
+ expect(() => assertNotNewRealDataDir(join(REAL_DATA, 'portos-guard-probe-dir'))).toThrow(/ensureDir refused/);
+ expect(() => assertNotNewRealDataDir(PATHS.installRoot)).not.toThrow();
+ });
+
+ it('stays silent on a directory that already exists — mkdir -p mutates nothing there', async () => {
+ // Read-only suites routinely ensureDir a real data subdirectory on their way
+ // to reading it. That is a no-op on disk, so faulting it would be noise, not
+ // a leak. `PATHS.data`'s own parent (the install root) is always present.
+ await expect(ensureDir(PATHS.installRoot)).resolves.toBeUndefined();
+ });
+});
+
+describe('the guarded raw-fs wrappers', () => {
+ // These exist so a writer that genuinely cannot use atomicWrite (an append,
+ // an exclusive `wx` create, a copy, a NAME_MAX-clamped name) still inherits
+ // the guard instead of having to remember an import.
+ it('writeFileGuarded refuses the real tree and allows a temp root', async () => {
+ await expect(writeFileGuarded(join(REAL_DATA, 'probe.txt'), 'x')).rejects.toThrow(/writeFile refused/);
+ const target = join(tempRoot, 'raw.txt');
+ await writeFileGuarded(target, 'x');
+ expect(readFileSync(target, 'utf8')).toBe('x');
+ });
+
+ it('appendFileGuarded refuses the real tree', async () => {
+ await expect(appendFileGuarded(join(REAL_DATA, 'probe.log'), 'x')).rejects.toThrow(/appendFile refused/);
+ });
+
+ it('copyFileGuarded judges the DESTINATION, not the source', async () => {
+ const src = join(tempRoot, 'src.txt');
+ await writeFileGuarded(src, 'payload');
+ // Source inside the real tree would be a read, which this guard does not police.
+ await expect(copyFileGuarded(src, join(REAL_DATA, 'copied.txt'))).rejects.toThrow(/copyFile refused/);
+ await copyFileGuarded(src, join(tempRoot, 'dest.txt'));
+ expect(readFileSync(join(tempRoot, 'dest.txt'), 'utf8')).toBe('payload');
+ });
+});
+
+describe('appendJSONLine', () => {
+ it('appends to a temp data root untouched', async () => {
+ const target = join(tempRoot, 'log.jsonl');
+ await appendJSONLine(target, { n: 1 });
+ expect(readFileSync(target, 'utf8')).toBe('{"n":1}\n');
+ });
+
+ it('refuses an append into the real data tree', async () => {
+ const target = join(REAL_DATA, 'portos-guard-probe.jsonl');
+ // Names the PRIMITIVE (appendJSONLine delegates to appendFileGuarded), and
+ // the offending path is what identifies the caller.
+ await expect(appendJSONLine(target, { leaked: true })).rejects.toThrow(
+ /appendFile refused[\s\S]*portos-guard-probe\.jsonl/,
+ );
+ expect(existsSync(target)).toBe(false);
+ });
+});
diff --git a/server/lib/uploads.js b/server/lib/uploads.js
index aaa50afaa4..8e5ac2069a 100644
--- a/server/lib/uploads.js
+++ b/server/lib/uploads.js
@@ -1,9 +1,9 @@
/** Upload staging, validation, persistence, and local-file serving helpers. */
-import { copyFile, readFile, stat, unlink, writeFile } from 'fs/promises';
+import { readFile, stat, unlink } from 'fs/promises';
import { randomUUID } from 'crypto';
import { join, resolve as resolvePath } from 'path';
import { ServerError } from './errorHandler.js';
-import { atomicWrite, ensureDir, pathExists } from './fileCore.js';
+import { copyFileGuarded, ensureDir, pathExists, writeFileGuarded } from './fileCore.js';
import { detectImageFormat, getFileExtension, getMimeType, RISKY_MIME_TYPES, sanitizeFilename } from './mimeTypes.js';
import { PATHS } from './paths.js';
import { assertSafeFilename, isPathInsideDir } from './pathSafety.js';
@@ -29,7 +29,7 @@ export async function importFileToDir(tempPath, originalName, destDir, { extensi
await ensureDir(destDir);
const filename = `${randomUUID().slice(0, 8)}-${sanitizeFilename(originalName)}`;
const dest = join(destDir, filename);
- await copyFile(tempPath, dest);
+ await copyFileGuarded(tempPath, dest);
await unlink(tempPath).catch(() => {});
const s = await stat(dest).catch(() => null);
return { filename, sizeBytes: s?.size ?? 0 };
@@ -111,7 +111,10 @@ export async function saveImageUpload(dir, { filename, data }, { maxBytes }) {
}
await ensureDir(dir);
- await writeFile(filePath, buffer);
+ // writeFileGuarded, not atomicWrite: the stored name is clamped to NAME_MAX
+ // just above, and atomicWrite's `.<pid>.<ts>.<uuid>.tmp` suffix would push the
+ // temp file past it (#6176).
+ await writeFileGuarded(filePath, buffer);
return { filename: fname, filePath, size: buffer.length, format: detected.format, mime: detected.mime };
}
@@ -159,7 +162,7 @@ export async function saveBase64Upload(dir, { filename, data }, { allowedExtensi
throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });
}
- await writeFile(filePath, buffer);
+ await writeFileGuarded(filePath, buffer);
return { id, filename: fname, filePath, buffer, size: buffer.length, mime: getMimeType(getFileExtension(fname)) };
}
diff --git a/server/routes/providers.readiness.test.js b/server/routes/providers.readiness.test.js
index 57a70ae8f0..995cb9d3a2 100644
--- a/server/routes/providers.readiness.test.js
+++ b/server/routes/providers.readiness.test.js
@@ -1,4 +1,14 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+// serve-model takes the MACHINE-WIDE heavy-local-job claim, whose path is
+// derived from PATHS.data at module load. Without this redirect the suite wrote
+// that claim into the developer's live data/ tree — briefly gating their real
+// local renders, and stranding the file whenever a case failed mid-claim
+// (#6176).
+vi.mock('../lib/fileUtils.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-readiness-') }));
+afterAll(cleanupTempDataRoots);
import express, { Router } from 'express';
import { errorMiddleware } from '../lib/errorHandler.js';
import { request } from '../lib/testHelper.js';
diff --git a/server/services/agentRunTracking.js b/server/services/agentRunTracking.js
index e40e0143f3..e221ddb570 100644
--- a/server/services/agentRunTracking.js
+++ b/server/services/agentRunTracking.js
@@ -5,7 +5,7 @@
*/
import { join } from 'path';
-import { writeFile, mkdir } from 'fs/promises';
+import { mkdir } from 'fs/promises';
import { v4 as uuidv4 } from '../lib/uuid.js';
import { recordSession } from './usage.js';
import { recordCompletedRunUsage } from './usageReconciler.js';
@@ -59,8 +59,8 @@ export async function createAgentRun({ agentId, task, model, provider, workspace
};
await atomicWrite(join(runDir, 'metadata.json'), metadata);
- await writeFile(join(runDir, 'prompt.txt'), task.description || '');
- await writeFile(join(runDir, 'output.txt'), '');
+ await atomicWrite(join(runDir, 'prompt.txt'), task.description || '');
+ await atomicWrite(join(runDir, 'output.txt'), '');
// Record usage session for CoS agent
recordSession(provider.id, provider.name, model || provider.defaultModel).catch(err => {
@@ -149,7 +149,7 @@ export async function completeAgentRun(runId, output, exitCode, duration, errorA
// Persist output first so endTime remains the durable completion marker. If
// this write fails, the still-open metadata lets recovery retry the whole
// operation; once metadata lands, every run artifact is already complete.
- await writeFile(join(runDir, 'output.txt'), output || '');
+ await atomicWrite(join(runDir, 'output.txt'), output || '');
await atomicWrite(metaPath, metadata);
// Record usage for every completed CoS agent run: failed and interrupted
diff --git a/server/services/agentRunTracking.test.js b/server/services/agentRunTracking.test.js
index bbc3f41aa7..771d3ab011 100644
--- a/server/services/agentRunTracking.test.js
+++ b/server/services/agentRunTracking.test.js
@@ -115,8 +115,13 @@ describe('completeAgentRun idempotency', () => {
it('writes the transcript before stamping the terminal metadata', async () => {
vi.resetModules();
const order = [];
- const atomicWrite = vi.fn().mockImplementation(() => { order.push('metadata'); });
- const writeFile = vi.fn().mockImplementation(() => { order.push('output'); });
+ // Both artifacts are written with atomicWrite (#6176 routed output.txt off
+ // the raw writeFile), so the ordering is read off the PATH, not off which
+ // primitive was called.
+ const atomicWrite = vi.fn().mockImplementation((filePath) => {
+ order.push(String(filePath).endsWith('metadata.json') ? 'metadata' : 'output');
+ });
+ const writeFile = vi.fn();
vi.doMock('../lib/fileUtils.js', async (importOriginal) => ({
...(await importOriginal()),
readJSONFile: vi.fn().mockResolvedValue({
diff --git a/server/services/autonomousJobs/store.js b/server/services/autonomousJobs/store.js
index 0e4b13b5be..7fbeee72d7 100644
--- a/server/services/autonomousJobs/store.js
+++ b/server/services/autonomousJobs/store.js
@@ -8,7 +8,7 @@
* scripts-state.json into jobs.
*/
-import { writeFile, rename, readdir } from 'fs/promises'
+import { rename, readdir } from 'fs/promises'
import { join } from 'path'
import { existsSync } from 'fs'
import { ensureDir, PATHS, readJSONFile, atomicWrite, tryReadFile } from '../../lib/fileUtils.js'
@@ -59,22 +59,22 @@ async function syncSkillTemplatesFromSample() {
const existingContent = await tryReadFile(destPath)
if (!existingContent) {
// Case a: fresh install — seed file and record shipped snapshot
- await writeFile(destPath, sampleContent)
- await writeFile(shippedPath, sampleContent)
+ await atomicWrite(destPath, sampleContent)
+ await atomicWrite(shippedPath, sampleContent)
console.log(`📝 Seeded missing skill template: ${file}`)
continue
}
if (existingContent === sampleContent) {
// Case b: file already matches sample — ensure .shipped is current
const shippedContent = await tryReadFile(shippedPath)
- if (shippedContent !== sampleContent) await writeFile(shippedPath, sampleContent)
+ if (shippedContent !== sampleContent) await atomicWrite(shippedPath, sampleContent)
continue
}
const shippedContent = await tryReadFile(shippedPath)
if (existingContent === shippedContent) {
// Case c: file matches last-shipped snapshot but sample has changed — safe to update
- await writeFile(destPath, sampleContent)
- await writeFile(shippedPath, sampleContent)
+ await atomicWrite(destPath, sampleContent)
+ await atomicWrite(shippedPath, sampleContent)
console.log(`🔄 Updated unmodified skill template: ${file}`)
} else {
// Case d: for installs upgrading from a pre-.shipped release, any existing
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index e28d625faa..3ba2117293 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -1098,29 +1098,40 @@ describe('getState and saveState', () => {
writeLog = [];
// `vi.doMock` is NOT hoisted, so the factory can close over `tmpRoot` and
- // `writeLog`. Only PATHS.data and atomicWrite are overridden — readJSONFile,
- // ensureDir and the rest stay real.
+ // `writeLog`. makePathsProxy rather than a hand-rolled `PATHS: { ...actual.PATHS,
+ // data: tmpRoot }`: spelling one member by hand re-roots only `data`, leaving
+ // every other data-derived member (`backup`'s siblings, `imageRefs`, …) aimed
+ // at the live install — the #3683/#6176 partial-redirect trap. `overrides`
+ // carries the atomicWrite spy, which is why this stays a doMock at all.
vi.doMock('../lib/fileUtils.js', async (importOriginal) => {
const actual = await importOriginal();
- return {
- ...actual,
- PATHS: { ...actual.PATHS, data: tmpRoot },
- // Bracket the real write with log markers and a delay, so an unqueued
- // read-merge-write would visibly interleave (start/start/end/end).
- atomicWrite: async (filePath, data) => {
- writeLog.push(`start:${data?.status}`);
- await new Promise((r) => setTimeout(r, 10));
- const result = await actual.atomicWrite(filePath, data);
- writeLog.push(`end:${data?.status}`);
- return result;
- }
- };
+ return makePathsProxy(actual, {
+ dataRoot: () => tmpRoot,
+ overrides: {
+ // Bracket the real write with log markers and a delay, so an unqueued
+ // read-merge-write would visibly interleave (start/start/end/end).
+ atomicWrite: async (filePath, data) => {
+ writeLog.push(`start:${data?.status}`);
+ await new Promise((r) => setTimeout(r, 10));
+ const result = await actual.atomicWrite(filePath, data);
+ writeLog.push(`end:${data?.status}`);
+ return result;
+ },
+ },
+ });
});
backup = await import('./backup.js');
});
afterEach(async () => {
- vi.doUnmock('../lib/fileUtils.js');
+ // Re-register the FILE-LEVEL redirect instead of calling `vi.doUnmock`.
+ // `doUnmock` drops the hoisted `vi.mock` at the top of this file too, so
+ // every suite AFTER this one resolved PATHS.data to the install's real
+ // data/ tree — and `runBackup lifecycle` below then rewrote the
+ // developer's genuine data/backup/state.json on every run (#6176; the
+ // runtime write guard is what surfaced it).
+ vi.doMock('../lib/fileUtils.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), { dataRoot: testDataRoot }));
vi.resetModules();
const { rm } = await import('fs/promises');
if (tmpRoot) await rm(tmpRoot, { recursive: true, force: true });
diff --git a/server/services/brainSyncLog.js b/server/services/brainSyncLog.js
index 83a9694185..e358a62796 100644
--- a/server/services/brainSyncLog.js
+++ b/server/services/brainSyncLog.js
@@ -10,11 +10,11 @@
* write — so one lagging peer stalled local writes once per sync cycle (#5441).
*/
-import { readFile, appendFile, stat } from 'fs/promises';
+import { readFile, stat } from 'fs/promises';
import { existsSync, createReadStream } from 'fs';
import { join } from 'path';
import { createMutex } from '../lib/asyncMutex.js';
-import { ensureDir, safeJSONParse, PATHS, atomicWrite } from '../lib/fileUtils.js';
+import { appendFileGuarded, ensureDir, safeJSONParse, PATHS, atomicWrite } from '../lib/fileUtils.js';
const DATA_DIR = PATHS.brain;
const SYNC_LOG_FILE = join(DATA_DIR, 'sync_log.jsonl');
@@ -106,7 +106,7 @@ async function ensureIndex() {
*/
async function writeIndexedLines(lines) {
const payload = (pendingNewline ? '\n' : '') + lines.map(({ text }) => text).join('\n') + '\n';
- await appendFile(SYNC_LOG_FILE, payload).catch((err) => {
+ await appendFileGuarded(SYNC_LOG_FILE, payload).catch((err) => {
indexLoaded = false;
throw err;
});
diff --git a/server/services/cosState.js b/server/services/cosState.js
index deeb7c706a..4aa30b7bbf 100644
--- a/server/services/cosState.js
+++ b/server/services/cosState.js
@@ -4,7 +4,7 @@
* Shared state management for Chief of Staff services.
*/
-import { readFile, writeFile, readdir, rm, rename } from 'fs/promises';
+import { readFile, readdir, rm, rename } from 'fs/promises';
import { existsSync } from 'fs';
import { join, dirname, basename } from 'path';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
@@ -220,7 +220,7 @@ function mergeStoredConfig(storedConfig) {
async function quarantineCorruptFile(filePath, content, label, { remove = false } = {}) {
const backupPath = `${filePath}.corrupted.${Date.now()}`;
const moved = remove && await rename(filePath, backupPath).then(() => true).catch(() => false);
- if (!moved) await writeFile(backupPath, content).catch(() => {});
+ if (!moved) await atomicWrite(backupPath, content).catch(() => {});
console.log(`📝 Backed up corrupted ${label} to ${backupPath}`);
const dir = dirname(filePath);
const prefix = `${basename(filePath)}.corrupted.`;
diff --git a/server/services/identity.test.js b/server/services/identity.test.js
index a3d5fb2c1a..d611542db9 100644
--- a/server/services/identity.test.js
+++ b/server/services/identity.test.js
@@ -1,4 +1,6 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
import {
extractSleepMarkers,
extractCaffeineMarkers,
@@ -16,6 +18,23 @@ import {
// fs/promises with a simple path-keyed in-memory store; makeFsPromisesStore()
// supplies the rename/unlink/mkdir the real atomicWrite needs so the temp→final
// move lands in the same store the reads come from.
+afterAll(cleanupTempDataRoots);
+
+// Every integration block below installs BOTH halves of the isolation: the
+// in-memory fs above, and a redirected data root. Nothing here reaches a disk
+// either way, but the runtime write guard (#6176) judges the PATH and cannot
+// see that the filesystem underneath is a fake — and naming a disposable root
+// means a future edit that drops the fs/promises mock can't quietly start
+// writing into the developer's live data. Registered with `doMock` rather than
+// a file-level `vi.mock` so each `vi.resetModules()` below rebuilds a FRESH
+// store; a hoisted mock would hand every test the first one, and the goal CRUD
+// cases would then accumulate each other's records.
+function mockIdentityStorage() {
+ vi.doMock('fs/promises', makeFsPromisesStore);
+ vi.doMock('../lib/fileUtils.js', async () =>
+ makePathsProxy(await vi.importActual('../lib/fileUtils.js'), { dataRoot: () => lazyTempDataRoot('portos-identity-') }));
+}
+
function makeFsPromisesStore() {
const store = {};
return {
@@ -600,7 +619,7 @@ describe('Integration: deriveChronotype', () => {
vi.resetModules();
// Mock fs/promises
- vi.doMock('fs/promises', makeFsPromisesStore);
+ mockIdentityStorage();
// Mock genome service
vi.doMock('./genome.js', () => ({
@@ -689,7 +708,7 @@ describe('Integration: getIdentityStatus', () => {
beforeEach(async () => {
vi.resetModules();
- vi.doMock('fs/promises', makeFsPromisesStore);
+ mockIdentityStorage();
vi.doMock('./genome.js', () => ({
getGenomeSummary: vi.fn(async () => ({
@@ -726,7 +745,7 @@ describe('Integration: getIdentityStatus', () => {
it('should show genome as active when markers exist', async () => {
vi.resetModules();
- vi.doMock('fs/promises', makeFsPromisesStore);
+ mockIdentityStorage();
vi.doMock('./genome.js', () => ({
getGenomeSummary: vi.fn(async () => ({
@@ -780,7 +799,7 @@ describe('Integration: deriveLongevity', () => {
beforeEach(async () => {
vi.resetModules();
- vi.doMock('fs/promises', makeFsPromisesStore);
+ mockIdentityStorage();
vi.doMock('./genome.js', () => ({
getGenomeSummary: vi.fn(async () => ({
@@ -856,7 +875,7 @@ describe('Integration: Goal CRUD', () => {
beforeEach(async () => {
vi.resetModules();
- vi.doMock('fs/promises', makeFsPromisesStore);
+ mockIdentityStorage();
vi.doMock('./genome.js', () => ({
getGenomeSummary: vi.fn(async () => ({
@@ -1049,7 +1068,7 @@ describe('Integration: Goal Tree', () => {
beforeEach(async () => {
vi.resetModules();
- vi.doMock('fs/promises', makeFsPromisesStore);
+ mockIdentityStorage();
vi.doMock('./genome.js', () => ({
getGenomeSummary: vi.fn(async () => ({
@@ -1107,7 +1126,7 @@ describe('Integration: Progress Log', () => {
beforeEach(async () => {
vi.resetModules();
- vi.doMock('fs/promises', makeFsPromisesStore);
+ mockIdentityStorage();
vi.doMock('./genome.js', () => ({
getGenomeSummary: vi.fn(async () => ({
@@ -1168,7 +1187,7 @@ describe('Integration: Calendar Linking', () => {
beforeEach(async () => {
vi.resetModules();
- vi.doMock('fs/promises', makeFsPromisesStore);
+ mockIdentityStorage();
vi.doMock('./genome.js', () => ({
getGenomeSummary: vi.fn(async () => ({
@@ -1252,7 +1271,7 @@ describe('Integration: applyGoalOrganization', () => {
beforeEach(async () => {
vi.resetModules();
- vi.doMock('fs/promises', makeFsPromisesStore);
+ mockIdentityStorage();
vi.doMock('./genome.js', () => ({
getGenomeSummary: vi.fn(async () => ({
@@ -1409,7 +1428,7 @@ describe('Integration: organizeGoals', () => {
beforeEach(async () => {
vi.resetModules();
- vi.doMock('fs/promises', makeFsPromisesStore);
+ mockIdentityStorage();
vi.doMock('./genome.js', () => ({
getGenomeSummary: vi.fn(async () => ({
@@ -1485,7 +1504,7 @@ describe('Integration: organizeGoals', () => {
it('should throw when no AI provider is available', async () => {
vi.resetModules();
- vi.doMock('fs/promises', makeFsPromisesStore);
+ mockIdentityStorage();
vi.doMock('./genome.js', () => ({
getGenomeSummary: vi.fn(async () => ({
diff --git a/server/services/loraTraining/captionLeakStaging.test.js b/server/services/loraTraining/captionLeakStaging.test.js
index 72f1d4642d..534b65585a 100644
--- a/server/services/loraTraining/captionLeakStaging.test.js
+++ b/server/services/loraTraining/captionLeakStaging.test.js
@@ -1,4 +1,14 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';
+
+// runTraining takes the machine-wide heavy-local-job claim, whose path is
+// derived from PATHS.data at module load. Without this redirect the suite wrote
+// (and briefly held) the claim in the developer's LIVE data/ tree — a file that
+// gates their real local renders, stranded there whenever a case failed before
+// the release (#6176).
+vi.mock('../../lib/fileUtils.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-caption-leak-') }));
+afterAll(cleanupTempDataRoots);
// Regression guard for the caption-leak gate's SECOND call site. The gate is
// re-checked when the queued job actually stages (runTraining), not just at
diff --git a/server/services/modelAbuseGuard.materialize.test.js b/server/services/modelAbuseGuard.materialize.test.js
index 558223d865..ce786e85dc 100644
--- a/server/services/modelAbuseGuard.materialize.test.js
+++ b/server/services/modelAbuseGuard.materialize.test.js
@@ -1,20 +1,30 @@
-import { afterEach, describe, expect, it } from 'vitest';
+import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';
import { mkdtemp, readFile, rm, stat } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { PATHS } from '../lib/fileUtils.js';
import { PUBLIC_REVIEW_INPUT_FILENAME, PUBLIC_REVIEW_PATCH_DIRNAME } from '../lib/agentScratchPaths.js';
-import {
- materializePublicReviewInput,
- materializePublicReviewPatches,
- writePublicReviewInputSnapshot,
- PUBLIC_REVIEW_PATCH_MANIFEST_FILENAME,
-} from './modelAbuseGuard.js';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
// Runs against the real filesystem on purpose: the materializers were only ever
// exercised through mocks, which is how a callback-style `chmod` from `node:fs`
// (throws synchronously when called without a callback) shipped and failed every
// Stage 2 spawn with "The \"cb\" argument must be of type function".
+//
+// Real filesystem, but not the INSTALL's filesystem: the snapshot writer lands
+// under `PATHS.cos`, so without this redirect the suite deposited
+// `public-review-inputs/<scanKey>.json` in the developer's live data/ tree —
+// swept up by the afterEach only when nothing above it threw (#6176).
+vi.mock('../lib/fileUtils.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-public-review-data-') }));
+afterAll(cleanupTempDataRoots);
+
+const { PATHS } = await import('../lib/fileUtils.js');
+const {
+ materializePublicReviewInput,
+ materializePublicReviewPatches,
+ writePublicReviewInputSnapshot,
+ PUBLIC_REVIEW_PATCH_MANIFEST_FILENAME,
+} = await import('./modelAbuseGuard.js');
const scanKey = 'a'.repeat(64);
const headSha = 'b'.repeat(40);
const pullRequests = [{
diff --git a/server/services/postRunStore.js b/server/services/postRunStore.js
index 8af0086723..366e72f708 100644
--- a/server/services/postRunStore.js
+++ b/server/services/postRunStore.js
@@ -8,7 +8,7 @@ import { join } from 'path';
import { atomicWrite, ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';
import { isPlainObject } from '../lib/objects.js';
import { createPgFileFacade, resolvePgBackend } from '../lib/pgFileFacade.js';
-import { isTestRunner } from '../lib/db.js';
+import { isTestRunner } from '../lib/runtimeEnv.js';
import {
getScoredSession as getScoredSessionDb,
listScoredSessions as listScoredSessionsDb,
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.js
index d3c1d980c5..5decbd4e97 100644
--- a/server/services/sharing/importer.js
+++ b/server/services/sharing/importer.js
@@ -22,10 +22,10 @@
*/
import { join, basename } from 'path';
-import { copyFile, readdir } from 'fs/promises';
+import { readdir } from 'fs/promises';
import { existsSync } from 'fs';
import { EventEmitter } from 'events';
-import { PATHS, ensureDir, atomicWrite, readJSONFile } from '../../lib/fileUtils.js';
+import { PATHS, copyFileGuarded, ensureDir, atomicWrite, readJSONFile } from '../../lib/fileUtils.js';
import { isSafeRecordId } from '../../lib/validation.js';
import { getBucket, bucketBlobPath, bucketBlobSidecarPath, bucketRecordsDir, bucketRecordPath, imageSidecarName, isHexHash } from './buckets.js';
import { readManifest, markProcessed, readCursor, hasBeenProcessed, forgetProcessed } from './manifest.js';
@@ -298,12 +298,12 @@ async function copyAssetsLocally(bucketPath, assetRefs) {
}
available.push({ kind, ref: filename });
if (!existsSync(targetPath)) {
- await copyFile(blobPath, targetPath);
+ await copyFileGuarded(blobPath, targetPath);
copied.push({ kind, ref: filename });
}
if (sidecarPath && existsSync(sidecarPath)) {
const sidecarTarget = join(targetDir, imageSidecarName(filename));
- if (!existsSync(sidecarTarget)) await copyFile(sidecarPath, sidecarTarget);
+ if (!existsSync(sidecarTarget)) await copyFileGuarded(sidecarPath, sidecarTarget);
}
}));
return { copied, available, missing };
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index e857422c8a..4f35dfe54d 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -13,7 +13,7 @@ import { mkdtempSync, rmSync, writeFileSync, existsSync, mkdirSync, readFileSync
import { tmpdir } from 'os';
import { join } from 'path';
import { createHash } from 'crypto';
-import { mockNoPeerSync, mockNoPeers } from '../../lib/mockPathsDataRoot.js';
+import { makePathsProxy, mockNoPeerSync, mockNoPeers } from '../../lib/mockPathsDataRoot.js';
function sha256Hex(buf) {
return createHash('sha256').update(buf).digest('hex');
@@ -25,20 +25,14 @@ function sha256Hex(buf) {
const tempData = mkdtempSync(join(tmpdir(), 'portos-sharing-roundtrip-data-'));
let tempBucket;
-vi.mock('../../lib/fileUtils.js', async () => {
- const actual = await vi.importActual('../../lib/fileUtils.js');
- return new Proxy(actual, {
- get(target, prop) {
- if (prop === 'PATHS') return {
- ...actual.PATHS,
- data: tempData,
- images: join(tempData, 'images'),
- videos: join(tempData, 'videos'),
- };
- return target[prop];
- },
- });
-});
+// makePathsProxy, not a hand-rolled one: this suite listed `data`/`images`/
+// `videos` by hand, so `PATHS.imageRefs` — added later — still resolved to the
+// install's live `data/image-refs`, and the importer's copyAssetsLocally
+// created it and copied bundled reference sheets there on every run (#6176).
+// The shared helper re-roots EVERY member that lives under `data/`, so a member
+// added tomorrow is covered without touching this file.
+vi.mock('../../lib/fileUtils.js', async () =>
+ makePathsProxy(await vi.importActual('../../lib/fileUtils.js'), { dataRoot: tempData }));
// Stub instances.getInstanceId so the exporter doesn't try to read the
// real identity.json. Returns a fixed id for assertions.
diff --git a/server/services/sprites/records.js b/server/services/sprites/records.js
index ea4a4b217d..1f4217be0c 100644
--- a/server/services/sprites/records.js
+++ b/server/services/sprites/records.js
@@ -14,7 +14,7 @@
* #2895's scope); the tombstone trio on the record keeps peer-sync additive.
*/
-import { isTestRunner } from '../../lib/db.js';
+import { isTestRunner } from '../../lib/runtimeEnv.js';
import { ServerError } from '../../lib/errorHandler.js';
import { createRecordStoreBackendSelector } from '../../lib/pgFileFacade.js';
import { listSpriteAssets } from './paths.js';
diff --git a/server/services/userActions.js b/server/services/userActions.js
index 9bd9e5533e..b82c13fda8 100644
--- a/server/services/userActions.js
+++ b/server/services/userActions.js
@@ -46,8 +46,8 @@ import { atomicWrite, ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { isPlainObject } from '../lib/objects.js';
import { createPgFileFacade, resolvePgBackend } from '../lib/pgFileFacade.js';
-import { isTestRunner } from '../lib/db.js';
-import { resolveCodeRootForModule, resolveInstallRoot } from '../lib/dataRoot.js';
+import { isTestRunner } from '../lib/runtimeEnv.js';
+import { isInsideRealDataRoot } from '../lib/testDataIsolation.js';
import { isUserActionActor, isUserActionType } from '../lib/userActionTypes.js';
import { insertUserActionEvent, listUserActionEvents, pruneUserActionEvents } from './userActionsDb.js';
@@ -56,14 +56,6 @@ import { insertUserActionEvent, listUserActionEvents, pruneUserActionEvents } fr
// pre-mock value and crash any suite whose fileUtils stub omits PATHS.data.
const eventsFile = () => join(PATHS.data, 'user-action-events.json');
-// The REAL repo data/ dir, computed independently of the (possibly test-mocked)
-// `PATHS` import above via the same resolveCodeRootForModule/resolveInstallRoot
-// technique lib/paths.js itself uses (both go through the shared helper, so
-// they can't silently drift apart) — so a suite that redirects PATHS.data to a
-// temp root can't accidentally spoof this comparison too. `dataRoot.js` reads
-// its own env var directly rather than through anything a PATHS mock would touch.
-const REAL_REPO_DATA_DIR = join(resolveInstallRoot(resolveCodeRootForModule(import.meta.url)), 'data');
-
/**
* Structural guard against the bug class in #3683/#3687/#5605: a suite that
* exercises a route wired to `recordUserAction` without redirecting
@@ -77,13 +69,16 @@ const REAL_REPO_DATA_DIR = join(resolveInstallRoot(resolveCodeRootForModule(impo
*
* Reads are guarded as well as writes: the live ledger holds machine-local
* operator records (ADR docs/decisions/2026-08-08-privacy-records-machine-local.md),
- * so an untethered suite must not pull them into the test process either.
+ * so an untethered suite must not pull them into the test process either. That
+ * read half is why this stays a local guard rather than folding into #6176's
+ * write backstop; the real-root derivation itself is shared with it, so the two
+ * can't disagree about which tree is live.
*
* @param {string} attempted what the file backend was about to do, e.g.
* `'recordUserAction attempted a write of'`
*/
function assertTestDataRootRedirected(attempted) {
- if (!isTestRunner() || PATHS.data !== REAL_REPO_DATA_DIR) return;
+ if (!isTestRunner() || !isInsideRealDataRoot(eventsFile())) return;
throw new Error(
`${attempted} user-action-events.json in the repo's real data/ tree. ` +
'This suite exercises the user-action ledger but never redirected ' +