Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: force NODE_ENV=test in the server vitest configs and guard git fixtures against escaping os.tmpdir() (#4554)
[._.]/ Adam Eivye98e7e40258c
diff --git a/.githooks/pre-commit b/.githooks/pre-commitindex 37556e4517..611b3d58b5 100755--- a/.githooks/pre-commit+++ b/.githooks/pre-commit@@ -37,7 +37,11 @@ printf -- "\n🔎 pre-commit: validating staged PortOS changes\n"if [ "$run_server" = true ]; thenprintf -- "- running server tests...\n"- npm test --prefix server+ # NODE_ENV=test is what points the suite at the file storage backend instead+ # of the developer's live Postgres. server/vitest.config.js now forces it, but+ # a commit fired from a PortOS-spawned shell inherits NODE_ENV=development+ # from PM2, so state it here too — the hook must be correct on its own (#4554).+ NODE_ENV=test npm test --prefix serverfiif [ "$run_client" = true ]; thendiff --git a/CLAUDE.md b/CLAUDE.mdindex e3d4440cdf..05d96df9b5 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -13,6 +13,9 @@ npm run install:all # includes git submodule update --init --recursive# per workspace to scope to one — both are Vitest, with different environments:cd server && npm test # Vitest (node) — ALSO globs ../scripts, ../lib, ../autofixercd client && npm test # Vitest (jsdom) — component/unit tests+# No NODE_ENV prefix needed: server/vitest.config.js FORCES NODE_ENV=test (#4554).+# Vitest only defaults it when unset, and PortOS runs under PM2 with+# NODE_ENV=development — a suite run that inherits that aims at the real Postgres.npm run test:db # DB-backed suites → portos_test ONLY (see Security Model)```diff --git a/autofixer/sandbox.git.test.js b/autofixer/sandbox.git.test.jsindex f533dd2811..16b991d933 100644--- a/autofixer/sandbox.git.test.js+++ b/autofixer/sandbox.git.test.js@@ -15,6 +15,11 @@ import {applyDiffToLive,execGit,} from './sandbox.js';+// The autofixer package has no runner of its own — these specs run under the+// server vitest config's '../autofixer/**' glob — and tempPathGuard.js imports+// nothing but node builtins, so reusing it here keeps ONE definition of "is+// this really a throwaway dir" rather than a second copy (#4554).+import { assertTempPath } from '../server/lib/tempPathGuard.js';// Exercises the disposable-worktree isolation + promotion helpers against a// real throwaway git repo. These prove the agent's edits land in an isolated@@ -25,6 +30,10 @@ describe('git worktree isolation (integration)', () => {beforeEach(async () => {scratch = await mkdtemp(join(tmpdir(), 'autofix-git-'));+ // The 'git config user.email test@test' lines below are what corrupted a+ // real checkout once, so prove the target is disposable before running any+ // of them — never let a bad path fall through to process.cwd() (#4554).+ assertTempPath(scratch, 'autofixer git fixture setup');repo = join(scratch, 'repo');await mkdir(repo, { recursive: true });await execGit(['init', '-q'], repo);@@ -37,6 +46,7 @@ describe('git worktree isolation (integration)', () => {});afterEach(async () => {+ assertTempPath(scratch, 'autofixer git fixture teardown');await rm(scratch, { recursive: true, force: true }).catch(() => {});});diff --git a/autofixer/sandbox.js b/autofixer/sandbox.jsindex df8961cefd..0b027c117d 100644--- a/autofixer/sandbox.js+++ b/autofixer/sandbox.js@@ -348,7 +348,16 @@ export function validateProposedDiff(diff, opts = {}) {* an error shape instead.*/export function execGit(gitArgs, cwd) {- return new Promise((resolve) => {+ return new Promise((resolve, reject) => {+ // A missing cwd makes `spawn` fall back to `process.cwd()` — which for the+ // autofixer suite is the PortOS checkout itself, so a fixture that lost its+ // temp dir would `git init` / `git config` the developer's real repo.+ // This is a caller bug, not a git failure, so it rejects rather than+ // resolving with the `{ code: -1 }` shape reserved for spawn errors (#4554).+ if (typeof cwd !== 'string' || cwd.trim() === '') {+ reject(new Error(`execGit requires a working directory: git ${gitArgs.join(' ')}`));+ return;+ }const child = spawn('git', gitArgs, { cwd, windowsHide: true });let stdout = '';let stderr = '';diff --git a/server/lib/README.md b/server/lib/README.mdindex f93e28fc39..5f4dcce45a 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -201,7 +201,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `commandSecurity.js` | Allowlist of safe shell commands + `validatePm2Command(args)` (rejects daemon-wide `pm2 kill`/`startup`/`unstartup` and `<verb> all`). `validateCommand` runs the pm2 check for `pm2` base commands. Mirrored by the `agentGuard/` PATH shim for agentic paths. || `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd,killProcessGroup?})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Group-kill mode persists a marker so cancel, reattach, and orphan reaping terminate a group-leader wrapper plus every runtime child together. Windows has no double-fork (plain-spawn fallback), so its handle's `kill` delegates to `killProcessTree` (`taskkill /T /F`) — a cancel there takes the runner's children with it. Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart (boot re-attach, #1332) and `reapDetached` to checkpoint-kill one when re-attach isn't possible. || `hostShutdown.js` | Tells "PortOS was restarted out from under a running agent" apart from "the agent failed" (#3202). `markHostShuttingDown()` / `isHostShuttingDown()` are the in-process latch the SIGTERM/SIGINT handler sets first thing; `shouldAbandonForHostShutdown({sentinelPresent,terminatedByUser,paused})` keeps every spawn path on the same preserve-vs-finalize policy. `writeHostShutdownMarker({agentIds,signal})` / `readHostShutdownMarker()` / `clearHostShutdownMarker()` persist that verdict to `data/cos/host-shutdown.json` so the NEXT boot's orphan sweep can requeue those agents as *interrupted* — no orphan-retry charge, no 30-minute cooldown. All non-throwing: a missing marker degrades to the ordinary orphan path. |-| `execGit.js` | `execGit` utility imported by `git.js` + worktree manager. |+| `execGit.js` | `execGit(args, cwd, options)` utility imported by `git.js` + worktree manager. `cwd` is REQUIRED — it rejects on a missing/blank one rather than letting `spawn` fall back to `process.cwd()` and run git against PortOS's own checkout (#4554). || `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). Includes `probeFrameCount(videoPath)` (metadata `nb_frames`, falling back to a real `-count_frames` pass — expensive, so call it once per file) and `trimVideoFromFrame(videoPath, outPath, {startFrame, fps})` — a frame-EXACT head cut via the `trim` filter (an `-ss` seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with `atrim` when the clip has a soundtrack and taking `-an` when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; `outPath` may equal the input (temp-file + rename install). Used by the chained-render context window — see `videoContinuity.js`. `buildTrimConcatArgs({inputs, outPath, width, height, fps, withAudio})` builds the argv for the other half of that job: a concat that drops leading frames from some of its inputs inside a `filter_complex` graph, so the cuts ride along with the timeline encode instead of costing one pre-encode per clip (pass `withAudio` only when EVERY input has an audio stream — check with `hasAudioStream`). `H264_ENCODE_ARGS` / `AAC_ENCODE_ARGS` are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. Every re-encode here also pins BT.709: `BT709_CONTAINER_ARGS` (the `colr` atom, always emitted) plus `bt709TagFilter()` → the `BT709_TAG_FILTER` `setparams=…` string, or `null` on an ffmpeg without that filter (`supportsSetparamsFilter()` probes `-filters` once per process; `null` = not probed, and a probe that couldn't run stays uncached). Both halves are required — from ffmpeg 8 the encoder reads color properties off the FRAMES, silently overriding the container flags, so a flags-only output decodes washed-out. `buildTrimConcatArgs` takes the filter as its `colorTagFilter` option rather than probing, to stay pure. || `ffmpegRenderGuard.js` | `attachFfmpegRenderGuard(proc, {label, onSpawnError, onProcessError, onClose})` — shared spawn-state tracking + exactly-once `terminal` guard + pre-vs-post-spawn dispatch for the SSE ffmpeg render runners (musicVideo/render + videoTimeline/local). Owns the 'spawn'/'error'/'close' wiring (only the pre-spawn 'error' or 'close' finalizes; a post-spawn 'error' records only) and takes the service-specific finalize bodies as callbacks so each renderer keeps its own project-status/history behavior. || `gitArgs.js` | `PROTECTED_BRANCHES`, `validateFilePaths(files)` — pure command-arg builders/validators for `git.js` (reject injection/traversal in staged paths). |@@ -321,6 +321,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `renderSlot.js` | Render-slot helpers for `(proof\|final)Image` per stage. || `renderTargets.js` | Render-target alphabet (#3231): `RENDER_TARGET`/`RENDER_TARGETS` name every creative surface that enqueues renders (universe-bible, sprite-reference, music-video, …) — the keys into `settings.renderDefaults` — plus the `RENDER_TARGET_BACKEND_AUTO` fall-through sentinel. Dependency-free leaf; resolved per surface by `services/imageGen/cloudProviderConfig.js#resolveRenderTargetConfig`. || `telegramClient.js` | Telegram bot client. |+| `tempPathGuard.js` | Throwaway-path guard for destructive test fixtures. `isTempPath(target)` — true only for an absolute path under `os.tmpdir()` (both the raw dir and its realpath count, so macOS `/var/folders/...` vs `/private/var/folders/...` both pass); `assertTempPath(target, operation)` throws otherwise and returns `target` so it can wrap an argument inline. Use it before any fixture `git init` / `git config` / `rm -rf`: `spawn` silently substitutes `process.cwd()` for a missing cwd, which is how a test run once set `core.bare = true` on a real checkout (#4554). || `vaultCrypto.js` | Privacy Center PII Vault field-level encryption (issue #2140). AES-256-GCM `encryptValue`/`decryptValue` (`v1:<iv>:<tag>:<ct>` format, per-value 12-byte IV), `ensureVaultKey()` self-heal (generates `PRIVACY_VAULT_KEY` into the install root's `.env` on first write, replacing any invalid line; never logs the value), key resolution that falls back to reading `.env` so decrypt/status survive a server restart, `isVaultKeyConfigured()`, and the per-type `maskValue(type, plaintext)` display masking (last-4 / domain-visible / street-masked). Plaintext must never be logged by callers. |## Model & config@@ -386,7 +387,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|-| `gitTestRepo.js` | Shared real-git sandbox for integration tests (#4394): one initialized template (working tree + bare origin) per worker, then `fs.cp` into a fresh temp dir. `makeGitSandbox({ origin })`, `attachBareOrigin(scratch, repo)`, `materializeGitRepo(dest)`, `destroyGitSandbox`, plus `SKIP_HEAVY_INTEGRATION` (`VITEST_FAST=1`). Still real git — just not rebuilt from `init`+`commit`+`push` in every `beforeEach`. |+| `gitTestRepo.js` | Shared real-git sandbox for integration tests (#4394): one initialized template (working tree + bare origin) per worker, then `fs.cp` into a fresh temp dir. `makeGitSandbox({ origin })`, `attachBareOrigin(scratch, repo)`, `materializeGitRepo(dest)`, `destroyGitSandbox`, plus `SKIP_HEAVY_INTEGRATION` (`VITEST_FAST=1`). Every entry point runs `assertTempPath` first, so a path outside `os.tmpdir()` throws instead of `git init`-ing or `rm -rf`-ing a real checkout (#4554). Still real git — just not rebuilt from `init`+`commit`+`push` in every `beforeEach`. || `mirrorParity.js` | Source-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`), and `compareDeclaration(serverSrc, clientSrc, name)`. Use these instead of hand-rolling a brace-walker per mirror. Pure — no `vitest` import — so callers own the assertions. || `mockPathsDataRoot.js` | Shared Vitest helpers for `PATHS.data → temp dir` 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. |diff --git a/server/lib/execGit.js b/server/lib/execGit.jsindex 18eaae1c29..720543287f 100644--- a/server/lib/execGit.js+++ b/server/lib/execGit.js@@ -8,7 +8,8 @@ import { spawn } from './childProcess.js';/*** Execute a git command safely using spawn (prevents shell injection).* @param {string[]} args - Git command arguments- * @param {string} cwd - Working directory+ * @param {string} cwd - Working directory (required — an absent cwd would+ * silently resolve to process.cwd(), i.e. PortOS's own checkout)* @param {object} options - Additional options* @param {number} [options.maxBuffer] - Max output buffer size in bytes (default 10 MB)* @param {number} [options.timeout] - Timeout in ms (default 30s)@@ -17,6 +18,14 @@ import { spawn } from './childProcess.js';*/export function execGit(args, cwd, options = {}) {return new Promise((resolve, reject) => {+ // `spawn` treats a missing cwd as `process.cwd()`, so a caller whose repo+ // path came back undefined (a fixture whose temp-dir setup failed, a+ // config lookup that returned nothing) would run `git init` / `git config`+ // against PortOS's own checkout instead of failing. Refuse loudly (#4554).+ if (typeof cwd !== 'string' || cwd.trim() === '') {+ reject(new Error(`❌ execGit requires a working directory: git ${args.join(' ')}`));+ return;+ }const maxBuffer = options.maxBuffer || 10 * 1024 * 1024;const timeout = options.timeout || 30000;// Always disable the shell to keep this helper a hard boundary againstdiff --git a/server/lib/gitTestRepo.js b/server/lib/gitTestRepo.jsindex 807b8397fe..6353c9b41e 100644--- a/server/lib/gitTestRepo.js+++ b/server/lib/gitTestRepo.js@@ -15,6 +15,7 @@ import { rmSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { execGit } from './execGit.js';+import { assertTempPath } from './tempPathGuard.js';export const SKIP_HEAVY_INTEGRATION = ['1', 'true', 'yes'].includes(String(process.env.VITEST_FAST || '').toLowerCase(),@@ -39,12 +40,14 @@ async function copyTree(src, dest) {}async function configureIdentity(repo, identity = DEFAULT_IDENTITY) {+ assertTempPath(repo, 'git config on a fixture repo');await execGit(['config', 'user.email', identity.email], repo);await execGit(['config', 'user.name', identity.name], repo);await execGit(['config', 'commit.gpgsign', 'false'], repo);}async function stripOrigin(repo) {+ assertTempPath(repo, 'git remote surgery on a fixture repo');await execGit(['remote', 'remove', 'origin'], repo, { ignoreExitCode: true });await execGit(['branch', '--unset-upstream'], repo, { ignoreExitCode: true });}@@ -75,6 +78,7 @@ async function buildTemplate() {const scratch = await mkdtemp(join(tmpdir(), TEMPLATE_PREFIX));const repo = join(scratch, 'primary');const origin = join(scratch, 'origin.git');+ assertTempPath(scratch, 'git init for the fixture template');await execGit(['init', '-b', 'main', repo], scratch);await configureIdentity(repo);await writeFile(join(repo, 'initial.txt'), 'initial');@@ -107,6 +111,7 @@ export async function makeGitSandbox({} = {}) {const template = await getTemplate();const scratch = await mkdtemp(join(tmpdir(), prefix));+ assertTempPath(scratch, 'git sandbox creation');const repo = join(scratch, 'primary');await cp(template.repo, repo, { recursive: true, force: true });if (identity) await configureIdentity(repo, identity);@@ -128,6 +133,8 @@ export async function makeGitSandbox({* publish those commits.*/export async function attachBareOrigin(scratch, repo) {+ assertTempPath(scratch, 'bare-origin attach');+ assertTempPath(repo, 'bare-origin attach');const template = await getTemplate();const originPath = join(scratch, 'origin.git');await cp(template.origin, originPath, { recursive: true, force: true });@@ -142,6 +149,7 @@ export async function attachBareOrigin(scratch, repo) {* temp dir — `git worktree list` spelling / realpath checks.*/export async function materializeGitRepo(dest, { identity } = {}) {+ assertTempPath(dest, 'git repo materialization');const template = await getTemplate();await copyTree(template.repo, dest);await stripOrigin(dest);@@ -151,5 +159,6 @@ export async function materializeGitRepo(dest, { identity } = {}) {export async function destroyGitSandbox(scratch) {if (!scratch) return;+ assertTempPath(scratch, 'recursive sandbox delete');await rm(scratch, { recursive: true, force: true }).catch(() => {});}diff --git a/server/lib/index.js b/server/lib/index.jsindex 150b537eba..34167196d6 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -302,6 +302,7 @@ export * from './markdownText.js';export * from './renderSlot.js';export * from './renderTargets.js';export * from './telegramClient.js';+export * from './tempPathGuard.js';export * from './textUtils.js';export * from './vaultCrypto.js';diff --git a/server/lib/tempPathGuard.js b/server/lib/tempPathGuard.jsnew file mode 100644index 0000000000..9e1869f49c--- /dev/null+++ b/server/lib/tempPathGuard.js@@ -0,0 +1,71 @@+/**+ * "Is this path really a throwaway?" guard for destructive test fixtures (#4554).+ *+ * Test helpers that `git init`, `git config`, or `rm -rf` a directory are only+ * safe because that directory lives under `os.tmpdir()`. When the path they are+ * handed is `undefined`, empty, or relative, the underlying primitive does not+ * fail — `child_process.spawn` silently substitutes `process.cwd()`, so a+ * fixture's `git init --bare` / `git config user.email test@test` lands on the+ * developer's real checkout. That is exactly how a server-suite run corrupted a+ * live `.git/config` (`core.bare = true`, commits re-attributed to+ * `test <test@test>`).+ *+ * These helpers turn that silent fallback into a loud throw: resolve the target+ * and refuse anything that is not an absolute path under the OS temp dir.+ * Both the raw `os.tmpdir()` and its realpath count as roots, because macOS+ * reports `/var/folders/...` while `realpath` yields `/private/var/folders/...`.+ */+import { realpathSync } from 'fs';+import { tmpdir } from 'os';+import { isAbsolute, resolve, sep } from 'path';++const realpathOrSelf = (candidate) => {+ try {+ return realpathSync(candidate);+ } catch {+ // Not created yet (a fixture's `scratch/primary`) — the resolved path is+ // the best answer we have, and its temp-ness is decided by its ancestors.+ return candidate;+ }+};++function tempRoots() {+ // Read `tmpdir()` on every call: TMPDIR is per-process env, and tests stub it.+ const raw = resolve(tmpdir());+ const real = realpathOrSelf(raw);+ return real === raw ? [raw] : [raw, real];+}++const isUnder = (child, parent) =>+ child === parent || child.startsWith(parent.endsWith(sep) ? parent : `${parent}${sep}`);++/**+ * True when `target` is an absolute path inside the OS temp dir.+ * A non-string, empty, or relative `target` is always false — those are the+ * shapes that would otherwise be resolved against `process.cwd()`.+ */+export function isTempPath(target) {+ if (typeof target !== 'string' || target.length === 0 || !isAbsolute(target)) return false;+ const resolved = resolve(target);+ const candidates = resolved === realpathOrSelf(resolved)+ ? [resolved]+ : [resolved, realpathOrSelf(resolved)];+ return tempRoots().some((root) => candidates.some((candidate) => isUnder(candidate, root)));+}++/**+ * Throw unless `target` is a temp path. Returns `target` so it can wrap an+ * argument inline: `await execGit(['init', repo], assertTempPath(scratch, 'git init'));`+ *+ * @param {string} target - directory a destructive fixture operation will run against+ * @param {string} operation - what is about to run, for the error message+ * @returns {string} target+ */+export function assertTempPath(target, operation = 'this operation') {+ if (isTempPath(target)) return target;+ throw new Error(+ `❌ refusing to run ${operation} outside ${tmpdir()} — got ${JSON.stringify(target)}. `+ + 'Test git fixtures must target a directory created under os.tmpdir(); '+ + 'a missing or relative path would fall back to process.cwd() and mutate the real checkout.',+ );+}diff --git a/server/lib/tempPathGuard.test.js b/server/lib/tempPathGuard.test.jsnew file mode 100644index 0000000000..636f7151a3--- /dev/null+++ b/server/lib/tempPathGuard.test.js@@ -0,0 +1,160 @@+/**+ * Regression guard for #4554 — a server-suite run mutated the developer's real+ * `.git/config` (`core.bare = true`, `user.email = test@test`), because a git+ * fixture reached `spawn` with an unusable cwd and `spawn` quietly substitutes+ * `process.cwd()`.+ *+ * Each guard case is paired with a BYPASS PROBE: the same helper, same on-disk+ * directory, run once where the guard permits it. The probe proves the guarded+ * operation is genuinely destructive (it really does `git init` / really does+ * `rm -rf`), so a passing guard case means "the guard stopped it", not "this+ * call never did anything anyway".+ *+ * The "non-temp" directory is physically created under `os.tmpdir()` and only+ * LOOKS non-temp because TMPDIR is stubbed elsewhere for the duration — the+ * suite never writes outside the OS temp dir, and never near a real checkout.+ */+import { describe, it, expect, afterEach, vi } from 'vitest';+import { mkdtemp, rm, writeFile, readFile, readdir } from 'fs/promises';+import { existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { isTempPath, assertTempPath } from './tempPathGuard.js';+import { execGit } from './execGit.js';+import {+ materializeGitRepo,+ destroyGitSandbox,+ attachBareOrigin,+ SKIP_HEAVY_INTEGRATION,+} from './gitTestRepo.js';++const scratches = [];++async function scratchDir(prefix = 'portos-tempguard-') {+ const dir = await mkdtemp(join(tmpdir(), prefix));+ scratches.push(dir);+ return dir;+}++/**+ * Make `os.tmpdir()` report a DIFFERENT directory, so a path that is really in+ * the OS temp dir reads as non-temp to the guard. `os.tmpdir()` consults these+ * env vars on every call (TMPDIR on POSIX, TEMP/TMP on Windows).+ */+function pretendTmpdirIs(dir) {+ vi.stubEnv('TMPDIR', dir);+ vi.stubEnv('TMP', dir);+ vi.stubEnv('TEMP', dir);+}++afterEach(async () => {+ vi.unstubAllEnvs();+ while (scratches.length) {+ await rm(scratches.pop(), { recursive: true, force: true }).catch(() => {});+ }+});++describe('isTempPath', () => {+ it('accepts a directory created under os.tmpdir()', async () => {+ expect(isTempPath(await scratchDir())).toBe(true);+ });++ it('accepts a not-yet-created child of a temp directory', async () => {+ expect(isTempPath(join(await scratchDir(), 'primary'))).toBe(true);+ });++ it('rejects the shapes that would resolve against process.cwd()', () => {+ // `spawn({ cwd: undefined })` and a relative cwd are the exact inputs that+ // silently became "the real checkout" in #4554.+ expect(isTempPath(undefined)).toBe(false);+ expect(isTempPath(null)).toBe(false);+ expect(isTempPath('')).toBe(false);+ expect(isTempPath('relative/repo')).toBe(false);+ expect(isTempPath('.')).toBe(false);+ expect(isTempPath(42)).toBe(false);+ });++ it('rejects an absolute path outside the temp dir', async () => {+ const outside = await scratchDir();+ pretendTmpdirIs(await scratchDir());+ expect(isTempPath(outside)).toBe(false);+ });+});++describe('assertTempPath', () => {+ it('returns the path so it can wrap an argument inline', async () => {+ const dir = await scratchDir();+ expect(assertTempPath(dir, 'probe')).toBe(dir);+ });++ it('names the operation it refused', () => {+ expect(() => assertTempPath(undefined, 'git init')).toThrow(/refusing to run git init/);+ });+});++describe('execGit refuses to guess a working directory', () => {+ // BYPASS PROBE: with a real cwd the same call succeeds, so the rejections+ // below are the guard firing — not `git rev-parse` being broken.+ it('runs when handed a real directory (probe)', async () => {+ const dir = await scratchDir();+ await execGit(['init', '-q'], dir);+ const { stdout } = await execGit(['rev-parse', '--is-inside-work-tree'], dir);+ expect(stdout.trim()).toBe('true');+ });++ it.each([undefined, null, '', ' '])('rejects cwd %p instead of using process.cwd()', async (cwd) => {+ await expect(execGit(['init', '-q'], cwd)).rejects.toThrow(/requires a working directory/);+ });+});++describe.skipIf(SKIP_HEAVY_INTEGRATION)('gitTestRepo refuses non-temp targets', () => {+ it('materializeGitRepo git-inits a temp dir but leaves a non-temp dir untouched', async () => {+ // BYPASS PROBE — guard permits: the helper really does create a repo.+ const allowed = await scratchDir();+ await materializeGitRepo(allowed);+ expect(existsSync(join(allowed, '.git'))).toBe(true);++ // Guard case — same helper, a directory the guard sees as non-temp.+ const victim = await scratchDir();+ await writeFile(join(victim, 'keep.txt'), 'untouched');+ pretendTmpdirIs(await scratchDir());++ await expect(materializeGitRepo(victim)).rejects.toThrow(/refusing to run/);+ expect(existsSync(join(victim, '.git'))).toBe(false);+ expect(await readdir(victim)).toEqual(['keep.txt']);+ expect(await readFile(join(victim, 'keep.txt'), 'utf8')).toBe('untouched');+ });++ it('attachBareOrigin refuses before touching the repo it was pointed at', async () => {+ const victim = await scratchDir();+ await materializeGitRepo(victim);+ const before = await execGit(['remote'], victim);+ expect(before.stdout.trim()).toBe('');++ pretendTmpdirIs(await scratchDir());+ await expect(attachBareOrigin(victim, victim)).rejects.toThrow(/refusing to run/);++ vi.unstubAllEnvs();+ const after = await execGit(['remote'], victim);+ expect(after.stdout.trim()).toBe('');+ expect(existsSync(join(victim, 'origin.git'))).toBe(false);+ });+});++describe('destroyGitSandbox refuses to rm -rf a non-temp directory', () => {+ it('deletes a temp dir but refuses the same dir once it reads as non-temp', async () => {+ // BYPASS PROBE — guard permits: this helper really is `rm -rf`.+ const doomed = await scratchDir();+ await writeFile(join(doomed, 'file.txt'), 'x');+ await destroyGitSandbox(doomed);+ expect(existsSync(doomed)).toBe(false);++ // Guard case.+ const victim = await scratchDir();+ await writeFile(join(victim, 'file.txt'), 'x');+ pretendTmpdirIs(await scratchDir());++ await expect(destroyGitSandbox(victim)).rejects.toThrow(/refusing to run/);+ expect(existsSync(join(victim, 'file.txt'))).toBe(true);+ });+});diff --git a/server/vitest.config.db.js b/server/vitest.config.db.jsindex 2e23efca0f..d0873e38a8 100644--- a/server/vitest.config.db.js+++ b/server/vitest.config.db.js@@ -1,5 +1,11 @@import { defineConfig } from 'vitest/config';+// Same reason as vitest.config.js: an inherited NODE_ENV (PM2 exports+// 'development') is NOT overridden by vitest's own default, and the DB guards+// in lib/db.js key on it. Force it so `npm run test:db` behaves identically+// wherever it is launched from (#4554).+process.env.NODE_ENV = 'test';+/*** The DB-backed test files, relative to this config's root (server/). Exported* as the single source of truth: this config's `include` uses it, and the drift@@ -59,6 +65,7 @@ export default defineConfig({// One file at a time — these suites assume exclusive access to their tables.fileParallelism: false,env: {+ NODE_ENV: 'test',PGDATABASE: process.env.PGTESTDATABASE || 'portos_test',},include: DB_TEST_INCLUDE,diff --git a/server/vitest.config.js b/server/vitest.config.jsindex ad77140947..42d4fdd957 100644--- a/server/vitest.config.js+++ b/server/vitest.config.js@@ -8,9 +8,24 @@ if (process.env.npm_lifecycle_event === 'test:fast') {process.env.VITEST_FAST = '1';}+// The suite REQUIRES NODE_ENV=test: it is what selects the file storage backend+// (memoryBackend.js and every store facade) so no suite talks to the real+// Postgres. Vitest only DEFAULTS NODE_ENV to 'test' when it is unset, and PortOS+// runs under PM2 with NODE_ENV=development — so any commit made from a+// PortOS-spawned shell fires .githooks/pre-commit -> 'npm test --prefix server'+// with NODE_ENV=development inherited, and hundreds of suites then aim at the+// developer's live database (#4554). Forcing it here, rather than prefixing the+// npm script, keeps every entry point correct — 'npm test --prefix server', a+// bare 'npx vitest run', an IDE runner, the git hook — and stays Windows-safe+// (cmd.exe parses 'NODE_ENV=test vitest' as an executable name, which is why+// VITEST_FAST is set here too).+process.env.NODE_ENV = 'test';+export default defineConfig({test: {...vitestCiPool(),+ // Workers get their own process.env — set it there as well as above.+ env: { NODE_ENV: 'test' },testTimeout: process.platform === 'win32' ? 30000 : 10000,// hookTimeout tracks testTimeout for the same reason: Windows fs + module// resolution is markedly slower, and vitest's 10s DEFAULT applies to hooksdiff --git a/server/vitest.config.test.js b/server/vitest.config.test.jsnew file mode 100644index 0000000000..5ba4b7bbea--- /dev/null+++ b/server/vitest.config.test.js@@ -0,0 +1,45 @@+/**+ * Regression guard for #4554 — the server suite MUST run with NODE_ENV=test.+ *+ * That single variable is what makes every store facade pick the file backend+ * instead of the developer's live Postgres. Vitest supplies `NODE_ENV=test`+ * only when the variable is UNSET, and PortOS itself runs under PM2 with+ * `NODE_ENV=development` (`ecosystem.config.cjs`) — so a commit fired from a+ * PortOS-spawned shell ran `.githooks/pre-commit` -> `npm test --prefix server`+ * with `development` inherited, and hundreds of suites aimed at the real+ * database. Measured on the reproduction: 457 failures across 43 files under+ * `NODE_ENV=development`, versus 1 under `NODE_ENV=test`.+ *+ * The configs therefore FORCE the value rather than defaulting it. These cases+ * assert the forcing, not the defaulting — the bypass probe is the stubbed+ * `development` value each one starts from.+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';++const CONFIGS = ['./vitest.config.js', './vitest.config.db.js'];++beforeEach(() => {+ vi.resetModules();+});++afterEach(() => {+ // Restores the pre-stub value even though the config under test reassigns+ // process.env.NODE_ENV directly.+ vi.unstubAllEnvs();+});++describe.each(CONFIGS)('%s', (configPath) => {+ it('overrides an inherited non-test NODE_ENV when the config loads', async () => {+ vi.stubEnv('NODE_ENV', 'development');+ expect(process.env.NODE_ENV).toBe('development'); // bypass probe: really unset++ await import(configPath);++ expect(process.env.NODE_ENV).toBe('test');+ });++ it('pins NODE_ENV=test for the worker processes too', async () => {+ const config = (await import(configPath)).default;+ expect(config.test.env.NODE_ENV).toBe('test');+ });+});