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

fix: keep incomplete legacy imports retryable after repair (#6950)

[._.]/ Adam Eivy618952d71ca4
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index f7a392d3ee..884e9e0581 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -394,3 +394,49 @@ also exposes a numeric-only projection through `GET /api/apps/quality-federation
(`days=30|90|365`), gated on an identified, registered, enabled full-sync peer
with outbound sharing allowed. The ordinary app list and capability/status
payloads still carry no assessment data. See [quality federation](decisions/2026-09-10-portos-quality-federation.md).
+
+### Retrying incomplete legacy creative imports
+
+The Series, Pipeline Issues, Story Builder, Universe and Writers Room file-to-DB
+importers withhold their domain completion marker while a source is malformed,
+unreadable, invalid, or cannot be parked. Healthy rows remain available in
+PostgreSQL. Repair the affected canonical JSON from a backup, resolve filesystem
+errors, then restart: the next import retries without replacing existing DB rows.
+Whole-directory imports keep their canonical directory until verification
+completes. Writers Room prose and Series manuscript-review siblings stay in place.
+A pre-existing recovery copy is preserved; if it prevents parking a repaired
+canonical file, archive that older copy separately before retrying.
+
+An older release may already have stamped a premature marker. Do **not** clear
+all migration markers or move entire historical directories back into service:
+that can resurrect records intentionally deleted since migration. Instead, run
+this explicit recovery command from the install checkout with its normal database
+connection configuration (after database setup has completed):
+
+```bash
+# Read-only inventory of canonical and parked recovery sources and DB presence.
+node server/scripts/recoverLegacyImports.js
+
+# Preview only the IDs you intend to restore.
+node server/scripts/recoverLegacyImports.js --id series:ser-example --id issue:iss-example
+
+# Apply that exact selection after checking the preview.
+node server/scripts/recoverLegacyImports.js --id series:ser-example --id issue:iss-example --apply
+```
+
+No arguments means **dry-run**. The command reports `missing`, `exists`,
+`invalid-source`, `invalid-record`, or `not-found`; application reports `inserted`
+for newly restored rows. It inspects both canonical sources and `.imported`
+recovery copies, preferring a valid canonical record when the same ID appears in
+both. Fix invalid sources before applying a selection. It never changes source
+files or migration markers, and every insert retains `ON CONFLICT DO NOTHING` so
+existing rows, including soft-deleted rows and newer edits, remain authoritative.
+
+Selection kinds are `series`, `issue`, `story`, `universe`, `run`, `work`, `draft`,
+`folder`, and `exercise`, each followed by `:` and the original record ID.
+Selection is per database row: selecting a Writers Room work does **not** select
+its historical drafts; include each wanted `draft:<id>` explicitly. Likewise,
+select required parent records (for example a series for an issue) separately.
+Recovery is never run automatically at boot. Keep a backup while verifying the
+restored records in the UI; this command cannot recover artifacts already pruned
+from disk, so those must first be restored from a backup.
diff --git a/server/scripts/legacyImport.js b/server/scripts/legacyImport.js
new file mode 100644
index 0000000000..699147821b
--- /dev/null
+++ b/server/scripts/legacyImport.js
@@ -0,0 +1,34 @@
+// Shared filesystem boundaries for the legacy creative importers. Only ENOENT
+// means absence; a present source that cannot be verified keeps import pending.
+import { readFile, stat, rename } from 'fs/promises';
+
+const absent = error => {
+ if (error.code === 'ENOENT') return null;
+ throw error;
+};
+
+export async function legacyDirectory(path) {
+ const entry = await stat(path).catch(absent);
+ if (entry && !entry.isDirectory()) throw new Error('Legacy import source is not a directory');
+ return entry;
+}
+
+export async function readLegacyJSON(path) {
+ const raw = await readFile(path, 'utf8').then(value => ({ value }), error => ({ error }));
+ if (raw.error) return { status: raw.error.code === 'ENOENT' ? 'missing' : 'invalid' };
+ return Promise.resolve().then(() => JSON.parse(raw.value)).then(
+ value => value && typeof value === 'object' ? { status: 'valid', value } : { status: 'invalid' },
+ () => ({ status: 'invalid' }),
+ );
+}
+
+export async function parkLegacyFile(path, aside) {
+ // Preserve an older recovery copy; do not replace it with a different source.
+ if (await stat(aside).catch(absent)) return false;
+ return rename(path, aside).then(() => true, () => false);
+}
+
+export function incompleteImport(domain, counts, incomplete) {
+ console.warn(`⚠️ ${domain}→DB import incomplete: ${incomplete} source(s) could not be verified or parked; retained for retry`);
+ return { ok: true, reason: 'incomplete', ...counts, incomplete };
+}
diff --git a/server/scripts/legacyImportRetry.test.js b/server/scripts/legacyImportRetry.test.js
new file mode 100644
index 0000000000..d3842d8b3d
--- /dev/null
+++ b/server/scripts/legacyImportRetry.test.js
@@ -0,0 +1,147 @@
+// Regression: partial imports must survive repair/retry without replacing newer
+// DB rows. Real temporary filesystem, DB double only; never a live database.
+import { beforeEach, afterEach, expect, it, vi } from 'vitest';
+import { mkdtemp, mkdir, readFile, writeFile, rm, stat } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join, dirname } from 'path';
+
+let dataDir;
+const tables = new Map();
+vi.mock('../lib/fileUtils.js', () => ({ PATHS: { get data() { return dataDir; } } }));
+vi.mock('../lib/migrationMarker.js', () => ({
+ markerExists: async name => stat(join(dataDir, name)).then(() => true, () => false),
+ writeMarker: async (name, body) => writeFile(join(dataDir, name), JSON.stringify(body)),
+}));
+const db = vi.fn(async (sql, params) => {
+ const table = /(?:INSERT INTO|FROM) (\w+)/.exec(sql)?.[1];
+ if (!table) throw new Error('Unexpected test query');
+ if (!tables.has(table)) tables.set(table, new Map());
+ const rows = tables.get(table);
+ if (sql.startsWith('SELECT')) return { rows: rows.has(params[0]) ? [{ id: params[0] }] : [] };
+ expect(sql).toContain('ON CONFLICT (id) DO NOTHING');
+ if (rows.has(params[0])) return { rowCount: 0 };
+ rows.set(params[0], params);
+ return { rowCount: 1 };
+});
+vi.mock('../lib/db.js', () => ({ query: (...args) => db(...args), close: vi.fn() }));
+
+import { migrateSeriesToDB } from './migrateSeriesToDB.js';
+import { migrateIssuesToDB } from './migrateIssuesToDB.js';
+import { migrateStoryBuilderToDB } from './migrateStoryBuilderToDB.js';
+import { migrateUniversesToDB } from './migrateUniversesToDB.js';
+import { migrateWritersRoomToDB } from './migrateWritersRoomToDB.js';
+import { recoverLegacyImports, parseRecoveryArgs } from './recoverLegacyImports.js';
+
+const exists = path => stat(join(dataDir, path)).then(() => true, () => false);
+async function put(path, body) {
+ await mkdir(dirname(join(dataDir, path)), { recursive: true });
+ await writeFile(join(dataDir, path), typeof body === 'string' ? body : JSON.stringify(body));
+}
+beforeEach(async () => { dataDir = await mkdtemp(join(tmpdir(), 'legacy-retry-')); tables.clear(); db.mockClear(); });
+afterEach(async () => { await rm(dataDir, { recursive: true, force: true }); });
+
+it.each([
+ ['pipeline-series', 'ser', 'pipeline_series', migrateSeriesToDB],
+ ['pipeline-issues', 'iss', 'pipeline_issues', migrateIssuesToDB],
+ ['story-builder', 'stb', 'story_builder_sessions', migrateStoryBuilderToDB],
+ ['universes', 'uni', 'universes', migrateUniversesToDB],
+])('%s imports healthy rows, retains damaged sources, then repairs without overwriting DB edits', async (domain, prefix, table, migrate) => {
+ const good = `${prefix}-good`, bad = `${prefix}-bad`;
+ await put(`${domain}/${good}/index.json`, { id: good, seriesId: 'ser-parent' });
+ await put(`${domain}/${bad}/index.json`, '{');
+ const first = await migrate();
+ expect(first).toMatchObject({ reason: 'incomplete', imported: 1 });
+ expect(await exists(`${domain}.migrated.json`)).toBe(false);
+ expect(await exists(`${domain}/${bad}/index.json`)).toBe(true);
+ expect(await exists(`${domain}.imported`)).toBe(false);
+ tables.get(table).set(good, 'newer database edit');
+ await put(`${domain}/${bad}/index.json`, { id: bad, seriesId: 'ser-parent' });
+ expect(await migrate()).toMatchObject({ reason: 'imported', imported: 1 });
+ expect(tables.get(table).get(good)).toBe('newer database edit');
+ expect(tables.get(table).has(bad)).toBe(true);
+ expect(await exists(`${domain}.migrated.json`)).toBe(true);
+});
+
+it.each(['folders', 'exercises', 'manifest', 'draft'])('Writers Room keeps invalid %s retryable and preserves prose', async invalid => {
+ const path = invalid === 'folders' || invalid === 'exercises'
+ ? `writers-room/${invalid}.json` : 'writers-room/works/wr-work-bbb/manifest.json';
+ const repaired = invalid === 'folders' || invalid === 'exercises'
+ ? [{ id: `wr-${invalid}-bbb` }] : { id: 'wr-work-bbb', drafts: [{ id: 'wr-draft-bbb' }] };
+ await put(path, invalid === 'draft' ? { id: 'wr-work-bbb', drafts: [{}] } : '{');
+ await put('writers-room/works/wr-work-aaa/manifest.json', { id: 'wr-work-aaa' });
+ await put('writers-room/works/wr-work-aaa/drafts/wr-draft-aaa.md', 'Original prose');
+ expect(await migrateWritersRoomToDB()).toMatchObject({ reason: 'incomplete', works: 1 });
+ expect(await exists('writers-room.migrated.json')).toBe(false);
+ expect(await exists(path)).toBe(true);
+ tables.get('writers_room_works').set('wr-work-aaa', 'newer edit');
+ await put(path, repaired);
+ expect(await migrateWritersRoomToDB()).toMatchObject({ reason: 'imported' });
+ expect(tables.get('writers_room_works').get('wr-work-aaa')).toBe('newer edit');
+ expect(await readFile(join(dataDir, 'writers-room/works/wr-work-aaa/drafts/wr-draft-aaa.md'), 'utf8')).toBe('Original prose');
+});
+
+it('retains canonical metadata when a recovery copy prevents parking', async () => {
+ await put('pipeline-series/ser-a/index.json', { id: 'ser-a' });
+ await put('pipeline-series/ser-a/index.json.imported', { id: 'ser-a', name: 'old recovery' });
+ await put('pipeline-series/ser-a/manuscript-review.json', { review: 'file primary' });
+ expect(await migrateSeriesToDB()).toMatchObject({ reason: 'incomplete' });
+ expect(await exists('pipeline-series.migrated.json')).toBe(false);
+ expect(await exists('pipeline-series/ser-a/index.json')).toBe(true);
+ expect(JSON.parse(await readFile(join(dataDir, 'pipeline-series/ser-a/index.json.imported'), 'utf8')).name).toBe('old recovery');
+ expect(await exists('pipeline-series/ser-a/manuscript-review.json')).toBe(true);
+});
+
+it('blocks completion on a damaged universe runs index until repair', async () => {
+ await put('universes/index.json', '{');
+ expect(await migrateUniversesToDB()).toMatchObject({ reason: 'incomplete' });
+ await put('universes/index.json', { config: { runs: [{ id: 'run-a', universeId: 'uni-a' }] } });
+ expect(await migrateUniversesToDB()).toMatchObject({ reason: 'imported', runs: 1 });
+});
+
+it('does not misreport an invalid directory as a fresh installation', async () => {
+ await put('pipeline-series', 'not a directory');
+ await expect(migrateSeriesToDB()).rejects.toThrow('not a directory');
+ expect(await exists('pipeline-series.migrated.json')).toBe(false);
+});
+
+it('recovery dry-run inspects canonical and parked sources, applies only selected missing rows, and preserves markers', async () => {
+ await put('pipeline-series.migrated.json', { reason: 'imported' });
+ await put('pipeline-series/ser-a/index.json', { id: 'ser-a', name: 'repaired' });
+ await put('pipeline-series/ser-a/index.json.imported', { id: 'ser-a', name: 'old' });
+ await put('pipeline-issues.imported/iss-a/index.json', { id: 'iss-a', seriesId: 'ser-a' });
+ await put('universes.imported/uni-old/index.json', { id: 'uni-old' });
+ await put('writers-room/works/wr-work-aaa/manifest.imported.json', { id: 'wr-work-aaa', drafts: [{ id: 'wr-draft-aaa' }] });
+ const preview = await recoverLegacyImports();
+ expect(preview.mode).toBe('dry-run');
+ expect(preview.results.map(row => row.key)).toEqual(expect.arrayContaining(['series:ser-a', 'issue:iss-a', 'universe:uni-old', 'work:wr-work-aaa', 'draft:wr-draft-aaa']));
+ expect(db.mock.calls.every(([sql]) => sql.startsWith('SELECT'))).toBe(true);
+ tables.get('pipeline_series').set('ser-a', 'newer DB edit');
+ const applied = await recoverLegacyImports({ apply: true, selections: ['series:ser-a', 'issue:iss-a', 'work:wr-work-aaa'] });
+ expect(applied.results).toEqual(expect.arrayContaining([expect.objectContaining({ key: 'series:ser-a', status: 'exists' }), expect.objectContaining({ key: 'issue:iss-a', status: 'inserted' })]));
+ expect(tables.get('pipeline_series').get('ser-a')).toBe('newer DB edit');
+ expect(tables.get('universes').size).toBe(0);
+ expect(tables.get('writers_room_draft_versions').size).toBe(0); // selecting work does NOT resurrect deleted drafts
+ expect(await exists('pipeline-series.migrated.json')).toBe(true);
+ expect(await exists('pipeline-issues.imported/iss-a/index.json')).toBe(true);
+ expect((await recoverLegacyImports({ selections: ['series:unknown'] })).results).toContainEqual({ key: 'series:unknown', status: 'not-found' });
+});
+
+it('refuses unscoped apply and unknown recovery arguments before DB access', async () => {
+ expect(parseRecoveryArgs(['--id', 'series:ser-a', '--apply'])).toEqual({ apply: true, selections: ['series:ser-a'] });
+ expect(() => parseRecoveryArgs(['--all'])).toThrow('Usage');
+ await expect(recoverLegacyImports({ apply: true })).rejects.toThrow('explicit');
+ await expect(recoverLegacyImports({ selections: ['unknown:record'] })).rejects.toThrow('kind:record-id');
+ expect(db).not.toHaveBeenCalled();
+});
+
+it('accepts DB-native prose/review directories with no legacy metadata or marker', async () => {
+ await put('writers-room/works/wr-work-aaa/drafts/wr-draft-aaa.md', 'DB-native prose');
+ await put('pipeline-series/ser-a/manuscript-review.json', { review: 'DB-native review' });
+ tables.set('writers_room_works', new Map([['wr-work-aaa', 'current work']]));
+ tables.set('pipeline_series', new Map([['ser-a', 'current series']]));
+ expect(await migrateWritersRoomToDB()).toMatchObject({ reason: 'imported', works: 0 });
+ expect(await migrateSeriesToDB()).toMatchObject({ reason: 'imported', imported: 0 });
+ expect(db.mock.calls.every(([sql]) => sql.startsWith('SELECT'))).toBe(true);
+ expect(await exists('writers-room/works/wr-work-aaa/drafts/wr-draft-aaa.md')).toBe(true);
+ expect(await exists('pipeline-series/ser-a/manuscript-review.json')).toBe(true);
+});
diff --git a/server/scripts/migrateIssuesToDB.js b/server/scripts/migrateIssuesToDB.js
index 5f25b5eb75..8db7ce5a8b 100644
--- a/server/scripts/migrateIssuesToDB.js
+++ b/server/scripts/migrateIssuesToDB.js
@@ -19,11 +19,12 @@
* the dir → next boot retries (ON CONFLICT DO NOTHING makes the retry safe).
*/
-import { rename, readdir, stat } from 'fs/promises';
+import { rename, readdir } from 'fs/promises';
import { join } from 'path';
-import { PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { PATHS } from '../lib/fileUtils.js';
import { markerExists, writeMarker } from '../lib/migrationMarker.js';
import { query } from '../lib/db.js';
+import { readLegacyJSON, legacyDirectory, incompleteImport } from './legacyImport.js';
import { mirrorTimestamp } from '../lib/pgTimestamp.js';
const LEGACY_DIRNAME = 'pipeline-issues';
@@ -31,12 +32,12 @@ const IMPORTED_DIRNAME = 'pipeline-issues.imported';
const MARKER_FILENAME = 'pipeline-issues.migrated.json';
const RECORD_RE = /^iss-[A-Za-z0-9-]+$/;
-async function importRecord(record) {
- if (!record || typeof record !== 'object' || typeof record.id !== 'string' || !record.id) return false;
- if (typeof record.seriesId !== 'string' || !record.seriesId) return false;
+export async function importRecord(record, execute = query) {
+ if (!record || typeof record !== 'object' || typeof record.id !== 'string' || !record.id) return null;
+ if (typeof record.seriesId !== 'string' || !record.seriesId) return null;
const now = new Date().toISOString();
const createdAt = mirrorTimestamp(record.createdAt, now);
- const result = await query(
+ const result = await execute(
`INSERT INTO pipeline_issues (id, series_id, season_id, number, status, data, ephemeral, created_at, updated_at, deleted, deleted_at)
VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, $8, $9, $10, $11)
ON CONFLICT (id) DO NOTHING`,
@@ -61,23 +62,37 @@ export async function migrateIssuesToDB() {
if (await markerExists(MARKER_FILENAME)) return { ok: true, reason: 'already-applied', imported: 0 };
const legacyDir = join(PATHS.data, LEGACY_DIRNAME);
- const dirStat = await stat(legacyDir).catch(() => null);
+ const dirStat = await legacyDirectory(legacyDir);
- if (!dirStat || !dirStat.isDirectory()) {
+ if (!dirStat) {
return { ok: true, reason: 'fresh-install', imported: 0 };
}
- const entries = await readdir(legacyDir).catch(() => []);
+ const entries = await readdir(legacyDir);
let imported = 0;
let skipped = 0;
+ let incomplete = 0;
for (const name of entries) {
if (!RECORD_RE.test(name)) continue;
- const record = await readJSONFile(join(legacyDir, name, 'index.json'), null, { allowArray: false, logError: false });
- if (!record) { skipped += 1; continue; }
- if (await importRecord(record)) imported += 1;
+ const recordPath = join(legacyDir, name, 'index.json');
+ const source = await readLegacyJSON(recordPath);
+ if (source.status === 'missing') {
+ // Current DB-backed records may own file-primary siblings without legacy
+ // metadata. Confirm the row instead of treating those directories as loss.
+ const existing = await query('SELECT id FROM pipeline_issues WHERE id = $1', [name]);
+ if (!existing.rows.length) incomplete += 1;
+ skipped += 1;
+ continue;
+ }
+ if (source.status !== 'valid' || source.value?.id !== name) { incomplete += 1; continue; }
+ const inserted = await importRecord(source.value);
+ if (inserted === null) { incomplete += 1; continue; }
+ if (inserted) imported += 1;
else skipped += 1;
}
+ if (incomplete) return incompleteImport('Issues', { imported, skipped }, incomplete);
+
try {
await rename(legacyDir, join(PATHS.data, IMPORTED_DIRNAME));
} catch (err) {
diff --git a/server/scripts/migrateIssuesToDB.test.js b/server/scripts/migrateIssuesToDB.test.js
index 3b87741743..860d13eab5 100644
--- a/server/scripts/migrateIssuesToDB.test.js
+++ b/server/scripts/migrateIssuesToDB.test.js
@@ -27,6 +27,12 @@ vi.mock('../lib/migrationMarker.js', () => ({
}));
vi.mock('fs/promises', () => ({
+ readFile: vi.fn(async (path) => {
+ const key = toPosix(path);
+
+ if (!(key in recordsByDir)) { const error = new Error('ENOENT'); error.code = 'ENOENT'; throw error; }
+ return JSON.stringify(recordsByDir[key]);
+ }),
rename: vi.fn(async (from, to) => {
if (renameShouldFail) throw new Error('EACCES');
renamed.push([toPosix(from), toPosix(to)]);
diff --git a/server/scripts/migrateSeriesToDB.js b/server/scripts/migrateSeriesToDB.js
index f26599a658..eb86e6e2fb 100644
--- a/server/scripts/migrateSeriesToDB.js
+++ b/server/scripts/migrateSeriesToDB.js
@@ -30,11 +30,12 @@
* retry safe; an already-renamed record is simply skipped on re-read).
*/
-import { rename, readdir, stat } from 'fs/promises';
+import { readdir } from 'fs/promises';
import { join } from 'path';
-import { PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { PATHS } from '../lib/fileUtils.js';
import { markerExists, writeMarker } from '../lib/migrationMarker.js';
import { query } from '../lib/db.js';
+import { readLegacyJSON, legacyDirectory, parkLegacyFile, incompleteImport } from './legacyImport.js';
import { mirrorTimestamp } from '../lib/pgTimestamp.js';
const LEGACY_DIRNAME = 'pipeline-series';
@@ -44,11 +45,11 @@ const RECORD_RE = /^ser-[A-Za-z0-9-]+$/;
// One legacy series record → `pipeline_series` row. Verbatim into `data`; the
// typed mirror columns are bind-sanitized so a hand-edited/legacy value can't
// make the INSERT throw and abort the whole import.
-async function importRecord(record) {
- if (!record || typeof record !== 'object' || typeof record.id !== 'string' || !record.id) return false;
+export async function importRecord(record, execute = query) {
+ if (!record || typeof record !== 'object' || typeof record.id !== 'string' || !record.id) return null;
const now = new Date().toISOString();
const createdAt = mirrorTimestamp(record.createdAt, now);
- const result = await query(
+ const result = await execute(
`INSERT INTO pipeline_series (id, name, universe_id, writers_room_work_id, data, ephemeral, created_at, updated_at, deleted, deleted_at)
VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7, $8, $9, $10)
ON CONFLICT (id) DO NOTHING`,
@@ -72,32 +73,40 @@ export async function migrateSeriesToDB() {
if (await markerExists(MARKER_FILENAME)) return { ok: true, reason: 'already-applied', imported: 0 };
const legacyDir = join(PATHS.data, LEGACY_DIRNAME);
- const dirStat = await stat(legacyDir).catch(() => null);
+ const dirStat = await legacyDirectory(legacyDir);
// Fresh install (no legacy dir): no-op WITHOUT stamping the marker (keeps the
// recovery escape hatch open — see migrateUniversesToDB).
- if (!dirStat || !dirStat.isDirectory()) {
+ if (!dirStat) {
return { ok: true, reason: 'fresh-install', imported: 0 };
}
- const entries = await readdir(legacyDir).catch(() => []);
+ const entries = await readdir(legacyDir);
let imported = 0;
let skipped = 0;
+ let incomplete = 0;
for (const name of entries) {
if (!RECORD_RE.test(name)) continue; // skip index.json, hidden, non-record dirs
const recordPath = join(legacyDir, name, 'index.json');
- const record = await readJSONFile(recordPath, null, { allowArray: false, logError: false });
- // Already-renamed (index.json absent) on a retried run, or unreadable.
- if (!record) { skipped += 1; continue; }
- if (await importRecord(record)) imported += 1;
+ const source = await readLegacyJSON(recordPath);
+ if (source.status === 'missing') {
+ // Current DB-backed records may own file-primary siblings without legacy
+ // metadata. Confirm the row instead of treating those directories as loss.
+ const existing = await query('SELECT id FROM pipeline_series WHERE id = $1', [name]);
+ if (!existing.rows.length) incomplete += 1;
+ skipped += 1;
+ continue;
+ }
+ if (source.status !== 'valid' || source.value?.id !== name) { incomplete += 1; continue; }
+ const inserted = await importRecord(source.value);
+ if (inserted === null) { incomplete += 1; continue; }
+ if (inserted) imported += 1;
else skipped += 1;
- // Rename the record's index.json aside IN PLACE — leaves the dir + its
- // manuscript-review.json sibling untouched, so the file-primary review doc
- // stays readable at its canonical path. Best-effort: a rename failure leaves
- // the index.json (next boot retries; ON CONFLICT DO NOTHING is safe).
- await rename(recordPath, `${recordPath}.imported`).catch(() => {});
+ if (!await parkLegacyFile(recordPath, `${recordPath}.imported`)) incomplete += 1;
}
+ if (incomplete) return incompleteImport('Series', { imported, skipped }, incomplete);
+
await writeMarker(MARKER_FILENAME, { migratedAt: new Date().toISOString(), imported, skipped, reason: 'imported' });
console.log(`🎬 pipeline-series→DB import: imported ${imported} series (${skipped} skipped); index.json renamed aside in place (review siblings kept)`);
return { ok: true, reason: 'imported', imported, skipped };
diff --git a/server/scripts/migrateSeriesToDB.test.js b/server/scripts/migrateSeriesToDB.test.js
index 5402aeab22..f9a2847e34 100644
--- a/server/scripts/migrateSeriesToDB.test.js
+++ b/server/scripts/migrateSeriesToDB.test.js
@@ -6,6 +6,7 @@
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { readFile, stat, readdir, rename } from 'fs/promises';
import { posixPath as toPosix } from '../lib/testHelper.js';
let files = {}; // path → string (markers)
@@ -26,6 +27,12 @@ vi.mock('../lib/migrationMarker.js', () => ({
}));
vi.mock('fs/promises', () => ({
+ readFile: vi.fn(async (path) => {
+ const key = toPosix(path);
+
+ if (!(key in recordsByDir)) { const error = new Error('ENOENT'); error.code = 'ENOENT'; throw error; }
+ return JSON.stringify(recordsByDir[key]);
+ }),
rename: vi.fn(async (from, to) => { renamed.push([toPosix(from), toPosix(to)]); }),
readdir: vi.fn(async () => (dirEntries === null ? [] : dirEntries)),
stat: vi.fn(async (path) => {
@@ -118,3 +125,22 @@ describe('migrateSeriesToDB', () => {
expect(table.has('ser-bad')).toBe(false);
});
});
+
+it.each(['stat', 'readdir'])('surfaces unexpected %s failures without marking a completed import', async operation => {
+ dirEntries = ['ser-a'];
+ const error = Object.assign(new Error('access denied'), { code: 'EACCES' });
+ ({ stat, readdir })[operation].mockRejectedValueOnce(error);
+ await expect(importer()).rejects.toThrow('access denied');
+ expect(MARKER in files).toBe(false);
+});
+
+it.each(['read', 'park'])('retries after a source %s failure without falsely completing', async operation => {
+ dirEntries = ['ser-a'];
+ recordsByDir['/fake/data/pipeline-series/ser-a/index.json'] = rec('ser-a');
+ const error = Object.assign(new Error('access denied'), { code: 'EACCES' });
+ (operation === 'read' ? readFile : rename).mockRejectedValueOnce(error);
+ expect(await importer()).toMatchObject({ reason: 'incomplete' });
+ expect(MARKER in files).toBe(false);
+ expect(await importer()).toMatchObject({ reason: 'imported' });
+ expect(MARKER in files).toBe(true);
+});
diff --git a/server/scripts/migrateStoryBuilderToDB.js b/server/scripts/migrateStoryBuilderToDB.js
index 4485beea44..994ec727b8 100644
--- a/server/scripts/migrateStoryBuilderToDB.js
+++ b/server/scripts/migrateStoryBuilderToDB.js
@@ -20,11 +20,12 @@
* the dir → next boot retries (ON CONFLICT DO NOTHING makes the retry safe).
*/
-import { rename, readdir, stat } from 'fs/promises';
+import { rename, readdir } from 'fs/promises';
import { join } from 'path';
-import { PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { PATHS } from '../lib/fileUtils.js';
import { markerExists, writeMarker } from '../lib/migrationMarker.js';
import { query } from '../lib/db.js';
+import { readLegacyJSON, legacyDirectory, incompleteImport } from './legacyImport.js';
import { mirrorTimestamp } from '../lib/pgTimestamp.js';
const LEGACY_DIRNAME = 'story-builder';
@@ -35,11 +36,11 @@ const RECORD_RE = /^stb-[A-Za-z0-9-]+$/;
// One legacy session record → `story_builder_sessions` row. Verbatim into
// `data`; the typed mirror columns are bind-sanitized so a hand-edited/legacy
// value can't make the INSERT throw and abort the whole import.
-async function importRecord(record) {
- if (!record || typeof record !== 'object' || typeof record.id !== 'string' || !record.id) return false;
+export async function importRecord(record, execute = query) {
+ if (!record || typeof record !== 'object' || typeof record.id !== 'string' || !record.id) return null;
const now = new Date().toISOString();
const createdAt = mirrorTimestamp(record.createdAt, now);
- const result = await query(
+ const result = await execute(
`INSERT INTO story_builder_sessions (id, universe_id, series_id, sync, data, ephemeral, created_at, updated_at, deleted, deleted_at)
VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7, $8, $9, $10)
ON CONFLICT (id) DO NOTHING`,
@@ -63,25 +64,39 @@ export async function migrateStoryBuilderToDB() {
if (await markerExists(MARKER_FILENAME)) return { ok: true, reason: 'already-applied', imported: 0 };
const legacyDir = join(PATHS.data, LEGACY_DIRNAME);
- const dirStat = await stat(legacyDir).catch(() => null);
+ const dirStat = await legacyDirectory(legacyDir);
// Fresh install (no legacy dir): no-op WITHOUT stamping the marker (keeps the
// recovery escape hatch open — see migrateIssuesToDB).
- if (!dirStat || !dirStat.isDirectory()) {
+ if (!dirStat) {
return { ok: true, reason: 'fresh-install', imported: 0 };
}
- const entries = await readdir(legacyDir).catch(() => []);
+ const entries = await readdir(legacyDir);
let imported = 0;
let skipped = 0;
+ let incomplete = 0;
for (const name of entries) {
if (!RECORD_RE.test(name)) continue; // skip index.json, hidden, non-record dirs
- const record = await readJSONFile(join(legacyDir, name, 'index.json'), null, { allowArray: false, logError: false });
- if (!record) { skipped += 1; continue; }
- if (await importRecord(record)) imported += 1;
+ const recordPath = join(legacyDir, name, 'index.json');
+ const source = await readLegacyJSON(recordPath);
+ if (source.status === 'missing') {
+ // Current DB-backed records may own file-primary siblings without legacy
+ // metadata. Confirm the row instead of treating those directories as loss.
+ const existing = await query('SELECT id FROM story_builder_sessions WHERE id = $1', [name]);
+ if (!existing.rows.length) incomplete += 1;
+ skipped += 1;
+ continue;
+ }
+ if (source.status !== 'valid' || source.value?.id !== name) { incomplete += 1; continue; }
+ const inserted = await importRecord(source.value);
+ if (inserted === null) { incomplete += 1; continue; }
+ if (inserted) imported += 1;
else skipped += 1;
}
+ if (incomplete) return incompleteImport('StoryBuilder', { imported, skipped }, incomplete);
+
try {
await rename(legacyDir, join(PATHS.data, IMPORTED_DIRNAME));
} catch (err) {
diff --git a/server/scripts/migrateStoryBuilderToDB.test.js b/server/scripts/migrateStoryBuilderToDB.test.js
index c9d4183570..47eafaf69e 100644
--- a/server/scripts/migrateStoryBuilderToDB.test.js
+++ b/server/scripts/migrateStoryBuilderToDB.test.js
@@ -27,6 +27,12 @@ vi.mock('../lib/migrationMarker.js', () => ({
}));
vi.mock('fs/promises', () => ({
+ readFile: vi.fn(async (path) => {
+ const key = toPosix(path);
+
+ if (!(key in recordsByDir)) { const error = new Error('ENOENT'); error.code = 'ENOENT'; throw error; }
+ return JSON.stringify(recordsByDir[key]);
+ }),
rename: vi.fn(async (from, to) => {
if (renameShouldFail) throw new Error('EACCES');
renamed.push([toPosix(from), toPosix(to)]);
diff --git a/server/scripts/migrateUniversesToDB.js b/server/scripts/migrateUniversesToDB.js
index 56ce0a50d4..f5a8c193cd 100644
--- a/server/scripts/migrateUniversesToDB.js
+++ b/server/scripts/migrateUniversesToDB.js
@@ -28,11 +28,12 @@
* it's gated on its own marker and invoked from the backend selector.
*/
-import { rename, readdir, stat } from 'fs/promises';
+import { rename, readdir } from 'fs/promises';
import { join } from 'path';
-import { PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { PATHS } from '../lib/fileUtils.js';
import { markerExists, writeMarker } from '../lib/migrationMarker.js';
import { query } from '../lib/db.js';
+import { readLegacyJSON, legacyDirectory, incompleteImport } from './legacyImport.js';
import { mirrorTimestamp } from '../lib/pgTimestamp.js';
const LEGACY_DIRNAME = 'universes';
@@ -42,12 +43,12 @@ const MARKER_FILENAME = 'universes.migrated.json';
// One legacy universe record → `universes` row. Verbatim into `data`; the typed
// mirror columns are bind-sanitized so a hand-edited/legacy timestamp or missing
// field can't make the INSERT throw and abort the whole import.
-async function importRecord(record) {
- if (!record || typeof record !== 'object' || typeof record.id !== 'string' || !record.id) return false;
+export async function importRecord(record, execute = query) {
+ if (!record || typeof record !== 'object' || typeof record.id !== 'string' || !record.id) return null;
const now = new Date().toISOString();
const createdAt = mirrorTimestamp(record.createdAt, now);
const schemaVersion = Number.isInteger(record.schemaVersion) ? record.schemaVersion : 4;
- const result = await query(
+ const result = await execute(
`INSERT INTO universes (id, name, data, schema_version, ephemeral, created_at, updated_at, deleted, deleted_at)
VALUES ($1, $2, $3::jsonb, $4, $5, $6, $7, $8, $9)
ON CONFLICT (id) DO NOTHING`,
@@ -66,9 +67,9 @@ async function importRecord(record) {
return result.rowCount > 0;
}
-async function importRun(run) {
- if (!run || typeof run !== 'object' || typeof run.id !== 'string' || typeof run.universeId !== 'string') return false;
- const result = await query(
+export async function importRun(run, execute = query) {
+ if (!run || typeof run !== 'object' || typeof run.id !== 'string' || typeof run.universeId !== 'string' || !run.id || !run.universeId) return null;
+ const result = await execute(
`INSERT INTO universe_runs (id, universe_id, collection_id, data, created_at)
VALUES ($1, $2, $3, $4::jsonb, $5)
ON CONFLICT (id) DO NOTHING`,
@@ -87,40 +88,60 @@ export async function migrateUniversesToDB() {
if (await markerExists(MARKER_FILENAME)) return { ok: true, reason: 'already-applied', imported: 0 };
const legacyDir = join(PATHS.data, LEGACY_DIRNAME);
- const dirStat = await stat(legacyDir).catch(() => null);
+ const dirStat = await legacyDirectory(legacyDir);
// Fresh install (no legacy dir): no-op WITHOUT stamping the marker. The probe
// is a single stat per boot — cheap — and NOT stamping keeps the recovery
// escape hatch open: a user who later restores data/universes.imported back to
// data/universes (to re-import after a rollback) gets a real import on the next
// boot. Stamping here would silently suppress that forever.
- if (!dirStat || !dirStat.isDirectory()) {
+ if (!dirStat) {
return { ok: true, reason: 'fresh-install', imported: 0, runs: 0 };
}
- const entries = await readdir(legacyDir).catch(() => []);
+ const entries = await readdir(legacyDir);
let imported = 0;
let skipped = 0;
+ let incomplete = 0;
for (const name of entries) {
if (name === 'index.json' || name.startsWith('.')) continue;
- const record = await readJSONFile(join(legacyDir, name, 'index.json'), null, { allowArray: false, logError: false });
- if (!record) { skipped += 1; continue; }
- if (await importRecord(record)) imported += 1;
+ const recordPath = join(legacyDir, name, 'index.json');
+ const source = await readLegacyJSON(recordPath);
+ if (source.status === 'missing') {
+ // Current DB-backed records may own file-primary siblings without legacy
+ // metadata. Confirm the row instead of treating those directories as loss.
+ const existing = await query('SELECT id FROM universes WHERE id = $1', [name]);
+ if (!existing.rows.length) incomplete += 1;
+ skipped += 1;
+ continue;
+ }
+ if (source.status !== 'valid' || source.value?.id !== name) { incomplete += 1; continue; }
+ const inserted = await importRecord(source.value);
+ if (inserted === null) { incomplete += 1; continue; }
+ if (inserted) imported += 1;
else skipped += 1;
}
// Runs from the type-level index.json `config.runs[]`.
let runs = 0;
- const typeIndex = await readJSONFile(join(legacyDir, 'index.json'), null, { allowArray: false, logError: false });
- const legacyRuns = Array.isArray(typeIndex?.config?.runs) ? typeIndex.config.runs : [];
- for (const run of legacyRuns) {
- if (await importRun(run)) runs += 1;
+ const typeIndex = await readLegacyJSON(join(legacyDir, 'index.json'));
+ if (typeIndex.status === 'invalid' || Array.isArray(typeIndex.value)) incomplete += 1;
+ if (typeIndex.status === 'valid') {
+ const legacyRuns = typeIndex.value?.config?.runs;
+ if (legacyRuns !== undefined && !Array.isArray(legacyRuns)) incomplete += 1;
+ for (const run of Array.isArray(legacyRuns) ? legacyRuns : []) {
+ const inserted = await importRun(run);
+ if (inserted === null) incomplete += 1;
+ else if (inserted) runs += 1;
+ }
}
// Rename the legacy dir aside AFTER all rows land, then stamp the marker only
// if the rename succeeded (so a rollback / MEMORY_BACKEND=file boot can't read
// a stale dir while the marker claims migration is done). If the rename fails,
// leave the dir + no marker → next boot retries the idempotent import.
+ if (incomplete) return incompleteImport('Universes', { imported, skipped, runs }, incomplete);
+
try {
await rename(legacyDir, join(PATHS.data, IMPORTED_DIRNAME));
} catch (err) {
diff --git a/server/scripts/migrateUniversesToDB.test.js b/server/scripts/migrateUniversesToDB.test.js
index 71db34cdd6..e3d8ca2ec5 100644
--- a/server/scripts/migrateUniversesToDB.test.js
+++ b/server/scripts/migrateUniversesToDB.test.js
@@ -34,6 +34,12 @@ vi.mock('../lib/migrationMarker.js', () => ({
}));
vi.mock('fs/promises', () => ({
+ readFile: vi.fn(async (path) => {
+ const key = toPosix(path);
+ if (key === '/fake/data/universes/index.json' && typeIndex !== null) return JSON.stringify(typeIndex);
+ if (!(key in recordsByDir)) { const error = new Error('ENOENT'); error.code = 'ENOENT'; throw error; }
+ return JSON.stringify(recordsByDir[key]);
+ }),
rename: vi.fn(async (from, to) => {
if (renameShouldFail) throw new Error('EACCES');
renamed.push([toPosix(from), toPosix(to)]);
diff --git a/server/scripts/migrateWritersRoomToDB.js b/server/scripts/migrateWritersRoomToDB.js
index e43763c647..e8ecc468af 100644
--- a/server/scripts/migrateWritersRoomToDB.js
+++ b/server/scripts/migrateWritersRoomToDB.js
@@ -28,35 +28,23 @@
* retries (ON CONFLICT DO NOTHING makes the retry safe).
*/
-import { readFile, rename, readdir, stat } from 'fs/promises';
+import { readdir } from 'fs/promises';
import { join } from 'path';
-import { PATHS, readJSONFile, safeJSONParse } from '../lib/fileUtils.js';
+import { PATHS } from '../lib/fileUtils.js';
import { markerExists, writeMarker } from '../lib/migrationMarker.js';
import { query } from '../lib/db.js';
+import { readLegacyJSON, legacyDirectory, parkLegacyFile, incompleteImport } from './legacyImport.js';
import { mirrorTimestamp } from '../lib/pgTimestamp.js';
const ROOT_DIRNAME = 'writers-room';
const MARKER_FILENAME = 'writers-room.migrated.json';
const WORK_ID_RE = /^wr-work-[0-9a-f-]+$/i;
-// Rename a file aside (path → path.replace('.json','.imported.json')) if it
-// exists; a missing file is a no-op. Never overwrites an existing recovery copy.
-async function parkFileAside(path) {
- const exists = await stat(path).catch(() => null);
- if (!exists) return;
- const aside = path.replace(/\.json$/, '.imported.json');
- const asideExists = await stat(aside).catch(() => null);
- if (asideExists) return; // recovery copy already present — don't clobber
- await rename(path, aside).catch((err) => {
- console.warn(`⚠️ writers-room→DB import: could not park ${path} aside (${err.message})`);
- });
-}
-
-async function importFolder(folder) {
- if (!folder || typeof folder.id !== 'string' || !folder.id) return false;
+export async function importFolder(folder, execute = query) {
+ if (!folder || typeof folder.id !== 'string' || !folder.id) return null;
const now = new Date().toISOString();
const createdAt = mirrorTimestamp(folder.createdAt, now);
- const result = await query(
+ const result = await execute(
`INSERT INTO writers_room_folders (id, parent_id, name, sort_order, data, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7)
ON CONFLICT (id) DO NOTHING`,
@@ -73,9 +61,9 @@ async function importFolder(folder) {
return result.rowCount > 0;
}
-async function importExercise(exercise) {
- if (!exercise || typeof exercise.id !== 'string' || !exercise.id) return false;
- const result = await query(
+export async function importExercise(exercise, execute = query) {
+ if (!exercise || typeof exercise.id !== 'string' || !exercise.id) return null;
+ const result = await execute(
`INSERT INTO writers_room_exercises (id, work_id, status, data, started_at, finished_at)
VALUES ($1, $2, $3, $4::jsonb, $5, $6)
ON CONFLICT (id) DO NOTHING`,
@@ -93,13 +81,14 @@ async function importExercise(exercise) {
// A work manifest → one work row (manifest minus drafts[]) + one draft-version
// row per draft entry. All existing works import as deleted = FALSE.
-async function importWork(manifest) {
- if (!manifest || typeof manifest.id !== 'string' || !manifest.id) return false;
+export async function importWork(manifest, execute = query) {
+ if (!manifest || typeof manifest.id !== 'string' || !manifest.id) return null;
+ if (manifest.drafts !== undefined && (!Array.isArray(manifest.drafts) || manifest.drafts.some(draft => !draft || typeof draft.id !== 'string' || !draft.id))) return null;
const now = new Date().toISOString();
const createdAt = mirrorTimestamp(manifest.createdAt, now);
const { drafts: draftList, ...workData } = manifest;
const drafts = Array.isArray(draftList) ? draftList : [];
- const result = await query(
+ const result = await execute(
`INSERT INTO writers_room_works
(id, folder_id, title, kind, status, active_draft_version_id,
pipeline_series_id, pipeline_issue_id, cd_project_id, media_collection_id,
@@ -123,8 +112,7 @@ async function importWork(manifest) {
],
);
for (const draft of drafts) {
- if (!draft || typeof draft.id !== 'string') continue;
- await query(
+ await execute(
`INSERT INTO writers_room_draft_versions
(id, work_id, label, content_file, content_hash, word_count,
segment_index, created_from_version_id, data, created_at)
@@ -151,62 +139,47 @@ export async function migrateWritersRoomToDB() {
if (await markerExists(MARKER_FILENAME)) return { ok: true, reason: 'already-applied' };
const root = join(PATHS.data, ROOT_DIRNAME);
- const rootStat = await stat(root).catch(() => null);
-
- // Fresh install (no legacy dir): no-op WITHOUT stamping the marker (keeps the
- // recovery escape hatch open — see migrateStoryBuilderToDB).
- if (!rootStat || !rootStat.isDirectory()) {
- return { ok: true, reason: 'fresh-install', folders: 0, works: 0, exercises: 0 };
- }
+ const rootStat = await legacyDirectory(root);
+ if (!rootStat) return { ok: true, reason: 'fresh-install', folders: 0, works: 0, exercises: 0 };
- // Folders.
- const foldersFile = join(root, 'folders.json');
- const folders = await readJSONFile(foldersFile, []);
- let folderCount = 0;
- for (const f of Array.isArray(folders) ? folders : []) {
- if (await importFolder(f)) folderCount += 1;
+ const counts = { folders: 0, works: 0, exercises: 0 };
+ let incomplete = 0;
+ for (const [name, importRow] of [['folders', importFolder], ['exercises', importExercise]]) {
+ const path = join(root, `${name}.json`);
+ const source = await readLegacyJSON(path);
+ if (source.status === 'missing') continue;
+ if (source.status !== 'valid' || !Array.isArray(source.value)) { incomplete += 1; continue; }
+ let valid = true;
+ for (const row of source.value) {
+ const inserted = await importRow(row);
+ if (inserted === null) { incomplete += 1; valid = false; }
+ else if (inserted) counts[name] += 1;
+ }
+ if (valid && !await parkLegacyFile(path, path.replace(/\.json$/, '.imported.json'))) incomplete += 1;
}
- // Exercises.
- const exercisesFile = join(root, 'exercises.json');
- const exercises = await readJSONFile(exercisesFile, []);
- let exerciseCount = 0;
- for (const e of Array.isArray(exercises) ? exercises : []) {
- if (await importExercise(e)) exerciseCount += 1;
- }
-
- // Works (manifest.json per work dir; .md bodies stay in place).
const worksDir = join(root, 'works');
- const worksStat = await stat(worksDir).catch(() => null);
- const workEntries = worksStat?.isDirectory()
- ? await readdir(worksDir, { withFileTypes: true }).catch(() => [])
- : [];
- let workCount = 0;
- const importedManifestPaths = [];
+ const workEntries = await legacyDirectory(worksDir) ? await readdir(worksDir, { withFileTypes: true }) : [];
for (const entry of workEntries) {
if (!entry.isDirectory() || !WORK_ID_RE.test(entry.name)) continue;
- const manifestPath = join(worksDir, entry.name, 'manifest.json');
- const content = await readFile(manifestPath, 'utf-8').catch(() => null);
- if (content === null) continue;
- const manifest = safeJSONParse(content, null, { allowArray: false, logError: true, context: manifestPath });
- // `allowArray: false` only rejects a root array — a bare JSON scalar
- // still parses, so also guard for a genuine object before treating the
- // manifest as valid.
- if (!manifest || typeof manifest !== 'object') continue; // corrupted manifest — skip, leave on disk untouched
- if (await importWork(manifest)) workCount += 1;
- importedManifestPaths.push(manifestPath);
+ const path = join(worksDir, entry.name, 'manifest.json');
+ const aside = path.replace(/\.json$/, '.imported.json');
+ const source = await readLegacyJSON(path);
+ if (source.status === 'missing') {
+ // A DB-native work creates prose directories but no legacy manifest.
+ const existing = await query('SELECT id FROM writers_room_works WHERE id = $1', [entry.name]);
+ if (!existing.rows.length) incomplete += 1;
+ continue;
+ }
+ if (source.status !== 'valid' || source.value?.id !== entry.name) { incomplete += 1; continue; }
+ const inserted = await importWork(source.value);
+ if (inserted === null) { incomplete += 1; continue; }
+ if (inserted) counts.works += 1;
+ if (!await parkLegacyFile(path, aside)) incomplete += 1;
}
- // Park the JSON metadata files aside (the .md bodies stay put). Only after all
- // rows have landed, so a crash before this leaves a clean retry.
- await parkFileAside(foldersFile);
- await parkFileAside(exercisesFile);
- for (const p of importedManifestPaths) await parkFileAside(p);
-
- await writeMarker(MARKER_FILENAME, {
- migratedAt: new Date().toISOString(),
- folders: folderCount, works: workCount, exercises: exerciseCount, reason: 'imported',
- });
- console.log(`✍️ writers-room→DB import: ${folderCount} folder(s), ${workCount} work(s), ${exerciseCount} exercise(s); .md bodies left in place`);
- return { ok: true, reason: 'imported', folders: folderCount, works: workCount, exercises: exerciseCount };
+ if (incomplete) return incompleteImport('Writers Room', counts, incomplete);
+ await writeMarker(MARKER_FILENAME, { migratedAt: new Date().toISOString(), ...counts, reason: 'imported' });
+ console.log(`✍️ writers-room→DB import: ${counts.folders} folder(s), ${counts.works} work(s), ${counts.exercises} exercise(s); .md bodies left in place`);
+ return { ok: true, reason: 'imported', ...counts };
}
diff --git a/server/scripts/migrateWritersRoomToDB.test.js b/server/scripts/migrateWritersRoomToDB.test.js
index f68fe73ce9..42c464168c 100644
--- a/server/scripts/migrateWritersRoomToDB.test.js
+++ b/server/scripts/migrateWritersRoomToDB.test.js
@@ -36,6 +36,7 @@ vi.mock('../lib/migrationMarker.js', () => ({
vi.mock('fs/promises', () => ({
readFile: vi.fn(async (path) => {
+ if (toPosix(path) in jsonByPath) return JSON.stringify(jsonByPath[toPosix(path)]);
if (!(toPosix(path) in files)) { const e = new Error('ENOENT'); e.code = 'ENOENT'; throw e; }
return files[toPosix(path)];
}),
diff --git a/server/scripts/pruneImportedLegacyFiles.test.js b/server/scripts/pruneImportedLegacyFiles.test.js
index 0f2dd4fb67..db8a485c62 100644
--- a/server/scripts/pruneImportedLegacyFiles.test.js
+++ b/server/scripts/pruneImportedLegacyFiles.test.js
@@ -291,6 +291,17 @@ describe('pruneImportedLegacyFiles', () => {
expect(await exists(join(dataDir, 'legacy-prune.applied.json'))).toBe(false);
});
+ it('retains healthy parked series alongside an incomplete canonical record until import finishes', async () => {
+ await mkdir(join(dataDir, 'pipeline-series/ser-good'), { recursive: true });
+ await mkdir(join(dataDir, 'pipeline-series/ser-bad'), { recursive: true });
+ await writeJSON(join(dataDir, 'pipeline-series/ser-good/index.json.imported'), { id: 'ser-good' });
+ await writeJSON(join(dataDir, 'pipeline-series/ser-bad/index.json'), { id: 'ser-bad' });
+ const result = await pruneImportedLegacyFiles({ dataDir, db: stubDb({ pipeline_series: ['ser-good'] }) });
+ expect(result.markerWritten).toBe(false);
+ expect(await exists(join(dataDir, 'pipeline-series/ser-good/index.json.imported'))).toBe(true);
+ expect(await exists(join(dataDir, 'pipeline-series/ser-bad/index.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' }]);
diff --git a/server/scripts/recoverLegacyImports.js b/server/scripts/recoverLegacyImports.js
new file mode 100644
index 0000000000..3d1dd19942
--- /dev/null
+++ b/server/scripts/recoverLegacyImports.js
@@ -0,0 +1,130 @@
+/** Explicit, dry-run-first recovery for premature legacy import markers.
+ * Reuses the importers' INSERT mappings; never changes markers or source files.
+ */
+import { readdir } from 'fs/promises';
+import { join, relative, resolve } from 'path';
+import { pathToFileURL } from 'url';
+import { PATHS } from '../lib/fileUtils.js';
+import { query, close } from '../lib/db.js';
+import { legacyDirectory, readLegacyJSON } from './legacyImport.js';
+import { importRecord as importSeries } from './migrateSeriesToDB.js';
+import { importRecord as importIssue } from './migrateIssuesToDB.js';
+import { importRecord as importStory } from './migrateStoryBuilderToDB.js';
+import { importRecord as importUniverse, importRun } from './migrateUniversesToDB.js';
+import { importWork, importFolder, importExercise } from './migrateWritersRoomToDB.js';
+
+const TABLE_KINDS = {
+ pipeline_series: 'series', pipeline_issues: 'issue', story_builder_sessions: 'story',
+ universes: 'universe', universe_runs: 'run', writers_room_works: 'work',
+ writers_room_draft_versions: 'draft', writers_room_folders: 'folder', writers_room_exercises: 'exercise',
+};
+
+export function parseRecoveryArgs(args) {
+ const options = { apply: false, selections: [] };
+ for (let i = 0; i < args.length; i += 1) {
+ if (args[i] === '--apply') options.apply = true;
+ else if (args[i] === '--id' && args[i + 1]) options.selections.push(args[++i]);
+ else throw new Error('Usage: node server/scripts/recoverLegacyImports.js [--id kind:record-id ...] [--apply]');
+ }
+ return options;
+}
+
+export async function recoverLegacyImports({ apply = false, selections = [] } = {}) {
+ const selected = new Set(selections);
+ for (const key of selected) {
+ const colon = key.indexOf(':');
+ if (colon < 1 || !Object.values(TABLE_KINDS).includes(key.slice(0, colon)) || !key.slice(colon + 1).trim()) {
+ throw new Error('Recovery selections must be kind:record-id');
+ }
+ }
+ if (apply && !selected.size) throw new Error('Recovery application requires explicit --id selections');
+ const results = [];
+ const seen = new Set();
+ const encountered = new Set();
+ let sourcePath;
+ // Table identifiers are accepted ONLY from our fixed mapping, never from disk
+ // or CLI input. Dry-run uses SELECT only, including nested work draft rows.
+ const execute = async (sql, params) => {
+ const table = /INSERT INTO (\w+)/.exec(sql)?.[1];
+ const kind = TABLE_KINDS[table];
+ if (!kind) throw new Error('Unsupported legacy recovery table');
+ const key = `${kind}:${params[0]}`;
+ if (selected.size && !selected.has(key)) return { rowCount: 0 };
+ encountered.add(key);
+ if (seen.has(key)) return { rowCount: 0 };
+ seen.add(key);
+ const existing = await query(`SELECT id FROM ${table} WHERE id = $1`, [params[0]]);
+ let status = existing.rows.length ? 'exists' : 'missing';
+ if (apply && status === 'missing') status = (await query(sql, params)).rowCount ? 'inserted' : 'exists';
+ results.push({ key, status, source: relative(PATHS.data, sourcePath) });
+ return { rowCount: status === 'inserted' ? 1 : 0 };
+ };
+ const read = async path => {
+ const source = await readLegacyJSON(path);
+ if (source.status === 'invalid') results.push({ status: 'invalid-source', source: relative(PATHS.data, path) });
+ return source;
+ };
+ const mapSource = async (path, mapper, array = false) => {
+ const source = await read(path);
+ if (source.status !== 'valid') return;
+ if (array && !Array.isArray(source.value)) {
+ results.push({ status: 'invalid-source', source: relative(PATHS.data, path) });
+ return;
+ }
+ sourcePath = path;
+ for (const record of array ? source.value : [source.value]) {
+ if (await mapper(record, execute) === null) results.push({ status: 'invalid-record', source: relative(PATHS.data, path) });
+ }
+ };
+ for (const [domain, mapper] of [
+ ['pipeline-series', importSeries], ['pipeline-issues', importIssue],
+ ['story-builder', importStory], ['universes', importUniverse],
+ ]) {
+ // Prefer a repaired canonical source over a parked historical copy.
+ for (const dir of [domain, `${domain}.imported`]) {
+ const root = join(PATHS.data, dir);
+ if (!await legacyDirectory(root)) continue;
+ for (const entry of await readdir(root, { withFileTypes: true })) {
+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
+ for (const filename of ['index.json', 'index.json.imported']) {
+ await mapSource(join(root, entry.name, filename), mapper);
+ }
+ }
+ if (domain === 'universes') {
+ const path = join(root, 'index.json');
+ const source = await read(path);
+ if (source.status === 'valid' && Array.isArray(source.value)) results.push({ status: 'invalid-source', source: relative(PATHS.data, path) });
+ if (source.status === 'valid') {
+ const runs = source.value?.config?.runs;
+ if (runs !== undefined && !Array.isArray(runs)) results.push({ status: 'invalid-source', source: relative(PATHS.data, path) });
+ sourcePath = path;
+ for (const run of Array.isArray(runs) ? runs : []) {
+ if (await importRun(run, execute) === null) results.push({ status: 'invalid-record', source: relative(PATHS.data, path) });
+ }
+ }
+ }
+ }
+ }
+ const root = join(PATHS.data, 'writers-room');
+ if (await legacyDirectory(root)) {
+ for (const [name, mapper] of [['folders', importFolder], ['exercises', importExercise]]) {
+ for (const suffix of ['.json', '.imported.json']) await mapSource(join(root, `${name}${suffix}`), mapper, true);
+ }
+ const works = join(root, 'works');
+ if (await legacyDirectory(works)) {
+ for (const entry of await readdir(works, { withFileTypes: true })) {
+ if (!entry.isDirectory() || !/^wr-work-[0-9a-f-]+$/i.test(entry.name)) continue;
+ for (const filename of ['manifest.json', 'manifest.imported.json']) await mapSource(join(works, entry.name, filename), importWork);
+ }
+ }
+ }
+ for (const key of selected) if (!encountered.has(key)) results.push({ key, status: 'not-found' });
+ return { mode: apply ? 'apply' : 'dry-run', results };
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
+ Promise.resolve().then(() => recoverLegacyImports(parseRecoveryArgs(process.argv.slice(2))))
+ .then(result => console.log(JSON.stringify(result, null, 2)))
+ .catch(error => { console.error(`❌ Legacy recovery failed: ${error.message}`); process.exitCode = 1; })
+ .finally(close);
+}