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

feat(db): prune legacy file→Postgres migration artifacts

Adam Eivy5b580d9bf9e2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 10754dba82..e20c152490 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -43,6 +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) and rode along into every rsync backup 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 is at least what the migration's `*.migrated.json` marker recorded, so a wiped or restored database keeps its recovery files and a later boot retries. Until pruned, the artifacts are excluded from rsync backups. The Writers Room `.md` draft bodies (which are file-primary by design, not migrated to the database) are explicitly preserved. The prune never runs under the `MEMORY_BACKEND=file` dev/test escape hatch.
## Fixed
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 146a605ab0..1baa8d7aea 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -98,6 +98,10 @@ The contract draws a single line:
Defaulting a new Create feature to a fresh `data/*.json` file is the anti-pattern this contract exists to stop. Monolithic JSON in hot paths (`media-jobs.json`, `video-history.json` — and `creative-director-projects.json` before #997 moved it to Postgres) causes write contention and growth risk; string-id cross-references across separate JSON stores drift with no integrity check. New relational surfaces should be `db-primary` from the start.
+### 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 the migrator's `<domain>.migrated.json` marker recorded — so a wiped/restored DB keeps its recovery files and a future boot retries. Until pruned, the artifacts are excluded from rsync backups (`DEFAULT_EXCLUDES` in `server/services/backup.js`) since the authoritative copy already ships in the pg_dump.
+
---
## PostgreSQL is required — `MEMORY_BACKEND=file` is test-only
diff --git a/scripts/migrations/077-prune-imported-legacy-files.js b/scripts/migrations/077-prune-imported-legacy-files.js
new file mode 100644
index 0000000000..4200b4005f
--- /dev/null
+++ b/scripts/migrations/077-prune-imported-legacy-files.js
@@ -0,0 +1,32 @@
+/**
+ * Registration stub for the legacy file→Postgres artifact prune.
+ *
+ * Every file→DB migrator (universes, pipeline-issues/series, story-builder,
+ * writers-room, creative-director) renames its source aside — `.imported` /
+ * `index.json.imported` / `manifest.imported.json` — and the split migrations
+ * (034–036) left `.bak-NNN` copies, kept "as a recovery source for at least one
+ * release." Nothing ever removed them, so they linger in ./data (multiple MB on
+ * a long-lived install) and ride into every rsync snapshot even though the
+ * authoritative copy is now in Postgres + the pg_dump.
+ *
+ * The actual prune reads Postgres row counts (to confirm the DB is authoritative
+ * before deleting a recovery copy), but the `scripts/migrations/` runner runs
+ * BEFORE the DB pool is up — the same reason migrations 048–053 are boot-time +
+ * stub-registered. So the prune runs at boot from
+ * `server/scripts/pruneImportedLegacyFiles.js` (after ensureSchema + every
+ * store's file→DB warm import), marker-gated in `data/legacy-prune.applied.json`,
+ * with a count-vs-marker guard that withholds deletion when the live row count
+ * is short of what the migration marker recorded (wiped / restored DB).
+ *
+ * This stub exists so the change is registered the standard way — it lands in
+ * `data/migrations.applied.json` so the migration ledger and `git log` show when
+ * the artifact prune was introduced.
+ *
+ * No-op + idempotent: nothing to do in the file runner.
+ */
+
+export default {
+ async up() {
+ console.log('🧹 legacy-prune: artifact cleanup runs at boot (pruneImportedLegacyFiles.js); nothing to do in the file runner');
+ },
+};
diff --git a/server/index.js b/server/index.js
index 393ba0c7ae..2048d443ef 100644
--- a/server/index.js
+++ b/server/index.js
@@ -899,6 +899,15 @@ ensureSelf()
// DB. Idempotent with that early warm (same setUserCatalogTypes result).
const warmTypes = await readUserTypeSlice();
setUserCatalogTypes(Array.isArray(warmTypes) ? warmTypes : []);
+ // Legacy artifact prune: runs LAST, after every file→DB warm above has
+ // imported + stamped its marker, so both the migration markers AND the
+ // authoritative DB rows exist. Removes the `.imported` / `.bak-NNN`
+ // recovery copies the migrators parked aside, but ONLY when the live row
+ // count matches the marker's recorded import (a wiped/restored DB keeps
+ // the recovery files). Marker-gated in data/legacy-prune.applied.json;
+ // never runs under the file escape hatch (gated by the dbReady block).
+ const { pruneImportedLegacyFiles } = await import('./scripts/pruneImportedLegacyFiles.js');
+ await pruneImportedLegacyFiles();
} catch (err) {
console.error(`🪄 catalog migrations failed at boot: ${err.message}`);
}
diff --git a/server/scripts/pruneImportedLegacyFiles.js b/server/scripts/pruneImportedLegacyFiles.js
new file mode 100644
index 0000000000..6338483328
--- /dev/null
+++ b/server/scripts/pruneImportedLegacyFiles.js
@@ -0,0 +1,228 @@
+/**
+ * One-time cleanup: prune the legacy file→Postgres migration artifacts that the
+ * file→DB migrators intentionally park aside instead of deleting.
+ *
+ * Every file→DB migrator (migrateUniversesToDB, migrateIssuesToDB,
+ * migrateSeriesToDB, migrateStoryBuilderToDB, migrateWritersRoomToDB,
+ * migrateCreativeDirectorToDB) renames its source aside — `…​.imported` /
+ * `index.json.imported` / `manifest.imported.json` — and the split migrations
+ * (034–036) left `…​.bak-NNN` copies, "a recovery source for at least one
+ * release." Nothing ever removed them, so on a long-lived install they linger in
+ * `./data` indefinitely (multiple MB) and ride along into every rsync snapshot
+ * even though the authoritative copy is now in Postgres + the pg_dump. This
+ * removes them once the DB is provably authoritative.
+ *
+ * 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.
+ *
+ * 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
+ * `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.
+ *
+ * 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.
+ */
+
+import { readFile, writeFile, rm, readdir, stat } from 'fs/promises';
+import { join } from 'path';
+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; `table` + `expected(marker)` form the
+// count-vs-marker guard; `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 of subdirs).
+const DB_DOMAINS = [
+ {
+ label: 'universes',
+ markerFile: 'universes.migrated.json',
+ table: 'universes',
+ expected: (m) => num(m?.imported),
+ artifacts: ['universes.imported', 'universe-builder.json.bak-034'],
+ },
+ {
+ label: 'pipeline-issues',
+ markerFile: 'pipeline-issues.migrated.json',
+ table: 'pipeline_issues',
+ expected: (m) => num(m?.imported),
+ artifacts: ['pipeline-issues.imported', 'pipeline-issues.json.bak-035'],
+ },
+ {
+ label: 'pipeline-series',
+ markerFile: 'pipeline-series.migrated.json',
+ 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.
+ nestedGlobs: [{ baseDir: 'pipeline-series', leaf: 'index.json.imported' }],
+ },
+ {
+ label: 'story-builder',
+ markerFile: 'story-builder.migrated.json',
+ table: 'story_builder_sessions',
+ expected: (m) => num(m?.imported),
+ artifacts: ['story-builder.imported'],
+ },
+ {
+ label: 'writers-room',
+ markerFile: 'writers-room.migrated.json',
+ table: 'writers_room_works',
+ // The writers-room marker records works/folders/exercises, not `imported`.
+ expected: (m) => num(m?.works),
+ artifacts: ['writers-room/folders.imported.json', 'writers-room/exercises.imported.json'],
+ nestedGlobs: [{ baseDir: 'writers-room/works', leaf: 'manifest.imported.json' }],
+ },
+ {
+ label: 'creative-director',
+ markerFile: 'creative-director-projects.migrated.json',
+ table: 'creative_director_projects',
+ expected: (m) => num(m?.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.
+const FILE_SPLIT_BACKUPS = [
+ { label: 'history', backup: 'history.json.bak-037', successor: 'history.jsonl' },
+ { label: 'media-collections', backup: '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);
+ if (!raw) return null;
+ try { return JSON.parse(raw); } catch { return null; }
+}
+
+// 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) {
+ const abs = join(base, rel);
+ const existed = await pathExists(abs);
+ if (existed) await rm(abs, { recursive: true, force: true });
+ return existed;
+}
+
+// Remove `<baseDir>/<sub>/<leaf>` for every immediate subdir of baseDir.
+async function removeNestedGlob(base, baseDir, leaf) {
+ const entries = await readdir(join(base, baseDir), { withFileTypes: true }).catch(() => []);
+ let removed = 0;
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue;
+ if (await removeUnder(base, join(baseDir, entry.name, leaf))) removed++;
+ }
+ return removed;
+}
+
+/**
+ * @param {object} [opts]
+ * @param {boolean} [opts.force] - re-run even if the marker is current (tests/admin).
+ * @param {object} [opts.db] - injectable db module ({ query }); defaults to server/lib/db.js.
+ * @param {string} [opts.dataDir] - override data dir (tests). Defaults to PATHS.data.
+ */
+export async function pruneImportedLegacyFiles({ force = false, db, dataDir } = {}) {
+ const base = dataDir ?? PATHS.data;
+
+ const existing = await readJsonMarker(base, MARKER_FILENAME);
+ if (existing?.version === MARKER_VERSION && !force) {
+ return { skipped: true, marker: existing };
+ }
+
+ const { query } = db ?? await import('../lib/db.js');
+ 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.
+ if (!marker) continue;
+
+ const expected = domain.expected(marker);
+ const { rows } = await query(`SELECT COUNT(*)::int AS n FROM ${domain.table}`);
+ const count = num(rows?.[0]?.n);
+ // Count-vs-marker guard: a short count 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.
+ if (count < expected) {
+ console.warn(`🧹 legacy-prune: ${domain.label} blocked — ${domain.table} has ${count} row(s) but marker recorded ${expected}; keeping recovery files`);
+ totals.blocked++;
+ continue;
+ }
+
+ let domainRemoved = 0;
+ for (const rel of domain.artifacts) {
+ if (await removeUnder(base, rel)) domainRemoved++;
+ }
+ for (const glob of (domain.nestedGlobs ?? [])) {
+ domainRemoved += await removeNestedGlob(base, glob.baseDir, glob.leaf);
+ }
+ if (domainRemoved > 0) {
+ totals.removed += domainRemoved;
+ totals.pruned.push(`${domain.label}(${domainRemoved})`);
+ }
+ }
+
+ // File-split backups: prune only when the reshaped successor is present on
+ // disk (proof the split landed). Absent successor → leave the backup alone.
+ for (const item of FILE_SPLIT_BACKUPS) {
+ if (!await pathExists(join(base, item.successor))) continue;
+ if (await removeUnder(base, item.backup)) {
+ totals.removed++;
+ totals.pruned.push(item.label);
+ }
+ }
+
+ // Only stamp the completion marker on a clean pass with NO blocked domain —
+ // a block means a future boot should retry (same logic as repairUniverseTags
+ // withholding its marker on an incomplete pass).
+ const markerWritten = totals.blocked === 0;
+ if (markerWritten) {
+ await writeFile(
+ join(base, MARKER_FILENAME),
+ JSON.stringify({ version: MARKER_VERSION, completedAt: new Date().toISOString(), removed: totals.removed }, null, 2) + '\n',
+ 'utf-8',
+ );
+ }
+
+ console.log(
+ `🧹 legacy-prune: removed ${totals.removed} artifact(s)` +
+ (totals.pruned.length ? ` [${totals.pruned.join(', ')}]` : '') +
+ (totals.blocked ? `, ${totals.blocked} domain(s) blocked` : '') +
+ (markerWritten ? '' : ' — marker NOT written (will retry next boot)'),
+ );
+
+ return { skipped: false, markerWritten, ...totals };
+}
diff --git a/server/scripts/pruneImportedLegacyFiles.test.js b/server/scripts/pruneImportedLegacyFiles.test.js
new file mode 100644
index 0000000000..4175e5c642
--- /dev/null
+++ b/server/scripts/pruneImportedLegacyFiles.test.js
@@ -0,0 +1,181 @@
+/**
+ * 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),
+ * 4. removes the per-record nested artifacts but leaves live siblings + bodies,
+ * 5. file-split backups gate on the successor existing,
+ * 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.
+ */
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtemp, rm, mkdir, writeFile, stat, readFile } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { pruneImportedLegacyFiles } from './pruneImportedLegacyFiles.js';
+
+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) {
+ return {
+ async query(text) {
+ const m = text.match(/FROM (\w+)/);
+ const table = m?.[1];
+ return { rows: [{ n: counts[table] ?? 0 }] };
+ },
+ };
+}
+
+beforeEach(async () => {
+ dataDir = await mkdtemp(join(tmpdir(), 'legacy-prune-'));
+});
+afterEach(async () => {
+ await rm(dataDir, { recursive: true, force: true });
+});
+
+describe('pruneImportedLegacyFiles', () => {
+ it('prunes a domain whose row count matches the marker', async () => {
+ await writeJSON(join(dataDir, 'universes.migrated.json'), { imported: 13 });
+ await mkdir(join(dataDir, 'universes.imported'), { recursive: true });
+ await writeFile(join(dataDir, 'universe-builder.json.bak-034'), 'legacy', 'utf-8');
+
+ const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ universes: 13 }) });
+
+ expect(res.skipped).toBe(false);
+ expect(await exists(join(dataDir, 'universes.imported'))).toBe(false);
+ expect(await exists(join(dataDir, 'universe-builder.json.bak-034'))).toBe(false);
+ expect(res.markerWritten).toBe(true);
+ 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 });
+ await mkdir(join(dataDir, 'universes.imported'), { recursive: true });
+
+ const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ universes: 0 }) });
+
+ 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('prunes the genuinely-empty case (imported:0, 0 rows)', 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 }) });
+
+ 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);
+ expect(res.markerWritten).toBe(true);
+ });
+
+ 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');
+ 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, 'manuscript-review.json'), '{}', 'utf-8'); // live sibling
+ await writeFile(join(seriesB, 'index.json.imported'), '{}', 'utf-8');
+
+ const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ pipeline_series: 2 }) });
+
+ expect(res.markerWritten).toBe(true);
+ expect(await exists(join(seriesA, 'index.json.imported'))).toBe(false);
+ expect(await exists(join(seriesB, 'index.json.imported'))).toBe(false);
+ // Live record + sibling untouched.
+ expect(await exists(join(seriesA, 'index.json'))).toBe(true);
+ expect(await exists(join(seriesA, 'manuscript-review.json'))).toBe(true);
+ });
+
+ it('removes writers-room metadata artifacts but keeps .md draft bodies', async () => {
+ await writeJSON(join(dataDir, 'writers-room.migrated.json'), { works: 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');
+ await writeFile(join(work, 'manifest.imported.json'), '{}', 'utf-8');
+ await writeFile(join(drafts, 'draft-1.md'), '# body', 'utf-8'); // file-primary body
+
+ const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ writers_room_works: 1 }) });
+
+ expect(res.markerWritten).toBe(true);
+ expect(await exists(join(wr, 'folders.imported.json'))).toBe(false);
+ expect(await exists(join(wr, 'exercises.imported.json'))).toBe(false);
+ expect(await exists(join(work, 'manifest.imported.json'))).toBe(false);
+ // The prose body MUST survive (it's file-primary, not migrated to DB).
+ expect(await exists(join(drafts, 'draft-1.md'))).toBe(true);
+ });
+
+ 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.
+ await writeFile(join(dataDir, 'media-collections.json.bak-059'), 'x', 'utf-8');
+
+ const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({}) });
+
+ expect(await exists(join(dataDir, 'history.json.bak-037'))).toBe(false);
+ expect(await exists(join(dataDir, 'media-collections.json.bak-059'))).toBe(true);
+ expect(res.markerWritten).toBe(true);
+ });
+
+ 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 res = await pruneImportedLegacyFiles({ dataDir, db });
+
+ expect(res.skipped).toBe(true);
+ expect(queried).toBe(false);
+ });
+
+ 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');
+
+ const res = await pruneImportedLegacyFiles({ dataDir, force: true, db: stubDb({ creative_director_projects: 1 }) });
+
+ expect(res.skipped).toBe(false);
+ expect(await exists(join(dataDir, 'creative-director-projects.json.imported'))).toBe(false);
+ });
+
+ 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 });
+
+ 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);
+ });
+});
diff --git a/server/services/backup.js b/server/services/backup.js
index f06719dc23..b569771534 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -45,7 +45,23 @@ export const DEFAULT_EXCLUDES = [
{ path: '/loras/*.safetensors', reason: 'LoRA adapter weight files — large, re-downloadable. .metadata.json sidecars (Civitai metadata, user-editable name/notes) ARE backed up.', overridable: true },
{ path: '/repos/', reason: 'Cloned git repositories — large, re-cloneable from origin', overridable: true },
{ path: '/cos/reference-repos/', reason: 'Reference upstream repos used by agents — re-cloneable', overridable: true },
- { path: '/browser-downloads/', reason: 'Browser downloads cache — large, re-downloadable', overridable: true }
+ { path: '/browser-downloads/', reason: 'Browser downloads cache — large, re-downloadable', overridable: true },
+ // Legacy file→Postgres migration artifacts. Each migrator parks its source
+ // aside (`.imported` / `.bak-NNN`) as a one-release recovery copy rather than
+ // deleting it; the boot-time prune in pruneImportedLegacyFiles.js removes them
+ // once the DB row is authoritative. These excludes stop rsync from copying the
+ // now-redundant data to the backup target in the meantime (the authoritative
+ // copy ships in the pg_dump). Non-overridable: this is migrated state Postgres
+ // already owns, never irreplaceable user data. All anchored per the rule above;
+ // the two nested patterns target the only sub-dir artifacts (pipeline-series
+ // per-record index, writers-room per-work manifest) without catching the live
+ // `.md` bodies that must stay backed up.
+ { path: '/*.imported', reason: 'Legacy file→DB migration sources (universes/pipeline-issues/story-builder dirs, creative-director-projects.json) — data now in Postgres', overridable: false },
+ { path: '/*.migrated.json', reason: 'Per-domain file→DB migration markers — runtime state, redundant in a snapshot', overridable: false },
+ { path: '/*.bak-*', reason: 'Split-migration backups (.bak-034…059) — superseded by per-record stores / Postgres', overridable: false },
+ { path: '/pipeline-series/*/index.json.imported', reason: 'Per-series legacy index parked by the series→DB migration — data now in Postgres', overridable: false },
+ { path: '/writers-room/*.imported.json', reason: 'Writers Room folders/exercises metadata parked by the writers-room→DB migration — data now in Postgres', overridable: false },
+ { path: '/writers-room/works/*/manifest.imported.json', reason: 'Per-work manifest parked by the writers-room→DB migration — data now in Postgres (the .md bodies stay backed up)', overridable: false }
];
// Snapshots live under snapshots/<hostname>/<snapshotId> so a single shared
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index d070249e03..247de5face 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -153,6 +153,36 @@ describe('computeEffectiveExcludes', () => {
const result = computeEffectiveExcludes();
expect(result).toEqual(DEFAULT_EXCLUDES.map(e => e.path));
});
+
+ it('excludes legacy file→DB migration artifacts as non-overridable', () => {
+ // These are migrated state Postgres already owns — never irreplaceable user
+ // data — so they must always be excluded (can't be re-enabled from the UI)
+ // and they ride along with the dynamic includes-everything assertion above.
+ const legacy = [
+ '/*.imported',
+ '/*.migrated.json',
+ '/*.bak-*',
+ '/pipeline-series/*/index.json.imported',
+ '/writers-room/*.imported.json',
+ '/writers-room/works/*/manifest.imported.json',
+ ];
+ for (const path of legacy) {
+ const entry = DEFAULT_EXCLUDES.find(e => e.path === path);
+ expect(entry, `expected DEFAULT_EXCLUDES to contain ${path}`).toBeDefined();
+ expect(entry.overridable, `${path} must be non-overridable`).toBe(false);
+ // Even when a hand-edited settings.json tries to disable it, it stays.
+ const result = computeEffectiveExcludes({ excludePaths: [], disabledDefaultExcludes: [path] });
+ expect(result).toContain(path);
+ }
+ });
+
+ it('keeps the writers-room .md draft bodies backed up (not caught by the artifact excludes)', () => {
+ // Regression guard: the writers-room artifact patterns target `*.imported.json`
+ // metadata only — a draft body path must NOT match any default exclude.
+ const draftBody = '/writers-room/works/work-123/drafts/draft-1.md';
+ const result = computeEffectiveExcludes({ excludePaths: [], disabledDefaultExcludes: [] });
+ expect(result).not.toContain(draftBody);
+ });
});
describe('dumpPostgres status classification', () => {