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

address review (codex): cover all migrated tables in prune guard; drop backup excludes

Adam Eivyaf73038b279c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index e20c152490..f9e765654b 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) 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.
+- **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.
## Fixed
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 1baa8d7aea..179219b452 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 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.
+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.
---
diff --git a/server/scripts/pruneImportedLegacyFiles.js b/server/scripts/pruneImportedLegacyFiles.js
index 8caaf7de7e..bbc83fa8f7 100644
--- a/server/scripts/pruneImportedLegacyFiles.js
+++ b/server/scripts/pruneImportedLegacyFiles.js
@@ -8,9 +8,11 @@
* `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.
+ * `./data` indefinitely (multiple MB). This removes them once the DB is provably
+ * authoritative. (They are deliberately NOT excluded from rsync backups: while a
+ * prune is blocked they are the only recovery source, so a snapshot must keep
+ * 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
@@ -63,7 +65,14 @@ const DB_DOMAINS = [
{
label: 'universes',
markerFile: 'universes.migrated.json',
- guards: [{ table: 'universes', expected: (m) => num(m?.imported) }],
+ // 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) },
+ ],
artifacts: ['universes.imported', 'universe-builder.json.bak-034'],
},
{
@@ -103,6 +112,17 @@ const DB_DOMAINS = [
{ 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' },
+ },
artifacts: ['writers-room/folders.imported.json', 'writers-room/exercises.imported.json'],
nestedGlobs: [{ baseDir: 'writers-room/works', leaf: 'manifest.imported.json' }],
},
@@ -169,6 +189,21 @@ 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).
@@ -207,6 +242,19 @@ export async function pruneImportedLegacyFiles({ force = false, db, dataDir } =
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.js
index d7d35914ae..5809829e7e 100644
--- a/server/scripts/pruneImportedLegacyFiles.test.js
+++ b/server/scripts/pruneImportedLegacyFiles.test.js
@@ -43,11 +43,11 @@ afterEach(async () => {
describe('pruneImportedLegacyFiles', () => {
it('prunes a domain whose row count matches the marker', async () => {
- await writeJSON(join(dataDir, 'universes.migrated.json'), { imported: 13 });
+ await writeJSON(join(dataDir, 'universes.migrated.json'), { imported: 13, runs: 2 });
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 }) });
+ const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ universes: 13, universe_runs: 2 }) });
expect(res.skipped).toBe(false);
expect(await exists(join(dataDir, 'universes.imported'))).toBe(false);
@@ -57,10 +57,10 @@ describe('pruneImportedLegacyFiles', () => {
});
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 writeJSON(join(dataDir, 'universes.migrated.json'), { imported: 13, runs: 2 });
await mkdir(join(dataDir, 'universes.imported'), { recursive: true });
- const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ universes: 0 }) });
+ const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ universes: 0, universe_runs: 0 }) });
expect(res.blocked).toBe(1);
expect(res.markerWritten).toBe(false);
@@ -70,6 +70,19 @@ describe('pruneImportedLegacyFiles', () => {
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 });
+
+ const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ universes: 13, universe_runs: 0 }) });
+
+ 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 () => {
await writeJSON(join(dataDir, 'story-builder.migrated.json'), { imported: 0 });
await mkdir(join(dataDir, 'story-builder.imported'), { recursive: true });
@@ -117,11 +130,12 @@ describe('pruneImportedLegacyFiles', () => {
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');
+ // Manifest carries 2 drafts → decomposed into 2 writers_room_draft_versions.
+ 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 three guarded tables meet their marker counts.
- const db = stubDb({ writers_room_folders: 2, writers_room_works: 1, writers_room_exercises: 3 });
+ // 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 res = await pruneImportedLegacyFiles({ dataDir, db });
expect(res.markerWritten).toBe(true);
@@ -132,6 +146,25 @@ 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 });
+ 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' }] });
+
+ // 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 });
+ 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);
+ });
+
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
diff --git a/server/services/backup.js b/server/services/backup.js
index b569771534..6a6c063efd 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -45,23 +45,17 @@ 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 },
- // 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 }
+ { path: '/browser-downloads/', reason: 'Browser downloads cache — large, re-downloadable', overridable: true }
+ // NOTE: legacy file→Postgres migration artifacts (`.imported` / `.bak-NNN`)
+ // are intentionally NOT excluded here. They are deleted on disk by the
+ // boot-time prune (pruneImportedLegacyFiles.js) the same boot the migration
+ // runs — but ONLY once the DB is provably authoritative. While the prune is
+ // *blocked* (a wiped/partial-restore DB short of the migration markers) those
+ // parked files are the only recovery source, and `pg_dump` is capturing the
+ // incomplete DB — so excluding them from snapshots would mean a backup taken
+ // in that window restores neither the missing rows nor the source to rebuild
+ // them. Letting rsync copy them is the safe default; once the prune removes
+ // them from disk they leave subsequent snapshots naturally.
];
// 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 247de5face..819db5d97c 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -154,35 +154,17 @@ describe('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('does NOT exclude legacy file→DB migration artifacts (they are the recovery source while a prune is blocked)', () => {
+ // The boot-time prune deletes these on disk once the DB is authoritative;
+ // excluding them from snapshots would strip the only recovery source during
+ // a blocked (wiped/partial-restore) prune, while pg_dump captures the
+ // incomplete DB. So none of these patterns may appear in the default set.
+ const mustNotExclude = ['/*.imported', '/*.bak-034', '/*.migrated.json', '/writers-room/works/*/manifest.imported.json'];
+ const paths = DEFAULT_EXCLUDES.map(e => e.path);
+ for (const p of mustNotExclude) {
+ expect(paths, `${p} must NOT be a default exclude`).not.toContain(p);
}
});
-
- 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', () => {