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): verify parsed index.json id, not folder name

Adam Eivy4268af052994
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index d9f25984db..41381a5fd9 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`) 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 the **`.imported`** 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). Anything that can't be verified withholds the whole domain's prune: a missing id, a present-but-unparseable artifact, an id-less record, or a domain whose migration is still pending (legacy source on disk, no marker). The prune deliberately does **not** touch the deeper `*.bak-NNN` monolith backups (the file→file split migrations 034–036) or the file-split backups (037 history, 059 media-collections): those predate the DB, can hold records the split migrator *skipped*, and carry soft-deleted records the live DB legitimately lacks, so they're neither identity-verifiable nor safe to auto-delete — they're left for manual cleanup. None of these artifacts are 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`) 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 the **`.imported`** 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 **parsed `index.json.id`** of each per-record directory (the same id the migrator inserted, which can differ from the folder name), or the parsed JSON `.id` of the creative-director export, each writers-room manifest/folder/exercise, the universe `config.runs[]`, and 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). Anything that can't be verified withholds the whole domain's prune: a missing id, a present-but-unparseable artifact, an id-less record, or a domain whose migration is still pending (legacy source on disk, no marker). The prune deliberately does **not** touch the deeper `*.bak-NNN` monolith backups (the file→file split migrations 034–036) or the file-split backups (037 history, 059 media-collections): those predate the DB, can hold records the split migrator *skipped*, and carry soft-deleted records the live DB legitimately lacks, so they're neither identity-verifiable nor safe to auto-delete — they're left for manual cleanup. None of these artifacts are 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 ee131a638e..408b3d6dd7 100644
--- a/server/scripts/pruneImportedLegacyFiles.js
+++ b/server/scripts/pruneImportedLegacyFiles.js
@@ -110,14 +110,29 @@ async function readParkedJson(base, file) {
// --- 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) {
+// Record ids for a per-record-directory layout. The migrators key the DB row on
+// the PARSED `index.json.id`, NOT the directory name (the two normally match but
+// can drift), so we must verify the same id the migrator inserted. Reads each
+// subdir's `<leaf>` and blocks (throws) on a missing/unparseable/id-less record
+// — an unverifiable record must not let the prune delete its recovery copy.
+// `leaf` defaults to the live record file; pass `index.json.imported` for the
+// in-place rename layout (pipeline-series) and a missing leaf is skipped there.
+async function idsFromRecordDirs(base, dir, { leaf = 'index.json', requireLeaf = false } = {}) {
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);
+ const ids = [];
+ for (const entry of entries) {
+ if (!entry.isDirectory() || entry.name === 'index.json' || entry.name.startsWith('.')) continue;
+ const rel = join(dir, entry.name, leaf);
+ if (requireLeaf && !await pathExists(join(base, rel))) continue; // unrelated sibling dir
+ const record = await readParkedJson(base, rel);
+ if (record === null) {
+ if (requireLeaf) continue; // leaf vanished between listing and read — skip
+ throw new ParkedArtifactUnreadable(`${rel}: missing or unreadable record`);
+ }
+ if (typeof record.id !== 'string') throw new ParkedArtifactUnreadable(`${rel}: record has no string id`);
+ ids.push(record.id);
+ }
+ return ids;
}
// Map array elements to their string `.id`, BLOCKING (throw) on any element
@@ -223,7 +238,7 @@ const DB_DOMAINS = [
// 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: 'universes', ids: await idsFromRecordDirs(base, 'universes.imported') },
{ table: 'universe_runs', ids: await universeRunIds(base) },
],
pending: (base) => pathExists(join(base, 'universes')),
@@ -233,7 +248,7 @@ const DB_DOMAINS = [
label: 'pipeline-issues',
markerFile: 'pipeline-issues.migrated.json',
verify: async (base) => [
- { table: 'pipeline_issues', ids: await idsFromSubdirs(base, 'pipeline-issues.imported') },
+ { table: 'pipeline_issues', ids: await idsFromRecordDirs(base, 'pipeline-issues.imported') },
],
pending: (base) => pathExists(join(base, 'pipeline-issues')),
artifacts: ['pipeline-issues.imported'],
@@ -245,7 +260,7 @@ const DB_DOMAINS = [
// 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') },
+ { table: 'pipeline_series', ids: await idsFromRecordDirs(base, 'pipeline-series', { leaf: 'index.json.imported', requireLeaf: true }) },
],
pending: pipelineSeriesPending,
artifacts: [],
@@ -255,7 +270,7 @@ const DB_DOMAINS = [
label: 'story-builder',
markerFile: 'story-builder.migrated.json',
verify: async (base) => [
- { table: 'story_builder_sessions', ids: await idsFromSubdirs(base, 'story-builder.imported') },
+ { table: 'story_builder_sessions', ids: await idsFromRecordDirs(base, 'story-builder.imported') },
],
pending: (base) => pathExists(join(base, 'story-builder')),
artifacts: ['story-builder.imported'],
@@ -299,19 +314,6 @@ async function readJson(base, file) {
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) {
diff --git a/server/scripts/pruneImportedLegacyFiles.test.js b/server/scripts/pruneImportedLegacyFiles.test.js
index 9acfb2f316..0f2dd4fb67 100644
--- a/server/scripts/pruneImportedLegacyFiles.test.js
+++ b/server/scripts/pruneImportedLegacyFiles.test.js
@@ -45,12 +45,17 @@ 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.
+// Build a universes.imported tree: one subdir per universe id, each holding an
+// index.json whose `.id` IS the record id the migrator inserted (the verifier
+// reads the parsed id, not the folder name), plus 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 });
+ for (const id of ids) {
+ await mkdir(join(dir, id), { recursive: true });
+ await writeJSON(join(dir, id, 'index.json'), { id, name: `Universe ${id}` });
+ }
await writeJSON(join(dir, 'index.json'), { config: { runs: runIds.map((id) => ({ id, universeId: ids[0] })) } });
}
@@ -75,6 +80,7 @@ describe('pruneImportedLegacyFiles', () => {
await writeJSON(join(dataDir, 'pipeline-issues.migrated.json'), { imported: 1 });
const imp = join(dataDir, 'pipeline-issues.imported');
await mkdir(join(imp, 'iss-1'), { recursive: true });
+ await writeJSON(join(imp, 'iss-1', 'index.json'), { id: 'iss-1' });
await writeFile(join(dataDir, 'pipeline-issues.json.bak-035'), 'monolith', 'utf-8');
await writeFile(join(dataDir, 'history.json.bak-037'), 'x', 'utf-8');
await writeFile(join(dataDir, 'history.jsonl'), '', 'utf-8');
@@ -115,6 +121,39 @@ describe('pruneImportedLegacyFiles', () => {
expect(await exists(join(dataDir, 'universes.imported'))).toBe(true);
});
+ it('verifies the parsed index.json id, not the folder name, when they drift', async () => {
+ // The migrator inserts record.id from the JSON; the folder name can differ.
+ // A DB that has the folder name but NOT the real id must block.
+ await writeJSON(join(dataDir, 'universes.migrated.json'), { imported: 1, runs: 0 });
+ const dir = join(dataDir, 'universes.imported');
+ await mkdir(join(dir, 'folder-name'), { recursive: true });
+ await writeJSON(join(dir, 'folder-name', 'index.json'), { id: 'real-id' });
+ await writeJSON(join(dir, 'index.json'), { config: { runs: [] } });
+
+ // DB only has the folder name, not the real record id → block.
+ const blocked = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ universes: ['folder-name'] }) });
+ expect(blocked.blocked).toBe(1);
+ expect(await exists(dir)).toBe(true);
+
+ // DB has the real id → prunes.
+ const ok = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ universes: ['real-id'] }) });
+ expect(ok.markerWritten).toBe(true);
+ expect(await exists(dir)).toBe(false);
+ });
+
+ it('BLOCKS a record directory whose index.json has no string id', async () => {
+ await writeJSON(join(dataDir, 'universes.migrated.json'), { imported: 1, runs: 0 });
+ const dir = join(dataDir, 'universes.imported');
+ await mkdir(join(dir, 'u1'), { recursive: true });
+ await writeJSON(join(dir, 'u1', 'index.json'), { name: 'no id here' });
+ await writeJSON(join(dir, 'index.json'), { config: { runs: [] } });
+
+ const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ universes: ['u1'] }) });
+
+ expect(res.blocked).toBe(1);
+ expect(await exists(dir)).toBe(true);
+ });
+
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.
@@ -150,10 +189,10 @@ describe('pruneImportedLegacyFiles', () => {
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 writeJSON(join(seriesA, 'index.json.imported'), { id: 'ser-a' });
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');
+ await writeJSON(join(seriesB, 'index.json.imported'), { id: 'ser-b' });
const res = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ pipeline_series: ['ser-a', 'ser-b'] }) });