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
address review (codex): verify record identity, not row counts, before prune
Adam Eivy5c67785caaa4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex f9e765654b..7bff0e74f9 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -43,7 +43,7 @@- Code quality: extracted the duplicated cron-expression validation in `cosJobRoutes.js` (job create/update) into a single `validateCronExpression()` helper, and unified the two slightly-divergent error messages.- Code quality: replaced inline `8000` / `8` / `4` / `20 * 1024 * 1024` literals in the image-generation routes with named constants (`MAX_PROMPT_LENGTH`, `MAX_LORAS`, `MAX_REFERENCE_IMAGES`, `MAX_IMAGE_UPLOAD_BYTES`); the `referenceImageN` upload field list now derives from `MAX_REFERENCE_IMAGES` so it can't drift.- Code quality: replaced the local `safeReadJson` reimplementation in `apps.js` with the shared `readJSONFile` helper from `fileUtils.js`, and named the repeated `1500` ms inter-action throttle in `agentActionExecutor.js` as `INTER_ACTION_DELAY_MS`.-- **Legacy file→Postgres migration artifacts are now cleaned up automatically** — the file→DB migrations (#997, #1014–#1017, plus the split migrations 034–036) each parked their source data aside as a "one-release recovery source" (`data/universes.imported`, `pipeline-issues.imported`, `*.bak-NNN`, per-record `index.json.imported` / `manifest.imported.json`, etc.) but nothing ever removed them, so they accumulated in `./data` (several MB on a long-lived install) even though the authoritative copy now lives in PostgreSQL and the `pg_dump`. A new boot-time prune (`server/scripts/pruneImportedLegacyFiles.js`, registered in the ledger as migration 077) removes those copies once the database is provably authoritative — it deletes a domain's parked files **only** when the live row count meets or exceeds the count recorded for *every* table whose data those files hold (the migration's `*.migrated.json` marker counts, plus the draft-version count read back from the parked Writers Room manifests), so a wiped or partially-restored database keeps its recovery files and a later boot retries. The artifacts are intentionally still included in rsync backups while they remain on disk — during a blocked prune they're the only recovery source and the `pg_dump` is of the incomplete database, so a snapshot must keep them; once pruned they leave subsequent snapshots naturally. The Writers Room `.md` draft bodies (file-primary by design, not migrated to the database) are always preserved. The prune never runs under the `MEMORY_BACKEND=file` dev/test escape hatch.+- **Legacy file→Postgres migration artifacts are now cleaned up automatically** — the file→DB migrations (#997, #1014–#1017, plus the split migrations 034–036) each parked their source data aside as a "one-release recovery source" (`data/universes.imported`, `pipeline-issues.imported`, `*.bak-NNN`, per-record `index.json.imported` / `manifest.imported.json`, etc.) but nothing ever removed them, so they accumulated in `./data` (several MB on a long-lived install) even though the authoritative copy now lives in PostgreSQL and the `pg_dump`. A new boot-time prune (`server/scripts/pruneImportedLegacyFiles.js`, registered in the ledger as migration 077) removes those copies once the database is provably authoritative — it deletes a domain's parked files **only** after verifying, by record identity, that every migrated record those files hold is still present in the database (it reads the record ids off the artifacts themselves — directory names and JSON `.id`s, including universe run logs and Writers Room draft versions — and checks those exact ids exist). Identity rather than a row count, so a wipe-and-restore to a *different* record set can't satisfy the check with substitute rows; a database missing any parked id keeps its recovery files and a later boot retries. The artifacts are intentionally still included in rsync backups while they remain on disk — during a blocked prune they're the only recovery source and the `pg_dump` is of the incomplete database, so a snapshot must keep them; once pruned they leave subsequent snapshots naturally. The Writers Room `.md` draft bodies (file-primary by design, not migrated to the database) are always preserved. The prune never runs under the `MEMORY_BACKEND=file` dev/test escape hatch.## Fixeddiff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 179219b452..88c0972511 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -100,7 +100,7 @@ Defaulting a new Create feature to a fresh `data/*.json` file is the anti-patter### Legacy migration-source cleanup-Each file→Postgres migrator parks its source aside (`<domain>.imported`, per-record `index.json.imported` / `manifest.imported.json`, split-migration `*.bak-NNN`) instead of deleting it, as a one-release recovery copy. `server/scripts/pruneImportedLegacyFiles.js` (run at boot from `server/index.js`, after every store's file→DB warm, registered in the ledger by `scripts/migrations/077-prune-imported-legacy-files.js`) removes those copies **only** when the live Postgres row count is `>=` the count recorded for **every** table whose data the artifacts hold — the `<domain>.migrated.json` marker counts (e.g. `universes` + `universe_runs`, all three writers-room tables) plus, for writers-room draft versions, the `drafts[]` count read back from the parked manifests. A wiped or partially-restored DB that is short in any of those tables keeps its recovery files and a future boot retries. These artifacts are deliberately **not** excluded from rsync backups: while a prune is blocked they are the only recovery source and `pg_dump` is capturing the incomplete DB, so a snapshot must keep them — once pruned from disk they leave subsequent snapshots naturally.+Each file→Postgres migrator parks its source aside (`<domain>.imported`, per-record `index.json.imported` / `manifest.imported.json`, split-migration `*.bak-NNN`) instead of deleting it, as a one-release recovery copy. `server/scripts/pruneImportedLegacyFiles.js` (run at boot from `server/index.js`, after every store's file→DB warm, registered in the ledger by `scripts/migrations/077-prune-imported-legacy-files.js`) removes those copies **only** when it has verified, by **record identity**, that every migrated record those artifacts hold is still present in the database. It reads the record ids straight off the parked artifacts — the `.imported` directory names, or the parsed JSON `.id` (the creative-director export, each writers-room manifest/folder/exercise, the universe `config.runs[]`, each manifest's `drafts[]`) — and checks those exact ids exist via `WHERE id = ANY(...)`. Identity rather than a row count, because a count can be satisfied by unrelated rows after a wipe+restore to a different record set (and the migrators' `imported` count comes from `INSERT … ON CONFLICT DO NOTHING`, so it can undercount). A wiped or partially-restored DB missing **any** parked id keeps its recovery files and a future boot retries. These artifacts are deliberately **not** excluded from rsync backups: while a prune is blocked they are the only recovery source and `pg_dump` is capturing the incomplete DB, so a snapshot must keep them — once pruned from disk they leave subsequent snapshots naturally.---diff --git a/server/scripts/pruneImportedLegacyFiles.js b/server/scripts/pruneImportedLegacyFiles.jsindex bbc83fa8f7..8fcf08ca22 100644--- a/server/scripts/pruneImportedLegacyFiles.js+++ b/server/scripts/pruneImportedLegacyFiles.js@@ -14,36 +14,46 @@* them — see the NOTE in server/services/backup.js. Once pruned from disk they* leave subsequent snapshots naturally.)*- * WHY THIS RUNS AT BOOT (not in scripts/migrations/): the prune reads Postgres- * row counts, but the `scripts/migrations/` runner executes BEFORE the DB pool- * is up. So — exactly like repairUniverseTags / reconcileCanonCatalog — the real- * work runs here from server/index.js (after ensureSchema + every store's- * file→DB warm import), and scripts/migrations/077-prune-imported-legacy-files.js- * is a registration stub so the change still lands in the migration ledger.+ * WHY THIS RUNS AT BOOT (not in scripts/migrations/): the prune reads Postgres,+ * but the `scripts/migrations/` runner executes BEFORE the DB pool is up. So —+ * exactly like repairUniverseTags / reconcileCanonCatalog — the real work runs+ * here from server/index.js (after ensureSchema + every store's file→DB warm+ * import), and scripts/migrations/077-prune-imported-legacy-files.js is a+ * registration stub so the change still lands in the migration ledger.*- * SAFETY — the count-vs-marker guard (avoids the .length-truthiness footgun in- * CLAUDE.md). A domain is pruned only when:- * (1) its `<domain>.migrated.json` marker exists (the migrator stamped it ONLY- * after a successful import + rename), AND- * (2) the live DB row count is >= the `imported` count the marker recorded.- * "Table non-empty" would be WRONG: an install with genuinely zero records- * (imported:0) would never prune its empty `.imported` dir and would re-walk- * every boot forever. Comparing against the marker's recorded count instead- * prunes the empty case (0 >= 0) while still WITHHOLDING when the marker says- * `imported:13` but the table has 0 rows — the signature of a wiped / restored- * DB, where the `.imported` files are the only remaining recovery source and- * must NOT be deleted. This whole repair is also gated upstream by the+ * SAFETY — IDENTITY verification (not a row count). A domain's artifacts are+ * deleted only when EVERY record id those artifacts hold is confirmed present in+ * the database. The ids come straight off disk: the parked directory NAMES+ * (`universes.imported/<id>/`, `pipeline-issues.imported/<id>/`) or the parsed+ * JSON `.id` (the creative-director array, each writers-room manifest/folder/+ * exercise, the universe `config.runs[]`, each manifest's `drafts[]`). We then+ * verify those exact ids exist via `SELECT id ... WHERE id = ANY($1)`.+ *+ * Why identity, not `COUNT(*) >= marker.imported` (the prior approach, rejected+ * in review): a count can be satisfied by UNRELATED rows after a wipe+restore to+ * a different record set, and the migrators record `imported` from+ * `INSERT … ON CONFLICT DO NOTHING`, so a partial-retry marker can undercount+ * the parked source — either way a count `>=` check can pass while the specific+ * migrated rows are gone, deleting the only recovery copy. Checking the actual+ * ids can't be fooled by substitute rows or an undercounted marker. It also+ * handles the genuinely-empty install for free (no ids on disk → nothing to+ * verify → safe to prune the empty `.imported` dir) without depending on any+ * marker field. The `<domain>.migrated.json` marker is now used ONLY as a+ * "migration ran" signal (no marker → nothing was parked → skip).+ *+ * A wiped / partially-restored DB that is missing ANY parked id WITHHOLDS the+ * whole domain's prune and leaves the completion marker unwritten, so a future+ * boot retries once the DB is whole. This repair is also gated upstream by the* `dbReady` block in server/index.js, so it never runs under the* MEMORY_BACKEND=file escape hatch (no DB → no prune → recovery files kept).** File-split backups (037 history.json, 059 media-collections.json) are NOT a* Postgres move — their successors live on disk — so they use a successor-exists- * gate instead of a row count.+ * gate instead of id verification.** Idempotent: `rm({ recursive: true, force: true })` no-ops on already-removed* paths, and a marker in `data/legacy-prune.applied.json` skips the walk once a- * clean, complete pass has run. The marker is WITHHELD if any domain was blocked- * (marker present but row count short) so a future boot retries that domain.+ * clean, complete pass has run.*/import { readFile, writeFile, rm, readdir, stat } from 'fs/promises';@@ -53,75 +63,109 @@ import { PATHS } from '../lib/fileUtils.js';const MARKER_VERSION = 1;const MARKER_FILENAME = 'legacy-prune.applied.json';-// DB-gated domains: each was migrated file→Postgres. `markerFile` is the-// migrator's own completion marker; `guards` is the count-vs-marker check — one-// `{ table, expected(marker) }` per DB table whose data this domain's artifacts-// hold, so a wipe/restore that lost rows in ANY of them withholds the prune (a-// domain is pruned only when EVERY guard's live row count >= the marker's-// recorded count for that table); `artifacts` are the parked sources to remove-// (relative to data/, file OR dir — rm handles both); `nestedGlobs` are-// per-record artifacts that sit inside a still-live directory (one level deep).+// --- id extractors: pull the record ids a parked artifact holds, off disk. ---++// Immediate subdirectory names under `data/<dir>` (each a record id). Skips a+// type-level `index.json` and dotfiles. Used by the split-migration layouts+// where the record id IS the directory name.+async function idsFromSubdirs(base, dir) {+ const entries = await readdir(join(base, dir), { withFileTypes: true }).catch(() => []);+ return entries+ .filter((e) => e.isDirectory() && e.name !== 'index.json' && !e.name.startsWith('.'))+ .map((e) => e.name);+}++// `.id` of every element of a top-level JSON array file (the CD export, and the+// writers-room folders.imported.json / exercises.imported.json bare arrays).+async function idsFromJsonArray(base, file) {+ const arr = await readJson(base, file);+ return Array.isArray(arr) ? arr.map((r) => r?.id).filter((id) => typeof id === 'string') : [];+}++// Universe run ids: the type-level index.json's `config.runs[]`, each `{ id }`.+// (migrateUniversesToDB reads runs from `universes.imported/index.json`.)+async function universeRunIds(base) {+ const typeIndex = await readJson(base, 'universes.imported/index.json');+ const runs = Array.isArray(typeIndex?.config?.runs) ? typeIndex.config.runs : [];+ return runs.map((r) => r?.id).filter((id) => typeof id === 'string');+}++// Writers-room work ids + draft-version ids, read from each parked manifest.+async function writersRoomManifestIds(base) {+ const worksDir = 'writers-room/works';+ const subdirs = await readdir(join(base, worksDir), { withFileTypes: true }).catch(() => []);+ const workIds = [];+ const draftIds = [];+ for (const entry of subdirs) {+ if (!entry.isDirectory()) continue;+ const manifest = await readJson(base, join(worksDir, entry.name, 'manifest.imported.json'));+ if (typeof manifest?.id === 'string') workIds.push(manifest.id);+ if (Array.isArray(manifest?.drafts)) {+ for (const d of manifest.drafts) if (typeof d?.id === 'string') draftIds.push(d.id);+ }+ }+ return { workIds, draftIds };+}++// DB-gated domains. `markerFile` is the migrator's completion marker (used only+// as a "migration ran" signal — no marker means nothing was parked). `verify`+// returns `{ table, ids }[]`: the record ids each table must still contain for+// the artifacts to be safe to delete. `artifacts` are the parked sources to+// remove (file OR dir); `nestedGlobs` are per-record artifacts inside a still-+// live directory (one level deep).const DB_DOMAINS = [{label: 'universes',markerFile: 'universes.migrated.json',- // universes.imported / .bak-034 hold BOTH the universe rows AND the- // cross-record config.runs[] log that migrateUniversesToDB decomposes into- // universe_runs (recorded as marker.runs). Guard both, so a restore that- // kept universes but lost the run history withholds the prune.- guards: [- { table: 'universes', expected: (m) => num(m?.imported) },- { table: 'universe_runs', expected: (m) => num(m?.runs) },+ // universes.imported holds both the universe records (subdir names) and the+ // config.runs[] log decomposed into universe_runs — verify both id sets.+ verify: async (base) => [+ { table: 'universes', ids: await idsFromSubdirs(base, 'universes.imported') },+ { table: 'universe_runs', ids: await universeRunIds(base) },],artifacts: ['universes.imported', 'universe-builder.json.bak-034'],},{label: 'pipeline-issues',markerFile: 'pipeline-issues.migrated.json',- guards: [{ table: 'pipeline_issues', expected: (m) => num(m?.imported) }],+ verify: async (base) => [+ { table: 'pipeline_issues', ids: await idsFromSubdirs(base, 'pipeline-issues.imported') },+ ],artifacts: ['pipeline-issues.imported', 'pipeline-issues.json.bak-035'],},{label: 'pipeline-series',markerFile: 'pipeline-series.migrated.json',- guards: [{ table: 'pipeline_series', expected: (m) => num(m?.imported) }],- artifacts: ['pipeline-series.json.bak-036'],// migrateSeriesToDB renamed each record's index.json IN PLACE, leaving the- // pipeline-series/<id>/ dir (+ manuscript-review.json sibling) intact.+ // pipeline-series/<id>/ dir (+ manuscript-review.json sibling) intact — so+ // the series ids are the subdir names holding an index.json.imported.+ verify: async (base) => [+ { table: 'pipeline_series', ids: await idsFromSubdirsWithLeaf(base, 'pipeline-series', 'index.json.imported') },+ ],+ artifacts: ['pipeline-series.json.bak-036'],nestedGlobs: [{ baseDir: 'pipeline-series', leaf: 'index.json.imported' }],},{label: 'story-builder',markerFile: 'story-builder.migrated.json',- guards: [{ table: 'story_builder_sessions', expected: (m) => num(m?.imported) }],+ verify: async (base) => [+ { table: 'story_builder_sessions', ids: await idsFromSubdirs(base, 'story-builder.imported') },+ ],artifacts: ['story-builder.imported'],},{label: 'writers-room',markerFile: 'writers-room.migrated.json',- // The writers-room marker records folders/works/exercises separately, and- // this domain deletes the recovery copy of ALL THREE (folders.imported.json,- // each work's manifest.imported.json, exercises.imported.json) — so guard on- // all three tables, not just works. (The migrator writes the marker only- // after all three import, so on a clean migration works alone would proxy- // the rest; the per-table guards make the wipe/restore case correct too — a- // restore that brought back works but lost folders won't delete the folders- // recovery file.)- guards: [- { table: 'writers_room_folders', expected: (m) => num(m?.folders) },- { table: 'writers_room_works', expected: (m) => num(m?.works) },- { table: 'writers_room_exercises', expected: (m) => num(m?.exercises) },- ],- // The per-work manifest.imported.json files carry the `drafts[]` metadata- // that migrateWritersRoomToDB decomposes into writers_room_draft_versions- // rows (the marker records no draft-version count, so it can't be a normal- // marker guard). Before deleting the manifests, count the drafts they hold- // and require at least that many version rows — else a restore that kept- // works but lost draft-version rows would delete the only recovery source- // for that version metadata. The .md bodies stay on disk regardless.- manifestDraftGuard: {- table: 'writers_room_draft_versions',- manifestGlob: { baseDir: 'writers-room/works', leaf: 'manifest.imported.json' },+ // This domain deletes the recovery copy of folders + works + exercises ++ // each work's drafts[], so verify every id set those artifacts hold.+ verify: async (base) => {+ const { workIds, draftIds } = await writersRoomManifestIds(base);+ return [+ { table: 'writers_room_folders', ids: await idsFromJsonArray(base, 'writers-room/folders.imported.json') },+ { table: 'writers_room_exercises', ids: await idsFromJsonArray(base, 'writers-room/exercises.imported.json') },+ { table: 'writers_room_works', ids: workIds },+ { table: 'writers_room_draft_versions', ids: draftIds },+ ];},artifacts: ['writers-room/folders.imported.json', 'writers-room/exercises.imported.json'],nestedGlobs: [{ baseDir: 'writers-room/works', leaf: 'manifest.imported.json' }],@@ -129,35 +173,54 @@ const DB_DOMAINS = [{label: 'creative-director',markerFile: 'creative-director-projects.migrated.json',- guards: [{ table: 'creative_director_projects', expected: (m) => num(m?.imported) }],+ verify: async (base) => [+ { table: 'creative_director_projects', ids: await idsFromJsonArray(base, 'creative-director-projects.json.imported') },+ ],artifacts: ['creative-director-projects.json.imported'],},];// File-split backups: data reshaped file→file (NOT moved to Postgres), so they-// gate on the successor existing on disk rather than a DB row count. `backup` is-// a prefix: migration 037/059 normally write the bare `.bak-NNN`, but on a-// re-run collision they append `-<timestamp>`, so match the prefix to catch-// those variants too.+// gate on the reshaped successor existing on disk. `backupPrefix` is a prefix:+// migration 037/059 normally write the bare `.bak-NNN`, but on a re-run+// collision they append `-<timestamp>`, so match the prefix to catch those too.const FILE_SPLIT_BACKUPS = [{ label: 'history', backupPrefix: 'history.json.bak-037', successor: 'history.jsonl' },{ label: 'media-collections', backupPrefix: 'media-collections.json.bak-059', successor: 'media-collections' },];-function num(v) {- return typeof v === 'number' && Number.isFinite(v) ? v : 0;-}-async function pathExists(p) {return stat(p).then(() => true, () => false);}-async function readJsonMarker(base, filename) {- const raw = await readFile(join(base, filename), 'utf-8').catch(() => null);+async function readJson(base, file) {+ const raw = await readFile(join(base, file), 'utf-8').catch(() => null);if (!raw) return null;try { return JSON.parse(raw); } catch { return null; }}+// Subdir names under `data/<dir>` that contain a `<leaf>` file — the record ids+// for an in-place rename layout (pipeline-series keeps the live dir, so a bare+// subdir scan would also pick up unrelated siblings; gate on the leaf).+async function idsFromSubdirsWithLeaf(base, dir, leaf) {+ const entries = await readdir(join(base, dir), { withFileTypes: true }).catch(() => []);+ const ids = [];+ for (const entry of entries) {+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue;+ if (await pathExists(join(base, dir, entry.name, leaf))) ids.push(entry.name);+ }+ return ids;+}++// Of `ids`, return those NOT present in `table` (the rows a prune would orphan).+// Empty `ids` → no query, nothing missing (genuinely-empty install prunes free).+async function missingIds(query, table, ids) {+ if (ids.length === 0) return [];+ const { rows } = await query(`SELECT id FROM ${table} WHERE id = ANY($1)`, [ids]);+ const present = new Set(rows.map((r) => r.id));+ return ids.filter((id) => !present.has(id));+}+// Remove a path (file or dir) under `base`. force:true → no throw if absent.// Returns true if the path existed before removal (so we can report a count).async function removeUnder(base, rel) {@@ -189,21 +252,6 @@ async function removeByPrefix(base, prefix) {return removed;}-// Sum the `drafts[]` lengths across every `<baseDir>/<sub>/<leaf>` manifest —-// the number of draft-version rows those manifests were decomposed into. Used-// to verify writers_room_draft_versions wasn't lost before deleting the-// manifests (the only on-disk recovery source for that version metadata).-async function countManifestDrafts(base, baseDir, leaf) {- const entries = await readdir(join(base, baseDir), { withFileTypes: true }).catch(() => []);- let drafts = 0;- for (const entry of entries) {- if (!entry.isDirectory()) continue;- const manifest = await readJsonMarker(base, join(baseDir, entry.name, leaf));- if (Array.isArray(manifest?.drafts)) drafts += manifest.drafts.length;- }- return drafts;-}-/*** @param {object} [opts]* @param {boolean} [opts.force] - re-run even if the marker is current (tests/admin).@@ -213,7 +261,7 @@ async function countManifestDrafts(base, baseDir, leaf) {export async function pruneImportedLegacyFiles({ force = false, db, dataDir } = {}) {const base = dataDir ?? PATHS.data;- const existing = await readJsonMarker(base, MARKER_FILENAME);+ const existing = await readJson(base, MARKER_FILENAME);if (existing?.version === MARKER_VERSION && !force) {return { skipped: true, marker: existing };}@@ -222,39 +270,25 @@ export async function pruneImportedLegacyFiles({ force = false, db, dataDir } =const totals = { removed: 0, blocked: 0, pruned: [] };for (const domain of DB_DOMAINS) {- const marker = await readJsonMarker(base, domain.markerFile);// No marker → migrator never completed for this install (or fresh install// with no legacy data). Nothing parked aside to prune; not a block.+ const marker = await readJson(base, domain.markerFile);if (!marker) continue;- // Count-vs-marker guard: a short count in ANY guarded table means the DB- // lost rows the marker says were imported (wipe / restore) — the parked- // files are the recovery source, so WITHHOLD and let a future boot retry- // once the DB is whole. Check every table whose data this domain deletes.+ // Identity guard: every id the parked artifacts hold must still be present+ // in its table. A missing id means the DB lost a migrated record (wipe /+ // partial restore) — the parked files are the recovery source, so WITHHOLD+ // the whole domain and let a future boot retry once the DB is whole.+ const checks = await domain.verify(base);let blocked = false;- for (const guard of domain.guards) {- const expected = guard.expected(marker);- const { rows } = await query(`SELECT COUNT(*)::int AS n FROM ${guard.table}`);- const count = num(rows?.[0]?.n);- if (count < expected) {- console.warn(`🧹 legacy-prune: ${domain.label} blocked — ${guard.table} has ${count} row(s) but marker recorded ${expected}; keeping recovery files`);+ for (const { table, ids } of checks) {+ const missing = await missingIds(query, table, ids);+ if (missing.length > 0) {+ console.warn(`🧹 legacy-prune: ${domain.label} blocked — ${missing.length}/${ids.length} ${table} id(s) missing from DB (e.g. ${missing[0]}); keeping recovery files`);blocked = true;break;}}- // Manifest-derived guard (writers-room draft versions): the expected count- // comes from the parked manifests on disk, not the marker. Only checked when- // not already blocked by a table guard.- if (!blocked && domain.manifestDraftGuard) {- const g = domain.manifestDraftGuard;- const expected = await countManifestDrafts(base, g.manifestGlob.baseDir, g.manifestGlob.leaf);- const { rows } = await query(`SELECT COUNT(*)::int AS n FROM ${g.table}`);- const count = num(rows?.[0]?.n);- if (count < expected) {- console.warn(`🧹 legacy-prune: ${domain.label} blocked — ${g.table} has ${count} row(s) but parked manifests hold ${expected} draft(s); keeping recovery files`);- blocked = true;- }- }if (blocked) {totals.blocked++;continue;diff --git a/server/scripts/pruneImportedLegacyFiles.test.js b/server/scripts/pruneImportedLegacyFiles.test.jsindex 5809829e7e..ff1714c1a6 100644--- a/server/scripts/pruneImportedLegacyFiles.test.js+++ b/server/scripts/pruneImportedLegacyFiles.test.js@@ -1,15 +1,17 @@/*** Isolated unit test for the legacy-artifact prune. No live DB needed — the- * module accepts an injectable `db` (a `{ query }` stub returning row counts)- * and a `dataDir` override pointing at a temp tree. Proves the contract:- * 1. prunes a domain's parked artifacts when the live row count >= the marker,- * 2. WITHHOLDS (keeps the recovery files) when the count is short of the- * marker — the wiped/restored-DB signature,- * 3. prunes the genuinely-empty case (imported:0 / 0 rows),+ * module accepts an injectable `db` (a `{ query }` stub backed by a per-table+ * id-set) and a `dataDir` override pointing at a temp tree. Proves the contract:+ * 1. prunes a domain's parked artifacts when EVERY parked record id is present+ * in its table (identity verification, not a row count),+ * 2. WITHHOLDS (keeps the recovery files) when ANY parked id is missing — the+ * wiped / partial-restore signature — including the secondary id sets+ * (universe_runs, writers_room_draft_versions) that share a domain,+ * 3. prunes the genuinely-empty case (no ids on disk → nothing to verify),* 4. removes the per-record nested artifacts but leaves live siblings + bodies,- * 5. file-split backups gate on the successor existing,+ * 5. file-split backups gate on the successor existing (+ timestamped variant),* 6. marker-gated: a clean pass stamps the marker and the next run no-ops; a- * blocked pass withholds the marker so a future boot retries.+ * blocked pass withholds the marker; a force-blocked run drops a stale one.*/import { describe, it, expect, beforeEach, afterEach } from 'vitest';@@ -23,13 +25,15 @@ let dataDir;const exists = (p) => stat(p).then(() => true, () => false);const writeJSON = (p, obj) => writeFile(p, JSON.stringify(obj), 'utf-8');-// A db stub whose COUNT(*) result is driven by a per-table map.-function stubDb(counts) {+// A db stub backed by a per-table set of present ids. Answers the prune's only+// query shape: `SELECT id FROM <table> WHERE id = ANY($1)`.+function stubDb(tables) {return {- async query(text) {- const m = text.match(/FROM (\w+)/);- const table = m?.[1];- return { rows: [{ n: counts[table] ?? 0 }] };+ async query(text, params) {+ const table = text.match(/FROM (\w+)/)?.[1];+ const present = new Set(tables[table] ?? []);+ const asked = params?.[0] ?? [];+ return { rows: asked.filter((id) => present.has(id)).map((id) => ({ id })) };},};}@@ -41,13 +45,22 @@ afterEach(async () => {await rm(dataDir, { recursive: true, force: true });});+// Build a universes.imported tree with the given universe-id subdirs and a+// type-level index.json carrying config.runs[] of the given run ids.+async function seedUniverses(ids, runIds = []) {+ const dir = join(dataDir, 'universes.imported');+ await mkdir(dir, { recursive: true });+ for (const id of ids) await mkdir(join(dir, id), { recursive: true });+ await writeJSON(join(dir, 'index.json'), { config: { runs: runIds.map((id) => ({ id, universeId: ids[0] })) } });+}+describe('pruneImportedLegacyFiles', () => {- it('prunes a domain whose row count matches the marker', async () => {- await writeJSON(join(dataDir, 'universes.migrated.json'), { imported: 13, runs: 2 });- await mkdir(join(dataDir, 'universes.imported'), { recursive: true });+ it('prunes a domain when every parked record id is present in the DB', async () => {+ await writeJSON(join(dataDir, 'universes.migrated.json'), { imported: 2, runs: 1 });+ await seedUniverses(['u1', 'u2'], ['r1']);await writeFile(join(dataDir, 'universe-builder.json.bak-034'), 'legacy', 'utf-8');- const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ universes: 13, universe_runs: 2 }) });+ const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ universes: ['u1', 'u2'], universe_runs: ['r1'] }) });expect(res.skipped).toBe(false);expect(await exists(join(dataDir, 'universes.imported'))).toBe(false);@@ -56,45 +69,55 @@ describe('pruneImportedLegacyFiles', () => {expect(await exists(join(dataDir, 'legacy-prune.applied.json'))).toBe(true);});- it('WITHHOLDS prune + marker when the row count is short of the marker (wiped/restored DB)', async () => {- await writeJSON(join(dataDir, 'universes.migrated.json'), { imported: 13, runs: 2 });- await mkdir(join(dataDir, 'universes.imported'), { recursive: true });+ it('WITHHOLDS prune + marker when a parked universe id is missing (wiped/restored DB)', async () => {+ await writeJSON(join(dataDir, 'universes.migrated.json'), { imported: 2, runs: 0 });+ await seedUniverses(['u1', 'u2']);- const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ universes: 0, universe_runs: 0 }) });+ // DB only has u1 — u2 was lost. Must keep the recovery dir.+ const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ universes: ['u1'] }) });expect(res.blocked).toBe(1);expect(res.markerWritten).toBe(false);- // Recovery files survive, and no completion marker is written so a future- // boot (once the DB is whole) retries.expect(await exists(join(dataDir, 'universes.imported'))).toBe(true);expect(await exists(join(dataDir, 'legacy-prune.applied.json'))).toBe(false);});- it('WITHHOLDS universe prune when universe_runs is short even though universes is whole', async () => {- // Partial restore: universe rows came back, run history did not. The- // .imported dir is the only recovery source for universe_runs, so keep it.- await writeJSON(join(dataDir, 'universes.migrated.json'), { imported: 13, runs: 2 });- await mkdir(join(dataDir, 'universes.imported'), { recursive: true });+ it('WITHHOLDS universe prune when a run id is missing even though all universes are present', async () => {+ // Partial restore: universe rows back, run history lost. universes.imported+ // is the only recovery source for universe_runs, so keep it.+ await writeJSON(join(dataDir, 'universes.migrated.json'), { imported: 1, runs: 2 });+ await seedUniverses(['u1'], ['r1', 'r2']);- const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ universes: 13, universe_runs: 0 }) });+ const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ universes: ['u1'], universe_runs: ['r1'] }) });expect(res.blocked).toBe(1);expect(res.markerWritten).toBe(false);expect(await exists(join(dataDir, 'universes.imported'))).toBe(true);});- it('prunes the genuinely-empty case (imported:0, 0 rows)', async () => {+ it('does NOT pass identity verification just because the table has unrelated rows', async () => {+ // The count-based predecessor would have passed (1 row >= 1 imported); the+ // id check must fail because the DB row is a DIFFERENT universe.+ await writeJSON(join(dataDir, 'universes.migrated.json'), { imported: 1, runs: 0 });+ await seedUniverses(['u1']);++ const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ universes: ['some-other-universe'] }) });++ expect(res.blocked).toBe(1);+ expect(await exists(join(dataDir, 'universes.imported'))).toBe(true);+ });++ it('prunes the genuinely-empty case (no ids on disk → nothing to verify)', async () => {await writeJSON(join(dataDir, 'story-builder.migrated.json'), { imported: 0 });await mkdir(join(dataDir, 'story-builder.imported'), { recursive: true });- const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ story_builder_sessions: 0 }) });+ const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ story_builder_sessions: [] }) });expect(res.markerWritten).toBe(true);expect(await exists(join(dataDir, 'story-builder.imported'))).toBe(false);});it('skips a domain with no migration marker (never parked anything)', async () => {- // creative-director never migrated on this install — no marker, no files.const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({}) });expect(res.blocked).toBe(0);expect(res.removed).toBe(0);@@ -103,16 +126,16 @@ describe('pruneImportedLegacyFiles', () => {it('removes per-record nested artifacts but keeps live siblings', async () => {await writeJSON(join(dataDir, 'pipeline-series.migrated.json'), { imported: 2 });- const seriesA = join(dataDir, 'pipeline-series', 'aaa');- const seriesB = join(dataDir, 'pipeline-series', 'bbb');+ const seriesA = join(dataDir, 'pipeline-series', 'ser-a');+ const seriesB = join(dataDir, 'pipeline-series', 'ser-b');await mkdir(seriesA, { recursive: true });await mkdir(seriesB, { recursive: true });await writeFile(join(seriesA, 'index.json.imported'), '{}', 'utf-8');- await writeFile(join(seriesA, 'index.json'), '{}', 'utf-8'); // live record+ await writeFile(join(seriesA, 'index.json'), '{}', 'utf-8'); // live recordawait writeFile(join(seriesA, 'manuscript-review.json'), '{}', 'utf-8'); // live siblingawait writeFile(join(seriesB, 'index.json.imported'), '{}', 'utf-8');- const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ pipeline_series: 2 }) });+ const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ pipeline_series: ['ser-a', 'ser-b'] }) });expect(res.markerWritten).toBe(true);expect(await exists(join(seriesA, 'index.json.imported'))).toBe(false);@@ -123,19 +146,20 @@ describe('pruneImportedLegacyFiles', () => {});it('removes writers-room metadata artifacts but keeps .md draft bodies', async () => {- await writeJSON(join(dataDir, 'writers-room.migrated.json'), { folders: 2, works: 1, exercises: 3 });+ await writeJSON(join(dataDir, 'writers-room.migrated.json'), { folders: 1, works: 1, exercises: 1 });const wr = join(dataDir, 'writers-room');const work = join(wr, 'works', 'work-1');const drafts = join(work, 'drafts');await mkdir(drafts, { recursive: true });- await writeFile(join(wr, 'folders.imported.json'), '[]', 'utf-8');- await writeFile(join(wr, 'exercises.imported.json'), '[]', 'utf-8');- // Manifest carries 2 drafts → decomposed into 2 writers_room_draft_versions.+ await writeJSON(join(wr, 'folders.imported.json'), [{ id: 'f1' }]);+ await writeJSON(join(wr, 'exercises.imported.json'), [{ id: 'e1' }]);await writeJSON(join(work, 'manifest.imported.json'), { id: 'work-1', drafts: [{ id: 'd1' }, { id: 'd2' }] });await writeFile(join(drafts, 'draft-1.md'), '# body', 'utf-8'); // file-primary body- // All guarded tables (incl. draft versions) meet their expected counts.- const db = stubDb({ writers_room_folders: 2, writers_room_works: 1, writers_room_exercises: 3, writers_room_draft_versions: 2 });+ const db = stubDb({+ writers_room_folders: ['f1'], writers_room_exercises: ['e1'],+ writers_room_works: ['work-1'], writers_room_draft_versions: ['d1', 'd2'],+ });const res = await pruneImportedLegacyFiles({ dataDir, db });expect(res.markerWritten).toBe(true);@@ -146,44 +170,51 @@ describe('pruneImportedLegacyFiles', () => {expect(await exists(join(drafts, 'draft-1.md'))).toBe(true);});- it('WITHHOLDS writers-room prune when draft-version rows are short of the parked manifests', async () => {- // Restore brought back folders/works/exercises but lost draft-version rows.- // The manifests are the only recovery source for that version metadata, so- // keep them even though every table-count guard passes.- await writeJSON(join(dataDir, 'writers-room.migrated.json'), { folders: 0, works: 1, exercises: 0 });+ it('WITHHOLDS writers-room prune when a folder id is missing, not just works', async () => {+ await writeJSON(join(dataDir, 'writers-room.migrated.json'), { folders: 1, works: 1, exercises: 0 });const wr = join(dataDir, 'writers-room');const work = join(wr, 'works', 'work-1');await mkdir(work, { recursive: true });- await writeJSON(join(work, 'manifest.imported.json'), { id: 'work-1', drafts: [{ id: 'd1' }, { id: 'd2' }, { id: 'd3' }] });+ await writeJSON(join(wr, 'folders.imported.json'), [{ id: 'f1' }]);+ await writeJSON(join(work, 'manifest.imported.json'), { id: 'work-1', drafts: [] });- // 3 drafts on disk, but only 1 draft-version row survived.- const db = stubDb({ writers_room_folders: 0, writers_room_works: 1, writers_room_exercises: 0, writers_room_draft_versions: 1 });+ // Works present, folder f1 lost.+ const db = stubDb({ writers_room_folders: [], writers_room_works: ['work-1'], writers_room_draft_versions: [] });const res = await pruneImportedLegacyFiles({ dataDir, db });expect(res.blocked).toBe(1);expect(res.markerWritten).toBe(false);- expect(await exists(join(work, 'manifest.imported.json'))).toBe(true);+ expect(await exists(join(wr, 'folders.imported.json'))).toBe(true);});- it('WITHHOLDS writers-room prune when ANY guarded table is short, not just works', async () => {- // Works restored fully, but folders lost on a partial restore → must NOT- // delete the folders recovery file. The single-table-on-works guard would- // have wrongly pruned here.- await writeJSON(join(dataDir, 'writers-room.migrated.json'), { folders: 2, works: 1, exercises: 0 });+ it('WITHHOLDS writers-room prune when a draft-version id is missing', async () => {+ // Restore kept folders/works/exercises but lost a draft-version row. The+ // manifest is the only recovery source for that version metadata.+ await writeJSON(join(dataDir, 'writers-room.migrated.json'), { folders: 0, works: 1, exercises: 0 });const wr = join(dataDir, 'writers-room');- await mkdir(wr, { recursive: true });- await writeFile(join(wr, 'folders.imported.json'), '[]', 'utf-8');+ const work = join(wr, 'works', 'work-1');+ await mkdir(work, { recursive: true });+ await writeJSON(join(work, 'manifest.imported.json'), { id: 'work-1', drafts: [{ id: 'd1' }, { id: 'd2' }, { id: 'd3' }] });- const db = stubDb({ writers_room_folders: 0, writers_room_works: 1, writers_room_exercises: 0 });+ const db = stubDb({ writers_room_works: ['work-1'], writers_room_draft_versions: ['d1', 'd2'] });const res = await pruneImportedLegacyFiles({ dataDir, db });expect(res.blocked).toBe(1);expect(res.markerWritten).toBe(false);- expect(await exists(join(wr, 'folders.imported.json'))).toBe(true);+ expect(await exists(join(work, 'manifest.imported.json'))).toBe(true);+ });++ it('prunes the creative-director JSON export when its project ids are present', async () => {+ await writeJSON(join(dataDir, 'creative-director-projects.migrated.json'), { imported: 1 });+ await writeJSON(join(dataDir, 'creative-director-projects.json.imported'), [{ id: 'cd-1' }]);++ const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ creative_director_projects: ['cd-1'] }) });++ expect(res.markerWritten).toBe(true);+ expect(await exists(join(dataDir, 'creative-director-projects.json.imported'))).toBe(false);});it('prunes a file-split backup only when its successor exists', async () => {- // history: successor present → backup removed.await writeFile(join(dataDir, 'history.json.bak-037'), 'x', 'utf-8');await writeFile(join(dataDir, 'history.jsonl'), '', 'utf-8');// media-collections: successor ABSENT → backup kept.@@ -197,7 +228,6 @@ describe('pruneImportedLegacyFiles', () => {});it('prunes timestamped file-split backup variants (re-run collision suffix)', async () => {- // Migration 037 appends -<timestamp> when a bare .bak-037 already exists.await writeFile(join(dataDir, 'history.json.bak-037'), 'x', 'utf-8');await writeFile(join(dataDir, 'history.json.bak-037-1717000000000'), 'x', 'utf-8');await writeFile(join(dataDir, 'history.jsonl'), '', 'utf-8');@@ -211,7 +241,7 @@ describe('pruneImportedLegacyFiles', () => {it('is marker-gated: a current marker no-ops without touching the DB', async () => {await writeJSON(join(dataDir, 'legacy-prune.applied.json'), { version: 1, completedAt: 'x', removed: 0 });let queried = false;- const db = { async query() { queried = true; return { rows: [{ n: 0 }] }; } };+ const db = { async query() { queried = true; return { rows: [] }; } };const res = await pruneImportedLegacyFiles({ dataDir, db });@@ -222,40 +252,35 @@ describe('pruneImportedLegacyFiles', () => {it('force re-runs even with a current marker', async () => {await writeJSON(join(dataDir, 'legacy-prune.applied.json'), { version: 1, completedAt: 'x', removed: 0 });await writeJSON(join(dataDir, 'creative-director-projects.migrated.json'), { imported: 1 });- await writeFile(join(dataDir, 'creative-director-projects.json.imported'), '[]', 'utf-8');+ await writeJSON(join(dataDir, 'creative-director-projects.json.imported'), [{ id: 'cd-1' }]);- const res = await pruneImportedLegacyFiles({ dataDir, force: true, db: stubDb({ creative_director_projects: 1 }) });+ const res = await pruneImportedLegacyFiles({ dataDir, force: true, db: stubDb({ creative_director_projects: ['cd-1'] }) });expect(res.skipped).toBe(false);expect(await exists(join(dataDir, 'creative-director-projects.json.imported'))).toBe(false);});it('force re-run that ends blocked drops the stale clean marker so a normal boot retries', async () => {- // Pre-existing clean marker + a domain that will block (DB short of marker).await writeJSON(join(dataDir, 'legacy-prune.applied.json'), { version: 1, completedAt: 'x', removed: 0 });- await writeJSON(join(dataDir, 'universes.migrated.json'), { imported: 13 });- await mkdir(join(dataDir, 'universes.imported'), { recursive: true });+ await writeJSON(join(dataDir, 'universes.migrated.json'), { imported: 1, runs: 0 });+ await seedUniverses(['u1']);- const res = await pruneImportedLegacyFiles({ dataDir, force: true, db: stubDb({ universes: 0 }) });+ const res = await pruneImportedLegacyFiles({ dataDir, force: true, db: stubDb({ universes: [] }) });expect(res.blocked).toBe(1);expect(res.markerWritten).toBe(false);- // Stale clean marker removed → a subsequent normal (non-force) boot will- // re-evaluate instead of short-circuiting on `skipped`.expect(await exists(join(dataDir, 'legacy-prune.applied.json'))).toBe(false);- // Recovery files untouched.expect(await exists(join(dataDir, 'universes.imported'))).toBe(true);});it('is idempotent across runs (second run finds nothing to remove)', async () => {- await writeJSON(join(dataDir, 'universes.migrated.json'), { imported: 5 });- await mkdir(join(dataDir, 'universes.imported'), { recursive: true });- const db = stubDb({ universes: 5 });+ await writeJSON(join(dataDir, 'universes.migrated.json'), { imported: 1, runs: 0 });+ await seedUniverses(['u1']);+ const db = stubDb({ universes: ['u1'] });const first = await pruneImportedLegacyFiles({ dataDir, db });expect(first.removed).toBe(1);- // Marker now current → second run skips entirely.const second = await pruneImportedLegacyFiles({ dataDir, db });expect(second.skipped).toBe(true);});