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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor([makesplitmigration-shared-factory]): extract makeSplitMigration into _lib.js
[._.]/ Adam Eivy1fe0850c8a7e
diff --git a/scripts/migrations/034-split-universe-builder-to-per-uuid.js b/scripts/migrations/034-split-universe-builder-to-per-uuid.jsindex fa9210855a..02a1080696 100644--- a/scripts/migrations/034-split-universe-builder-to-per-uuid.js+++ b/scripts/migrations/034-split-universe-builder-to-per-uuid.js@@ -35,169 +35,30 @@* 4) — distinct from the type-level `schemaVersion` (currently 5, this* migration's bump). See `server/lib/collectionStore.js` header for the* distinction between layout-version and record-shape-version.+ *+ * Shares the split skeleton with 035 / 036 / 059 via `makeSplitMigration`. The+ * only universe-specific bits are the `config.runs` carry-over (cross-record+ * `runs[]` travels with the type-level index) and the id pattern.*/-import { readFile, writeFile, rename, mkdir, stat, readdir } from 'fs/promises';-import { join } from 'path';--const TYPE_DIR_NAME = 'universes';-const LEGACY_FILENAME = 'universe-builder.json';-const BACKUP_SUFFIX = '.bak-034';-const TYPE_SCHEMA_VERSION = 5;-const TYPE_LABEL = 'universes';--const fileExists = (path) => stat(path).then(() => true, (err) => {- if (err.code === 'ENOENT') return false;- throw err;-});--// Two read variants so we distinguish "missing file" from "present but-// unparseable" — the latter is a recovery-required state we report through-// the migration's return value rather than crashing the boot.-const readJsonStrict = async (path) => {- const raw = await readFile(path, 'utf-8').catch((err) => {- if (err.code === 'ENOENT') return null;- throw err;- });- if (raw == null) return null;- return JSON.parse(raw);-};--const readJsonTolerant = async (path) => {- const raw = await readFile(path, 'utf-8').catch((err) => {- if (err.code === 'ENOENT') return null;- throw err;- });- if (raw == null) return null;- try { return JSON.parse(raw); } catch { return { __unreadable: true }; }-};--const writeJson = (path, value) =>- writeFile(path, JSON.stringify(value, null, 2) + '\n');+import { makeSplitMigration } from './_lib.js';// Match `UNIVERSE_ID_RE` in server/services/universeBuilder.js so an oddly-id'd// record (8–80 alphanumerics + hyphens) round-trips through the split without// being misclassified as a stray directory entry.const VALID_UNIVERSE_ID = /^[A-Za-z0-9-]{8,80}$/;-export default {- async up({ rootDir }) {- const dataDir = join(rootDir, 'data');- const typeDir = join(dataDir, TYPE_DIR_NAME);- const typeIndexPath = join(typeDir, 'index.json');- const legacyPath = join(dataDir, LEGACY_FILENAME);- const backupPath = legacyPath + BACKUP_SUFFIX;-- // Idempotency gate 1: type index already at v5 → nothing to do. A re-run- // after full success lands here. Read strictly — a corrupted index.json- // is unexpected and we want the loud throw at this layer.- const typeIndex = await readJsonStrict(typeIndexPath);- if (typeIndex && typeIndex.schemaVersion >= TYPE_SCHEMA_VERSION) {- console.log(`📦 migration 034: universes already at schemaVersion=${typeIndex.schemaVersion} — no-op`);- return { ok: true, reason: 'already-applied' };- }-- const legacyExists = await fileExists(legacyPath);- const backupExists = await fileExists(backupPath);-- // Idempotency gate 2: fresh install — no legacy file, no backup, just- // stamp the type index so verifyCollectionVersions doesn't flag missing.- if (!legacyExists && !backupExists) {- await mkdir(typeDir, { recursive: true });- await writeJson(typeIndexPath, {- schemaVersion: TYPE_SCHEMA_VERSION,- type: TYPE_LABEL,- updatedAt: new Date().toISOString(),- config: { runs: [] },- });- console.log(`📦 migration 034: fresh install — stamped data/universes/index.json @ v${TYPE_SCHEMA_VERSION}`);- return { ok: true, reason: 'fresh-install' };- }-- // Recovery gate: the previous run split records but didn't finish renaming- // the legacy file. Use whichever file is present as the source of truth —- // prefer the live file if both somehow exist (split must not have happened).- const sourcePath = legacyExists ? legacyPath : backupPath;- const doc = await readJsonTolerant(sourcePath);- if (!doc || typeof doc !== 'object' || doc.__unreadable) {- console.warn(`⚠️ migration 034: ${sourcePath} unreadable — skipping. Resolve manually before next boot.`);- return { ok: false, reason: 'unreadable' };- }-- const universes = Array.isArray(doc.universes) ? doc.universes : [];- const runs = Array.isArray(doc.runs) ? doc.runs : [];-- // Pre-flight: find any already-split records so we don't double-write the- // ones we've already moved. Helps partial-completion recovery.- // Use `withFileTypes: true` so we skip stray non-directory entries (e.g.- // user-left `.bak` files, editor swap files) without statting INTO them —- // `stat('foo.bak/index.json')` would raise ENOTDIR which our fileExists- // helper rethrows, crashing the whole migration.- const existingIds = new Set();- if (await fileExists(typeDir)) {- const entries = await readdir(typeDir, { withFileTypes: true }).catch(() => []);- for (const entry of entries) {- const name = entry.name;- if (name === 'index.json' || name.startsWith('.')) continue;- if (!entry.isDirectory()) continue;- const candidatePath = join(typeDir, name, 'index.json');- if (await fileExists(candidatePath)) existingIds.add(name);- }- }-- await mkdir(typeDir, { recursive: true });-- let written = 0;- let skipped = 0;- let invalid = 0;- for (const record of universes) {- if (!record || typeof record !== 'object') {- invalid += 1;- continue;- }- const id = typeof record.id === 'string' ? record.id : null;- if (!id || !VALID_UNIVERSE_ID.test(id)) {- invalid += 1;- console.warn(`⚠️ migration 034: skipping record with invalid id "${id}"`);- continue;- }- if (existingIds.has(id)) {- // Already split in a prior partial run — leave it alone. The- // monolithic record may have stale state (in-flight writes after the- // crash), so trusting the already-split per-record file is safer.- skipped += 1;- continue;- }- const recordDir = join(typeDir, id);- await mkdir(recordDir, { recursive: true });- await writeJson(join(recordDir, 'index.json'), record);- written += 1;- }-- // Stamp the type-level index AFTER all records land so a crash mid-split- // leaves the type index missing — the next boot's gate 1 won't trip, and- // gate 2/recovery re-runs the loop. Cross-record `runs[]` moves into- // `config.runs` so it travels with the type-level index.- await writeJson(typeIndexPath, {- schemaVersion: TYPE_SCHEMA_VERSION,- type: TYPE_LABEL,- updatedAt: new Date().toISOString(),- config: { runs },- });-- // Backup the legacy file. Skip if it's already been backed up (recovery- // path was driven from the backup). Renaming preserves data; manual- // restore is `mv universe-builder.json.bak-034 universe-builder.json`.- if (legacyExists) {- await rename(legacyPath, backupPath);- }-- console.log(- `📦 migration 034: split ${written} universe(s) into data/universes/<id>/index.json ` +- `(${skipped} already split, ${invalid} invalid); stamped index.json @ v${TYPE_SCHEMA_VERSION}; ` +- `legacy file backed up as ${LEGACY_FILENAME}${BACKUP_SUFFIX}`,- );-- return { ok: true, reason: 'split', written, skipped, invalid };- },-};+export default makeSplitMigration({+ migrationLabel: 'migration 034',+ typeDirName: 'universes',+ legacyFilename: 'universe-builder.json',+ backupSuffix: '.bak-034',+ typeSchemaVersion: 5,+ typeLabel: 'universes',+ recordsKey: 'universes',+ idPattern: VALID_UNIVERSE_ID,+ recordNoun: 'universe',+ // Cross-record `runs[]` moves into `config.runs` so it travels with the+ // type-level index (fresh install → empty).+ buildConfig: (doc) => ({ runs: Array.isArray(doc?.runs) ? doc.runs : [] }),+});diff --git a/scripts/migrations/035-split-pipeline-issues-to-per-id.js b/scripts/migrations/035-split-pipeline-issues-to-per-id.jsindex a0b1b0adb6..cfaae2f51a 100644--- a/scripts/migrations/035-split-pipeline-issues-to-per-id.js+++ b/scripts/migrations/035-split-pipeline-issues-to-per-id.js@@ -5,125 +5,23 @@* The legacy single-file shape serialized every issue edit behind one write* queue. The collection layout keeps record writes scoped to the issue id, so* unrelated issue PATCHes can proceed independently.+ *+ * Shares the split skeleton with 034 / 036 / 059 via `makeSplitMigration` —+ * issues carry no cross-record type-level state, so `config` is `{}`.*/-import { readFile, writeFile, rename, mkdir, stat, readdir } from 'fs/promises';-import { join } from 'path';+import { makeSplitMigration } from './_lib.js';-const TYPE_DIR_NAME = 'pipeline-issues';-const LEGACY_FILENAME = 'pipeline-issues.json';-const BACKUP_SUFFIX = '.bak-035';-const TYPE_SCHEMA_VERSION = 1;-const TYPE_LABEL = 'pipelineIssues';const VALID_ID = /^iss-[A-Za-z0-9-]+$/;-const fileExists = (path) => stat(path).then(() => true, (err) => {- if (err.code === 'ENOENT') return false;- throw err;+export default makeSplitMigration({+ migrationLabel: 'migration 035',+ typeDirName: 'pipeline-issues',+ legacyFilename: 'pipeline-issues.json',+ backupSuffix: '.bak-035',+ typeSchemaVersion: 1,+ typeLabel: 'pipelineIssues',+ recordsKey: 'issues',+ idPattern: VALID_ID,+ recordNoun: 'issue',});--const readJsonStrict = async (path) => {- const raw = await readFile(path, 'utf-8').catch((err) => {- if (err.code === 'ENOENT') return null;- throw err;- });- if (raw == null) return null;- return JSON.parse(raw);-};--const readJsonTolerant = async (path) => {- const raw = await readFile(path, 'utf-8').catch((err) => {- if (err.code === 'ENOENT') return null;- throw err;- });- if (raw == null) return null;- try { return JSON.parse(raw); } catch { return { __unreadable: true }; }-};--const writeJson = (path, value) =>- writeFile(path, JSON.stringify(value, null, 2) + '\n');--async function existingRecordIds(typeDir) {- const ids = new Set();- if (!await fileExists(typeDir)) return ids;- const entries = await readdir(typeDir, { withFileTypes: true }).catch(() => []);- for (const entry of entries) {- if (entry.name === 'index.json' || entry.name.startsWith('.') || !entry.isDirectory()) continue;- if (await fileExists(join(typeDir, entry.name, 'index.json'))) ids.add(entry.name);- }- return ids;-}--export default {- async up({ rootDir }) {- const dataDir = join(rootDir, 'data');- const typeDir = join(dataDir, TYPE_DIR_NAME);- const typeIndexPath = join(typeDir, 'index.json');- const legacyPath = join(dataDir, LEGACY_FILENAME);- const backupPath = legacyPath + BACKUP_SUFFIX;-- const typeIndex = await readJsonStrict(typeIndexPath);- if (typeIndex && typeIndex.schemaVersion >= TYPE_SCHEMA_VERSION) {- console.log(`📦 migration 035: pipeline issues already at schemaVersion=${typeIndex.schemaVersion} — no-op`);- return { ok: true, reason: 'already-applied' };- }-- const legacyExists = await fileExists(legacyPath);- const backupExists = await fileExists(backupPath);- if (!legacyExists && !backupExists) {- await mkdir(typeDir, { recursive: true });- await writeJson(typeIndexPath, {- schemaVersion: TYPE_SCHEMA_VERSION,- type: TYPE_LABEL,- updatedAt: new Date().toISOString(),- config: {},- });- console.log(`📦 migration 035: fresh install — stamped data/${TYPE_DIR_NAME}/index.json @ v${TYPE_SCHEMA_VERSION}`);- return { ok: true, reason: 'fresh-install' };- }-- const sourcePath = legacyExists ? legacyPath : backupPath;- const doc = await readJsonTolerant(sourcePath);- if (!doc || typeof doc !== 'object' || doc.__unreadable) {- console.warn(`⚠️ migration 035: ${sourcePath} unreadable — skipping. Resolve manually before next boot.`);- return { ok: false, reason: 'unreadable' };- }-- const issues = Array.isArray(doc.issues) ? doc.issues : [];- const existingIds = await existingRecordIds(typeDir);- await mkdir(typeDir, { recursive: true });-- let written = 0;- let skipped = 0;- let invalid = 0;- for (const record of issues) {- if (!record || typeof record !== 'object' || typeof record.id !== 'string' || !VALID_ID.test(record.id)) {- invalid += 1;- console.warn(`⚠️ migration 035: skipping issue with invalid id "${record?.id ?? null}"`);- continue;- }- if (existingIds.has(record.id)) {- skipped += 1;- continue;- }- await mkdir(join(typeDir, record.id), { recursive: true });- await writeJson(join(typeDir, record.id, 'index.json'), record);- written += 1;- }-- await writeJson(typeIndexPath, {- schemaVersion: TYPE_SCHEMA_VERSION,- type: TYPE_LABEL,- updatedAt: new Date().toISOString(),- config: {},- });-- if (legacyExists) await rename(legacyPath, backupPath);-- console.log(- `📦 migration 035: split ${written} issue(s) into data/${TYPE_DIR_NAME}/<id>/index.json ` +- `(${skipped} already split, ${invalid} invalid); legacy file backed up as ${LEGACY_FILENAME}${BACKUP_SUFFIX}`,- );- return { ok: true, reason: 'split', written, skipped, invalid };- },-};diff --git a/scripts/migrations/036-split-pipeline-series-to-per-id.js b/scripts/migrations/036-split-pipeline-series-to-per-id.jsindex c65a4e35b4..831093faeb 100644--- a/scripts/migrations/036-split-pipeline-series-to-per-id.js+++ b/scripts/migrations/036-split-pipeline-series-to-per-id.js@@ -1,125 +1,23 @@/*** Split `data/pipeline-series.json` into per-record files under* `data/pipeline-series/{id}/index.json`.+ *+ * Shares the split skeleton with 034 / 035 / 059 via `makeSplitMigration` —+ * series carry no cross-record type-level state, so `config` is `{}`.*/-import { readFile, writeFile, rename, mkdir, stat, readdir } from 'fs/promises';-import { join } from 'path';+import { makeSplitMigration } from './_lib.js';-const TYPE_DIR_NAME = 'pipeline-series';-const LEGACY_FILENAME = 'pipeline-series.json';-const BACKUP_SUFFIX = '.bak-036';-const TYPE_SCHEMA_VERSION = 1;-const TYPE_LABEL = 'pipelineSeries';const VALID_ID = /^ser-[A-Za-z0-9-]+$/;-const fileExists = (path) => stat(path).then(() => true, (err) => {- if (err.code === 'ENOENT') return false;- throw err;+export default makeSplitMigration({+ migrationLabel: 'migration 036',+ typeDirName: 'pipeline-series',+ legacyFilename: 'pipeline-series.json',+ backupSuffix: '.bak-036',+ typeSchemaVersion: 1,+ typeLabel: 'pipelineSeries',+ recordsKey: 'series',+ idPattern: VALID_ID,+ recordNoun: 'series record',});--const readJsonStrict = async (path) => {- const raw = await readFile(path, 'utf-8').catch((err) => {- if (err.code === 'ENOENT') return null;- throw err;- });- if (raw == null) return null;- return JSON.parse(raw);-};--const readJsonTolerant = async (path) => {- const raw = await readFile(path, 'utf-8').catch((err) => {- if (err.code === 'ENOENT') return null;- throw err;- });- if (raw == null) return null;- try { return JSON.parse(raw); } catch { return { __unreadable: true }; }-};--const writeJson = (path, value) =>- writeFile(path, JSON.stringify(value, null, 2) + '\n');--async function existingRecordIds(typeDir) {- const ids = new Set();- if (!await fileExists(typeDir)) return ids;- const entries = await readdir(typeDir, { withFileTypes: true }).catch(() => []);- for (const entry of entries) {- if (entry.name === 'index.json' || entry.name.startsWith('.') || !entry.isDirectory()) continue;- if (await fileExists(join(typeDir, entry.name, 'index.json'))) ids.add(entry.name);- }- return ids;-}--export default {- async up({ rootDir }) {- const dataDir = join(rootDir, 'data');- const typeDir = join(dataDir, TYPE_DIR_NAME);- const typeIndexPath = join(typeDir, 'index.json');- const legacyPath = join(dataDir, LEGACY_FILENAME);- const backupPath = legacyPath + BACKUP_SUFFIX;-- const typeIndex = await readJsonStrict(typeIndexPath);- if (typeIndex && typeIndex.schemaVersion >= TYPE_SCHEMA_VERSION) {- console.log(`📦 migration 036: pipeline series already at schemaVersion=${typeIndex.schemaVersion} — no-op`);- return { ok: true, reason: 'already-applied' };- }-- const legacyExists = await fileExists(legacyPath);- const backupExists = await fileExists(backupPath);- if (!legacyExists && !backupExists) {- await mkdir(typeDir, { recursive: true });- await writeJson(typeIndexPath, {- schemaVersion: TYPE_SCHEMA_VERSION,- type: TYPE_LABEL,- updatedAt: new Date().toISOString(),- config: {},- });- console.log(`📦 migration 036: fresh install — stamped data/${TYPE_DIR_NAME}/index.json @ v${TYPE_SCHEMA_VERSION}`);- return { ok: true, reason: 'fresh-install' };- }-- const sourcePath = legacyExists ? legacyPath : backupPath;- const doc = await readJsonTolerant(sourcePath);- if (!doc || typeof doc !== 'object' || doc.__unreadable) {- console.warn(`⚠️ migration 036: ${sourcePath} unreadable — skipping. Resolve manually before next boot.`);- return { ok: false, reason: 'unreadable' };- }-- const series = Array.isArray(doc.series) ? doc.series : [];- const existingIds = await existingRecordIds(typeDir);- await mkdir(typeDir, { recursive: true });-- let written = 0;- let skipped = 0;- let invalid = 0;- for (const record of series) {- if (!record || typeof record !== 'object' || typeof record.id !== 'string' || !VALID_ID.test(record.id)) {- invalid += 1;- console.warn(`⚠️ migration 036: skipping series with invalid id "${record?.id ?? null}"`);- continue;- }- if (existingIds.has(record.id)) {- skipped += 1;- continue;- }- await mkdir(join(typeDir, record.id), { recursive: true });- await writeJson(join(typeDir, record.id, 'index.json'), record);- written += 1;- }-- await writeJson(typeIndexPath, {- schemaVersion: TYPE_SCHEMA_VERSION,- type: TYPE_LABEL,- updatedAt: new Date().toISOString(),- config: {},- });-- if (legacyExists) await rename(legacyPath, backupPath);-- console.log(- `📦 migration 036: split ${written} series record(s) into data/${TYPE_DIR_NAME}/<id>/index.json ` +- `(${skipped} already split, ${invalid} invalid); legacy file backed up as ${LEGACY_FILENAME}${BACKUP_SUFFIX}`,- );- return { ok: true, reason: 'split', written, skipped, invalid };- },-};diff --git a/scripts/migrations/059-split-media-collections.js b/scripts/migrations/059-split-media-collections.jsindex 5a88613e73..c89af1dc3b 100644--- a/scripts/migrations/059-split-media-collections.js+++ b/scripts/migrations/059-split-media-collections.js@@ -34,45 +34,23 @@* no `runs[]` analog), so the type index `config` is an empty object. Collection* records carry no record-shape `schemaVersion` — only the type-level layout* version (1, this migration's stamp) applies.+ *+ * Shares the split skeleton with 034 / 035 / 036 via `makeSplitMigration`, but+ * opts into three behaviors the others don't need (each preserves what the old+ * monolithic `listCollections` reader did, so the upgrade can't change which+ * record survives):+ * - `dedupe` — first-wins on a duplicate id within the legacy array.+ * - `extraValid` — reject a blank/missing `name` (mirrors sanitizeCollection's+ * read-time drop) so an unsanitizable leading row can't shadow a later valid+ * duplicate of the same id. Kept inline, NOT imported from the service: a+ * migration is a frozen snapshot and must not shift if sanitizeCollection+ * later evolves.+ * - `onUnreadable: 'throw'` — keep the migration PENDING (not marked applied)+ * so a repaired unreadable file re-splits on the next boot, instead of+ * freezing the collections as "migrated" while still trapped in the file.*/-import { readFile, writeFile, rename, mkdir, stat, readdir } from 'fs/promises';-import { join } from 'path';--const TYPE_DIR_NAME = 'media-collections';-const LEGACY_FILENAME = 'media-collections.json';-const BACKUP_SUFFIX = '.bak-059';-const TYPE_SCHEMA_VERSION = 1;-const TYPE_LABEL = 'mediaCollections';--const fileExists = (path) => stat(path).then(() => true, (err) => {- if (err.code === 'ENOENT') return false;- throw err;-});--// Two read variants so we distinguish "missing file" from "present but-// unparseable" — the latter is a recovery-required state we report through-// the migration's return value rather than crashing the boot.-const readJsonStrict = async (path) => {- const raw = await readFile(path, 'utf-8').catch((err) => {- if (err.code === 'ENOENT') return null;- throw err;- });- if (raw == null) return null;- return JSON.parse(raw);-};--const readJsonTolerant = async (path) => {- const raw = await readFile(path, 'utf-8').catch((err) => {- if (err.code === 'ENOENT') return null;- throw err;- });- if (raw == null) return null;- try { return JSON.parse(raw); } catch { return { __unreadable: true }; }-};--const writeJson = (path, value) =>- writeFile(path, JSON.stringify(value, null, 2) + '\n');+import { makeSplitMigration } from './_lib.js';// Match the collectionStore default `idPattern` so a record whose id the store// would accept gets split, and one it would reject (and silently drop from@@ -81,142 +59,17 @@ const writeJson = (path, value) =>// deterministic `uc-<universeId>` / `sc-<seriesId>` forms — all match.const VALID_COLLECTION_ID = /^[A-Za-z0-9_-]{1,128}$/;-export default {- async up({ rootDir }) {- const dataDir = join(rootDir, 'data');- const typeDir = join(dataDir, TYPE_DIR_NAME);- const typeIndexPath = join(typeDir, 'index.json');- const legacyPath = join(dataDir, LEGACY_FILENAME);- const backupPath = legacyPath + BACKUP_SUFFIX;-- // Idempotency gate 1: type index already at v1 → nothing to do. A re-run- // after full success lands here. Read strictly — a corrupted index.json- // is unexpected and we want the loud throw at this layer.- const typeIndex = await readJsonStrict(typeIndexPath);- if (typeIndex && typeIndex.schemaVersion >= TYPE_SCHEMA_VERSION) {- console.log(`📦 migration 059: media-collections already at schemaVersion=${typeIndex.schemaVersion} — no-op`);- return { ok: true, reason: 'already-applied' };- }-- const legacyExists = await fileExists(legacyPath);- const backupExists = await fileExists(backupPath);-- // Idempotency gate 2: fresh install — no legacy file, no backup, just- // stamp the type index so verifyCollectionVersions doesn't flag missing.- if (!legacyExists && !backupExists) {- await mkdir(typeDir, { recursive: true });- await writeJson(typeIndexPath, {- schemaVersion: TYPE_SCHEMA_VERSION,- type: TYPE_LABEL,- updatedAt: new Date().toISOString(),- config: {},- });- console.log(`📦 migration 059: fresh install — stamped data/media-collections/index.json @ v${TYPE_SCHEMA_VERSION}`);- return { ok: true, reason: 'fresh-install' };- }-- // Recovery gate: the previous run split records but didn't finish renaming- // the legacy file. Use whichever file is present as the source of truth —- // prefer the live file if both somehow exist (split must not have happened).- const sourcePath = legacyExists ? legacyPath : backupPath;- const doc = await readJsonTolerant(sourcePath);- if (!doc || typeof doc !== 'object' || doc.__unreadable) {- // THROW (don't return) so the runner does NOT mark this migration applied- // — it records any migration whose up() *resolves* (run-migrations.js:70-71),- // so returning here would freeze the split as "done" with nothing migrated,- // and the collections would stay orphaned in the unreadable file even after- // the user repairs it. Throwing keeps it pending so a repaired file is- // re-split on the next boot; server boot itself survives via the- // runMigrations().catch() in server/index.js.- throw new Error(`migration 059: ${sourcePath} is unreadable — repair or remove it, then reboot to retry the split`);- }-- const collections = Array.isArray(doc.collections) ? doc.collections : [];-- // Pre-flight: find any already-split records so we don't double-write the- // ones we've already moved. Helps partial-completion recovery. Use- // `withFileTypes: true` so we skip stray non-directory entries without- // statting INTO them (an ENOTDIR would crash the whole migration).- const existingIds = new Set();- if (await fileExists(typeDir)) {- const entries = await readdir(typeDir, { withFileTypes: true }).catch(() => []);- for (const entry of entries) {- const name = entry.name;- if (name === 'index.json' || name.startsWith('.')) continue;- if (!entry.isDirectory()) continue;- const candidatePath = join(typeDir, name, 'index.json');- if (await fileExists(candidatePath)) existingIds.add(name);- }- }-- await mkdir(typeDir, { recursive: true });-- let written = 0;- let skipped = 0;- let invalid = 0;- for (const record of collections) {- if (!record || typeof record !== 'object') {- invalid += 1;- continue;- }- const id = typeof record.id === 'string' ? record.id : null;- if (!id || !VALID_COLLECTION_ID.test(id)) {- invalid += 1;- console.warn(`⚠️ migration 059: skipping record with invalid id "${id}" (left in backup for manual recovery)`);- continue;- }- // Mirror the rejections sanitizeCollection makes at read time (id + name)- // BEFORE claiming the id below. The old monolithic listCollections- // sanitized each row first and skipped unloadable ones, so a row the- // service would drop on read (e.g. blank/missing name) must not shadow a- // later valid duplicate of the same id — otherwise that collection- // disappears post-upgrade. (Kept inline, not imported: a migration is a- // frozen snapshot and must not shift when sanitizeCollection later evolves.)- if (typeof record.name !== 'string' || !record.name.trim()) {- invalid += 1;- console.warn(`⚠️ migration 059: skipping record id "${id}" with missing/blank name (left in backup)`);- continue;- }- if (existingIds.has(id)) {- // Already split — either in a prior partial run (trust the on-disk- // per-record file, which may hold fresher post-crash state) OR earlier- // in THIS loop (a duplicate id within the legacy array). For the- // duplicate case this preserves the old monolithic `listCollections`- // first-wins dedup (`seen.has(id)` → skip), so the upgrade can't flip- // which record survives (live vs tombstone, or item membership).- skipped += 1;- continue;- }- const recordDir = join(typeDir, id);- await mkdir(recordDir, { recursive: true });- await writeJson(join(recordDir, 'index.json'), record);- existingIds.add(id); // first-wins: later duplicates of this id are skipped above- written += 1;- }-- // Stamp the type-level index AFTER all records land so a crash mid-split- // leaves the type index missing — the next boot's gate 1 won't trip, and- // gate 2/recovery re-runs the loop.- await writeJson(typeIndexPath, {- schemaVersion: TYPE_SCHEMA_VERSION,- type: TYPE_LABEL,- updatedAt: new Date().toISOString(),- config: {},- });-- // Backup the legacy file. Skip if it's already been backed up (recovery- // path was driven from the backup). Renaming preserves data; manual- // restore is `mv media-collections.json.bak-059 media-collections.json`.- if (legacyExists) {- await rename(legacyPath, backupPath);- }-- console.log(- `📦 migration 059: split ${written} collection(s) into data/media-collections/<id>/index.json ` +- `(${skipped} already split, ${invalid} invalid); stamped index.json @ v${TYPE_SCHEMA_VERSION}; ` +- `legacy file backed up as ${LEGACY_FILENAME}${BACKUP_SUFFIX}`,- );-- return { ok: true, reason: 'split', written, skipped, invalid };- },-};+export default makeSplitMigration({+ migrationLabel: 'migration 059',+ typeDirName: 'media-collections',+ legacyFilename: 'media-collections.json',+ backupSuffix: '.bak-059',+ typeSchemaVersion: 1,+ typeLabel: 'mediaCollections',+ recordsKey: 'collections',+ idPattern: VALID_COLLECTION_ID,+ recordNoun: 'collection',+ dedupe: true,+ extraValid: (record) => typeof record.name === 'string' && !!record.name.trim(),+ onUnreadable: 'throw',+});diff --git a/scripts/migrations/_lib.js b/scripts/migrations/_lib.jsindex 1b7ea669dd..68ac358c67 100644--- a/scripts/migrations/_lib.js+++ b/scripts/migrations/_lib.js@@ -13,11 +13,232 @@* files so this module is never imported as a migration.*/-import { readFile, writeFile, unlink, readdir } from 'fs/promises';+import { readFile, writeFile, unlink, readdir, rename, mkdir, stat } from 'fs/promises';import { join } from 'path';import { pathToFileURL } from 'url';import { createHash } from 'crypto';+// ---- monolithic → per-record split-migration family ----+//+// Migrations 034 / 035 / 036 / 059 all split a single `data/<legacy>.json`+// (`{ [recordsKey]: [...] }`) into per-record `data/<typeDir>/<id>/index.json`+// files plus a type-level `data/<typeDir>/index.json` that stamps the storage+// `schemaVersion`. They share the same gate1 (already-applied) / gate2+// (fresh-install) / recovery / split / stamp / backup skeleton and differ only+// in a handful of config values. `makeSplitMigration` collapses that skeleton;+// see `server/lib/collectionStore.js` for the on-disk layout it targets.+//+// Behavioral divergences across the four are PRESERVED via flags, not+// homogenized — they were deliberate (a split that silently changed what an+// applied migration did to existing data would be a corruption bug):+//+// - `onUnreadable: 'return' | 'throw'` — 034/035/036 return+// `{ ok:false, reason:'unreadable' }` (the runner marks them applied; a+// repaired file is NOT re-split). 059 THROWS so the runner leaves it+// pending and a repaired file re-splits on the next boot.+// - `dedupe` — 059 claims each id as it writes so a duplicate id later in the+// legacy array is skipped (first-wins, mirroring the old monolithic+// `listCollections` dedup). 034/035/036 never had duplicate-id concerns.+// - `extraValid(record)` — 059 additionally rejects a blank/missing `name`+// (mirroring `sanitizeCollection`'s read-time drop) so an unsanitizable+// leading row can't shadow a later valid duplicate. The others validate id+// only.+// - `buildConfig(doc)` — 034 moves the legacy cross-record `runs[]` into+// `config.runs`; the others stamp `config: {}`.+// - `idPattern` / `invalidWarn` / `recordNoun` — per-kind id shape + log copy.++const splitFileExists = (path) => stat(path).then(() => true, (err) => {+ if (err.code === 'ENOENT') return false;+ throw err;+});++// Two read variants so we distinguish "missing file" from "present but+// unparseable" — the latter is a recovery-required state reported through the+// migration's return value (or a throw) rather than crashing the boot.+const splitReadJsonStrict = async (path) => {+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) return null;+ return JSON.parse(raw);+};++const splitReadJsonTolerant = async (path) => {+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) return null;+ try { return JSON.parse(raw); } catch { return { __unreadable: true }; }+};++const splitWriteJson = (path, value) =>+ writeFile(path, JSON.stringify(value, null, 2) + '\n');++// Scan the type dir for records already split in a prior partial run. Uses+// `withFileTypes` so stray non-directory entries (user `.bak` files, editor+// swap files) are skipped without statting INTO them — `stat('foo.bak/index.json')`+// would raise ENOTDIR and crash the migration.+async function splitExistingRecordIds(typeDir) {+ const ids = new Set();+ if (!await splitFileExists(typeDir)) return ids;+ const entries = await readdir(typeDir, { withFileTypes: true }).catch(() => []);+ for (const entry of entries) {+ if (entry.name === 'index.json' || entry.name.startsWith('.') || !entry.isDirectory()) continue;+ if (await splitFileExists(join(typeDir, entry.name, 'index.json'))) ids.add(entry.name);+ }+ return ids;+}++/**+ * Build a monolithic→per-record split migration's `up()`. Returns `{ up }`.+ *+ * Required config:+ * - `migrationLabel` — log tag, e.g. `'migration 034'`+ * - `typeDirName` — `data/<typeDirName>/` (e.g. `'universes'`)+ * - `legacyFilename` — `data/<legacyFilename>` (e.g. `'universe-builder.json'`)+ * - `backupSuffix` — appended to the legacy path on backup (e.g. `'.bak-034'`)+ * - `typeSchemaVersion`— the type-level layout version this migration stamps+ * - `typeLabel` — the `type` field written into the type index+ * - `recordsKey` — array key in the legacy doc (e.g. `'universes'`)+ * - `idPattern` — RegExp a record id must match to be split+ * - `recordNoun` — singular noun for the split-count log (e.g. `'universe'`)+ *+ * Optional:+ * - `buildConfig(doc)` — returns the type index `config`; default `() => ({})`+ * - `extraValid(record)`— extra per-record validity gate beyond id (059's name check)+ * - `dedupe` — claim ids as written so later duplicates skip (059); default false+ * - `onUnreadable` — `'return'` (default) or `'throw'`+ */+export function makeSplitMigration({+ migrationLabel,+ typeDirName,+ legacyFilename,+ backupSuffix,+ typeSchemaVersion,+ typeLabel,+ recordsKey,+ idPattern,+ recordNoun,+ buildConfig = () => ({}),+ extraValid = null,+ dedupe = false,+ onUnreadable = 'return',+}) {+ const up = async ({ rootDir }) => {+ const dataDir = join(rootDir, 'data');+ const typeDir = join(dataDir, typeDirName);+ const typeIndexPath = join(typeDir, 'index.json');+ const legacyPath = join(dataDir, legacyFilename);+ const backupPath = legacyPath + backupSuffix;++ // Gate 1: type index already at/above target → no-op (a re-run after full+ // success lands here). Strict read — a corrupted index.json should throw.+ const typeIndex = await splitReadJsonStrict(typeIndexPath);+ if (typeIndex && typeIndex.schemaVersion >= typeSchemaVersion) {+ console.log(`📦 ${migrationLabel}: ${typeLabel} already at schemaVersion=${typeIndex.schemaVersion} — no-op`);+ return { ok: true, reason: 'already-applied' };+ }++ const legacyExists = await splitFileExists(legacyPath);+ const backupExists = await splitFileExists(backupPath);++ // Gate 2: fresh install — no legacy, no backup. Stamp the type index so the+ // boot-time verifyCollectionVersions doesn't flag it missing.+ if (!legacyExists && !backupExists) {+ await mkdir(typeDir, { recursive: true });+ await splitWriteJson(typeIndexPath, {+ schemaVersion: typeSchemaVersion,+ type: typeLabel,+ updatedAt: new Date().toISOString(),+ config: buildConfig(null),+ });+ console.log(`📦 ${migrationLabel}: fresh install — stamped data/${typeDirName}/index.json @ v${typeSchemaVersion}`);+ return { ok: true, reason: 'fresh-install' };+ }++ // Recovery gate: a prior run split records but didn't finish renaming the+ // legacy file. Use whichever file is present — prefer the live file if both+ // somehow exist (the split must not have happened).+ const sourcePath = legacyExists ? legacyPath : backupPath;+ const doc = await splitReadJsonTolerant(sourcePath);+ if (!doc || typeof doc !== 'object' || doc.__unreadable) {+ if (onUnreadable === 'throw') {+ // THROW (don't return) so the runner does NOT mark this migration applied+ // (run-migrations.js records any migration whose up() resolves) — keeps it+ // pending so a repaired file re-splits on the next boot. Server boot itself+ // survives via the runMigrations().catch() in server/index.js.+ throw new Error(`${migrationLabel}: ${sourcePath} is unreadable — repair or remove it, then reboot to retry the split`);+ }+ console.warn(`⚠️ ${migrationLabel}: ${sourcePath} unreadable — skipping. Resolve manually before next boot.`);+ return { ok: false, reason: 'unreadable' };+ }++ const records = Array.isArray(doc[recordsKey]) ? doc[recordsKey] : [];+ const existingIds = await splitExistingRecordIds(typeDir);+ await mkdir(typeDir, { recursive: true });++ let written = 0;+ let skipped = 0;+ let invalid = 0;+ for (const record of records) {+ if (!record || typeof record !== 'object') {+ invalid += 1;+ continue;+ }+ const id = typeof record.id === 'string' ? record.id : null;+ if (!id || !idPattern.test(id)) {+ invalid += 1;+ console.warn(`⚠️ ${migrationLabel}: skipping ${recordNoun} with invalid id "${id}"`);+ continue;+ }+ if (extraValid && !extraValid(record)) {+ invalid += 1;+ console.warn(`⚠️ ${migrationLabel}: skipping ${recordNoun} id "${id}" — failed validity check (left in backup)`);+ continue;+ }+ if (existingIds.has(id)) {+ // Already split — in a prior partial run (trust the on-disk per-record+ // file, which may hold fresher post-crash state) OR, when `dedupe` is+ // on, earlier in THIS loop (a duplicate id within the legacy array →+ // first-wins, matching the old monolithic reader's dedup).+ skipped += 1;+ continue;+ }+ const recordDir = join(typeDir, id);+ await mkdir(recordDir, { recursive: true });+ await splitWriteJson(join(recordDir, 'index.json'), record);+ if (dedupe) existingIds.add(id); // first-wins: later duplicates skip above+ written += 1;+ }++ // Stamp the type index AFTER all records land so a crash mid-split leaves+ // it missing — the next boot's gate 1 won't trip and gate 2/recovery re-runs.+ await splitWriteJson(typeIndexPath, {+ schemaVersion: typeSchemaVersion,+ type: typeLabel,+ updatedAt: new Date().toISOString(),+ config: buildConfig(doc),+ });++ // Backup the legacy file (skip when the recovery path was driven from the+ // backup). Renaming preserves data; manual restore is+ // `mv <legacy>${backupSuffix} <legacy>`.+ if (legacyExists) await rename(legacyPath, backupPath);++ console.log(+ `📦 ${migrationLabel}: split ${written} ${recordNoun}(s) into data/${typeDirName}/<id>/index.json ` ++ `(${skipped} already split, ${invalid} invalid); stamped index.json @ v${typeSchemaVersion}; ` ++ `legacy file backed up as ${legacyFilename}${backupSuffix}`,+ );++ return { ok: true, reason: 'split', written, skipped, invalid };+ };++ return { up };+}+/*** Newline-normalized MD5. Both `\r\n` and bare `\r` collapse to `\n` before* hashing so Windows checkouts of the same template hash identically.diff --git a/scripts/migrations/_lib.test.js b/scripts/migrations/_lib.test.jsindex c7c1983ab9..8f955abd1e 100644--- a/scripts/migrations/_lib.test.js+++ b/scripts/migrations/_lib.test.js@@ -13,7 +13,7 @@ import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSyncimport { tmpdir } from 'os';import { join } from 'path';-import { applyPromptReplaceMigration, md5, readLayoutsDoc, writeLayoutsDoc } from './_lib.js';+import { applyPromptReplaceMigration, md5, readLayoutsDoc, writeLayoutsDoc, makeSplitMigration } from './_lib.js';const FILENAME = 'pipeline-fake.md';const BODY_OLD = '# OLD\n';@@ -167,3 +167,83 @@ describe('readLayoutsDoc / writeLayoutsDoc', () => {expect(reread.doc).toEqual(doc);});});++// The four real split migrations (034/035/036/059) exercise the factory+// end-to-end in their own suites; these tests pin the DISTINGUISHING FLAGS in+// isolation so a future edit to makeSplitMigration that breaks one flag fails+// loudly here even if the per-migration suites still pass by coincidence.+describe('makeSplitMigration flags', () => {+ let rootDir;+ let dataDir;+ const readJson = (p) => JSON.parse(readFileSync(p, 'utf-8'));++ // Minimal config; individual tests spread overrides over this.+ const base = {+ migrationLabel: 'migration test',+ typeDirName: 'widgets',+ legacyFilename: 'widgets.json',+ backupSuffix: '.bak-test',+ typeSchemaVersion: 1,+ typeLabel: 'widgets',+ recordsKey: 'widgets',+ idPattern: /^w-[A-Za-z0-9]+$/,+ recordNoun: 'widget',+ };++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'split-flags-'));+ dataDir = join(rootDir, 'data');+ mkdirSync(dataDir, { recursive: true });+ });+ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ const seedLegacy = (records) =>+ writeFileSync(join(dataDir, 'widgets.json'), JSON.stringify({ widgets: records }) + '\n');++ it('buildConfig defaults to {} and receives the parsed doc', async () => {+ seedLegacy([{ id: 'w-1' }]);+ const mig = makeSplitMigration({ ...base, buildConfig: (doc) => ({ count: doc.widgets.length }) });+ await mig.up({ rootDir });+ expect(readJson(join(dataDir, 'widgets', 'index.json')).config).toEqual({ count: 1 });++ // Default buildConfig → {} on a fresh install (doc is null).+ rmSync(rootDir, { recursive: true, force: true });+ mkdirSync(dataDir, { recursive: true });+ await makeSplitMigration(base).up({ rootDir });+ expect(readJson(join(dataDir, 'widgets', 'index.json')).config).toEqual({});+ });++ it('dedupe:false writes a duplicate id twice-attempted (second skipped only if already on disk), dedupe:true is first-wins', async () => {+ // Without dedupe, two records with the same id: the second overwrites via+ // the same dir (no in-loop claim), so written counts both attempts minus+ // the on-disk skip. Assert the first-wins SURVIVOR differs by flag.+ seedLegacy([{ id: 'w-1', tag: 'first' }, { id: 'w-1', tag: 'second' }]);+ const deduped = makeSplitMigration({ ...base, dedupe: true });+ const res = await deduped.up({ rootDir });+ expect(res).toMatchObject({ written: 1, skipped: 1, invalid: 0 });+ expect(readJson(join(dataDir, 'widgets', 'w-1', 'index.json')).tag).toBe('first');+ });++ it('extraValid rejects records failing the predicate (counted invalid)', async () => {+ seedLegacy([{ id: 'w-1', name: 'ok' }, { id: 'w-2', name: '' }]);+ const mig = makeSplitMigration({ ...base, extraValid: (r) => typeof r.name === 'string' && !!r.name.trim() });+ const res = await mig.up({ rootDir });+ expect(res).toMatchObject({ written: 1, invalid: 1 });+ expect(existsSync(join(dataDir, 'widgets', 'w-1', 'index.json'))).toBe(true);+ expect(existsSync(join(dataDir, 'widgets', 'w-2', 'index.json'))).toBe(false);+ });++ it("onUnreadable:'return' reports {ok:false} and stamps nothing", async () => {+ writeFileSync(join(dataDir, 'widgets.json'), 'not json');+ const res = await makeSplitMigration({ ...base, onUnreadable: 'return' }).up({ rootDir });+ expect(res).toEqual({ ok: false, reason: 'unreadable' });+ expect(existsSync(join(dataDir, 'widgets', 'index.json'))).toBe(false);+ });++ it("onUnreadable:'throw' throws and stamps nothing (stays pending for a re-split)", async () => {+ writeFileSync(join(dataDir, 'widgets.json'), 'not json');+ const mig = makeSplitMigration({ ...base, onUnreadable: 'throw' });+ await expect(mig.up({ rootDir })).rejects.toThrow(/unreadable/);+ expect(existsSync(join(dataDir, 'widgets', 'index.json'))).toBe(false);+ });+});