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([legacy-series-canon-orphan-universe-leak-on-throw]): reuse orphan universe across import retries

[._.]/ Adam Eivyc2efc074f6ea
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ed07de7a31..0af0e7315f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -10,5 +10,6 @@
## Fixed
- **[feeds-ssrf-ipv6-bracket-hostname-gap] RSS feed subscriptions now reliably reject IPv6 loopback, link-local, and unique-local addresses** — previously the loopback `http://[::1]/feed` case was blocked only incidentally by DNS errors; subscribing to feeds at literal private IPv6 addresses is now refused outright, including IPv4-mapped variants like `[::ffff:192.168.1.1]`.
+- **[legacy-series-canon-orphan-universe-leak-on-throw] Retrying a failed peer-share import no longer leaves empty "(auto-migrated)" universes behind** — when a transient disk error interrupted importing a peer's series, each retry used to mint a fresh empty universe; the importer now reuses the same one across retries so the import either lands cleanly or is harmless to retry.
## Removed
diff --git a/PLAN.md b/PLAN.md
index 2e6bb8753e..1a1b256da0 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -40,8 +40,6 @@ The 2026-04-25 CODEX 5.5 review's concrete bugs (Brain Feeds nav, Time Capsule n
### Deferred from better/2026-05-19
-- [ ] [legacy-series-canon-orphan-universe-leak-on-throw] **[LOW][SHARING]** `server/services/pipeline/migrateSeriesCanon.js#applyLegacySeriesCanonToUniverse` — when the helper hits a transient I/O failure between `createUniverse(...)` and `updateUniverse(universeId, patch)` (or any subsequent write), the orphan universe is persisted on disk but the helper throws. On retry the manifest reprocesses, sees `s.universeId` still unset (bucket record isn't mutated), and mints a SECOND auto-migrated universe. Canon data isn't lost (the manifest stays retryable via `legacyCanonPendingFailures`), but empty `"<series-name> (auto-migrated)"` universes accumulate per retry pass. Fix needs a deterministic universe id derived from the importing series (e.g. `uni-import-<seriesHash>` or persisting the chosen id back to the bucket sidecar) so the second creation hits `ERR_DUPLICATE` and the helper reuses the existing universe. Deferred from `[med-sharing-server-services-sharing-version-js]` because the fix touches the universe identity model — out of scope for the importer-side migration salvage PR. Surfaced 2026-05-20 in codex review iter 4.
-
- [ ] [universebuilder-collection-hook-flaky-batch-enrich] **[MED][TESTS]** `server/services/universeBuilderCollectionHook.test.js > "enriches every sidecar in a batch — all N images get tagged"` still fails intermittently when the full server suite runs in parallel, even after the 2026-05-19 fix that migrated `enrichSidecar` to `atomicWrite` (`[imagegen-local-defer-module-load-side-effects]` PR). Passes 100% in isolation (`vitest run services/universeBuilderCollectionHook.test.js` — 8/8). Suggests a cross-file race that survives the temp+rename atomicity — likely shared `PATHS.data` Proxy / mocked `mediaCollections` state colliding with a sibling test that drains the same hook queue concurrently. Reproduce by running the full server `vitest run` 10× and grepping for FAIL; instrument the batch enrich path to log timing and identify the contending writer. Surfaced 2026-05-20 during the legacy-series-canon import PR.
- [ ] [ansistrip-osc-alternative-unreachable] **[MED][TUI]** `server/lib/ansiStrip.js:14` — the OSC alternative in `ANSI_PATTERN` (`\][^\x07]*(?:\x07|\x1B\\)`) is dead code. Alternation order matches the single-byte alternative `[@-Z\\-_]` against `\x1B]` (0x5D is in 0x5C-0x5F) before the OSC alt is tried. Effect: only `\x1B]` is stripped from OSC sequences; the body+terminator leak into the cleaned stream (e.g. `\x1B]0;title\x07after` → `0;title\x07after`). Callers (`tuiPromptRunner.js:237`, `agentTuiSpawning.js:292`) consume the result without further filtering. Fix by either reordering alternatives (OSC before single-byte) or excluding `]` from the single-byte class (`[@-Z\\^_]` or similar). The new `ansiStrip.test.js` pins the current buggy behavior so a fix has an unambiguous before/after baseline. Surfaced 2026-05-20 during the test-coverage PR for med-tests-no-tests-for-server-lib-ansistrip-js; deferred to keep that PR scoped to tests.
diff --git a/server/services/pipeline/migrateSeriesCanon.js b/server/services/pipeline/migrateSeriesCanon.js
index 819230eefe..7d14c7a043 100644
--- a/server/services/pipeline/migrateSeriesCanon.js
+++ b/server/services/pipeline/migrateSeriesCanon.js
@@ -13,11 +13,20 @@
// next series-side write will rewrite the JSON without the legacy fields.
import { join } from 'path';
+import { createHash } from 'node:crypto';
import { updateSeries } from './series.js';
import { PATHS, readJSONFile } from '../../lib/fileUtils.js';
-import { getUniverse, createUniverse, updateUniverse } from '../universeBuilder.js';
+import { getUniverse, insertUniverseWithId, updateUniverse, ERR_DUPLICATE } from '../universeBuilder.js';
import { mergeExtractedBible, BIBLE_FIELD, BIBLE_SOURCE } from '../../lib/storyBible.js';
+// Derive a stable universe id from the importing series so a retry after a
+// mid-helper throw (insert succeeded, a later write failed) reuses the orphan
+// from the prior pass instead of minting a second "(auto-migrated)" universe
+// per retry. sha1 of `series.id` truncated to 32 hex chars fits UNIVERSE_ID_RE
+// (`[A-Za-z0-9-]{8,80}`) regardless of the series-id format.
+export const deriveOrphanUniverseId = (seriesId) =>
+ `uni-from-series-${createHash('sha1').update(String(seriesId)).digest('hex').slice(0, 32)}`;
+
// Raw read of pipeline-series.json (bypasses sanitizeSeries, which post-B.4
// strips the legacy canon fields the migration needs to see).
const readRawSeriesState = () =>
@@ -78,21 +87,34 @@ export async function applyLegacySeriesCanonToUniverse(series, { dryRun = false,
let universeId = series.universeId;
let universeCreated = false;
+ let freshlyInserted = null;
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({
+ const deterministicId = deriveOrphanUniverseId(series.id);
+ freshlyInserted = await insertUniverseWithId({
+ id: deterministicId,
name: `${series.name} (auto-migrated)`,
starterPrompt: series.logline || series.premise?.slice(0, 500) || '',
+ }).catch((err) => {
+ if (err?.code === ERR_DUPLICATE) return null;
+ throw err;
});
- universeId = newUniverse.id;
+ universeId = deterministicId;
universeCreated = true;
- log(`🌌 Created universe "${newUniverse.name}" (${newUniverse.id}) for orphan series "${series.name}"`);
+ if (freshlyInserted) {
+ log(`🌌 Created universe "${freshlyInserted.name}" (${freshlyInserted.id}) for orphan series "${series.name}"`);
+ } else {
+ // Prior retry minted this universe but threw before updateUniverse
+ // landed — still flag `universeCreated` so the caller stamps
+ // `series.universeId` and the merge below populates the empty canon.
+ log(`♻️ Reusing universe ${deterministicId} for orphan series "${series.name}" (retry after prior failure)`);
+ }
}
- const universe = await getUniverse(universeId).catch(() => null);
+ const universe = freshlyInserted || 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' };
diff --git a/server/services/pipeline/migrateSeriesCanon.test.js b/server/services/pipeline/migrateSeriesCanon.test.js
new file mode 100644
index 0000000000..dd32e9e336
--- /dev/null
+++ b/server/services/pipeline/migrateSeriesCanon.test.js
@@ -0,0 +1,129 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+const ERR_DUPLICATE = 'DUPLICATE';
+const ERR_NOT_FOUND = 'NOT_FOUND';
+
+// In-memory universe store the mock backs. Mirrors the file-backed shape so
+// insert/get/update behave like the real module from the helper's POV.
+const universes = new Map();
+const insertCalls = [];
+
+vi.mock('../universeBuilder.js', () => ({
+ ERR_DUPLICATE,
+ insertUniverseWithId: vi.fn(async ({ id, name, starterPrompt }) => {
+ insertCalls.push({ id, name });
+ if (universes.has(id)) {
+ const err = new Error(`Universe id already exists: ${id}`);
+ err.code = ERR_DUPLICATE;
+ throw err;
+ }
+ const rec = { id, name, starterPrompt, characters: [], places: [], objects: [] };
+ universes.set(id, rec);
+ return rec;
+ }),
+ getUniverse: vi.fn(async (id) => {
+ if (!universes.has(id)) {
+ const err = new Error(`Universe not found: ${id}`);
+ err.code = ERR_NOT_FOUND;
+ throw err;
+ }
+ return universes.get(id);
+ }),
+ updateUniverse: vi.fn(async (id, patch) => {
+ const cur = universes.get(id);
+ Object.assign(cur, patch);
+ return cur;
+ }),
+}));
+
+vi.mock('./series.js', () => ({ updateSeries: vi.fn(async () => null) }));
+vi.mock('../../lib/fileUtils.js', () => ({
+ PATHS: { data: '/mock/data' },
+ readJSONFile: vi.fn(async (_p, fallback) => fallback),
+}));
+
+const { applyLegacySeriesCanonToUniverse, deriveOrphanUniverseId } = await import('./migrateSeriesCanon.js');
+const universeBuilder = await import('../universeBuilder.js');
+
+const baseSeries = (over = {}) => ({
+ id: 'series-abc-123',
+ name: 'Aegis Online',
+ characters: [{ name: 'Iris', description: 'protagonist' }],
+ places: [],
+ objects: [],
+ ...over,
+});
+
+beforeEach(() => {
+ universes.clear();
+ insertCalls.length = 0;
+ vi.clearAllMocks();
+});
+
+describe('deriveOrphanUniverseId', () => {
+ it('is deterministic for the same series id', () => {
+ expect(deriveOrphanUniverseId('series-abc-123')).toBe(deriveOrphanUniverseId('series-abc-123'));
+ });
+
+ it('produces a different id for a different series id', () => {
+ expect(deriveOrphanUniverseId('series-abc-123')).not.toBe(deriveOrphanUniverseId('series-xyz-789'));
+ });
+
+ it('fits UNIVERSE_ID_RE (^[A-Za-z0-9-]{8,80}$)', () => {
+ const id = deriveOrphanUniverseId('any-seed');
+ expect(id).toMatch(/^[A-Za-z0-9-]{8,80}$/);
+ });
+});
+
+describe('applyLegacySeriesCanonToUniverse — retry idempotency', () => {
+ it('creates a single deterministic universe for an orphan series on first call', async () => {
+ const r = await applyLegacySeriesCanonToUniverse(baseSeries(), { log: () => {} });
+ expect(r.universeCreated).toBe(true);
+ expect(r.universeId).toBe(deriveOrphanUniverseId('series-abc-123'));
+ expect(insertCalls).toHaveLength(1);
+ expect(universes.size).toBe(1);
+ });
+
+ it('reuses the prior orphan universe when retried after an updateUniverse failure', async () => {
+ // First pass: insertUniverseWithId lands the universe, updateUniverse
+ // throws (transient I/O). Helper bubbles the throw (caller catches).
+ universeBuilder.updateUniverse.mockRejectedValueOnce(new Error('EIO: disk full'));
+ await expect(applyLegacySeriesCanonToUniverse(baseSeries(), { log: () => {} }))
+ .rejects.toThrow(/EIO/);
+ expect(universes.size).toBe(1);
+ const orphanId = deriveOrphanUniverseId('series-abc-123');
+ expect(universes.has(orphanId)).toBe(true);
+ expect(universes.get(orphanId).characters).toEqual([]);
+
+ // Retry pass: same series.id, no universeId on the record (bucket
+ // record isn't mutated between retries).
+ const r2 = await applyLegacySeriesCanonToUniverse(baseSeries(), { log: () => {} });
+ expect(r2.universeId).toBe(orphanId);
+ expect(r2.universeCreated).toBe(true);
+ expect(r2.migrated).toBe(true);
+ // Exactly two insert attempts (first success, second ERR_DUPLICATE) —
+ // never a third orphan minted.
+ expect(insertCalls).toHaveLength(2);
+ expect(universes.size).toBe(1);
+ expect(universes.get(orphanId).characters).toEqual([
+ expect.objectContaining({ name: 'Iris' }),
+ ]);
+ });
+
+ it('does not create a universe in dry-run mode', async () => {
+ const r = await applyLegacySeriesCanonToUniverse(baseSeries(), { dryRun: true, log: () => {} });
+ expect(r.skipped).toBe('dry-run-orphan');
+ expect(r.universeCreated).toBe(false);
+ expect(insertCalls).toHaveLength(0);
+ expect(universes.size).toBe(0);
+ });
+
+ it('rethrows non-ERR_DUPLICATE insert errors so callers can mark the series pending', async () => {
+ universeBuilder.insertUniverseWithId.mockRejectedValueOnce(
+ Object.assign(new Error('disk dead'), { code: 'EIO' }),
+ );
+ await expect(applyLegacySeriesCanonToUniverse(baseSeries(), { log: () => {} }))
+ .rejects.toThrow(/disk dead/);
+ expect(universes.size).toBe(0);
+ });
+});