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 (claude): tighten writers-room guard, prefix-match backups, force-blocked marker

Adam Eivy151f462a6ebf
diff --git a/server/scripts/pruneImportedLegacyFiles.js b/server/scripts/pruneImportedLegacyFiles.js
index 6338483328..8caaf7de7e 100644
--- a/server/scripts/pruneImportedLegacyFiles.js
+++ b/server/scripts/pruneImportedLegacyFiles.js
@@ -52,30 +52,30 @@ 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).
+// 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).
const DB_DOMAINS = [
{
label: 'universes',
markerFile: 'universes.migrated.json',
- table: 'universes',
- expected: (m) => num(m?.imported),
+ guards: [{ 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),
+ guards: [{ 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),
+ 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.
@@ -84,33 +84,44 @@ const DB_DOMAINS = [
{
label: 'story-builder',
markerFile: 'story-builder.migrated.json',
- table: 'story_builder_sessions',
- expected: (m) => num(m?.imported),
+ guards: [{ 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),
+ // 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) },
+ ],
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),
+ guards: [{ 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.
+// 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.
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' },
+ { 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) {
@@ -147,6 +158,17 @@ async function removeNestedGlob(base, baseDir, leaf) {
return removed;
}
+// Remove every top-level entry of `base` whose name starts with `prefix` (the
+// bare `.bak-NNN` plus any `-<timestamp>` re-run collision variant).
+async function removeByPrefix(base, prefix) {
+ const entries = await readdir(base).catch(() => []);
+ let removed = 0;
+ for (const name of entries) {
+ if (name.startsWith(prefix) && await removeUnder(base, name)) removed++;
+ }
+ return removed;
+}
+
/**
* @param {object} [opts]
* @param {boolean} [opts.force] - re-run even if the marker is current (tests/admin).
@@ -170,14 +192,22 @@ export async function pruneImportedLegacyFiles({ force = false, db, dataDir } =
// 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`);
+ // 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.
+ 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`);
+ blocked = true;
+ break;
+ }
+ }
+ if (blocked) {
totals.blocked++;
continue;
}
@@ -199,8 +229,9 @@ export async function pruneImportedLegacyFiles({ force = false, db, dataDir } =
// 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++;
+ const removed = await removeByPrefix(base, item.backupPrefix);
+ if (removed > 0) {
+ totals.removed += removed;
totals.pruned.push(item.label);
}
}
@@ -215,6 +246,13 @@ export async function pruneImportedLegacyFiles({ force = false, db, dataDir } =
JSON.stringify({ version: MARKER_VERSION, completedAt: new Date().toISOString(), removed: totals.removed }, null, 2) + '\n',
'utf-8',
);
+ } else if (existing) {
+ // A forced re-run that ended blocked must not leave a STALE clean marker on
+ // disk — otherwise the next normal boot reads it, short-circuits via the
+ // `skipped` branch above, and silently never retries the blocked domain.
+ // Drop it so a normal boot re-evaluates. (Only reachable on the force path:
+ // a non-forced run with a current marker returned `skipped` before any work.)
+ await rm(join(base, MARKER_FILENAME), { force: true });
}
console.log(
diff --git a/server/scripts/pruneImportedLegacyFiles.test.js b/server/scripts/pruneImportedLegacyFiles.test.js
index 9aff2e90c0..d7d35914ae 100644
--- a/server/scripts/pruneImportedLegacyFiles.test.js
+++ b/server/scripts/pruneImportedLegacyFiles.test.js
@@ -110,7 +110,7 @@ describe('pruneImportedLegacyFiles', () => {
});
it('removes writers-room metadata artifacts but keeps .md draft bodies', async () => {
- await writeJSON(join(dataDir, 'writers-room.migrated.json'), { works: 1 });
+ await writeJSON(join(dataDir, 'writers-room.migrated.json'), { folders: 2, works: 1, exercises: 3 });
const wr = join(dataDir, 'writers-room');
const work = join(wr, 'works', 'work-1');
const drafts = join(work, 'drafts');
@@ -120,7 +120,9 @@ describe('pruneImportedLegacyFiles', () => {
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 }) });
+ // All three guarded tables meet their marker counts.
+ const db = stubDb({ writers_room_folders: 2, writers_room_works: 1, writers_room_exercises: 3 });
+ const res = await pruneImportedLegacyFiles({ dataDir, db });
expect(res.markerWritten).toBe(true);
expect(await exists(join(wr, 'folders.imported.json'))).toBe(false);
@@ -130,6 +132,23 @@ describe('pruneImportedLegacyFiles', () => {
expect(await exists(join(drafts, 'draft-1.md'))).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 });
+ const wr = join(dataDir, 'writers-room');
+ await mkdir(wr, { recursive: true });
+ await writeFile(join(wr, 'folders.imported.json'), '[]', 'utf-8');
+
+ const db = stubDb({ writers_room_folders: 0, writers_room_works: 1, writers_room_exercises: 0 });
+ 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);
+ });
+
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');
@@ -144,6 +163,18 @@ describe('pruneImportedLegacyFiles', () => {
expect(res.markerWritten).toBe(true);
});
+ 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');
+
+ await pruneImportedLegacyFiles({ dataDir, db: stubDb({}) });
+
+ expect(await exists(join(dataDir, 'history.json.bak-037'))).toBe(false);
+ expect(await exists(join(dataDir, 'history.json.bak-037-1717000000000'))).toBe(false);
+ });
+
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;
@@ -166,6 +197,23 @@ describe('pruneImportedLegacyFiles', () => {
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 });
+
+ const res = await pruneImportedLegacyFiles({ dataDir, force: true, db: stubDb({ universes: 0 }) });
+
+ 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 });