Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix(memory): never use a developer's real Postgres under the test runner

[._.]/ Adam Eivy5bcecc73435c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index b97aa946e5..c545a6d9f3 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -24,5 +24,6 @@
- **[issue-1090] Git tab dialogs are now screen-reader friendly** — the diff and release-confirmation pop-ups announce themselves as dialogs, their close buttons are labeled, and pressing Escape (or clicking outside) dismisses them.
- **[issue-1091] Cleared two dependency security advisories** — pinned patched versions of two transitive packages to resolve a pair of moderate denial-of-service advisories flagged by `npm audit`, with no breaking changes. A couple of remaining advisories stay blocked on upstream projects publishing compatible major releases.
+- **Tests no longer write to a developer's real Postgres (and federate fixtures to live peers).** `memoryBackend.getBackend()` selected the file backend under `NODE_ENV=test` only when Postgres was *unreachable* — so on any dev machine with a healthy local `portos` DB the suite wrote hundreds of fixture universes/series/works straight into the real database, fanned them out to live Tailscale peers via `autoSubscribeRecordToAllPeers`, and let test-cleanup tombstones delete the user's real records. Test mode now short-circuits to the file backend **before** the health probe, so a running dev DB is never touched (an explicit `MEMORY_BACKEND=postgres` still opts a suite into the PG path). Adds a regression test asserting test mode bypasses a healthy Postgres, plus a one-off recovery script (`scripts/recover-synced-test-fixtures.mjs`) that restores tombstoned-real records, purges fixtures, and prunes the peer-subscription ledger.
## Removed
diff --git a/scripts/recover-synced-test-fixtures.mjs b/scripts/recover-synced-test-fixtures.mjs
new file mode 100644
index 0000000000..a6b11dd3d7
--- /dev/null
+++ b/scripts/recover-synced-test-fixtures.mjs
@@ -0,0 +1,123 @@
+#!/usr/bin/env node
+/**
+ * One-off recovery: undo the "tests wrote to the real Postgres + federated
+ * fixtures to peers" incident (see memoryBackend.js fix — test mode now bypasses
+ * a healthy DB).
+ *
+ * What happened: on machines with a live `portos` DB, the test suite created
+ * hundreds of fixture universes/series and tombstoned the user's real records.
+ * Fixtures are tiny (~700B–3KB of JSON); real authored universes/series are much
+ * larger — so a size threshold separates them cleanly with a wide safety gap.
+ *
+ * This script (per machine):
+ * 1. RESTORES real records that were tombstoned by test cleanup (deleted=true
+ * AND data >= threshold) → un-tombstones them.
+ * 2. PURGES fixture records (data < threshold), whether live or deleted.
+ * 3. PRUNES data/sharing/peer_subscriptions.json of subscriptions that point
+ * at records no longer present.
+ * 4. LISTS writers_room_works for MANUAL review (a short real work can be
+ * small, so we never auto-purge WR by size — you decide by name).
+ *
+ * SAFETY: dry-run by default. Re-run with `--apply` to mutate. Stop the
+ * portos-server first (`pm2 stop portos-server`) so sync can't race the cleanup,
+ * and take a backup:
+ * pg_dump -h localhost -p <port> -d portos -t universes -t pipeline_series \
+ * -t writers_room_works -f backup.sql
+ *
+ * Thresholds are overridable: --uni-threshold=5000 --ser-threshold=2000
+ * DB connection uses standard PG env (PGHOST/PGPORT/PGUSER/PGPASSWORD/PGDATABASE)
+ * or pass --port=5432.
+ */
+import { readFileSync, writeFileSync, copyFileSync, existsSync } from 'fs';
+import { execFileSync } from 'child_process';
+import { join } from 'path';
+
+const args = process.argv.slice(2);
+const has = (f) => args.includes(f);
+const val = (name, def) => {
+ const a = args.find((x) => x.startsWith(`--${name}=`));
+ return a ? a.split('=')[1] : def;
+};
+
+const APPLY = has('--apply');
+const UNI_THRESHOLD = Number(val('uni-threshold', 5000));
+const SER_THRESHOLD = Number(val('ser-threshold', 2000));
+const PORT = val('port', process.env.PGPORT || '5432');
+const DB = process.env.PGDATABASE || 'portos';
+const HOST = process.env.PGHOST || 'localhost';
+const DATA_ROOT = val('data-root', join(process.cwd(), 'data'));
+
+const psql = (sql) =>
+ execFileSync('psql', ['-h', HOST, '-p', PORT, '-d', DB, '-tAc', sql], {
+ encoding: 'utf8',
+ }).trim();
+
+const log = (m) => console.log(m);
+const mode = APPLY ? '🔧 APPLY' : '🔎 DRY-RUN';
+log(`${mode} — recover synced test fixtures (uni<${UNI_THRESHOLD}B, ser<${SER_THRESHOLD}B = fixture)`);
+log(` DB: ${HOST}:${PORT}/${DB}\n`);
+
+// ---- Universes ----
+const uniRestore = Number(psql(`SELECT count(*) FROM universes WHERE deleted=true AND length(data::text) >= ${UNI_THRESHOLD}`));
+const uniPurge = Number(psql(`SELECT count(*) FROM universes WHERE length(data::text) < ${UNI_THRESHOLD}`));
+log(`Universes: restore ${uniRestore} tombstoned-real | purge ${uniPurge} fixtures`);
+log(' Real universes that will be LIVE after restore:');
+log(psql(
+ `SELECT ' - '||name||' ('||length(data::text)||'B)' FROM universes WHERE length(data::text) >= ${UNI_THRESHOLD} ORDER BY name`,
+) || ' (none)');
+
+// ---- Series ----
+const serRestore = Number(psql(`SELECT count(*) FROM pipeline_series WHERE deleted=true AND length(data::text) >= ${SER_THRESHOLD}`));
+const serPurge = Number(psql(`SELECT count(*) FROM pipeline_series WHERE length(data::text) < ${SER_THRESHOLD}`));
+log(`\nSeries: restore ${serRestore} tombstoned-real | purge ${serPurge} fixtures`);
+log(' Real series that will be LIVE after restore:');
+log(psql(
+ `SELECT ' - '||name||' ('||length(data::text)||'B)' FROM pipeline_series WHERE length(data::text) >= ${SER_THRESHOLD} ORDER BY name`,
+) || ' (none)');
+
+// ---- Writers Room (manual review only) ----
+log('\nWriters Room works (MANUAL review — not auto-purged; delete the test ones by name yourself):');
+log(psql(
+ `SELECT ' - '||title||' ('||length(data::text)||'B)'||CASE WHEN deleted THEN ' [deleted]' ELSE '' END FROM writers_room_works ORDER BY length(data::text) DESC`,
+) || ' (none)');
+
+if (!APPLY) {
+ log('\nDry-run only. Re-run with --apply to execute (after stopping portos-server + backup).');
+ process.exit(0);
+}
+
+// ---- APPLY ----
+log('\n🔧 Applying…');
+const out = execFileSync('psql', ['-h', HOST, '-p', PORT, '-d', DB, '-v', 'ON_ERROR_STOP=1'], {
+ encoding: 'utf8',
+ input: `
+BEGIN;
+UPDATE universes SET deleted=false, deleted_at=NULL WHERE deleted=true AND length(data::text) >= ${UNI_THRESHOLD};
+DELETE FROM universes WHERE length(data::text) < ${UNI_THRESHOLD};
+UPDATE pipeline_series SET deleted=false, deleted_at=NULL WHERE deleted=true AND length(data::text) >= ${SER_THRESHOLD};
+DELETE FROM pipeline_series WHERE length(data::text) < ${SER_THRESHOLD};
+COMMIT;
+`,
+});
+log(out.trim());
+
+// ---- Prune peer_subscriptions.json ----
+const subsPath = join(DATA_ROOT, 'sharing', 'peer_subscriptions.json');
+if (existsSync(subsPath)) {
+ const uniIds = new Set(psql('SELECT id FROM universes WHERE deleted=false').split('\n').filter(Boolean));
+ const serIds = new Set(psql('SELECT id FROM pipeline_series WHERE deleted=false').split('\n').filter(Boolean));
+ copyFileSync(subsPath, `${subsPath}.bak`);
+ const j = JSON.parse(readFileSync(subsPath, 'utf8'));
+ const before = j.subscriptions.length;
+ j.subscriptions = j.subscriptions.filter((s) => {
+ if (s.recordKind === 'universe') return uniIds.has(s.recordId);
+ if (s.recordKind === 'series') return serIds.has(s.recordId);
+ return true; // keep mediaCollection + other kinds
+ });
+ writeFileSync(subsPath, JSON.stringify(j, null, 2));
+ log(`peer_subscriptions.json: ${before} -> ${j.subscriptions.length} (pruned ${before - j.subscriptions.length} dead; .bak saved)`);
+}
+
+log('\n✅ Done. Universes live: ' + psql('SELECT count(*) FROM universes WHERE deleted=false') +
+ ', series live: ' + psql('SELECT count(*) FROM pipeline_series WHERE deleted=false'));
+log(' Clean every federated machine while sync is paused, then `pm2 start portos-server` to resume.');
diff --git a/server/services/memoryBackend.js b/server/services/memoryBackend.js
index f622f34f8d..2f4c9db1fc 100644
--- a/server/services/memoryBackend.js
+++ b/server/services/memoryBackend.js
@@ -48,6 +48,23 @@ async function getBackend() {
return backend;
}
+ // Under the test runner, ALWAYS use the file backend — never probe or touch a
+ // real Postgres instance. A developer's machine commonly has a live `portos`
+ // DB running (and that DB is federated to real peers). If the suite were to
+ // auto-detect that healthy DB it would write hundreds of fixture
+ // universes/series into it AND fan them out to live peers via
+ // autoSubscribeRecordToAllPeers — and test-cleanup tombstones would delete the
+ // user's real records. This must short-circuit BEFORE checkHealth(); the
+ // earlier conditional-on-unavailable form silently wrote to a dev's real DB
+ // whenever Postgres happened to be up. An explicit `MEMORY_BACKEND=postgres`
+ // (handled above) still opts a suite into the PG path.
+ if (process.env.NODE_ENV === 'test') {
+ backend = await import('./memory.js');
+ backendName = 'file';
+ console.log('🧠 Memory backend: file-based (test mode — Postgres deliberately bypassed)');
+ return backend;
+ }
+
// MEMORY_BACKEND unset: require PostgreSQL. We do NOT silently fall back to
// file storage when Postgres is unavailable — that masks a broken install.
const health = await checkHealth();
@@ -59,18 +76,6 @@ async function getBackend() {
return backend;
}
- // Postgres is required but unavailable/unhealthy. The only sanctioned
- // file-backed path here is the test/dev escape hatch — and that requires
- // NODE_ENV=test (explicit MEMORY_BACKEND=file is handled above). Tests boot
- // without a database; gate the file backend on test mode so a real install
- // never silently serves file-backed memory.
- if (process.env.NODE_ENV === 'test') {
- backend = await import('./memory.js');
- backendName = 'file';
- console.log(`🧠 Memory backend: file-based (test mode — PostgreSQL unavailable: ${health.error || 'no schema'})`);
- return backend;
- }
-
// Production / normal install with no DB and no escape hatch: this is an
// error condition, not a fallback. Log loudly and point at setup. Startup
// (server/index.js) fails fast on the same condition.
diff --git a/server/services/memoryBackend.test.js b/server/services/memoryBackend.test.js
index 0487091f5e..28418bc78b 100644
--- a/server/services/memoryBackend.test.js
+++ b/server/services/memoryBackend.test.js
@@ -90,4 +90,18 @@ describe('memoryBackend backend selection', () => {
const name = await mod.ensureBackend();
expect(name).toBe('file');
});
+
+ it('uses the file backend in test mode even when Postgres is HEALTHY — never probes a live dev DB', async () => {
+ // Regression guard: a developer's machine commonly has a live `portos` DB
+ // running (federated to real peers). The test runner must never write to
+ // it — fixture creation would pollute the DB and fan out to peers, and
+ // cleanup tombstones would delete real records. Test mode must short-circuit
+ // to the file backend BEFORE the health probe runs.
+ process.env.NODE_ENV = 'test';
+ checkHealth.mockResolvedValue({ connected: true, hasSchema: true });
+ const mod = await loadFresh();
+ const name = await mod.ensureBackend();
+ expect(name).toBe('file');
+ expect(checkHealth).not.toHaveBeenCalled();
+ });
});