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
Stop test suites from deleting real Postgres data; audit all record deletions
[._.]/ Adam Eivy0d49dc1cf985
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 2a27c64010..46b049ace1 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -40,6 +40,8 @@## Fixed+- **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`)- **A gated-model LoRA training failure now shows a one-click "Request access" link, like image rendering already does** — Training a FLUX.2 Klein LoRA pulls a *different, separately-gated* HuggingFace repo than rendering does (the mflux trainer resolves `flux2-klein-9b` → `black-forest-labs/FLUX.2-klein-base-9B`, whereas inference uses `FLUX.2-klein-9B`). So a user who'd accepted the inference model's license — and whose stored token is otherwise valid, with `canReadGatedRepos` — still hit a `GatedRepoError` the instant training started, with no obvious next step. Image rendering already turns this into an actionable banner with a deep link to the license page; training now does the same. The failure classifier extracts the gated `owner/repo` from the trainer's stderr (both the `Access to model … is restricted` and `Cannot access gated repo for url …` forms), persists it on the run record as `errorRepo`, and the training panel renders a **"Request access to `<repo>` ↗"** button that opens the exact license page — accept it there with the token's account and retry, no token change needed. The repo-extraction the image runner already did inline is now a shared `extractGatedRepo()` helper (`server/lib/hfErrors.js`) both subsystems consume. (`server/lib/hfErrors.js`, `server/services/loraTraining/failure.js`, `server/services/loraTraining/index.js`, `server/services/imageGen/local.js`, `client/src/components/loraTraining/TrainingPanel.jsx`)diff --git a/scripts/show-deletions.mjs b/scripts/show-deletions.mjsnew file mode 100644index 0000000000..89e2effd05--- /dev/null+++ b/scripts/show-deletions.mjs@@ -0,0 +1,70 @@+#!/usr/bin/env node+/**+ * Inspect the deletion audit log (record_audit).+ *+ * Every tombstone / un-tombstone / hard-delete of a user-authored record+ * (universes, pipeline_series, pipeline_issues, story_builder_sessions,+ * writers_room_*, catalog_*, creative_director_projects, lora_training_runs)+ * is logged by a DB trigger — regardless of what caused it (the app, a test+ * suite's raw DELETE, or a manual psql session). This script reads that log so+ * you can answer "what got deleted, when, and by what."+ *+ * Usage:+ * node scripts/show-deletions.mjs # last 50 events, all tables+ * node scripts/show-deletions.mjs --table=universes+ * node scripts/show-deletions.mjs --action=hard_delete+ * node scripts/show-deletions.mjs --since='2026-06-13' --limit=200+ * node scripts/show-deletions.mjs --id=<recordId> # full history for one record+ *+ * Uses `psql` (like scripts/recover-synced-test-fixtures.mjs) so it needs no+ * node_modules at the repo root. DB connection uses standard PG env+ * (PGHOST/PGPORT/PGUSER/PGPASSWORD/PGDATABASE) or pass --port=5432.+ */+import { execFileSync } from 'child_process';++const args = process.argv.slice(2);+const val = (name, def) => {+ const a = args.find((x) => x.startsWith(`--${name}=`));+ return a ? a.split('=')[1] : def;+};++const PORT = val('port', process.env.PGPORT || '5432');+const DB = process.env.PGDATABASE || 'portos';+const HOST = process.env.PGHOST || 'localhost';+const limit = parseInt(val('limit', '50'), 10);++// Build the filter from simple, validated inputs (no string interpolation of+// raw user text into SQL beyond these whitelisted, escaped literals).+const esc = (s) => `'${String(s).replace(/'/g, "''")}'`;+const where = [];+if (val('table')) where.push(`table_name = ${esc(val('table'))}`);+if (val('action')) where.push(`action = ${esc(val('action'))}`);+if (val('id')) where.push(`record_id = ${esc(val('id'))}`);+if (val('since')) where.push(`occurred_at >= ${esc(val('since'))}`);++const sql = `+ SELECT to_char(occurred_at, 'YYYY-MM-DD"T"HH24:MI:SS') || '|' || action || '|' ||+ table_name || '|' || coalesce(record_name, record_id, '?') || '|' ||+ coalesce(actor, 'pid ' || backend_pid || coalesce(' (' || application_name || ')', '')) || '|' ||+ coalesce(regexp_replace(left(source_query, 120), '\\s+', ' ', 'g'), '')+ FROM record_audit+ ${where.length ? 'WHERE ' + where.join(' AND ') : ''}+ ORDER BY occurred_at DESC+ LIMIT ${Number.isFinite(limit) ? limit : 50}`;++const out = execFileSync('psql', ['-h', HOST, '-p', PORT, '-d', DB, '-tAc', sql], {+ encoding: 'utf8',+}).trim();++if (!out) {+ console.log('No matching deletion-audit events.');+} else {+ const lines = out.split('\n');+ console.log(`📜 ${lines.length} event(s) (most recent first):\n`);+ for (const line of lines) {+ const [when, action, table, name, who, query] = line.split('|');+ console.log(`${when} ${action.toUpperCase().padEnd(12)} ${table}/${name}`);+ console.log(` by: ${who}`);+ if (query) console.log(` sql: ${query}`);+ }+}diff --git a/server/lib/db.catalogDdlParity.test.js b/server/lib/db.catalogDdlParity.test.jsindex f709035deb..8b56bbbaf8 100644--- a/server/lib/db.catalogDdlParity.test.js+++ b/server/lib/db.catalogDdlParity.test.js@@ -144,8 +144,13 @@ describe('catalog DDL parity (init-db.sql ↔ db.js ensureSchema)', () => {});it('every trg_catalog_* trigger appears in both files', () => {- const sqlTrgs = extractTriggerNames(INIT_SQL);- const jsTrgs = extractTriggerNames(DB_JS);+ // Exclude the generic `*_audit` triggers (record_audit): init-db.sql spells+ // them literally while db.js builds them from the auditedTables array via a+ // `trg_${t}_audit` template literal, so a literal-name extractor only sees+ // them on the init-db.sql side. They have their own parity assertion below.+ const noAudit = (s) => new Set([...s].filter((t) => !t.endsWith('_audit')));+ const sqlTrgs = noAudit(extractTriggerNames(INIT_SQL));+ const jsTrgs = noAudit(extractTriggerNames(DB_JS));expect([...sqlTrgs].sort()).toEqual([...jsTrgs].sort());expect(sqlTrgs.size).toBeGreaterThan(0);});@@ -309,6 +314,47 @@ describe('catalog DDL parity (init-db.sql ↔ db.js ensureSchema)', () => {.toEqual([...new Set(extractColumnNames(jsBody))].sort());});+ // Deletion audit log (incident #1248-follow-up) — the record_audit table, the+ // record_audit_log() trigger function, and the per-content-table `_audit`+ // triggers all live in BOTH DDL sources. A one-sided edit (e.g. auditing a new+ // table only in db.js) would leave fresh installs un-audited, so lock all three.+ it('record_audit table + trigger function + audit triggers match in both files', () => {+ // table columns+ const sqlBody = extractCreateTable(INIT_SQL, 'record_audit');+ const jsBody = extractCreateTable(DB_JS, 'record_audit');+ expect(sqlBody, 'init-db.sql missing CREATE TABLE record_audit').toBeTruthy();+ expect(jsBody, 'db.js missing CREATE TABLE record_audit').toBeTruthy();+ expect([...new Set(extractColumnNames(sqlBody))].sort())+ .toEqual([...new Set(extractColumnNames(jsBody))].sort());++ // generic trigger function present in both+ expect(/CREATE OR REPLACE FUNCTION\s+record_audit_log\b/i.test(INIT_SQL)).toBe(true);+ expect(/CREATE OR REPLACE FUNCTION\s+record_audit_log\b/i.test(DB_JS)).toBe(true);++ // The set of audited tables is identical across both. init-db.sql spells out+ // a `trg_<table>_audit` per table; db.js builds them from the `auditedTables`+ // array via a `trg_${t}_audit` template literal, so we parse that array on the+ // js side rather than matching literal trigger names.+ const sqlAuditTables = (() => {+ const out = new Set();+ const re = /CREATE TRIGGER\s+trg_([a-z0-9_]+)_audit\b/gi;+ let m;+ while ((m = re.exec(INIT_SQL)) !== null) out.add(m[1]);+ return out;+ })();+ const jsAuditTables = (() => {+ const m = /const auditedTables\s*=\s*\[([\s\S]*?)\]/i.exec(DB_JS);+ expect(m, 'db.js missing the auditedTables array').toBeTruthy();+ const out = new Set();+ const re = /'([a-z0-9_]+)'/gi;+ let mm;+ while ((mm = re.exec(m[1])) !== null) out.add(mm[1]);+ return out;+ })();+ expect(sqlAuditTables.size, 'no _audit triggers found in init-db.sql — DDL broke').toBeGreaterThan(8);+ expect([...sqlAuditTables].sort()).toEqual([...jsAuditTables].sort());+ });+// Broad drift guard for the whole upgrade-vs-fresh-install gap (beyond the// catalog tables above). init-db.sql runs ONLY on fresh `db.sh setup-native`// provisioning; existing installs + federated peers get new tables solelydiff --git a/server/lib/db.guards.test.js b/server/lib/db.guards.test.jsnew file mode 100644index 0000000000..02d15a44ea--- /dev/null+++ b/server/lib/db.guards.test.js@@ -0,0 +1,129 @@+/**+ * Test-runner safety guards in db.js (incident #1248-follow-up).+ *+ * On 2026-06-13 a CoS agent ran the server test suite in its worktree; the+ * DB-backed `*.db.test.js` suites — which connect to the single real `portos`+ * Postgres and run `DELETE FROM universes` — wiped every universe/series when the+ * agent's process was torn down before their snapshot-restore could finish.+ *+ * 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.+ */++import { describe, it, expect, afterEach } from 'vitest';+import { isTestDatabase, checkHealth, query } from './db.js';++// NODE_ENV is 'test' throughout (vitest default); we vary PGDATABASE / TEST_DB_OK.+const saved = {};+function setEnv(key, value) {+ if (!(key in saved)) saved[key] = process.env[key];+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+}++afterEach(() => {+ for (const [k, v] of Object.entries(saved)) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+ for (const k of Object.keys(saved)) delete saved[k];+});++describe('isTestDatabase', () => {+ it('treats the production default name as NOT a test DB', () => {+ setEnv('PGDATABASE', undefined); // → defaults to 'portos'+ setEnv('TEST_DB_OK', undefined);+ expect(isTestDatabase()).toBe(false);+ });++ it('treats an explicit production name as NOT a test DB', () => {+ setEnv('PGDATABASE', 'portos');+ setEnv('TEST_DB_OK', undefined);+ expect(isTestDatabase()).toBe(false);+ });++ it('accepts the canonical portos_test name', () => {+ setEnv('PGDATABASE', 'portos_test');+ setEnv('TEST_DB_OK', undefined);+ expect(isTestDatabase()).toBe(true);+ });++ it('accepts any *_test database name', () => {+ setEnv('PGDATABASE', 'myfork_test');+ setEnv('TEST_DB_OK', undefined);+ expect(isTestDatabase()).toBe(true);+ });++ it('honors the TEST_DB_OK=1 override even on a non-test name', () => {+ setEnv('PGDATABASE', 'portos');+ setEnv('TEST_DB_OK', '1');+ expect(isTestDatabase()).toBe(true);+ });++ it('ignores TEST_DB_OK values other than "1"', () => {+ setEnv('PGDATABASE', 'portos');+ setEnv('TEST_DB_OK', 'true');+ expect(isTestDatabase()).toBe(false);+ });+});++describe('checkHealth test-runner gate', () => {+ it('reports disconnected on a non-test DB under NODE_ENV=test', async () => {+ setEnv('PGDATABASE', 'portos');+ setEnv('TEST_DB_OK', undefined);+ const health = await checkHealth();+ expect(health.connected).toBe(false);+ expect(health.hasSchema).toBe(false);+ expect(health.error).toMatch(/test runner blocked/i);+ });+});++describe('query destructive 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);+ });++ 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);+ });++ 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,+ );+ });++ it('does NOT block non-destructive statements 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+ // 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),+ );+ });++ it('does not false-positive on a column/word containing "delete"', async () => {+ setEnv('PGDATABASE', 'portos');+ setEnv('TEST_DB_OK', undefined);+ await query("SELECT deleted FROM universes WHERE name = 'x'").then(+ () => {},+ (err) => expect(err.message).not.toMatch(/Refusing destructive query/i),+ );+ });+});diff --git a/server/lib/db.js b/server/lib/db.jsindex db6e84642e..b6bbb16213 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -29,6 +29,33 @@ pool.on('error', (err) => {console.error(`🗄️ Database pool error: ${err.message}`);});+/**+ * Is the configured database a DESIGNATED test database?+ *+ * The test runner must NEVER touch a real (production) Postgres — there is only+ * ONE database per install (`PGDATABASE || 'portos'`), shared by every git+ * worktree, so a DB-backed `*.db.test.js` suite that does `DELETE FROM universes`+ * runs against the user's real authored content. (This is exactly how a CoS+ * agent running the suite in its worktree wiped every universe/series on+ * 2026-06-13.) A database is "safe for destructive tests" only when its name is+ * explicitly a test database (ends in `_test`, or the canonical `portos_test`)+ * or the operator sets `TEST_DB_OK=1` to opt a non-standard name in.+ *+ * Consumed by `checkHealth()` (skips DB suites on a non-test DB) and by the+ * destructive-statement guard in `query()` (a hard backstop).+ *+ * @returns {boolean}+ */+export function isTestDatabase() {+ if (process.env.TEST_DB_OK === '1') return true;+ const db = process.env.PGDATABASE || 'portos';+ 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;+/*** Execute a query against the connection pool.* @param {string} text - SQL query text with $1, $2, etc. placeholders@@ -36,6 +63,21 @@ pool.on('error', (err) => {* @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.+ if (+ process.env.NODE_ENV === 'test' &&+ !isTestDatabase() &&+ typeof text === 'string' &&+ DESTRUCTIVE_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)}`,+ );+ }return pool.query(text, params);}@@ -84,6 +126,20 @@ 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"+ // 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()) {+ return {+ connected: false,+ hasSchema: false,+ hasCatalogSchema: false,+ error: `test runner blocked from non-test database '${process.env.PGDATABASE || 'portos'}' — point PGDATABASE at a *_test database (e.g. portos_test) or set TEST_DB_OK=1`,+ };+ }try {const result = await pool.query(`SELECT@@ -852,7 +908,100 @@ async function ensureSchemaImpl() {)`,`CREATE INDEX IF NOT EXISTS idx_lora_training_runs_status ON lora_training_runs (status)`,`CREATE INDEX IF NOT EXISTS idx_lora_training_runs_character ON lora_training_runs (character_id)`,++ // ─── Deletion audit log (incident #1248-follow-up) ──────────────────────+ // Append-only forensic trail of EVERY tombstone (soft-delete), un-tombstone+ // (recovery), and hard-delete of user-authored records — written by a DB+ // trigger so it captures deletions from ANY source: the app, a test suite+ // doing raw `DELETE FROM`, or a manual `psql` session. (On 2026-06-13 a CoS+ // agent's test run wiped every universe/series with no trace of who/when;+ // this table closes that gap.) `row_snapshot` keeps the OLD row JSON so a+ // wrongful delete is recoverable from the log alone. Local-only, never+ // federated (no sync_sequence) — each install audits its own mutations.+ // Mirrors the record_audit block in init-db.sql (parity-locked by+ // db.catalogDdlParity.test.js).+ `CREATE TABLE IF NOT EXISTS record_audit (+ id BIGSERIAL PRIMARY KEY,+ table_name TEXT NOT NULL,+ record_id TEXT,+ record_name TEXT,+ action VARCHAR(16) NOT NULL,+ actor TEXT,+ source_query TEXT,+ application_name TEXT,+ backend_pid INTEGER,+ row_snapshot JSONB,+ occurred_at TIMESTAMPTZ DEFAULT NOW()+ )`,+ `CREATE INDEX IF NOT EXISTS idx_record_audit_record ON record_audit (table_name, record_id, occurred_at DESC)`,+ `CREATE INDEX IF NOT EXISTS idx_record_audit_occurred ON record_audit (occurred_at DESC)`,+ `CREATE INDEX IF NOT EXISTS idx_record_audit_action ON record_audit (action, occurred_at DESC)`,++ // Generic audit trigger. Works on any table via to_jsonb(OLD/NEW) so it needs+ // no per-table column knowledge: `id`/`name`/`title`/`deleted`/`deleted_at`+ // are read out of the row JSON (absent keys → NULL). A row is "deleted" when+ // its `deleted` boolean is true OR its `deleted_at` is non-null (covers both+ // the bool-trio tables and catalog_user_types' deleted_at-only shape).+ // `actor` reads the optional `portos.actor` GUC the app MAY set per session;+ // `source_query` captures current_query() so even an un-attributed raw DELETE+ // is traceable. AFTER trigger: only committed-path rows are logged.+ `CREATE OR REPLACE FUNCTION record_audit_log()+ RETURNS TRIGGER AS $$+ DECLARE+ oldj JSONB := to_jsonb(OLD);+ newj JSONB;+ was_deleted BOOLEAN;+ now_deleted BOOLEAN;+ v_action TEXT;+ BEGIN+ IF TG_OP = 'DELETE' THEN+ v_action := 'hard_delete';+ INSERT INTO record_audit+ (table_name, record_id, record_name, action, actor, source_query, application_name, backend_pid, row_snapshot)+ VALUES+ (TG_TABLE_NAME, oldj->>'id', COALESCE(oldj->>'name', oldj->>'title'), v_action,+ current_setting('portos.actor', true), current_query(),+ current_setting('application_name', true), pg_backend_pid(), oldj);+ RETURN OLD;+ END IF;++ newj := to_jsonb(NEW);+ was_deleted := COALESCE((oldj->>'deleted')::boolean, oldj->>'deleted_at' IS NOT NULL, false);+ now_deleted := COALESCE((newj->>'deleted')::boolean, newj->>'deleted_at' IS NOT NULL, false);+ IF now_deleted AND NOT was_deleted THEN+ v_action := 'tombstone';+ ELSIF was_deleted AND NOT now_deleted THEN+ v_action := 'untombstone';+ ELSE+ RETURN NEW;+ END IF;+ INSERT INTO record_audit+ (table_name, record_id, record_name, action, actor, source_query, application_name, backend_pid, row_snapshot)+ VALUES+ (TG_TABLE_NAME, newj->>'id', COALESCE(newj->>'name', newj->>'title'), v_action,+ current_setting('portos.actor', true), current_query(),+ current_setting('application_name', true), pg_backend_pid(), newj);+ RETURN NEW;+ END;+ $$ LANGUAGE plpgsql`,];++ // Attach the audit trigger to every user-authored-content table. Adding a+ // table here is all it takes to audit its deletions. (Keep in sync with the+ // AUDITED_RECORD_TABLES list in init-db.sql.)+ const auditedTables = [+ 'universes', 'universe_runs', 'pipeline_series', 'pipeline_issues',+ 'story_builder_sessions', 'writers_room_works', 'writers_room_folders',+ 'writers_room_draft_versions', 'catalog_ingredients', 'catalog_scraps',+ 'catalog_user_types', 'creative_director_projects', 'lora_training_runs',+ ];+ for (const t of auditedTables) {+ catalogDDL.push(`DROP TRIGGER IF EXISTS trg_${t}_audit ON ${t}`);+ catalogDDL.push(+ `CREATE TRIGGER trg_${t}_audit AFTER UPDATE OR DELETE ON ${t} FOR EACH ROW EXECUTE FUNCTION record_audit_log()`,+ );+ }+for (const sql of catalogDDL) {await pool.query(sql);}diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex c6d8d9528d..70f14ecce2 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -849,3 +849,100 @@ CREATE TABLE IF NOT EXISTS lora_training_runs ();CREATE INDEX IF NOT EXISTS idx_lora_training_runs_status ON lora_training_runs (status);CREATE INDEX IF NOT EXISTS idx_lora_training_runs_character ON lora_training_runs (character_id);++-- Deletion audit log (incident #1248-follow-up). Append-only forensic trail of+-- every tombstone / un-tombstone / hard-delete of user-authored records, written+-- by a DB trigger so it captures deletions from ANY source (app, a test suite's+-- raw DELETE, a manual psql session). row_snapshot keeps the OLD row JSON so a+-- wrongful delete is recoverable from the log alone. Local-only (not federated).+-- Mirrors the record_audit block in server/lib/db.js (parity-locked by+-- db.catalogDdlParity.test.js).+CREATE TABLE IF NOT EXISTS record_audit (+ id BIGSERIAL PRIMARY KEY,+ table_name TEXT NOT NULL,+ record_id TEXT,+ record_name TEXT,+ action VARCHAR(16) NOT NULL,+ actor TEXT,+ source_query TEXT,+ application_name TEXT,+ backend_pid INTEGER,+ row_snapshot JSONB,+ occurred_at TIMESTAMPTZ DEFAULT NOW()+);+CREATE INDEX IF NOT EXISTS idx_record_audit_record ON record_audit (table_name, record_id, occurred_at DESC);+CREATE INDEX IF NOT EXISTS idx_record_audit_occurred ON record_audit (occurred_at DESC);+CREATE INDEX IF NOT EXISTS idx_record_audit_action ON record_audit (action, occurred_at DESC);++-- Generic audit trigger function — reads id/name/title/deleted/deleted_at out of+-- to_jsonb(OLD/NEW) so it needs no per-table column knowledge. A row is "deleted"+-- when `deleted` is true OR `deleted_at` is non-null. See server/lib/db.js for+-- the authoritative copy + commentary.+CREATE OR REPLACE FUNCTION record_audit_log()+RETURNS TRIGGER AS $$+DECLARE+ oldj JSONB := to_jsonb(OLD);+ newj JSONB;+ was_deleted BOOLEAN;+ now_deleted BOOLEAN;+ v_action TEXT;+BEGIN+ IF TG_OP = 'DELETE' THEN+ v_action := 'hard_delete';+ INSERT INTO record_audit+ (table_name, record_id, record_name, action, actor, source_query, application_name, backend_pid, row_snapshot)+ VALUES+ (TG_TABLE_NAME, oldj->>'id', COALESCE(oldj->>'name', oldj->>'title'), v_action,+ current_setting('portos.actor', true), current_query(),+ current_setting('application_name', true), pg_backend_pid(), oldj);+ RETURN OLD;+ END IF;++ newj := to_jsonb(NEW);+ was_deleted := COALESCE((oldj->>'deleted')::boolean, oldj->>'deleted_at' IS NOT NULL, false);+ now_deleted := COALESCE((newj->>'deleted')::boolean, newj->>'deleted_at' IS NOT NULL, false);+ IF now_deleted AND NOT was_deleted THEN+ v_action := 'tombstone';+ ELSIF was_deleted AND NOT now_deleted THEN+ v_action := 'untombstone';+ ELSE+ RETURN NEW;+ END IF;+ INSERT INTO record_audit+ (table_name, record_id, record_name, action, actor, source_query, application_name, backend_pid, row_snapshot)+ VALUES+ (TG_TABLE_NAME, newj->>'id', COALESCE(newj->>'name', newj->>'title'), v_action,+ current_setting('portos.actor', true), current_query(),+ current_setting('application_name', true), pg_backend_pid(), newj);+ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++-- Audit trigger on every user-authored-content table. AUDITED_RECORD_TABLES —+-- keep in sync with the auditedTables list in server/lib/db.js.+DROP TRIGGER IF EXISTS trg_universes_audit ON universes;+CREATE TRIGGER trg_universes_audit AFTER UPDATE OR DELETE ON universes FOR EACH ROW EXECUTE FUNCTION record_audit_log();+DROP TRIGGER IF EXISTS trg_universe_runs_audit ON universe_runs;+CREATE TRIGGER trg_universe_runs_audit AFTER UPDATE OR DELETE ON universe_runs FOR EACH ROW EXECUTE FUNCTION record_audit_log();+DROP TRIGGER IF EXISTS trg_pipeline_series_audit ON pipeline_series;+CREATE TRIGGER trg_pipeline_series_audit AFTER UPDATE OR DELETE ON pipeline_series FOR EACH ROW EXECUTE FUNCTION record_audit_log();+DROP TRIGGER IF EXISTS trg_pipeline_issues_audit ON pipeline_issues;+CREATE TRIGGER trg_pipeline_issues_audit AFTER UPDATE OR DELETE ON pipeline_issues FOR EACH ROW EXECUTE FUNCTION record_audit_log();+DROP TRIGGER IF EXISTS trg_story_builder_sessions_audit ON story_builder_sessions;+CREATE TRIGGER trg_story_builder_sessions_audit AFTER UPDATE OR DELETE ON story_builder_sessions FOR EACH ROW EXECUTE FUNCTION record_audit_log();+DROP TRIGGER IF EXISTS trg_writers_room_works_audit ON writers_room_works;+CREATE TRIGGER trg_writers_room_works_audit AFTER UPDATE OR DELETE ON writers_room_works FOR EACH ROW EXECUTE FUNCTION record_audit_log();+DROP TRIGGER IF EXISTS trg_writers_room_folders_audit ON writers_room_folders;+CREATE TRIGGER trg_writers_room_folders_audit AFTER UPDATE OR DELETE ON writers_room_folders FOR EACH ROW EXECUTE FUNCTION record_audit_log();+DROP TRIGGER IF EXISTS trg_writers_room_draft_versions_audit ON writers_room_draft_versions;+CREATE TRIGGER trg_writers_room_draft_versions_audit AFTER UPDATE OR DELETE ON writers_room_draft_versions FOR EACH ROW EXECUTE FUNCTION record_audit_log();+DROP TRIGGER IF EXISTS trg_catalog_ingredients_audit ON catalog_ingredients;+CREATE TRIGGER trg_catalog_ingredients_audit AFTER UPDATE OR DELETE ON catalog_ingredients FOR EACH ROW EXECUTE FUNCTION record_audit_log();+DROP TRIGGER IF EXISTS trg_catalog_scraps_audit ON catalog_scraps;+CREATE TRIGGER trg_catalog_scraps_audit AFTER UPDATE OR DELETE ON catalog_scraps FOR EACH ROW EXECUTE FUNCTION record_audit_log();+DROP TRIGGER IF EXISTS trg_catalog_user_types_audit ON catalog_user_types;+CREATE TRIGGER trg_catalog_user_types_audit AFTER UPDATE OR DELETE ON catalog_user_types FOR EACH ROW EXECUTE FUNCTION record_audit_log();+DROP TRIGGER IF EXISTS trg_creative_director_projects_audit ON creative_director_projects;+CREATE TRIGGER trg_creative_director_projects_audit AFTER UPDATE OR DELETE ON creative_director_projects FOR EACH ROW EXECUTE FUNCTION record_audit_log();+DROP TRIGGER IF EXISTS trg_lora_training_runs_audit ON lora_training_runs;+CREATE TRIGGER trg_lora_training_runs_audit AFTER UPDATE OR DELETE ON lora_training_runs FOR EACH ROW EXECUTE FUNCTION record_audit_log();