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
guard test DB writes on the VITEST signal, not just NODE_ENV
[._.]/ Adam Eivy1619a0fc7f27
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6557ab8af7..2553ced5c5 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -46,6 +46,8 @@## Fixed+- **Test runner can no longer write fixtures into — or wipe — the real `portos` database when `NODE_ENV` isn't `test`** — A CoS agent running the server test suite in its worktree wrote test fixtures (`Test Work` writers-room works, `Issue 1`/`Old B` pipeline issues, `X`/`B` universes, `u-1`/`u-B` universe-runs, `stb-*` story-builder sessions) straight into the shared production Postgres, and the DB suites' `DELETE FROM …` cleanup **hard-deleted the user's real universes, series, and writers-room work**. Root cause: the test-runner safety gate in `server/lib/db.js` keyed only on `NODE_ENV==='test'`. The agent's wrapper left `NODE_ENV` unset/`development`, so `checkHealth()` did **not** report disconnected, the DB-backed `*.db.test.js` suites ran against the real DB instead of skipping, and the `query()` backstop only blocked `DELETE`/`TRUNCATE` — letting `INSERT`s leak while cleanup `DELETE`s threw and stranded them. Fixes: a new `isTestRunner()` detects the runner via `NODE_ENV==='test'` **or** `process.env.VITEST` (set in every vitest worker), so a misconfigured `NODE_ENV` can't disarm the gate; `checkHealth()` and the `query()` backstop both use it; and the backstop now refuses **all** row writes (`INSERT`/`UPDATE`/`DELETE`/`TRUNCATE`), not just deletions, against a non-test database under the runner. Verified: with `NODE_ENV=development`, `writersRoom/db.test.js` + `seriesStore/db.test.js` now skip against the prod DB and write nothing; the full main suite (11,251 tests) leaves the prod DB byte-identical; `npm run test:db` (99 tests on `portos_test`) still passes. (`server/lib/db.js`, `server/lib/db.guards.test.js`)+- **LoRA training stops oversubscribing unified memory — frees resident models, spills the latent cache to disk, and refuses to start when memory is too tight** — On a 128 GB Apple-Silicon box a single mflux FLUX.2 run pushed the machine to ~122 GB used + ~21 GB swap, and that swap-thrash coincided with the GPU watchdog reboots above. Three changes keep a run inside the unified-memory pool. (1) **Pre-train reclaim** — before spawning the trainer, PortOS unloads every model resident in Ollama and LM Studio (best-effort; failures are ignored) so their memory returns to the pool instead of stacking under the run. Only **loopback-local** backends are touched — a remote `OLLAMA_URL`/`LM_STUDIO_URL` (a LAN peer in a federated setup) is left alone, since evicting it would free no local memory. (2) **Latent cache always spills to disk** — the mflux `low_ram` flag is now on at every memory tier; keeping the encoded dataset cache in RAM bought nothing but the swap pressure, and disk-backing it costs only I/O, no training quality. (3) **Headroom gate** — the quantize/`low_ram` tier is now derived from the *post-unload available* memory (measured via `vm_stat` on macOS, free + inactive + speculative + purgeable) rather than raw RAM, so a busy box auto-tightens to a smaller base; and a run refuses to start with a clear error when under ~24 GB is free, rather than crashing the box mid-run. (`server/services/loraTraining/memoryPrep.js`, `server/services/loraTraining/runtimes.js`, `server/services/loraTraining/index.js`)- **LoRA training now survives a mid-run machine crash and self-instruments for GPU forensics** — Two GPU watchdog-timeout kernel panics (`watchdog timeout: no checkins from watchdogd in 90 seconds`) hard-rebooted the machine during mflux FLUX.2 training in a single day on M5 silicon (`Mac17,7`/`T6050`, macOS 26.5) — a system-level Metal/GPU hang, not a PortOS bug. Two changes make training resilient to it: (1) a checkpoint crash-resilience floor — `save_frequency` is now capped at `ceil(totalSteps/4)` (`MFLUX_MIN_CHECKPOINTS`) even when the user picks "only final save" (`checkpointEvery: 0`) or a huge interval, so a hard reboot loses at most ~¼ of a run instead of everything; resume from the newest checkpoint as before. (2) Each run streams `powermetrics --samplers cpu_power,gpu_power,thermal` into `<run>/powermetrics.log` so the next crash leaves a forensic record of GPU temp/power leading up to the hang — gated on a non-interactive `sudo -n` probe so it no-ops cleanly (training unaffected) when passwordless `powermetrics` isn't configured. The incident, analysis, and an investigation checklist are documented in `docs/TROUBLESHOOTING.md` ("GPU watchdog kernel panic during LoRA training") + `docs/research/2026-06-13-mflux-training-watchdog-panic.md`. (`server/services/loraTraining/runtimes.js`, `scripts/train_mflux_lora.py`, `docs/TROUBLESHOOTING.md`, `docs/research/`)diff --git a/CLAUDE.md b/CLAUDE.mdindex 181a71e1c0..c7d52fc383 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -41,6 +41,8 @@ The default database password `portos` (in `ecosystem.config.cjs`, `docker-compo**Storage backend policy.** PostgreSQL (system `:5432` or Docker `:5561`) is a **mandatory** dependency for every install and every federated peer — provisioned by `npm run setup:db` (see the ADR `docs/decisions/2026-06-07-postgres-as-primary-datastore.md` and `docs/STORAGE.md`). **`MEMORY_BACKEND=file` is a development/test-only escape hatch, NOT a supported deployment mode** (the creative catalog/pgvector, federation, and backup all assume Postgres and have no file-backed equivalent). When `MEMORY_BACKEND` is unset, `server/services/memoryBackend.js` requires a healthy DB and fails fast with no silent fallback — this is **intentional**; do not "fix" the no-fallback behavior, re-add a file menu choice in `scripts/setup-db.js`, or treat the file backend as a fallback for real installs. The file path stays runnable only because `NODE_ENV=test` selects it (it is guarded from bitrot by the suite, not promoted to a deployment option).+**Never run DB-backed tests against the real `portos` database.** There is ONE Postgres per install, shared by every git worktree (including CoS-agent worktrees). The `*.db.test.js` suites `DELETE FROM`/`INSERT` whole tables, so running them against `portos` corrupts the user's real universes/series/writers-room/catalog. They are gated to skip on a non-test DB and run only via `npm run test:db` (→ `portos_test`, provisioned by `npm run setup:db:test`). The gate in `server/lib/db.js` keys on `isTestRunner()` (`NODE_ENV==='test'` **OR** `process.env.VITEST`, not bare `NODE_ENV` — a wrapper that drops `NODE_ENV` must NOT be able to disarm it) and the `query()` backstop refuses ALL row writes (`INSERT`/`UPDATE`/`DELETE`/`TRUNCATE`) to a non-test DB under the runner. Do not weaken either to "just `NODE_ENV`" or "DELETE-only" — that's exactly the hole that wiped real data on 2026-06-13/14. See `server/lib/db.guards.test.js`.+## ArchitecturePortOS is a monorepo with Express.js server (always user-facing on `:5555`, HTTP or HTTPS) and React/Vite client (Vite dev server on `:5554` in `npm run dev`; in `npm start` the built client is served from `:5555` directly). PM2 manages app lifecycles. Data persists to JSON files in `./data/`.diff --git a/server/lib/db.guards.test.js b/server/lib/db.guards.test.jsindex 5eb9eaf439..fe373882ae 100644--- a/server/lib/db.guards.test.js+++ b/server/lib/db.guards.test.js@@ -8,18 +8,23 @@** These guards make the test runner refuse to touch a NON-test database:* - isTestDatabase() — names a DB safe for destructive tests.- * - checkHealth() — reports "disconnected" under NODE_ENV=test on a real DB- * so every db-backed suite skips via its existing branch.- * - query() — hard backstop: throws on DELETE/TRUNCATE under- * NODE_ENV=test on a non-test DB even if a suite reaches- * it without gating on checkHealth first.+ * - 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.+ * - 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/+ * DELETE/TRUNCATE) under the test runner on a non-test DB+ * even if a suite reaches it without gating on checkHealth+ * first. (DELETE-only guarding let test INSERTs leak+ * fixtures into the real `portos` DB on 2026-06-14.)*/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, checkHealth, query } from './db.js';+import { isTestDatabase, isTestRunner, checkHealth, query } from './db.js';import { DB_TEST_INCLUDE } from '../vitest.config.db.js';// NODE_ENV is 'test' throughout (vitest default); we vary PGDATABASE / TEST_DB_OK.@@ -76,8 +81,31 @@ describe('isTestDatabase', () => {});});+describe('isTestRunner', () => {+ it('is true under NODE_ENV=test', () => {+ setEnv('NODE_ENV', 'test');+ setEnv('VITEST', undefined);+ expect(isTestRunner()).toBe(true);+ });++ it('is true via VITEST even when NODE_ENV is not "test"', () => {+ // The leak path: a worktree wrapper sets NODE_ENV=development, so backend+ // selectors keyed on bare NODE_ENV quietly choose Postgres. VITEST is still+ // set, so the runner is still detected and the guard stays armed.+ setEnv('NODE_ENV', 'development');+ setEnv('VITEST', 'true');+ expect(isTestRunner()).toBe(true);+ });++ it('is false outside the runner (no NODE_ENV=test, no VITEST)', () => {+ setEnv('NODE_ENV', 'production');+ setEnv('VITEST', undefined);+ expect(isTestRunner()).toBe(false);+ });+});+describe('checkHealth test-runner gate', () => {- it('reports disconnected on a non-test DB under NODE_ENV=test', async () => {+ it('reports disconnected on a non-test DB under the test runner', async () => {setEnv('PGDATABASE', 'portos');setEnv('TEST_DB_OK', undefined);const health = await checkHealth();@@ -85,49 +113,84 @@ describe('checkHealth test-runner gate', () => {expect(health.hasSchema).toBe(false);expect(health.error).toMatch(/test runner blocked/i);});++ it('reports disconnected via VITEST even when NODE_ENV is not "test"', async () => {+ setEnv('PGDATABASE', 'portos');+ setEnv('TEST_DB_OK', undefined);+ setEnv('NODE_ENV', 'development');+ setEnv('VITEST', 'true');+ const health = await checkHealth();+ expect(health.connected).toBe(false);+ });});-describe('query destructive backstop', () => {+describe('query row-write backstop', () => {// These all run with a non-test DB so the guard is active. The throw happens// BEFORE pool.query, so no live database is needed.it('throws on DELETE FROM against a non-test DB', async () => {setEnv('PGDATABASE', 'portos');setEnv('TEST_DB_OK', undefined);- await expect(query('DELETE FROM universes')).rejects.toThrow(/Refusing destructive query/i);+ await expect(query('DELETE FROM universes')).rejects.toThrow(/Refusing to mutate/i);});it('throws on TRUNCATE against a non-test DB', async () => {setEnv('PGDATABASE', 'portos');setEnv('TEST_DB_OK', undefined);- await expect(query('TRUNCATE pipeline_series')).rejects.toThrow(/Refusing destructive query/i);+ await expect(query('TRUNCATE pipeline_series')).rejects.toThrow(/Refusing to mutate/i);+ });++ it('throws on INSERT INTO against a non-test DB (the fixture-leak path)', async () => {+ setEnv('PGDATABASE', 'portos');+ setEnv('TEST_DB_OK', undefined);+ await expect(+ query("INSERT INTO pipeline_series (id, data) VALUES ('ser-fixed-abc', '{}')"),+ ).rejects.toThrow(/Refusing to mutate/i);+ });++ it('throws on UPDATE against a non-test DB', async () => {+ setEnv('PGDATABASE', 'portos');+ setEnv('TEST_DB_OK', undefined);+ await expect(query("UPDATE universes SET deleted = TRUE WHERE id = 'x'")).rejects.toThrow(+ /Refusing to mutate/i,+ );+ });++ it('throws on a write via VITEST even when NODE_ENV is not "test"', async () => {+ setEnv('PGDATABASE', 'portos');+ setEnv('TEST_DB_OK', undefined);+ setEnv('NODE_ENV', 'development');+ setEnv('VITEST', 'true');+ await expect(query("INSERT INTO universes (id) VALUES ('x')")).rejects.toThrow(+ /Refusing to mutate/i,+ );});it('throws even when the statement is prefixed with comments/whitespace', async () => {setEnv('PGDATABASE', 'portos');setEnv('TEST_DB_OK', undefined);await expect(query(' -- cleanup\n DELETE FROM writers_room_works')).rejects.toThrow(- /Refusing destructive query/i,+ /Refusing to mutate/i,);});- it('does NOT block non-destructive statements via the guard', async () => {+ it('does NOT block reads via the guard', async () => {setEnv('PGDATABASE', 'portos');setEnv('TEST_DB_OK', undefined);- // A SELECT is not destructive — the guard lets it through to pool.query.- // We only assert the guard's own error is NOT thrown; any connection error+ // A SELECT is not a row write — the guard lets it through to pool.query. We+ // only assert the guard's own error is NOT thrown; any connection error// from pool.query (no DB in CI) is fine and distinct.await query('SELECT 1').then(() => {},- (err) => expect(err.message).not.toMatch(/Refusing destructive query/i),+ (err) => expect(err.message).not.toMatch(/Refusing to mutate/i),);});- it('does not false-positive on a column/word containing "delete"', async () => {+ it('does not false-positive on a column/word containing "delete"/"update"', async () => {setEnv('PGDATABASE', 'portos');setEnv('TEST_DB_OK', undefined);- await query("SELECT deleted FROM universes WHERE name = 'x'").then(+ await query("SELECT deleted, updated_at FROM universes WHERE name = 'x'").then(() => {},- (err) => expect(err.message).not.toMatch(/Refusing destructive query/i),+ (err) => expect(err.message).not.toMatch(/Refusing to mutate/i),);});});diff --git a/server/lib/db.js b/server/lib/db.jsindex f2ea05d58a..424ca4c04d 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -57,9 +57,35 @@ export function isTestDatabase() {return /_test$/.test(db) || db === 'portos_test';}-// Only guard row deletion — not schema DDL (ensureSchema's CREATE/ALTER/DROP is-// idempotent and not a data-loss risk). Skips leading line/block comments + space.-const DESTRUCTIVE_SQL = /^\s*(?:--[^\n]*\n|\/\*[\s\S]*?\*\/|\s)*(DELETE\s+FROM|TRUNCATE)\b/i;+/**+ * 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+// series/issues/story-builder fixtures leaked into the real `portos` DB and+// federated to peers. INSERT/UPDATE are now blocked too. Schema DDL+// (CREATE/ALTER/DROP) is still allowed: it is idempotent, carries no row-data,+// and ensureSchema() needs it to stand up portos_test. Skips leading+// line/block comments + whitespace before the verb.+const ROW_WRITE_SQL =+ /^\s*(?:--[^\n]*\n|\/\*[\s\S]*?\*\/|\s)*(INSERT\s+INTO|UPDATE\s|DELETE\s+FROM|TRUNCATE)\b/i;/*** Execute a query against the connection pool.@@ -68,19 +94,21 @@ const DESTRUCTIVE_SQL = /^\s*(?:--[^\n]*\n|\/\*[\s\S]*?\*\/|\s)*(DELETE\s+FROM|T* @returns {Promise<pg.QueryResult>}*/export async function query(text, params) {- // Hard backstop: under the test runner, refuse to delete rows from a non-test- // database even if a suite somehow reaches query() without gating on- // checkHealth() first (e.g. a new test author calls query('DELETE …')- // directly). Throwing fails loudly instead of silently destroying real data.+ // Hard backstop: under the test runner, refuse to MUTATE a non-test database+ // even if a suite somehow reaches query() without gating on checkHealth()+ // first (a new test author calls query('INSERT …') directly, or a backend+ // selector mis-chose Postgres because NODE_ENV wasn't 'test'). Throwing fails+ // loudly instead of silently writing — or stranding — real data. Reads+ // (SELECT) are left alone so health/version probes still work.if (- process.env.NODE_ENV === 'test' &&+ isTestRunner() &&!isTestDatabase() &&typeof text === 'string' &&- DESTRUCTIVE_SQL.test(text)+ ROW_WRITE_SQL.test(text)) {throw new Error(- `🛑 Refusing destructive query against non-test database '${process.env.PGDATABASE || 'portos'}' under NODE_ENV=test. ` +- `Point PGDATABASE at a *_test database (e.g. portos_test) or set TEST_DB_OK=1. Query: ${text.slice(0, 80)}`,+ `🛑 Refusing to mutate non-test database '${process.env.PGDATABASE || 'portos'}' under the test runner. ` ++ `Point PGDATABASE at a *_test database (e.g. portos_test), gate the suite on requireDb(), or set TEST_DB_OK=1. Query: ${text.slice(0, 80)}`,);}return pool.query(text, params);@@ -131,13 +159,15 @@ export async function withTransaction(fn) {* @returns {Promise<{connected: boolean, hasSchema: boolean, error?: string}>}*/export async function checkHealth() {- // Test-runner safety gate. Under NODE_ENV=test the only database we permit is- // a designated test database (see isTestDatabase). Reporting "disconnected"+ // Test-runner safety gate. Under the test runner the only database we permit+ // is a designated test database (see isTestDatabase). Reporting "disconnected"// here makes every DB-backed `*.db.test.js` suite skip via its existing// `if (!health.connected)` branch — instead of running DELETE FROM against the- // developer's real universes/series/writing. The mocked checkHealth in- // memoryBackend.test.js / backup.test.js is unaffected (it replaces this fn).- if (process.env.NODE_ENV === 'test' && !isTestDatabase()) {+ // developer's real universes/series/writing. Keyed on isTestRunner() (not bare+ // NODE_ENV) so a worktree run that left NODE_ENV unset is still gated. The+ // mocked checkHealth in memoryBackend.test.js / backup.test.js is unaffected+ // (it replaces this fn).+ if (isTestRunner() && !isTestDatabase()) {return {connected: false,hasSchema: false,