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
feat([same-collection-export-pattern-for-pipeline-series]): per-series auto-collection bundled into manifest.collection
[._.]/ Adam Eivy4ef04f1107a5
diff --git a/server/routes/sharing.js b/server/routes/sharing.jsindex 982ea8dc50..db80134324 100644--- a/server/routes/sharing.js+++ b/server/routes/sharing.js@@ -57,6 +57,7 @@ const SHARING_ERROR_STATUS = {SHARING_RECORDS_PENDING: 409,SHARING_ASSETS_PENDING: 409,SHARING_UNIVERSE_PENDING: 409,+ SHARING_SERIES_PENDING: 409,};const mapSharingError = (err) => {diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.jsindex ecc18da35d..bcbe801b31 100644--- a/server/services/mediaCollections.js+++ b/server/services/mediaCollections.js@@ -67,6 +67,7 @@ const sanitizeItem = (raw) => {};const UNIVERSE_ID_MAX = 80;+const SERIES_ID_MAX = 80;const sanitizeCollection = (raw) => {if (!raw || typeof raw !== 'object') return null;@@ -102,9 +103,15 @@ const sanitizeCollection = (raw) => {const universeId = typeof raw.universeId === 'string' && raw.universeId? raw.universeId.slice(0, UNIVERSE_ID_MAX): null;+ // Mutually exclusive with universeId on read — a hand-edited record+ // carrying both is resolved to the universe link (older, established+ // relationship) so a single collection can't drive two subscriptions.+ const seriesId = !universeId && typeof raw.seriesId === 'string' && raw.seriesId+ ? raw.seriesId.slice(0, SERIES_ID_MAX)+ : null;const createdAt = typeof raw.createdAt === 'string' ? raw.createdAt : new Date().toISOString();const updatedAt = typeof raw.updatedAt === 'string' ? raw.updatedAt : createdAt;- return { id: raw.id, name, description, coverKey, universeId, items, createdAt, updatedAt };+ return { id: raw.id, name, description, coverKey, universeId, seriesId, items, createdAt, updatedAt };};export async function listCollections() {@@ -312,6 +319,99 @@ export async function findOrCreateUniverseCollection({ universeId, universeName,});}+// Series-side mirror of the universe collection helpers above+// (`universeCollectionNameFor`, `findCollectionByUniverseId`,+// `findOrCreateUniverseCollection`, `unlinkCollectionsForUniverse`,+// `renameCollectionForUniverse`). Same resolution-order + orphan-avoidance+// rules — see those functions' docstrings for the rationale.+export const seriesCollectionNameFor = (seriesName) =>+ `Series: ${typeof seriesName === 'string' ? seriesName : ''}`.slice(0, NAME_MAX_LENGTH);++export async function findCollectionBySeriesId(seriesId) {+ if (typeof seriesId !== 'string' || !seriesId) return null;+ const needle = seriesId.slice(0, SERIES_ID_MAX);+ const all = await listCollections();+ return all.find((c) => c.seriesId === needle) || null;+}++export async function findOrCreateSeriesCollection({ seriesId, seriesName, description = '' }) {+ if (!seriesId || typeof seriesId !== 'string') {+ throw makeErr('seriesId is required', ERR_VALIDATION);+ }+ if (typeof seriesName !== 'string' || !seriesName.trim()) {+ throw makeErr('seriesName is required', ERR_VALIDATION);+ }+ const normalizedSeriesId = seriesId.slice(0, SERIES_ID_MAX);+ const desiredName = seriesCollectionNameFor(seriesName);+ const trimmedDescription = typeof description === 'string'+ ? description.trim().slice(0, DESCRIPTION_MAX_LENGTH)+ : '';+ return serializeFileWrite(async () => {+ const all = await listCollections();+ const linked = all.find((c) => c.seriesId === normalizedSeriesId);+ if (linked) return linked;+ const now = new Date().toISOString();+ const next = {+ id: randomUUID(),+ name: desiredName,+ description: trimmedDescription,+ coverKey: null,+ seriesId: normalizedSeriesId,+ items: [],+ createdAt: now,+ updatedAt: now,+ };+ await writeAll([...all, next]);+ return next;+ });+}++export async function unlinkCollectionsForSeries(seriesId) {+ if (typeof seriesId !== 'string' || !seriesId) return [];+ const needle = seriesId.slice(0, SERIES_ID_MAX);+ return serializeFileWrite(async () => {+ const all = await listCollections();+ const matches = all+ .map((c, i) => (c.seriesId === needle ? i : -1))+ .filter((i) => i >= 0);+ if (!matches.length) return [];+ const now = new Date().toISOString();+ const next = [...all];+ const unlinkedIds = [];+ for (const i of matches) {+ next[i] = { ...all[i], seriesId: null, updatedAt: now };+ unlinkedIds.push(all[i].id);+ }+ await writeAll(next);+ return unlinkedIds;+ });+}++export async function renameCollectionForSeries(seriesId, newSeriesName) {+ if (typeof seriesId !== 'string' || !seriesId) return null;+ const needle = seriesId.slice(0, SERIES_ID_MAX);+ return serializeFileWrite(async () => {+ const all = await listCollections();+ const matchIdxs = all+ .map((c, i) => (c.seriesId === needle ? i : -1))+ .filter((i) => i >= 0);+ if (!matchIdxs.length) return null;+ const desired = seriesCollectionNameFor(newSeriesName);+ if (!desired) return all[matchIdxs[0]];+ const now = new Date().toISOString();+ const next = [...all];+ let changed = false;+ for (const i of matchIdxs) {+ if (next[i].name === desired) continue;+ next[i] = { ...next[i], name: desired, updatedAt: now };+ changed = true;+ }+ if (!changed) return all[matchIdxs[0]];+ await writeAll(next);+ return next[matchIdxs[0]];+ });+}+// Clear the `universeId` link on any collection bound to this universe.// Used by deleteUniverse to release the rename-lock so the orphaned bucket// becomes a normal user-owned collection (renamable, deletable, etc.). The@@ -391,6 +491,12 @@ export async function updateCollection(id, patch) {ERR_VALIDATION,);}+ if ('name' in patch && cur.seriesId && patch.name !== cur.name) {+ throw makeErr(+ 'This collection is linked to a Series — rename the series to rename it.',+ ERR_VALIDATION,+ );+ }// Cover key validation is deferred to sanitizeCollection on read, but we// also reject up-front so the API gives a clear error rather than silently// dropping the cover.@@ -412,12 +518,12 @@ export async function updateCollection(id, patch) {}export async function deleteCollection(id) {- const deletedUniverseId = await serializeFileWrite(async () => {+ const { universeId: deletedUniverseId, seriesId: deletedSeriesId } = await serializeFileWrite(async () => {const all = await listCollections();const target = all.find((c) => c.id === id);if (!target) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);await writeAll(all.filter((c) => c.id !== id));- return target.universeId || null;+ return { universeId: target.universeId || null, seriesId: target.seriesId || null };});// Mirror addItem/removeItem/bulkUpdateCollectionItems — universe-linked// shares need to know membership changed so the subscriber doesn't keep@@ -425,6 +531,7 @@ export async function deleteCollection(id) {// fires. Emit outside the serialized critical section so subscribers'// own reads don't deadlock the tail.if (deletedUniverseId) emitRecordUpdated('universe', deletedUniverseId);+ if (deletedSeriesId) emitRecordUpdated('series', deletedSeriesId);return { id };}@@ -469,6 +576,7 @@ export async function addItem(id, item) {// Emit outside the serialized critical section — subscribers may issue// their own collection reads and we don't want to deadlock the tail.if (merged.universeId) emitRecordUpdated('universe', merged.universeId);+ if (merged.seriesId) emitRecordUpdated('series', merged.seriesId);return merged;}@@ -547,8 +655,9 @@ export async function bulkUpdateCollectionItems(id, { add = [], remove = [] } =await writeAll(next);return { collection: merged, added: additions.length, removed };});- if (result.collection.universeId && (result.added || result.removed)) {- emitRecordUpdated('universe', result.collection.universeId);+ if (result.added || result.removed) {+ if (result.collection.universeId) emitRecordUpdated('universe', result.collection.universeId);+ if (result.collection.seriesId) emitRecordUpdated('series', result.collection.seriesId);}return result;}@@ -577,5 +686,6 @@ export async function removeItem(id, key) {return updated;});if (merged.universeId) emitRecordUpdated('universe', merged.universeId);+ if (merged.seriesId) emitRecordUpdated('series', merged.seriesId);return merged;}diff --git a/server/services/mediaCollections.test.js b/server/services/mediaCollections.test.jsindex a1505939e4..a472ea88ae 100644--- a/server/services/mediaCollections.test.js+++ b/server/services/mediaCollections.test.js@@ -495,6 +495,120 @@ describe('mediaCollections service', () => {});});+ describe('series-linked collections', () => {+ it('updateCollection rejects a name change when the collection is series-linked', async () => {+ const linked = await svc.findOrCreateSeriesCollection({+ seriesId: 'ser-1', seriesName: 'Foo',+ });+ await expect(svc.updateCollection(linked.id, { name: 'Renamed' }))+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });+ });++ it('seriesCollectionNameFor produces the canonical "Series: <name>" string and truncates', () => {+ expect(svc.seriesCollectionNameFor('Foo')).toBe('Series: Foo');+ const long = 'x'.repeat(200);+ expect(svc.seriesCollectionNameFor(long).length).toBe(svc.NAME_MAX_LENGTH);+ });++ it('findCollectionBySeriesId locates the linked collection (or returns null)', async () => {+ expect(await svc.findCollectionBySeriesId('ser-ghost')).toBeNull();+ const linked = await svc.findOrCreateSeriesCollection({+ seriesId: 'ser-1', seriesName: 'Foo',+ });+ const found = await svc.findCollectionBySeriesId('ser-1');+ expect(found?.id).toBe(linked.id);+ });++ it('findOrCreateSeriesCollection returns the existing series-linked collection on second call', async () => {+ const first = await svc.findOrCreateSeriesCollection({+ seriesId: 'ser-1', seriesName: 'Foo',+ });+ const second = await svc.findOrCreateSeriesCollection({+ seriesId: 'ser-1', seriesName: 'Foo',+ });+ expect(second.id).toBe(first.id);+ expect(await svc.listCollections()).toHaveLength(1);+ });++ it('findOrCreateSeriesCollection requires both seriesId and seriesName', async () => {+ await expect(svc.findOrCreateSeriesCollection({ seriesName: 'X' }))+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });+ await expect(svc.findOrCreateSeriesCollection({ seriesId: 'ser-1' }))+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });+ });++ it('renameCollectionForSeries cascades a new name onto the linked collection', async () => {+ const linked = await svc.findOrCreateSeriesCollection({+ seriesId: 'ser-1', seriesName: 'Foo',+ });+ const updated = await svc.renameCollectionForSeries('ser-1', 'Bar');+ expect(updated.id).toBe(linked.id);+ expect(updated.name).toBe('Series: Bar');+ });++ it('unlinkCollectionsForSeries clears the seriesId (preserves items)', async () => {+ const linked = await svc.findOrCreateSeriesCollection({+ seriesId: 'ser-1', seriesName: 'Foo',+ });+ await svc.addItem(linked.id, { kind: 'image', ref: 'cover.png' });+ const cleared = await svc.unlinkCollectionsForSeries('ser-1');+ expect(cleared).toEqual([linked.id]);+ const fresh = await svc.getCollection(linked.id);+ expect(fresh.seriesId).toBeNull();+ expect(fresh.items).toHaveLength(1);+ // Lock released — renames now succeed.+ const renamed = await svc.updateCollection(linked.id, { name: 'Orphan' });+ expect(renamed.name).toBe('Orphan');+ });++ it('addItem on a series-linked collection emits recordUpdated("series", seriesId)', async () => {+ const events = [];+ const { recordEvents } = await import('./sharing/recordEvents.js');+ const listener = (evt) => events.push(evt);+ recordEvents.on('updated', listener);+ try {+ const linked = await svc.findOrCreateSeriesCollection({+ seriesId: 'ser-1', seriesName: 'Foo',+ });+ events.length = 0;+ await svc.addItem(linked.id, { kind: 'image', ref: 'x.png' });+ expect(events).toContainEqual(expect.objectContaining({ recordKind: 'series', recordId: 'ser-1' }));+ } finally {+ recordEvents.off('updated', listener);+ }+ });++ it('deleteCollection emits recordUpdated("series", seriesId) when the deleted collection was series-linked', async () => {+ const events = [];+ const { recordEvents } = await import('./sharing/recordEvents.js');+ const listener = (evt) => events.push(evt);+ recordEvents.on('updated', listener);+ try {+ const linked = await svc.findOrCreateSeriesCollection({+ seriesId: 'ser-1', seriesName: 'Foo',+ });+ events.length = 0;+ await svc.deleteCollection(linked.id);+ expect(events).toContainEqual(expect.objectContaining({ recordKind: 'series', recordId: 'ser-1' }));+ } finally {+ recordEvents.off('updated', listener);+ }+ });++ it('sanitizer drops seriesId when universeId is also set (universeId wins)', async () => {+ fileStore.set('/mock/data/media-collections.json', {+ collections: [{+ id: 'c1', name: 'Mixed', items: [],+ universeId: 'u-1', seriesId: 'ser-1',+ createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',+ }],+ });+ const [c] = await svc.listCollections();+ expect(c.universeId).toBe('u-1');+ expect(c.seriesId).toBeNull();+ });+ });+it('sanitizes hand-edited JSON with bogus items', async () => {fileStore.set('/mock/data/media-collections.json', {collections: [diff --git a/server/services/pipeline/comicPagesFilenameHook.js b/server/services/pipeline/comicPagesFilenameHook.jsindex 54cb4b6712..48013be7bf 100644--- a/server/services/pipeline/comicPagesFilenameHook.js+++ b/server/services/pipeline/comicPagesFilenameHook.js@@ -17,7 +17,7 @@ import { parseComicPagesOwner, slotKeyForVariant } from './owners.js';import { createFilenameHook } from './filenameHookFactory.js';import { buildRenderSlot } from './visualStages.js';import { getIssue } from './issues.js';-import { fileCoverIntoUniverseCollection } from './coverUniverseFiler.js';+import { fileCoverIntoAutoCollection } from './coverUniverseFiler.js';// Slot record for a legacy in-flight completion (job enqueued before the// proof/final split). `job.params` carries the originally-requested width@@ -113,7 +113,7 @@ const hook = createFilenameHook({if (parsed.target !== 'cover' && parsed.target !== 'backCover') return;const issue = await getIssue(parsed.issueId).catch(() => null);if (!issue?.seriesId) return;- await fileCoverIntoUniverseCollection({ seriesId: issue.seriesId, filename });+ await fileCoverIntoAutoCollection({ seriesId: issue.seriesId, filename });},});diff --git a/server/services/pipeline/coverUniverseFiler.js b/server/services/pipeline/coverUniverseFiler.jsindex 2b5d55e1d9..5bee44c18c 100644--- a/server/services/pipeline/coverUniverseFiler.js+++ b/server/services/pipeline/coverUniverseFiler.js@@ -1,38 +1,56 @@/**- * Pipeline — auto-file series/volume/issue cover renders into a Universe's- * media collection.+ * Pipeline — auto-file series/volume/issue cover renders into either the+ * series' universe collection (when the series is universe-linked) or a+ * per-series collection (fallback for series without a universe).** The Universe Builder already maintains a `Universe: <name>` collection per* universe (`server/services/universeBuilderCollectionHook.js` files render* jobs into it by tag). Pipeline cover renders bypass that hook — they go* through dedicated routes that don't carry a `universeRun` tag — so without* this helper, a series/volume/issue cover image renders into the gallery- * but never lands in the universe's collection alongside the universe's own- * concept art.+ * but never lands in any collection. Without a collection to bundle, the+ * share-bucket exporter has nothing to put in `manifest.collection` either.** The two cover filename hooks (seasonCover, comicPages cover/backCover)- * call into this helper after they finish stamping the filename on the- * stage record. Failures are logged and swallowed — bookkeeping must never- * fail the user's render.+ * call `fileCoverIntoAutoCollection` after they finish stamping the+ * filename on the stage record. Failures are logged and swallowed —+ * bookkeeping must never fail the user's render.*- * **Concurrency.** No per-universe queue is needed here. Every collection- * write the helper makes (findOrCreateUniverseCollection, addItem,- * unlinkCollectionsForUniverse) routes through the single file-level write- * tail in `mediaCollections.js`. Two parallel filings for the same universe- * (cover + back-cover from the same render burst) interleave their own- * `await` points freely; the file tail serializes the *writes* so both- * filenames land and neither orphans the collection.+ * **Concurrency.** No per-universe/per-series queue is needed here. Every+ * collection write routes through the single file-level write tail in+ * `mediaCollections.js`. Two parallel filings for the same series (cover ++ * back-cover from the same render burst) interleave their own `await`+ * points freely; the file tail serializes the *writes* so both filenames+ * land and neither orphans the collection.*/import {findOrCreateUniverseCollection,+ findOrCreateSeriesCollection,unlinkCollectionsForUniverse,+ unlinkCollectionsForSeries,addItem,ERR_DUPLICATE,} from '../mediaCollections.js';import * as seriesSvc from './series.js';import * as universeSvc from '../universeBuilder.js';+/**+ * Dispatch a freshly-rendered cover image to whichever auto-collection the+ * series qualifies for: universe-linked first, per-series fallback when+ * the series has no universeId. Silent no-op for missing/invalid input.+ */+export async function fileCoverIntoAutoCollection({ seriesId, filename }) {+ if (!seriesId || typeof filename !== 'string' || !filename) return;+ const series = await seriesSvc.getSeries(seriesId).catch(() => null);+ if (!series) return;+ if (series.universeId) {+ await fileCoverIntoUniverseCollection({ seriesId, filename });+ return;+ }+ await fileCoverIntoSeriesCollection({ seriesId, filename });+}+// Adds a freshly-rendered cover image to the universe's collection.// `seriesId` is the bridge — series → universeId → universe → collection.// Silent no-op when the series has no universe link (a common case for@@ -100,3 +118,39 @@ export async function fileCoverIntoUniverseCollection({ seriesId, filename }) {});}}++// Per-series fallback when `series.universeId` is null. Same shape ++// delete-race recovery as the universe path above.+export async function fileCoverIntoSeriesCollection({ seriesId, filename }) {+ if (!seriesId || typeof filename !== 'string' || !filename) return;++ // Re-fetch close to the create so a series rename mid-flight stamps the+ // collection with the freshest name.+ const liveSeries = await seriesSvc.getSeries(seriesId).catch(() => null);+ if (!liveSeries) return;++ const collection = await findOrCreateSeriesCollection({+ seriesId: liveSeries.id,+ seriesName: liveSeries.name,+ description: `Renders for "${liveSeries.name}"`,+ }).catch((err) => {+ console.error(`❌ cover → series collection provision failed for ${filename}: ${err?.message || err}`);+ return null;+ });+ if (!collection) return;++ await addItem(collection.id, { kind: 'image', ref: filename }).catch((err) => {+ if (err?.code === ERR_DUPLICATE) return;+ console.error(`❌ cover → series collection filing failed for ${filename}: ${err?.message || err}`);+ });++ // Delete-race recovery: deleteSeries may have fired between getSeries and+ // the collection write. Unlink the stamped collection so the user can+ // rename or delete it via normal flows; covers added above are preserved.+ const stillExists = await seriesSvc.getSeries(seriesId).catch(() => null);+ if (!stillExists || stillExists.id !== liveSeries.id) {+ await unlinkCollectionsForSeries(seriesId).catch((err) => {+ console.error(`❌ cover → series collection orphan-unlink failed for series=${seriesId}: ${err?.message || err}`);+ });+ }+}diff --git a/server/services/pipeline/coverUniverseFiler.test.js b/server/services/pipeline/coverUniverseFiler.test.jsindex ab5afe6868..d54c913728 100644--- a/server/services/pipeline/coverUniverseFiler.test.js+++ b/server/services/pipeline/coverUniverseFiler.test.js@@ -20,7 +20,7 @@ vi.mock('crypto', async () => {const collections = await import('../mediaCollections.js');const seriesSvc = await import('./series.js');const universeSvc = await import('../universeBuilder.js');-const { fileCoverIntoUniverseCollection } = await import('./coverUniverseFiler.js');+const { fileCoverIntoUniverseCollection, fileCoverIntoSeriesCollection, fileCoverIntoAutoCollection } = await import('./coverUniverseFiler.js');describe('fileCoverIntoUniverseCollection', () => {beforeEach(() => {@@ -116,3 +116,92 @@ describe('fileCoverIntoUniverseCollection', () => {expect(named).toHaveLength(1);});});++describe('fileCoverIntoSeriesCollection', () => {+ beforeEach(() => {+ fileStore.clear();+ uuidCounter = 0;+ });++ it('files the cover image into a per-series collection (creating it on first use)', async () => {+ const series = await seriesSvc.createSeries({ name: 'Solo Series' });+ await fileCoverIntoSeriesCollection({ seriesId: series.id, filename: 'cover-001.png' });+ const linked = await collections.findCollectionBySeriesId(series.id);+ expect(linked?.name).toBe('Series: Solo Series');+ expect(linked?.items.map((it) => it.ref)).toEqual(['cover-001.png']);+ });++ it('reuses an existing series-linked collection on subsequent filings', async () => {+ const series = await seriesSvc.createSeries({ name: 'Solo' });+ await fileCoverIntoSeriesCollection({ seriesId: series.id, filename: 'a.png' });+ await fileCoverIntoSeriesCollection({ seriesId: series.id, filename: 'b.png' });+ const fresh = await collections.findCollectionBySeriesId(series.id);+ expect(fresh.items.map((it) => it.ref).sort()).toEqual(['a.png', 'b.png']);+ // Only one collection exists for this series.+ const named = (await collections.listCollections()).filter((c) => c.seriesId === series.id);+ expect(named).toHaveLength(1);+ });++ it('no-ops when seriesId or filename is missing', async () => {+ await fileCoverIntoSeriesCollection({ seriesId: null, filename: 'x.png' });+ await fileCoverIntoSeriesCollection({ seriesId: 'ser-x', filename: '' });+ expect(await collections.listCollections()).toEqual([]);+ });++ it('no-ops when the series no longer exists', async () => {+ await fileCoverIntoSeriesCollection({ seriesId: 'ghost-series', filename: 'x.png' });+ expect(await collections.listCollections()).toEqual([]);+ });++ it('serializes concurrent filings for the same series', async () => {+ const series = await seriesSvc.createSeries({ name: 'RaceSeries' });+ await Promise.all([+ fileCoverIntoSeriesCollection({ seriesId: series.id, filename: 'cover.png' }),+ fileCoverIntoSeriesCollection({ seriesId: series.id, filename: 'back.png' }),+ ]);+ const linked = await collections.findCollectionBySeriesId(series.id);+ expect(linked.items.map((it) => it.ref).sort()).toEqual(['back.png', 'cover.png']);+ const named = (await collections.listCollections()).filter((c) => c.name === 'Series: RaceSeries');+ expect(named).toHaveLength(1);+ });+});++describe('fileCoverIntoAutoCollection (dispatcher)', () => {+ beforeEach(() => {+ fileStore.clear();+ uuidCounter = 0;+ });++ it('routes a universe-linked series to the universe collection', async () => {+ const universe = await universeSvc.createUniverse({ name: 'Cosmos' });+ const series = await seriesSvc.createSeries({ name: 'S', universeId: universe.id });+ await fileCoverIntoAutoCollection({ seriesId: series.id, filename: 'cover.png' });+ expect(await collections.findCollectionByUniverseId(universe.id)).toMatchObject({+ name: 'Universe: Cosmos',+ });+ expect(await collections.findCollectionBySeriesId(series.id)).toBeNull();+ });++ it('routes a universeless series to the per-series collection', async () => {+ const series = await seriesSvc.createSeries({ name: 'Indie' });+ await fileCoverIntoAutoCollection({ seriesId: series.id, filename: 'cover.png' });+ expect(await collections.findCollectionBySeriesId(series.id)).toMatchObject({+ name: 'Series: Indie',+ });+ });++ it('does NOT fall through to a per-series collection when the universe link is dangling', async () => {+ // Dispatcher commits to the universe-path on `series.universeId` set,+ // even if the universe is missing — re-routing would mint a per-series+ // collection for a series the user clearly intended to be universe-owned.+ const series = await seriesSvc.createSeries({ name: 'Dangling', universeId: 'ghost-universe' });+ await fileCoverIntoAutoCollection({ seriesId: series.id, filename: 'x.png' });+ expect(await collections.listCollections()).toEqual([]);+ });++ it('no-ops when seriesId or filename is missing', async () => {+ await fileCoverIntoAutoCollection({ seriesId: null, filename: 'x.png' });+ await fileCoverIntoAutoCollection({ seriesId: 'ser-x', filename: '' });+ expect(await collections.listCollections()).toEqual([]);+ });+});diff --git a/server/services/pipeline/seasonCoverFilenameHook.js b/server/services/pipeline/seasonCoverFilenameHook.jsindex 164505efd0..1244aeec66 100644--- a/server/services/pipeline/seasonCoverFilenameHook.js+++ b/server/services/pipeline/seasonCoverFilenameHook.js@@ -21,7 +21,7 @@import { mediaJobEvents } from '../mediaJobQueue/index.js';import { parseSeasonCoverOwner, slotKeyForVariant } from './owners.js';import * as seriesSvc from './series.js';-import { fileCoverIntoUniverseCollection } from './coverUniverseFiler.js';+import { fileCoverIntoAutoCollection } from './coverUniverseFiler.js';let registeredHandler = null;@@ -64,7 +64,7 @@ const handler = (job) => {if (reducerStamped && writeOk) {console.log(`📎 seasonCover filename stamped — series=${seriesId.slice(0, 8)} season=${seasonId.slice(0, 8)} ${target}.${slotKey} ← ${filename}`);- await fileCoverIntoUniverseCollection({ seriesId, filename });+ await fileCoverIntoAutoCollection({ seriesId, filename });}})().catch((err) => {console.error(`❌ seasonCover filename hook crashed: ${err?.message || err}`);diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex 0286de9235..730ab85d11 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -20,6 +20,7 @@ import { sanitizeArc, sanitizeSeasonList } from '../../lib/storyArc.js';import { sanitizeVisualStyleRef } from '../../lib/visualStyles.js';import { sanitizeOrigin } from '../../lib/sharingOrigin.js';import { emitRecordUpdated, emitRecordDeleted } from '../sharing/recordEvents.js';+import { renameCollectionForSeries, unlinkCollectionsForSeries } from '../mediaCollections.js';// Lazy resolution — PATHS.data may not be available at module-load time// (e.g. tests that swap it through a Proxy mock).@@ -207,7 +208,7 @@ export async function insertSeriesWithId(input = {}) {}export async function updateSeries(id, patch = {}) {- return queueSeriesWrite(async () => {+ const { merged, nameChanged } = await queueSeriesWrite(async () => {const state = await readState();const idx = state.series.findIndex((s) => s.id === id);if (idx < 0) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);@@ -216,7 +217,7 @@ export async function updateSeries(id, patch = {}) {const mergedLlm = 'llm' in patch? { ...(cur.llm || {}), ...(patch.llm || {}) }: cur.llm;- const merged = sanitizeSeries({+ const next = sanitizeSeries({...cur,...('name' in patch ? { name: patch.name } : {}),...('logline' in patch ? { logline: patch.logline } : {}),@@ -238,12 +239,23 @@ export async function updateSeries(id, patch = {}) {llm: mergedLlm,updatedAt: new Date().toISOString(),});- if (!merged) throw makeErr('Invalid series payload', ERR_VALIDATION);- state.series[idx] = merged;+ if (!next) throw makeErr('Invalid series payload', ERR_VALIDATION);+ state.series[idx] = next;await writeState(state);- emitRecordUpdated('series', merged.id);- return merged;+ emitRecordUpdated('series', next.id);+ return { merged: next, nameChanged: next.name !== cur.name };});+ // Cascade rename onto the linked per-series media collection (if any) —+ // log but don't fail the save. Runs OUTSIDE the queue so the media-+ // collections write tail can't stall subsequent series mutators. No-op+ // when no series-linked collection exists (the common case for+ // universe-backed series, where the universe owns the auto-collection).+ if (nameChanged) {+ await renameCollectionForSeries(merged.id, merged.name).catch((err) => {+ console.error(`❌ series-collection rename cascade failed for ${merged.id}: ${err?.message || err}`);+ });+ }+ return merged;}/**@@ -297,7 +309,7 @@ export async function updateSeasonOnSeries(seriesId, seasonId, patchFn) {}export async function deleteSeries(id) {- return queueSeriesWrite(async () => {+ const result = await queueSeriesWrite(async () => {const state = await readState();const before = state.series.length;state.series = state.series.filter((s) => s.id !== id);@@ -308,6 +320,13 @@ export async function deleteSeries(id) {emitRecordDeleted('series', id);return { id };});+ // Release the rename-lock on any linked per-series media collection so+ // the orphan becomes a normal user-owned bucket. Runs OUTSIDE the series+ // write tail; best-effort, mirrors the universe-side flow.+ await unlinkCollectionsForSeries(id).catch((err) => {+ console.error(`❌ unlink media collections for deleted series ${id} failed: ${err?.message || err}`);+ });+ return result;}/**diff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.jsindex 227ccd3d6c..3ce30c31e5 100644--- a/server/services/sharing/exporter.js+++ b/server/services/sharing/exporter.js@@ -24,7 +24,7 @@ import { buildManifest, writeManifest, pruneBucketManifests } from './manifest.jimport { listSeries, getSeries } from '../pipeline/series.js';import { listIssues } from '../pipeline/issues.js';import { getUniverse } from '../universeBuilder.js';-import { listCollections } from '../mediaCollections.js';+import { findCollectionByUniverseId, findCollectionBySeriesId } from '../mediaCollections.js';import { getJob } from '../mediaJobQueue/index.js';import { getInstanceId } from '../instances.js';import { getSettings } from '../settings.js';@@ -241,29 +241,6 @@ function collectAssetReferences(record) {};}-/**- * Find the media collection linked to a universe. universeId-only routing- * — no name-based legacy fallback. Two reasons the legacy fallback was- * removed:- * 1. A post-`deleteUniverse` orphan (now name-matching some new- * same-named universe) would otherwise be picked up and its old- * items would be serialized as the new universe's collection,- * reintroducing the cross-universe mixing this PR set out to- * prevent.- * 2. An ambiguous case that migration 021 deliberately skipped (two- * universes share a display name, no safe link) would otherwise be- * exported under whichever universe ran the export — same- * mis-attribution risk.- *- * Pre-link installs converge on universeId stamps via migration 021 at- * boot, so the runtime fallback is no longer needed for the upgrade- * path. Returns null when no collection is linked.- */-async function findCollectionForUniverse(universe) {- if (!universe?.id) return null;- const all = await listCollections().catch(() => []);- return all.find((c) => c.universeId === universe.id) || null;-}/*** Walk a collection's items and return:@@ -325,8 +302,11 @@ export async function exportSeries(seriesId, bucketId, opts = {}) {let linkedCollection = null;if (series.universeId) {universe = await getUniverse(series.universeId).catch(() => null);- if (universe) linkedCollection = await findCollectionForUniverse(universe);+ if (universe) linkedCollection = await findCollectionByUniverseId(universe.id);}+ // Per-series fallback so a universeless series still ships with its+ // auto-filed cover renders via the seriesId-stamped collection.+ if (!linkedCollection) linkedCollection = await findCollectionBySeriesId(series.id);const [source, sourceBio, senderInstanceId, producedByVersion] = await Promise.all([resolveSourceName(bucket),@@ -410,7 +390,7 @@ export async function exportUniverse(universeId, bucketId, opts = {}) {const bucket = await getBucket(bucketId);await ensureBucketLayout(bucket);const universe = await getUniverse(universeId);- const linkedCollection = await findCollectionForUniverse(universe);+ const linkedCollection = await findCollectionByUniverseId(universe.id);const [source, sourceBio, senderInstanceId, producedByVersion] = await Promise.all([resolveSourceName(bucket),diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.jsindex 02f5ba8d8e..ce18cc724e 100644--- a/server/services/sharing/importer.js+++ b/server/services/sharing/importer.js@@ -32,7 +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 { findOrCreateUniverseCollection, addItem as addCollectionItem, ERR_DUPLICATE as COLLECTION_ERR_DUPLICATE } from '../mediaCollections.js';+import { findOrCreateUniverseCollection, findOrCreateSeriesCollection, addItem as addCollectionItem, ERR_DUPLICATE as COLLECTION_ERR_DUPLICATE } from '../mediaCollections.js';import { adoptImportedSubscription, withReexportSuppressed } from './subscriptions.js';import { getInstanceId } from '../instances.js';import { mergePeerAnnotations } from '../mediaAnnotations.js';@@ -68,13 +68,14 @@ function remoteWins(localTs, remoteTs) {/*** Merge a manifest's `collection` payload into local state. Find-or-create- * the universe-linked collection via the universeId-first helper, then- * add each remote item via `addItem` — `ERR_DUPLICATE` errors are expected- * and swallowed (the item already exists locally; nothing to do).+ * the universe-linked OR series-linked collection via the id-first helper+ * (universeId wins when both are present), then add each remote item via+ * `addItem` — `ERR_DUPLICATE` errors are expected and swallowed (the item+ * already exists locally; nothing to do).*- * Routing is by `universeId`, never by name — a manifest from a peer whose- * universe happens to share a display name with a local universe of a- * different id must NOT silently land in the local universe's bucket.+ * Routing is by `universeId` / `seriesId`, never by name — a manifest from+ * a peer whose universe or series happens to share a display name with a+ * local one of a different id must NOT silently land in the local bucket.** The asset blobs are NOT copied here — `copyAssetsLocally` (called in* `processManifest`) already pulled every available asset entry. This function@@ -82,39 +83,58 @@ function remoteWins(localTs, remoteTs) {* UI does not point at files that Google Drive has not synced yet.*/async function mergeCollectionPayload(payload, availableAssetKeys = null) {- if (!payload?.universeId || !Array.isArray(payload.items)) return { itemsAdded: 0 };-- // Defer the merge until the referenced universe exists locally. Creating- // a stamped (rename-locked) collection for a universe we haven't- // imported yet leaves the user with an unfixable orphan if the universe- // record fails to import or arrives in a later manifest. processManifest- // re-runs the merge attempt on each pass, so a deferred merge will be- // applied as soon as the universe lands.- const localUniverse = await getUniverse(payload.universeId).catch(() => null);- if (!localUniverse) {- return { itemsAdded: 0, itemsDeferred: payload.items.length, missingUniverse: true };+ if (!payload || !Array.isArray(payload.items)) return { itemsAdded: 0 };+ if (!payload.universeId && !payload.seriesId) return { itemsAdded: 0 };++ // Resolve the local owner record (universe OR series). Defer the merge+ // until it exists locally — creating a stamped (rename-locked) collection+ // for an owner we haven't imported yet leaves the user with an unfixable+ // orphan. processManifest re-runs the merge on each pass, so a deferred+ // merge applies as soon as the owner record lands.+ let collection;+ if (payload.universeId) {+ const localUniverse = await getUniverse(payload.universeId).catch(() => null);+ if (!localUniverse) {+ return { itemsAdded: 0, itemsDeferred: payload.items.length, missingUniverse: true };+ }+ // Use the LOCAL owner's name (authoritative for the linked collection's+ // locked name) over the manifest's `payload.name`. A peer exporting a+ // stale or tampered collection payload must not be able to mint a+ // locked collection on the receiver with the wrong visible name —+ // once the id is stamped, no cascade fixes it. Fall back to a+ // sanitized payload.name only when the local name is unusable.+ const fallbackRaw = typeof payload.name === 'string' ? payload.name : '';+ const fallbackName = fallbackRaw.replace(/^Universe:\s*/i, '').trim() || payload.universeId;+ const universeName = typeof localUniverse.name === 'string' && localUniverse.name.trim()+ ? localUniverse.name+ : fallbackName;+ collection = await findOrCreateUniverseCollection({+ universeId: payload.universeId,+ universeName,+ description: payload.description || '',+ }).catch((err) => {+ console.log(`⚠️ sharing.importer: findOrCreateUniverseCollection failed: ${err.message}`);+ return null;+ });+ } else {+ const localSeries = await getSeries(payload.seriesId).catch(() => null);+ if (!localSeries) {+ return { itemsAdded: 0, itemsDeferred: payload.items.length, missingSeries: true };+ }+ const fallbackRaw = typeof payload.name === 'string' ? payload.name : '';+ const fallbackName = fallbackRaw.replace(/^Series:\s*/i, '').trim() || payload.seriesId;+ const seriesName = typeof localSeries.name === 'string' && localSeries.name.trim()+ ? localSeries.name+ : fallbackName;+ collection = await findOrCreateSeriesCollection({+ seriesId: payload.seriesId,+ seriesName,+ description: payload.description || '',+ }).catch((err) => {+ console.log(`⚠️ sharing.importer: findOrCreateSeriesCollection failed: ${err.message}`);+ return null;+ });}-- // Use the LOCAL universe's name (authoritative for the linked- // collection's locked name) over the manifest's `payload.name`. A peer- // exporting a stale or tampered collection payload must not be able to- // mint a locked collection on the receiver with the wrong visible name- // — once the universeId is stamped, no cascade fixes it. Fall back to- // a sanitized payload.name only when localUniverse.name is unusable.- const fallbackRaw = typeof payload.name === 'string' ? payload.name : '';- const fallbackName = fallbackRaw.replace(/^Universe:\s*/i, '').trim() || payload.universeId;- const universeName = typeof localUniverse.name === 'string' && localUniverse.name.trim()- ? localUniverse.name- : fallbackName;-- const collection = await findOrCreateUniverseCollection({- universeId: payload.universeId,- universeName,- description: payload.description || '',- }).catch((err) => {- console.log(`⚠️ sharing.importer: findOrCreateUniverseCollection failed: ${err.message}`);- return null;- });if (!collection) return { itemsAdded: 0 };let added = 0;let deferred = 0;@@ -401,25 +421,33 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =});}- // Universe shares can carry a linked media collection payload. Items- // are unioned into a local "Universe: <name>" collection so peer-- // generated images appear alongside the universe in the recipient's UI.+ // Universe and series shares can both carry a linked media collection+ // payload. Items are unioned into a local "Universe: <name>" or+ // "Series: <name>" collection so peer-generated images appear alongside+ // the owner record in the recipient's UI.let itemsAdded = 0;let itemsDeferred = 0;let collectionPendingUniverse = null;+ let collectionPendingSeries = null;if (manifest.collection) {- const r = await withReexportSuppressed('universe', manifest.collection.universeId, () =>+ // Suppress re-export of the owner record while the collection items+ // land — the items themselves drive recordEvents, which would loop+ // back through the receiver's own subscriptions if not gated.+ const ownerKind = manifest.collection.universeId ? 'universe' : 'series';+ const ownerId = manifest.collection.universeId || manifest.collection.seriesId;+ const r = await withReexportSuppressed(ownerKind, ownerId, () =>mergeCollectionPayload(manifest.collection, availableAssetKeys));itemsAdded = r.itemsAdded;itemsDeferred = r.itemsDeferred || 0;if (itemsAdded > 0) applied += itemsAdded;- // `mergeCollectionPayload` defers when the referenced universe hasn't- // been imported locally yet. Propagate that as a pending condition so- // processManifest leaves the cursor un-advanced and the watcher- // retries — otherwise the manifest is marked processed and the- // deferred items never land if the universe record arrives in a+ // `mergeCollectionPayload` defers when the referenced owner record+ // hasn't been imported locally yet. Propagate that as a pending+ // condition so processManifest leaves the cursor un-advanced and the+ // watcher retries — otherwise the manifest is marked processed and+ // the deferred items never land if the owner record arrives in a// later (independent) sync.if (r.missingUniverse) collectionPendingUniverse = manifest.collection.universeId;+ if (r.missingSeries) collectionPendingSeries = manifest.collection.seriesId;}let adoptedSubscription = null;@@ -439,6 +467,7 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =collectionItemsAdded: itemsAdded,collectionItemsDeferred: itemsDeferred,collectionPendingUniverse,+ collectionPendingSeries,adoptedSubscription: adoptedSubscription? { id: adoptedSubscription.id, bucketId: adoptedSubscription.bucketId, recordKind: adoptedSubscription.recordKind, recordId: adoptedSubscription.recordId }: null,@@ -643,18 +672,21 @@ export async function processManifest(bucketId, manifestFilename) {outcome = { mode: 'inbox', ...(await applyInbox(bucket, manifest, manifestFilename, records)) };}// A manifest is pending when any of these still need to land before the- // cursor advances: asset blobs, referenced record JSONs, OR a universe- // referenced by the manifest's collection payload that hasn't been- // imported yet. The third case can happen when the universe record- // failed to import (corrupt JSON, schema-version mismatch) or the- // manifest references a universeId not listed in `recordIds`.+ // cursor advances: asset blobs, referenced record JSONs, OR an owner+ // record (universe or series) referenced by the manifest's collection+ // payload that hasn't been imported yet. The last two cases can happen+ // when the owner record failed to import (corrupt JSON, schema-version+ // mismatch) or the manifest references an owner id not listed in+ // `recordIds`.const collectionPendingUniverse = outcome?.collectionPendingUniverse || null;- if (assetCopy.missing.length > 0 || missingRecords.length > 0 || collectionPendingUniverse) {+ const collectionPendingSeries = outcome?.collectionPendingSeries || null;+ if (assetCopy.missing.length > 0 || missingRecords.length > 0 || collectionPendingUniverse || collectionPendingSeries) {if (assetCopy.missing.length > 0) outcome.pendingAssets = assetCopy.missing;if (missingRecords.length > 0) outcome.pendingRecords = missingRecords;if (collectionPendingUniverse) outcome.pendingCollectionUniverse = collectionPendingUniverse;+ if (collectionPendingSeries) outcome.pendingCollectionSeries = collectionPendingSeries;sharingEvents.emit('manifest-processed', { bucketId, manifestId: manifest.id, manifestFilename, outcome });- console.log(`⏳ sharing: bucket=${bucket.name} manifest=${manifest.id} kind=${manifest.kind} mode=${bucket.mode} waitingForAssets=${assetCopy.missing.length} waitingForRecords=${missingRecords.length}${collectionPendingUniverse ? ` waitingForUniverse=${collectionPendingUniverse}` : ''}`);+ console.log(`⏳ sharing: bucket=${bucket.name} manifest=${manifest.id} kind=${manifest.kind} mode=${bucket.mode} waitingForAssets=${assetCopy.missing.length} waitingForRecords=${missingRecords.length}${collectionPendingUniverse ? ` waitingForUniverse=${collectionPendingUniverse}` : ''}${collectionPendingSeries ? ` waitingForSeries=${collectionPendingSeries}` : ''}`);return { processed: true, pending: true, manifest, outcome };}await markProcessed(bucketId, manifestFilename, manifest.id);@@ -767,16 +799,22 @@ export async function promoteInboxItem(bucketId, manifestId) {const availableAssetKeys = new Set(assetCopy.available.map((ref) => `${ref.kind}:${ref.ref}`));const outcome = await applyAutoMerge(bucket, manifest, records, { availableAssetKeys });// Mirror the missing-record/asset gates above: if the collection- // payload deferred because its universe isn't present locally yet,- // throw a pending error instead of silently dropping the inbox item.- // Otherwise the user's "promote" click would consume the inbox row- // while the collection items never landed.+ // payload deferred because its owner (universe or series) isn't+ // present locally yet, throw a pending error instead of silently+ // dropping the inbox item. Otherwise the user's "promote" click+ // would consume the inbox row while the collection items never landed.if (outcome.collectionPendingUniverse) {throw Object.assign(new Error(`Collection payload waiting on universe ${outcome.collectionPendingUniverse} to be imported first`), {code: 'SHARING_UNIVERSE_PENDING',pendingCollectionUniverse: outcome.collectionPendingUniverse,});}+ if (outcome.collectionPendingSeries) {+ throw Object.assign(new Error(`Collection payload waiting on series ${outcome.collectionPendingSeries} to be imported first`), {+ code: 'SHARING_SERIES_PENDING',+ pendingCollectionSeries: outcome.collectionPendingSeries,+ });+ }// Drop from inbox.inbox.items.splice(idx, 1);await writeInbox(bucketId, inbox);diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.jsindex 0b6193582c..63d1d4328f 100644--- a/server/services/sharing/integration.test.js+++ b/server/services/sharing/integration.test.js@@ -261,6 +261,115 @@ describe('sharing round-trip', () => {expect(fs.existsSync(join(tempData, 'images', 'second.png'))).toBe(true);});+ it('series export bundles the per-series collection when the series has no universe', async () => {+ // A series without a universeId — covers auto-file into a per-series+ // "Series: <name>" collection (mediaCollections.seriesId stamp) and the+ // exporter must bundle that into manifest.collection so the recipient+ // sees the same covers alongside the series record.+ const bucket = await buckets.createBucket({ name: 'SeriesCollBucket', path: tempBucket, mode: 'auto-merge' });+ const mediaCollections = await import('../mediaCollections.js');+ const s = await series.createSeries({ name: 'Indie Saga', logline: 'L' });++ const fs = await import('fs');+ fs.writeFileSync(join(tempData, 'images', 'cover-a.png'), 'COVA');+ fs.writeFileSync(join(tempData, 'images', 'cover-b.png'), 'COVB');+ const collection = await mediaCollections.findOrCreateSeriesCollection({+ seriesId: s.id, seriesName: s.name,+ });+ await mediaCollections.addItem(collection.id, { kind: 'image', ref: 'cover-a.png' });+ await mediaCollections.addItem(collection.id, { kind: 'image', ref: 'cover-b.png' });++ // Export — manifest must carry the seriesId-keyed collection payload.+ const exp = await exporter.exportSeries(s.id, bucket.id);+ const manifest = JSON.parse(fs.readFileSync(join(tempBucket, 'manifests', exp.filename), 'utf-8'));+ expect(manifest.collection).toMatchObject({ seriesId: s.id });+ expect(manifest.collection.universeId).toBeUndefined();+ expect(manifest.collection.items.map((i) => i.ref).sort()).toEqual(['cover-a.png', 'cover-b.png']);+ expect(fs.existsSync(join(tempBucket, 'assets', 'blobs', sha256Hex('COVA')))).toBe(true);+ expect(fs.existsSync(join(tempBucket, 'assets', 'blobs', sha256Hex('COVB')))).toBe(true);++ // Drop the local collection + series, then re-process: importer+ // restores the series and find-or-creates the local per-series+ // collection by seriesId, unioning the items in.+ await mediaCollections.deleteCollection(collection.id);+ await series.deleteSeries(s.id);+ expect((await mediaCollections.listCollections()).find((c) => c.seriesId === s.id)).toBeUndefined();++ simulateRemoteSender(tempBucket, exp.filename);+ const r = await importer.processManifest(bucket.id, exp.filename);+ expect(r.processed).toBe(true);+ expect(r.outcome.collectionItemsAdded).toBe(2);++ const localCollections = await mediaCollections.listCollections();+ const restored = localCollections.find((c) => c.seriesId === s.id);+ expect(restored).toBeTruthy();+ expect(restored.name).toBe('Series: Indie Saga');+ expect(restored.items.map((i) => i.ref).sort()).toEqual(['cover-a.png', 'cover-b.png']);+ // Asset blobs are back in the local data/images pool.+ expect(fs.existsSync(join(tempData, 'images', 'cover-a.png'))).toBe(true);+ expect(fs.existsSync(join(tempData, 'images', 'cover-b.png'))).toBe(true);+ });++ it('series export prefers the universe-linked collection when both exist', async () => {+ // A series can in principle be linked to a universe (universe-owned+ // collection) AND have a stray per-series collection (e.g. from a+ // prior universeless phase). The exporter prefers the universe one+ // since it represents the canonical bucket for that universe.+ const bucket = await buckets.createBucket({ name: 'BothBucket', path: tempBucket, mode: 'auto-merge' });+ const universeBuilder = await import('../universeBuilder.js');+ const mediaCollections = await import('../mediaCollections.js');+ const u = await universeBuilder.createUniverse({ name: 'Linked' });+ const s = await series.createSeries({ name: 'Series', universeId: u.id });++ const fs = await import('fs');+ fs.writeFileSync(join(tempData, 'images', 'uni.png'), 'UNI');+ fs.writeFileSync(join(tempData, 'images', 'ser.png'), 'SER');++ const uniColl = await mediaCollections.findOrCreateUniverseCollection({+ universeId: u.id, universeName: u.name,+ });+ await mediaCollections.addItem(uniColl.id, { kind: 'image', ref: 'uni.png' });++ const serColl = await mediaCollections.findOrCreateSeriesCollection({+ seriesId: s.id, seriesName: s.name,+ });+ await mediaCollections.addItem(serColl.id, { kind: 'image', ref: 'ser.png' });++ const exp = await exporter.exportSeries(s.id, bucket.id);+ const manifest = JSON.parse(fs.readFileSync(join(tempBucket, 'manifests', exp.filename), 'utf-8'));+ expect(manifest.collection).toMatchObject({ universeId: u.id });+ expect(manifest.collection.items.map((i) => i.ref)).toEqual(['uni.png']);+ });++ it('series collection import defers when the local series is missing', async () => {+ // Mirrors the universe-pending case: the manifest references a+ // seriesId we haven't imported locally. The cursor must stay+ // un-advanced so a later sync of the series unblocks the merge.+ const bucket = await buckets.createBucket({ name: 'DeferBucket', path: tempBucket, mode: 'auto-merge' });+ const mediaCollections = await import('../mediaCollections.js');+ const s = await series.createSeries({ name: 'Will Vanish' });+ const fs = await import('fs');+ fs.writeFileSync(join(tempData, 'images', 'late-cover.png'), 'LATE');+ const collection = await mediaCollections.findOrCreateSeriesCollection({+ seriesId: s.id, seriesName: s.name,+ });+ await mediaCollections.addItem(collection.id, { kind: 'image', ref: 'late-cover.png' });++ const exp = await exporter.exportSeries(s.id, bucket.id);+ // Delete the series locally so the importer sees an orphaned payload.+ await mediaCollections.deleteCollection(collection.id);+ await series.deleteSeries(s.id);+ // Also drop the series record from the bucket so insertSeriesWithId+ // doesn't restore it — this isolates the "collection waits on series"+ // case rather than "round-trip restores everything."+ fs.rmSync(join(tempBucket, 'records', 'series', `${s.id}.json`), { force: true });++ simulateRemoteSender(tempBucket, exp.filename);+ const r = await importer.processManifest(bucket.id, exp.filename);+ expect(r.pending).toBe(true);+ expect(r.outcome.pendingCollectionSeries).toBe(s.id);+ });+it('universe export ignores a same-named unlinked collection (universeId-only routing)', async () => {// Round-9 review caught that the exporter's old "fall back to name// match" path could pick up a post-deleteUniverse orphan and ship itdiff --git a/server/services/sharing/manifest.js b/server/services/sharing/manifest.jsindex e66a4f85a7..0e172a3838 100644--- a/server/services/sharing/manifest.js+++ b/server/services/sharing/manifest.js@@ -20,6 +20,7 @@ import { readdir, rename } from 'fs/promises';import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';import { SHARING_SCHEMA_VERSION, getProducedByVersion } from './version.js';import { isStr } from '../../lib/storyBible.js';+import { universeCollectionNameFor, seriesCollectionNameFor } from '../mediaCollections.js';export const MANIFEST_KIND = Object.freeze(['series', 'universe', 'media', 'media-annotations']);@@ -162,13 +163,21 @@ export function buildManifest({bucketName: bucketName || bucketId,recordIds: Array.isArray(recordIds) ? recordIds : [],assetRefs: Array.isArray(assetRefs) ? assetRefs : [],- // Optional payload for universe shares — the linked media collection so- // recipients gain the same set of generated images and the link is- // restored on their side.- collection: collection && collection.universeId && Array.isArray(collection.items)+ // Optional payload for universe/series shares — the linked media+ // collection so recipients gain the same set of generated images and+ // the link is restored on their side. Either `universeId` (universe-+ // owned auto-collection, or a universe-linked series' bundle) OR+ // `seriesId` (per-series auto-collection for universeless series) is+ // present, never both.+ collection: collection && Array.isArray(collection.items)+ && (collection.universeId || collection.seriesId)? {- name: collection.name || `Universe: ${collection.universeId}`,- universeId: collection.universeId,+ name: collection.name+ || (collection.universeId+ ? universeCollectionNameFor(collection.universeId)+ : seriesCollectionNameFor(collection.seriesId)),+ ...(collection.universeId ? { universeId: collection.universeId } : {}),+ ...(collection.seriesId && !collection.universeId ? { seriesId: collection.seriesId } : {}),description: collection.description || '',items: collection.items.map((it) => ({ kind: it.kind, ref: it.ref, addedAt: it.addedAt || null })),}