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([med-sharing-server-services-sharing-version-js]): salvage pre-B.4 series canon on import

[._.]/ Adam Eivy631514cfffd0
diff --git a/server/services/pipeline/migrateSeriesCanon.js b/server/services/pipeline/migrateSeriesCanon.js
index f680f95655..28cef4e02b 100644
--- a/server/services/pipeline/migrateSeriesCanon.js
+++ b/server/services/pipeline/migrateSeriesCanon.js
@@ -32,95 +32,134 @@ const KIND_BY_FIELD = Object.freeze(
Object.fromEntries(Object.entries(BIBLE_FIELD).map(([kind, field]) => [field, kind])),
);
+const formatCounts = (counts) =>
+ Object.entries(counts).map(([k, n]) => `${n} ${k}`).join(', ');
+
+/**
+ * Move a single series record's legacy `characters/settings/objects` arrays
+ * into its linked (or freshly-created) universe. Pure orchestrator: does NOT
+ * write the series itself — the caller decides whether to call `updateSeries`
+ * (CLI batch) or stamp `universeId` onto an in-memory record (sharing
+ * importer) so `sanitizeSeries` doesn't strip the new link before the record
+ * lands.
+ *
+ * Returns:
+ * - `perKindSeen` — raw incoming counts per field on the source record.
+ * - `perKindApplied` — incoming counts only where the universe-side patch
+ * actually grew or changed (zero when the universe
+ * already had every entry).
+ * - `universeId` — the universe the series should be linked to (existing
+ * or freshly-created), null when the helper couldn't
+ * resolve one (dry-run orphan, missing universe).
+ * - `universeCreated` — true when this call created a new orphan universe.
+ * - `migrated` — true when the universe was actually patched.
+ * - `skipped` — `'no-legacy' | 'missing-universe' | 'dry-run-orphan' | null`.
+ */
+export async function applyLegacySeriesCanonToUniverse(series, { dryRun = false, log = console.log } = {}) {
+ // Coalesce the pre-022 `settings[]` alias onto `places[]` so peers that
+ // shipped from a pre-rename install still migrate cleanly. Local disk is
+ // post-rename (migration 022 ran at setup), so this is a no-op for the
+ // CLI batch and only carries weight for cross-peer share-bucket imports.
+ const incomingPlaces = Array.isArray(series.places) && series.places.length > 0
+ ? series.places
+ : (Array.isArray(series.settings) ? series.settings : []);
+ const normalized = { ...series, places: incomingPlaces };
+
+ const perKindSeen = {
+ characters: Array.isArray(normalized.characters) ? normalized.characters.length : 0,
+ places: incomingPlaces.length,
+ objects: Array.isArray(normalized.objects) ? normalized.objects.length : 0,
+ };
+ const perKindApplied = { characters: 0, places: 0, objects: 0 };
+ if (perKindSeen.characters + perKindSeen.places + perKindSeen.objects === 0) {
+ return { perKindSeen, perKindApplied, universeId: normalized.universeId || null, universeCreated: false, migrated: false, skipped: 'no-legacy' };
+ }
+ series = normalized;
+
+ let universeId = series.universeId;
+ let universeCreated = false;
+ if (!universeId) {
+ if (dryRun) {
+ log(`📋 [dry-run] Would create universe for orphan series "${series.name}" (${series.id})`);
+ return { perKindSeen, perKindApplied, universeId: null, universeCreated: false, migrated: false, skipped: 'dry-run-orphan' };
+ }
+ const newUniverse = await createUniverse({
+ name: `${series.name} (auto-migrated)`,
+ starterPrompt: series.logline || series.premise?.slice(0, 500) || '',
+ });
+ universeId = newUniverse.id;
+ universeCreated = true;
+ log(`🌌 Created universe "${newUniverse.name}" (${newUniverse.id}) for orphan series "${series.name}"`);
+ }
+
+ const universe = await getUniverse(universeId).catch(() => null);
+ if (!universe) {
+ log(`⚠️ Series "${series.name}" links to missing universe ${universeId} — skipping`);
+ return { perKindSeen, perKindApplied, universeId, universeCreated, migrated: false, skipped: 'missing-universe' };
+ }
+
+ const patch = {};
+ for (const [field, kind] of Object.entries(KIND_BY_FIELD)) {
+ const incoming = Array.isArray(series[field]) ? series[field] : [];
+ if (incoming.length === 0) continue;
+ // mergeExtractedBible mutates its first arg (pushes new entries into the
+ // array, then sorts in place). Snapshot the universe side BEFORE the
+ // call so the diff check below sees the pre-merge length, and pass a
+ // clone so the live universe object isn't mutated mid-loop.
+ const before = Array.isArray(universe[field]) ? universe[field] : [];
+ // Mirror the live extract path's provenance (textStages.js +
+ // routes/pipeline.js): series-driven canon enters the universe as
+ // SERIES_EXTRACT with autoLock so a later AI refine/differentiate can't
+ // silently rewrite it. Without these opts the migrated entries default
+ // to source:'ai' + autoLock:false, leaving them one click away from
+ // being clobbered — the opposite of what the live path promises.
+ const merged = mergeExtractedBible([...before], incoming, kind, {
+ source: BIBLE_SOURCE.SERIES_EXTRACT,
+ autoLock: true,
+ sourceSeriesId: series.id,
+ });
+ if (merged.length > before.length || JSON.stringify(merged) !== JSON.stringify(before)) {
+ patch[field] = merged;
+ perKindApplied[field] = incoming.length;
+ }
+ }
+
+ let migrated = false;
+ if (Object.keys(patch).length > 0) {
+ if (dryRun) {
+ log(`📋 [dry-run] Would merge into universe "${universe.name}": ${formatCounts(perKindSeen)} from series "${series.name}"`);
+ } else {
+ await updateUniverse(universeId, patch);
+ migrated = true;
+ log(`✅ Migrated series "${series.name}" → universe "${universe.name}": ${formatCounts(perKindSeen)}`);
+ }
+ }
+
+ return { perKindSeen, perKindApplied, universeId, universeCreated, migrated, skipped: null };
+}
+
export async function migrateSeriesCanon({ dryRun = false, log = console.log } = {}) {
const { series: rawSeries } = await readRawSeriesState();
const series = Array.isArray(rawSeries) ? rawSeries : [];
- const summary = { seriesScanned: 0, seriesMigrated: 0, universesCreated: 0, perKind: { characters: 0, settings: 0, objects: 0 } };
+ const summary = { seriesScanned: 0, seriesMigrated: 0, universesCreated: 0, perKind: { characters: 0, places: 0, objects: 0 } };
for (const s of series) {
summary.seriesScanned += 1;
- const counts = {
- characters: Array.isArray(s.characters) ? s.characters.length : 0,
- settings: Array.isArray(s.settings) ? s.settings.length : 0,
- objects: Array.isArray(s.objects) ? s.objects.length : 0,
- };
- if (counts.characters + counts.settings + counts.objects === 0) continue;
-
// For orphan series, defer the link-to-universe write until AFTER the
// canon has landed in the universe. The link write strips the series'
// legacy `characters/settings/objects` (sanitizeSeries no longer
// round-trips them post-B.4), so a crash between linking and merging
- // would leave the series stripped + the new universe empty. Holding the
- // orphan-link variables here lets us flip the order at write time.
- let universeId = s.universeId;
- let pendingOrphanUniverse = null;
- if (!universeId) {
- if (dryRun) {
- log(`📋 [dry-run] Would create universe for orphan series "${s.name}" (${s.id})`);
- } else {
- const newUniverse = await createUniverse({
- name: `${s.name} (auto-migrated)`,
- starterPrompt: s.logline || s.premise?.slice(0, 500) || '',
- });
- pendingOrphanUniverse = newUniverse;
- universeId = newUniverse.id;
- // Count the universe at create-time so the trailing "created N
- // universe(s)" log stays accurate — even when a crash later strands
- // the link write, the universe really was created on disk.
- summary.universesCreated += 1;
- log(`🌌 Created universe "${newUniverse.name}" (${newUniverse.id}) for orphan series "${s.name}"`);
- }
- }
-
- const universe = await getUniverse(universeId).catch(() => null);
- if (!universe) {
- log(`⚠️ Series "${s.name}" links to missing universe ${universeId} — skipping`);
- continue;
- }
-
- const patch = {};
- for (const [field, kind] of Object.entries(KIND_BY_FIELD)) {
- const incoming = Array.isArray(s[field]) ? s[field] : [];
- if (incoming.length === 0) continue;
- // mergeExtractedBible mutates its first arg (pushes new entries into
- // the array, then sorts in place). Snapshot the universe side BEFORE
- // the call so the diff check below sees the pre-merge length, and
- // pass a clone so the live universe object isn't mutated mid-loop.
- const before = Array.isArray(universe[field]) ? universe[field] : [];
- // Mirror the live extract path's provenance (textStages.js +
- // routes/pipeline.js): series-driven canon enters the universe as
- // SERIES_EXTRACT with autoLock so a later AI refine/differentiate
- // can't silently rewrite it. Without these opts the migrated
- // entries default to source:'ai' + autoLock:false, leaving them one
- // click away from being clobbered — the opposite of what the live
- // path promises.
- const merged = mergeExtractedBible([...before], incoming, kind, {
- source: BIBLE_SOURCE.SERIES_EXTRACT,
- autoLock: true,
- sourceSeriesId: s.id,
- });
- if (merged.length > before.length || JSON.stringify(merged) !== JSON.stringify(before)) {
- patch[field] = merged;
- summary.perKind[field] += incoming.length;
- }
- }
-
- if (Object.keys(patch).length > 0) {
- if (dryRun) {
- log(`📋 [dry-run] Would merge into universe "${universe.name}": ${Object.entries(counts).map(([k, n]) => `${n} ${k}`).join(', ')} from series "${s.name}"`);
- } else {
- await updateUniverse(universeId, patch);
- summary.seriesMigrated += 1;
- log(`✅ Migrated series "${s.name}" → universe "${universe.name}": ${Object.entries(counts).map(([k, n]) => `${n} ${k}`).join(', ')}`);
- }
- }
-
- // Now that the universe carries the canon (or we've at least attempted
- // the write), link the orphan series. A crash earlier in the loop leaves
- // the universe in place to retry against; the series still carries its
- // legacy fields until this write lands.
- if (pendingOrphanUniverse && !dryRun) {
- await updateSeries(s.id, { universeId: pendingOrphanUniverse.id });
+ // would leave the series stripped + the new universe empty.
+ const r = await applyLegacySeriesCanonToUniverse(s, { dryRun, log });
+ if (r.skipped === 'no-legacy') continue;
+ if (r.universeCreated) summary.universesCreated += 1;
+ if (r.migrated) summary.seriesMigrated += 1;
+ for (const field of Object.keys(summary.perKind)) summary.perKind[field] += r.perKindApplied[field];
+ // Link the orphan series to the (now-populated) universe — sanitizeSeries
+ // strips legacy canon during this write, but it's already in the universe
+ // so the data isn't lost.
+ if (r.universeCreated && !dryRun) {
+ await updateSeries(s.id, { universeId: r.universeId });
}
}
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.js
index aedf115a4b..5b4a74e326 100644
--- a/server/services/sharing/importer.js
+++ b/server/services/sharing/importer.js
@@ -32,6 +32,7 @@ import { SHARING_SCHEMA_VERSION, isManifestCompatible } from './version.js';
import { insertSeriesWithId, updateSeries, getSeries } from '../pipeline/series.js';
import { insertIssueWithId, updateIssue, getIssue } from '../pipeline/issues.js';
import { insertUniverseWithId, updateUniverse, getUniverse } from '../universeBuilder.js';
+import { applyLegacySeriesCanonToUniverse } from '../pipeline/migrateSeriesCanon.js';
import { findOrCreateUniverseCollection, findOrCreateSeriesCollection, addItem as addCollectionItem, ERR_DUPLICATE as COLLECTION_ERR_DUPLICATE } from '../mediaCollections.js';
import { adoptImportedSubscription, withReexportSuppressed } from './subscriptions.js';
import { getInstanceId, UNKNOWN_INSTANCE_ID } from '../instances.js';
@@ -430,6 +431,31 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =
updateFn: (id, record) => updateUniverse(id, () => record),
});
}
+ // Pre-B.4 peers ship series records with legacy canon arrays (`characters /
+ // settings|places / objects`) that `sanitizeSeries` strips on insert —
+ // silent data loss for cross-peer imports authored before the B.4 schema
+ // teardown. Mirror the CLI migration here, so the canon lands on the
+ // linked (or freshly-created) universe before mergeOne writes the
+ // sanitized series. Both `settings` (pre-022) and `places` (post-022) wire
+ // names are recognized; the helper coalesces them. No-op for post-B.4
+ // records (the helper returns 'no-legacy' immediately).
+ for (const s of records.series) {
+ const hasLegacyCanon = ['characters', 'settings', 'places', 'objects']
+ .some((field) => Array.isArray(s[field]) && s[field].length > 0);
+ if (!hasLegacyCanon) continue;
+ const r = await applyLegacySeriesCanonToUniverse(s).catch((err) => {
+ console.log(`⚠️ sharing.importer: legacy series canon migration for ${s.id} failed: ${err.message}`);
+ return null;
+ });
+ // Stamp the freshly-created orphan universe id onto the in-memory record
+ // so the upcoming insertSeriesWithId call preserves the link. (We can't
+ // call updateSeries here like the CLI batch does — the series record
+ // hasn't been inserted yet.)
+ if (r?.universeCreated && r.universeId) {
+ s.universeId = r.universeId;
+ }
+ }
+
for (const s of records.series) {
await mergeOne({
kind: 'series', record: s, label: s.name,
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index 4597f3bff8..27c5d19b97 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -1260,6 +1260,131 @@ describe('sharing round-trip', () => {
expect(fs.readFileSync(join(tempData, 'images', 'legacy-v1.png'), 'utf-8')).toBe('V1BYTES');
});
+ it('migrates legacy series canon arrays into the linked universe on import (pre-B.4 peer)', async () => {
+ const bucket = await buckets.createBucket({ name: 'LegacyCanonBucket', path: tempBucket, mode: 'auto-merge' });
+ const fs = await import('fs');
+
+ // Local target universe — the migration writes incoming canon here.
+ const uni = await universeSvc.createUniverse({ name: 'Pre-B.4 Universe' });
+ expect((uni.characters || []).length).toBe(0);
+ expect((uni.places || []).length).toBe(0);
+ expect((uni.objects || []).length).toBe(0);
+
+ // Hand-write a pre-B.4 series record carrying the legacy canon arrays.
+ // `sanitizeSeries` would normally strip these on insert; the importer's
+ // pre-pass must fold them into the universe first.
+ const seriesId = 'ser-pre-b4-test';
+ const legacySeries = {
+ id: seriesId,
+ name: 'Pre-B.4 Series',
+ logline: 'Test',
+ premise: 'Test premise',
+ universeId: uni.id,
+ characters: [{ name: 'Echo', physicalDescription: 'tall' }],
+ // Pre-022 wire name — the helper coalesces this onto `places`.
+ settings: [{ name: 'The Foundry', slugline: 'INT. FOUNDRY - NIGHT' }],
+ objects: [{ name: 'Brass Key', description: 'opens the gate' }],
+ createdAt: '2026-05-01T00:00:00.000Z',
+ updatedAt: '2026-05-01T00:00:00.000Z',
+ };
+ mkdirSync(join(tempBucket, 'records', 'series'), { recursive: true });
+ writeFileSync(
+ join(tempBucket, 'records', 'series', `${seriesId}.json`),
+ JSON.stringify(legacySeries),
+ );
+
+ const manifest = {
+ id: 'mfst-pre-b4',
+ schemaVersion: 1,
+ sharingSchemaVersion: 1,
+ producedByVersion: '1.0.0',
+ createdAt: new Date().toISOString(),
+ kind: 'series',
+ senderInstanceId: 'pre-b4-peer',
+ source: 'Pre B.4 Peer',
+ sourceBio: null,
+ bucketId: bucket.id,
+ bucketName: bucket.name,
+ recordIds: [seriesId],
+ assetRefs: [],
+ note: null,
+ };
+ const filename = `2026-05-01T00-00-00-000Z-pre-b4-peer-${manifest.id}.json`;
+ writeFileSync(join(tempBucket, 'manifests', filename), JSON.stringify(manifest));
+
+ const result = await importer.processManifest(bucket.id, filename);
+ expect(result.processed).toBe(true);
+ expect(result.outcome.applied).toBeGreaterThan(0);
+
+ // Series imported under the preserved id, with legacy canon stripped.
+ const restored = await series.getSeries(seriesId);
+ expect(restored.id).toBe(seriesId);
+ expect(restored.universeId).toBe(uni.id);
+ expect(restored.characters).toBeUndefined();
+ expect(restored.settings).toBeUndefined();
+ expect(restored.places).toBeUndefined();
+ expect(restored.objects).toBeUndefined();
+
+ // Universe gained the canon entries with SERIES_EXTRACT provenance.
+ const merged = await universeSvc.getUniverse(uni.id);
+ expect(merged.characters.map((c) => c.name)).toContain('Echo');
+ expect(merged.places.map((p) => p.name)).toContain('The Foundry');
+ expect(merged.objects.map((o) => o.name)).toContain('Brass Key');
+ // Provenance: live extract path tags series-driven canon as locked + sourceSeriesId.
+ const echo = merged.characters.find((c) => c.name === 'Echo');
+ expect(echo.locked).toBe(true);
+ expect(echo.sourceSeriesId).toBe(seriesId);
+ expect(echo.source).toBe('series-extract');
+ });
+
+ it('creates an orphan universe and links the series when a pre-B.4 record has no universeId', async () => {
+ const bucket = await buckets.createBucket({ name: 'OrphanCanonBucket', path: tempBucket, mode: 'auto-merge' });
+
+ const seriesId = 'ser-orphan-test';
+ const legacySeries = {
+ id: seriesId,
+ name: 'Orphan Series',
+ logline: 'unlinked',
+ premise: 'unlinked premise',
+ // No universeId — pre-B universes-don't-exist era.
+ characters: [{ name: 'Solo', physicalDescription: 'lone' }],
+ createdAt: '2026-05-01T00:00:00.000Z',
+ updatedAt: '2026-05-01T00:00:00.000Z',
+ };
+ mkdirSync(join(tempBucket, 'records', 'series'), { recursive: true });
+ writeFileSync(
+ join(tempBucket, 'records', 'series', `${seriesId}.json`),
+ JSON.stringify(legacySeries),
+ );
+ const manifest = {
+ id: 'mfst-orphan',
+ schemaVersion: 1,
+ sharingSchemaVersion: 1,
+ producedByVersion: '1.0.0',
+ createdAt: new Date().toISOString(),
+ kind: 'series',
+ senderInstanceId: 'orphan-peer',
+ source: 'Orphan Peer',
+ sourceBio: null,
+ bucketId: bucket.id,
+ bucketName: bucket.name,
+ recordIds: [seriesId],
+ assetRefs: [],
+ note: null,
+ };
+ const filename = `2026-05-01T00-00-00-000Z-orphan-peer-${manifest.id}.json`;
+ writeFileSync(join(tempBucket, 'manifests', filename), JSON.stringify(manifest));
+
+ const result = await importer.processManifest(bucket.id, filename);
+ expect(result.processed).toBe(true);
+
+ const restored = await series.getSeries(seriesId);
+ expect(restored.universeId).toBeTruthy(); // freshly minted
+ const orphanUni = await universeSvc.getUniverse(restored.universeId);
+ expect(orphanUni.name).toMatch(/Orphan Series/);
+ expect(orphanUni.characters.map((c) => c.name)).toContain('Solo');
+ });
+
it('refuses a manifest with a sharingSchemaVersion newer than local + emits incompatible event', async () => {
const { SHARING_SCHEMA_VERSION } = await import('./version.js');
const { sharingEvents } = await import('./importer.js');