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
Run DB-adapter test suites against a throwaway portos_test database
[._.]/ Adam Eivy8d7060197f3b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 46b049ace1..567f5a90de 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -40,6 +40,8 @@## Fixed+- **DB-adapter test suites run again — against a throwaway `portos_test`, never your real data** — Blocking the test runner from the production `portos` database (previous fix) left the 12 DB-backed adapter suites *skipping everywhere*: CI has no Postgres, and locally they're now refused on the real DB — so the universe/series/issue/story/writers-room/catalog/media DB layer had effectively zero executed coverage. This restores it the safe way. `npm run setup:db:test` provisions a throwaway `portos_test` database (creates it + applies `init-db.sql`), and `npm run test:db` runs just the DB-backed suites against it via a dedicated `vitest.config.db.js` that runs them serially (`fileParallelism: false`) so suites truncating the same tables can't clobber each other. CI now spins up a `pgvector/pgvector:pg17` service and runs those suites against `portos_test` on every PR — the default `npm test` still skips them (no test DB in scope), so nobody needs Postgres to run the rest of the suite and nobody's real `portos` is ever touched. A drift guard in `db.guards.test.js` fails if a new `checkHealth()`-gated suite is left out of the DB config (silently losing coverage). (`server/scripts/setup-db-test.mjs`, `server/vitest.config.db.js`, `server/lib/db.guards.test.js`, `.github/workflows/ci.yml`, `server/package.json`, `package.json`)+- **Tests can no longer wipe your real universes, series, and writing — and every deletion is now audited** — The DB-backed `*.db.test.js` suites (universe, pipeline series/issues, story builder, writers room, catalog, creative director, media index) connect to the single real `portos` Postgres whenever it's reachable and run `DELETE FROM …` in their setup, restoring a snapshot afterward. Because git worktrees share that one database, a CoS agent running the suite in its worktree wiped all 12 universes + 4 series + the writers-room works when its process was torn down before the restore finished (the snapshot/restore swallowed every error). Two new guards in `server/lib/db.js` close this off: (1) `checkHealth()` reports "disconnected" under `NODE_ENV=test` against any non-test database, so every db-backed suite **skips cleanly** instead of deleting — a database is "safe for destructive tests" only when its name ends in `_test` (e.g. `portos_test`) or `TEST_DB_OK=1` is set (`isTestDatabase()`); (2) `query()` is a hard backstop that **throws** on `DELETE FROM` / `TRUNCATE` under the test runner on a non-test DB even if a suite reaches it without gating first. Separately, a new **`record_audit` table + generic DB trigger** now logs every tombstone, un-tombstone, and hard-delete of user-authored content (universes, pipeline series/issues, story-builder sessions, writers-room works/folders/drafts, catalog ingredients/scraps/types, creative-director projects, LoRA runs) — captured at the database layer so it records deletions from *any* source (the app, a stray test, a manual `psql`), with the old row snapshot kept for recovery and the originating SQL for forensics. Inspect it with `node scripts/show-deletions.mjs`. (`server/lib/db.js`, `server/scripts/init-db.sql`, `server/lib/db.guards.test.js`, `server/lib/db.catalogDdlParity.test.js`, `scripts/show-deletions.mjs`)- **Opening a LoRA dataset whose universe was deleted no longer spams the server log with `❌ Route error`** — The dataset workbench (`/media/training/:id`) speculatively fetches the dataset's `character.universeId` ({ silent: true }) to pre-load the canon character's variation axes. When that universe has since been deleted, the lookup 404s — harmless, and the client already swallows it — but the server logged every 404 as `❌ Route error [GET /api/universe-builder/<id>]: Universe not found`, and since the page reconnects every ~20s it logged the same line on a loop. `GET /api/universe-builder/:id` now tags a not-found result `severity: 'warning'`, so the error middleware skips the log line (and the client's error-toast hook already drops warnings) — matching the existing benign-404 precedent for speculative media-job archive lookups. (`server/routes/universeBuilder.js`)diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 34f7d632ef..38d9368335 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -19,6 +19,32 @@ jobs:matrix:node-version: [20.x]+ # Postgres (with pgvector) for the DB-backed adapter suites. The image ships+ # the `vector` extension that init-db.sql requires. The default `portos` DB+ # exists so setup:db:test has a maintenance connection to CREATE portos_test+ # from; the suites themselves only ever touch portos_test (the production+ # `portos` name is hard-blocked by isTestDatabase()).+ services:+ postgres:+ image: pgvector/pgvector:pg17+ env:+ POSTGRES_USER: portos+ POSTGRES_PASSWORD: portos+ POSTGRES_DB: portos+ ports:+ - 5432:5432+ options: >-+ --health-cmd "pg_isready -U portos"+ --health-interval 10s+ --health-timeout 5s+ --health-retries 5++ env:+ PGHOST: localhost+ PGPORT: 5432+ PGUSER: portos+ PGPASSWORD: portos+steps:- uses: actions/checkout@v6@@ -37,9 +63,20 @@ jobs:- name: Install client dependenciesrun: npm install --prefix client+ # Main server suite runs WITHOUT PGDATABASE pointing at a test DB, so the+ # DB-backed suites skip here (they'd see the non-test `portos` name). They+ # run in their own serial step below against portos_test.- name: Run server testsrun: npm run test:ci --prefix server+ - name: Provision test database (portos_test)+ run: npm run setup:db:test --prefix server++ - name: Run DB-backed tests (portos_test)+ run: npm run test:db:ci --prefix server+ env:+ PGDATABASE: portos_test+- name: Run client testsrun: npm test --prefix clientdiff --git a/package.json b/package.jsonindex dcb9598e61..6c6b08f045 100644--- a/package.json+++ b/package.json@@ -23,6 +23,8 @@"setup": "git submodule update --init --recursive && npm install && npm install --prefix client && npm install --prefix server && npm install --prefix autofixer && npm rebuild esbuild --prefix client && (npm rebuild esbuild --prefix server || true) && npm rebuild node-pty sharp --prefix server && node scripts/setup-data.js && node scripts/setup-db.js && node scripts/setup-llm.js && node scripts/setup-browser.js","setup:data": "node scripts/setup-data.js","setup:db": "node scripts/setup-db.js",+ "setup:db:test": "npm run setup:db:test --prefix server",+ "test:db": "npm run test:db --prefix server","setup:llm": "node scripts/setup-llm.js","setup:browser": "node scripts/setup-browser.js","setup:cert": "node scripts/setup-cert.js",diff --git a/server/lib/db.guards.test.js b/server/lib/db.guards.test.jsindex 02d15a44ea..b3f04c51c0 100644--- a/server/lib/db.guards.test.js+++ b/server/lib/db.guards.test.js@@ -16,7 +16,11 @@*/import { describe, it, expect, afterEach } from 'vitest';+import { readdirSync, openSync, readSync, closeSync } from 'node:fs';+import { dirname, join, sep } from 'node:path';+import { fileURLToPath } from 'node:url';import { isTestDatabase, 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.const saved = {};@@ -127,3 +131,71 @@ describe('query destructive backstop', () => {);});});++// Drift guard: a DB-backed suite skips on a non-test DB (correct), so if a new+// one is left out of vitest.config.db.js it would simply NEVER run — silently+// losing coverage with a green board. This asserts every real DB-backed suite+// (identified by the checkHealth + dbReady gating pattern those suites share) is+// matched by the db-config include set. Suites that MOCK checkHealth (no dbReady+// gate, e.g. memoryBackend.test.js) are not DB-backed and are correctly excluded.+describe('DB-backed test files are covered by vitest.config.db.js', () => {+ it('every checkHealth+dbReady suite is in the db-config include set', () => {+ const HERE = dirname(fileURLToPath(import.meta.url)); // server/lib+ const SERVER = join(HERE, '..'); // vitest root for the db config+ const REPO_SCRIPTS = join(SERVER, '..', 'scripts');++ const hasDbGlob = DB_TEST_INCLUDE.includes('**/db.test.js');+ // Match by basename — robust to the `../scripts/` relative-path prefix. The+ // explicit include entries all have distinct basenames, so this can't+ // false-match.+ const explicitBasenames = new Set(+ DB_TEST_INCLUDE.filter((p) => p !== '**/db.test.js').map((p) => p.split('/').pop()),+ );++ // The checkHealth + dbReady gating always sits in a suite's first ~40 lines,+ // so read only the file header instead of slurping every test file whole.+ const readHead = (path, bytes = 2048) => {+ const fd = openSync(path, 'r');+ try {+ const buf = Buffer.alloc(bytes);+ return buf.toString('utf8', 0, readSync(fd, buf, 0, bytes, 0));+ } finally {+ closeSync(fd);+ }+ };++ const SKIP_DIRS = new Set(['node_modules', 'slashdo', 'coverage', '.git']);+ const collect = (root) => {+ let entries;+ try {+ entries = readdirSync(root, { recursive: true });+ } catch {+ return [];+ }+ return entries+ .map(String)+ .filter((p) => p.endsWith('.test.js') && !p.split(sep).some((seg) => SKIP_DIRS.has(seg)));+ };++ const offenders = [];+ for (const [root, prefix] of [[SERVER, ''], [REPO_SCRIPTS, '../scripts/']]) {+ for (const rel of collect(root)) {+ const base = rel.split(sep).pop();+ // This guard file itself references checkHealth/dbReady (imports + the+ // detector regex) but is not a DB-backed suite — exclude it.+ if (base === 'db.guards.test.js') continue;+ const head = readHead(join(root, rel));+ // A real DB-backed suite both gates on checkHealth() and exposes dbReady.+ if (!(/\bcheckHealth\b/.test(head) && /\bdbReady\b/.test(head))) continue;+ const covered = (hasDbGlob && base === 'db.test.js') || explicitBasenames.has(base);+ if (!covered) offenders.push(prefix + rel.split(sep).join('/'));+ }+ }++ expect(+ offenders,+ `These DB-backed suites use checkHealth()+dbReady but are missing from ` ++ `server/vitest.config.db.js include — they would never run against portos_test:\n ${offenders.join('\n ')}`,+ ).toEqual([]);+ });+});diff --git a/server/package.json b/server/package.jsonindex 9e07669dc9..3693eb916a 100644--- a/server/package.json+++ b/server/package.json@@ -9,7 +9,10 @@"test": "vitest run","test:watch": "vitest","test:ci": "vitest run --bail=1 --silent=passed-only --reporter=default --reporter=github-actions",- "test:coverage": "vitest run --coverage"+ "test:coverage": "vitest run --coverage",+ "setup:db:test": "node scripts/setup-db-test.mjs",+ "test:db": "vitest run --config vitest.config.db.js",+ "test:db:ci": "vitest run --config vitest.config.db.js --bail=1 --reporter=default --reporter=github-actions"},"dependencies": {"@googleapis/calendar": "^15.0.0",diff --git a/server/scripts/setup-db-test.mjs b/server/scripts/setup-db-test.mjsnew file mode 100644index 0000000000..b94656c000--- /dev/null+++ b/server/scripts/setup-db-test.mjs@@ -0,0 +1,67 @@+#!/usr/bin/env node+/**+ * Provision the throwaway TEST database (default `portos_test`) and apply the+ * full schema (init-db.sql).+ *+ * Why: the DB-backed `*.db.test.js` suites talk to a real Postgres and run+ * `DELETE FROM …` in setup. They are HARD-BLOCKED from the production `portos`+ * database (see isTestDatabase() in server/lib/db.js) and skip unless PGDATABASE+ * names a `*_test` database. This script creates that database so the suites can+ * actually run — against data nobody cares about — restoring real coverage of+ * the DB adapter layer without ever risking your authored content.+ *+ * Idempotent: re-running CREATEs nothing it already has (CREATE DATABASE is+ * guarded by a pg_database probe; init-db.sql is all IF NOT EXISTS).+ *+ * node server/scripts/setup-db-test.mjs # local: creates portos_test+ * npm run setup:db:test # same, via package.json+ *+ * Connection uses standard PG env (PGHOST/PGPORT/PGUSER/PGPASSWORD). The target+ * name is PGTESTDATABASE (default `portos_test`); the maintenance connection+ * used to issue CREATE DATABASE is PGADMINDATABASE (default `portos`, which+ * always exists on a provisioned install).+ */+import pg from 'pg';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';++const HERE = dirname(fileURLToPath(import.meta.url));+const TEST_DB = process.env.PGTESTDATABASE || 'portos_test';++// Guard the identifier — it's interpolated into CREATE DATABASE (which can't be+// parameterized), so refuse anything but a plain, test-suffixed name.+if (!/^[a-z][a-z0-9_]*_test$/.test(TEST_DB)) {+ console.error(`❌ Refusing to provision '${TEST_DB}': test DB name must match /^[a-z][a-z0-9_]*_test$/`);+ process.exit(1);+}++const conn = {+ host: process.env.PGHOST || 'localhost',+ port: parseInt(process.env.PGPORT || '5432', 10),+ user: process.env.PGUSER || 'portos',+ password: process.env.PGPASSWORD || 'portos',+};++// 1. Create the database if absent (from a maintenance connection — CREATE+// DATABASE cannot run inside the target DB or a transaction).+const admin = new pg.Client({ ...conn, database: process.env.PGADMINDATABASE || 'portos' });+await admin.connect();+const exists = await admin.query('SELECT 1 FROM pg_database WHERE datname = $1', [TEST_DB]);+if (exists.rowCount === 0) {+ await admin.query(`CREATE DATABASE ${TEST_DB}`);+ console.log(`🗄️ Created test database '${TEST_DB}'`);+} else {+ console.log(`🗄️ Test database '${TEST_DB}' already exists`);+}+await admin.end();++// 2. Apply the schema. node-postgres runs a multi-statement string in one+// simple-query call (no params), so the whole init-db.sql — including the $$+// function bodies — applies as a single batch.+const sql = readFileSync(join(HERE, 'init-db.sql'), 'utf8');+const client = new pg.Client({ ...conn, database: TEST_DB });+await client.connect();+await client.query(sql);+await client.end();+console.log(`✅ Schema applied to '${TEST_DB}'. Run the DB suites with: npm run test:db --prefix server`);diff --git a/server/vitest.config.db.js b/server/vitest.config.db.jsnew file mode 100644index 0000000000..1029436158--- /dev/null+++ b/server/vitest.config.db.js@@ -0,0 +1,58 @@+import { defineConfig } from 'vitest/config';++/**+ * 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+ * guard in lib/db.guards.test.js imports it to assert no checkHealth()-gated+ * suite is left out. `**\/db.test.js` auto-covers the adapter round-trips; the+ * rest are listed explicitly.+ */+export const DB_TEST_INCLUDE = [+ '**/db.test.js',+ 'services/catalogDB.test.js',+ 'services/catalogCanonProjection.test.js',+ 'services/catalogRefResolver.test.js',+ 'services/creativeDirector/projectsDB.test.js',+ 'routes/catalog.test.js',+ '../scripts/run-db-migrations.test.js',+];++/**+ * DB-backed test config — runs ONLY the suites that talk to a real Postgres+ * (the `*.db.test.js` adapter round-trips + a few catalog/migration suites),+ * against the throwaway `portos_test` database.+ *+ * Why a separate config:+ * - These suites `DELETE FROM` / truncate whole tables in setup. The default+ * runner parallelizes test FILES, so two of them hitting the same table in+ * one shared database would clobber each other. `fileParallelism: false`+ * runs them one file at a time — correct, and they're fast.+ * - `env.PGDATABASE = portos_test` points them at the test DB. isTestDatabase()+ * recognizes the `_test` suffix, so checkHealth() lets them connect and run+ * (against the real `portos` DB they would skip — that's the safety guard).+ *+ * The default `vitest.config.js` ALSO matches these files, but there they skip+ * (PGDATABASE is unset → resolves to non-test `portos`). So `npm test` never+ * runs them; `npm run test:db` does, after `npm run setup:db:test`.+ *+ * Adding a new DB-backed test? If it's named `*.db.test.js` it's auto-included.+ * Otherwise add it to `include` below — db.guards.test.js fails if a checkHealth+ * consumer is left out.+ */+export default defineConfig({+ test: {+ testTimeout: 15000,+ globals: true,+ setupFiles: ['./vitest.setup.js'],+ // One file at a time — these suites assume exclusive access to their tables.+ fileParallelism: false,+ env: {+ PGDATABASE: process.env.PGTESTDATABASE || 'portos_test',+ },+ include: DB_TEST_INCLUDE,+ exclude: [+ '**/node_modules/**',+ '../lib/slashdo/**',+ ],+ },+});